repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
rgp62/newton-gd
https://github.com/rgp62/newton-gd
1845a56b4e27c9e14af5436a1beb1d22e1259d31
2ade577dc07a7c1ac551ca4e5c3a4f447e42f836
ba14621ae81e10bcda49676cc79339fe46c5cf3a
refs/heads/main
2023-03-09T17:13:30.116514
2021-03-02T16:41:49
2021-03-02T16:41:49
339,240,244
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7077798843383789, "alphanum_fraction": 0.759013295173645, "avg_line_length": 34.13333511352539, "blob_id": "f2810715b1d92decf04ad1e54119f12fd49ab274", "content_id": "231531eb3729b8186bced3a9899321f5f3c549e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 527, "license_type": "no_license", "max_line_length": 224, "num_lines": 15, "path": "/README.md", "repo_name": "rgp62/newton-gd", "src_encoding": "UTF-8", "text": "# newton-gd\n\nThis code implements the block coordinate descent optimizer in [1]. `newton.py` implements the newton and gradient-based optimizer. `mnist.ipynb` is an example script applying Newton-GD to the MNIST classification benchmark.\n\nPython >= 3.5 \nnumpy \nscipy \nmatplotlib \ntoolz \ntensorflow >= 2.2 \ntensorflow-datasets \n\nSAND No: SAND2021-2384 O\n\n[1] R. G. Patel, N. A. Trask, M. A. Gulian, and E. C. Cyr. A block coordinate descent optimizer for classification problems exploiting convexity. arXiv preprint arXiv:2006.10123, 2020.\n" }, { "alpha_fraction": 0.5005460381507874, "alphanum_fraction": 0.5158354640007019, "avg_line_length": 27.278350830078125, "blob_id": "7bc45d8a878949fa7ff0054357aa2451902dbe20", "content_id": "6e8da3875d9f97d722d9b0b8d519aaf3c4bef2f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2747, "license_type": "no_license", "max_line_length": 97, "num_lines": 97, "path": "/newton.py", "repo_name": "rgp62/newton-gd", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\nimport scipy.sparse.linalg\n\ndef makeLS(p):\n if p[0] == 'dense':\n def LS(A,b):\n n = tf.reduce_prod(b.shape)\n br = tf.reshape(b,(n,))\n Ar = tf.reshape(A,(n,n)) + tf.eye(n,dtype=tf.float64)*p[1]\n xr = tf.linalg.solve(Ar,tf.expand_dims(br,1))\n x = tf.reshape(xr,b.shape)\n return x\n\n elif p[0] == 'cg':\n def LS(A,b):\n n = tf.reduce_prod(b.shape)\n br = tf.reshape(b,(n,)).numpy()\n Ar = tf.reshape(A,(n,n)).numpy()\n sol = scipy.sparse.linalg.cg(Ar,br,tol=p[1],maxiter=p[2])\n xr = sol[0]\n x = tf.reshape(xr,b.shape)\n return x\n return LS\n\n\n\nclass model:\n def __init__(self,NN,nvars,gdvars,opt,LS,alpha=1e-4,rho=0.7):\n self.NN = NN\n \n self.nvars = nvars\n self.gdvars = gdvars\n \n self.loss = tf.keras.losses.sparse_categorical_crossentropy\n self.opt=opt\n\n self.LS = LS\n\n self.alpha = alpha\n self.rho = rho\n\n\n @tf.function\n def getJ(self,x,ytrue):\n J = tf.reduce_mean(self.loss(ytrue,self.NN(x)))\n return J\n \n @tf.function\n def getdJ(self,x,ytrue):\n with tf.GradientTape() as gg:\n gg.watch(self.nvars)\n with tf.GradientTape() as g:\n g.watch(self.nvars)\n J = self.getJ(x,ytrue)\n dJ = g.gradient(J,[self.nvars])[0]\n d2J = gg.jacobian(dJ,[self.nvars])[0]\n return J,dJ,d2J\n\n def newton(self,x,ytrue):\n J,dJ,d2J = self.getdJ(x,ytrue)\n nvars_old = tf.Variable(self.nvars)\n dnvars = self.LS(d2J,dJ)\n lamb = 1.\n self.nvars.assign(nvars_old-lamb*dnvars)\n J_new = self.getJ(x,ytrue)\n while J_new > J - self.alpha*lamb*tf.reduce_sum(dJ*dnvars):\n lamb = lamb*self.rho\n self.nvars.assign(nvars_old-lamb*dnvars)\n J_new = self.getJ(x,ytrue)\n\n def newton_conv(self,x,ytrue,tol=1e-6,max_iter=100000):\n iter = 0\n J1 = self.getJ(x,ytrue)\n J2 = np.inf\n while abs(J2 - J1) > tol:\n iter+=1\n self.newton(x,ytrue)\n J2 = J1\n J1 = self.getJ(x,ytrue)\n\n if iter>max_iter:\n break\n return iter,(J1-J2).numpy()\n \n \n @tf.function\n def gd(self,x,ytrue):\n with tf.GradientTape() as g:\n g.watch(self.gdvars)\n J = self.getJ(x,ytrue)\n dJ = g.gradient(J,self.gdvars)\n self.opt.apply_gradients(zip(dJ,self.gdvars))\n\n \n def getacc(self,x,ytrue):\n return tf.keras.metrics.Accuracy(dtype=tf.float64)(ytrue,tf.argmax(self.NN(x),1)).numpy()\n\n\n\n\n" } ]
2
kongwanbianjinyu/hello-world
https://github.com/kongwanbianjinyu/hello-world
c06896004151550a8680bb4ff9ad7476ac779844
39f737dcfbc681908cf30a0d45169392092912ae
523ebb683802b558963956325043f327cf4c532c
refs/heads/master
2020-06-24T04:22:14.461933
2019-07-25T15:52:39
2019-07-25T15:52:39
198,847,807
1
0
null
2019-07-25T14:33:33
2019-07-25T15:11:33
2019-07-25T15:20:19
null
[ { "alpha_fraction": 0.7321428656578064, "alphanum_fraction": 0.7321428656578064, "avg_line_length": 17.66666603088379, "blob_id": "a761c5efa6cd73f520693def01ddc2e8ea6724d0", "content_id": "92f51eddd5120ead761c4804bcd61aeea6f63bab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 168, "license_type": "no_license", "max_line_length": 31, "num_lines": 9, "path": "/Readme.md", "repo_name": "kongwanbianjinyu/hello-world", "src_encoding": "UTF-8", "text": "This project is testing...\nWhere is the branch botton\n\n\nhello my name is jjc\n\nI delete it, can you see it \nyou are supposed to be so happy\nI want to see how it works..\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.699999988079071, "avg_line_length": 29, "blob_id": "066c019189e51f278f1a2478fbb6f6d6a49aa43d", "content_id": "4ac9a005fc528f24c8478d454d9b92bc2a6b5d51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 90, "license_type": "no_license", "max_line_length": 52, "num_lines": 3, "path": "/test.py", "repo_name": "kongwanbianjinyu/hello-world", "src_encoding": "UTF-8", "text": "print(\"hello world\")\nprint(\"This is jjc, please pull me ,Thankes a lot \")\nprint(\"goodby\")\n" }, { "alpha_fraction": 0.5341679453849792, "alphanum_fraction": 0.5805946588516235, "avg_line_length": 21.29069709777832, "blob_id": "90045d107b17a094c613ee333931bbb363ee9183", "content_id": "93c8033ecda398e21d70f71e6b2a3145b9f32d7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2031, "license_type": "no_license", "max_line_length": 114, "num_lines": 86, "path": "/hellopytorch.py", "repo_name": "kongwanbianjinyu/hello-world", "src_encoding": "UTF-8", "text": "import torch\nimport numpy\nfrom torch.autograd import Variable\n\n# Tensor的组织:列表层层嵌套\n# 一个大列表包含有3个子列表,每个子列表又由在5个子列表构成,每个子列表又由2个元素,依此类推\n# 索引从0到N-1\n'''\nx = torch.Tensor(3,5,2)\nprint(x[0,:,:])\nprint(x)\ny = torch.zeros(2,5)\nprint(y)\nz = torch.ones(3)\nprint(z)\n\na = torch.rand(5,3)\nb = torch.rand(5,3)\n\nc = a + b\nd = a - b\n\nn = a.numpy()\nprint(n)\n\n\nif torch.cuda.is_available():\n print(\"fine\")\nelse :\n print(\"fuck\")\n'''\n# x = Variable(torch.ones(2,2),requires_grad = True)\n# y = x + 2\n# print(y)\n# z= y * y * 3\n# print(z)\n# out = z.mean()\n# print(out)\n# z[0,0].backward()\n# print(x.grad)\n\n# x = torch.randn(3)\n# x = Variable(x, requires_grad = True)\n# y = x * 2\n# i = 1\n# while y.data.norm() < 1000:\n# y = y * 2\n# i = i+1\n# print(y.data.norm())\n# gradients = torch.FloatTensor([0.1, 1.0, 0.0001])\n# y.backward(gradients)\n# print(x.grad)\n\n\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 6, 5) # 1 input image channel, 6 output channels, 5x5 square convolution kernel\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 5 * 5, 120) # an affine operation: y = Wx + b\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n\n def forward(self, x):\n x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # Max pooling over a (2, 2) window\n x = F.max_pool2d(F.relu(self.conv2(x)), 2) # If the size is a square you can only specify a single number\n x = x.view(-1, self.num_flat_features(x))\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n def num_flat_features(self, x):\n size = x.size()[1:] # all dimensions except the batch dimension\n num_features = 1\n for s in size:\n num_features *= s\n return num_features\n\n\nnet = Net()\nnet\n" } ]
3
Jberczel/ATJindo
https://github.com/Jberczel/ATJindo
84cf48ae6b15230ef25b0e427fd3f40accd1b10b
1acd4d3401310ef0986ecf6ed9d7c734d7c273b3
2d48e18c1bb3ef7e463c9c33bb074a260dad5d99
refs/heads/master
2020-05-17T12:09:56.620776
2014-04-02T12:57:24
2014-04-02T12:57:24
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7565217614173889, "alphanum_fraction": 0.7782608866691589, "avg_line_length": 228, "blob_id": "5089e73a27bd3437fd12562832cb011e23b19c68", "content_id": "4b85e717c619e33337dad2d2afb38263ca2a41b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 230, "license_type": "no_license", "max_line_length": 228, "num_lines": 1, "path": "/README.md", "repo_name": "Jberczel/ATJindo", "src_encoding": "UTF-8", "text": "[Website](http://www.atjindo.com) built to record my 2013 Appalachian Trail thru-hike. I built this website after taking 2 Udacity courses: Intro to Comp Sci and Web App Development, as well as online tutorials on html and css.\n\n" }, { "alpha_fraction": 0.6134402751922607, "alphanum_fraction": 0.6170138716697693, "avg_line_length": 31.590909957885742, "blob_id": "9a348f03108fef8673700b22116aaae6c7878772", "content_id": "6ea23f30322368f42449d4d36bd44c1a7c533e96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11473, "license_type": "no_license", "max_line_length": 152, "num_lines": 352, "path": "/main.py", "repo_name": "Jberczel/ATJindo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n#\n# Copyright 2007 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport logging\nimport os\nimport re\n\nimport webapp2\nimport jinja2\n\nfrom google.appengine.ext import db\nfrom google.appengine.ext import deferred\nfrom google.appengine.api import memcache\nfrom google.appengine.api import mail\nfrom google.appengine.api import users\nfrom webapp2_extras import sessions\n\n#load jinja2 templates from template folder\ntemplate_dir = os.path.join(os.path.dirname(__file__), 'templates')\njinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=True)\n\nNAME_RE = re.compile(r\"^[ a-zA-Z_-]{2,30}$\")\nEMAIL_RE = re.compile(r'^[\\S]+@[\\S]+\\.[\\S]+$')\n\n#helper function\ndef render_str(template, **params):\n t = jinja_env.get_template(template)\n return t.render(params)\n\n\n#blog post database\nclass Post(db.Model):\n subject = db.StringProperty(required=True)\n content = db.TextProperty(required=True)\n subject_translation = db.StringProperty()\n content_translation = db.TextProperty()\n created = db.DateTimeProperty(auto_now_add=True)\n deleted = db.BooleanProperty(default=False)\n\n\nclass Handler(webapp2.RequestHandler):\n def write(self, *a, **kw):\n self.response.out.write(*a, **kw)\n\n def render_str(self, template, **params):\n t = jinja_env.get_template(template)\n return t.render(params)\n\n def render(self, template, **kw):\n self.write(self.render_str(template, **kw))\n\n def lang(self):\n lang = 'en'\n if self.session['lang'] != '':\n lang = self.session['lang']\n return lang\n\n def dispatch(self):\n # Get a session store for this request.\n self.session_store = sessions.get_store(request=self.request)\n\n # Check for language change and save it in the session\n lang = self.request.get('lang')\n if lang == 'en' or lang == 'ko':\n logging.info(\"Setting language: %s\", lang)\n self.session['lang'] = lang\n\n try:\n # Dispatch the request.\n webapp2.RequestHandler.dispatch(self)\n finally:\n # Save all sessions.\n self.session_store.save_sessions(self.response)\n\n @webapp2.cached_property\n def session(self):\n # Returns a session using the default cookie key.\n return self.session_store.get_session()\n\n\nclass HomePage(Handler):\n def get(self):\n self.render('home.html')\n\n\nclass NewPost(Handler):\n def get(self):\n #google users api authentication\n user = users.get_current_user()\n\n #no markup, so adding these code snippets to easily add photos/videos from phone.\n code = \"\"\"Img Code:\n\n <a href=\"?dl=1\"><img src=\"?dl=1\" alt=\"\"></a>\n <b></b>\n\n Vimeo Code:\n\n <div class=\"embed-container\"><iframe src=\"\" frameborder=\"0\" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></div>\n\n Youtube Code:\n\n <div class=\"embed-container\"><iframe src=\"\" frameborder=\"0\" allowfullscreen></iframe></div> \"\"\"\n self.render('newpost.html', code=code, user=user.nickname(), url=users.create_logout_url(\"/\"))\n\n def post(self):\n subject = self.request.get('subject')\n content = self.request.get('content')\n state = self.request.get('state')\n\n if subject and content:\n new_post = Post(subject=subject, content=content, parent=state_key(state)) # creates a new database object\n new_post.put() # stores object\n get_posts(state, True) # update state page filter\n top_posts(True) # update front page of blog\n post_id = str(new_post.key().id()) # finds db object's key\n self.redirect('/blog/%s/%s' % (state, post_id)) # redirects to permalink page\n\n\nclass PermaLink(Handler):\n def get(self, state, post_id):\n post = memcache.get(state + post_id)\n if post is None:\n post = Post.get_by_id(int(post_id), parent=state_key(state))\n memcache.set(state + post_id, post)\n lang = self.request.get('lang')\n self.render(\"permalink.html\", post=post, lang=lang)\n\n\nclass StatePage(Handler):\n def get(self, state):\n ##posts = db.GqlQuery(\"select * from Post where ancestor is :1 order by created desc\",state_key(state)) \n posts = get_posts(state)\n count = len(posts)\n lang = self.request.get('lang')\n self.render('sblog.html', posts=posts, state=state, count=count, lang=lang) ##checks session language in sblog template\n\n\ndef state_key(group='default'):\n#lookup ancestor key; used to pull all state posts\n return db.Key.from_path('Post', group)\n\n\nclass EditView(Handler):\n def get(self):\n posts = db.GqlQuery(\"select * from Post where deleted = :1 order by created desc\", False)\n self.render(\"edit.html\", posts=posts)\n\n\nclass EditPost(Handler):\n def get(self, state, post_id):\n user = users.get_current_user()\n post = Post.get_by_id(int(post_id), parent=state_key(state))\n code = \"\"\"Img Code:\n\n <a href=\"?dl=1\"><img src=\"?dl=1\" alt=\"\"></a>\n <b></b>\n\n Vimeo Code:\n\n <div class=\"embed-container\"><iframe src=\"\" frameborder=\"0\" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></div>\n\n Youtube Code:\n\n <div class=\"embed-container\"><iframe src=\"\" frameborder=\"0\" allowfullscreen></iframe></div> \"\"\"\n self.render(\"editpost.html\", subject=post.subject, content=post.content, state=state, code=code,\n user=user.nickname(), url=users.create_logout_url(\"/\"))\n\n # TODO this is very hackable\n def post(self, state, post_id):\n post = Post.get_by_id(int(post_id), parent=state_key(state))\n post.subject = self.request.get('subject')\n post.content = self.request.get('content')\n post.state = self.request.get('state')\n post.put()\n\n memcache.set(state + post_id, post) # update permalink with edits.\n get_posts(state, True) # update filtered states with edits\n top_posts(True)\n self.redirect('/blog/%s/%s' % (state, post_id))\n\n\nclass About(Handler):\n def get(self):\n self.render('about.html')\n\n\nclass Gear(Handler):\n def get(self):\n self.render('gear.html')\n\n\nclass FAQs(Handler):\n def get(self):\n self.render('FAQ.html')\n\n\nclass Links(Handler):\n def get(self):\n self.render('links.html')\n\nclass DataPage(Handler):\n def get(self):\n self.render('datapage.html')\n\ndef top_posts(update=False):\n posts = memcache.get('top')\n if posts is None or update:\n posts = db.GqlQuery(\"select * from Post where deleted = :1 order by created desc limit 10\", False)\n logging.error(\"DB Query hit\")\n posts = list(posts)\n memcache.set('top', posts)\n return posts\n\n\ndef get_posts(state, update=False):\n posts = memcache.get(state)\n if posts is None or update:\n posts = db.GqlQuery(\"select * from Post where ancestor is :1 and deleted = :2 order by created desc\",\n state_key(state), False)\n logging.error(\"DB Query\")\n posts = list(posts)\n memcache.set(state, posts)\n return posts\n\n\ndef valid_name(username):\n return username and NAME_RE.match(username)\n\n\ndef valid_email(email):\n return not email or EMAIL_RE.match(email)\n\n\nclass Contact(Handler):\n def get(self): \n self.render('contact.html')\n\n def post(self):\n author = self.request.get('author')\n email = self.request.get('email')\n message = self.request.get('content')\n\n if valid_name(author) and valid_email(email) and message:\n contact = mail.EmailMessage()\n contact.sender = '[email protected]'\n #contact.reply_to = '%s <%s>' % (author,email)\n contact.to = '[email protected]'\n contact.subject = \"New AT Jindo Message from: %s\" % author\n contact.body = '%s <%s>, %s' % (author, email,message)\n contact.send() \n self.redirect('/thanks?n=%s' % author) # redirects to permalink page\n else:\n self.render('contact.html',\n error=\"*Sorry, your message did not send. Please enter valid and required fields.\")\n\n\nclass Thanks(Handler):\n def get(self):\n name = self.request.get('n')\n self.render('thanks.html', name=name)\n\n\nclass Translate(Handler):\n def get(self, state, post_id):\n post = memcache.get(state + post_id)\n if post is None:\n post = Post.get_by_id(int(post_id), parent=state_key(state))\n memcache.set(state + post_id, post)\n\n nickname = users.get_current_user().nickname()\n self.render('translate.html', post=post, user=nickname, url=users.create_logout_url(\"/\"))\n\n def post(self, state, post_id):\n post = Post.get_by_id(int(post_id), parent=state_key(state))\n post.subject_translation = self.request.get('subject_translation')\n post.content_translation = self.request.get('content_translation')\n post.put()\n\n memcache.set(state + post_id, post)\n get_posts(state, True)\n top_posts(True)\n self.redirect('/blog/%s/%s' % (state, post_id))\n\n#############################\n# Update Schema\nBATCH_SIZE = 100\n\n\nclass UpdateHandler(Handler):\n def get(self):\n deferred.defer(UpdateSchema)\n self.response.out.write('Schema migration successfully initiated.')\n\n\ndef UpdateSchema(cursor=None, num_updated=0):\n query = Post.all()\n if cursor:\n query.with_cursor(cursor)\n\n to_put = []\n for p in query.fetch(limit=BATCH_SIZE):\n to_put.append(p)\n\n if to_put:\n db.put(to_put)\n num_updated += len(to_put)\n logging.debug('Put %d entities to Datastore for a total of %d', len(to_put), num_updated)\n deferred.defer(UpdateSchema, cursor=query.cursor(), num_updated=num_updated)\n else:\n logging.debug('UpdateSchema complete with %d updates!', num_updated)\n\n# End Update Schema\n#############################\n\n\nconfig = {'webapp2_extras.sessions': {\n 'secret_key': 'my-super-secret-key',\n}}\n\napp = webapp2.WSGIApplication([\n ('/', HomePage),\n ('/newpost', NewPost),\n ('/edit', EditView),\n ('/blog/(ME|NH|VT|MA|CT|NY|NJ|PA|MD|WV|NoVa|SoVa|NC|TN|GA|XX|finish)/(\\d+)/edit', EditPost),\n ('/blog/(ME|NH|VT|MA|CT|NY|NJ|PA|MD|WV|NoVa|SoVa|NC|TN|GA|XX|finish)/(\\d+)', PermaLink),\n ('/blog/(ME|NH|VT|MA|CT|NY|NJ|PA|MD|WV|NoVa|SoVa|NC|TN|GA|XX|finish)', StatePage),\n ('/blog/(ME|NH|VT|MA|CT|NY|NJ|PA|MD|WV|NoVa|SoVa|NC|TN|GA|XX|finish)/(\\d+)/translate', Translate), \n ('/about', About),\n ('/gear', Gear),\n ('/FAQs', FAQs),\n ('/links', Links),\n ('/contact', Contact),\n ('/thanks', Thanks),\n ('/data',DataPage),\n ('/updateSchema', UpdateHandler)\n\n], config=config, debug=True)\n\n" }, { "alpha_fraction": 0.5661605000495911, "alphanum_fraction": 0.5753796100616455, "avg_line_length": 35.17647171020508, "blob_id": "caecad8298fb381f646bcf04a46e16daa6b4d31e", "content_id": "071dcbd34d72ebede9dd5126e6e2b77ac406fc5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1844, "license_type": "no_license", "max_line_length": 161, "num_lines": 51, "path": "/templates/links.html", "repo_name": "Jberczel/ATJindo", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\n{% block head %}<title>AT Jindo - Links</title>{% endblock %}\n{% block content %}\n\n<div class=\"row-fluid\">\n\t<div class=\"span6 offset3 well\">\n <h3>Online Resources</h3> \n\n <table class=\"table table-striped table-bordered\">\n\n <thead>\n <tr>\n <th>Website</th>\n <th>Description</th>\n </tr>\n </thead>\n\n <tbody>\n <tr>\n <td><a href=\"http://www.appalachiantrail.org/hiking/hiking-basics\" target=\"_blank\">AT Conservancy</td>\n <td>Good place to start with hiking basics. This is where I started.</td>\n </tr>\n <tr>\n <td><a href=\"http://www.reddit.com/r/AppalachianTrail/\" target=\"_blank\">Appalachian Trail Subreddit</td>\n <td>Great resource and online community that can help answer questions.</td>\n </tr>\n <tr>\n <td><a href=\"http://www.youtube.com/user/Biophthera\" target=\"_blank\">Biophthera</a></td>\n <td>Great backpacking tips and gear reviews. I picked up some reliable gear thanks to his reviews.</td>\n </tr>\n <tr>\n <td><a href=\"http://www.hikelight.com\" target=\"_blank\">HikeLight</td>\n <td>Great tips (some a little extreme) to ligthen your load. Your body with thank you later.</td>\n </tr>\n <tr>\n <td><a href=\"http://www.atraillife.com/index.html\" target=\"_blank\">Atraillife</td>\n <td>Great blog posts on long-distance hiking with a dog.</td>\n </tr>\n \n </tbody>\n\n </table>\n\n\n <p>Andrew Skurka's (Nat Geo's 2007 Adventurer of the Year) Backpacking Clinic:</p>\n\n <div class=\"embed-container\"><iframe width=\"560\" height=\"315\" src=\"//www.youtube.com/embed/FGQTcQhL08A\" frameborder=\"0\" allowfullscreen></iframe></div> \n </div> \n\n</div> \n{% endblock %}" } ]
3
mily1298/blautechApi
https://github.com/mily1298/blautechApi
8ee89ed8e422da8268838915f665f10fa88c1729
edf1d8ffbc55ab894217f8d273970d7eaf7204f5
475cd583e0ac3b05855e65401ad5573c9c22838a
refs/heads/master
2023-01-01T00:18:18.487261
2020-10-22T18:47:50
2020-10-22T18:47:50
306,425,298
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5666273832321167, "alphanum_fraction": 0.5764544010162354, "avg_line_length": 28.581396102905273, "blob_id": "840a2ba4e7224c427f89ebe9b7d506ecfb89a6cb", "content_id": "5e4fa477e45afa364c73d9f857cca245ac6d6edc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5088, "license_type": "no_license", "max_line_length": 120, "num_lines": 172, "path": "/BlautechRest/app.py", "repo_name": "mily1298/blautechApi", "src_encoding": "UTF-8", "text": "import firebase_admin\nimport pymongo\nimport pyrebase\nfrom flask_pymongo import PyMongo\nfrom firebase_admin import credentials, auth, firestore\nimport json\nfrom pymongo import MongoClient\nfrom flask import Flask, request\nfrom functools import wraps\nfrom flask_cors import CORS\n\napp = Flask(__name__)\nCORS(app)\ncliente = MongoClient('mongodb+srv://emily:[email protected]/BLAUTECH')\ncursor = cliente['BLAUTECH']\nmongoDb = cursor['USERS']\n\ncred = credentials.Certificate('firebaseAdminConfig.json')\nfirebase = firebase_admin.initialize_app(cred)\npb = pyrebase.initialize_app(json.load(open('authConfig.json')))\ndb = firestore.client()\n\n\n\ndef check_token(f):\n @wraps(f)\n def wrap(*args, **kwargs):\n if not request.headers.get('authorization'):\n return {'message': 'No token provided'}, 400\n try:\n user = auth.verify_id_token(request.headers['authorization'])\n request.user = user\n except:\n return {'message': 'Invalid token provided.'}, 400\n return f(*args, **kwargs)\n\n return wrap\n\n\[email protected]('/blautechApi/getUserInfo',methods=['POST'])\n@check_token\ndef userInfor():\n email = request.form.get('email')\n user = auth.get_user_by_email(email)\n return {'nombre:': user.display_name, 'uid': user.uid, 'email': user.email}, 200\n\n\[email protected]('/blautechApi/signup', methods=['POST'])\ndef signup():\n email = request.form.get('email')\n password = request.form.get('password')\n display_name = request.form.get('name')\n\n if email is None or password is None:\n return {'message': 'Error missing email or password'}, 400\n\n try:\n\n user = auth.create_user(\n email=email,\n password=password,\n display_name=display_name,\n disabled=False\n )\n doc_ref = db.collection(u'users').document(user.uid)\n doc_ref.set({\n u'nombre': user.display_name,\n u'email': user.email,\n u'disabled': False\n })\n response = mongoDb.insert_one({\n u'_id': user.uid,\n u'nombre': user.display_name,\n u'email': user.email,\n u'disabled': False})\n print(response.inserted_id)\n\n return {'message': f'Successfully created user {user.uid}'}, 200\n except:\n return {'message': 'Error creating user'}, 400\n\n\[email protected]('/blautechApi/updateUser',methods=['PUT'])\n@check_token\ndef updateUser():\n uid = request.form.get('uid')\n email = request.form.get('email')\n password = request.form.get('password')\n display_name = request.form.get('name')\n disabledStr = request.form.get('disabled')\n\n if email is None or password is None:\n return {'message': 'Error missing email or password'}, 400\n\n try:\n disabled = False\n if (disabledStr == 'False'):\n disabled = False\n else:\n disabled = True\n print(uid)\n user = auth.update_user(\n uid,\n email=email,\n password=password,\n display_name=display_name,\n disabled=disabled)\n\n doc_ref = db.collection(u'users').document(uid)\n doc_ref.update({\n u'nombre': display_name,\n u'email': email,\n u'disabled': disabled\n })\n\n mongoDb.update_one(\n {u'_id': uid},\n {\n '$set': {\n u'_id': uid,\n u'nombre': display_name,\n u'email': email,\n u'disabled': disabled\n }\n })\n\n return {'message': f' Actualizando satisfactorio de usuario {user.uid}'}, 200\n except:\n return {'message': 'Error actualizando usuario '}, 400\n\n\[email protected]('/blautechApi/deleteUser',methods=['POST'])\n@check_token\ndef deleteUser():\n uid = request.form.get('uid')\n try:\n print(uid);\n auth.delete_user(uid)\n db.collection(u'users').document(uid).delete()\n mongoDb.delete_one({u'_id': uid})\n\n return {'message': f'Borrado correcto de usuario'}, 200\n except:\n return {'message': 'Error en borrado de usuario'}, 400\n\[email protected]('/blautechApi/listUsers',methods=['GET'])\n@check_token\ndef listUsers():\n try:\n users = []\n for user in auth.list_users().iterate_all():\n users.append({'uid': user.uid, 'email': user.email, 'nombre': user.display_name, 'disabled': user.disabled})\n\n return {'users': users}, 200\n except:\n return {'message': 'Error al obtener lista de usuarios'}, 400\n\n\[email protected]('/blautechApi/token',methods=['POST'])\ndef token():\n email = request.form.get('email')\n password = request.form.get('password')\n try:\n user = pb.auth().sign_in_with_email_and_password(email, password)\n jwt = user['idToken']\n return {'token': jwt}, 200\n except:\n return {'message': 'Error en el logeo'}, 400\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n" } ]
1
joydeep2899/neural-networks
https://github.com/joydeep2899/neural-networks
3788199d322a5de211c685c8b7b04ff640f38205
c577c01a467a5412e3d2ed7e6227d942008200c4
ef7d3eeb77926f14876f395d68e25d17149cf043
refs/heads/master
2022-02-02T20:29:20.235378
2019-07-22T17:02:34
2019-07-22T17:02:34
198,266,372
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5505788922309875, "alphanum_fraction": 0.6103379726409912, "avg_line_length": 36.34061050415039, "blob_id": "12ccc0a80e9f8e98487321356d9659e7832c2be1", "content_id": "552af391a14c3d4f9fc7b6e438bff1d4eec18cdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8551, "license_type": "no_license", "max_line_length": 179, "num_lines": 229, "path": "/cnn.py", "repo_name": "joydeep2899/neural-networks", "src_encoding": "UTF-8", "text": "import skimage.data\nimport numpy as np\nimport matplotlib\nimport sys\nimport matplotlib.pyplot\n\ndef conv_(img,convfilter):\n filter_size=convfilter.shape[1]\n result=np.zeros((img.shape)) \n for r in (np.uint16(np.arange(filter_size/2.0,img.shape[0]-filter_size/2.0+1))):\n for c in (np.uint16(np.arange(filter_size/2.0,img.shape[1]-filter_size/2.0+1))):\n \n curr_region=img[r-np.uint16(np.floor(filter_size/2.0)):r+np.uint16(np.ceil(filter_size/2.0)),c-np.uint16(np.floor(filter_size/2.0)):c+np.uint16(np.ceil(filter_size/2.0))]\n curr_result=curr_region * convfilter\n conv_sum=np.sum(curr_result)\n result[r,c]=conv_sum\n final_result=result[np.uint16(filter_size/2.0):result.shape[0]-np.uint16(filter_size/2.0),np.uint16(filter_size/2.0):result.shape[1]-np.uint16(filter_size/2.0)]\n return final_result\n\ndef conv(img,convfilter):\n if len(img.shape) >2 or len(convfilter.shape) >3:\n if img.shape[-1] != convfilter.shape[-1]:\n print(\"the number of channels in image and fitler must match\")\n sys.exit()\n if convfilter.shape[1] != convfilter.shape[2]:\n print(\"the filter must be a square filter\")\n sys.exit()\n if convfilter.shape[1]%2==0:\n print(\"the filter must be odd in shape\")\n sys.exit()\n feature_maps= np.zeros((img.shape[0]-convfilter.shape[1]+1,img.shape[1]-convfilter.shape[2]+1,convfilter.shape[0]))\n \n for filter_num in range(convfilter.shape[0]):\n curr_filter=convfilter[filter_num,:]\n \n if len(curr_filter.shape)>2:\n conv_map= conv_(img[:,:,0],curr_filter[:,:,0])\n \n for ch_num in range(1,curr_filter.shape[-1]):\n conv_map=conv_map+conv_(img[:,:,ch_num],curr_filter[:,:,ch_num])\n else :\n conv_map=conv_(img,curr_filter)\n feature_maps[:,:,filter_num]=conv_map\n return feature_maps\n \ndef pooling(feature_map,size=2,stride=2):\n pool_out=np.zeros((np.uint16((feature_map.shape[0]-size+1)/stride+1),np.uint16((feature_map.shape[1]-size+1)/stride+1),feature_map.shape[-1]))\n for map_num in range(feature_map.shape[-1]): \n r2=0\n for r in (np.arange(0,feature_map.shape[0]-size+1,stride)): \n c2=0\n for c in (np.arange(0,feature_map.shape[1]-size+1,stride)):\n pool_out[r2,c2,map_num]=np.max([feature_map[r:r+size,c:c+size]])\n c2=c2+1\n r2=r2+1\n return pool_out\ndef relu(feature_map):\n relu_out=np.zeros(feature_map.shape)\n for map_num in range(feature_map.shape[-1]):\n for r in (np.arange(0,feature_map.shape[0])): \n for c in (np.arange(0,feature_map.shape[1])):\n relu_out[r,c,map_num]=np.max([feature_map[r,c,map_num],0])\n return relu_out\n\n\nimg = skimage.io.imread(\"dog.jpeg\")\n# Converting the image into gray.\nimg = skimage.color.rgb2gray(img)\n# First conv layer\n#l1_filter = numpy.random.rand(2,7,7)*20 #\nl1_filter = np.zeros((2,3,3))\nl1_filter[0, :, :] = np.array([[[-1, 0, 1],\n [-1, 0, 1],\n [-1, 0, 1]]])\nl1_filter[1, :, :] = np.array([[[1, 1, 1],\n [0, 0, 0],\n [-1, -1, -1]]])\nprint(\"\\n**Working with conv layer 1**\")\nl1_feature_map = conv(img, l1_filter)\nprint(\"\\n**ReLU**\")\nl1_feature_map_relu = relu(l1_feature_map)\nprint(\"\\n**Pooling**\")\nl1_feature_map_relu_pool = pooling(l1_feature_map_relu, 2, 2)\nprint(\"**End of conv layer 1**\\n\")\n\n\nl2_filter = np.random.rand(3, 5, 5, l1_feature_map_relu_pool.shape[-1])\nprint(\"\\n**Working with conv layer 2**\")\nl2_feature_map = conv(l1_feature_map_relu_pool, l2_filter)\nprint(\"\\n**ReLU**\")\nl2_feature_map_relu = relu(l2_feature_map)\nprint(\"\\n**Pooling**\")\nl2_feature_map_relu_pool = pooling(l2_feature_map_relu, 2, 2)\nprint(\"**End of conv layer 2**\\n\")\n\nl3_filter = np.random.rand(1, 7, 7, l2_feature_map_relu_pool.shape[-1])\nprint(\"\\n**Working with conv layer 3**\")\nl3_feature_map = conv(l2_feature_map_relu_pool, l3_filter)\nprint(\"\\n**ReLU**\")\nl3_feature_map_relu = relu(l3_feature_map)\nprint(\"\\n**Pooling**\")\nl3_feature_map_relu_pool = pooling(l3_feature_map_relu, 2, 2)\nprint(\"**End of conv layer 3**\\n\")\n\nl4_filter = np.random.rand(5, 7, 7, l3_feature_map_relu_pool.shape[-1])\nprint(\"\\n**Working with conv layer 3**\")\nl4_feature_map = conv(l3_feature_map_relu_pool, l4_filter)\nprint(\"\\n**ReLU**\")\nl4_feature_map_relu = relu(l4_feature_map)\nprint(\"\\n**Pooling**\")\nl4_feature_map_relu_pool = pooling(l3_feature_map_relu, 2, 2)\nprint(\"**End of conv layer 3**\\n\")\n\n\n\n\n\n# Graphing results\nfig0, ax0 = matplotlib.pyplot.subplots(nrows=1, ncols=1)\nax0.imshow(img).set_cmap(\"gray\")\nax0.set_title(\"Input Image\")\nax0.get_xaxis().set_ticks([])\nax0.get_yaxis().set_ticks([])\nmatplotlib.pyplot.savefig(\"in_img.png\", bbox_inches=\"tight\")\nmatplotlib.pyplot.close(fig0)\n\n# Layer 1\nfig1, ax1 = matplotlib.pyplot.subplots(nrows=3, ncols=2)\nax1[0, 0].imshow(l1_feature_map[:, :, 0]).set_cmap(\"gray\")\nax1[0, 0].get_xaxis().set_ticks([])\nax1[0, 0].get_yaxis().set_ticks([])\nax1[0, 0].set_title(\"L1-Map1\")\n\nax1[0, 1].imshow(l1_feature_map[:, :, 1]).set_cmap(\"gray\")\nax1[0, 1].get_xaxis().set_ticks([])\nax1[0, 1].get_yaxis().set_ticks([])\nax1[0, 1].set_title(\"L1-Map2\")\n\nax1[1, 0].imshow(l1_feature_map_relu[:, :, 0]).set_cmap(\"gray\")\nax1[1, 0].get_xaxis().set_ticks([])\nax1[1, 0].get_yaxis().set_ticks([])\nax1[1, 0].set_title(\"L1-Map1ReLU\")\n\nax1[1, 1].imshow(l1_feature_map_relu[:, :, 1]).set_cmap(\"gray\")\nax1[1, 1].get_xaxis().set_ticks([])\nax1[1, 1].get_yaxis().set_ticks([])\nax1[1, 1].set_title(\"L1-Map2ReLU\")\n\nax1[2, 0].imshow(l1_feature_map_relu_pool[:, :, 0]).set_cmap(\"gray\")\nax1[2, 0].get_xaxis().set_ticks([])\nax1[2, 0].get_yaxis().set_ticks([])\nax1[2, 0].set_title(\"L1-Map1ReLUPool\")\n\nax1[2, 1].imshow(l1_feature_map_relu_pool[:, :, 1]).set_cmap(\"gray\")\nax1[2, 0].get_xaxis().set_ticks([])\nax1[2, 0].get_yaxis().set_ticks([])\nax1[2, 1].set_title(\"L1-Map2ReLUPool\")\n\nmatplotlib.pyplot.savefig(\"L1.png\", bbox_inches=\"tight\")\nmatplotlib.pyplot.close(fig1)\n\n# Layer 2\nfig2, ax2 = matplotlib.pyplot.subplots(nrows=3, ncols=3)\nax2[0, 0].imshow(l2_feature_map[:, :, 0]).set_cmap(\"gray\")\nax2[0, 0].get_xaxis().set_ticks([])\nax2[0, 0].get_yaxis().set_ticks([])\nax2[0, 0].set_title(\"L2-Map1\")\n\nax2[0, 1].imshow(l2_feature_map[:, :, 1]).set_cmap(\"gray\")\nax2[0, 1].get_xaxis().set_ticks([])\nax2[0, 1].get_yaxis().set_ticks([])\nax2[0, 1].set_title(\"L2-Map2\")\n\nax2[0, 2].imshow(l2_feature_map[:, :, 2]).set_cmap(\"gray\")\nax2[0, 2].get_xaxis().set_ticks([])\nax2[0, 2].get_yaxis().set_ticks([])\nax2[0, 2].set_title(\"L2-Map3\")\n\nax2[1, 0].imshow(l2_feature_map_relu[:, :, 0]).set_cmap(\"gray\")\nax2[1, 0].get_xaxis().set_ticks([])\nax2[1, 0].get_yaxis().set_ticks([])\nax2[1, 0].set_title(\"L2-Map1ReLU\")\n\nax2[1, 1].imshow(l2_feature_map_relu[:, :, 1]).set_cmap(\"gray\")\nax2[1, 1].get_xaxis().set_ticks([])\nax2[1, 1].get_yaxis().set_ticks([])\nax2[1, 1].set_title(\"L2-Map2ReLU\")\n\nax2[1, 2].imshow(l2_feature_map_relu[:, :, 2]).set_cmap(\"gray\")\nax2[1, 2].get_xaxis().set_ticks([])\nax2[1, 2].get_yaxis().set_ticks([])\nax2[1, 2].set_title(\"L2-Map3ReLU\")\nax2[2, 0].imshow(l2_feature_map_relu_pool[:, :, 0]).set_cmap(\"gray\")\nax2[2, 0].get_xaxis().set_ticks([])\nax2[2, 0].get_yaxis().set_ticks([])\nax2[2, 0].set_title(\"L2-Map1ReLUPool\")\n\nax2[2, 1].imshow(l2_feature_map_relu_pool[:, :, 1]).set_cmap(\"gray\")\nax2[2, 1].get_xaxis().set_ticks([])\nax2[2, 1].get_yaxis().set_ticks([])\nax2[2, 1].set_title(\"L2-Map2ReLUPool\")\n\nax2[2, 2].imshow(l2_feature_map_relu_pool[:, :, 2]).set_cmap(\"gray\")\nax2[2, 2].get_xaxis().set_ticks([])\nax2[2, 2].get_yaxis().set_ticks([])\nax2[2, 2].set_title(\"L2-Map3ReLUPool\")\n\nmatplotlib.pyplot.savefig(\"L2.png\", bbox_inches=\"tight\")\nmatplotlib.pyplot.close(fig2)\n\n# Layer 3\nfig3, ax3 = matplotlib.pyplot.subplots(nrows=1, ncols=3)\nax3[0].imshow(l3_feature_map[:, :, 0]).set_cmap(\"gray\")\nax3[0].get_xaxis().set_ticks([])\nax3[0].get_yaxis().set_ticks([])\nax3[0].set_title(\"L3-Map1\")\n\nax3[1].imshow(l3_feature_map_relu[:, :, 0]).set_cmap(\"gray\")\nax3[1].get_xaxis().set_ticks([])\nax3[1].get_yaxis().set_ticks([])\nax3[1].set_title(\"L3-Map1ReLU\")\n\nax3[2].imshow(l3_feature_map_relu_pool[:, :, 0]).set_cmap(\"gray\")\nax3[2].get_xaxis().set_ticks([])\nax3[2].get_yaxis().set_ticks([])\nax3[2].set_title(\"L3-Map1ReLUPool\")\n\nmatplotlib.pyplot.savefig(\"L3.png\", bbox_inches=\"tight\")\nmatplotlib.pyplot.close(fig3)\n" } ]
1
DeSouzaSR/MM3
https://github.com/DeSouzaSR/MM3
e66672b88f7fd422b4168af2f68fa1d07c28ec3f
f5374fc5660be77b8c12a48b0af290187e2b8c87
c4be6c2891be1c9fe11575490f690a2740132128
refs/heads/master
2021-01-20T00:45:45.812691
2017-04-27T21:56:46
2017-04-27T21:56:46
89,183,721
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.541269838809967, "alphanum_fraction": 0.6317460536956787, "avg_line_length": 27.68181800842285, "blob_id": "c7fe430eb8885fda7cf7fde129f0f08b81b39dfd", "content_id": "3455f68c8ede14e1d6775eecc78e931b5979793a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 630, "license_type": "no_license", "max_line_length": 83, "num_lines": 22, "path": "/README.md", "repo_name": "DeSouzaSR/MM3", "src_encoding": "UTF-8", "text": "# MM3\nSimulate Solar System evolution, with STIPs planets in a *Jumping Jupiter* cenario.\n\nAuthor: Sandro Ricaro De Souza - <[email protected]>\n\nfile structure\n--------------\n\n* data/\n - raw_data/\n + 2017-04-23-srds-planets.csv # JPL data\n + 2017-04-23-srds-mercury.csv # JPL data\n - 2017-04-23-srds-planets-with-angles.csv # Include random angles \n - 2017-04-23-srds-mercury-with-angles.csv # Include random angles\n* deliver/\n - 2017-04-23-srds-report-results.ipynb \n* develop/\n - 2017-04-23-srds-create-directory-tree.ipynb\n - 2017-04-23-srds-write-ini-files.ipynb\n* figures/\n* src/\n* README.md" }, { "alpha_fraction": 0.4584837555885315, "alphanum_fraction": 0.6835997700691223, "avg_line_length": 22.932098388671875, "blob_id": "c5be010f4088ce0617d1451a46a60e6ffe556c14", "content_id": "0417f4b579d351bddd87042e5e459e98f52f318b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3878, "license_type": "no_license", "max_line_length": 162, "num_lines": 162, "path": "/2017-04-25-srds-pipeline-mm.py", "repo_name": "DeSouzaSR/MM3", "src_encoding": "UTF-8", "text": "\n# coding: utf-8\n\n# # Multiple Mercury\n# \n# Simulate a Solar System, in a *jumping jupiter* scenario, evaluating different configurations of semi-axes for a hypothetical planet Mercury in a compact orbit.\n# \n# Tasks:\n# + Create directory tree\n# + Create the Swift configuration files\n# + Run the simulation\n# + Extract figures\n# \n\n# Import modules\n\n# In[1]:\n\nimport os\nimport shutil\nfrom glob import glob\nimport numpy as np\nimport math\n\nimport sys\n\nprint(os.getcwd())\nos.chdir(\"~/Projects/MM3\")\n# sys.path.insert(0, 'src/')\n# import oe2pv\n\n\n# ## Create directory tree\n\n# In[2]:\n\n# Vectorize oe2pv\noe2pv_vec = np.vectorize(oe2pv.orbel_el2xv)\n\n\n# In[3]:\n\nsimulation_name = \"mercury\"\nlevel1 = 4 # Number of mercury varying with distance \nlevel2 = 5 # Number of clones\nsimulation_path = \"output/\" + simulation_name\nabsolute_path = os.getcwd()\nplanets_name = ['mercury','venus', 'earth', 'mars', 'jupiter','saturn', 'uranus', 'neptune']\n\n\n# In[ ]:\n\n\n\n\n# ## Create the Swift configuration files\n\n# In[4]:\n\n# Planets' data\n\nmercury = np.array( [0.38709893000000001, 0.20499999999999999, 7.0, 2439.6999999999998, 87.968999999999994, 3.3011000000000001e+23] )\nvenus = np.array( [0.72333199000000004, 0.0067732299999999999, 3.3947099999999999, 6051.8000000000002, 224.70099999999999, 4.8674999999999993e+24] )\nearth = np.array( [1.00000011, 0.016710220000000001, 5.0000000000000002e-05, 6378.1369999999997, 365.25599999999997, 5.9722999999999996e+24] )\nmars = np.array( [1.52366231, 0.093412330000000002, 1.8506100000000001, 3396.1999999999998, 686.98000000000002, 6.4171000000000003e+23] )\njupiter = np.array( [5.2033630100000003, 0.048392659999999997, 1.3052999999999999, 71492.0, 4332.5889999999999, 1.8981900000000001e+27] )\nsaturn = np.array( [9.5370703199999998, 0.0541506, 2.4844599999999999, 60268.0, 10759.219999999999, 5.6834000000000003e+26] )\nuranus = np.array( [19.191263930000002, 0.047167710000000002, 0.76985999999999999, 25559.0, 30685.400000000001, 8.6813e+25] )\nneptune = np.array( [30.068963480000001, 0.0085858700000000007, 1.7691699999999999, 24764.0, 60189.0, 1.0241299999999999e+26] )\n\n\n# In[5]:\n\n# Create new column, considering G = 1\n# Mass of the Sum, in kg\nmass_sun_kg = 1988500e24\n\n# Mass of the Sun, with G = 1\nmass_sun_grav = 2.959139768995959e-04\n\n# Conic section is ellipse\nialpha = -1\n\n# Gravitational factor of the Sun\ngm = 2.959139768995959e-04\n\n\n# In[6]:\n\n# Repeat data lines for each planet\nrow_planets = level1 * level2\ncolumns_planets = len(mercury)\n\nfor pl in planets_name:\n exec(\"{0} = np.array([{0},]*row_planets)\".format(pl))\n\n\n# In[7]:\n\n# Create mass_grav column from mass = planet[8]\n# Create gmpl column from mass_grav = planet[9]\n\nfor pl in planets_name:\n exec(\"{0} = np.c_[{0}, {0}[:, 5] * mass_sun_grav / mass_sun_kg]\".format(pl))\n exec(\"{0} = np.c_[{0}, {0}[:, 6] + gm]\".format(pl))\n\n\n# ### Write config files\n\n# In[8]:\n\nos.chdir(\"output\")\n\nif os.path.isdir(simulation_name):\n shutil.rmtree(simulation_name)\n os.mkdir(simulation_name)\n os.chdir(simulation_name)\nelse:\n os.mkdir(simulation_name)\n os.chdir(simulation_name)\n\nfor i in range(level1):\n for j in range(level2):\n os.mkdir(simulation_name + \"-\" + \"{:03d}\".format(i) + \"-\" + \"{:03d}\".format(j))\n \nos.chdir(absolute_path)\n\n\n# In[10]:\n\n# Sun's data\n\nsun_pv = \"\"\"\n2.959139768995959E-04\n0.0 0.0 0.0\n0.0 0.0 0.0\n\"\"\"\n\nos.chdir(absolute_path)\nos.chdir(\"output/\" + simulation_name)\n\nsimulations = glob(\"*\")\nfor simulation in enumerate(simulations):\n os.chdir(simulation[1])\n with open(\"pl.in\", \"w+\") as f:\n f.write(str(len(planets_name)+1))\n f.write(sun_pv)\n for i in range(len(planets_name)):\n pl_data = str(planets_name[i], 0])\n f.write(pl_date)\n os.chdir(\"../\")\n\nos.chdir(absolute_path)\n\n\n# In[13]:\n\nprint(str(planets_name[0][0,1]))\n\n\n# ## Run the simulation\n\n# ## Extract figures\n" }, { "alpha_fraction": 0.5458715558052063, "alphanum_fraction": 0.5825688242912292, "avg_line_length": 12.6875, "blob_id": "e5ab59a79ddf197f88fb134494e78428903426a5", "content_id": "f1020c7523ffbecec4e7558af3bf4eb7ce5ded68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 218, "license_type": "no_license", "max_line_length": 32, "num_lines": 16, "path": "/teste.py", "repo_name": "DeSouzaSR/MM3", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python \n# coding: utf-8\n\n# In[]\nimport matplotlib.pyplot as plt \nimport numpy as np \n\n# In[]\nx = np.linspace(0, 10, 1000)\ny = np.sin(x)\n\nprint(\"x = \", len(x))\nprint(\"y = \", len(y))\n\n# In[]\nplt.plot(x, y)" } ]
3
enjey00/Chapter-4
https://github.com/enjey00/Chapter-4
0ef3a6ae3a38fe685fcc977e166cc43f21aac659
47408609dd33a6b04ecba41434af7e38ce6709ec
ebf9b7b88cf544897af2ee9cf27e9895eb79c96e
refs/heads/master
2020-09-06T18:06:45.867242
2019-11-08T17:45:18
2019-11-08T17:45:18
220,504,381
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5529157519340515, "alphanum_fraction": 0.5593952536582947, "avg_line_length": 33.22222137451172, "blob_id": "a97af63d20c7e624c04e8b101907d6b49d0970f1", "content_id": "9a7c024c5b968618a59c82adb2415423f5676049", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 926, "license_type": "no_license", "max_line_length": 77, "num_lines": 27, "path": "/task6.py", "repo_name": "enjey00/Chapter-4", "src_encoding": "UTF-8", "text": "class House:\n def __init__(self, household_type, total_area):\n self.type = household_type\n self.total_area = total_area\n self.furniture = []\n print(\n \"Total area in the\", household_type, ':', \n self.total_area, 'sq m.', end=' '\n )\n print('Furnitures in the', household_type, ':', self.furniture, '\\n')\n\n def add_furniture(self, name, area):\n self.name = name\n self.area = area\n self.total_area = self.total_area - self.area\n self.furniture.append(name)\n print(name, 'has been added to the', self.type)\n print(\n \"\\nFree area in the\", self.type, ':', \n house.total_area, 'sq m.', end=' '\n )\n print('Furnitures in the', self.type, house.furniture)\n\nhouse = House('Mansion', 15)\nhouse.add_furniture('Bed', 4)\nhouse.add_furniture('Wardrobe', 2)\nhouse.add_furniture('Table', 1.5)\n\n\n" }, { "alpha_fraction": 0.41258740425109863, "alphanum_fraction": 0.4545454680919647, "avg_line_length": 17, "blob_id": "a66a112a0b26dc4964a4272c862526d6ae9c851b", "content_id": "f1c68a127559e693dbbd01361dd5f5b2eb4f6a81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 143, "license_type": "no_license", "max_line_length": 27, "num_lines": 8, "path": "/task14.py", "repo_name": "enjey00/Chapter-4", "src_encoding": "UTF-8", "text": "def stepPerms(n):\n list_ = [1,2,4]\n\n for x in range(1, n):\n s = sum(list_[-3:])\n list_.append(s)\n \n return list_[n-1]" }, { "alpha_fraction": 0.5611510872840881, "alphanum_fraction": 0.5719424486160278, "avg_line_length": 33.8125, "blob_id": "1f33fc9bfd7eee2054ff19b553d0808757020e9b", "content_id": "cf195282298c8975406685cf42a5c8cb6c57aba9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 580, "license_type": "no_license", "max_line_length": 69, "num_lines": 16, "path": "/task1.py", "repo_name": "enjey00/Chapter-4", "src_encoding": "UTF-8", "text": "class Student:\n def __init__(self, name, lastname, department, year_of_entrance):\n self.name = name\n self.lastname = lastname\n self.department = department\n self.year_of_entrance = year_of_entrance\n\n def get_student_info(self):\n print(\n self.name + ' ' + self.lastname + ' поступил в ' + \n str(self.year_of_entrance) + ' году на факультет: ' \n + self.department\n )\n\nstudent1 = Student('Zhenishbek', 'Azimkanov', 'Python', 2019)\nstudent1.get_student_info()" }, { "alpha_fraction": 0.6069767475128174, "alphanum_fraction": 0.6139534711837769, "avg_line_length": 27.700000762939453, "blob_id": "02fe2897c167825ea926dde9089bbcbac8f8f322", "content_id": "c7cac156ce804ab57c81b35af27284a4e2dcca49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 860, "license_type": "no_license", "max_line_length": 62, "num_lines": 30, "path": "/task5.py", "repo_name": "enjey00/Chapter-4", "src_encoding": "UTF-8", "text": "class Soldier:\n def __init__(self, name, gun_type):\n self.name = name\n self.gun_type = gun_type\n print(name, 'has an', gun_type)\n\nclass Gun:\n def __init__(self, name, gun_type):\n Soldier.__init__(self, name, gun_type)\n self.bullets = 7\n print('Gun is loaded:', self.bullets, 'bullets')\n\n def fire_bullets(self):\n self.bullets = 0\n print('Gun has been fired:', self.bullets, 'bullets')\n\n def reload_bullets(self, bullets):\n self.bullets += bullets\n print('Gun has been reload:', self.bullets, 'bullets')\n\nclass Act_of_shooting(Gun):\n def __init__(self, name, gun_type):\n Gun.__init__(self, name, gun_type)\n\nsoldier = Act_of_shooting('Ryan', 'AK47')\nsoldier.fire_bullets()\nsoldier.reload_bullets(7)\nsoldier.fire_bullets()\nsoldier.reload_bullets(7)\nsoldier.fire_bullets()" }, { "alpha_fraction": 0.57413250207901, "alphanum_fraction": 0.57413250207901, "avg_line_length": 27.636363983154297, "blob_id": "6accc024be91eec7556651ea868a1bc75c29532c", "content_id": "ae3f8a1ff90189331a5d91c3749938bcf64a199e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 317, "license_type": "no_license", "max_line_length": 76, "num_lines": 11, "path": "/task4.py", "repo_name": "enjey00/Chapter-4", "src_encoding": "UTF-8", "text": "class ContactList(list):\n def __init__(self, *all_):\n self.all_ = all_\n\n def search_by_name(self, name):\n for a in self.all_:\n if a in name:\n print(a)\n\nall_contacts = ContactList('Zhenishbek', 'Altynbek', 'Orozobek', 'Orozobek')\nall_contacts.search_by_name('Orozobek')\n\n\n" }, { "alpha_fraction": 0.6087484955787659, "alphanum_fraction": 0.6208991408348083, "avg_line_length": 27.34482765197754, "blob_id": "9217f32ef67c6f4c6b0c1e8b310ab98292f049e7", "content_id": "27a22b3d9f3ca1ec3897552167956462785a9ee6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 881, "license_type": "no_license", "max_line_length": 63, "num_lines": 29, "path": "/task2.py", "repo_name": "enjey00/Chapter-4", "src_encoding": "UTF-8", "text": "class Airplane:\n def __init__(self, make, model, year, max_speed):\n self.make = make\n self.model = model\n self.year = year\n self.max_speed = max_speed\n self.odometer = 0\n self.is_flying = False\n print(make, model, year, max_speed)\n \n def take_off(self):\n self.is_flying = True\n print('Самолет взлетел')\n \n def fly(self, km):\n self.odometer = self.odometer + km\n\n def land(self):\n self.is_flying = False\n\nairplane = Airplane('Jet', 'Business', 2008, 600)\nprint(f'Одометр самолета: {airplane.odometer}')\nprint(f'Fly: {airplane.is_flying}')\nairplane.take_off()\nairplane.fly(45)\nprint(f'Fly: {airplane.is_flying}')\nprint(f'Самолет пролетел {airplane.odometer} км и приземлился')\nairplane.land()\nprint(f'Fly :{airplane.is_flying}')\n\n" }, { "alpha_fraction": 0.5316159129142761, "alphanum_fraction": 0.5526931881904602, "avg_line_length": 25.6875, "blob_id": "85b78cccc4b4d84b7392af40e739d5777be1ffe1", "content_id": "364fcbe359274fdf2ee3a69777688ddb770c3811", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 887, "license_type": "no_license", "max_line_length": 56, "num_lines": 32, "path": "/task3.py", "repo_name": "enjey00/Chapter-4", "src_encoding": "UTF-8", "text": "print('Сколько километров Вы хотите проехать?')\nnum = int(input())\nclass Car:\n def __init__(self, make, model, year):\n self.make = make\n self.model = model\n self.year = year\n self.odometer = 0\n self.fuel = 70\n\n def drive(self, km):\n if km <= 700:\n self.__add_distance(km)\n self.__subtract_fuel(km)\n print(\"Let's drive!!\\n\")\n\n else:\n print(\"Need more fuel,please, fill more!\\n\")\n\n def __add_distance(self, km):\n self.odometer += km\n\n def __subtract_fuel(self, km):\n km = km/10\n self.fuel -= km\n\ncar1 = Car('Toyota', 'ipsum', 2003)\nprint(\"\\nBefore driving: \", car1.odometer, 'km')\nprint(\"Before driving: \", car1.fuel, 'l', '\\n')\ncar1.drive(num)\nprint(\"After driving: \", car1.odometer, 'km')\nprint(\"After driving\", car1.fuel, 'l')\n" }, { "alpha_fraction": 0.5263158082962036, "alphanum_fraction": 0.5939849615097046, "avg_line_length": 19, "blob_id": "ca30034ef8133f358cf96bce453abbafc904fc7a", "content_id": "c7ec060d48ba107f68afad4a7600547381e4d563", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 399, "license_type": "no_license", "max_line_length": 48, "num_lines": 20, "path": "/task8.py", "repo_name": "enjey00/Chapter-4", "src_encoding": "UTF-8", "text": "class MoneyFmt():\n def __init__(self, data):\n self.data = data\n\n def repr(self):\n print(self.data)\n\n def update(self, new_data):\n self.data = new_data\n\n def __str__(self):\n dollarize = '${:,.2f}'.format(self.data)\n return dollarize\n\nfloat_ = MoneyFmt(123654.2160000)\nfloat_.repr()\nprint(float_)\nfloat_.update(31546549.12464)\nfloat_.repr()\nprint(float_)" } ]
8
jacktrinity/WeatherApp-API
https://github.com/jacktrinity/WeatherApp-API
e3f5dbbd67eb9e35ff358a088c4217a498a359a0
3321934bb39ae74f9cb40a90e077df79958bfa7d
1015dd20063af339586daa7246fb6abc250e0595
refs/heads/master
2020-04-20T18:52:16.868715
2019-02-04T06:09:29
2019-02-04T06:09:29
169,033,738
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6568174958229065, "alphanum_fraction": 0.6780548095703125, "avg_line_length": 29.563106536865234, "blob_id": "44eb5fb070d21475014920d945dd93df878335ac", "content_id": "b781afe6faf292618fdb05023fa88b7875217f55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3249, "license_type": "no_license", "max_line_length": 79, "num_lines": 103, "path": "/weather_app_gui.py", "repo_name": "jacktrinity/WeatherApp-API", "src_encoding": "UTF-8", "text": "from tkinter import *\r\nimport json\r\nimport urllib.request\r\nimport time\r\n\r\n# Our Window\r\nroot = Tk()\r\nroot.title(\"Weather Application\")\r\n\r\n\r\n# Button Function after pressing \"Enter\"\r\ndef city_output(event):\r\n city_name = city_input.get();\r\n get_api(city_name)\r\n\r\n\r\n# Get API from openweathermap.org\r\ndef get_api(city):\r\n url_first_half = \"http://api.openweathermap.org/data/2.5/weather?q=\"\r\n url_second_half = \",us&appid=8da995db2c96601bd55534c67e8856db\"\r\n full_url = url_first_half + city + url_second_half\r\n\r\n response = urllib.request.urlopen(full_url)\r\n result = json.loads(response.read())\r\n\r\n weather_forecast(result)\r\n\r\n# Parsing through the JSON file and updating for weather information\r\ndef weather_forecast(weather_result):\r\n my_time = weather_result[\"dt\"]\r\n\r\n intro_time = Label(root, text=str(time.ctime(my_time)))\r\n intro_time.grid(row=1, column=1, sticky=W)\r\n\r\n\r\n current_temperature = weather_result[\"main\"][\"temp\"] # Current temperature\r\n min_temperature = weather_result[\"main\"][\"temp_min\"] # Min temperature\r\n max_temperature = weather_result[\"main\"][\"temp_max\"] # Max temperature\r\n\r\n current_temperature = round(temp_k_to_f(current_temperature), 2)\r\n min_temperature = round(temp_k_to_f(min_temperature), 2)\r\n max_temperature = round(temp_k_to_f(max_temperature), 2)\r\n\r\n current_temp_display = Label(root, text=str(current_temperature) + \" F\")\r\n current_temp_display.grid(row=2, column=1, sticky=W)\r\n\r\n low_temp_display = Label(root, text=str(min_temperature) + \" F\")\r\n low_temp_display.grid(row=3, column=1, sticky=W)\r\n\r\n high_temp_display = Label(root, text=str(max_temperature) + \" F\")\r\n high_temp_display.grid(row=4, column=1, sticky=W)\r\n\r\n\r\n# Converting our temperature into Fahrenheit\r\ndef temp_k_to_f(kevin):\r\n fahrenheit = (kevin - 273.15) * (9 / 5) + 32\r\n\r\n return fahrenheit\r\n\r\n### Main body ###\r\ncity_label = Label(root, text=\"Please enter a city: \")\r\ncity_label.grid(row=0, column=0, sticky=W)\r\n\r\ncity_input = Entry(root)\r\ncity_input.bind(\"<Return>\", city_output)\r\ncity_input.grid(row=0, column=1)\r\n\r\n\r\nbutton_enter = Button(root, text=\"Enter\", fg=\"blue\")\r\nbutton_enter.bind(\"<Button-1>\", city_output)\r\nbutton_enter.grid(row=0, column=2)\r\n\r\nintro_label = Label(root, text=\"Date and Time: \")\r\nintro_label.grid(row=1, column=0, sticky=W)\r\n\r\nintro_time = Label(root, text=\"Current Weather Report\")\r\nintro_time.grid(row=1, column=1, sticky=W)\r\n\r\n\r\n\r\n# Temperature Display\r\ncurrent_temp = 0\r\nlow_temp = 0\r\nhigh_temp = 0\r\n\r\ncurrent_temp_label = Label(root, text=\"Current Temperature: \")\r\ncurrent_temp_label.grid(row=2, column=0, sticky=W)\r\ncurrent_temp_display = Label(root, text=str(current_temp) + \" F\")\r\ncurrent_temp_display.grid(row=2, column=1, sticky=W)\r\n\r\nlow_temp_label = Label(root, text=\"Low Temperature Today: \")\r\nlow_temp_label.grid(row=3, column=0, sticky=W)\r\nlow_temp_display = Label(root, text=str(low_temp) + \" F\")\r\nlow_temp_display.grid(row=3, column=1, sticky=W)\r\n\r\nhigh_temp_label = Label(root, text=\"High Temperature Today: \")\r\nhigh_temp_label.grid(row=4, column=0, sticky=W)\r\nhigh_temp_display = Label(root, text=str(high_temp) + \" F\")\r\nhigh_temp_display.grid(row=4, column=1, sticky=W)\r\n\r\n\r\n# Display Window\r\nroot.mainloop()" }, { "alpha_fraction": 0.7801724076271057, "alphanum_fraction": 0.7801724076271057, "avg_line_length": 23.421052932739258, "blob_id": "718fbac420ebe4dfe42db9464309283a6a76f933", "content_id": "a05d03dcf48f2b6dedba3b2ddca5f6a1ab2cffce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 464, "license_type": "no_license", "max_line_length": 87, "num_lines": 19, "path": "/README.md", "repo_name": "jacktrinity/WeatherApp-API", "src_encoding": "UTF-8", "text": "# WeatherApp-API\nWeather Application in GUI Framework - API\nPython Tkinter GUI Framework\n\nDisplay weather menu in frame.\n\nUser enter a city name from the United Sates to get API\nexample city:\n irvine\n los angeles\n\n \nOutput the weather temperature. Current, low, and high.\nDate and time is display when the weather forecast was last updated on myweathermap.org\n\nFun project, teaching me about GUI framework as well as using API.\n\nThank you for viewing.\nEnjoy =)\n" } ]
2
IntroProgramacion-P-Oct20-Feb21/2bim-proyecto-python-MichaelPereira69
https://github.com/IntroProgramacion-P-Oct20-Feb21/2bim-proyecto-python-MichaelPereira69
f3b3ddaef0b7631064b311b7399fbe7afa08b385
7d37de9207d4c8bbb3f78d0134c09db4fc0e467c
1f582983e20b99b8ee2a4b4a8178d6405c2caccd
refs/heads/main
2023-02-26T21:18:41.451617
2021-02-05T16:11:58
2021-02-05T16:11:58
332,068,408
0
0
null
2021-01-22T21:39:07
2021-01-22T21:39:14
2021-01-22T21:39:15
Python
[ { "alpha_fraction": 0.5088961720466614, "alphanum_fraction": 0.5144239068031311, "avg_line_length": 37.599998474121094, "blob_id": "36af25b186e99221a853f08205a147d3cca23800", "content_id": "a5c61d81a4bd09110e1291a2a895156ca13b31ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5828, "license_type": "no_license", "max_line_length": 81, "num_lines": 150, "path": "/codigo/run.py", "repo_name": "IntroProgramacion-P-Oct20-Feb21/2bim-proyecto-python-MichaelPereira69", "src_encoding": "UTF-8", "text": "def crearFacebook():\n print(\"Creemos una cuenta de Facebook \")\n usuario = input(\"Nombre de usuario\\n> \")\n edad = float (input(\"Edad\\n> \"))\n ciudad = input(\"Ciudad en la que resides\\n> \")\n pais = input(\"País\\n> \")\n correo = input(\"Correo electrónico\\n> \")\n cadena = (f\"Tus datos son:\\n\"\n f\"Usuario: {usuario}\\nEdad: {edad}\\nCiudad: {ciudad}\\n\"\n f\"País: {pais}\\nCorreo Electrónico: {correo}\\n\")\n return cadena\n\ndef crearTwitter():\n print(\"Creemos una cuenta de Twitter\")\n usuario = input(\"Nombre de usuario\\n> \")\n apellidos = input(\"Apellidos\\n> \")\n edad = int(input(\"Escribe tu Edad\\n> \"))\n ciudad = input(\"Ciudad en la que vives\\n> \")\n pais = input(\"País\\n> \")\n idioma = input(\"ingresa tu idioma\\n> \")\n correo = input(\"Correo electrónico\\n> \")\n print(f\"Tus datos personales son: \\n\"\n f\"Usuario: {usuario}\\nApellidos: {apellidos}\\nEdad: {edad}\\n\"\n f\"Ciudad: {ciudad}\\nPaís: {pais}\\nIdioma: {idioma}\\n\"\n f\"Correo Electrónico: {correo}\\n\")\n\n\ndef crearWhatsapp():\n print(\"Creemos una cuenta de Whatsapp \")\n usuario = input(\"Nombre de usuario\\n> \")\n numero = int(input(\"Número de teléfono\\n> \"))\n edad = int(input(\"Edad\\n> \"))\n ciudad = input(\"Ciudad en la que vives\\n> \")\n pais = input(\"País\\n> \")\n cadena = (f\"Tus Datos son:\\n\"\n f\"Usuario: {usuario}\\nNúmero de teléfono: {numero}\\n\"\n f\"Edad: {edad}\\nCiudad: {ciudad}\\nPaís: {pais}\\n\"\n f\"-----------\")\n return cadena\n\n\ndef crearTelegram():\n print(\"Creemos una cuenta de Telegram --*\")\n usuario = input(\"Nombre de usuario\\n> \")\n numero = int(input(\"Número de teléfono\\n> \"))\n ciudad = input(\"Ciudad en la que vives\\n> \")\n pais = input(\"País\\n> \")\n area_interes = input(\"Escrube un Area de tu interés\\n> \")\n print(f\"Tus datos personales son:\\n\"\n f\"Usuario: {usuario}\\nNúmero de teléfono: {numero}\\n\"\n f\"Ciudad: {ciudad}\\nPaís: {pais}\\nÁrea de Interés: {area_interes}\\n\")\n\n\ndef crearSignal():\n print(\"Creemos una cuenta de Signal --*\")\n usuario = input(\"Nombre de Usuario\\n> \")\n numero = int(input(\"Número de teléfono\\n> \"))\n ciudad = input(\"Ciudad\\n> \")\n pais = input(\"País\\n> \")\n hobby = input(\"Hobby principal\\n> \")\n cadena = (f\"Tus datos personales son: \\n\"\n f\"Usuario: {usuario}\\nNúmero de teléfono: {numero}\\n\"\n f\"Ciudad: {ciudad}\\nPaís: {pais}\\nHobby principla: {hobby}\\n\")\n return cadena\n\n\ndef crearInstagram():\n print(\"*-- Usted eligió la opción para crear una cuenta de Instagram --*\")\n usuario = input(\"Ingrese su nombre de usuario\\n> \")\n ciudad = input(\"Ingrese su ciudad\\n> \")\n edad = int(input(\"Ingrese su edad\\n> \"))\n correo = input(\"Ingrese su correo electrónico\\n> \")\n print(f\"Tus datos personales son: \\n\"\n f\"Usuario: {usuario}\\nCiudad: {ciudad}\\ndad: {edad}\\n\"\n f\"Correo Electrónico: {correo}\\n\")\n\n\ndef crearFlickr():\n print(\"Creemos una cuenta de Flickr *\")\n usuario = input(\"Nombre de usuario\\n> \")\n correo = input(\"Correo electrónico\\n> \")\n cadena = (f\" Datos Ingresados\\n\"\n f\"Usuario: {usuario}\\nCorreo Electrónico: {correo}\\n\")\n return cadena\n\n\ndef obtenerMensaje(a):\n mensaje_final = [\"Campaña con poca afluencia\",\n \"Campaña moderada siga adelante\", \"Excelente campaña\"]\n\n if ((a >= 1) and (a <= 5)):\n cadena = mensaje_final[0]\n else:\n if ((a >= 6) and (a <= 15)):\n cadena = mensaje_final[1]\n else:\n if (a >= 16):\n cadena = mensaje_final[2]\n return cadena\n\n\nif __name__ == \"__main__\":\n bandera = True\n contador = 0\n while bandera:\n print(\"Opciones\")\n opcion = int(input(\"> Inserte 1 para creara una cuenta de Facebook.\\n\"\n + \"> Ingrese 2 para creara una cuenta de Twitter.\\n\"\n + \"> Ingrese 3 para creara una cuenta de Whatsapp.\\n\"\n + \"> Ingrese 4 para creara una cuenta de Telegram.\\n\"\n + \"> Ingrese 5 para creara una cuenta de Signal.\\n\"\n + \"> Ingrese 6 para creara una cuenta de Instagram.\\n\"\n + \"> Ingrese 7 para creara una cuenta de Flickr.\\n\"))\n if (opcion == 1):\n contador += 1\n cuenta_facebook = crearFacebook()\n print(cuenta_facebook)\n else:\n if (opcion == 2):\n contador += 1\n crearTwitter()\n else:\n if (opcion == 3):\n contador += 1\n cuenta_whatsapp = crearWhatsapp()\n print(cuenta_whatsapp)\n else:\n if (opcion == 4):\n contador += 1\n crearTelegram()\n else:\n if (opcion == 5):\n contador += 1\n cuenta_signal = crearSignal()\n print(cuenta_signal)\n else:\n if (opcion == 6):\n contador += 1\n crearInstagram()\n else:\n if (opcion == 7):\n cuenta_flickr = crearFlickr()\n print(cuenta_flickr)\n else:\n print(\"Opción incorrecta\")\n salida = input(\"Ingrese 'salir' si desea salir del ciclo o diguite\"\n \" 1 para crear otra cuenta\\n> \")\n if (salida == \"salir\"):\n bandera = False\n print(obtenerMensaje(contador))" } ]
1
LucasBlommers/solicitatie
https://github.com/LucasBlommers/solicitatie
5e2ceb4d89d704b0c0e60a439669fb9791adf221
15501abc2e2dac50fafbc3493d137c35b44d1961
05689c0b19bf2892b3377fdce6b650ec9c95ebe4
refs/heads/master
2023-08-18T09:09:16.564845
2021-09-08T07:21:17
2021-09-08T07:21:17
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8545454740524292, "alphanum_fraction": 0.8545454740524292, "avg_line_length": 26.5, "blob_id": "d2d28e79350b2784f1a19daaab728acc592570fd", "content_id": "3da3a57d923c6d39a6a52536a76ba580337b42ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 55, "license_type": "no_license", "max_line_length": 40, "num_lines": 2, "path": "/README.md", "repo_name": "LucasBlommers/solicitatie", "src_encoding": "UTF-8", "text": "# solicitatie\nSolicitatie app voor een circusdirecteur\n" }, { "alpha_fraction": 0.48554250597953796, "alphanum_fraction": 0.49069568514823914, "avg_line_length": 45.586666107177734, "blob_id": "332bf4e975ed285770d953be14dd45624b8eac1c", "content_id": "94c479254bfd47818e02df166bb5d8a39408a887", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3495, "license_type": "no_license", "max_line_length": 128, "num_lines": 75, "path": "/solicitatie.py", "repo_name": "LucasBlommers/solicitatie", "src_encoding": "UTF-8", "text": "mogenlijkeKandidaat = False\n\nprint(\"Hoeveel jaar ervaring heeft met dieren dresuur?\")\ndierenDresuurErvaring = int(input())\n\nprint(\"Hoeveel jaar ervaring heeft u met jongleren?\")\njongleerErvaring = int(input())\n\nprint(\"Hoeveel jaar praktijk ervaring heeft u met acrobatiek?\")\nacrobatiekErvaring = int(input())\n\ninput(\"Hoeveel katten heeft u?\\n\")\ninput(\"Hoeveel honden heeft u?\\n\")\n\nif(dierenDresuurErvaring > 4 or jongleerErvaring > 5 or acrobatiekErvaring > 3):\n print(\"Ben u in het bezit van een MBO-4 ondernemen diploma J/N\")\n ondernemenDiploma = input()\n\n if(ondernemenDiploma == \"j\" or ondernemenDiploma == \"J\"):\n print(\"Bent u in het bezig van een geldig vrachtwagen rijbewijs? J/N\")\n vrachtwagenRijbewijs = input()\n\n if(vrachtwagenRijbewijs == \"j\" or vrachtwagenRijbewijs == \"J\"):\n print(\"Bent u in het bezit van een hoge hoed? J/N\")\n hogeHoed = input()\n\n input(\"Hoeveel jaren één wieler ervaring heeft u?\\n\")\n input(\"Hoeveel uur heeft u Bassie en Adriaan gezien?\\n\")\n if(hogeHoed == \"j\" or hogeHoed == \"J\"):\n print(\"Wat is uw geslacht? M/V\")\n geslacht = input()\n\n if(geslacht == \"m\" or geslacht == \"M\"):\n print(\"Hoe breed is uw snor in centimeters?\")\n breedteSnor = int(input())\n if(breedteSnor > 10):\n print(\"Wat is uw lengte in centimeters?\")\n lengte = int(input())\n\n if(lengte > 150):\n print(\"Wat is uw gewicht in kilogram?\")\n gewicht = int(input())\n if(gewicht > 90):\n print(\"Bent u in het bezit van een certificaat 'Overleven met gevaalijk personeel' J/N\")\n certOveleven = input()\n if(certOveleven == \"j\" or certOveleven == \"J\"):\n mogenlijkeKandidaat = True\n\n elif(geslacht == \"v\" or geslacht == \"V\"):\n print(\"Welke kleur is uw haar\")\n haarkleur = input()\n\n if(haarkleur == \"Rood\" or haarkleur == \"rood\"):\n print(\"Heeft u krullen? J/N\")\n krullen = input()\n\n if(krullen == \"j\" or krullen == \"J\"):\n print(\"Hoelang zijn de krullen in centimeters?\")\n krulLengte = int(input())\n if(krulLengte > 20):\n print(\"Wat is uw lengte in centimeters?\")\n lengte = int(input())\n if(lengte > 150):\n print(\"Wat is uw gewicht in kilogram?\")\n gewicht = int(input())\n if(gewicht > 90):\n print(\"Bent u in het bezit van een certificaat 'Overleven met gevaalijk personeel' J/N\")\n certOveleven = input()\n if(certOveleven == \"j\" or certOveleven == \"J\"):\n mogenlijkeKandidaat = True\n\nif(mogenlijkeKandidaat == False):\n print(\"U komt helaas niet in aanmerking voor onze vacature, tot ziens.\")\nelse:\n print(\"Gefeliciteerd! U komt in aanmerking voor de vacature.\")" } ]
2
sumitjat/blog_project
https://github.com/sumitjat/blog_project
d301938acb192cdd8b15b8db7a40aefbb49b6289
723b4cdc472168b4b4e509cb09b98401555c307a
c24810280247028ddeef5f87d818a2c3f5bb1dfb
refs/heads/master
2021-05-24T13:21:32.559030
2020-09-18T12:57:00
2020-09-18T12:57:00
253,581,151
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6693735718727112, "alphanum_fraction": 0.6693735718727112, "avg_line_length": 25.9375, "blob_id": "1847c2ac679ded2210d5c286f05faf7608b4f8ee", "content_id": "96a60934509f60d27e0be0f674cfe3686209909a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 862, "license_type": "no_license", "max_line_length": 83, "num_lines": 32, "path": "/app/admin.py", "repo_name": "sumitjat/blog_project", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom app.models import Post,Comment\n# Register your models here.\n\n\nclass PostAdmin(admin.ModelAdmin):\n list_display = ['title','slug','author','created','publish','updated','status']\n\n # we want to filter in admin\n list_filter = ('status',)\n\n # for search option\n search_fields = ('title',)\n\n # we want data to choose from id field\n raw_id_fields = ('author',)\n\n # we can see navbar in admin\n date_hierarchy = 'publish'\n # to order\n ordering = ['status','publish']\n # we can slug to be set automatically based on other field\n prepopulated_fields = {'slug':('title',)}\n\n\nclass CommentAdmin(admin.ModelAdmin):\n list_display = ['name','email','post','created','updated','active']\n list_filter = ('active',)\n\n\nadmin.site.register(Post,PostAdmin)\nadmin.site.register(Comment,CommentAdmin)\n" }, { "alpha_fraction": 0.6875, "alphanum_fraction": 0.6875, "avg_line_length": 20.33333396911621, "blob_id": "1cfaf9a13110a2656cef98bbffa5a38d8e750e27", "content_id": "de8702626dab4b395e3d899e12044993ede8342d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 64, "license_type": "no_license", "max_line_length": 47, "num_lines": 3, "path": "/README.md", "repo_name": "sumitjat/blog_project", "src_encoding": "UTF-8", "text": "# blog_project\n\nBasic Django Project Just doing for fun !!! :-)\n" }, { "alpha_fraction": 0.6560174822807312, "alphanum_fraction": 0.6625820398330688, "avg_line_length": 31.600000381469727, "blob_id": "1e253577798555778acf5925b086ada691cece12", "content_id": "029c4faf617afcb3aafc1b2047244505e57e24dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2285, "license_type": "no_license", "max_line_length": 118, "num_lines": 70, "path": "/app/views.py", "repo_name": "sumitjat/blog_project", "src_encoding": "UTF-8", "text": "from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.shortcuts import render,get_object_or_404\nfrom taggit.models import Tag\n\nfrom app.forms import EmailSendForm\nfrom app.models import Post\nfrom django.views.generic import ListView\nfrom django.core.mail import send_mail\nfrom app.forms import CommentForm\n# Create your views here.\n\ndef post_list_view(req,tag_slug=None):\n post_list=Post.objects.all()\n\n tag=None\n if tag_slug:\n tag=get_object_or_404(Tag,slug=tag_slug)\n post_list=post_list.filter(tags__in=[tag])\n\n paginator=Paginator(post_list,3)\n page_no=req.GET.get('page')\n try:\n post_list=paginator.page(page_no)\n except PageNotAnInteger:\n post_list=paginator.page(1)\n except EmptyPage:\n post_list=paginator.page(paginator.num_pages)\n\n return render(req,\"post_list.html\",{'post_list':post_list,'tag':tag})\n\nclass PostList(ListView):\n model=Post\n paginate_by = 2\n template_name = 'post_list.html'\n\n\n\ndef post_detail(req,year,month,day,post):\n post=get_object_or_404(Post,slug=post,status='published',publish__day=day,publish__year=year,publish__month=month)\n comments=post.comments.filter(active=True) # comments is related name\n csubmit=False\n if req.method == 'POST':\n form=CommentForm(req.POST)\n if form.is_valid():\n new_comment=form.save(commit=False)\n new_comment.post=post\n new_comment.save()\n csubmit=True\n else:\n form=CommentForm()\n return render(req,'post_detail.html',{'post':post,'form':form,'csubmit':csubmit,'comments':comments})\n\n\n\ndef email_send(req,id):\n post=get_object_or_404(Post,id=id,status='published')\n form=EmailSendForm()\n sent=False\n if req.method=='POST':\n form=EmailSendForm(req.POST)\n if form.is_valid():\n to = form.cleaned_data['to']\n name=form.cleaned_data['name']\n post_url=req.build_absolute_uri(post.get_absolute_url())\n comment=form.cleaned_data['comment']\n subject=name,' Recommend you ',post.title,comment,post_url\n send_mail(subject,'message','[email protected]',(to,))\n sent=True\n\n return render(req,'sharebymail.html',{'form':form,'post':post,'sent':sent})\n\n\n\n" }, { "alpha_fraction": 0.560606062412262, "alphanum_fraction": 0.5707070827484131, "avg_line_length": 19.517240524291992, "blob_id": "6b13fc3667c494489a556426d41a600d5a5c5479", "content_id": "005327530a0d5d6fd62a873ebf6f65dc810a6b4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 594, "license_type": "no_license", "max_line_length": 149, "num_lines": 29, "path": "/templates/base.html", "repo_name": "sumitjat/blog_project", "src_encoding": "UTF-8", "text": "{% load static %}\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\" integrity=\"sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh\" crossorigin=\"anonymous\">\n\n <link rel=\"stylesheet\" href=\"{% static \"css/blog.css\" %}\">\n <title>{% block title_block %}{% endblock %}</title>\n</head>\n<body>\n\n <div class=\"content\">\n\n {% block content %}\n\n {% endblock %}\n\n </div>\n\n <div class=\"sidebar\">\n\n <h2>Sumit's Blog</h2>\n <p>Here are you updations ..... </p>\n\n </div>\n\n</body>\n</html>" } ]
4
cash2one/weixin-3
https://github.com/cash2one/weixin-3
8bc64213985227747b90b8da1dfbf01540f9fa8e
d235b3b6d64ba94519977645b991bd574598fad4
f6529e074d35bc2470cf8aa7dc97c5525bb38a75
refs/heads/master
2021-01-19T10:14:36.952637
2017-03-01T03:13:31
2017-03-01T03:13:31
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.45507538318634033, "alphanum_fraction": 0.49929937720298767, "avg_line_length": 51.77219009399414, "blob_id": "7d46f19c0e3dd24c0c5cea7ca958eadcfde397fc", "content_id": "e4aee3200f04714a6541672d128f874b4e97cea5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18091, "license_type": "no_license", "max_line_length": 479, "num_lines": 338, "path": "/handle_url1.py", "repo_name": "cash2one/weixin-3", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport requests,json,MySQLdb,time,HTMLParser,sys,random,urlparse,logging,datetime\nfrom pyquery import PyQuery as pq\nreload(sys) \nsys.setdefaultencoding('utf8') \n\n# 增加重试连接次数\nrequests.adapters.DEFAULT_RETRIES = 5\n# 关闭多余的连接\ns = requests.session()\ns.keep_alive = False\n\n# 记录日志\nlog_file = time.strftime('%Y-%m-%d')+'-log.log'\nlogging.basicConfig(filename=log_file,level=logging.DEBUG)\n\n# 时间 昨天晚上6点到今天晚上6点之间24小时的数据 每天晚上6点之后执行就可以\n# 昨天6点\nnow_time = datetime.datetime.now()\nyes_time = now_time + datetime.timedelta(days=-1)\nyes_six_time = yes_time.strftime(\"%Y-%m-%d 18:00:00\")\nyes_timearray = time.strptime(yes_six_time, \"%Y-%m-%d %H:%M:%S\")\nyes_timestamp = int(time.mktime(yes_timearray))\n\n# 今天6点\nnow_time = datetime.datetime.now()\ntoday_six_time = now_time.strftime(\"%Y-%m-%d 18:00:00\")\ntoday_timearray = time.strptime(today_six_time, \"%Y-%m-%d %H:%M:%S\")\ntoday_timestamp = int(time.mktime(today_timearray))\n\n\nhtml = HTMLParser.HTMLParser()\n# 数据库设置\ntry:\n conn = MySQLdb.Connect(host='192.168.234.128', user='root', passwd='123456',db='weixin')\nexcept Exception,e:\n print e\n\nconn.set_character_set('utf8')\ncursor = conn.cursor()\ncursor.execute('SET NAMES utf8;')\ncursor.execute('SET character_set_connection=utf8;')\ncursor.execute('SET CHARACTER SET utf8mb4;')\n\n# headers设置 \nuserAgents = [{'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0'},\n {\"User-Agent\": \"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1) Gecko/20090624 Firefox/3.5\"},\n {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'},\n {\"User-Agent\":\"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1\"},\n {\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11\"},\n {\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER\"},\n {\"User-Agent\":\"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)\"},\n {\"User-Agent\":\"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)\"},\n {\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER\"},\n {\"User-Agent\":\"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)\"},\n {\"User-Agent\":\"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)\"},\n {\"User-Agent\":\"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)\"},\n {\"User-Agent\":\"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)\"},\n {\"User-Agent\":\"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1\"},\n {\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1\"},\n {\"User-Agent\":\"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0\"},\n {\"User-Agent\":\"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0)\"},\n {\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:16.0) Gecko/20121026 Firefox/16.0\"},\n {\"User-Agent\":\"Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5\"},\n {\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre\"},\n {\"User-Agent\":\"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0\"},\n {\"User-Agent\":\"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15\"},\n {\"User-Agent\":\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11\"},\n {\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11\"},\n {\"User-Agent\":\"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133\"},\n {\"User-Agent\":\"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)\"},\n {\"User-Agent\":\"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)\"},\n {\"User-Agent\":\"Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10\"}, \n {\"User-Agent\":\"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)\"},\n {\"User-Agent\":\"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)\"},\n {\"User-Agent\":\"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)\"},\n {\"User-Agent\":\"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)\"},\n {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101\"},\n {\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1\"}]\n\ndef getRandomHeaders():\n headers = {}\n headers[\"User-Agent\"] = random.choice(userAgents)[\"User-Agent\"]\n headers[\"Accept-Language\"] = \"zh-cn,zh;q=0.8;\"\n headers[\"Cache-Control\"] = \"max-age=0\"\n headers[\"Accept\"] = \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\"\n return headers\n\n# 代理服务器\nproxyHost = \"proxy.abuyun.com\"\nproxyPort = \"9020\"\n\n# 代理隧道验证信息\nproxyUser = \"\"\nproxyPass = \"\"\n\nproxyMeta = \"http://%(user)s:%(pass)s@%(host)s:%(port)s\" % {\n \"host\" : proxyHost,\n \"port\" : proxyPort,\n \"user\" : proxyUser,\n \"pass\" : proxyPass,\n}\n\nproxies = {\n \"http\" : proxyMeta,\n \"https\" : proxyMeta,\n}\n\n\nwhile True:\n # 每次拿一个\n sql = \"SELECT `id`, `url` FROM `weixin_url` limit 1\"\n cursor.execute(sql)\n result = cursor.fetchone()\n conn.commit()\n\n if result == None:\n print 'sleep 1 seconds,wait data......'\n logging.debug('sleep 1 seconds,wait data......')\n time.sleep(1)\n continue\n else:\n print 'running......'\n logging.debug('running......')\n int_id = result[0]\n print int_id\n logging.debug(int_id)\n # 加上UA\n headers = getRandomHeaders()\n weixin_url = \"http://\"+result[1]\n c = s.get(weixin_url, headers=headers, proxies=proxies) \n cookie = c.cookies\n r = s.get(weixin_url+'&f=json', headers=headers, cookies=cookie, proxies=proxies)\n #dict_s = json.loads(r.text)\n try:\n dict_s = r.json()\n except Exception:\n print 'no json'\n print r.content\n logging.debug('no json')\n logging.debug(r.content)\n continue\n \n # no content,sleep \n if 'general_msg_list' not in dict_s:\n print dict_s\n logging.debug(dict_s)\n if dict_s['ret'] == -3:\n # 删除这条记录\n delete_sql = \"DELETE FROM `weixin_url` WHERE `id`=(%d) \" % (int_id)\n cursor.execute(delete_sql)\n conn.commit()\n continue\n elif dict_s['ret'] == -6:\n print 'sleep 60 seconds......'\n logging.debug('sleep 60 seconds......')\n time.sleep(60)\n continue\n\n json_d = dict_s['general_msg_list']\n \n # get biz\n biz_code = dict_s['bizuin_code']\n # get account\n #select_account_sql = \"SELECT `aw_weixin_id` FROM `wyx_account_weixin_base` WHERE aw_weixin_biz=('%s')\" % (biz_code)\n #cursor.execute(select_account_sql)\n #conn.commit()\n #account_rs = cursor.fetchone()\n #account = account_rs[0]\n\n if json_d.strip() == '':\n print 'empty, next'\n logging.debug('empty, next')\n # 删除这条记录\n del_sql = \"DELETE FROM `weixin_url` WHERE `id`=(%d) \" % (int_id)\n cursor.execute(del_sql)\n conn.commit()\n continue\n else:\n dict_l = json.loads(json_d)\n\n list_x = dict_l['list']\n \n if len(list_x) == 0:\n print 'list is empty,next'\n logging.debug('list is empty,next')\n # 删除\n sql_of_delete = \"DELETE FROM `weixin_url` WHERE `id`=(%d) \" % (int_id)\n cursor.execute(sql_of_delete)\n conn.commit()\n continue\n for dict_x in list_x:\n dict_comm_msg_info = dict_x['comm_msg_info']\n datetime = dict_comm_msg_info['datetime']\n \n # 表名手写\n table_name = 'wyx_weixin_article'\n if datetime <= 1488297600: # 小于这个月\n table_name = table_name + '_201702'\n else: \n table_name = table_name + '_201703'\n \n if datetime >= yes_timestamp and datetime < today_timestamp: # 昨天晚上6点和今天晚上6点之间24小时的数据\n if 'app_msg_ext_info' in dict_x:\n dict_c = dict_x['app_msg_ext_info']\n\n title = dict_c['title']\n title_json = MySQLdb.escape_string(json.dumps(dict_c['title']))\n author = dict_c['author']\n digest = dict_c['digest']\n digest_json = MySQLdb.escape_string(json.dumps(dict_c['digest']))\n content_url = html.unescape(dict_c['content_url'])\n #source_url = html.unescape(dict_c['source_url'])\n #cover = dict_c['cover']\n now = int(time.time())\n \n rich_media_content = None\n if content_url != '':\n try:\n content_html = s.get(content_url, headers=headers, proxies=proxies)\n d = pq(content_html.content)\n rich_media_content = d('.rich_media_content').html()\n except Exception, e:\n print e\n print 'd has problem'\n logging.debug('d has problem')\n logging.debug(content_url)\n logging.debug(e)\n logging.debug(content_html.content)\n\n \n if rich_media_content == None:\n print 'first no rich_media_content'\n logging.debug('first no rich_media_content')\n logging.debug(content_html.content)\n try:\n article_content = MySQLdb.escape_string(d('.text_area').html().strip())\n except Exception as e:\n print e\n logging.debug(e)\n article_content = 'wrong'\n else:\n article_content = MySQLdb.escape_string(d('.rich_media_content').html().strip())\n\n url_result = urlparse.urlparse(content_url) \n url_params = urlparse.parse_qs(url_result.query,True)\n\n idx_list = url_params['idx'] \n sn_list = url_params['sn'] \n idx = int(idx_list[0])\n sn = str(sn_list[0])\n\n select_sn_sql = \"SELECT `wa_id` FROM \" + table_name + \" WHERE `wa_article_sn`=('%s')\" % (sn)\n cursor.execute(select_sn_sql)\n conn.commit()\n sn_result = cursor.fetchone()\n\n if sn_result == None:\n insert_sql = \"INSERT INTO \" + table_name + \" (`wa_account_biz`, `wa_title`, `wa_title_json`, `wa_summary`, `wa_summary_json`, `wa_article_sn`, `wa_url`, `wa_idx`, `wa_public_time`, `wa_data_type`, `wa_collection_time`, `wa_content`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d, '%s')\" % (biz_code, title, title_json, digest, digest_json, sn, content_url, idx, datetime, 3, now, article_content)\n cursor.execute(insert_sql)\n conn.commit()\n print 'insert first success'\n logging.debug('insert first success')\n is_multi = dict_c['is_multi']\n\n if is_multi == 1: \n list_multi_app_msg_item = dict_c['multi_app_msg_item_list']\n for dict_i in list_multi_app_msg_item:\n str_title = dict_i['title']\n str_title_json = MySQLdb.escape_string(json.dumps(dict_i['title']))\n str_author = dict_i['author']\n str_digest = dict_i['digest']\n str_digest_json = MySQLdb.escape_string(json.dumps(dict_i['digest']))\n str_content_url = html.unescape(dict_i['content_url'])\n # str_source_url = html.unescape(dict_i['source_url'])\n # str_cover = dict_i['cover']\n int_now = int(time.time())\n \n str_content_html = s.get(str_content_url, headers=headers, proxies=proxies)\n try:\n p = pq(str_content_html.content)\n except Exception:\n print 'pq has problem'\n logging.debug('pq has problem')\n logging.debug(str_content_html.content)\n continue\n \n unicode_rich_media_content = p('.rich_media_content').html()\n if unicode_rich_media_content == None:\n print 'no rich_media_content'\n logging.debug('no rich_media_content')\n logging.debug(str_content_html.content)\n try:\n str_article_content = MySQLdb.escape_string(d('.text_area').html().strip())\n except Exception as e:\n print e\n logging.debug(e)\n str_article_content = 'wrong'\n else:\n str_article_content = MySQLdb.escape_string(unicode_rich_media_content.strip())\n \n str_url_result = urlparse.urlparse(str_content_url) \n str_url_params = urlparse.parse_qs(str_url_result.query,True)\n\n int_idx_list = str_url_params['idx']\n str_sn_list = str_url_params['sn']\n int_idx = int(int_idx_list[0])\n str_sn = str(str_sn_list[0])\n \n select_str_sn_sql = \"SELECT wa_id FROM \" + table_name + \" WHERE `wa_article_sn`=('%s')\" % (str_sn)\n cursor.execute(select_str_sn_sql)\n conn.commit()\n str_sn_result = cursor.fetchone()\n if str_sn_result == None:\n sql = \"INSERT INTO \" + table_name + \"(`wa_account_biz`, `wa_title`, `wa_title_json`, `wa_summary`, `wa_summary_json`, `wa_article_sn`, `wa_url`, `wa_idx`, `wa_public_time`, `wa_data_type`, `wa_collection_time`, `wa_content`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d, '%s')\" % (biz_code, str_title, str_title_json, str_digest, str_digest_json, str_sn, str_content_url, int_idx, datetime, 3, int_now, str_article_content)\n cursor.execute(sql)\n conn.commit()\n print 'other insert success'\n logging.debug('other insert success')\n else:\n print 'single msg'\n logging.debug('single msg')\n continue\n else:\n print 'no content,next'\n logging.debug('no content,next')\n continue\n else:\n print 'time is out of range'\n logging.debug('time is out of range')\n continue\n del_sql = \"DELETE FROM `weixin_url` WHERE `id` = (%d)\" % (int_id)\n cursor.execute(del_sql)\n conn.commit()\n print 'success'\n logging.debug('success')\n\n\n\n\n" } ]
1
jhssyb/PINN--NUS
https://github.com/jhssyb/PINN--NUS
f43514b186ed01068f0157fef4f96cf5b8597fdb
16571babdb9e8d5936c30d273cdbec858ffbd1f9
1145a8c44b54089fc9cd10eb8726f989c773a4bb
refs/heads/master
2020-08-27T00:01:21.754978
2019-10-24T01:51:15
2019-10-24T01:51:15
217,188,307
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.29654738306999207, "alphanum_fraction": 0.4179535508155823, "avg_line_length": 25.8426570892334, "blob_id": "ef36565e62fa4eacc88d42a9f7bf94fcfb242035", "content_id": "6d47a1223c1ed8739a09d938d2e2f739d28f06ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7965, "license_type": "no_license", "max_line_length": 155, "num_lines": 286, "path": "/1D-Nozzle/NN/888.c", "repo_name": "jhssyb/PINN--NUS", "src_encoding": "UTF-8", "text": "#include<stdio.h>\r\n#include<stdlib.h>\r\n#include<math.h>\r\n\r\n\r\nvoid main()\r\n{\r\n\r\nFILE *datafile; \r\nFILE *rssfile;\r\nint i,j,k,q;\r\nfloat U[110][3],Fp[110][3],Fn[110][3],F[110][3],M[110],L1[110],L2[110],L3[110],wp[110],wn[110],z[103];\r\nfloat p_abs[103],u_abs[103],rho[110],rho_abs[110],p[110],u[110],a[110],A[110],S[110],rold[103],rn[103],rss1[110],rss2=0,rss3,pmax=0,rhomax=0,umax=0,Mmax=0;\r\nfloat u_plus_a=0,dt,dx=0.01,g,R,al,pl,ul,rhol,Ml,ptl,pratio,R2,R3,R1;\r\n\r\nfloat frac=0.0;\r\n\r\nchar filename[100]=\"cdnozzle.txt\"; \r\nchar filename1[100] =\"residue.txt\";\r\n\r\ndatafile=fopen(filename,\"w\");\r\n\r\nfor (frac=0.3; frac<=0.9; frac += 0.03){\r\n\r\nrssfile=fopen(filename1,\"w\");\r\n\r\ng=1.4,R=287.16; \r\n\r\nrhol=1,ul=0.1,pl=1,al=sqrt(g*1/rhol),Ml=ul/al,ptl=1.005; // values are to be changed\r\n\r\nR2=ul+(5*al);\r\n\r\n//Intial Condition:\r\nfor(i=1;i<=100;i++)\r\n{\r\n\r\nA[i]=1+2.2*pow(((3*dx*i)-1.5),2);\r\n\r\nrho[i]=1;\r\nu[i]=0.1;\r\np[i]=1;\r\na[i]=sqrt(g*p[i]/rho[i]);\r\nM[i]=u[i]/a[i];\r\n\r\nrold[i]=rho[i];\r\nU[i][0]=A[i]*rho[i];\r\nU[i][1]=A[i]*rho[i]*u[i];\r\nU[i][2]=A[i]*((p[i]/(g-1))+(0.5*rho[i]*u[i]*u[i]));\r\n\r\nL1[i]=u[i];\r\nL2[i]=u[i]+a[i];\r\nL3[i]=u[i]-a[i];\r\nwp[i]=(3-g)*a[i]*a[i]*0.5*L2[i]/(g-1); \r\nwn[i]=(3-g)*a[i]*a[i]*0.5*L3[i]/(g-1);\r\n\r\n\r\n\tFp[i][0]=A[i]*(rho[i]*(g-1)*(L1[i]/g)+(rho[i]*L2[i]*0.5/g)); \r\n Fp[i][1]=A[i]*(rho[i]*L1[i]*L1[i]*((g-1)/g)+(rho[i]*L2[i]*L2[i]*0.5/g)); \r\n Fp[i][2]=A[i]*(rho[i]*L1[i]*L1[i]*L1[i]*((g-1)/g)+(rho[i]*L2[i]*L2[i]*L2[i]*0.25/g)+(rho[i]*0.5*wp[i]/g)); \r\n\tFn[i][0]=A[i]*(rho[i]*L3[i]*.5/g);\r\n Fn[i][1]=A[i]*(rho[i]*L3[i]*L3[i]*.5/g);\r\n Fn[i][2]=A[i]*(rho[i]*L3[i]*L3[i]*L3[i]*(0.25/g)+(rho[i]*0.5*wn[i]/g));\r\n F[i][0]=A[i]*rho[i]*u[i];\r\n\tF[i][1]=A[i]*(rho[i]*u[i]*u[i]+p[i]);\r\n\tF[i][2]=A[i]*((p[i]*(g/(g-1))+0.5*rho[i]*u[i]*u[i])*u[i]);\r\n\r\n\tdt=0.9*0.01/(u[1]+a[1]);\r\n\t\r\n\t\r\n\r\n // printf(\"%d\\t%f\\t%f\\t%f\\t%f\\t%f\\n\",i,dt,dx,a[i],S[i],M[i]); \r\n\r\n //printf(\"%d\\t%f\\t%f\\t%f\\n\",i,U[i][0],U[i][1],U[i][2]);\r\n //printf(\"%d\\t%f\\n\",i,dt);\r\n}\r\n \r\n\r\nrss3=1;\r\n\r\n//calculation:\r\nfor(j=1;rss3>=0.00001;j++)\r\n {\r\n\r\nrss2=0;\r\n\r\nA[0]=A[1];\r\nA[101]=A[100];\r\n\r\nR3=u[1]-(2*a[1]/(g-1));\r\n\r\nu[0]=0.5*(R2+R3);\r\na[0]=0.1*(R2-R3);\r\nM[0]=u[0]/a[0];\r\npratio=pow((1+(0.2*M[0]*M[0])),3.5);\r\np[0]=ptl/pratio;\r\nrho[0]=g*p[0]/(a[0]*a[0]);\r\n\r\np[101]=frac*ptl;\r\nrho[101]=rho[100]*pow((p[101]/p[100]),0.714);\r\na[101]=sqrt(g*p[101]/rho[101]);\r\nu[101]=u[100]+5*(a[100]-a[101]);\r\n\r\n\r\n//printf(\"%d\\t%f\\t%f\\t%f\\t%f\\t%f\\n\",j,R2,R3,rho[101],a[0],M[0]);\r\n\r\nL1[0]=u[0];\r\nL2[0]=u[0]+a[0];\r\nL3[0]=u[0]-a[0];\r\nwp[0]=(3-g)*a[0]*a[0]*0.5*L2[0]/(g-1); \r\nwn[0]=(3-g)*a[0]*a[0]*0.5*L3[0]/(g-1);\r\n\r\n\r\n\tFp[0][0]=A[0]*(rho[0]*(g-1)*(L1[0]/g)+(rho[0]*L2[0]*0.5/g)); \r\n Fp[0][1]=A[0]*(rho[0]*L1[0]*L1[0]*((g-1)/g)+(rho[0]*L2[0]*L2[0]*0.5/g)); \r\n Fp[0][2]=A[0]*(rho[0]*L1[0]*L1[0]*L1[0]*((g-1)/g)+(rho[0]*L2[0]*L2[0]*L2[0]*0.25/g)+(rho[0]*0.5*wp[0]/g)); \r\n\tFn[0][0]=A[0]*(rho[0]*L3[0]*.5/g);\r\n Fn[0][1]=A[0]*(rho[0]*L3[0]*L3[0]*.5/g);\r\n Fn[0][2]=A[0]*(rho[0]*L3[0]*L3[0]*L3[0]*(0.25/g)+(rho[0]*0.5*wn[0]/g));\r\n F[0][0]=A[0]*rho[0]*u[0];\r\n\tF[0][1]=A[0]*(rho[0]*u[0]*u[0]+p[0]);\r\n\tF[0][2]=A[0]*((p[0]*(g/(g-1))+0.5*rho[0]*u[0]*u[0])*u[0]);\r\n\r\n\r\nL1[101]=u[101];\r\nL2[101]=u[101]+a[101];\r\nL3[101]=u[101]-a[101];\r\nwp[101]=(3-g)*a[101]*a[101]*0.5*L2[101]/(g-1); \r\nwn[101]=(3-g)*a[101]*a[101]*0.5*L3[101]/(g-1);\r\n\r\n\r\n\tFp[101][0]=A[101]*(rho[101]*(g-1)*(L1[101]/g)+(rho[101]*L2[101]*0.5/g)); \r\n Fp[101][1]=A[101]*(rho[101]*L1[101]*L1[101]*((g-1)/g)+(rho[101]*L2[101]*L2[101]*0.5/g)); \r\n Fp[101][2]=A[101]*(rho[101]*L1[101]*L1[101]*L1[101]*((g-1)/g)+(rho[101]*L2[101]*L2[101]*L2[101]*0.25/g)+(rho[101]*0.5*wp[101]/g)); \r\n\tFn[101][0]=A[101]*(rho[101]*L3[101]*.5/g);\r\n Fn[101][1]=A[101]*(rho[101]*L3[101]*L3[101]*.5/g);\r\n Fn[101][2]=A[101]*(rho[101]*L3[101]*L3[101]*L3[101]*(0.25/g)+(rho[101]*0.5*wn[101]/g));\r\n F[101][0]=A[101]*rho[101]*u[101];\r\n\tF[101][1]=A[101]*(rho[101]*u[101]*u[101]+p[101]);\r\n\tF[101][2]=A[101]*((p[101]*(g/(g-1))+0.5*rho[101]*u[101]*u[101])*u[101]);\r\n\r\n\r\n\r\n\t//printf(\"%d\\t%f\\t%f\\t%f\\t%f\\t%f\\n\",i,u[101],p[101],rho[101],a[101],T[101]);\r\n \r\n\r\n\r\nfor(i=1;i<=100;i++)\r\n {\r\n \tif(M[i]>=-1 && M[i]<=1) // Mach no condition\r\n \t{ \r\n\t \t \r\n \tU[i][0]=U[i][0]-((dt/dx)*(Fp[i][0]-Fp[i-1][0]))-((dt/dx)*(Fn[i+1][0]-Fn[i][0]));\r\n \tU[i][1]=U[i][1]-((dt/dx)*(Fp[i][1]-Fp[i-1][1]))-((dt/dx)*(Fn[i+1][1]-Fn[i][1]))+(dt/dx)*p[i]*0.5*(A[i+1]-A[i-1]);\r\n \tU[i][2]=U[i][2]-((dt/dx)*(Fp[i][2]-Fp[i-1][2]))-((dt/dx)*(Fn[i+1][2]-Fn[i][2]));\r\n\t//printf(\"%d\\t%f\\t%f\\t%f\\n\",i,U[i][0],U[i][1],U[i][2]);\r\n \t}\r\n\r\n else if(M[i]<-1) \r\n {\r\n\tU[i][0]=U[i][0]-((dt/dx)*(F[i+1][0]-F[i][0]));\r\n \tU[i][1]=U[i][1]-((dt/dx)*(F[i+1][1]-F[i][1]))+(dt/dx)*p[i]*0.5*(A[i+1]-A[i-1]);\r\n \tU[i][2]=U[i][2]-((dt/dx)*(F[i+1][2]-F[i][2]));\r\n\t}\r\n\r\n \r\n\t else if(M[i]>1) \r\n {\r\n\tU[i][0]=U[i][0]-((dt/dx)*(F[i][0]-F[i-1][0]));\r\n \tU[i][1]=U[i][1]-((dt/dx)*(F[i][1]-F[i-1][1]))+(dt/dx)*p[i]*0.5*(A[i+1]-A[i-1]);\r\n \tU[i][2]=U[i][2]-((dt/dx)*(F[i][2]-F[i-1][2]));\r\n\t}\r\n\r\n\t\r\n\r\n \t\r\n}// i loop\t\t\t\t\t\t\t\t\t\t\t\t\r\n \r\n \t// updating...\r\n\r\n\tfor(i=1;i<=100;i++)\r\n {\r\n\r\n\tU[i][0]=U[i][0]/A[i];\r\n\tU[i][1]=U[i][1]/A[i];\r\n\tU[i][2]=U[i][2]/A[i];\r\n\r\n//printf(\"%d\\t%f\\t%f\\t%f\\n\",i,U[i][0],U[i][1],U[i][2]);\r\n\r\n\trho[i]=U[i][0];\r\n\t\r\n \tu[i]=U[i][1]/U[i][0];\r\n\tp[i]=(U[i][2]-(U[i][1]*U[i][1]*0.5/U[i][0]))*(g-1);\r\n \tp_abs[i]=fabs(p[i]);\r\n\trho_abs[i]=fabs(rho[i]);\r\n\tu_abs[i]=fabs(u[i]);\r\n\r\n\t\r\n\trn[i]=rho[i];\r\n\r\n \ta[i]=sqrt(g*(p_abs[i])/(rho_abs[i]));\r\n \tL1[i]=u[i];\r\n \tL2[i]=u[i]+a[i];\r\n \tL3[i]=u[i]-a[i];\r\n \twp[i]=(3-g)*a[i]*a[i]*0.5*L2[i]/(g-1);\r\n \twn[i]=(3-g)*a[i]*a[i]*0.5*L3[i]/(g-1);\r\n \tM[i]=u[i]/a[i]; \r\n \t//printf(\"%d\\t%f\\t%f\\t%f\\t%f\\t%f\\n\",i,dt,M[i],rho[i],u[i],p[i]);\r\n \tFp[i][0]=A[i]*(rho[i]*(g-1)*(L1[i]/g)+(rho[i]*L2[i]*0.5/g));\r\n \tFp[i][1]=A[i]*(rho[i]*L1[i]*L1[i]*((g-1)/g)+(rho[i]*L2[i]*L2[i]*0.5/g));\r\n \tFp[i][2]=A[i]*(rho[i]*L1[i]*L1[i]*L1[i]*((g-1)/g)+(rho[i]*L2[i]*L2[i]*L2[i]*0.25/g)+(rho[i]*0.5*wp[i]/g));\r\n \tFn[i][0]=A[i]*(rho[i]*L3[i]*0.5/g);\r\n \tFn[i][1]=A[i]*(rho[i]*L3[i]*L3[i]*0.5/g);\r\n \tFn[i][2]=A[i]*(rho[i]*L3[i]*L3[i]*L3[i]*(0.25/g)+(rho[i]*0.5*wn[i]/g));\r\n\r\n\tF[i][0]=A[i]*rho[i]*u[i];\r\n\tF[i][1]=A[i]*(rho[i]*u[i]*u[i]+p[i]);\r\n\tF[i][2]=A[i]*((p[i]*(g/(g-1))+0.5*rho[i]*u[i]*u[i])*u[i]);\r\n \r\n\t\r\n z[i]=u[i]+a[i];\r\n\r\n \tU[i][0]=U[i][0]*A[i];\r\n\tU[i][1]=U[i][1]*A[i];\r\n\tU[i][2]=U[i][2]*A[i];\r\n\r\n \t//printf(\"%d\\t%f\\t%f\\t%f\\n\",i,U[i][0],U[i][1],U[i][2]);\r\n\r\n\r\n // finding dt global...\r\n \t\tif(u_plus_a<(z[i]))\r\n\t \t {\r\n \t u_plus_a=z[i];\r\n \t }\r\n\t\tdt=0.9*0.01/u_plus_a;\r\n\r\n\r\n\t// Residue calculation\r\n\r\n rss1[i]=((rn[i]-rold[i])/rold[i])*((rn[i]-rold[i])/rold[i]);\r\n\r\n rss2=rss2+rss1[i];\r\n\t\r\n\trold[i]=rn[i];\r\n \r\n \r\n\t}// update loop\r\n\r\n\r\n //printf(\"%d\\t%f\\n\",j,rss3);\r\n \t\r\n rss3=sqrt(rss2/100);\r\n\r\n fprintf(rssfile,\"%d\\t%f\\n\",j,rss3);\r\n \r\n \r\n}// j loop\r\n\r\nfclose(rssfile);\r\n \r\n\r\n //opening a file named \"cdnozzle\" on home folder:\r\n\r\n \r\n \r\n// printf(\"i\\tp[i]\\t\\trho[i]\\t\\tu[i]\\t\\tM[i]\\n\");\r\n\r\nfor (i=1;i<=100;i++)\r\n {\r\n// printf(\"%d\\t%f\\t%f\\t%f\\t%f\\n\",i,p[i],rho[i],u[i],M[i]);\r\n fprintf(datafile,\"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\",i/1.0, frac, p[i], U[i][0], U[i][1], U[i][2], rho[i], u[i], U[i][2]/U[i][0]);\r\n } \r\n \r\n};\r\n\r\nfclose(datafile);\r\n\r\n//FILE *plot = popen(\"gnuplot -persist\",\"w\");\r\n//fprintf(plot, \"plot 'cdnozzle.txt' using 1:4 title 'rho_S' with lines \\n\");\r\n//close(plot);\r\n/*\r\nFILE *plot1 = popen(\"gnuplot -persist\",\"w\");\r\n//fprintf(plot1, \"plot 'residue.txt' using 1:2 title 'residue' with lines\\n\");\r\n//close(plot1);\r\n*/\r\n\r\n} // End...\r\n\r\n" }, { "alpha_fraction": 0.49935752153396606, "alphanum_fraction": 0.529208242893219, "avg_line_length": 37.47148132324219, "blob_id": "0ee254544bf87b372378669548f4aa9701f46169", "content_id": "57578361e3cb57ac357bb5ffe21d50d712903b7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10117, "license_type": "no_license", "max_line_length": 119, "num_lines": 263, "path": "/1D-Nozzle/NN/NN1.py", "repo_name": "jhssyb/PINN--NUS", "src_encoding": "UTF-8", "text": "\"\"\"\n@author: Maziar Raissi\n\"\"\"\n\nimport sys\nsys.path.insert(0, '../../Utilities/')\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io\nfrom scipy.interpolate import griddata\nimport time\nfrom itertools import product, combinations\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\n#from plotting import newfig, savefig\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport matplotlib.gridspec as gridspec\n\nnp.random.seed(1234)\ntf.set_random_seed(1234)\n\nclass NN:\n # Initialize the class\n def __init__(self, P_back, x, P, U1, U2, U3, layers):\n \n X = np.concatenate([P_back, x], 1)\n \n self.lb = X.min(0)\n self.ub = X.max(0)\n self.X = X\n self.P_back = P_back\n self.x = x\n self.P = P\n self.U1 = U1\n self.U2 = U2\n self.U3 = U3\n \n self.layers = layers\n \n # Initialize NN\n self.weights, self.biases = self.initialize_NN(layers) \n \n # tf placeholders and graph\n self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,\n log_device_placement=True))\n \n self.P_back_tf = tf.placeholder(tf.float32, shape=[None, self.P_back.shape[1]])\n self.x_tf = tf.placeholder(tf.float32, shape=[None, self.x.shape[1]])\n self.P_tf = tf.placeholder(tf.float32, shape=[None, self.P.shape[1]])\n self.U1_tf = tf.placeholder(tf.float32, shape=[None, self.U1.shape[1]])\n self.U2_tf = tf.placeholder(tf.float32, shape=[None, self.U2.shape[1]])\n self.U3_tf = tf.placeholder(tf.float32, shape=[None, self.U3.shape[1]])\n \n self.P_pred, self.U1_pred, self.U2_pred, self.U3_pred, self.mass_flow_grad_pred, \\\n self.momentum_grad_pred, self.energy_grad_pred = self.net_NS(self.P_back_tf, self.x_tf)\n self.state_eq = self.P_pred - self.P_tf\n\n w = 40\n self.loss = tf.reduce_sum(tf.square(self.P_tf - self.P_pred)) + \\\n tf.reduce_sum(tf.square(self.U1_tf - self.U1_pred)) + \\\n tf.reduce_sum(tf.square(self.U2_tf - self.U2_pred)) + \\\n tf.reduce_sum(tf.square(self.U3_tf - self.U3_pred)) + \\\n w*tf.reduce_sum(tf.square(self.mass_flow_grad_pred)) + \\\n w*tf.reduce_sum(tf.square(self.energy_grad_pred)) + \\\n w*tf.reduce_sum(tf.square(self.momentum_grad_pred)) + \\\n w*tf.reduce_sum(tf.square(self.state_eq))\n \n self.optimizer = tf.contrib.opt.ScipyOptimizerInterface(self.loss, \n method = 'L-BFGS-B', \n options = {'maxiter': 15000,\n 'maxfun': 15000,\n 'maxcor': 50,\n 'maxls': 50,\n 'ftol' : 1.0 * np.finfo(float).eps}) \n \n self.optimizer_Adam = tf.train.AdamOptimizer()\n self.train_op_Adam = self.optimizer_Adam.minimize(self.loss) \n \n init = tf.global_variables_initializer()\n self.sess.run(init)\n\n def initialize_NN(self, layers): \n weights = []\n biases = []\n num_layers = len(layers) \n for l in range(0,num_layers-1):\n W = self.xavier_init(size=[layers[l], layers[l+1]])\n b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32)\n weights.append(W)\n biases.append(b) \n return weights, biases\n \n def xavier_init(self, size):\n in_dim = size[0]\n out_dim = size[1] \n xavier_stddev = np.sqrt(2/(in_dim + out_dim))\n return tf.Variable(tf.truncated_normal([in_dim, out_dim], stddev=xavier_stddev), dtype=tf.float32)\n # neural operation for output\n def neural_net(self, X, weights, biases):\n num_layers = len(weights) + 1\n H = 2.0*(X - self.lb)/(self.ub - self.lb) - 1.0\n for l in range(0,num_layers-2):\n W = weights[l]\n b = biases[l]\n H = tf.tanh(tf.add(tf.matmul(H, W), b))\n W = weights[-1]\n b = biases[-1]\n Y = tf.add(tf.matmul(H, W), b)\n return Y\n \n def net_NS(self, P_back, x):\n P_U1_U2_U3 = self.neural_net(tf.concat([P_back, x], 1), self.weights, self.biases)\n P = P_U1_U2_U3[:,0:1]\n U1 = P_U1_U2_U3[:,1:2]\n U2 = P_U1_U2_U3[:,2:3]\n U3 = P_U1_U2_U3[:,3:4]\n\n # autodiff gradient #1\n mass_flow_grad = tf.gradients(U2, x)[0]\n # autodiff gradient #2\n S = 1 + 2.2*(x-1.5)*(x-1.5)\n momentum_grad = tf.add(tf.gradients(U2*U2/U1 + P*S, x)[0], - tf.multiply(tf.gradients(S, x)[0], P))\n # autodiff gradient #3\n rho_u_E_S = tf.divide(tf.multiply(U2, U3), U1)\n p_u_S = tf.divide(tf.multiply(tf.multiply(P, S), U2), U1)\n net_energy_expression = tf.add(rho_u_E_S, p_u_S)\n energy_grad = tf.gradients(net_energy_expression, x)[0]\n\n return P, U1, U2, U3, mass_flow_grad, momentum_grad, energy_grad\n \n def callback(self, loss):\n print('Loss: %.3e' % (loss))\n \n def train(self, nIter): \n\n tf_dict = {self.P_back_tf: self.P_back, self.x_tf: self.x,\n self.P_tf: self.P, self.U1_tf: self.U1, self.U2_tf: self.U2, self.U3_tf: self.U3\n }\n \n start_time = time.time()\n for it in range(nIter):\n self.sess.run(self.train_op_Adam, tf_dict)\n \n # Print\n if it % 10 == 0:\n elapsed = time.time() - start_time\n loss_value = self.sess.run(self.loss, tf_dict)\n \n print('It: %d, Loss: %.3e, Time: %.2f' % \n (it, loss_value, elapsed))\n start_time = time.time()\n \n self.optimizer.minimize(self.sess,\n feed_dict = tf_dict,\n fetches = [self.loss],\n loss_callback = self.callback)\n \n \n def predict(self, P_back_test, x_test):\n tf_dict = {self.P_back_tf: P_back_test, self.x_tf: x_test}\n P_test = self.sess.run(self.P_pred, tf_dict)\n U1_test = self.sess.run(self.U1_pred, tf_dict)\n U2_test = self.sess.run(self.U2_pred, tf_dict)\n U3_test = self.sess.run(self.U3_pred, tf_dict)\n return P_test, U1_test, U2_test, U3_test\n\nif __name__ == \"__main__\":\n \n layers = [2, 10, 25, 50, 25, 15, 4]\n \n # Load Data\n data = np.loadtxt('cdnozzle.txt')\n\n N_train = int(0.8*data.shape[0])\n \n A = np.random.choice(range(data.shape[0]), size=(N_train,), replace=False)\n\n # x\n P_back_train = data[A,1:2].flatten()[:,None]\n x_train = data[A,0:1].flatten()[:,None]\n # y\n P_train = data[A,2:3].flatten()[:,None]\n U1_train = data[A,3:4].flatten()[:,None]\n U2_train = data[A,4:5].flatten()[:,None]\n U3_train = data[A,5:6].flatten()[:,None]\n\n # Training\n model = NN(P_back_train, x_train, P_train, U1_train, U2_train, U3_train, layers)\n model.train(1000)\n \n # Test Data\n data1 = data\n data1 = np.delete(data1, A, 0)\n\n # x\n P_back_test = data1[:,1:2].flatten()[:,None]\n x_test = data1[:,0:1].flatten()[:,None]\n # y\n P_test = data1[:,2:3].flatten()[:,None]\n U1_test = data1[:,3:4].flatten()[:,None]\n U2_test = data1[:,4:5].flatten()[:,None]\n U3_test = data1[:,5:6].flatten()[:,None]\n\n # Prediction\n P_pred, U1_pred, U2_pred, U3_pred = model.predict(P_back_test, x_test)\n \n # Error\n error_P = np.linalg.norm(P_test-P_pred,2)/np.linalg.norm(P_test,2)\n print(\"Test Error in P: \"+str(error_P))\n error_U1 = np.linalg.norm(U1_test-U1_pred,2)/np.linalg.norm(U1_test,2)\n print(\"Test Error in U1: \"+str(error_U1))\n error_U2 = np.linalg.norm(U2_test-U2_pred,2)/np.linalg.norm(U2_test,2)\n print(\"Test Error in U2: \"+str(error_U2))\n error_U3 = np.linalg.norm(U3_test-U3_pred,2)/np.linalg.norm(U3_test,2)\n print(\"Test Error in U3: \"+str(error_U3))\n\n #Plotting\n plt_l=700\n plt_u=800\n # x\n x_test_plt = data[plt_l:plt_u, 0:1].flatten()[:,None]\n P_back_test_plt = data[plt_l:plt_u, 1:2].flatten()[:,None]\n # y\n P_test_plt = data[plt_l:plt_u, 2:3].flatten()[:,None]\n U1_test_plt = data[plt_l:plt_u, 3:4].flatten()[:,None]\n U2_test_plt = data[plt_l:plt_u, 4:5].flatten()[:,None]\n U3_test_plt = data[plt_l:plt_u, 5:6].flatten()[:,None]\n # predict\n P_pred_plt, U1_pred_plt, U2_pred_plt, U3_pred_plt = model.predict(P_back_test_plt, x_test_plt)\n # plot P\n plt.plot(x_test_plt, P_pred_plt, 'ro', label='NN')\n plt.plot(x_test_plt, P_test_plt, 'g--', label='CFD')\n plt.legend()\n plt.title('Comparison of Neural Network and CFD')\n plt.xlabel('Length of nozzle')\n plt.ylabel('Pressure*')\n plt.show()\n # plot U1\n plt.plot(x_test_plt, U1_pred_plt, 'ro', label='NN')\n plt.plot(x_test_plt, U1_test_plt, 'g--', label='CFD')\n plt.legend()\n plt.title('Comparison of Neural Network and CFD')\n plt.xlabel('Length of nozzle')\n plt.ylabel('rho_S')\n plt.show()\n # plot U2\n plt.plot(x_test_plt, U2_pred_plt, 'ro', label='NN')\n plt.plot(x_test_plt, U2_test_plt, 'g--', label='CFD')\n plt.legend()\n plt.title('Comparison of Neural Network and CFD')\n plt.xlabel('Length of nozzle')\n plt.ylabel('rho_u_S')\n plt.show()\n # plot U3\n plt.plot(x_test_plt, U3_pred_plt, 'ro', label='NN')\n plt.plot(x_test_plt, U3_test_plt, 'g--', label='CFD')\n plt.legend()\n plt.title('Comparison of Neural Network and CFD')\n plt.xlabel('Length of nozzle')\n plt.ylabel('rho_E_S')\n plt.show()" }, { "alpha_fraction": 0.46077820658683777, "alphanum_fraction": 0.538521409034729, "avg_line_length": 44.25, "blob_id": "ab6449ee1fb11ce83dde2d841c3f1ed545eb5ced", "content_id": "ecc235112759847258129b83ab233d365f5a46ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12850, "license_type": "no_license", "max_line_length": 153, "num_lines": 284, "path": "/1D-Nozzle/JuPyter/NN2.py", "repo_name": "jhssyb/PINN--NUS", "src_encoding": "UTF-8", "text": "import sys\nsys.path.insert(0, '../../Utilities/')\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io\nfrom scipy.interpolate import griddata\nimport time\nfrom itertools import product, combinations\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\n#from plotting import newfig, savefig\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport matplotlib.gridspec as gridspec\n\nnp.random.seed(1234)\ntf.set_random_seed(1234)\n\nclass NN:\n # Initialize the class\n def __init__(self, P_back, x, P, rho, u, E, layers):\n \n X = np.concatenate([P_back, x], 1)\n \n self.lb = X.min(0)\n self.ub = X.max(0)\n self.X = X\n self.P_back = P_back\n self.x = x\n self.P = P\n self.rho = rho\n self.u = u\n self.E = E\n\n self.layers = layers\n \n # Initialize NN\n self.weights, self.biases = self.initialize_NN(layers) \n \n # tf placeholders and graph\n self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,\n log_device_placement=True))\n \n self.P_back_tf = tf.placeholder(tf.float32, shape=[None, self.P_back.shape[1]])\n self.x_tf = tf.placeholder(tf.float32, shape=[None, self.x.shape[1]])\n self.P_tf = tf.placeholder(tf.float32, shape=[None, self.P.shape[1]])\n self.rho_tf = tf.placeholder(tf.float32, shape=[None, self.rho.shape[1]])\n self.u_tf = tf.placeholder(tf.float32, shape=[None, self.u.shape[1]])\n self.E_tf = tf.placeholder(tf.float32, shape=[None, self.E.shape[1]])\n \n self.P_pred, self.rho_pred, self.u_pred, self.E_pred, self.e1, self.e2, self.e3= self.net_NS(self.P_back_tf, self.x_tf)\n\n # MSE Normalization\n P_norm = np.amax(P)\n rho_norm = np.amax(rho)\n u_norm = np.amax(u)\n E_norm = np.amax(E)\n S_norm = 5.95\n e1_norm = rho_norm*u_norm*S_norm\n e2_norm = P_norm*S_norm\n e3_norm = E_norm*rho_norm*u_norm*S_norm\n \n self.loss = tf.reduce_sum(tf.square(self.P_tf - self.P_pred))/(P_norm**2) + \\\n tf.reduce_sum(tf.square(self.rho_tf - self.rho_pred))/(rho_norm**2) + \\\n tf.reduce_sum(tf.square(self.u_tf - self.u_pred))/(u_norm**2) + \\\n tf.reduce_sum(tf.square(self.E_tf - self.E_pred))/(E_norm**2) + \\\n tf.reduce_sum(tf.square(self.e2))/(e2_norm**2) + \\\n tf.reduce_sum(tf.square(self.e3))/(e3_norm**2) + \\\n tf.reduce_sum(tf.square(self.e1))/(e1_norm**2)\n \n self.optimizer = tf.contrib.opt.ScipyOptimizerInterface(self.loss, \n method = 'L-BFGS-B', \n options = {'maxiter': 15000,\n 'maxfun': 15000,\n 'maxcor': 50,\n 'maxls': 50,\n 'ftol' : 1.0 * np.finfo(float).eps}) \n \n self.optimizer_Adam = tf.train.AdamOptimizer()\n self.train_op_Adam = self.optimizer_Adam.minimize(self.loss) \n \n init = tf.global_variables_initializer()\n self.sess.run(init)\n\n def initialize_NN(self, layers): \n weights = []\n biases = []\n num_layers = len(layers) \n for l in range(0,num_layers-1):\n W = self.xavier_init(size=[layers[l], layers[l+1]])\n b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32)\n weights.append(W)\n biases.append(b) \n return weights, biases\n \n def xavier_init(self, size):\n in_dim = size[0]\n out_dim = size[1] \n xavier_stddev = np.sqrt(2/(in_dim + out_dim))\n return tf.Variable(tf.truncated_normal([in_dim, out_dim], stddev=xavier_stddev), dtype=tf.float32)\n \n def neural_net(self, X, weights, biases):\n num_layers = len(weights) + 1\n \n H = 2.0*(X - self.lb)/(self.ub - self.lb) - 1.0\n for l in range(0,num_layers-2):\n W = weights[l]\n b = biases[l]\n H = tf.tanh(tf.add(tf.matmul(H, W), b))\n W = weights[-1]\n b = biases[-1]\n Y = tf.add(tf.matmul(H, W), b)\n return Y\n \n def net_NS(self, P_back, x):\n P_rho_u_E = self.neural_net(tf.concat([P_back, x], 1), self.weights, self.biases)\n P = P_rho_u_E[:,0:1]\n rho = P_rho_u_E[:,1:2]\n u = P_rho_u_E[:,2:3]\n E = P_rho_u_E[:,3:4]\n\n S = 1 + 2.2*((x-50)**2)*(9/10000)\n # autodiff gradient #1\n mass_flow_grad = tf.gradients(tf.multiply(tf.multiply(u, rho), S), x)[0]\n # autodiff gradient #2\n momentum_grad = tf.add(tf.gradients(tf.multiply(tf.add(tf.multiply(tf.multiply(u, u), rho), P), S), x)[0], tf.multiply(tf.gradients(S, x)[0], P))\n # autodiff gradient #3\n energy_grad = tf.gradients(tf.multiply(tf.multiply(tf.add(tf.multiply(E, rho), P), u), S), x)[0]\n\n return P, rho, u, E, mass_flow_grad, momentum_grad, energy_grad\n \n def callback(self, loss):\n print('Loss: %.3e' % (loss))\n \n def train(self, nIter): \n\n tf_dict = {self.P_back_tf: self.P_back, self.x_tf: self.x,\n self.P_tf: self.P, self.rho_tf: self.rho, self.u_tf: self.u, self.E_tf: self.E\n }\n \n start_time = time.time()\n for it in range(nIter):\n self.sess.run(self.train_op_Adam, tf_dict)\n \n # Print\n if it % 1000 == 0:\n elapsed = time.time() - start_time\n loss_value = self.sess.run(self.loss, tf_dict)\n \n print('Iter: %d, Loss: %.3e, Time: %.2f' % \n (it, loss_value, elapsed))\n start_time = time.time()\n \n self.optimizer.minimize(self.sess,\n feed_dict = tf_dict,\n fetches = [self.loss],\n loss_callback = self.callback)\n \n \n def predict(self, P_back_test, x_test):\n tf_dict = {self.P_back_tf: P_back_test, self.x_tf: x_test}\n P_test = self.sess.run(self.P_pred, tf_dict)\n rho_test = self.sess.run(self.rho_pred, tf_dict)\n u_test = self.sess.run(self.u_pred, tf_dict)\n E_test = self.sess.run(self.E_pred, tf_dict)\n return P_test, rho_test, u_test, E_test\n\nif __name__ == \"__main__\":\n \n layers = [2, 10, 25, 15, 4]\n \n # Load Data\n data = np.loadtxt('cdnozzle.txt')\n\n N_train = int(0.85*data.shape[0])\n \n A = np.random.choice(range(data.shape[0]), size=(N_train,), replace=False)\n\n # x\n P_back_train = data[A,1:2].flatten()[:,None]\n x_train = data[A,0:1].flatten()[:,None]\n # y\n P_train = data[A,2:3].flatten()[:,None]\n rho_train = data[A,6:7].flatten()[:,None]\n u_train = data[A,7:8].flatten()[:,None]\n E_train = data[A,8:9].flatten()[:,None]\n \n\n # Training\n model = NN(P_back_train, x_train, P_train, rho_train, u_train, E_train, layers)\n model.train(10000)\n \n # Test Data\n data1 = data\n data1 = np.delete(data1, A, 0)\n\n # x\n P_back_test = data1[:,1:2].flatten()[:,None]\n x_test = data1[:,0:1].flatten()[:,None]\n # y\n P_test = data1[:,2:3].flatten()[:,None]\n rho_test = data1[:,6:7].flatten()[:,None]\n u_test = data1[:,7:8].flatten()[:,None]\n E_test = data1[:,8:9].flatten()[:,None]\n\n # Prediction\n P_pred, rho_pred, u_pred, E_pred = model.predict(P_back_test, x_test)\n \n # Error\n error_P = np.linalg.norm(P_test-P_pred,2)/np.linalg.norm(P_test,2)\n print(\"Test Error in P: \"+str(error_P))\n error_rho = np.linalg.norm(rho_test-rho_pred,2)/np.linalg.norm(rho_test,2)\n print(\"Test Error in rho: \"+str(error_rho))\n error_u = np.linalg.norm(u_test-u_pred,2)/np.linalg.norm(u_test,2)\n print(\"Test Error in u: \"+str(error_u))\n error_E = np.linalg.norm(E_test-E_pred,2)/np.linalg.norm(E_test,2)\n print(\"Test Error in E: \"+str(error_E))\n\n #Plotting\n data_plt_1 = range(300, 400)\n data_plt_2 = range(1300, 1400)\n data_plt_3 = range(2300, 2400)\n data_plt_4 = range(3300, 3400)\n data_plt_5 = range(4300, 4400)\n data_plt_6 = range(5300, 5400)\n data_plt = list(data_plt_1) + list(data_plt_2) + list(data_plt_3) + list(data_plt_4) + list(data_plt_5) + list(data_plt_6)\n # x\n x_test_plt = data[data_plt, 0:1].flatten()[:,None]\n P_back_test_plt = data[data_plt, 1:2].flatten()[:,None]\n # y\n P_test_plt = data[data_plt, 2:3].flatten()[:,None]\n rho_test_plt = data[data_plt, 6:7].flatten()[:,None]\n u_test_plt = data[data_plt, 7:8].flatten()[:,None]\n E_test_plt = data[data_plt, 8:9].flatten()[:,None]\n # predict\n P_pred_plt, rho_pred_plt, u_pred_plt, E_pred_plt = model.predict(P_back_test_plt, x_test_plt)\n # plot P\n plt.plot(x_test_plt[0:100]/100.0, P_pred_plt[0:100], 'cx', x_test_plt[100:200]/100.0, P_pred_plt[100:200], 'cx',\n x_test_plt[200:300]/100.0, P_pred_plt[200:300], 'cx', x_test_plt[300:400]/100.0, P_pred_plt[300:400], 'cx',\n x_test_plt[400:500]/100.0, P_pred_plt[400:500], 'cx', x_test_plt[500:600]/100.0, P_pred_plt[500:600], 'cx', label='NN')\n plt.plot(x_test_plt[0:100]/100.0, P_test_plt[0:100], 'g--', x_test_plt[100:200]/100.0, P_test_plt[100:200], 'g--',\n x_test_plt[200:300]/100.0, P_test_plt[200:300], 'g--', x_test_plt[300:400]/100.0, P_test_plt[300:400], 'g--',\n x_test_plt[400:500]/100.0, P_test_plt[400:500], 'g--', x_test_plt[500:600]/100.0, P_test_plt[500:600], 'g--', label='CFD')\n plt.legend()\n plt.title('Comparison of Neural Network and CFD')\n plt.xlabel('Length of nozzle')\n plt.ylabel('Pressure*')\n plt.show()\n # plot rho\n plt.plot(x_test_plt[0:100]/100.0, rho_pred_plt[0:100], 'mx', x_test_plt[100:200]/100.0, rho_pred_plt[100:200], 'mx',\n x_test_plt[200:300]/100.0, rho_pred_plt[200:300], 'mx', x_test_plt[300:400]/100.0, rho_pred_plt[300:400], 'mx',\n x_test_plt[400:500]/100.0, rho_pred_plt[400:500], 'mx', x_test_plt[500:600]/100.0, rho_pred_plt[500:600], 'mx', label='NN')\n plt.plot(x_test_plt[0:100]/100.0, rho_test_plt[0:100], 'g--', x_test_plt[100:200]/100.0, rho_test_plt[100:200], 'g--',\n x_test_plt[200:300]/100.0, rho_test_plt[200:300], 'g--', x_test_plt[300:400]/100.0, rho_test_plt[300:400], 'g--',\n x_test_plt[400:500]/100.0, rho_test_plt[400:500], 'g--', x_test_plt[500:600]/100.0, rho_test_plt[500:600], 'g--', label='CFD')\n plt.legend()\n plt.title('Comparison of Neural Network and CFD')\n plt.xlabel('Length of nozzle')\n plt.ylabel('rho')\n plt.show()\n # plot u\n plt.plot(x_test_plt[0:100]/100.0, u_pred_plt[0:100], 'yx', x_test_plt[100:200]/100.0, u_pred_plt[100:200], 'yx',\n x_test_plt[200:300]/100.0, u_pred_plt[200:300], 'yx', x_test_plt[300:400]/100.0, u_pred_plt[300:400], 'yx',\n x_test_plt[400:500]/100.0, u_pred_plt[400:500], 'yx', x_test_plt[500:600]/100.0, u_pred_plt[500:600], 'yx', label='NN')\n plt.plot(x_test_plt[0:100]/100.0, u_test_plt[0:100], 'g--', x_test_plt[100:200]/100.0, u_test_plt[100:200], 'g--',\n x_test_plt[200:300]/100.0, u_test_plt[200:300], 'g--', x_test_plt[300:400]/100.0, u_test_plt[300:400], 'g--',\n x_test_plt[400:500]/100.0, u_test_plt[400:500], 'g--', x_test_plt[500:600]/100.0, u_test_plt[500:600], 'g--', label='CFD')\n plt.legend()\n plt.title('Comparison of Neural Network and CFD')\n plt.xlabel('Length of nozzle')\n plt.ylabel('u')\n plt.show()\n # plot E\n plt.plot(x_test_plt[0:100]/100.0, E_pred_plt[0:100], 'kx', x_test_plt[100:200]/100.0, E_pred_plt[100:200], 'kx',\n x_test_plt[200:300]/100.0, E_pred_plt[200:300], 'kx', x_test_plt[300:400]/100.0, E_pred_plt[300:400], 'kx',\n x_test_plt[400:500]/100.0, E_pred_plt[400:500], 'kx', x_test_plt[500:600]/100.0, E_pred_plt[500:600], 'kx', label='NN')\n plt.plot(x_test_plt[0:100]/100.0, E_test_plt[0:100], 'g--', x_test_plt[100:200]/100.0, E_test_plt[100:200], 'g--',\n x_test_plt[200:300]/100.0, E_test_plt[200:300], 'g--', x_test_plt[300:400]/100.0, E_test_plt[300:400], 'g--',\n x_test_plt[400:500]/100.0, E_test_plt[400:500], 'g--', x_test_plt[500:600]/100.0, E_test_plt[500:600], 'g--', label='CFD')\n plt.legend()\n plt.title('Comparison of Neural Network and CFD')\n plt.xlabel('Length of nozzle')\n plt.ylabel('E')\n plt.show()" }, { "alpha_fraction": 0.47578948736190796, "alphanum_fraction": 0.5018623471260071, "avg_line_length": 29.8799991607666, "blob_id": "16f71054689e97bce28958163bfb3a9bc2721f67", "content_id": "56e94d78696297e22a0619bb1f66f55b7775b4af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6175, "license_type": "no_license", "max_line_length": 119, "num_lines": 200, "path": "/1D-Nozzle/JuPyter/Neu_Net1_NOO.py", "repo_name": "jhssyb/PINN--NUS", "src_encoding": "UTF-8", "text": "import sys\nsys.path.insert(0, '../../Utilities/')\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io\nfrom scipy.interpolate import griddata\nimport time\nfrom itertools import product, combinations\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\n#from plotting import newfig, savefig\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport matplotlib.gridspec as gridspec\n\nnp.random.seed(1234)\ntf.set_random_seed(1234)\n \ndef callback(loss):\n print('Loss: %.3e' % (loss))\n \n#class PhysicsInformedNN:\n # Initialize the class\n #def __init__(self, P_back, x, P, layers): \n \n #def xavier_init(self, size):\n \n \n #def neural_net(self, X, weights, biases):\n \n \n #def net_NS(self, P_back, x):\n \n \n #del_P = del_and_sh[:,0:1]\n #shock_loc = del_and_sh[:,1:2]\n \n #return P\n \n #def callback(self, loss):\n \n \n #def train(self, nIter): \n\n \n \n \n #def predict(self, P_back_test, x_test):\n \n \n \n #return P_test\n\nif __name__ == \"__main__\": \n \n N_train = 1260\n \n layers = [2, 10, 10, 1]\n \n # Load Data\n data = np.loadtxt('cdnozzle1.txt')\n \n A = np.random.choice(range(data.shape[0]), size=(N_train,), replace=False)\n\n P_back_train = data[A,0:1].flatten()[:,None]\n x_train = data[A,1:2].flatten()[:,None]\n P_train = data[A,2:3].flatten()[:,None]\n\n # Training\n #model = PhysicsInformedNN(P_back_train, x_train, P_train, layers)\n X1 = np.concatenate([P_back_train, x_train], 1)\n lb = X1.min(0)\n ub = X1.max(0)\n \n # Initialize NN\n #self.weights, self.biases = self.initialize_NN(layers)\n \n # tf placeholders and graph\n sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,\n log_device_placement=True))\n\n P_back_tf = tf.placeholder(tf.float32, shape=[None, P_back_train.shape[1]])\n x_tf = tf.placeholder(tf.float32, shape=[None, x_train.shape[1]])\n \n P_tf = tf.placeholder(tf.float32, shape=[None, P_train.shape[1]])\n \n #P_pred = self.net_NS(self.P_back_tf, self.x_tf)\n #P_pred = self.neural_net(tf.concat([P_back, x], 1), self.weights, self.biases)\n\n X = tf.concat([P_back_tf, x_tf], 1) \n\n weights = []\n biases = []\n num_layers = len(layers) \n\n for l in range(0,num_layers-1):\n size=[layers[l], layers[l+1]]\n in_dim = size[0]\n out_dim = size[1] \n xavier_stddev = np.sqrt(2/(in_dim + out_dim))\n W = tf.Variable(tf.truncated_normal([in_dim, out_dim], stddev=xavier_stddev), dtype=tf.float32)\n b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32)\n weights.append(W)\n biases.append(b) \n \n\n num_layers = len(weights) + 1\n \n H = 2.0*(X - lb)/(ub - lb) - 1.0\n tf.cast(H, tf.float32)\n for l in range(0,num_layers-2):\n W = weights[l]\n b = biases[l]\n H = tf.tanh(tf.add(tf.matmul(H, W), b))\n W = weights[-1]\n b = biases[-1]\n P_pred = tf.add(tf.matmul(H, W), b)\n \n \n loss = tf.reduce_sum(tf.square(P_tf - P_pred)) \n \n optimizer = tf.contrib.opt.ScipyOptimizerInterface(loss, \n method = 'L-BFGS-B', \n options = {'maxiter': 150000,\n 'maxfun': 150000,\n 'maxcor': 50,\n 'maxls': 50,\n 'ftol' : 1.0 * np.finfo(float).eps}) \n \n optimizer_Adam = tf.train.AdamOptimizer()\n train_op_Adam = optimizer_Adam.minimize(loss) \n \n init = tf.global_variables_initializer()\n sess.run(init)\n\n\n #model.train(10000)\n\n tf_dict = {P_back_tf: P_back_train, \n x_tf: x_train, P_tf: P_train}\n \n start_time = time.time()\n for it in range(10000):\n sess.run(train_op_Adam, tf_dict)\n \n # Print\n if it % 10 == 0:\n elapsed = time.time() - start_time\n loss_value = sess.run(loss, tf_dict)\n \n print('It: %d, Loss: %.3e, Time: %.2f' % \n (it, loss_value, elapsed))\n start_time = time.time()\n \n optimizer.minimize(sess,\n feed_dict = tf_dict,\n fetches = [loss],\n loss_callback = callback)\n \n # Test Data\n #data1 = data\n #data1 = np.delete(data1, A, 0)\n data_test = np.loadtxt('cdnozzle_test.txt')\n\n #P_back_test = data1[:,0:1].flatten()[:,None]\n #x_test = data1[:,1:2].flatten()[:,None]\n for i in range(0, 8):\n P_back_test = 0.01*(27+8*i)*np.ones((100,1), dtype = float)\n x_test = 0.03*np.arange(1, 101, dtype=float).flatten()[:,None]\n P_test = data_test[100*i:100*(i+1),2:3]\n\n #P_test = data1[:,2:3].flatten()[:,None]\n \n # Prediction\n #P_pred = model.predict(P_back_test, x_test)\n tf_dict_test = {P_back_tf: P_back_test, x_tf: x_test}\n \n P_pred_test = sess.run(P_pred, tf_dict_test)\n\n plt.plot(x_test, P_pred_test, 'r--')\n plt.plot(x_test, P_test, 'b--')\n #print(P_test_pred)\n \n #Error\n error_P = np.linalg.norm(P_test-P_pred_test,2)/np.linalg.norm(P_test,2)\n print('Error P: %e' % (error_P)) \n\n \n plt.show()\n plt.title('Comparison of Neural Network and CFD')\n plt.xlabel('Length of nozzle')\n plt.ylabel('Pressure')\n \n # Plot Results\n# plot_solution(x_test, P_pred, 1)\n# plot_solution(X_star, v_pred, 2)\n# plot_solution(X_star, p_pred, 3) \n# plot_solution(X_star, p_star, 4)\n# plot_solution(X_star, p_star - p_pred, 5)" }, { "alpha_fraction": 0.47643035650253296, "alphanum_fraction": 0.529039204120636, "avg_line_length": 41.49541473388672, "blob_id": "850ab116dbfdae513cc9c69ad79b93c3c43ec40b", "content_id": "bb7cc313a195383ba1cee4d5b1ed6dacb33088cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13895, "license_type": "no_license", "max_line_length": 139, "num_lines": 327, "path": "/1D-Nozzle/NN/NN2_non-conservative.py", "repo_name": "jhssyb/PINN--NUS", "src_encoding": "UTF-8", "text": "import sys\nsys.path.insert(0, '../../Utilities/')\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io\nfrom scipy.interpolate import griddata\nimport time\nfrom itertools import product, combinations\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\n#from plotting import newfig, savefig\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport matplotlib.gridspec as gridspec\n\nnp.random.seed(1234)\ntf.set_random_seed(1234)\n\nclass NN:\n # Initialize the class\n def __init__(self, P_back, x, P, rho, u, E, layers):\n \n X = np.concatenate([P_back, x], 1)\n \n self.lb = X.min(0)\n self.ub = X.max(0)\n self.X = X\n self.P_back = P_back\n self.x = x\n self.P = P\n self.rho = rho\n self.u = u\n self.E = E\n\n gamma = 1.4\n\n self.layers = layers\n \n # Initialize NN\n self.weights, self.biases = self.initialize_NN(layers) \n \n # tf placeholders and graph\n self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,\n log_device_placement=True))\n \n self.P_back_tf = tf.placeholder(tf.float32, shape=[None, self.P_back.shape[1]])\n self.x_tf = tf.placeholder(tf.float32, shape=[None, self.x.shape[1]])\n self.P_tf = tf.placeholder(tf.float32, shape=[None, self.P.shape[1]])\n self.rho_tf = tf.placeholder(tf.float32, shape=[None, self.rho.shape[1]])\n self.u_tf = tf.placeholder(tf.float32, shape=[None, self.u.shape[1]])\n self.E_tf = tf.placeholder(tf.float32, shape=[None, self.E.shape[1]])\n \n self.P_pred, self.rho_pred, self.u_pred, self.E_pred, self.e1, self.e2, self.e3= self.net_NS(self.P_back_tf, self.x_tf)\n self.state_eq = self.P_pred - self.rho_pred*(gamma-1)*(self.E_pred - gamma/2*(self.u_pred)*(self.u_pred))\n\n # MSE Normalization\n P_norm = np.amax(P)\n rho_norm = np.amax(rho)\n u_norm = np.amax(u)\n E_norm = np.amax(E)\n S_norm = 5.95\n e1_norm = rho_norm*u_norm*S_norm\n e2_norm = P_norm*S_norm\n e3_norm = E_norm*rho_norm*u_norm*S_norm\n w = 40\n \n self.loss = tf.reduce_sum(tf.square(self.P_tf - self.P_pred))/(P_norm**2) + \\\n tf.reduce_sum(tf.square(self.rho_tf - self.rho_pred))/(rho_norm**2) + \\\n tf.reduce_sum(tf.square(self.u_tf - self.u_pred))/(u_norm**2) + \\\n tf.reduce_sum(tf.square(self.E_tf - self.E_pred))/(E_norm**2)# + \\\n # w*tf.reduce_sum(tf.square(self.e2))/(e2_norm**2) + \\\n # w*tf.reduce_sum(tf.square(self.e3))/(e3_norm**2) + \\\n # w*tf.reduce_sum(tf.square(self.e1))/(e1_norm**2) + \\\n # w*tf.reduce_sum(tf.square(self.state_eq))/(P_norm**2)\n \n self.optimizer = tf.contrib.opt.ScipyOptimizerInterface(self.loss, \n method = 'L-BFGS-B', \n options = {'maxiter': 15000,\n 'maxfun': 15000,\n 'maxcor': 50,\n 'maxls': 50,\n 'ftol' : 1.0 * np.finfo(float).eps}) \n \n self.optimizer_Adam = tf.train.AdamOptimizer()\n self.train_op_Adam = self.optimizer_Adam.minimize(self.loss) \n \n init = tf.global_variables_initializer()\n self.sess.run(init)\n\n def initialize_NN(self, layers): \n weights = []\n biases = []\n num_layers = len(layers) \n for l in range(0,num_layers-1):\n W = self.xavier_init(size=[layers[l], layers[l+1]])\n b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32)\n weights.append(W)\n biases.append(b) \n return weights, biases\n \n def xavier_init(self, size):\n in_dim = size[0]\n out_dim = size[1] \n xavier_stddev = np.sqrt(2/(in_dim + out_dim))\n return tf.Variable(tf.truncated_normal([in_dim, out_dim], stddev=xavier_stddev), dtype=tf.float32)\n \n def neural_net(self, X, weights, biases):\n num_layers = len(weights) + 1\n \n H = 2.0*(X - self.lb)/(self.ub - self.lb) - 1.0\n for l in range(0,num_layers-2):\n W = weights[l]\n b = biases[l]\n H = tf.tanh(tf.add(tf.matmul(H, W), b))\n W = weights[-1]\n b = biases[-1]\n Y = tf.add(tf.matmul(H, W), b)\n return Y\n \n def net_NS(self, P_back, x):\n P_rho_u_E = self.neural_net(tf.concat([P_back, x], 1), self.weights, self.biases)\n P = P_rho_u_E[:,0:1]\n rho = P_rho_u_E[:,1:2]\n u = P_rho_u_E[:,2:3]\n E = P_rho_u_E[:,3:4]\n\n S = 1 + 2.2*((x-50)**2)*(9/10000)\n # autodiff gradient #1\n mass_flow_grad = tf.gradients(rho*u*S, x)[0]\n # autodiff gradient #2\n momentum_grad = tf.gradients((rho*u*u + P)*S, x)[0] - P*tf.gradients(S, x)[0]\n # autodiff gradient #3\n energy_grad = tf.gradients((rho*E + P)*u*S, x)[0]\n\n return P, rho, u, E, mass_flow_grad, momentum_grad, energy_grad\n \n def callback(self, loss):\n loss_vector.append(loss)\n print('Loss: %.3e' % (loss))\n \n def train(self, nIter): \n\n tf_dict = {self.P_back_tf: self.P_back, self.x_tf: self.x,\n self.P_tf: self.P, self.rho_tf: self.rho, self.u_tf: self.u, self.E_tf: self.E\n }\n \n global loss_vector\n loss_vector = []\n\n start_time = time.time()\n for it in range(nIter):\n self.sess.run(self.train_op_Adam, tf_dict)\n \n loss_value = self.sess.run(self.loss, tf_dict)\n loss_vector.append(loss_value)\n\n # Print\n if it % 1000 == 0:\n elapsed = time.time() - start_time\n res1 = self.sess.run(self.e1, tf_dict)\n res2 = self.sess.run(self.e2, tf_dict)\n res3 = self.sess.run(self.e3, tf_dict)\n print('Iter: %d, Loss: %.3e, Time: %.2f' % \n (it, loss_value, elapsed))\n print('Mass Residual: %f\\t\\tMomentum Residual: %f\\tEnergy Residual: %f'\n %(sum(map(lambda a:a*a,res1))/len(res1), sum(map(lambda a:a*a,res2))/len(res2), sum(map(lambda a:a*a,res3))/len(res3)))\n start_time = time.time()\n \n self.optimizer.minimize(self.sess,\n feed_dict = tf_dict,\n fetches = [self.loss],\n loss_callback = self.callback)\n\n return loss_vector\n \n \n def predict(self, P_back_test, x_test):\n tf_dict = {self.P_back_tf: P_back_test, self.x_tf: x_test}\n P_test = self.sess.run(self.P_pred, tf_dict)\n rho_test = self.sess.run(self.rho_pred, tf_dict)\n u_test = self.sess.run(self.u_pred, tf_dict)\n E_test = self.sess.run(self.E_pred, tf_dict)\n return P_test, rho_test, u_test, E_test\n\nif __name__ == \"__main__\":\n \n layers = [2, 20, 25, 20, 4]\n \n # Load Data\n data = np.loadtxt('cdnozzle.txt')\n\n train_frac = 0.02\n N_train = int(train_frac*data.shape[0])\n \n A = np.random.choice(range(data.shape[0]), size=(N_train,), replace=False)\n\n # x\n P_back_train = data[A,1:2].flatten()[:,None]\n x_train = data[A,0:1].flatten()[:,None]\n # y\n P_train = data[A,2:3].flatten()[:,None]\n rho_train = data[A,6:7].flatten()[:,None]\n u_train = data[A,7:8].flatten()[:,None]\n E_train = data[A,8:9].flatten()[:,None]\n \n\n # Training\n model = NN(P_back_train, x_train, P_train, rho_train, u_train, E_train, layers)\n model.train(20001)\n # plt.plot(loss_vector, label='Loss value')\n # plt.legend()\n # plt.title('Loss value over iterations')\n # plt.xlabel('#iterations')\n # plt.ylabel('Loss')\n # plt.show()\n \n # Test Data\n data1 = data\n data1 = np.delete(data1, A, 0)\n\n # x\n P_back_test = data1[:,1:2].flatten()[:,None]\n x_test = data1[:,0:1].flatten()[:,None]\n # y\n P_test = data1[:,2:3].flatten()[:,None]\n rho_test = data1[:,6:7].flatten()[:,None]\n u_test = data1[:,7:8].flatten()[:,None]\n E_test = data1[:,8:9].flatten()[:,None]\n\n # Prediction\n P_pred, rho_pred, u_pred, E_pred = model.predict(P_back_test, x_test)\n \n # Error\n error_P = np.linalg.norm(P_test-P_pred,2)/np.linalg.norm(P_test,2)\n print(\"Test Error in P: \"+str(error_P))\n error_rho = np.linalg.norm(rho_test-rho_pred,2)/np.linalg.norm(rho_test,2)\n print(\"Test Error in rho: \"+str(error_rho))\n error_u = np.linalg.norm(u_test-u_pred,2)/np.linalg.norm(u_test,2)\n print(\"Test Error in u: \"+str(error_u))\n error_E = np.linalg.norm(E_test-E_pred,2)/np.linalg.norm(E_test,2)\n print(\"Test Error in E: \"+str(error_E))\n\n #Plotting\n data_plt_1 = range(305, 395)\n data_plt_2 = range(605, 695)\n data_plt_3 = range(905, 995)\n data_plt_4 = range(1205, 1295)\n data_plt_5 = range(1505, 1595)\n data_plt_6 = range(1805, 1895)\n data_plt = list(data_plt_1) + list(data_plt_2) + list(data_plt_3) + list(data_plt_4) + list(data_plt_5) + list(data_plt_6)\n l1_l = 0\n l1_u = 90\n l2_l = l1_u\n l2_u = 180\n l3_l = l2_u\n l3_u = 270\n l4_l = l3_u\n l4_u = 360\n l5_l = l4_u\n l5_u = 450\n l6_l = l5_u\n l6_u = 540\n # x\n x_test_plt = data[data_plt, 0:1].flatten()[:,None]\n P_back_test_plt = data[data_plt, 1:2].flatten()[:,None]\n # y\n P_test_plt = data[data_plt, 2:3].flatten()[:,None]\n rho_test_plt = data[data_plt, 6:7].flatten()[:,None]\n u_test_plt = data[data_plt, 7:8].flatten()[:,None]\n E_test_plt = data[data_plt, 8:9].flatten()[:,None]\n # predict\n P_pred_plt, rho_pred_plt, u_pred_plt, E_pred_plt = model.predict(P_back_test_plt, x_test_plt)\n # plot P\n plt.plot(x_test_plt[l5_l:l5_u]/100.0, P_pred_plt[l5_l:l5_u], 'b', label='NN')\n plt.ylim(0.0, 1.0)\n # plt.plot(x_test_plt[l5_l:l5_u]/100.0, P_test_plt[l5_l:l5_u], 'g',label='CFD')\n plt.legend(loc='center left')\n # plt.title('Comparison of Neural Network and CFD')\n plt.xlabel('Length of nozzle')\n plt.ylabel('Pressure')\n plt.show()\n # plot rho\n # plt.plot(x_test_plt[l5_l:l5_u]/100.0, rho_pred_plt[l5_l:l5_u], 'r', label='NN')\n # plt.plot(x_test_plt[l5_l:l5_u]/100.0, rho_test_plt[l5_l:l5_u], 'g', label='CFD')\n # plt.legend()\n # plt.title('Comparison of Neural Network and CFD')\n # plt.xlabel('Length of nozzle')\n # plt.ylabel('Density')\n # plt.show()\n # plot u\n # plt.plot(x_test_plt[l1_l:l1_u]/100.0, u_pred_plt[l1_l:l1_u], 'y', x_test_plt[l2_l:l2_u]/100.0, u_pred_plt[l2_l:l2_u], 'y',\n # x_test_plt[l3_l:l3_u]/100.0, u_pred_plt[l3_l:l3_u], 'y', x_test_plt[l4_l:l4_u]/100.0, u_pred_plt[l4_l:l4_u], 'y',\n # x_test_plt[l5_l:l5_u]/100.0, u_pred_plt[l5_l:l5_u], 'y', x_test_plt[l6_l:l6_u]/100.0, u_pred_plt[l6_l:l6_u], 'y', label='NN')\n # plt.plot(x_test_plt[l1_l:l1_u]/100.0, u_test_plt[l1_l:l1_u], 'g', x_test_plt[l2_l:l2_u]/100.0, u_test_plt[l2_l:l2_u], 'g',\n # x_test_plt[l3_l:l3_u]/100.0, u_test_plt[l3_l:l3_u], 'g', x_test_plt[l4_l:l4_u]/100.0, u_test_plt[l4_l:l4_u], 'g',\n # x_test_plt[l5_l:l5_u]/100.0, u_test_plt[l5_l:l5_u], 'g', x_test_plt[l6_l:l6_u]/100.0, u_test_plt[l6_l:l6_u], 'g', label='CFD')\n # plt.legend()\n # plt.title('Comparison of Neural Network and CFD')\n # plt.xlabel('Length of nozzle')\n # plt.ylabel('u')\n # plt.show()\n # plot E\n # plt.plot(x_test_plt[l1_l:l1_u]/100.0, E_pred_plt[l1_l:l1_u], 'b', x_test_plt[l2_l:l2_u]/100.0, E_pred_plt[l2_l:l2_u], 'b',\n # x_test_plt[l3_l:l3_u]/100.0, E_pred_plt[l3_l:l3_u], 'b', x_test_plt[l4_l:l4_u]/100.0, E_pred_plt[l4_l:l4_u], 'b',\n # x_test_plt[l5_l:l5_u]/100.0, E_pred_plt[l5_l:l5_u], 'b', x_test_plt[l6_l:l6_u]/100.0, E_pred_plt[l6_l:l6_u], 'b', label='NN')\n # plt.plot(x_test_plt[l1_l:l1_u]/100.0, E_test_plt[l1_l:l1_u], 'g', x_test_plt[l2_l:l2_u]/100.0, E_test_plt[l2_l:l2_u], 'g',\n # x_test_plt[l3_l:l3_u]/100.0, E_test_plt[l3_l:l3_u], 'g', x_test_plt[l4_l:l4_u]/100.0, E_test_plt[l4_l:l4_u], 'g',\n # x_test_plt[l5_l:l5_u]/100.0, E_test_plt[l5_l:l5_u], 'g', x_test_plt[l6_l:l6_u]/100.0, E_test_plt[l6_l:l6_u], 'g', label='CFD')\n # plt.legend()\n # plt.title('Comparison of Neural Network and CFD')\n # plt.xlabel('Length of nozzle')\n # plt.ylabel('E')\n # plt.show()\n\n # gamma = 1.4\n # rho_R_T = (gamma-1)*(E_test_plt-0.5*(u_test_plt**2))*rho_test_plt\n # plt.plot(x_test_plt[0:100]/100.0, rho_R_T[0:100], 'yx', x_test_plt[100:200]/100.0, rho_R_T[100:200], 'yx',\n # x_test_plt[200:300]/100.0, rho_R_T[200:300], 'yx', x_test_plt[300:400]/100.0, rho_R_T[300:400], 'yx',\n # x_test_plt[400:500]/100.0, rho_R_T[400:500], 'yx', x_test_plt[500:600]/100.0, rho_R_T[500:600], 'yx', label='rho_R_T')\n # plt.plot(x_test_plt[0:100]/100.0, P_test_plt[0:100], 'b--', x_test_plt[100:200]/100.0, P_test_plt[100:200], 'b--',\n # x_test_plt[200:300]/100.0, P_test_plt[200:300], 'b--', x_test_plt[300:400]/100.0, P_test_plt[300:400], 'b--',\n # x_test_plt[400:500]/100.0, P_test_plt[400:500], 'b--', x_test_plt[500:600]/100.0, P_test_plt[500:600], 'b--', label='P')\n # plt.legend()\n # plt.title('Comparison of rho_R_T and P: Ideal Gas Equation')\n # plt.xlabel('Length of nozzle')\n # plt.ylabel('Non-dimensional Pressure')\n # plt.show()" }, { "alpha_fraction": 0.693345308303833, "alphanum_fraction": 0.7041366696357727, "avg_line_length": 49.59090805053711, "blob_id": "66dd6654be07ea1f91ce414b69a5fa021ed68cee", "content_id": "b0622d352464770e45a80d7dea77786817567cee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1112, "license_type": "no_license", "max_line_length": 120, "num_lines": 22, "path": "/1D-Nozzle/JuPyter/README.txt", "repo_name": "jhssyb/PINN--NUS", "src_encoding": "UTF-8", "text": "This is a brief documentation of our work until now on PINN.\nThere are total of 15 files including thin on: 'README.txt':\n\n (5 files) 'figure_N.png' files: comparison plots of PINN and CFD, 'PINN.png' representation of PINN\n \n PINN: (3 files)\n 'PINN-1D_Nozzle.ipynb' is our well commented and well explained Jupyter noteboook object oriented PINN code.\n 'NN2.py' python source code only file for the above Jupyter notebook.\n The dataset 'cdnozzle.txt' file for PINN.\n \n Basic-NN: (4 files)\n 'Basic-NN_code.ipynb' non-object oriented basic Neural network - well commented and explained\n 'Neu_Net1_NOO.py' python source code only file for the above Jupyter notebook.\n 'cdnozzle1.txt' and 'cdnozzle_test.txt' as training and testing dataests for the Basic-NN_code.py.\n \n Report: (1 file)\n 'Report_ PINN for steady 1D nozzle Problem.ipynb' is documentation of the overall problem and solution approach.\n \n Documentation: (1 file)\n 'Backpropagation.ipynb' is demonstration of how Backprop and autodiff actually work.\n\nThank You!" }, { "alpha_fraction": 0.5477765798568726, "alphanum_fraction": 0.5787264108657837, "avg_line_length": 34.584808349609375, "blob_id": "c1501aab2019be4a514135b2c3fc8ac6f9b6019a", "content_id": "82dd89e5045aff7b514939b1564ece27afcdfb83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14055, "license_type": "no_license", "max_line_length": 154, "num_lines": 395, "path": "/1D-Nozzle/PINNNN/NOO-PINN.py", "repo_name": "jhssyb/PINN--NUS", "src_encoding": "UTF-8", "text": "import sys\nsys.path.insert(0, '../../Utilities/')\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io\nfrom scipy.interpolate import griddata\nimport time\nfrom itertools import product, combinations\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\n#from plotting import newfig, savefig\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport matplotlib.gridspec as gridspec\nimport csv\n\nglobal P_back, rho, u, E, P, x\n\nnp.random.seed(1234)\ntf.set_random_seed(1234)\n\ndef model_init(P_back, x, P, rho, u, E, layers):\n\n global lb, ub, X, weights, biases, sess\n global P_back_tf, x_tf, P_tf, rho_tf, u_tf, E_tf\n global P_pred, rho_pred, u_pred, E_pred\n\n X = np.concatenate([P_back, x], 1)\n\n lb = X.min(0)\n ub = X.max(0)\n \n # Initialize NN\n weights, biases = initialize_NN(layers) \n \n # tf placeholders and graph\n sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,\n log_device_placement=True))\n \n P_back_tf = tf.placeholder(tf.float32, shape=[None, P_back.shape[1]])\n x_tf = tf.placeholder(tf.float32, shape=[None, x.shape[1]])\n P_tf = tf.placeholder(tf.float32, shape=[None, P.shape[1]])\n rho_tf = tf.placeholder(tf.float32, shape=[None, rho.shape[1]])\n u_tf = tf.placeholder(tf.float32, shape=[None, u.shape[1]])\n E_tf = tf.placeholder(tf.float32, shape=[None, E.shape[1]])\n \n P_pred, rho_pred, u_pred, E_pred, e1, e2, e3, e4 = net_NS(P_back_tf, x_tf, weights, biases)\n\n # MSE Normalization\n P_norm = np.amax(P)\n rho_norm = np.amax(rho)\n u_norm = np.amax(u)\n E_norm = np.amax(E)\n S_norm = 5.95\n e1_norm = rho_norm*u_norm*S_norm\n e2_norm = P_norm*S_norm\n e3_norm = E_norm*rho_norm*u_norm*S_norm\n a = 40\n\n global loss\n loss = tf.reduce_sum(tf.square(P_tf - P_pred))/(P_norm**2) + \\\n tf.reduce_sum(tf.square(rho_tf - rho_pred))/(rho_norm**2) + \\\n tf.reduce_sum(tf.square(u_tf - u_pred))/(u_norm**2) + \\\n tf.reduce_sum(tf.square(E_tf - E_pred))/(E_norm**2) + \\\n a*tf.reduce_sum(tf.square(e2))/(e2_norm**2) + \\\n a*tf.reduce_sum(tf.square(e3))/(e3_norm**2) + \\\n a*tf.reduce_sum(tf.square(e1))/(e1_norm**2) + \\\n a*tf.reduce_sum(tf.square(e4))/(P_norm**2)\n \n global optimizer\n optimizer = tf.contrib.opt.ScipyOptimizerInterface(loss, \n method = 'L-BFGS-B', \n options = {'maxiter': 15000,\n 'maxfun': 15000,\n 'maxcor': 50,\n 'maxls': 50,\n 'ftol' : 1.0 * np.finfo(float).eps}) \n \n optimizer_Adam = tf.train.AdamOptimizer()\n global train_op_Adam\n train_op_Adam = optimizer_Adam.minimize(loss) \n \n init = tf.global_variables_initializer()\n sess.run(init)\n\ndef initialize_NN(layers): \n weights = []\n biases = []\n num_layers = len(layers) \n for l in range(0,num_layers-1):\n W = xavier_init(size=[layers[l], layers[l+1]])\n b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32)\n weights.append(W)\n biases.append(b) \n return weights, biases\n \ndef xavier_init(size):\n in_dim = size[0]\n out_dim = size[1] \n xavier_stddev = np.sqrt(2/(in_dim + out_dim))\n return tf.Variable(tf.truncated_normal([in_dim, out_dim], stddev=xavier_stddev), dtype=tf.float32)\n\ndef neural_net(X, weights, biases):\n num_layers = len(weights) + 1\n \n H = 2.0*(X - lb)/(ub - lb) - 1.0\n for l in range(0,num_layers-2):\n W = weights[l]\n b = biases[l]\n H = tf.tanh(tf.add(tf.matmul(H, W), b))\n W = weights[-1]\n b = biases[-1]\n Y = tf.add(tf.matmul(H, W), b)\n return Y\n \ndef net_NS(P_back, x, weights, biases):\n P_rho_u_E = neural_net(tf.concat([P_back, x], 1), weights, biases)\n P = P_rho_u_E[:,0:1]\n rho = P_rho_u_E[:,1:2]\n u = P_rho_u_E[:,2:3]\n E = P_rho_u_E[:,3:4]\n\n S = 1 + 2.2*(3*x-1.5)**2\n # autodiff gradient #1\n mass_flow_grad = tf.gradients(rho*u*S, x)[0]\n # autodiff gradient #2\n momentum_grad = tf.gradients((rho*u*u + P)*S, x)[0] - P*tf.gradients(S, x)[0]\n # autodiff gradient #3\n energy_grad = tf.gradients((rho*E + P)*u*S, x)[0]\n # state residual\n gamma = 1.4\n state_res = P - rho*(gamma-1)*(E-0.5*gamma*u*u)\n\n return P, rho, u, E, mass_flow_grad, momentum_grad, energy_grad, state_res\n\ndef callback(loss):\n loss_vector.append(loss)\n print('Loss: %.3e' % (loss))\n \ndef train(nIter, P_back, x, rho, u, E, P):\n\n tf_dict = {P_back_tf: P_back, x_tf: x,\n P_tf: P, rho_tf: rho, u_tf: u, E_tf: E\n }\n \n global loss_vector\n loss_vector = []\n\n start_time = time.time()\n for it in range(nIter):\n sess.run(train_op_Adam, tf_dict)\n\n loss_value = sess.run(loss, tf_dict)\n loss_vector.append(loss_value)\n\n # Print\n if it % 1000 == 0:\n elapsed = time.time() - start_time\n # res1 = self.sess.run(self.e1, tf_dict)\n # res2 = self.sess.run(self.e2, tf_dict)\n # res3 = self.sess.run(self.e3, tf_dict)\n print('Iter: %d, Loss: %.3e, Time: %.2f' % \n (it, loss_value, elapsed))\n # print('Mass Residual: %f\\t\\tMomentum Residual: %f\\tEnergy Residual: %f'\n # %(sum(map(lambda a:a*a,res1))/len(res1), sum(map(lambda a:a*a,res2))/len(res2), sum(map(lambda a:a*a,res3))/len(res3)))\n start_time = time.time()\n \n optimizer.minimize(sess,\n feed_dict = tf_dict,\n fetches = [loss],\n loss_callback = callback)\n\n return loss_vector\n \n\ndef predict(P_back_test, x_test):\n tf_dict = {P_back_tf: P_back_test, x_tf: x_test}\n P_test = sess.run(P_pred, tf_dict)\n rho_test = sess.run(rho_pred, tf_dict)\n u_test = sess.run(u_pred, tf_dict)\n E_test = sess.run(E_pred, tf_dict)\n return P_test, rho_test, u_test, E_test\n\n\nlayers = [2, 10, 10, 10, 4]\n\n\nP_dataset = []\nrho_dataset = []\nE_dataset = []\nu_dataset = []\n\nwith open('cdn_P.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for element in row:\n P_dataset.append(float(element))\n\nwith open('cdn_rho.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for element in row:\n rho_dataset.append(float(element))\n\nwith open('cdn_E.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for element in row:\n E_dataset.append(float(element))\n\nwith open('cdn_u.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for element in row:\n u_dataset.append(float(element))\n\nP_dataset = np.asarray(P_dataset)\nrho_dataset = np.asarray(rho_dataset)\nE_dataset = np.asarray(E_dataset)\nu_dataset = np.asarray(u_dataset)\n\nP_back_train_all = []\nP_back_train_all = np.asarray(P_back_train_all)\nx_train_all = []\nx_train_all = np.asarray(x_train_all)\n\nfor i in range(0, 27):\n P_back_value = 0.01*(21+3*i)*np.ones((101,1))\n P_back_train_all = np.concatenate((P_back_train_all, P_back_value), axis=None)\n x_value = 0.01*np.arange(0, 101, dtype=float).flatten()[:,None]\n x_train_all = np.concatenate((x_train_all, x_value), axis=None)\n\ntrain_frac = 0.01\nN_train = int(train_frac*P_dataset.shape[0])\n\nA = np.random.choice(range(P_dataset.shape[0]), size=(N_train,), replace=False)\n\n# x\nP_back_train_frac = P_back_train_all[A].flatten()[:,None]\nx_train_frac = x_train_all[A].flatten()[:,None]\n# y\nP_train_frac = P_dataset[A].flatten()[:,None]\nrho_train_frac = rho_dataset[A].flatten()[:,None]\nu_train_frac = u_dataset[A].flatten()[:,None]\nE_train_frac = E_dataset[A].flatten()[:,None]\n\n# Training\nmodel_init(P_back_train_frac, x_train_frac, P_train_frac, rho_train_frac, u_train_frac, E_train_frac, layers)\ntrain(20001, P_back_train_frac, x_train_frac, rho_train_frac, u_train_frac, E_train_frac, P_train_frac)\n\n# plt.plot(loss_vector, label='Loss value')\n# print(\"Total Iter = \" + str(len(loss_vector)))\n# plt.legend()\n# plt.title('Loss value over iterations')\n# plt.xlabel('#iterations')\n# plt.ylabel('Loss')\n# plt.show()\n\n# Test Data\nP_test_dataset = []\nrho_test_dataset = []\nE_test_dataset = []\nu_test_dataset = []\n\nwith open('cdn_P_test.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for element in row:\n P_test_dataset.append(float(element))\n\nwith open('cdn_rho_test.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for element in row:\n rho_test_dataset.append(float(element))\n\nwith open('cdn_E_test.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for element in row:\n E_test_dataset.append(float(element))\n\nwith open('cdn_u_test.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for element in row:\n u_test_dataset.append(float(element))\n\nP_test_dataset = np.asarray(P_test_dataset).flatten()[:,None]\nrho_test_dataset = np.asarray(rho_test_dataset).flatten()[:,None]\nE_test_dataset = np.asarray(E_test_dataset).flatten()[:,None]\nu_test_dataset = np.asarray(u_test_dataset).flatten()[:,None]\n\nP_back_test=[]\nP_back_test=np.asarray(P_back_test)\nx_test=[]\nx_test=np.asarray(x_test)\n\nfor i in range(0, 6):\n P_back_value = 0.01*(35+10*i)*np.ones((101,1))\n P_back_test = np.concatenate((P_back_test, P_back_value), axis=None)\n x_value = 0.01*np.arange(0, 101, dtype=float).flatten()[:,None]\n x_test = np.concatenate((x_test, x_value), axis=None)\n\nP_back_test = P_back_test.flatten()[:,None]\nx_test = x_test.flatten()[:,None]\n\n# Prediction\nP_test_pred, rho_test_pred, u_test_pred, E_test_pred = predict(P_back_test, x_test)\n\n# Error\nP_test_error = np.linalg.norm(P_test_dataset-P_test_pred,2)/np.linalg.norm(P_test_dataset,2)\nprint(\"Test Error in P: \"+str(P_test_error))\nrho_test_error = np.linalg.norm(rho_test_dataset-rho_test_pred,2)/np.linalg.norm(rho_test_dataset,2)\nprint(\"Test Error in rho: \"+str(rho_test_error))\nu_test_error = np.linalg.norm(u_test_dataset-u_test_pred,2)/np.linalg.norm(u_test_dataset,2)\nprint(\"Test Error in u: \"+str(u_test_error))\nE_test_error = np.linalg.norm(E_test_dataset-E_test_pred,2)/np.linalg.norm(E_test_dataset,2)\nprint(\"Test Error in E: \"+str(E_test_error))\n\n#Plotting\na = 0\nb = 6\ns = 1\nval = 101*a\n\nfor i in range (101*a, 101*b, 101*s):\n plt.ylim(0, 1.0)\n plt.plot(x_test[i:i+101], P_test_pred[i:i+101], 'c', label='Prediction' if i == val else \"\")\n plt.plot(x_test[i:i+101], P_test_dataset[i:i+101], 'g', label='Truth' if i == val else \"\")\n plt.title('Comparison of PINN results for Pressure')\n plt.xlabel('Nozzle Length')\n plt.ylabel('value')\n plt.legend(loc='center left')\nplt.show()\n\nfor i in range (101*a, 101*b, 101*s):\n plt.plot(x_test[i:i+101], E_test_pred[i:i+101], 'b', label='Prediction' if i == val else \"\")\n plt.plot(x_test[i:i+101], E_test_dataset[i:i+101], 'g', label='Truth' if i == val else \"\")\n plt.title('Comparison of PINN results for Energy')\n plt.xlabel('Nozzle Length')\n plt.ylabel('value')\n plt.legend()\nplt.show()\n\nfor i in range (101*a, 101*b, 101*s):\n plt.plot(x_test[i:i+101], u_test_pred[i:i+101], 'c', label='Prediction' if i == val else \"\")\n plt.plot(x_test[i:i+101], u_test_dataset[i:i+101], 'g', label='Truth' if i == val else \"\")\n plt.title('Comparison of PINN results for speed')\n plt.xlabel('Nozzle Length')\n plt.ylabel('value')\n plt.legend()\nplt.show()\n\nfor i in range (101*a, 101*b, 101*s):\n plt.plot(x_test[i:i+101], rho_test_pred[i:i+101], 'y', label='Prediction' if i == val else \"\")\n plt.plot(x_test[i:i+101], rho_test_dataset[i:i+101], 'g', label='Truth' if i == val else \"\")\n plt.title('Comparison of PINN results for density')\n plt.xlabel('Nozzle Length')\n plt.ylabel('value')\n plt.legend()\nplt.show()\n\n# for i in range (101*a, 101*b, 101*s):\n# plt.ylim(0, 0.05)\n# plt.plot(z_test[i:i+101], ((P_test[i:i+101]-P_pred[i:i+101])**2 + (u_test[i:i+101]-u_pred[i:i+101])**2 +\n# (E_test[i:i+101]-E_pred[i:i+101])**2 + (rho_test[i:i+101]-rho_pred[i:i+101])**2)/4, 'y', label='PINN Mean square Error')\n# flux1 = (rho_pred*u_pred*S).reshape((606, ))\n# flux2 = ((rho_pred*u_pred**2+ P_pred)*S).reshape((606, ))\n# flux3 = ((rho_pred*E_pred+P_pred)*u_pred*S).reshape((606, ))\n# S = S.reshape((606, ))\n# P_pred = P_pred.reshape((606, ))\n# P_pred = P_pred.reshape((606, ))\n# P_pred = P_pred.reshape((606, ))\n# E_pred = E_pred.reshape((606, ))\n# gamma = 1.4\n# plt.plot(z_test[i:i+101], ((np.gradient(flux1[i:i+101]))**2 +\n# (np.gradient(flux2[i:i+101])-P_pred[i:i+101]*np.gradient(S[i:i+101]))**2 +\n# (np.gradient(flux3[i:i+101]))**2)/3, 'k', label='PINN Mean square residual')\n# plt.xlabel('Nozzle Length')\n# plt.ylabel('value')\n# plt.legend(loc='center left')\n# plt.show()\n\n# #ideal gas eq\n# gamma = 1.4\n# RHS = rho_pred*(gamma-1)*(E_pred-0.5*u_pred*gamma*u_pred)\n# for i in range (101*a, 101*b, 101*s):\n# plt.plot(z_test[i:i+101], RHS[i:i+101], 'kx', label='NN')\n# plt.plot(z_test[i:i+101], P_pred[i:i+101], 'g', label='Truth')\n# plt.title('Ideal Gas Equation')\n# plt.xlabel('Nozzle Length')\n# plt.ylabel('value')\n# plt.legend()\n# plt.show()" }, { "alpha_fraction": 0.6206896305084229, "alphanum_fraction": 0.6896551847457886, "avg_line_length": 13.5, "blob_id": "65a94306b2d13994cae7bb00ee78b2d398dc2d0e", "content_id": "7b8cb97ee8405c8c83e9733b1182ab5a0d929399", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 29, "license_type": "no_license", "max_line_length": 16, "num_lines": 2, "path": "/README.md", "repo_name": "jhssyb/PINN--NUS", "src_encoding": "UTF-8", "text": "# PINN--NUS\n1D and 2D nozzle\n" }, { "alpha_fraction": 0.5091819763183594, "alphanum_fraction": 0.5415024757385254, "avg_line_length": 34.32075500488281, "blob_id": "db4d91a169199f84f516e79923e071cbaf1ab5cf", "content_id": "da701354dbacce4a43ad5c6698ce779409897030", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14975, "license_type": "no_license", "max_line_length": 154, "num_lines": 424, "path": "/1D-Nozzle/NN/PINNN/PINN.py", "repo_name": "jhssyb/PINN--NUS", "src_encoding": "UTF-8", "text": "import sys\nsys.path.insert(0, '../../Utilities/')\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io\nfrom scipy.interpolate import griddata\nimport time\nfrom itertools import product, combinations\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\n#from plotting import newfig, savefig\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport matplotlib.gridspec as gridspec\nimport csv\n\nnp.random.seed(1234)\ntf.set_random_seed(1234)\n\nclass PINN:\n # Initialize the class\n def __init__(self, P_back, x, P, rho, u, E, layers):\n \n X = np.concatenate([P_back, x], 1)\n \n self.lb = X.min(0)\n self.ub = X.max(0)\n self.X = X\n self.P_back = P_back\n self.x = x\n self.P = P\n self.rho = rho\n self.u = u\n self.E = E\n\n self.layers = layers\n \n # Initialize NN\n self.weights, self.biases = self.initialize_NN(layers) \n \n # tf placeholders and graph\n self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,\n log_device_placement=True))\n \n self.P_back_tf = tf.placeholder(tf.float32, shape=[None, self.P_back.shape[1]])\n self.x_tf = tf.placeholder(tf.float32, shape=[None, self.x.shape[1]])\n self.P_tf = tf.placeholder(tf.float32, shape=[None, self.P.shape[1]])\n self.rho_tf = tf.placeholder(tf.float32, shape=[None, self.rho.shape[1]])\n self.u_tf = tf.placeholder(tf.float32, shape=[None, self.u.shape[1]])\n self.E_tf = tf.placeholder(tf.float32, shape=[None, self.E.shape[1]])\n \n self.P_pred, self.rho_pred, self.u_pred, self.E_pred, self.e1, self.e2, self.e3, self.e4 = self.net_NS(self.P_back_tf, self.x_tf)\n\n # MSE Normalization\n P_norm = np.amax(P)\n rho_norm = np.amax(rho)\n u_norm = np.amax(u)\n E_norm = np.amax(E)\n S_norm = 5.95\n e1_norm = rho_norm*u_norm*S_norm\n e2_norm = P_norm*S_norm\n e3_norm = E_norm*rho_norm*u_norm*S_norm\n a = 40\n\n self.loss = tf.reduce_sum(tf.square(self.P_tf - self.P_pred))/(P_norm**2) + \\\n tf.reduce_sum(tf.square(self.rho_tf - self.rho_pred))/(rho_norm**2) + \\\n tf.reduce_sum(tf.square(self.u_tf - self.u_pred))/(u_norm**2) + \\\n tf.reduce_sum(tf.square(self.E_tf - self.E_pred))/(E_norm**2) + \\\n a*tf.reduce_sum(tf.square(self.e2))/(e2_norm**2) + \\\n a*tf.reduce_sum(tf.square(self.e3))/(e3_norm**2) + \\\n a*tf.reduce_sum(tf.square(self.e1))/(e1_norm**2) + \\\n a*tf.reduce_sum(tf.square(self.e4))/(P_norm**2)\n \n self.optimizer = tf.contrib.opt.ScipyOptimizerInterface(self.loss, \n method = 'L-BFGS-B', \n options = {'maxiter': 15000,\n 'maxfun': 15000,\n 'maxcor': 50,\n 'maxls': 50,\n 'ftol' : 1.0 * np.finfo(float).eps}) \n \n self.optimizer_Adam = tf.train.AdamOptimizer()\n self.train_op_Adam = self.optimizer_Adam.minimize(self.loss) \n \n init = tf.global_variables_initializer()\n self.sess.run(init)\n\n def initialize_NN(self, layers): \n weights = []\n biases = []\n num_layers = len(layers) \n for l in range(0,num_layers-1):\n W = self.xavier_init(size=[layers[l], layers[l+1]])\n b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32)\n weights.append(W)\n biases.append(b) \n return weights, biases\n \n def xavier_init(self, size):\n in_dim = size[0]\n out_dim = size[1] \n xavier_stddev = np.sqrt(2/(in_dim + out_dim))\n return tf.Variable(tf.truncated_normal([in_dim, out_dim], stddev=xavier_stddev), dtype=tf.float32)\n \n def neural_net(self, X, weights, biases):\n num_layers = len(weights) + 1\n \n H = 2.0*(X - self.lb)/(self.ub - self.lb) - 1.0\n for l in range(0,num_layers-2):\n W = weights[l]\n b = biases[l]\n H = tf.tanh(tf.add(tf.matmul(H, W), b))\n W = weights[-1]\n b = biases[-1]\n Y = tf.add(tf.matmul(H, W), b)\n return Y\n \n def net_NS(self, P_back, x):\n P_rho_u_E = self.neural_net(tf.concat([P_back, x], 1), self.weights, self.biases)\n P = P_rho_u_E[:,0:1]\n rho = P_rho_u_E[:,1:2]\n u = P_rho_u_E[:,2:3]\n E = P_rho_u_E[:,3:4]\n\n S = 1 + 2.2*(3*x-1.5)**2\n # autodiff gradient #1\n mass_flow_grad = tf.gradients(rho*u*S, x)[0]\n # autodiff gradient #2\n momentum_grad = tf.gradients((rho*u*u + P)*S, x)[0] - P*tf.gradients(S, x)[0]\n # autodiff gradient #3\n energy_grad = tf.gradients((rho*E + P)*u*S, x)[0]\n # state residual\n gamma = 1.4\n state_res = P - rho*(gamma-1)*(E-0.5*gamma*u*u)\n\n return P, rho, u, E, mass_flow_grad, momentum_grad, energy_grad, state_res\n \n def callback(self, loss):\n loss_vector.append(loss)\n print('Loss: %.3e' % (loss))\n \n def train(self, nIter): \n\n tf_dict = {self.P_back_tf: self.P_back, self.x_tf: self.x,\n self.P_tf: self.P, self.rho_tf: self.rho, self.u_tf: self.u, self.E_tf: self.E\n }\n \n global loss_vector\n loss_vector = []\n\n start_time = time.time()\n for it in range(nIter):\n self.sess.run(self.train_op_Adam, tf_dict)\n\n loss_value = self.sess.run(self.loss, tf_dict)\n\n loss_vector.append(loss_value)\n\n # Print\n if it % 1000 == 0:\n elapsed = time.time() - start_time\n # res1 = self.sess.run(self.e1, tf_dict)\n # res2 = self.sess.run(self.e2, tf_dict)\n # res3 = self.sess.run(self.e3, tf_dict)\n print('Iter: %d, Loss: %.3e, Time: %.2f' % \n (it, loss_value, elapsed))\n # print('Mass Residual: %f\\t\\tMomentum Residual: %f\\tEnergy Residual: %f'\n # %(sum(map(lambda a:a*a,res1))/len(res1), sum(map(lambda a:a*a,res2))/len(res2), sum(map(lambda a:a*a,res3))/len(res3)))\n start_time = time.time()\n \n # self.optimizer.minimize(self.sess,\n # feed_dict = tf_dict,\n # fetches = [self.loss],\n # loss_callback = self.callback)\n\n return loss_vector\n \n \n def predict(self, P_back_test, x_test):\n tf_dict = {self.P_back_tf: P_back_test, self.x_tf: x_test}\n P_test = self.sess.run(self.P_pred, tf_dict)\n rho_test = self.sess.run(self.rho_pred, tf_dict)\n u_test = self.sess.run(self.u_pred, tf_dict)\n E_test = self.sess.run(self.E_pred, tf_dict)\n return P_test, rho_test, u_test, E_test\n\n\nlayers = [2, 10, 10, 10, 4]\n\nP=[]\nrho=[]\nE=[]\nu=[]\n\nwith open('cdn_P.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for e in row:\n P.append(float(e))\n\nwith open('cdn_rho.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for e in row:\n rho.append(float(e))\n\nwith open('cdn_E.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for e in row:\n E.append(float(e))\n\nwith open('cdn_u.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for e in row:\n u.append(float(e))\n\nP = np.asarray(P)\nrho = np.asarray(rho)\nE = np.asarray(E)\nu = np.asarray(u)\n\npb=[]\npb=np.asarray(pb)\n\nz=[]\nz=np.asarray(z)\n\nfor i in range(0, 27):\n P_back = 0.01*(21+3*i)*np.ones((101,1))\n pb = np.concatenate((pb, P_back), axis=None)\n x_l = 0.01*np.arange(0, 101, dtype=float).flatten()[:,None]\n z = np.concatenate((z, x_l), axis=None)\n\ntrain_frac = 0.01\nN_train = int(train_frac*P.shape[0])\n\nA = np.random.choice(range(P.shape[0]), size=(N_train,), replace=False)\n\n# x\nP_back_train = pb[A].flatten()[:,None]\nx_train = z[A].flatten()[:,None]\n# y\nP_train = P[A].flatten()[:,None]\nrho_train = rho[A].flatten()[:,None]\nu_train = u[A].flatten()[:,None]\nE_train = E[A].flatten()[:,None]\n\n# Training\nmodel = PINN(P_back_train, x_train, P_train, rho_train, u_train, E_train, layers)\nmodel.train(20001)\n\n# plt.plot(loss_vector, label='Loss value')\n# print(\"Total Iter = \" + str(len(loss_vector)))\n# plt.legend()\n# plt.title('Loss value over iterations')\n# plt.xlabel('#iterations')\n# plt.ylabel('Loss')\n# plt.show()\n\n# Test Data\nP_test=[]\nrho_test=[]\nE_test=[]\nu_test=[]\n\nwith open('cdn_P_test.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for e in row:\n P_test.append(float(e))\n\nwith open('cdn_rho_test.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for e in row:\n rho_test.append(float(e))\n\nwith open('cdn_E_test.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for e in row:\n E_test.append(float(e))\n\nwith open('cdn_u_test.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for e in row:\n u_test.append(float(e))\n\nP_test = np.asarray(P_test).flatten()[:,None]\nrho_test = np.asarray(rho_test).flatten()[:,None]\nE_test = np.asarray(E_test).flatten()[:,None]\nu_test = np.asarray(u_test).flatten()[:,None]\n\n\npb_test=[]\npb_test=np.asarray(pb_test)\n\nz_test=[]\nz_test=np.asarray(z_test)\n\nfor i in range(0, 6):\n P_back = 0.01*(35+10*i)*np.ones((101,1))\n pb_test = np.concatenate((pb_test, P_back), axis=None)\n x_l = 0.01*np.arange(0, 101, dtype=float).flatten()[:,None]\n z_test = np.concatenate((z_test, x_l), axis=None)\n\npb_test = pb_test.flatten()[:,None]\nz_test = z_test.flatten()[:,None]\n\n# Prediction\nP_pred, rho_pred, u_pred, E_pred = model.predict(pb_test, z_test)\n\n# Error\nerror_P = np.linalg.norm(P_test-P_pred,2)/np.linalg.norm(P_test,2)\nprint(\"Test Error in P: \"+str(error_P))\nerror_rho = np.linalg.norm(rho_test-rho_pred,2)/np.linalg.norm(rho_test,2)\nprint(\"Test Error in rho: \"+str(error_rho))\nerror_u = np.linalg.norm(u_test-u_pred,2)/np.linalg.norm(u_test,2)\nprint(\"Test Error in u: \"+str(error_u))\nerror_E = np.linalg.norm(E_test-E_pred,2)/np.linalg.norm(E_test,2)\nprint(\"Test Error in E: \"+str(error_E))\n\n#Plotting\na = 2\nb = 3\ns = 1\nval = 101*a\n\nS = 1 + 2.2*(3*z_test-1.5)**2\n# rho_u_pred = rho_pred*u_pred\n# rho_E_pred = rho_pred*E_pred\n# rho_u_test = rho_test*u_test\n# rho_E_test = rho_test*E_test\n\nfor i in range (101*a, 101*b, 101*s):\n plt.ylim(0, 1.0)\n plt.plot(z_test[i:i+101], P_pred[i:i+101], 'c', label='PINN' if i == val else \"\")\n plt.plot(z_test[i:i+101], P_test[i:i+101], 'g', label='Truth' if i == val else \"\")\n plt.title('Comparison of PINN results for Pressure')\n plt.xlabel('Nozzle Length')\n plt.ylabel('value')\n plt.legend(loc='center left')\nplt.show()\n\nfor i in range (101*a, 101*b, 101*s):\n plt.plot(z_test[i:i+101], E_pred[i:i+101], 'b', label='PINN' if i == val else \"\")\n plt.plot(z_test[i:i+101], E_test[i:i+101], 'g', label='Truth' if i == val else \"\")\n plt.title('Comparison of PINN results for Energy')\n plt.xlabel('Nozzle Length')\n plt.ylabel('value')\n plt.legend()\nplt.show()\n\nfor i in range (101*a, 101*b, 101*s):\n plt.plot(z_test[i:i+101], u_pred[i:i+101], 'c', label='PINN' if i == val else \"\")\n plt.plot(z_test[i:i+101], u_test[i:i+101], 'g', label='Truth' if i == val else \"\")\n plt.title('Comparison of PINN results for speed')\n plt.xlabel('Nozzle Length')\n plt.ylabel('value')\n plt.legend()\nplt.show()\n\nfor i in range (101*a, 101*b, 101*s):\n plt.plot(z_test[i:i+101], rho_pred[i:i+101], 'y', label='PINN' if i == val else \"\")\n plt.plot(z_test[i:i+101], rho_test[i:i+101], 'g', label='Truth' if i == val else \"\")\n plt.title('Comparison of PINN results for density')\n plt.xlabel('Nozzle Length')\n plt.ylabel('value')\n plt.legend()\nplt.show()\n\n# for i in range (101*a, 101*b, 101*s):\n# plt.plot(z_test[i:i+101], rho_u_pred[i:i+101], 'y', label='PINN' if i == val else \"\")\n# plt.plot(z_test[i:i+101], rho_u_test[i:i+101], 'g', label='Truth' if i == val else \"\")\n# plt.title('Comparison of PINN results for rho_U')\n# plt.xlabel('Nozzle Length')\n# plt.ylabel('value')\n# plt.legend()\n# plt.show()\n\n# for i in range (101*a, 101*b, 101*s):\n# plt.plot(z_test[i:i+101], rho_E_pred[i:i+101], 'y', label='PINN' if i == val else \"\")\n# plt.plot(z_test[i:i+101], rho_E_test[i:i+101], 'g', label='Truth' if i == val else \"\")\n# plt.title('Comparison of PINN results for rho_E')\n# plt.xlabel('Nozzle Length')\n# plt.ylabel('value')\n# plt.legend()\n# plt.show()\n\n# for i in range (101*a, 101*b, 101*s):\n# plt.ylim(0, 0.05)\n# plt.plot(z_test[i:i+101], ((P_test[i:i+101]-P_pred[i:i+101])**2 + (u_test[i:i+101]-u_pred[i:i+101])**2 +\n# (E_test[i:i+101]-E_pred[i:i+101])**2 + (rho_test[i:i+101]-rho_pred[i:i+101])**2)/4, 'y', label='PINN Mean square Error')\n# flux1 = (rho_pred*u_pred*S).reshape((606, ))\n# flux2 = ((rho_pred*u_pred**2+ P_pred)*S).reshape((606, ))\n# flux3 = ((rho_pred*E_pred+P_pred)*u_pred*S).reshape((606, ))\n# S = S.reshape((606, ))\n# P_pred = P_pred.reshape((606, ))\n# P_pred = P_pred.reshape((606, ))\n# P_pred = P_pred.reshape((606, ))\n# E_pred = E_pred.reshape((606, ))\n# gamma = 1.4\n# plt.plot(z_test[i:i+101], ((np.gradient(flux1[i:i+101]))**2 +\n# (np.gradient(flux2[i:i+101])-P_pred[i:i+101]*np.gradient(S[i:i+101]))**2 +\n# (np.gradient(flux3[i:i+101]))**2)/3, 'k', label='PINN Mean square residual')\n# plt.xlabel('Nozzle Length')\n# plt.ylabel('value')\n# plt.legend(loc='center left')\n# plt.show()\n\n# #ideal gas eq\n# gamma = 1.4\n# RHS = rho_pred*(gamma-1)*(E_pred-0.5*u_pred*gamma*u_pred)\n# for i in range (101*a, 101*b, 101*s):\n# plt.plot(z_test[i:i+101], RHS[i:i+101], 'kx', label='NN')\n# plt.plot(z_test[i:i+101], P_pred[i:i+101], 'g', label='Truth')\n# plt.title('Ideal Gas Equation')\n# plt.xlabel('Nozzle Length')\n# plt.ylabel('value')\n# plt.legend()\n# plt.show()" } ]
9
ncrousset/dataStructures
https://github.com/ncrousset/dataStructures
a161276e1355929b48421bde40f1cebaa862bdbf
dba53c861b617858f4d75d69da7317c903049e5b
a00dcf7e53cee01d793d674547f721edc647b15a
refs/heads/master
2021-01-05T08:10:13.172021
2020-02-17T19:11:50
2020-02-17T19:11:50
240,945,990
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6416621804237366, "alphanum_fraction": 0.6632487773895264, "avg_line_length": 19.36263656616211, "blob_id": "43cd3b6cb33ab75795c897f435d043974a2034f8", "content_id": "5c5f228ad855d5eb43f49d8b7562d1349c8e41bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1853, "license_type": "no_license", "max_line_length": 52, "num_lines": 91, "path": "/list/app.py", "repo_name": "ncrousset/dataStructures", "src_encoding": "UTF-8", "text": "\"\"\"\nDefiniendo y utilizando algunas funciones\nmas comunes y uliles de lista\n\"\"\"\nmyList = [1,2,3]\n\ndef title(label):\n print(f\"------{label}------\")\n\ndef labelWithList(myList, label=\"Origin\"):\n strList = '[' + ','.join(map(str, myList)) + ']'\n print(f\"{label} = {strList}\")\n\n# agregar un elemento al final\ntitle('append()')\nlabelWithList(myList)\nmyList.append(5)\nlabelWithList(myList, \"Now\")\nprint('\\n')\n\n# Agregando un elemento con su indice\ntitle('insert()')\nlabelWithList(myList)\nmyList.insert(0,0)\nlabelWithList(myList, \"Now\")\nprint('\\n')\n\n# extender la lista con otra lista\ntitle('extend()')\nlabelWithList(myList)\nmyList.extend([6,7,8])\nlabelWithList(myList, \"Now\")\nprint('\\n')\n\n# extender con :\ntitle('extend with \":\"')\nlabelWithList(myList)\nmyList[3:4] = [10,11, 12]\nlabelWithList(myList, \"Now\")\nprint('\\n')\n\n# clear\ntitle('clear()')\nlabelWithList(myList)\nmyList.clear()\nlabelWithList(myList, \"Now\")\nprint('\\n')\n\n# del()\ntitle('del')\nmyList = [1,2,3]\nlabelWithList(myList)\ndel myList[1:]\nlabelWithList(myList, \"Now\")\ndel myList[:]\nlabelWithList(myList, \"Now Del all\")\nprint('\\n')\n\n# count()\nmyList = ['one','one', 'two', 'three', 'five']\nprint(f\"Out of count(): {myList.count('one')}\")\nprint('\\n')\n\n# index() get the first element\nprint(f\"Out of index(): {myList.index('one')}\")\nprint('\\n')\n\n# sort()\ntitle('sort()')\nmyList = [1, 4, 3, 5, 2]\nlabelWithList(myList)\nmyList.sort()\nlabelWithList(myList, \"Now\")\n\ntitle('sort(reverse=True)')\nmyList = [1, 4, 3, 5, 2]\nlabelWithList(myList)\n# myList = sorted(myList, reverse=True)\nmyList.sort(reverse=True)\nlabelWithList(myList, \"Now\")\nprint('\\n')\n\n# take the second element for sort\ndef take_second(elem):\n return elem[1]\n# random list\nrandom = [(2, 2), (3, 4), (4, 1), (1, 3)]\n# sort list with key\nsorted_list = sorted(random, key=take_second)\n# print list\nprint('Sorted list:', sorted_list)\n" } ]
1
FreddieAbad/Reglas-de-Asociacion-y-KMeans
https://github.com/FreddieAbad/Reglas-de-Asociacion-y-KMeans
affa1a326d92359fe40a66518b42d3975c99baba
3e8e4379261017f8c07b6ef52ecbd889f5fcec1f
eea0f006683a050bacc959fc0e2f9b6ffdc7b8f6
refs/heads/master
2020-04-22T01:18:01.339691
2019-08-12T15:53:45
2019-08-12T15:53:45
170,010,290
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7970296740531921, "alphanum_fraction": 0.7970296740531921, "avg_line_length": 24.25, "blob_id": "e977708da6de05d316575e88245fc2831c911565", "content_id": "064378c484b61dcce0f3e41b2e70959cde81be53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 205, "license_type": "no_license", "max_line_length": 33, "num_lines": 8, "path": "/README.md", "repo_name": "FreddieAbad/Reglas-de-Asociacion-y-KMeans", "src_encoding": "UTF-8", "text": "# Reglas-de-Asociacion-y-KMeans\n### English Version\nAssociation Rules and KMeans\nImplementation in Python and Java\n\n### Version en Español\nReglas de Asociación y K Means\nImplementación en Python y Java\n" }, { "alpha_fraction": 0.6265560388565063, "alphanum_fraction": 0.6286306977272034, "avg_line_length": 26.542856216430664, "blob_id": "6a0964c23f3c318371ae4f752d3778d7c33cbb0d", "content_id": "60643cecce35631dc408806ff6e262a6d368c148", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 964, "license_type": "no_license", "max_line_length": 86, "num_lines": 35, "path": "/AsociationRules/src/metrics/transformFiles.java", "repo_name": "FreddieAbad/Reglas-de-Asociacion-y-KMeans", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage metrics;\n\nimport au.com.bytecode.opencsv.CSVReader;\nimport java.io.FileNotFoundException;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.List;\n\n/**\n *\n * @author ediss\n */\npublic class transformFiles {\n public static void main(String[] args) throws FileNotFoundException, IOException {\n CSVReader reader = new CSVReader(new FileReader(\"file.csv\"),';');\n\t\n List<String[]> transacciones = reader.readAll();\n String[] cabeceras = transacciones.get(0);\n transacciones.remove(0);\n \n for (String s[] : transacciones) {\n for (String st : s) {\n System.out.print(st+\"\\t\");\n }\n System.out.println(\"\");\n }\n System.out.println(\"\\n\");\n \n }\n}\n" }, { "alpha_fraction": 0.6383689641952515, "alphanum_fraction": 0.6490641832351685, "avg_line_length": 25.660715103149414, "blob_id": "d43bfccbd6550c45cf5c785476a6f3247255845c", "content_id": "5bead0728564811139ed20a6e6d2f1749ad0e5ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1496, "license_type": "no_license", "max_line_length": 86, "num_lines": 56, "path": "/K-Means Python/means/k-means.py", "repo_name": "FreddieAbad/Reglas-de-Asociacion-y-KMeans", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as pyplot\nprint(\"fsdf\")\ndf = pd.read_csv('iris.csv')\n#print(df.header)\ndf['e'] = pd.factorize(df['e'])[0] +1\nprint(df['e'])\ncluster_df = df\ncluster_df = cluster_df.drop(columns=\"e\")\nprint(cluster_df)\ncluster_df = (cluster_df - cluster_df.mean() ) / (cluster_df.max() - cluster_df.min())\nprint(cluster_df)\nprint(cluster_df.iloc[1])\n\nnp.array(cluster_df.iloc[1])\ncentroides = np.random.rand(3,4)\nk = 3\n\niteraciones = 100\nprint(centroides)\nfor i in range(1):\n clasificacion = {}\n claseResult = []\n for i in range(k):\n clasificacion[i] = []\n\n for row in range(cluster_df.shape[0]):\n row_data = np.array(cluster_df.iloc[row])\n distancias = []\n for i in range(k):\n distancias.append(np.linalg.norm(row_data - centroides[i]))\n clase = distancias.index(min(distancias))\n claseResult.append(clase)\n clasificacion[clase].append(row_data)\n\n for i in range(k):\n centroides[clase] = np.average(clasificacion[clase], axis=0)\n # Actualizacion centroides\nclaseResult_df = pd.DataFrame(claseResult)\nprint(claseResult_df)\nnew_df = df.join(claseResult_df)\nprint(new_df)\n\nnew_df['COMPARACION'] = np.where(new_df['e'] == new_df[0], 'SI', 'NO')\nprint(new_df)\nconf_matrix = np.array((k,k))\nprint(conf_matrix)\n\ndf_confusion = pd.crosstab(new_df['e'], new_df[0])\n\nprint(df_confusion)\n\ndf_confusion = pd.crosstab(new_df['e'], new_df[0])\n\nprint(df_confusion)\n\n\n\n" }, { "alpha_fraction": 0.45850950479507446, "alphanum_fraction": 0.4805760979652405, "avg_line_length": 34.195350646972656, "blob_id": "79b1e5ab3a2262cff1d5ad396e1c14c75271666d", "content_id": "82b36e549414d17357f3af6a2c489888b5a91ce3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7569, "license_type": "no_license", "max_line_length": 93, "num_lines": 215, "path": "/K-Means Java/src/kmeans/kmeans.java", "repo_name": "FreddieAbad/Reglas-de-Asociacion-y-KMeans", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage kmeans;\n\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.util.ArrayList;\nimport java.util.List;\nimport au.com.bytecode.opencsv.CSVReader;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.util.Arrays;\n\n/**\n *\n * @author ediss\n */\npublic class kmeans {\n \n public static void main(String[] args) throws FileNotFoundException, IOException {\n CSVReader reader = new CSVReader(new FileReader(\"bank-data-bien.csv\"),';');\n\tFileWriter writer = new FileWriter(\"out.csv\");\n\n Integer numReg=0, numVar=0, numClus=2;\n \n\tList<String[]> entradas = reader.readAll();\n String[] cabeceras = entradas.get(0);\n entradas.remove(0);\n \n numReg=entradas.size();\n numVar=cabeceras.length;\n \n System.out.println(\"\\t\\tDATOS\");\n System.out.println(\"Numero Registros: \"+numReg);\n System.out.println(\"Numero Atributos: \"+numVar);\n \n \n Double data[][] = new Double[numReg][numVar];\n \n for (int i = 0; i < entradas.size(); i++)\n for (int j = 0; j < entradas.get(i).length; j++)\n data[i][j]=Double.parseDouble(entradas.get(i)[j]);\n \n System.out.println(\"Registros\");\n System.out.println(Arrays.toString(cabeceras));\n System.out.println(Arrays.toString(data[0]));\n System.out.println(Arrays.toString(data[1]));\n System.out.println(\"...\\n\");\n \n \n System.out.println(\"\\t\\tCLUSTERING\");\n Integer al1 = (int)(Math.random()*(numReg+1));\n Integer al2 = (int)(Math.random()*(numReg+1));\n System.out.println(\"Numero Clusters: \"+numClus);\n Double c1[] = data[al1-1]; Double c2[] = data[al2-1];\n System.out.println(\"Centroide 1: (200)\\t-> \"+Arrays.toString(c1));\n System.out.println(\"Centroide 2: (400)\\t-> \"+Arrays.toString(c2));\n \n \n /*\n Double c1[] = data[199]; Double c2[] = data[399];\n System.out.println(\"Registro: \"+200+\"\\t-> \"+Arrays.toString(c1));\n System.out.println(\"Registro: \"+400+\"\\t-> \"+Arrays.toString(c2));\n */\n \n Integer asignClust[] = new Integer[numReg];\n //Arrays.fill(asignClust, 0.0);\n \n \n Integer distCentrMin[] = new Integer[numVar];\n Integer distCentr[][] = new Integer[numReg][2];\n Integer auxAsignClust[] = new Integer[numReg];\n \n ArrayList<Double []> cluster1 = null;\n ArrayList<Double []> cluster2 = null;\n \n \n Boolean fin=true;\n int it=1;\n \n while (fin) {\n \n cluster1 = new ArrayList<>();\n cluster2 = new ArrayList<>();\n \n System.out.println(\"\\n\\tITERACIÓN \"+it);\n \n \n for (int i = 0; i < numReg; i++) {\n //System.out.println(\"Registro: \"+(i+1));\n Double reg[] = data[i];\n //System.out.print(Arrays.toString(reg));\n \n //ENCONTRAR DISTANCIAS A LOS CENTROIDES\n Double dist1=0.0;\n for (int k = 0; k < reg.length; k++)\n dist1+=Math.pow(reg[k]-c1[k], 2); \n dist1=Math.sqrt(dist1);\n //System.out.println(\"Distancia Centroide 1: \"+dist1+\" \");\n \n Double dist2=0.0;\n for (int k = 0; k < reg.length; k++)\n dist2+=Math.pow(reg[k]-c2[k], 2); \n dist2=Math.sqrt(dist2);\n //System.out.println(\"Distancia Centroide 2: \"+dist2);\n \n if (dist1<dist2) {\n cluster1.add(reg);\n //System.out.println(\"Asignacion Cluster 1\");\n auxAsignClust[i]=1;\n } else {\n cluster2.add(reg);\n //System.out.println(\"Asignacion Cluster 2\");\n auxAsignClust[i]=2;\n }\n //System.out.println(\"\");\n }\n \n /*\n for (int i = 0; i < data.length; i++) {\n System.out.println(Arrays.toString(data[i])+\" Cluster: \"+auxAsignClust[i]);\n }\n */\n \n //IMPRESION CLUSTER 1\n /*System.out.println(\"CLUSTER 1\");\n for (Double [] reg: cluster1) {\n System.out.println(Arrays.toString(reg));\n }\n System.out.println(\"Catidad Registros: \"+cluster1.size());\n \n //IMPRESION CLUSTER 2\n System.out.println(\"\\nCLUSTER2\");\n for (Double [] reg: cluster2) {\n System.out.println(Arrays.toString(reg));\n }\n System.out.println(\"Catidad Registros: \"+cluster2.size());\n */\n \n \n //CALCULO NUEVOS CENTROIDES\n Double auxc1[] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}; \n Double auxc2[] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};\n \n //centroide 1\n //System.out.println(\"CLUSTER1\");\n for (int i = 0; i < cabeceras.length; i++) {\n Double media=0.0;\n for (Double [] reg: cluster1) {\n media+=reg[i];\n }\n //System.out.println(\"suma: \"+media);\n //System.out.println(\"num reg: \"+cluster1.size());\n media=media/cluster1.size();\n //System.out.println(\"media: \"+media+\"\\n\");\n auxc1[i]=media;\n }\n \n //centroide 2\n //System.out.println(\"CLUSTER 2\");\n for (int i = 0; i < cabeceras.length; i++) {\n Double media=0.0;\n for (Double [] reg: cluster2) {\n media+=reg[i];\n }\n //System.out.println(\"suma: \"+media);\n //System.out.println(\"num reg: \"+cluster2.size());\n media=media/cluster2.size();\n //System.out.println(\"media: \"+media+\"\\n\");\n auxc2[i]=media;\n }\n \n System.out.println(\"Asignaciones Anteriores\\t\"+Arrays.toString(asignClust));\n System.out.println(\"Asignaciones Actuales\\t\"+Arrays.toString(auxAsignClust));\n System.out.println(\"\");\n System.out.println(Arrays.toString(auxc1));\n System.out.println(Arrays.toString(auxc2));\n \n \n c1=auxc1;\n c2=auxc2;\n \n Integer cont=0;\n for (int i = 0; i < asignClust.length; i++) {\n if (asignClust[i]==auxAsignClust[i]) {\n cont++;\n }\n asignClust[i]=auxAsignClust[i];\n }\n \n if (cont==asignClust.length)\n fin=false; \n \n \n System.out.println(\"\\n\\n\\n\");\n \n \n it++; \n }\n \n \n for (int i = 0; i < data.length; i++) {\n System.out.println(Arrays.toString(data[i])+\" Cluster: \"+auxAsignClust[i]);\n }\n \n System.out.println(\"Cluster 1: \"+cluster1.size()+\" observaciones\");\n System.out.println(\"Cluster 2: \"+cluster2.size()+\" observaciones\");\n \n\t\n }\n \n}\n\n" } ]
4
XiaoxuanHEI/New_Data_On_The_Web
https://github.com/XiaoxuanHEI/New_Data_On_The_Web
655f9974f4744fa68183bb2e51454b649ffa20a7
9d1e016d9bb08a646480c2ea5c63b8a046857f0d
2d350a4ccf95dc10a049fc764791695bfbd9af66
refs/heads/master
2022-10-27T12:39:11.836888
2020-06-15T22:36:16
2020-06-15T22:36:16
272,556,837
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6078320145606995, "alphanum_fraction": 0.623723030090332, "avg_line_length": 24.08571434020996, "blob_id": "bbcd34fc14fd2eb86124b4d2d4396238a5eba30c", "content_id": "dc716afd4990e1c9405e834c55805a6256b16c03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1762, "license_type": "no_license", "max_line_length": 88, "num_lines": 70, "path": "/Lab5_BlockChain/merkle_tree.py", "repo_name": "XiaoxuanHEI/New_Data_On_The_Web", "src_encoding": "UTF-8", "text": "import json\nimport hashlib\n\n\nclass MerkleTree(object):\n\n def __init__(self):\n self.root = None\n self.nodes = [] # Stores all other nodes except the leaf nodes\n self.leaves = [] # List of leaves of the tree. Leaves contain the transactions\n\n def add_node(self, node):\n # Add new node\n self.nodes.append(node)\n\n def add_leaf(self, leaf):\n # Add new leaf node\n self.leaves.append(leaf)\n\n\n# You can use the classes for node and leaf or you can create your own.\n'''\nclass MerkleTreeNode(object):\n\n def __init__(self):\n self.index = None\n self.parent = None\n self.child_left = None\n self.child_right = None\n self.hash = None\n\n\nclass MerkleTreeLeaf(object):\n\n def __init__(self):\n self.index = None\n self.parent = None\n self.transaction = None\n self.hash = None\n\n\ndef create_hashList(transactions):\n # Using the Merkle algorithm build the tree from a list of transactions in the block\n # transactions is list of Transaction\n hashList = []\n for t in transactions:\n hashList.append(hashlib.sha256(t).hexdigest())\n return hashList\n\ndef create_merkle_tree(hashList):\n if len(hashList) == 1:\n return hashList[0]\n\n newHashList = []\n\n for i in range(0, len(hashList) - 1, 2):\n newHashList.append(dhash256(hashList[i], hashList[i + 1]))\n\n if len(hashList) % 2 == 1: # odd, hash last item twice\n newHashList.append(dhash256(hashList[-1], hashList[-1]))\n return create_merkle_tree(newHashList)\n\ndef dhash256(a, b):\n # due to big-endian / little-endian nonsense\n concat = a + b\n temp = hashlib.sha256(concat).digest()\n h = hashlib.sha256(temp).hexdigest()\n return h\n\n'''\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.448263555765152, "alphanum_fraction": 0.46955281496047974, "avg_line_length": 33.182926177978516, "blob_id": "3c7f0fabf140ff4b464258d7a9185823c8f214a4", "content_id": "8a00c0004d9d4ba9c218c84ea97557a4c694b6ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8415, "license_type": "no_license", "max_line_length": 79, "num_lines": 246, "path": "/Lab1_Password/crack.py", "repo_name": "XiaoxuanHEI/New_Data_On_The_Web", "src_encoding": "UTF-8", "text": "# Written with <3 by Julien Romero\n\nimport hashlib\nfrom sys import argv\nimport sys\nimport random\nimport itertools\nimport string\nif (sys.version_info > (3, 0)):\n from urllib.request import urlopen\n from urllib.parse import urlencode\nelse:\n from urllib2 import urlopen\n from urllib import urlencode\n\n\nclass Crack:\n \"\"\"Crack The general method used to crack the passwords\"\"\"\n\n def __init__(self, filename, name):\n \"\"\"__init__\n Initialize the cracking session\n :param filename: The file with the encrypted passwords\n :param name: Your name\n :return: Nothing\n \"\"\"\n self.name = name.lower()\n self.passwords = get_passwords(filename)\n\n def check_password(self, password):\n \"\"\"check_password\n Checks if the password is correct\n !! This method should not be modified !!\n :param password: A string representing the password\n :return: Whether the password is correct or not\n \"\"\"\n password = str(password)\n cond = False\n if (sys.version_info > (3, 0)):\n cond = hashlib.md5(bytes(password, \"utf-8\")).hexdigest() in \\\n self.passwords\n else:\n cond = hashlib.md5(bytearray(password)).hexdigest() in \\\n self.passwords\n if cond:\n \n\n '''args = {\"name\": self.name,\n \"password\": password}\n args = urlencode(args, \"utf-8\")\n page = urlopen('http://137.194.211.71:5000/' +\n 'submit?' + args)\n if b'True' in page.read():''' \n \n print(\"You found the password: \" + password)\n return True\n return False\n \n def evaluate(self):\n \"\"\"evaluate\n Retrieve the grade from the server,\n !! This method MUST not be modified !!\n \"\"\"\n args = {\"name\": self.name }\n args = urlencode(args, \"utf-8\")\n page = urlopen('http://137.194.211.71:5000/' +\n 'evaluate?' + args)\n print(\"Grade :=>> \" + page.read().decode('ascii').strip())\n\n def crack(self):\n \"\"\"crack\n Cracks the passwords. YOUR CODE GOES BELOW.\n \n We suggest you use one function per question. Once a password is found,\n it is memorized by the server, thus you can comment the call to the\n corresponding function once you find all the corresponding passwords.\n \"\"\"\n# self.bruteforce_digits()\n# self.bruteforce_letters()\n \n self.dictionary_passwords()\n self.dictionary_passwords_leet()\n self.dictionary_words_hyphen()\n self.dictionary_words_digits()\n self.dictionary_words_diacritics()\n self.dictionary_city_diceware()\n\n # self.social_google()\n # self.social_jdoe()\n \n def bruteforce_digits(self):\n for n in range(9999999999):\n self.check_password(n)\n# for i in range(1,9):\n# for j in itertools.product(list(string.digits), repeat = i):\n# self.check_password(j)\n \n \n def bruteforce_letters(self):\n n = \"\"\n for i in range(5):\n if i == 0:\n for a in range(65,123):\n n = chr(a)\n self.check_password(n)\n if i == 1:\n for a in range(65,123):\n for b in range(65,123):\n n = chr(a)+chr(b)\n self.check_password(n)\n if i == 2:\n for a in range(65,123):\n for b in range(65,123):\n for c in range(65,123):\n n = chr(a)+chr(b)+chr(c)\n self.check_password(n)\n if i == 3:\n for a in range(65,123):\n for b in range(65,123):\n for c in range(65,123):\n for d in range(65,123):\n n = chr(a)+chr(b)+chr(c)+chr(d)\n self.check_password(n)\n if i == 4:\n for a in range(65,123):\n for b in range(65,123):\n for c in range(65,123):\n for d in range(65,123):\n for e in range(65,123):\n n = chr(a)+chr(b)+chr(c)+chr(d)+chr(e)\n self.check_password(n)\n \n def dictionary_passwords(self):\n with open (\"10k-most-common.txt\") as f:\n content = f.readlines()\n content = [x.strip() for x in content]\n for n in content:\n print(n)\n self.check_password(n)\n \n def dictionary_passwords_leet(self):\n with open (\"10k-most-common.txt\") as f:\n content = f.readlines()\n content = [x.strip() for x in content]\n for n in content:\n n = n.replace('e','3')\n n = n.replace('l','1')\n n = n.replace('a','0')\n n = n.replace('i','1')\n n = n.replace('o','0')\n self.check_password(n)\n \n\n def dictionary_words_hyphen(self):\n with open (\"20k.txt\") as f:\n content = f.readlines()\n content = [x.strip() for x in content]\n for n in content:\n num = random.randint(1,3)\n for i in range(1, num+1):\n p = random.randint(0,len(n))\n n = n[0:p] + \"-\" + n[p:]\n self.check_password(n)\n \n def dictionary_words_digits(self):\n with open (\"20k.txt\") as f:\n content = f.readlines()\n content = [x.strip() for x in content]\n for n in content:\n if len(n) > 5: \n for a in range(10):\n for b in range(10):\n wd = n + str(a) + str(b)\n self.check_password(wd)\n\n def dictionary_words_diacritics(self):\n with open (\"10kfrench.txt\") as f:\n content = f.readlines()\n content = [x.strip() for x in content]\n for n in content:\n n = n.replace('é','e')\n n = n.replace('è','e')\n n = n.replace('ê','e')\n n = n.replace('à','a')\n n = n.replace('ç','c')\n n = n.replace('ï','i')\n n = n.replace('ô','o')\n self.check_password(n)\n \n def dictionary_city_diceware(self):\n with open (\"africa_capitals.txt\") as f:\n content = f.readlines()\n content = [x.strip() for x in content]\n num = random.randint(1,4)\n wd = \"\"\n l = []\n for n in content:\n l.append(n.lower())\n # print(l)\n for i in range(0,10000):\n for i in range(0,num): \n a = random.randint(0,5)\n b = random.randint(0,5)\n c = random.randint(0,5)\n index = a*6*6 + b*6 + c*1\n if index < len(n):\n wd = wd + l[index]\n #if wd != \"\":\n #print(wd)\n self.check_password(wd)\n wd = \"\" \n \n # def social_google(self):\n # pass\n \n # def social_jdoe(self):\n # pass\n\n\ndef get_passwords(filename):\n \"\"\"get_passwords\n Get the passwords from a file\n :param filename: The name of the file which stores the passwords\n :return: The set of passwords\n \"\"\"\n passwords = set()\n with open(filename, \"r\") as f:\n for line in f:\n passwords.add(line.strip())\n return passwords\n\n\nif __name__ == \"__main__\":\n name = \"hei\".lower()\n # This is the correct location on the moodle\n #encfile = \"../passwords2019/\" + name + \".enc\"\n \n # If you run the script on your computer: uncomment and fill the following \n # line. Do not forget to comment this line again when you submit your code\n # on the moodle.\n encfile = \"hei.enc\"\n \n # First argument is the password file, the second your name\n crack = Crack(encfile, name)\n if \"--eval\" in sys.argv: crack.evaluate()\n else: crack.crack()" }, { "alpha_fraction": 0.5619637966156006, "alphanum_fraction": 0.5776930451393127, "avg_line_length": 35.120689392089844, "blob_id": "1fcea3c32ec92b8a1f2da82a862f94ebaa21bd24", "content_id": "b7cafc9f3a1ec44da48c60514dddf7ee98b71fc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2098, "license_type": "no_license", "max_line_length": 138, "num_lines": 58, "path": "/Lab2_Instance Extraction/extractor.py", "repo_name": "XiaoxuanHEI/New_Data_On_The_Web", "src_encoding": "UTF-8", "text": "'''Extracts type facts from a wikipedia file\nusage: extractor.py wikipedia.txt output.txt\n\nEvery line of output.txt contains a fact of the form\n <title> TAB <type>\nwhere <title> is the title of the Wikipedia page, and\n<type> is a simple noun (excluding abstract types like\nsort, kind, part, form, type, number, ...).\n\nNote: the formatting of the output is already taken care of\nby our template, you just have to complete the function\nextractType below.\n\nIf you do not know the type of an entity, skip the article.\n(Public skeleton code)'''\n\nfrom Parser import Parser\nimport sys\nimport re\nimport nltk\n\nif len(sys.argv) != 3:\n print(__doc__)\n sys.exit(-1)\n\ndef extractType(content):\n # Code goes here\n searchObj1 = re.search( r'(.*) (is|was) (a|the) (name|type|kind|study) of (.*?).*', content, re.M|re.I)\n searchObj2 = re.search( r'(.*) (is|was|are) (a|an) (.*)', content, re.M|re.I)\n # searchObj2 = re.search( r'(.*) is the (.*?) .*', content, re.M|re.I)\n \n if searchObj1:\n # tokens = nltk.word_tokenize(searchObj1.group(5))\n # pos_tags = nltk.pos_tag(tokens)\n # for word,pos in pos_tags:\n # if (pos == 'NN' or pos == 'NNP' or pos == 'NNS' or pos == 'NNPS'): \n return searchObj1.group(5)\n elif searchObj2:\n tokens = nltk.word_tokenize(searchObj2.group(4))\n pos_tags = nltk.pos_tag(tokens)\n for i in range(len(pos_tags)):\n if i == len(pos_tags)-1:\n return pos_tags[i][0]\n elif ((pos_tags[i][1] == 'NN' or pos_tags[i][1] == 'NNP' or pos_tags[i][1] == 'NNS' or pos_tags[i][1] == 'NNPS')\n and (pos_tags[i+1][1] != 'NN' and pos_tags[i+1][1] != 'NNP' and pos_tags[i+1][1] != 'NNS' and pos_tags[i+1][1] != 'NNPS') \n and pos_tags[i+1][1] != 'POS'): \n return pos_tags[i][0]\n else:\n return None\n\n \n \n\nwith open(sys.argv[2], 'w', encoding=\"utf-8\") as output:\n for page in Parser(sys.argv[1]):\n typ = extractType(page.content)\n if typ:\n output.write(page.title + \"\\t\" + typ + \"\\n\")\n\n\n\n" }, { "alpha_fraction": 0.5468663573265076, "alphanum_fraction": 0.5551857948303223, "avg_line_length": 38.173912048339844, "blob_id": "f079e85d1107b9c147a1542de1c2d85db349651f", "content_id": "1967bcf8c37d545c24b1b073e5a0b16858de34d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1803, "license_type": "no_license", "max_line_length": 109, "num_lines": 46, "path": "/Lab5_BlockChain/blockchain.py", "repo_name": "XiaoxuanHEI/New_Data_On_The_Web", "src_encoding": "UTF-8", "text": "class Blockchain(object):\n\n def __init__(self):\n self.chain = [] # contains the blockchain\n self.wallets = dict() # Contains the amount of coin each user owns\n self.wallets[\"admin\"] = 100000000000000\n\n def add_block(self, block):\n # Add a block to the chain\n # It needs to check if a block is correct\n # Returns True if the block was added, False otherwise\n if block.is_proof_ready() and self.check_legal_transactions(block):\n self.chain.append(block)\n self.update_wallet(block)\n return True\n else:\n return False\n\n def update_wallet(self, block):\n # Update the values in the wallet\n # We assume the block is correct\n for t in block.transactions:\n if t.receiver in self.wallets:\n self.wallets[t.receiver] += t.amount\n else:\n self.wallets[t.receiver] = t.amount\n if t.sender in self.wallets:\n self.wallets[t.sender] -= t.amount \n\n def check_legal_transactions(self, block):\n # Check if the transactions of a block are legal given the current state\n # of the chain and the wallet\n # Returns a boolean\n is_first = True\n for t in block.transactions:\n if t.sender not in self.wallets:\n if is_first:\n print(\"The index of the first incorrect is: \" + str(t.index), end = \"\")\n is_first = False\n return False\n elif (self.wallets[t.sender] < t.amount):\n if is_first:\n print(\"The index of the first incorrect is in the transaction \" + str(t.index), end = \"\")\n is_first = False\n return False\n return True\n\n" }, { "alpha_fraction": 0.6036117672920227, "alphanum_fraction": 0.6081264019012451, "avg_line_length": 30.657142639160156, "blob_id": "57090eab03afeafa9b3783629529b2d1c2110ff9", "content_id": "f407fb43d42a8bede1fcc020fb4e73870df8946d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2215, "license_type": "no_license", "max_line_length": 112, "num_lines": 70, "path": "/Lab5_BlockChain/block_reader.py", "repo_name": "XiaoxuanHEI/New_Data_On_The_Web", "src_encoding": "UTF-8", "text": "import json\n\nfrom block_header import BlockHeader\nfrom transaction import Transaction\nfrom block import Block\nfrom blockchain import Blockchain\n\n\ndef read_header(header):\n # Implement these functions to help you\n # Takes a dictionary as an input\n return BlockHeader(header[\"index\"], header[\"previous_hash\"], header[\"timestamp\"], header[\"nonce\"])\n\ndef read_transaction(transaction):\n # Same above for transformation\n return Transaction(transaction[\"index\"],transaction[\"sender\"],transaction[\"receiver\"],transaction[\"amount\"])\n\ndef read_block(block):\n # Reads a block from a dictionary\n header = read_header(block[\"header\"])\n transactions = []\n for t in block[\"transactions\"]:\n transactions.append(read_transaction(t))\n return Block(header, transactions)\n\ndef read_block_json(block_json):\n # Reads a block in json format\n return read_block(json.loads(open(block_json, 'r').read()))\n\ndef read_chain(chain):\n # read the chain from a json str\n # Returns a list of Block\n # This method does not do any checking\n blocks = []\n for block in json.loads(chain):\n blocks.append(read_block(block))\n return blocks\n\n''' \nfor i in range (10):\n file = \"blocks_to_prove/block\" + str(i) + \".json\"\n with open(file, 'r') as load_f:\n block = read_block(json.load(load_f))\n print(\"For file\" + file +\": \")\n\n\nfor i in range(0,10):\n block_chain = Blockchain()\n file = \"blockchain_wallets/chain\" + str(i) + \".json\"\n with open(file,'r') as load_f:\n for block in read_chain(load_f.read()):\n block_chain.add_block(block)\n print(\"For \" + file + \" :\")\n for (k,v) in block_chain.wallets.items():\n print(k + \": \" + str(v))\n print(\"\")\n'''\n \nfor i in range(0,10):\n file = \"blockchain_incorrect/chain\" + str(i) + \".json\"\n with open(file,'r') as load_f:\n block_chain = Blockchain()\n index_error = 0\n print(\"For \" + file + \" :\")\n for block in read_chain(load_f.read()):\n if not block_chain.add_block(block):\n print(\" of the block \" + str(index_error))\n break\n else:\n index_error += 1" }, { "alpha_fraction": 0.5284271240234375, "alphanum_fraction": 0.5347763299942017, "avg_line_length": 35.86170196533203, "blob_id": "8bd72ddf5b01233d122322aced538bc7a2294a6f", "content_id": "4fac1371a83dfc4923e1690040cf953651af0383", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3465, "license_type": "no_license", "max_line_length": 70, "num_lines": 94, "path": "/Lab3_Disambiguation/disambiguate.py", "repo_name": "XiaoxuanHEI/New_Data_On_The_Web", "src_encoding": "UTF-8", "text": "usage='''\n Given as command line arguments\n (1) wikidataLinks.tsv \n (2) wikidataLabels.tsv\n (optional 2') wikidataDates.tsv\n (3) wikipedia-ambiguous.txt\n (4) the output filename'''\n'''writes lines of the form\n title TAB entity\n where <title> is the title of the ambiguous\n Wikipedia article, and <entity> is the \n wikidata entity that this article belongs to. \n It is OK to skip articles (do not output\n anything in that case). \n (Public skeleton code)'''\n\nimport sys\nimport re\nfrom Parser import Parser\nfrom simpleKB import SimpleKB\n\nwikidata = None\nif __name__ == \"__main__\":\n if len(sys.argv) is 5:\n dateFile = None\n wikipediaFile = sys.argv[3]\n outputFile = sys.argv[4]\n elif len(sys.argv) is 6:\n dateFile = sys.argv[3]\n wikipediaFile = sys.argv[4]\n outputFile = sys.argv[5]\n else:\n print(usage, file=sys.stderr)\n sys.exit(1)\n\n wikidata = SimpleKB(sys.argv[1], sys.argv[2], dateFile)\n \n# wikidata is here an object containing 4 dictionaries:\n## wikidata.links is a dictionary of type: entity -> set(entity).\n## It represents all the entities connected to a\n## given entity in the yago graph\n## wikidata.labels is a dictionary of type: entity -> set(label).\n## It represents all the labels an entity can have.\n## wikidata.rlabels is a dictionary of type: label -> set(entity).\n## It represents all the entities sharing a same label.\n## wikidata.dates is a dictionnary of type: entity -> set(date).\n## It represents all the dates associated to an entity.\n\n# Note that the class Page has a method Page.label(),\n# which retrieves the human-readable label of the title of an \n# ambiguous Wikipedia page.\n\n with open(outputFile, 'w', encoding=\"utf-8\") as output:\n for page in Parser(wikipediaFile):\n # DO NOT MODIFY THE CODE ABOVE THIS POINT\n # or you may not be evaluated (you can add imports).\n \n # YOUR CODE GOES HERE:\n output.write(page.title)\n output.write('\\t')\n contents = re.split(r'[,\\s.]\\s*',page.content)\n contents.pop(-1)\n maxi = 0\n entites = wikidata.rlabels[page.label()]\n for e in entites:\n count = 0\n words = set()\n words.update(re.split(r'[<>()\\s_,-]\\s*',e))\n words.discard('')\n words.discard('and')\n words.discard('of')\n for w in words:\n if w in contents:\n count = count + 3\n set_label = set()\n for s in wikidata.labels[e]:\n set_label.update(re.split(r'[(\\s),.]\\s*',s))\n if e in wikidata.links: \n for s in wikidata.links[e]:\n set_label.update(re.split(r'[<>()\\s_]\\s*',s))\n if e in wikidata.dates:\n for s in wikidata.dates[e]:\n set_label.update(re.split(r'[\"-]\\s*',s))\n set_label.discard('')\n for c in contents: \n for l in set_label:\n if c == l:\n count = count + 1\n if count > maxi:\n maxi = count\n entity = e\n output.write(entity)\n output.write('\\n')\n #pass\n" }, { "alpha_fraction": 0.6185628771781921, "alphanum_fraction": 0.6227545142173767, "avg_line_length": 33.77083206176758, "blob_id": "d59cb2fc4ebf1905167d2f14d27347a97e5e206b", "content_id": "6531802c1bbc329123bdf3ebbf8ee127c192fcbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1670, "license_type": "no_license", "max_line_length": 79, "num_lines": 48, "path": "/Lab5_BlockChain/block.py", "repo_name": "XiaoxuanHEI/New_Data_On_The_Web", "src_encoding": "UTF-8", "text": "import json\nimport hashlib\n#from merkle_tree import create_merkle_tree, create_hashList\n\n\nclass Block(object):\n\n def __init__(self, header, transactions):\n # Store everything internally\n # header is a BlockHeader and transactions is a list of Transaction\n # call create_merkle_tree function to store transactions in Merkle tree\n self.N_STARTING_ZEROS = 4\n self.header = header\n self.transactions = transactions\n # create_merkle_tree(create_hashList(transactions))\n\n def to_dict(self):\n # Turns the object into a dictionary\n # There are two fields: header and transactions\n # The values are obtained by using the to_dict methods\n block_dict = {}\n block_dict['header'] = self.header\n block_dict['transactions'] = self.transactions\n return block_dict\n\n def to_json(self):\n # Transforms into a json string\n # use the option sort_key=True to make the representation unique\n return json.dumps(self.to_dict(), sort_key=True)\n\n def is_proof_ready(self):\n # Check whether the block is proven\n # For that, make sure the hash begins by N_STARTING_ZEROS\n hash_value = self.header.get_hash()\n if hash_value[:self.N_STARTING_ZEROS] == \"0000\":\n return True\n else:\n return False\n\n def make_proof_ready(self):\n # Transforms the block into a proven block\n nonce = 0\n while not self.is_proof_ready():\n nonce += 1\n self.header.set_nonce(nonce)\n print(\"nonce: \" + str(nonce))\n print(\"hash value: \" + self.header.get_hash())\n print(\"\")\n\n" } ]
7
th3walkingdud3/CSV-Py-Compare
https://github.com/th3walkingdud3/CSV-Py-Compare
d851359710f68b4bab5357a4ab5518ec039ae9d7
eeb7afd9f7ff4b57ac57d4039ad9e9c851ebdf62
4a579eecacd3a0936872e430a4496b8279082225
refs/heads/master
2016-09-11T06:40:20.297082
2015-04-01T02:07:30
2015-04-01T02:07:30
33,159,870
0
0
null
2015-03-31T02:19:52
2015-04-01T01:44:09
2015-04-01T02:02:05
Python
[ { "alpha_fraction": 0.7200811505317688, "alphanum_fraction": 0.7241379022598267, "avg_line_length": 27.823530197143555, "blob_id": "98e8f163bf2602f272e6dc8d7cf2cc9154a48497", "content_id": "a47e39f8ca58626c023ae897c79c87a166e25a63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 493, "license_type": "no_license", "max_line_length": 130, "num_lines": 17, "path": "/README.md", "repo_name": "th3walkingdud3/CSV-Py-Compare", "src_encoding": "UTF-8", "text": "# CSV-Py-Compare\nUses Python to compare 2 .csv files, each with a single column of data.\n\nThis is very basic, currently. Built on Mac, run from CLI. \n\nIn it's current form, you must have a file structure set up as follows:\n\nroot-level\n\n addlist2.py - file\n Old-CSV - folder\n New-CSV - folder\n\n \nI would like to clean this up and eliminate the need for folders. I would also like to add a gui for drag and drop functionality.\n\nInstructions for current usage in addlist.py file.\n \n" }, { "alpha_fraction": 0.6702741980552673, "alphanum_fraction": 0.6753246784210205, "avg_line_length": 28.489360809326172, "blob_id": "a2ea98e547c97ad1c3043df4cf1b093c4e78aaeb", "content_id": "db3e585f639127f52df0a519205b20cee22cd88e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1386, "license_type": "no_license", "max_line_length": 82, "num_lines": 47, "path": "/addlist2.py", "repo_name": "th3walkingdud3/CSV-Py-Compare", "src_encoding": "UTF-8", "text": "import time , sys , csv , re , os , shutil\nfrom sys import argv\nfrom os import listdir\n#to use: python addlist2.py\n\n###Works in python 2.5 and 2.7###\nscript = argv\ntimestr = time.strftime(\"%Y-%m-%d\")\n\n#create some variables\nsuffix = \".csv\"\noldcsv = [f for f in os.listdir(\"Old-CSV/\") if f.endswith(suffix)]\nnewcsv = [f for f in os.listdir(\"New-CSV/\") if f.endswith(suffix)]\noldcsv = str(\"Old-CSV/\") + oldcsv[0]\nnewcsv = str(\"New-CSV/\") + newcsv[0]\n\n#create a new csv for cleaned values from old csv entered\no = open(\"first.csv\",\"w\")\ndata = open(oldcsv).read()\no.write( re.sub(\" \",\"\",data) )\no.close()\n\n#creat a new csv for cleaned values from new csv entered\nn = open(\"second.csv\",\"w\")\ndata = open(newcsv).read()\nn.write( re.sub(\" \",\"\",data) )\nn.close()\n\n#create csv of names to newToList/noLongerInList from group in $filename\nremove = open(\"noLongerInList.csv\",\"w\")\nadd = open(\"newToList.csv\",\"w\")\n\n#adds any names from first list not found in second list to the noLongerInList.csv\nfor line in open(\"first.csv\",\"r\"):\n if line not in open(\"second.csv\",\"r\"):\n remove.write(line)\nremove.close()\n\n#adds any names from second list not found in first list to the newToList.csv\nfor line in open (\"second.csv\",\"r\"):\n if line not in open(\"first.csv\",\"r\"):\n add.write(line)\nadd.close()\n\n#remove the generated \"clean\" csv files\nos.remove(\"first.csv\")\nos.remove(\"second.csv\")\n" } ]
2
lawliet0823/FaceTracking
https://github.com/lawliet0823/FaceTracking
7b8fb3a4d3178e52f17fee6d7fa732848cfb9bd3
af65b4822c81a2ac9ab4e7470b5e505f40a00f75
91edbfc8610c0e549abe958fcb6d8c934a587808
refs/heads/master
2021-05-03T09:44:36.897064
2016-10-29T15:08:20
2016-10-29T15:08:20
49,360,717
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6125927567481995, "alphanum_fraction": 0.6300380825996399, "avg_line_length": 24.24736785888672, "blob_id": "1da63948b1fc48e1923ebd2a5d8dab388d01098d", "content_id": "2af3a356382442cfa61f899831e1c7a780b9cc28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4987, "license_type": "no_license", "max_line_length": 144, "num_lines": 190, "path": "/Test.cpp", "repo_name": "lawliet0823/FaceTracking", "src_encoding": "UTF-8", "text": "#include <opencv2/core/core.hpp>\r\n#include <opencv2/highgui/highgui.hpp>\r\n#include <opencv2/objdetect/objdetect.hpp>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <cstdio>\r\n#include <sys/stat.h>\r\n#include \"tld_utils.h\"\r\n#include \"TLD.h\"\r\n\r\n//#include \"CompressiveTracker.h\"\r\n\r\nusing namespace cv;\r\nusing namespace std;\r\n\r\nstruct TLD_Info {\r\n\tTLD *tld;\r\n\tint dirCounter;\r\n\tint fileCounter;\r\n};\r\n\r\n// Global Variables\r\n// Face model\r\nconst String face_cascade_name = \"haarcascade_frontalface_alt.xml\";\r\n\r\nvoid read_options(int, char**,VideoCapture&,int&);\r\nvoid createDirectory(VideoCapture&, FileStorage&, Mat&, vector<Rect>&, vector<TLD_Info>&, int&);\r\nvoid setTLD_Info(TLD_Info&, TLD*, int, int);\r\nvoid freeTLD_Info(vector<TLD_Info> &);\r\nvector<Rect> faceDetection(Mat);\r\n\r\nint main(int argc, char** argv)\r\n{\r\n\t// parameters setting\r\n\tVideoCapture capture;\r\n\t//vector<TLD*> vTLD;\r\n\tvector<TLD_Info> vtld_info;\r\n\tFileStorage fs;\r\n\tfs.open(\"parameters.yml\", FileStorage::READ);\r\n\tint skip_msecs = 0;\r\n\tint dirCounter = 1;\r\n\r\n\t// get program parameters\r\n\tread_options(argc, argv, capture, skip_msecs);\r\n\r\n\tif (!capture.isOpened()) {\r\n\t\tcout << \"VideoCapture Fail !!!\" << endl;\r\n\t\treturn 1;\r\n\t}\r\n\r\n\t//namedWindow(\"Test\", WINDOW_AUTOSIZE);\r\n\tcapture.set(CV_CAP_PROP_POS_MSEC, skip_msecs); // The big bang theory\r\n\t//capture.set(CV_CAP_PROP_POS_MSEC, 1400000); // Sherlock\r\n\r\n\tMat frame;\r\n\tMat last_gray;\r\n\tvector<Rect> faces;\r\n\r\n\tcreateDirectory(capture, fs, last_gray, faces, vtld_info, dirCounter);\r\n\r\n\tMat current_gray;\r\n\tBoundingBox pbox;\r\n\tvector<Point2f> pts1;\r\n\tvector<Point2f> pts2;\r\n\tbool status = true;\r\n\tbool tl = true;\r\n\r\n\tint remainFrame = 3;\r\n\r\n\twhile (capture.read(frame)) {\r\n\t\tcvtColor(frame, current_gray, CV_RGB2GRAY);\r\n\r\n\t\tif(remainFrame != 0){\r\n\t\t\tint correct_num = 0;\r\n\t\t\tfor(size_t i = 0; i < vtld_info.size(); i++) {\r\n\t\t\t\tchar filePath[30];\r\n\t\t\t\tmemset(filePath, '\\0', 30);\r\n\t\t\t\tTLD_Info tempTLD_Info = vtld_info[i];\r\n\t\t\t\ttempTLD_Info.tld->processFrame(last_gray, current_gray, pts1, pts2, pbox, status, tl);\r\n\r\n\t\t\t\t// success tracking\r\n\t\t\t\tif (status) {\r\n\t\t\t\t\tpbox.x = pbox.x - 20;\r\n\t\t\t\t\tpbox.y = pbox.y - 20;\r\n\t\t\t\t\tpbox.width = pbox.width + 40;\r\n\t\t\t\t\tpbox.height = pbox.height + 40;\r\n\t\t\t\t\tMat face_image = frame(pbox);\r\n\t\t\t\t\tsprintf(filePath, \"./Crop_Image/%03d/%03d.jpg\", tempTLD_Info.dirCounter, tempTLD_Info.fileCounter);\r\n\t\t\t\t\timwrite(filePath, face_image);\r\n\t\t\t\t\t++tempTLD_Info.fileCounter;\r\n\t\t\t\t\tvtld_info[i] = tempTLD_Info;\r\n\t\t\t\t\t//drawPoints(frame, pts1);\r\n\t\t\t\t\t//drawPoints(frame, pts2, Scalar(0, 255, 0));\r\n\t\t\t\t\t//drawBox(frame, pbox);\r\n\t\t\t\t\tpts1.clear();\r\n\t\t\t\t\tpts2.clear();\r\n\t\t\t\t\t++correct_num;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif(correct_num == vtld_info.size()){\r\n\t\t\t\tremainFrame = 3;\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\t--remainFrame;\r\n\t\t\t}\r\n\t\t\tswap(last_gray, current_gray);\r\n\t\t}\r\n\t\telse{\r\n\t\t\t// erase vector\r\n\t\t\tvector<Point2f>().swap(pts1);\r\n\t\t\tvector<Point2f>().swap(pts2);\r\n\t\t\tfreeTLD_Info(vtld_info);\r\n\t\t\tvector<TLD_Info>().swap(vtld_info);\r\n\t\t\tvector<Rect>().swap(faces);\r\n\t\t\tcreateDirectory(capture, fs, last_gray, faces, vtld_info, dirCounter);\r\n\t\t\tremainFrame = 3;\r\n\t\t}\r\n\t\t//imshow(\"Test\", frame);\r\n\t\t//waitKey(1);\r\n\t}\r\n\tsystem(\"pause\");\r\n\treturn 0;\r\n}\r\n\r\nvoid read_options(int argc, char** argv, VideoCapture &capture, int &skip_msecs){\r\n\tfor(size_t i = 0; i < argc; i++) {\r\n\t\tif (strcmp(argv[i],\"-s\") == 0) {\r\n\t\t\tif (argc > i) {\r\n\t\t\t\tstring video = string(argv[i+1]);\r\n\t\t\t\tcapture.open(video);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(strcmp(argv[i], \"-t\") == 0) {\r\n\t\t\tif(argc > i) {\r\n\t\t\t\tskip_msecs = atoi(argv[i+1]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid createDirectory(VideoCapture &capture, FileStorage &fs, Mat &last_gray, vector<Rect> &faces, vector<TLD_Info> &vtld_info, int &dirCounter){\r\n\tMat frame;\r\n\twhile (faces.size() == 0) {\r\n\t\tcapture >> frame;\r\n\t\tcvtColor(frame, last_gray, CV_RGB2GRAY);\r\n\t\tfaces = faceDetection(last_gray);\r\n\t}\r\n\r\n\t// create directory && initialize TLD && set up parameters\r\n\tchar dirPath[30];\r\n\tmemset(dirPath, '\\0', 30);\r\n\tfor(size_t i = 0; i < faces.size(); i++) {\r\n\t\tTLD_Info tempTLD_Info;\r\n\t\tTLD *tempTLD = new TLD();\r\n\t\ttempTLD->read(fs.getFirstTopLevelNode());\r\n\t\ttempTLD->init(last_gray, faces[i]);\r\n\t\tsetTLD_Info(tempTLD_Info, tempTLD, dirCounter, 1);\r\n\t\tsprintf(dirPath, \"./Crop_Image/%03d/\", dirCounter);\r\n\t\tmkdir(dirPath, 0700);\r\n\t\t++dirCounter;\r\n\t\tvtld_info.push_back(tempTLD_Info);\r\n\t\t//vTLD.push_back(tld);\r\n\t}\r\n}\r\n\r\nvoid setTLD_Info(TLD_Info &tld_info, TLD *tld, int dirCounter, int fileCounter){\r\n\ttld_info.tld = tld;\r\n\ttld_info.dirCounter = dirCounter;\r\n\ttld_info.fileCounter = fileCounter;\r\n}\r\n\r\nvoid freeTLD_Info(vector<TLD_Info> &vtld_info){\r\n\tfor(size_t i = 0; i < vtld_info.size(); i++){\r\n\t\tdelete vtld_info[i].tld;\r\n\t}\r\n}\r\n\r\nvector<Rect> faceDetection(Mat frame) {\r\n\tCascadeClassifier face_cascade;\r\n\tvector<Rect> faces;\r\n\r\n\tif (!face_cascade.load(face_cascade_name)) {\r\n\t\tprintf(\"Error Loading\");\r\n\t}\r\n\r\n\tface_cascade.detectMultiScale(frame, faces, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, cvSize(90, 90));\r\n\treturn faces;\r\n}\r\n" }, { "alpha_fraction": 0.5435897707939148, "alphanum_fraction": 0.5569230914115906, "avg_line_length": 25.69862937927246, "blob_id": "effaf2a6b09a2e248fbf3969ec26c21abe18edd2", "content_id": "d25f6bf4d2659d4e00880c66dd3eb5ba817375b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1950, "license_type": "no_license", "max_line_length": 88, "num_lines": 73, "path": "/LFW-Formulate.py", "repo_name": "lawliet0823/FaceTracking", "src_encoding": "UTF-8", "text": "\nimport os\nimport sys\nimport random\nimport math\nimport re\n\n\ndef split_data_to_train_test(src_folder):\n test_set = []\n train_set = []\n label = 1\n\n # get people_folder in dataset\n people_folders = os.listdir(src_folder)\n ordered_folders = sorted(people_folders, key=str)\n\n for people_folder in ordered_folders:\n # lfw/Aaron_Eckhart/\n people_path = src_folder + people_folder + '/'\n\n img_files = os.listdir(people_path)\n img_files = sorted(img_files, key=str)\n\n people_imgs = []\n\n # if image number is less than five, do nothing\n if(len(img_files) < 5):\n continue\n\n for img_file in img_files:\n # lfw/Aaron_Eckhart/Aaron_Eckhart_0001.jpg\n img_path = people_path + img_file\n people_imgs.append((img_path, label))\n\n '''\n if len(people_imgs) < 20:\n #train_set += people_imgs\n label += 1\n continue\n '''\n train_set += people_imgs[0:len(people_imgs)]\n '''\n test_set += people_imgs[25:30]\n train_set += people_imgs[0:25]\n '''\n\n #train_set += people_imgs[0:len(people_imgs)]\n\n sys.stdout.write('\\rdone' + str(label))\n sys.stdout.flush()\n label += 1\n return test_set, train_set\n\n\ndef save_file(data_set, file_name):\n f = open(file_name, 'wb')\n for item in data_set:\n line = item[0] + ' ' + str(item[1]) + '\\n'\n f.write(line)\n f.close()\n\nif __name__ == '__main__':\n if len(sys.argv) != 4:\n print 'Usage: python %s src_folder test_set_file train_set_file' % (sys.argv[0])\n sys.exit()\n src_folder = sys.argv[1]\n test_set_file = sys.argv[2]\n train_set_file = sys.argv[3]\n if not src_folder.endswith('/'):\n src_folder += '/'\n test_set, train_set = split_data_to_train_test(src_folder)\n save_file(test_set, test_set_file)\n save_file(train_set, train_set_file)\n" }, { "alpha_fraction": 0.5326639413833618, "alphanum_fraction": 0.5476651191711426, "avg_line_length": 28.389705657958984, "blob_id": "3f64d2f9ffce422b9890de54432cf6a1098b5610", "content_id": "05e7393b2e2e6cdc26c077e203eb291d335189e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8266, "license_type": "no_license", "max_line_length": 80, "num_lines": 272, "path": "/FaceTracking_Modify.cpp", "repo_name": "lawliet0823/FaceTracking", "src_encoding": "UTF-8", "text": "#include \"TLD.h\"\r\n#include \"tld_utils.h\"\r\n#include <cstdio>\r\n#include <fstream>\r\n#include <iostream>\r\n#include <opencv2/core/core.hpp>\r\n#include <opencv2/highgui/highgui.hpp>\r\n#include <opencv2/objdetect/objdetect.hpp>\r\n#include <sstream>\r\n#include <sys/stat.h>\r\n\r\n//#include \"CompressiveTracker.h\"\r\n\r\nusing namespace cv;\r\nusing namespace std;\r\n\r\nstruct TLD_Info {\r\n TLD *tld;\r\n int dirCounter;\r\n int fileCounter;\r\n int remainFrame;\r\n};\r\n\r\n// Global Variables\r\n// Face model\r\nconst String face_cascade_name = \"haarcascade_frontalface_alt.xml\";\r\n\r\nvoid read_options(int, char **, VideoCapture &, int &, string &);\r\n// Initialize TLD tracker, Information, File Directory\r\nvoid createDirectory(VideoCapture &, FileStorage &, Mat &, vector<Rect> &,\r\n vector<TLD_Info> &, int &, double &, string);\r\nvoid setTLD_Info(TLD_Info &, TLD *, int, int, int);\r\nvoid freeTLD_Info(vector<TLD_Info> &);\r\nvector<Rect> faceDetection(Mat);\r\n\r\nint main(int argc, char **argv) {\r\n // parameters setting\r\n VideoCapture capture;\r\n // vector<TLD*> vTLD;\r\n vector<TLD_Info> vtld_info;\r\n FileStorage fs;\r\n fs.open(\"parameters.yml\", FileStorage::READ);\r\n int skip_msecs = 0;\r\n int dirCounter = 1;\r\n double frame_num = 0;\r\n string dirName = \"Crop_Image\";\r\n\r\n // get program parameters\r\n read_options(argc, argv, capture, skip_msecs, dirName);\r\n if (!capture.isOpened()) {\r\n cout << \"VideoCapture Fail !!!\" << endl;\r\n return 1;\r\n }\r\n capture.set(CV_CAP_PROP_POS_MSEC, skip_msecs);\r\n\r\n cout << \"Directory Name: \" << dirName << endl;\r\n // namedWindow(\"Test\", WINDOW_AUTOSIZE);\r\n\r\n Mat frame;\r\n Mat last_gray;\r\n // save detect face\r\n vector<Rect> faces;\r\n\r\n char mainDir[30];\r\n memset(mainDir, '\\0', 30);\r\n sprintf(mainDir, \"./%s/\", dirName.c_str());\r\n mkdir(mainDir, 0700);\r\n cout << \"Begin Tracking\" << endl;\r\n createDirectory(capture, fs, last_gray, faces, vtld_info, dirCounter,\r\n frame_num, dirName);\r\n\r\n Mat current_gray;\r\n BoundingBox pbox;\r\n vector<Point2f> pts1;\r\n vector<Point2f> pts2;\r\n bool status = true;\r\n bool tl = true;\r\n\r\n int remainFrame = 5;\r\n\r\n while (capture.read(frame)) {\r\n // frame_num += 3;\r\n // capture.set(CV_CAP_PROP_POS_FRAMES, frame_num);\r\n cvtColor(frame, current_gray, CV_RGB2GRAY);\r\n if (remainFrame > 0 && vtld_info.size() > 0) {\r\n // correct_num caculate how many faces should we track\r\n int correct_num = 0;\r\n for (size_t i = 0; i < vtld_info.size(); i++) {\r\n char filePath[30];\r\n memset(filePath, '\\0', 30);\r\n TLD_Info tempTLD_Info = vtld_info[i];\r\n tempTLD_Info.tld->processFrame(last_gray, current_gray, pts1, pts2,\r\n pbox, status, tl);\r\n\r\n // success tracking\r\n if (status) {\r\n if (pbox.x < 0 || pbox.y < 0 || (pbox.x + pbox.width) > frame.cols ||\r\n (pbox.y + pbox.height) > frame.rows) {\r\n delete vtld_info[i].tld;\r\n vtld_info.erase(vtld_info.begin() + i);\r\n continue;\r\n }\r\n\r\n Mat face_image = frame(pbox);\r\n\r\n // Test Code\r\n\r\n if (tempTLD_Info.fileCounter % 5 == 0) {\r\n vector<Rect>().swap(faces);\r\n faces = faceDetection(face_image);\r\n if (faces.size() == 0 && faces.size() != vtld_info.size()) {\r\n correct_num = -1; // if (correct_num != vtld_info.size()), stop\r\n // tracking\r\n remainFrame = -1;\r\n pts1.clear();\r\n pts2.clear();\r\n break;\r\n }\r\n }\r\n sprintf(filePath, \"./%s/%03d/%03d.jpg\", dirName.c_str(),\r\n tempTLD_Info.dirCounter, tempTLD_Info.fileCounter);\r\n imwrite(filePath, face_image);\r\n ++tempTLD_Info.fileCounter;\r\n vtld_info[i] = tempTLD_Info;\r\n // show video tracking state\r\n /*\r\n drawPoints(frame, pts1);\r\n drawPoints(frame, pts2, Scalar(0, 255, 0));\r\n drawBox(frame, pbox);\r\n imshow(\"Tracking\", frame);\r\n // char tempChar[20];\r\n // sprintf(tempChar, \"%f.jpg\", frame_num);\r\n // imwrite(tempChar, frame);\r\n if (waitKey(10) >= 0) {\r\n break;\r\n }\r\n */\r\n ++correct_num;\r\n } else {\r\n --correct_num;\r\n }\r\n }\r\n\r\n pts1.clear();\r\n pts2.clear();\r\n\r\n // if program can't detect\r\n if (correct_num == vtld_info.size()) {\r\n remainFrame = 5;\r\n } else {\r\n --remainFrame;\r\n }\r\n // swap frame\r\n // cout << \"Correct Number: \" << correct_num << \" Vector size \" <<\r\n // vtld_info.size() << \" Remain Frame: \" << remainFrame << endl;\r\n swap(last_gray, current_gray);\r\n } else {\r\n // erase vector\r\n vector<Point2f>().swap(pts1);\r\n vector<Point2f>().swap(pts2);\r\n freeTLD_Info(vtld_info);\r\n vector<TLD_Info>().swap(vtld_info);\r\n vector<Rect>().swap(faces);\r\n createDirectory(capture, fs, last_gray, faces, vtld_info, dirCounter,\r\n frame_num, dirName);\r\n remainFrame = 5;\r\n }\r\n // imshow(\"Test\", frame);\r\n // waitKey(1);\r\n }\r\n system(\"pause\");\r\n return 0;\r\n}\r\n\r\nvoid read_options(int argc, char **argv, VideoCapture &capture, int &skip_msecs,\r\n string &dirName) {\r\n for (size_t i = 0; i < argc; i++) {\r\n if (strcmp(argv[i], \"-s\") == 0) {\r\n if (argc > i) {\r\n string video = string(argv[i + 1]);\r\n capture.open(video);\r\n }\r\n }\r\n if (strcmp(argv[i], \"-t\") == 0) {\r\n if (argc > i) {\r\n skip_msecs = atoi(argv[i + 1]);\r\n }\r\n }\r\n if (strcmp(argv[i], \"-f\") == 0) {\r\n if (argc > i) {\r\n dirName = string(argv[i + 1]);\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid createDirectory(VideoCapture &capture, FileStorage &fs, Mat &last_gray,\r\n vector<Rect> &faces, vector<TLD_Info> &vtld_info,\r\n int &dirCounter, double &frame_num, string dirName) {\r\n Mat frame;\r\n while (faces.size() == 0) {\r\n capture >> frame;\r\n // frame_num += 3;\r\n // capture.set(CV_CAP_PROP_POS_FRAMES, frame_num);\r\n cvtColor(frame, last_gray, CV_RGB2GRAY);\r\n faces = faceDetection(last_gray);\r\n }\r\n\r\n // create directory && initialize TLD && set up parameters\r\n char dirPath[30];\r\n char filePath[30];\r\n memset(dirPath, '\\0', 30);\r\n memset(filePath, '\\0', 30);\r\n\r\n for (size_t i = 0; i < faces.size(); i++) {\r\n // increase face size to avoid detection fail\r\n faces[i].x = faces[i].x - 70;\r\n faces[i].y = faces[i].y - 70;\r\n faces[i].width = faces[i].width + 140;\r\n faces[i].height = faces[i].height + 140;\r\n if (faces[i].x < 0 || faces[i].y < 0 ||\r\n (faces[i].x + faces[i].width) > frame.cols ||\r\n (faces[i].y + faces[i].height) > frame.rows) {\r\n faces.erase(faces.begin() + i);\r\n continue;\r\n }\r\n\r\n TLD_Info tempTLD_Info;\r\n TLD *tempTLD = new TLD();\r\n tempTLD->read(fs.getFirstTopLevelNode());\r\n tempTLD->init(last_gray, faces[i]);\r\n // set TLD information: TLD dirCounter fileCounter remainFrame\r\n setTLD_Info(tempTLD_Info, tempTLD, dirCounter, 2, 4);\r\n sprintf(dirPath, \"./%s/%03d/\", dirName.c_str(), dirCounter);\r\n mkdir(dirPath, 0700);\r\n\r\n Mat face_image = frame(faces[i]);\r\n sprintf(filePath, \"./%s/%03d/%03d.jpg\", dirName.c_str(), dirCounter, 1);\r\n imwrite(filePath, face_image);\r\n\r\n ++dirCounter;\r\n vtld_info.push_back(tempTLD_Info);\r\n // vTLD.push_back(tld);\r\n }\r\n}\r\n\r\nvoid setTLD_Info(TLD_Info &tld_info, TLD *tld, int dirCounter, int fileCounter,\r\n int remainFrame) {\r\n tld_info.tld = tld;\r\n tld_info.dirCounter = dirCounter;\r\n tld_info.fileCounter = fileCounter;\r\n tld_info.remainFrame = remainFrame;\r\n}\r\n\r\nvoid freeTLD_Info(vector<TLD_Info> &vtld_info) {\r\n for (size_t i = 0; i < vtld_info.size(); i++) {\r\n delete vtld_info[i].tld;\r\n }\r\n}\r\n\r\nvector<Rect> faceDetection(Mat frame) {\r\n CascadeClassifier face_cascade;\r\n vector<Rect> faces;\r\n\r\n if (!face_cascade.load(face_cascade_name)) {\r\n printf(\"Error Loading\");\r\n }\r\n\r\n face_cascade.detectMultiScale(frame, faces, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE,\r\n cvSize(90, 90));\r\n return faces;\r\n}\r\n" } ]
3
zopefoundation/zope.html
https://github.com/zopefoundation/zope.html
f6f1d88a41a0b5175a274aa6f397648cbe689f47
63f43fc128cf936149b9f98b4a723a6e1beea5b7
26e4ce403b0d0d4e103a1f7dc22331a07edfb382
refs/heads/master
2023-08-10T04:31:38.089713
2020-04-09T14:54:11
2020-04-09T14:54:11
18,846,407
0
1
NOASSERTION
2014-04-16T16:07:47
2018-10-18T22:09:47
2018-10-22T15:47:25
JavaScript
[ { "alpha_fraction": 0.7410439848899841, "alphanum_fraction": 0.7420675754547119, "avg_line_length": 39.70833206176758, "blob_id": "959dabddcbda03c0999082efc2e7de01cdbc83fc", "content_id": "0fbd0de57f94095bbb2f8831d940d9e3fe6733a8", "detected_licenses": [ "ZPL-2.1" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 2931, "license_type": "permissive", "max_line_length": 70, "num_lines": 72, "path": "/src/zope/html/README.txt", "repo_name": "zopefoundation/zope.html", "src_encoding": "UTF-8", "text": "=========================\nHTML file editing support\n=========================\n\nThis package contains support for editing HTML and XHTML inside a web\npage using the CKEditor as a widget. This is a fairly simple\napplication of CKEditor, and simply instantiates a pre-configured\neditor for each widget. There are no options to control the editors\nindividually.\n\nIn creating this, we ran into some limitations of the editor that are\nworth being aware of. Noting these as limitations does not mean that\nother editors do any better; what's available seems to be a mixed bag.\n\n- The editor only deals with what can be contained inside a <body>\n element; anything that goes outside that, including the <body> and\n </body> tags, get lost or damaged. If there's any way to configure\n CKEditor to deal with such material, it isn't documented.\n\n- There's no real control of the HTML source; whitespace is not\n preserved as a programmer would expect. That's acceptable in many\n use cases, but not all. Applications should avoid using this widget\n if the original whitespace must be maintained.\n\nImplementation problems\n-----------------------\n\nThese are problems with the widget used to integrate CKEditor rather\nthan problems with CKEditor itself. These should be dealt with.\n\n- The width of the editor is hardcoded; this should be either\n configurable or the editor should stretch to fill the available\n space. The sample uses of the CKEditor don't seem to exhibit this\n problem, so it can be better than it is.\n\n- The height of the editor should be configurable in a way similar to\n the configuration of the basic textarea widget.\n\nIdeas for future development\n----------------------------\n\nThese ideas might be interesting to pursue, but there are no specific\nplans to do so at this time:\n\n- Categorize the applications of the editor and provide alternate\n toolbar configurations for those applications. There's a lot of\n configurability in the editor itself, so it can be made to do\n different things.\n\n- Add support for some of the other fancy client-side HTML editors,\n and allow a user preference to select which to use for what\n applications, including the option of disabling the GUI editors when\n detailed control over the HTML is needed (or for luddite users who\n don't like the GUI editors).\n\n XINHA (http://xinha.python-hosting.com/) appears to be an\n interesting option as well, and may be more usable for applications\n that want more than editing of small HTML fragments, especially if\n the user is fairly HTML-savvy.\n\n HTMLArea (http://www.dynarch.com/projects/htmlarea/) may become\n interesting at some point, but a rough reading at this time\n indicates that XINHA may be a more reasonable route.\n\nMore information about CKEditor\n--------------------------------\n\n- http://www.ckeditor.com/\n\n- http://discerning.com/topics/software/ttw.html\n\n- http://www.phpsolvent.com/wordpress/?page_id=330\n" }, { "alpha_fraction": 0.729629635810852, "alphanum_fraction": 0.729629635810852, "avg_line_length": 30.764705657958984, "blob_id": "baf5f535b120eee34dea7837ba2d415b0a4670e5", "content_id": "c87a5df924a34391e99213da310df3f04a322ee9", "detected_licenses": [ "ZPL-2.1" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 540, "license_type": "permissive", "max_line_length": 70, "num_lines": 17, "path": "/src/zope/html/TODO.txt", "repo_name": "zopefoundation/zope.html", "src_encoding": "UTF-8", "text": "Things that need to be done\n---------------------------\n\n- When encoding text, make sure everything is encoded (nothing is left\n over), and deal with errors.\n\n- Make it possible for a user to override the use of the GUI editor\n with a preference setting, possibly allowing a different editor to\n be plugged in.\n\n- Fetch CKeditor separately instead of including it in the\n zope.html checkout.\n\n- Add support for CKeditor plugins.\n\n- Better widgets, with less haphazard configurability. There should\n really be display widgets as well.\n" }, { "alpha_fraction": 0.5628511905670166, "alphanum_fraction": 0.5650545358657837, "avg_line_length": 35.019840240478516, "blob_id": "8c15a197a9a48d23db4685ce953a9c0bc2c03315", "content_id": "ce25a7c760cb592a4b5f0b070da5b9e2d3be8085", "detected_licenses": [ "ZPL-2.1" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9077, "license_type": "permissive", "max_line_length": 79, "num_lines": 252, "path": "/src/zope/html/browser.py", "repo_name": "zopefoundation/zope.html", "src_encoding": "UTF-8", "text": "##############################################################################\n#\n# Copyright (c) 2007 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Browser views that implement editing and preview.\n\n\"\"\"\n__docformat__ = \"reStructuredText\"\n\nimport datetime\n\nimport zope.lifecycleevent\nimport zope.event\nimport zope.file.contenttype\nimport zope.file.interfaces\nimport zope.formlib.form\nimport zope.html.field\nimport zope.html.interfaces\nimport zope.mimetype.interfaces\n\nfrom zope import mimetype\nfrom zope.interface.common import idatetime\n\nfrom i18n import _\n\n\nUNIVERSAL_CHARSETS = (\"utf-8\", \"utf-16\", \"utf-16be\", \"utf-16le\")\n\n\ndef get_rendered_text(form):\n f = form.context.open(\"r\")\n data = f.read()\n f.close()\n ci = mimetype.interfaces.IContentInfo(form.context)\n return ci.decode(data)\n\n\nclass BaseEditingView(zope.formlib.form.Form):\n\n # initial value helpers:\n\n def get_rendered_isFragment(self):\n info = zope.html.interfaces.IEditableHtmlInformation(self.context)\n return info.isFragment\n\n def get_rendered_encoding(self):\n charset = self.context.parameters.get(\"charset\")\n if charset:\n return zope.component.queryUtility(\n mimetype.interfaces.ICharsetCodec, charset)\n else:\n return None\n\n # field definitions:\n\n view_fields = zope.formlib.form.Fields(\n zope.html.interfaces.IEditableHtmlInformation,\n )\n view_fields[\"isFragment\"].get_rendered = get_rendered_isFragment\n\n encoding_field = zope.formlib.form.Field(\n zope.schema.Choice(\n __name__=_(\"encoding\"),\n title=_(\"Encoding\"),\n description=_(\"Character data encoding\"),\n source=mimetype.source.codecSource,\n required=False,\n ))\n encoding_field.get_rendered = get_rendered_encoding\n\n reencode_field = zope.formlib.form.Field(\n zope.schema.Bool(\n __name__=\"reencode\",\n title=_(\"Re-encode\"),\n description=_(\"Enable encoding the text using UTF-8\"\n \" instead of the original encoding.\"),\n default=False,\n )\n )\n\n msgCannotDecodeText = _(\"Can't decode text for editing; please specify\"\n \" the document encoding.\")\n\n def setUpWidgets(self, ignore_request=False):\n ci = mimetype.interfaces.IContentInfo(self.context)\n self.have_text = \"charset\" in ci.effectiveParameters\n fields = [self.view_fields]\n if self.have_text:\n if self.get_rendered_isFragment():\n text_field = self.fragment_field\n else:\n text_field = self.document_field\n fields.append(text_field)\n if ci.effectiveParameters.get(\"charset\") not in UNIVERSAL_CHARSETS:\n fields.append(self.reencode_field)\n else:\n if not self.status:\n self.status = self.msgCannotDecodeText\n fields.append(self.encoding_field)\n self.form_fields = zope.formlib.form.Fields(*fields)\n super(BaseEditingView, self).setUpWidgets(\n ignore_request=ignore_request)\n\n def save_validator(self, action, data):\n errs = self.validate(None, data)\n if not self.have_text:\n ifaces = zope.interface.providedBy(\n zope.security.proxy.removeSecurityProxy(self.context))\n for iface in ifaces:\n if mimetype.interfaces.IContentTypeInterface.providedBy(iface):\n break\n else:\n # Should never happen!\n assert False, \"this view has been mis-registered!\"\n errs += zope.file.contenttype.validateCodecUse(\n self.context, iface, data.get(\"encoding\"),\n self.encoding_field)\n return errs\n\n @zope.formlib.form.action(_(\"Save\"), validator=save_validator)\n def save(self, action, data):\n changed = False\n context = self.context\n\n if self.have_text:\n changed = self.handle_text_update(data)\n else:\n # maybe we have a new encoding?\n codec = data[\"encoding\"]\n if codec is None:\n self.status = self.msgCannotDecodeText\n else:\n if \"charset\" in context.parameters:\n old_codec = zope.component.queryUtility(\n mimetype.interfaces.ICharsetCodec,\n context.parameters[\"charset\"])\n else:\n old_codec = None\n if getattr(old_codec, \"name\", None) != codec.name:\n # use the preferred charset for the new codec\n new_charset = zope.component.getUtility(\n mimetype.interfaces.ICodecPreferredCharset,\n codec.name)\n parameters = dict(context.parameters)\n parameters[\"charset\"] = new_charset.name\n context.parameters = parameters\n changed = True\n\n # Deal with the isFragment flag:\n info = zope.html.interfaces.IEditableHtmlInformation(context)\n isFragment = data[\"isFragment\"]\n if isFragment != info.isFragment:\n info.isFragment = data[\"isFragment\"]\n changed = True\n\n # Set the status message:\n if changed:\n # Should this get done if only the isFragment changed?\n zope.event.notify(\n zope.lifecycleevent.ObjectModifiedEvent(context))\n formatter = self.request.locale.dates.getFormatter(\n 'dateTime', 'medium')\n now = datetime.datetime.now(idatetime.ITZInfo(self.request))\n self.status = _(\"Updated on ${date_time}\",\n mapping={'date_time': formatter.format(now)})\n elif not self.status:\n self.status = _('No changes')\n\n def handle_text_update(self, data):\n text = data[\"text\"]\n if text != get_rendered_text(self):\n ci = mimetype.interfaces.IContentInfo(self.context)\n codec = ci.getCodec()\n try:\n textdata, consumed = codec.encode(text)\n if consumed != len(text):\n # XXX borked!\n pass\n except:\n # The old encoding will no longer support the data, so\n # switch to UTF-8:\n if data.get(\"reencode\"):\n textdata = text.encode(\"utf-8\")\n parameters = dict(self.context.parameters)\n parameters[\"charset\"] = \"utf-8\"\n self.context.parameters = parameters\n else:\n encoding = ci.effectiveParameters[\"charset\"]\n self.status = _(\n \"Can't encode text in current encoding (${encoding})\"\n \"; check 'Re-encode' to enable conversion to UTF-8.\",\n mapping={\"encoding\": encoding})\n self.form_reset = False\n return False\n # need to discard re-encode checkbox\n f = self.context.open(\"w\")\n f.write(textdata)\n f.close()\n return True\n\n\nclass HtmlEditingView(BaseEditingView):\n \"\"\"Editing view for HTML content.\"\"\"\n\n document_field = zope.formlib.form.Field(\n zope.html.field.HtmlDocument(\n __name__=\"text\",\n title=_(\"Text\"),\n description=_(\"Text of the document being edited.\"),\n )\n )\n document_field.get_rendered = get_rendered_text\n\n fragment_field = zope.formlib.form.Field(\n zope.html.field.HtmlFragment(\n __name__=\"text\",\n title=_(\"Text\"),\n description=_(\"Text of the fragment being edited.\"),\n )\n )\n fragment_field.get_rendered = get_rendered_text\n\n\nclass XhtmlEditingView(BaseEditingView):\n \"\"\"Editing view for XHTML content.\"\"\"\n\n document_field = zope.formlib.form.Field(\n zope.html.field.XhtmlDocument(\n __name__=\"text\",\n title=_(\"Text\"),\n description=_(\"Text of the document being edited.\"),\n )\n )\n document_field.get_rendered = get_rendered_text\n\n fragment_field = zope.formlib.form.Field(\n zope.html.field.XhtmlFragment(\n __name__=\"text\",\n title=_(\"Text\"),\n description=_(\"Text of the fragment being edited.\"),\n )\n )\n fragment_field.get_rendered = get_rendered_text\n" }, { "alpha_fraction": 0.62109375, "alphanum_fraction": 0.62109375, "avg_line_length": 41.66666793823242, "blob_id": "3abb3c53f518e42e4cbb5f1fc6434592538b3e08", "content_id": "d9c06741626e6c3e097c3f255059dae258b1033b", "detected_licenses": [ "ZPL-2.1" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 768, "license_type": "permissive", "max_line_length": 75, "num_lines": 18, "path": "/README.txt", "repo_name": "zopefoundation/zope.html", "src_encoding": "UTF-8", "text": "This package contains support for editing HTML and XHTML inside a web\npage using the CKEditor as a widget. This is a fairly simple\napplication of CKEditor, and simply instantiates a pre-configured\neditor for each widget. There are no options to control the editors\nindividually.\n\n\n***************************************************************************\nDeprecated / Unmaintained\n-------------------------\n\nThis package is deprecated, and is no longer being maintained. Future\nreleases will *not* be made from this repository unless a new maintainer\nvolunteers.\n\nIf you are interested in maintaining the package, please create an issue\nin https://github.com/zopefoundation/meta/issues.\n***************************************************************************\n" }, { "alpha_fraction": 0.5986099243164062, "alphanum_fraction": 0.6055603623390198, "avg_line_length": 32.85293960571289, "blob_id": "772a8cdaa0e3176aca9af3188933a054d6468a73", "content_id": "baf610cd4efe2782d6d82e04457b60c8b5d6de56", "detected_licenses": [ "ZPL-2.1" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1151, "license_type": "permissive", "max_line_length": 78, "num_lines": 34, "path": "/src/zope/html/interfaces.py", "repo_name": "zopefoundation/zope.html", "src_encoding": "UTF-8", "text": "##############################################################################\n#\n# Copyright (c) 2007 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Interfaces for zope.html.\n\n\"\"\"\n__docformat__ = \"reStructuredText\"\n\nimport zope.interface\nimport zope.schema\n\nfrom i18n import _\n\n\nclass IEditableHtmlInformation(zope.interface.Interface):\n \"\"\"Information about an HTML file or fragment.\"\"\"\n\n isFragment = zope.schema.Bool(\n title=_(\"Is fragment?\"),\n description=_(\"Set to true if the HTML should be handled as a\"\n \" fragment to be composed to create a document.\"),\n required=True,\n readonly=False,\n )\n" }, { "alpha_fraction": 0.6240708827972412, "alphanum_fraction": 0.6286449432373047, "avg_line_length": 29.955751419067383, "blob_id": "042f337385d358ccb4c33a44a350122747bfab51", "content_id": "6a807c9e380f0d1c5df11baf19a66f955ebe870a", "detected_licenses": [ "ZPL-2.1" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3498, "license_type": "permissive", "max_line_length": 78, "num_lines": 113, "path": "/src/zope/html/docinfo.py", "repo_name": "zopefoundation/zope.html", "src_encoding": "UTF-8", "text": "##############################################################################\n#\n# Copyright (c) 2007 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Helper functions to get information on the current document.\n\n\"\"\"\n__docformat__ = \"reStructuredText\"\n\nimport HTMLParser\nimport xml.parsers.expat\n\nimport persistent.dict\n\nimport zope.annotation.interfaces\nimport zope.file.interfaces\nimport zope.html.interfaces\nimport zope.interface\nimport zope.mimetype.types\n\n\n# Use the package name as the annotation key:\nKEY = __name__.rsplit(\".\", 1)[0]\n\n\nclass EditableHtmlInformation(object):\n\n zope.interface.implements(\n zope.html.interfaces.IEditableHtmlInformation)\n\n _annotations = None\n\n def __init__(self, file):\n self.__parent__ = file\n self.context = file\n\n def _get_annotation(self):\n if self._annotations is None:\n self._annotations = zope.annotation.interfaces.IAnnotations(\n self.context)\n return self._annotations.get(KEY)\n\n def _get_isFragment(self):\n annotation = self._get_annotation()\n if annotation is not None:\n if \"is_fragment\" in annotation:\n return annotation[\"is_fragment\"]\n # compute from data\n f = zope.file.interfaces.IFile(self.context)\n if zope.mimetype.types.IContentTypeTextHtml.providedBy(self.context):\n isfrag = _is_html_fragment(f)\n else:\n isfrag = _is_xhtml_fragment(f)\n return isfrag\n\n def _set_isFragment(self, value):\n value = bool(value)\n if value != self.isFragment:\n annotation = self._get_annotation()\n if annotation is None:\n annotation = persistent.dict.PersistentDict()\n annotation[\"is_fragment\"] = value\n self._annotations[KEY] = annotation\n\n isFragment = property(_get_isFragment, _set_isFragment)\n\n\ndef _is_xhtml_fragment(file):\n f = file.open(\"r\")\n p = xml.parsers.expat.ParserCreate()\n h = HTMLContentSniffer()\n p.StartElementHandler = h.handle_starttag\n p.CharacterDataHandler = h.handle_data\n try:\n p.Parse(f.read(2048))\n except xml.parsers.expat.ExpatError:\n # well-formedness failure; don't even pretend it might be a\n # document (might not be a useful fragment either, though)\n return True\n return p.leading_content or p.first_element != \"html\"\n\n\ndef _is_html_fragment(file):\n \"\"\"Return True iff `file` represents an HTML fragment.\"\"\"\n f = file.open(\"r\")\n p = HTMLContentSniffer()\n p.feed(f.read(2048))\n return p.leading_content or p.first_element != \"html\"\n\n\nclass HTMLContentSniffer(HTMLParser.HTMLParser):\n\n first_element = None\n leading_content = None\n\n def handle_starttag(self, name, attrs):\n if not self.first_element:\n self.first_element = name\n\n def handle_data(self, data):\n if not self.first_element:\n data = data.strip()\n if data:\n self.leading_content = True\n" }, { "alpha_fraction": 0.5943552851676941, "alphanum_fraction": 0.6004427075386047, "avg_line_length": 31.26785659790039, "blob_id": "d9ab1b3ca51b752055675069a9188ffdd2372a51", "content_id": "609f0bbd96b188cbe30e883acfdd43f380b7de0c", "detected_licenses": [ "ZPL-2.1" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1807, "license_type": "permissive", "max_line_length": 78, "num_lines": 56, "path": "/src/zope/html/widget.py", "repo_name": "zopefoundation/zope.html", "src_encoding": "UTF-8", "text": "##############################################################################\n#\n# Copyright (c) 2007 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Widget implementations for rich-text fields.\n\n\"\"\"\n__docformat__ = \"reStructuredText\"\n\nimport zope.formlib\n\nimport zc.resourcelibrary\n\n\nclass CkeditorWidget(zope.formlib.widgets.TextAreaWidget):\n\n editorHeight = 400\n\n configurationPath = \"/@@/zope_ckconfig.js\"\n\n def __call__(self):\n zc.resourcelibrary.need(\"ckeditor\")\n #\n # XXX The 'shortname' here needs some salt to ensure that\n # multiple widgets with the same trailing name are\n # distinguishable; some encoding of the full name seems\n # appropriate, or a per-request counter would also do nicely.\n #\n d = {\n \"config\": self.configurationPath,\n \"name\": self.name,\n \"shortname\": self.name.split('.', 1)[-1],\n \"height\": self.editorHeight,\n }\n textarea = super(CkeditorWidget, self).__call__()\n return textarea + (self.javascriptTemplate % d)\n\n javascriptTemplate = '''\n<script type=\"text/javascript\" language=\"JavaScript\">\nvar CKeditor_%(shortname)s = new CKEDITOR.replace(\"%(name)s\",\n {\n height: %(height)s,\n customConfig : \"%(config)s\",\n }\n);\n</script>\n'''\n" }, { "alpha_fraction": 0.6901763081550598, "alphanum_fraction": 0.6926952004432678, "avg_line_length": 28.774999618530273, "blob_id": "1c0af4ff51628c417b39106a93f0e2e14b617f0c", "content_id": "a16b292f3fdcddd8266cbe8420fbb423329690dd", "detected_licenses": [ "ZPL-2.1" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2382, "license_type": "permissive", "max_line_length": 78, "num_lines": 80, "path": "/src/zope/html/tests.py", "repo_name": "zopefoundation/zope.html", "src_encoding": "UTF-8", "text": "##############################################################################\n#\n# Copyright (c) 2007 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Test harness for zope.html.\n\n\"\"\"\n__docformat__ = \"reStructuredText\"\n\nimport os\nimport unittest\nimport doctest\n\nimport pytz\n\nimport zope.annotation.attribute\nimport zope.formlib.tests.test_textareawidget\nimport zope.app.testing.placelesssetup\nimport zope.component\nimport zope.file.testing\nimport zope.interface.common.idatetime\nimport zope.mimetype.types\nimport zope.publisher.interfaces\n\nfrom zope.app.testing import functional\n\nimport zope.html.widget\n\n\nclass CkeditorWidgetTestCase(\n zope.formlib.tests.test_textareawidget.TextAreaWidgetTest):\n\n _WidgetFactory = zope.html.widget.CkeditorWidget\n\n\ndef setUp(test):\n zope.app.testing.placelesssetup.setUp()\n zope.component.provideAdapter(\n zope.annotation.attribute.AttributeAnnotations)\n # we have to initialize the mimetype handling\n zope.mimetype.types.setup()\n\n\ndef tearDown(test):\n zope.app.testing.placelesssetup.tearDown()\n\n\[email protected](zope.publisher.interfaces.IRequest)\[email protected](zope.interface.common.idatetime.ITZInfo)\ndef requestToTZInfo(request):\n return pytz.timezone('US/Eastern')\n\nEditableHtmlLayer = zope.file.testing.ZCMLLayer(\n os.path.join(os.path.dirname(__file__), 'ftesting.zcml'),\n __name__, \"EditableHtmlLayer\")\n\n\ndef test_suite():\n ftests = zope.file.testing.FunctionalBlobDocFileSuite(\"browser.txt\")\n ftests.layer = EditableHtmlLayer\n return unittest.TestSuite([\n doctest.DocFileSuite(\n \"docinfo.txt\",\n setUp=setUp,\n tearDown=tearDown),\n doctest.DocFileSuite(\n \"widget.txt\",\n optionflags=(doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)),\n unittest.makeSuite(CkeditorWidgetTestCase),\n ftests,\n ])\n" }, { "alpha_fraction": 0.636734664440155, "alphanum_fraction": 0.6530612111091614, "avg_line_length": 15.333333015441895, "blob_id": "384439e897e079457df076cce93f8fbb1b891517", "content_id": "066da41385dad5adf04faf8d052f8ee9e5e628c3", "detected_licenses": [ "ZPL-2.1" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 245, "license_type": "permissive", "max_line_length": 38, "num_lines": 15, "path": "/tox.ini", "repo_name": "zopefoundation/zope.html", "src_encoding": "UTF-8", "text": "[tox]\nenvlist =\n py26,py27\n\n[testenv]\ndeps =\n # extras_require[test]\n zope.app.testing\n zope.app.zcmlfiles\n zope.testing\n zope.testbrowser\n # test runner\n zope.testrunner\ncommands =\n zope-testrunner --test-path=src -v\n" }, { "alpha_fraction": 0.7029554843902588, "alphanum_fraction": 0.7052001357078552, "avg_line_length": 26, "blob_id": "6f490cc462aa8d8c847c7d8141a3026f1b67fda5", "content_id": "5e09bcc0b535c93a93f3b110c2d9817ac2d4b0ab", "detected_licenses": [ "ZPL-2.1" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2673, "license_type": "permissive", "max_line_length": 78, "num_lines": 99, "path": "/src/zope/html/field.py", "repo_name": "zopefoundation/zope.html", "src_encoding": "UTF-8", "text": "##############################################################################\n#\n# Copyright (c) 2007 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Interfaces and fields for HTML/XHTML documents.\n\n\"\"\"\n__docformat__ = \"reStructuredText\"\n\nimport zope.interface\nimport zope.schema\nimport zope.schema.interfaces\n\n\nclass IHtmlTextField(zope.schema.interfaces.IText):\n \"\"\"Text that contains HTML markup.\n\n This is an abstract interface. Only the concrete derived\n interfaces should be used for actual field definitions.\n\n \"\"\"\n\n\nclass IHtmlDocumentField(IHtmlTextField):\n \"\"\"HTML document field.\n\n This is for fields that represent complete HTML documents,\n including the document head as well as the body.\n\n \"\"\"\n\n\nclass IHtmlFragmentField(IHtmlTextField):\n \"\"\"HTML fragment field.\n\n This is for fields that represent pieces of HTML that can be\n composed to create complete documents. This field implies no\n specifics about what portion of an HTML document is represented,\n but it must be internally well-formed.\n\n \"\"\"\n\n\nclass IXhtmlTextField(zope.schema.interfaces.IText):\n \"\"\"Text that contains XHTML markup.\n\n This is an abstract interface. Only the concrete derived\n interfaces should be used for actual field definitions.\n\n \"\"\"\n\n\nclass IXhtmlDocumentField(IXhtmlTextField):\n \"\"\"XHTML document field.\n\n This is for fields that represent complete XHTML documents,\n including the document head as well as the body.\n\n \"\"\"\n\n\nclass IXhtmlFragmentField(IXhtmlTextField):\n \"\"\"XHTML fragment field.\n\n This is for fields that represent pieces of XHTML that can be\n composed to create complete documents. This field implies no\n specifics about what portion of an HTML document is represented,\n but it must be internally well-formed.\n\n \"\"\"\n\n\nclass HtmlDocument(zope.schema.Text):\n\n zope.interface.implements(IHtmlDocumentField)\n\n\nclass HtmlFragment(zope.schema.Text):\n\n zope.interface.implements(IHtmlFragmentField)\n\n\nclass XhtmlDocument(zope.schema.Text):\n\n zope.interface.implements(IXhtmlDocumentField)\n\n\nclass XhtmlFragment(zope.schema.Text):\n\n zope.interface.implements(IXhtmlFragmentField)\n" } ]
10
yashmundra13/RNN
https://github.com/yashmundra13/RNN
3146a39c7e2f8fcc8efd5efbdd9e03a29655b117
8b3bd843b44402fe90600ffad6b71f6f1e383420
a17179b97d7465f17fa84df77ac947e2641e4507
refs/heads/master
2020-12-04T02:01:06.998873
2020-01-03T10:19:26
2020-01-03T10:19:26
231,563,136
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.553459107875824, "alphanum_fraction": 0.5723270177841187, "avg_line_length": 10.357142448425293, "blob_id": "e9116f6a9854466780ff3d373fe6629e058c71d3", "content_id": "2465953388a78f66cbe4f470d574236b5ff6d581", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 159, "license_type": "no_license", "max_line_length": 39, "num_lines": 14, "path": "/main.py", "repo_name": "yashmundra13/RNN", "src_encoding": "UTF-8", "text": "from rnn import main as rnn_main\n\n\nFLAG = 'RNN'\n\n\ndef main():\n\tif FLAG == 'RNN':\n\t\trnn_main(hidden_dim=32, batch_size=1)\n\n\n\nif __name__ == '__main__':\n\tmain()\n" }, { "alpha_fraction": 0.8032786846160889, "alphanum_fraction": 0.811475396156311, "avg_line_length": 23.399999618530273, "blob_id": "b0c107acbc51981516ee3235af8628c689367e1b", "content_id": "44699be0d0341a6ffbfce3b4913df71204dd44e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 122, "license_type": "no_license", "max_line_length": 51, "num_lines": 5, "path": "/README.md", "repo_name": "yashmundra13/RNN", "src_encoding": "UTF-8", "text": "# RNN\nA Recurrent Neural Network to classify Yelp Reviews\n\nRequirements:\nNumpy, Pytorch, Gensim's Glove6B Word Embeddings\n" }, { "alpha_fraction": 0.6845117211341858, "alphanum_fraction": 0.702418327331543, "avg_line_length": 33.26582336425781, "blob_id": "1d91e59b2e4831327cba5d80fa727f55a9bba832", "content_id": "6fd0520d01eab3c7f5e9e600d3666e8a03463c73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5417, "license_type": "no_license", "max_line_length": 127, "num_lines": 158, "path": "/rnn.py", "repo_name": "yashmundra13/RNN", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport torch.optim as optim\nimport math\nimport random\nimport os\nfrom gensim.scripts.glove2word2vec import glove2word2vec\nfrom gensim.models.keyedvectors import KeyedVectors\n\nimport time\nfrom tqdm import tqdm\nfrom data_loader import fetch_data\n\nw2v = None\ndevice = None\nnum_total = 0\nnum_unk = 0\nunk = '<UNK>'\nrand_vecs = {}\n\nclass RNN(nn.Module):\n\tdef __init__(self, input_size, hidden_size, output_size, batch_size): # Add relevant parameters\n\t\tsuper(RNN, self).__init__()\n\t\t# Fill in relevant parameters\n\t\t# Ensure parameters are initialized to small values, see PyTorch documentation for guidance\n\t\tself.batch_size = batch_size\n\t\tself.hidden_size = hidden_size\n\t\tself.rnn = nn.RNN(input_size, hidden_size,)\n\t\tself.activation = nn.Tanh()\n\t\tself.linear1 = nn.Linear(hidden_size, hidden_size)\n\t\tnn.init.uniform_(self.linear1.weight.data, -math.sqrt(6)/math.sqrt(2 * hidden_size), math.sqrt(6)/math.sqrt(2 * hidden_size))\n\t\tself.linear2 = nn.Linear(hidden_size, output_size)\n\t\tnn.init.uniform_(self.linear2.weight.data, -math.sqrt(6)/math.sqrt(hidden_size + 5), math.sqrt(6)/math.sqrt(hidden_size + 5))\n\t\tself.softmax = nn.LogSoftmax(dim=1)\n\t\tself.loss = nn.CrossEntropyLoss()\n\n\tdef compute_Loss(self, predicted_vector, gold_label):\n\t\treturn self.loss(predicted_vector, gold_label)\t\n\n\tdef forward(self, inputs): \n\t\t#begin code\n\t\th_0 = torch.rand(1,self.batch_size, self.hidden_size, dtype=torch.double).to(device)\n\t\toutput, hidden = self.rnn(inputs)\n\t\tl1 = self.linear1(output[-1])\n\t\tl2 = self.linear2(self.activation(l1))\n\t\tpredicted_vector = self.softmax(l2) \n\t\t# Remember to include the predicted unnormalized scores which should be normalized into a (log) probability distribution\n\t\t#end code\n\t\treturn predicted_vector\n\n\n# Converts list of pairs (doc, y) into pair of (list of v for each doc, array of y for each doc)\ndef vectorize_data(data):\n\tvecs = []\n\tlabels = torch.zeros(len(data))\n\tfor i, (doc, y) in enumerate(data):\n\t\tvec = vectorize_doc(doc)\n\t\tvecs.append(torch.tensor(vec))\n\t\tlabels[i] = y\n\tprint (num_total, num_unk)\n\treturn vecs, labels\n\n# Convert doc into v where v has shape (n, d) where n is then number of words in doc and\n# d is the number of dimensions in the word embedding\ndef vectorize_doc(doc):\n\tres = np.zeros((len(doc), 50))\n\tfor i in range(len(doc)):\n\t\tres[i] = vectorize_word(doc[i])\n\treturn res.reshape((len(doc), 1, 50))\n\n# Convert word into v of size d\ndef vectorize_word(word):\n\tglobal num_unk, num_total\n\tword = word.lower()\n\tnum_total += 1\n\tif not word in w2v:\n\t\tif word in rand_vecs:\n\t\t\treturn rand_vecs[word]\n\t\telse:\n\t\t\tr = np.random.random(50)\n\t\t\trand_vecs[word] = r\n\t\t\tnum_unk += 1\n\t\t\treturn r\n\treturn w2v.word_vec(word)\n\ndef main(hidden_dim, batch_size): \n\tglobal device\n\tdevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\t\n\tif not os.path.exists('glove.6B.50d.w2v.txt'):\n\t\tprint(\"w2v file not found, generating...\")\n\t\tglove2word2vec(glove_input_file='glove.6B.50d.txt', word2vec_output_file='glove.6B.50d.w2v.txt')\n\tglobal w2v\n\tw2v = KeyedVectors.load_word2vec_format('glove.6B.50d.w2v.txt', binary=False)\n\n\tprint(\"Fetching data...\")\n\ttrain_data, valid_data = fetch_data() # X_data is a list of pairs (document, y); y in {0,1,2,3,4}\n\n\tmodel = RNN(50,hidden_dim,5,batch_size)\n\tmodel.double()\n\tmodel.cuda()\n\n\tprint(\"Vectorizing data...\")\n\ttrain_vecs, train_labs = vectorize_data(train_data)\n\tvalid_vecs, valid_labs = vectorize_data(valid_data)\n\tprint(\"Finished vectorizing data\")\n\n\toptimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9, nesterov=False) \n\t#scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)\n\titers = 10\n\twhile iters > 0: # How will you decide to stop training and why\n\t\tmodel.train()\n\t\toptimizer.zero_grad()\n\t\tminibatch_size = 16\n\t\tN = len(train_data)\n\t\tperm = np.random.permutation(N)\n\t\ttrain_vecs = [train_vecs[i] for i in perm]\n\t\ttrain_labs = train_labs[perm]\n\t\ttotal = 0\n\t\tcorrect = 0\n\t\tepoch = 10 - iters\n\t\tfor minibatch_index in tqdm(range(N // minibatch_size)):\n\t\t\toptimizer.zero_grad()\n\t\t\tloss = None\n\t\t\tfor example_index in range(minibatch_size):\n\t\t\t\tgold_label = train_labs[minibatch_index * minibatch_size + example_index].long()\n\t\t\t\tpredicted_vector = model(train_vecs[minibatch_index * minibatch_size + example_index].to(device))\n\t\t\t\tpredicted_label = torch.argmax(predicted_vector)\n\t\t\t\tcorrect += int(predicted_label == gold_label)\n\t\t\t\ttotal += 1\n\t\t\t\texample_loss = model.compute_Loss(predicted_vector.view(1,-1), torch.tensor([gold_label]).to(device))\n\t\t\t\tif loss is None:\n\t\t\t\t\tloss = example_loss\n\t\t\t\telse:\n\t\t\t\t\tloss += example_loss\n\t\t\tloss = loss / minibatch_size\n\t\t\tloss.backward()\n\t\t\toptimizer.step()\n\n\t\toptimizer.zero_grad() \n\t\tN = len(valid_data)\n\t\ttotal = 0\n\t\tcorrect = 0\n\t\tfor minibatch_index in tqdm(range(N // minibatch_size)):\n\t\t\toptimizer.zero_grad()\n\t\t\tloss = None\n\t\t\tfor example_index in range(minibatch_size):\n\t\t\t\tgold_label = valid_labs[minibatch_index * minibatch_size + example_index].long()\n\t\t\t\tpredicted_vector = model(valid_vecs[minibatch_index * minibatch_size + example_index].to(device))\n\t\t\t\tpredicted_label = torch.argmax(predicted_vector)\n\t\t\t\tcorrect += int(predicted_label == gold_label)\n\t\t\t\ttotal += 1\n\t\tprint(\"Validation completed for epoch {}\".format(epoch + 1))\n\t\tprint(\"Validation accuracy for epoch {}: {}\".format(epoch + 1, correct / total))\n\t\t#scheduler.step()\n\t\titers -= 1\n\n\n\n" } ]
3
stavco/testrepo
https://github.com/stavco/testrepo
3fec07a4f914639926efcce29a682c268de17b7d
0301e8bd2127980831ee715732f01cc142e67453
047bf27c720494eea0579914eb80bafce72c1311
refs/heads/master
2022-12-12T18:40:14.246429
2020-09-09T15:04:27
2020-09-09T15:04:27
294,145,068
0
0
null
2020-09-09T14:56:57
2020-09-09T14:59:53
2020-09-09T15:04:28
Python
[ { "alpha_fraction": 0.6938775777816772, "alphanum_fraction": 0.6938775777816772, "avg_line_length": 23, "blob_id": "17b5bf5303a450caa3b240b8ac6d272c2f349351", "content_id": "9fd65aacf1d63723b372071cf9c65b5f5bf3c975", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 49, "license_type": "no_license", "max_line_length": 27, "num_lines": 2, "path": "/firstpython.py", "repo_name": "stavco/testrepo", "src_encoding": "UTF-8", "text": " #display the outpot\n #print (\"new python file\")\n" } ]
1
PuZheng/lite-mms
https://github.com/PuZheng/lite-mms
5402bbf4857c53f5a8c2975d929770d7453da49f
30ace5d0a1fc82a3b18d8e40f97a0aeae29db492
7ebb0b8794306406b4c8680ec5fc5fb46ea81d15
refs/heads/master
2021-01-02T08:57:49.125936
2018-01-27T01:46:15
2018-01-27T01:46:15
9,022,388
0
1
null
2013-03-26T03:54:26
2015-03-20T06:44:23
2015-06-24T02:26:41
Python
[ { "alpha_fraction": 0.4536481201648712, "alphanum_fraction": 0.4751637578010559, "avg_line_length": 18.31810188293457, "blob_id": "bec1e7dabc5798a721a4904f89a0fa67a557a0f0", "content_id": "5d9bbeca7e4b6c16474a3424e5203f649746ab15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 27638, "license_type": "no_license", "max_line_length": 141, "num_lines": 1138, "path": "/docs/source/webservices.rst", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "###########\nwebservices\n###########\n\nuserGroup:\n1:车间主任\n2:班组长\n3:装卸工\n4:质检员\n5:收发员\n6:调度员\n\n'''注释后面打*的字段可选填'''\n\n************************\npost-auth-login(客户端登陆接口)\n************************\n\n:request\n=======\n\n**POST /auth_ws/login?username=<str>&password=<str>**\n\n* username - 用户名 \n* password - 用户密码 \n\nresponse\n========\n* 200 - 成功::\n\n.. code-block:: python\n \n {\n \"username\": <str>, # 用户名\n \"teamID\": <int>, # 班组ID\n \"userID\": <int>, # 用户ID\n \"departmentID\": <int+>, # 车间ID, 包括多个,存在一个车间主任管理多个班组的情况。\n \"userGroup\": <int>, # \n \"token\": <str>, \n }\n \n* 403/401 - 错误::\n\n.. code-block:: python\n\n \"actual error reason\"\n \nexample\n=======\n\n* 请求\n\n**POST /auth_ws/login?username=xiechao&password=asdf**\n\n* 返回\n \n * http code - 200\n * 数据\n.. code-block:: python\n \n {\n \"username\": \"wangjiali\",\n \"teamID\": \"22\",\n \"userID\": \"10000\",\n \"departmentID\": \"2,3\",\n \"userGroup\": \"1\"\n }\n \n*********************************\nget-unload-session-list(获取卸货会话列表)\n*********************************\n\n获取的卸货会话都是未完成的\n\nrequest\n=======\n**GET /cargo_ws/unload-session-list?index=<int>&cnt=<int>&auth_token=<str>**\n\n* \\*index - 返回的集合在所有卸货会话列表中的起始位置,默认为0\n* \\*cnt - 返回的卸货会话数量,默认为sys.maxint\n\nresponse\n========\n* 200 - 成功\n.. code-block:: python\n \n {\n \"total_cnt\": <int>,\n \"data\": [\n {\n \"sessionID\": <int>, # 会话ID\n \"plateNumber\": <str>, # 车牌号 \n \"isLocked\": 1|0, # 是否被锁定\n },\n ...\n ]\n }\n* 403/401 - 错误\n.. code-block:: python\n\n \"actual error reason\"\n\nexample\n=======\n* 请求\n**GET /cargo_ws/unload-session-list&auth_token=xxx**\n\n* 响应\n\n * http code: 200\n * 数据\n\n.. code-block:: python\n\n {\n \"total_cnt\": 400,\n \"data\": [\n {\n \"sessionID\": 1,\n \"plateNumber\": \"ZA000001\",\n \"isLocked\": 1,\n },\n {\n \"sessionID\": 2,\n \"plateNumber\": \"ZA000002\",\n \"isLocked\": 0,\n },\n {\n \"sessionID\": 3,\n \"plateNumber\": \"ZA000003\",\n \"isLocked\": 0,\n }\n ]\n }\n\n**************************\nget-harbour-list(获取装卸货点列表)\n**************************\n\nrequest\n=======\n**GET /cargo_ws/harbour-list&auth_token=<str>**\n\nresponse\n========\n* 200 - 成功\n\n.. code-block:: python\n\n [\n <str>, # harbours\n ...\n ]\n\n* 401 - 失败\n\n.. code-block:: python\n \n \"actual error reason\"\n\nexample\n=======\n\n* 请求\n**GET /cargo_ws/harbour-list&auth_token=<str>**\n\n* 响应\n\n * http code - 200\n * 数据\n.. code-block:: python\n\n [\n \"车间一\",\n \"车间二\"\n ]\n\n************************\npost-unload-task(生成卸货任务)\n************************\n\n此接口需要装卸工角色\n\nrequest\n=======\n\n**POST /cargo_ws/unload-task?customer_id=<int>&harbour=<int>&is_finished=[0|1]&session_id=<int>&auth_token=<str>**\n\n**<raw_picture_data>**\n\n* customer_id - 客户id\n* harbour - 卸货点名称\n* \\* is_finished - 是否完全卸货, 0代表没有,1代表完毕。可选项,默认为0\n* session_id - 卸货会话id\n* raw_picture_data - 原始图片数据\n\nresponse\n========\n* 200 - 成功 \n\n.. code-block:: python\n \n <int> # unload task id, 代表新创建的卸货任务ID \n\n* 403/401 - 失败 \n\n.. code-block:: python\n\n \"error reason\"\n \nexample\n=======\n* 请求:\n**POST http://<your site>/cargo_ws/unload-task?session_id=1&is_finished=1&harbour=装卸点1&customer_id=2&auth_token=xxx**\n\n* 返回:\n * http code - 200\n * 数据:\n \n.. code-block:: python\n\n 10001\n\n\n**************************\nget-work-command(获取工单)\n**************************\n\n获取单个工单\n\nrequest\n=======\n\n**GET /manufacture_ws/work-command/<work_command_id:int>?auth_token=<str>**\n\n* work_command_id - 工单ID\n\n\nresponse\n========\n\n* 200 - 成功\n\n.. code-block:: python\n\n {\n \"customerName\": <string>, # 客户名称\n \"department\": {\n \"id\": <int>, # 车间ID\n \"name\": <string>, # 车间名称\t\n }\n \"handleType\": <int>, # 处理类型\n \"id\": <int>, # 工单ID\n \"isUrgent\": 1|0, # 是否加急,1加急。\n \"lastMod\": <int>, # last modified time, seconds since epoch\n \"orderID\": <int>, # 订单ID\n \"orderNum\": <str>, # 订单号\n \"orderCreateTime\": <int>, # 订单创建时间,seconds since epoch\n \"orderType\": <int>, # 工单类型\n \"orgWeight\": <int>, # 工序前重量 , 需要说明的是,若工单类型为瑞格或者紧固件,那么这个值只有参考意义。 \n \"orgWeight\": <int>, # 工序前重量 \n \"picPath\": <str>, # 图片链接\n \"previousProcedure\": <string>, # 上一道工序名称,可为空\n \"procedure\": <string>, # 当前工序名,可为空\n \"processedCount\": <int>, # 桶数或者件数,视工单所属的订单类型而定\n \"processedWeight\": <int>, # 工序后重量, 若工单类型为瑞格或者紧固件,那么这个值只有参考意义。\n \"productName\": <string>, # 产品名称 \n \"status\": <int>, # 状态\n \"subOrderId\": <int>, # 子订单ID\n \"team\": {\n id: <int>, # 班组ID\n name: <string>, # 组名称\n }\n \"technicalRequirements\": <string>, # 技术要求,可为空\n \"rejected\": <int>, # 是否退货\n \"qirList\": [\n {\n result: <int>, # 质检结果,\n weight: <int>, # 质检重量,\n id: <int>, # 质检报告ID,\n quantity: <int>, # 质检数量,\n picUrl: <str>, # 质检报告图片链接\n actorId: <int>, # 操作员ID\n }\n ]\n }\n \n* 404 - 该工单不存在\n\n*****************************\nget-work-command-list(获取工单列表)\n*****************************\n\n获取一系列的工单列表,其排序规则如下:\n\n* 首先按加急与否进行排序\n* 其次,按工单上一次状态变更的时间由远及近进行排序。\n例如:存在A,B两个待分配工单,这两个工单排产的时间分别是 \\*2012-9-10[10:09:10]\\* 和 \\*2012-9-10[9:50:07]\\* , 那么B要排在A的前面 \n\n\nrequest\n=======\n\n**GET /manufacture_ws/work-command-list?department_id=<int>&team_id=<int>&start=<int:0>&cnt=<int:sys.maxint>&status=<int>+&auth_token=<str>**\n\n* \\*department_id - 车间ID, 若为空,则team_id不能为空\n* \\*team_id - 班组ID, 若为空,则department_id不能为空\n* \\*start - 返回的工单列表在所有符合其他参数条件的工单列表中的起始位置, 若为空,默认为0\n* \\*cnt - 返回的工单数量,若为空,默认为sys.maxint\n* status - 见 :py:mod:`lite_mms.constants.work_command` 中对各种工单状态的说明, 可以是多种工单状态的组合, 若是多种工单状态的组合,中间用','隔开\n\nresponse\n========\n* 200 - 成功\n\n.. code-block:: python\n\n {\n \"totalCnt\": <int>, # 总数量\n \"data\": [\n {\n \"customerName\": <string>, # 客户名称\n \"department\": {\n \"id\": <int>, # 车间ID\n \"name\": <string>, # 车间名称\t\n }\n \"handleType\": <int>, # 处理类型\n \"id\": <int>, # 工单ID\n \"isUrgent\": 1|0, # 是否加急,1加急。\n \"lastMod\": <int>, # last modified time, seconds since epoch\n \"orderID\": <int>, # 订单ID\n \"orderNum\": <str>, # 订单号\n \"orderCreateTime\": <int>, # 订单创建时间,seconds since epoch\n \"orderType\": <int>, # 工单类型\n \"orgWeight\": <int>, # 工序前重量 , 需要说明的是,若工单类型为瑞格或者紧固件,那么这个值只有参考意义。 \n \"orgCount\": <int>, # 工序前数量 \n \"picPath\": <str>, # 图片链接\n \"previousProcedure\": <string>, # 上一道工序名称,可为空\n \"procedure\": <string>, # 当前工序名,可为空\n \"processedCount\": <int>, # 桶数或者件数,视工单所属的订单类型而定\n \"processedWeight\": <int>, # 工序后重量, 若工单类型为瑞格或者紧固件,那么这个值只有参考意义。\n \"productName\": <string>, # 产品名称 \n \"status\": <int>, # 状态\n \"subOrderId\": <int>, # 子订单ID\n \"team\": {\n id: <int>, # 班组ID\n name: <string>, # 组名称\n }\n \"technicalRequirements\": <string>, # 技术要求,可为空\n \"rejected\": <int>, # 是否退货\n \"qirList\": [\n {\n result: <int>, # 质检结果,\n weight: <int>, # 质检重量,\n id: <int>, # 质检报告ID,\n quantity: <int>, # 质检数量,\n picUrl: <str>, # 质检报告图片链接\n actorId: <int>, # 操作员ID\n }\n ]\n }\n ]\n }\n \n\n有关orderType的说明,请见 :py:mod:`lite_mms.constants.default` 中对各种订单类型的说明\n\n这里特别需要说明的是 **picPath** 字段, 这个字段的含义是工序的工序前加工件的照片,也就是说:\n\n1. 工单第一次分配时,取子订单的照片。\n\n2. 工单结束,进入下道工序时,质检员拍的工序后产品照片。\n\n若照片有缺失,不会回溯。\n\n* 401 - 失败\n\n.. code-block:: python\n \n \"actual error reason\"\n \nexample\n=======\n* 请求:\n**POST http://<your site>/manufacture_ws/work-command-list?department_id=1&team_id=2&status=3,5&auth_token=xxx**\n\n* 返回:\n * http code - 200\n * 数据:\n\n.. code-block:: python\n\n {\n \"totalCnt\": 8,\n \"data\": [\n {\n \"status\": 3,\n \"processedWeight\": 0,\n \"customerName\": \"赛瑞\",\n \"orgCount\": 0,\n \"team\": {\n\t\t\t\"id\": 1, \n\t\t\t\"name\": \"1号班组\",\n\t\t}\n \"productName\": \"workpiece\",\n \"department\": {\n\t\t\t\"id\": 1,\n\t\t\t\"name\": \"一号车间\",\n\t\t}\n \"subOrderId\": 1,\n \"technicalRequirements\": \"\",\n \"lastMod\": 1349851179,\n \"id\": 1,\n \"orderID\": 1,\n \"previousProcedure\": \"\",\n \"orderType\": 1,\n \"isUrgent\": 0,\n \"picPath\": \"\",\n \"processedCount\": 0,\n \"handleType\": 1,\n \"orgWeight\": 1000,\n \"procedure\": \"screw\"\n \"rejected\": 0, \n }\n ]\n }\n\n*************************\nget-customer-list(获取客户列表)\n*************************\n\nrequest\n=======\n**GET /order_ws/customer-list&auth_token=<str>**\n\nresponse\n========\n\n* 200 - 成功, 即使没有一个客户列表\n\n.. code-block:: python\n\n [\n {\n \"id\": <int>, # 用户ID\n \"name\": <str>, # 用户名称\n \"abbr\": <str>, # 拼音首字母缩写,例如\"杭州Nokia\"的缩写是\"hznokia\"\n },\n ]\n\nexample\n=======\n略\n\n*********************\nget-team-list(获取班组列表)\n*********************\n\nrequest\n=======\n**GET /manufacture_ws/team-list?department_id=<int>&auth_token=<str>**\n\n* \\* department_id - 车间ID\n\nresponse\n========\n* 200 - 成功\n\n.. code-block:: python\n\n [\n {\n \"id\": <int>, # 班组ID\n \"name\": <str>, # 班组名称\n },\n ...\n ]\n\n* 401 - 失败\n\n.. code-block:: python\n \n \"actual error reason\"\n \nexample\n=======\n\n* 请求\n\n**GET /manufacture_ws/team-list?department_id=100&auth_token=xxx**\n\n* 返回值\n * http code - 200\n * 数据\n\n.. code-block:: python\n\n [\n {\n \"id\": 100,\n \"name\": \"alpha\"\n },\n {\n \"id\": 101,\n \"name\": \"delta\"\n }\n ]\n\n.. _assign-work-command:\n\n*************************\nassign-work-command(分配工单)\n*************************\n\n此接口需要车间主任权限\n\nrequest\n=======\n\n**PUT /manufacture_ws/work-command/<int>?team_id=<int>&action=203&auth_token=<str>**\n\n* work_command_id - 工单id\n* team_id - 被分配的班组id\n* action - 见 :py:mod:`lite_mms.constants.work_command` 中对各种工单操作的说明\n\nresponse\n========\n\n* 200 - 成功, 返回更新后的工单\n\n.. code-block:: python\n\n {\n \"customerName\": <string>, # 客户名称\n\t\"department\": {\n\t\t\"id\": <int>, # 车间ID\n\t\t\"name\": <string>, # 车间名称\t\n\t}\n \"handleType\": <int>, # 处理类型\n \"id\": <int>, # 工单ID\n \"isUrgent\": 1|0, # 是否加急,1加急。\n \"lastMod\": <int>, # last modified time, seconds since epoch\n \"orderID\": <int>, # 工单ID\n \"orderType\": <int>, # 工单类型\n \"orgCount\": <int>, # 工序前的桶数或者件数,视工单所属的订单类型而定\n \"orgWeight\": <int>, # 工序前重量 , 需要说明的是,若工单类型为瑞格或者紧固件,那么这个值只有参考意义。\n \"picPath\": <str>, # 图片链接\n \"previousProcedure\": <string>, # 上一道工序名称,可为空\n \"procedure\": <string>, # 当前工序名,可为空\n \"processedCount\": <int>, # 桶数或者件数,视工单所属的订单类型而定 \n \"processedWeight\": <int>, # 工序后重量, 若工单类型为瑞格或者紧固件,那么这个值只有参考意义。 \n \"productName\": <string>, # 产品名称 \n \"status\": <int>, # 状态\n \"subOrderId\": <int>, # 子订单ID\n \"team\": {\n\t\t\"id\": <string>, # 班组ID\n\t\t\"name\": <string>, # 组名称\n\t}\n \"technicalRequirements\": <string>, # 技术要求,可为空\n \"unit\": <string>, # 单位\n \"rejected\": <int>, # 是否退货\n }\n \n有关orderType的说明,请见 :py:mod:`lite_mms.constants.default` 中对各种订单类型的说明\n\n* 403/401 - 失败\n\n一般可能发生在工单当前状态不是 **待分配** \n\n.. code-block:: python\n\n \"actual error reason\"\n \nexample\n=======\n\n* 请求\n\n**PUT /manufacture_ws/work-command/123?team_id=23&action=203&auth_token=xxx**\n\n* 返回值\n\n * http code: 200\n * 数据\n \n.. code-block:: python\n \n {\n \"status\": 2,\n \"processedWeight\": 0,\n \"customerName\": \"赛瑞\",\n \"orgCount\": 0,\n \"team\": \"1号班组\",\n \"productName\": \"workpiece\",\n \"department\": {\n\t\t\"id\": 1, \n\t\t\"name\": \"一号车间\",\n\t}\n\t\"team\": {\n\t\t\"id\": 1, \n\t\t\"name\": \"一号班组\", \n\t}\n \"subOrderId\": 1,\n \"technicalRequirements\": \"\",\n \"lastMod\": 1349851179,\n \"id\": 1,\n \"orderID\": 1,\n \"previousProcedure\": \"\",\n \"orderType\": 1,\n \"isUrgent\": 0,\n \"picPath\": \"\",\n \"processedCount\": 0,\n \"handleType\": 1,\n \"orgWeight\": 1000,\n \"procedure\": \"screw\",\n \"unit: \"件\",\n \"rejected\": 0, \n }\n\n*****************************\nadd-processed-weight(增加工序后重量)\n*****************************\n\n只有工单在 **待请求结束或结转** 时才可以增加工序后重量\n\n此接口需要班组长权限\n\nrequest\n=======\n\n**PUT /manufacture_ws/work-command/<int>?weight=<int>&quantity=<int>&action=204&is_finished=<1|0>&auth_token=str>**\n\n* work_command_id - 工单id\n* weight - 重量\n* \\*quantity - **增加** 的件数,对于不同类型的工单有不同的含义,标准-公斤;瑞格-件数;紧固件-桶数;对于计件类型,quantity是必须填写的\n* action - 见 :py:mod:`lite_mms.constants.work_command` 中对各种工单操作的说明\n* \\*is_finished - 是否结束,1为结束,若不传,默认为0\n\n\nresponse\n========\n\n* 200 - 成功,返回修改后的工单信息, 返回信息见 :ref:`assign-work-command`\n\n* 403/401 - 失败\n\n一般可能发生在工单当前状态不是\"待请求结束或结转\"\n\n.. code-block:: python\n\n \"actual error reason\"\n\nexample\n=======\n\n请参考 :ref:`assign-work-command`\n \n***********************************\nrequest-end-work-command(请求结束或结转工单)\n***********************************\n\n此接口需要班组长权限\n\nrequest\n=======\n\n**PUT /manufacture_ws/work-command/<int>?action=[205|206]&auth_token=<str>**\n\n* work_command_id - 工单id, 可以是一个工单id列表。例如 **1,2,3**\n* action - 见 :py:mod:`lite_mms.constants.work_command` 中对各种工单操作的说明, 205代表**结束**, 206代表**结转**\n\nresponse\n========\n\n* 200 - 成功,返回修改后的工单信息, 返回信息见 :ref:`assign-work-command`\n\n *这里特别需要说明的是: 若修改的是多个工单,那么返回的工单信息是多个*\n\n* 403/401 - 失败\n\n一般可能发生在工单当前状态不是**待请求结束或结转**\n\n.. code-block:: python\n\n \"actual error reason\"\n\nexample\n=======\n\n 请参考 :ref:`assign-work-command`\n\n\n*************************\nrefuse-work-command(打回工单)\n*************************\n车间主任打回工单\n\n此接口需要车间主任权限\n\nreqeust\n=======\n\n**PUT /manufacture_ws/work-command/<int>?reason=<str>&action=209&auth_token=<str>**\n\n* work_command_id - 工单id\n* \\*reason - 理由\n* action - 见 :py:mod:`lite_mms.constants.work_command` 中对各种工单操作的说明\n\nresponse\n========\n\n* 200 - 成功\n 返回数据请参考 :ref:`assign-work-command`\n \n* 403/401 - 失败\n\n一般可能发生在工单当前状态不是**待分配**\n\nexample\n=======\n\n 请参考 :ref:`assign-work-command`\n\n************************************\naffirm-retrieve-work-command(确认回收工单)\n************************************\n车间主任确认回收工单\n\n此接口需要车间主任权限\n\nrequest\n=======\n\n**PUT /manufacture_ws/work-command/<int>?action=211&weight=<int>&quantity=<int>&auth_token=<str>**\n\n* work_command_id - 工单id\n* action - 见 :py:mod:`lite_mms.constants.work_command` 中对各种工单操作的说明\n* \\*quantity - 最终生产完成的件数,对于不同类型的工单有不同的含义,标准-公斤;瑞格-件数;紧固件-桶数;对于计件类型,quantity是必须填写的\n* weight - 最终生产完成的重量\n\nresponse\n========\n\n* 200 - 成功\n\n 返回数据请参考 :ref:`assign-work-command`\n \n* 403/401 - 失败\n\n一般可能发生在工单当前状态不是**锁定**\n\nexample\n=======\n\n 请参考 :ref:`assign-work-command`\n\n******************************************\nrefuse-retrieval-work-command(拒绝回收工单)\n******************************************\n车间主任拒绝回收工单\n\n此接口需要车间主任权限\n\nrequest\n=======\n\n**PUT /manufacture_ws/work-command/<int>?action=213&auth_token=<str>**\n\n* work_command_id - 工单id, 支持多个工单id,可以用\",\"隔开\n* action - 见 :py:mod:`lite_mms.constants.work_command` 中对各种工单操作的说明\n\nresponse\n========\n\n* 200 - 成功\n\n 返回数据请参考 :ref:`assign-work-command`\n \n* 403/401 - 失败\n一般可能发生在工单当前状态不是**锁定**\n\nexample\n=======\n\n 请参考 :ref:`assign-work-command`\n\n\n\n********************************\nsubmit-quality-inspection(提交质检单)\n********************************\n\n提交质检单,根据对应的质检报告,生成新的工单, 对于已经完成的,需要加入待发货列表中去。\n\n此接口需要质检员权限\n\nrequest\n=======\n\n**PUT /manufacture_ws/work-command/<int>?action=212&deduction=<int>&auth_token=<str>**\n\n.. code-bolck:: python\n\n [\n {\n result: <int>, # 质检结果,\n weight: <int>, # 质检重量,\n quantity: <int>, # 质检数量, 若是计重类型的订单,可以不传\n }\n ]\n\n**<multiple_raw_picture_data>**\n\n* work_command_id - 工单id\n* action - 见 :py:mod:`lite_mms.constants.work_command` 中对各种工单操作的说明\n* \\*deduction - 扣量,必须以公斤为单位,默认为0\n* multiple_raw_picture_data - 多个图片文件,文件名为 **n.jpeg**, n从0开始计算,\n 对应第N个质检报告,例如\"2.jpeg\"对应第3个质检报告,这里允许质检报告没有对应的\n 图片\n\nresponse\n========\n\n* 200 - 成功\n\n 返回数据请参考 :ref:`assign-work-command`, 即处于结束状态的原工单\n \n* 403/401 - 失败\n\n一般可能发生在工单当前状态不是**待质检**\n\nexample\n=======\n\n 请参考 :ref:`assign-work-command`\n \n*********************************\nget-delivery-session-list(获取发货会话列表)\n*********************************\n\n获取的发货会话都是未完成的,而且有仓单的,按创建时间由近及远进行排序\n\n\nrequest\n=======\n**GET /delivery_ws/delivery-session-list&auth_token=<str>**\n\nresponse\n========\n* 200 - 成功\n\n.. code-block:: python\n\n [\n {\n \"sessionID\": <int>, # 会话ID\n \"plateNumber\": <str>, # 车牌号 \n \"isLocked\": 1|0, # 是否被锁定 \n },\n ...\n ]\n \n\n* 401 - 错误\n\n.. code-block:: python\n\n \"actual error reason\"\n\nexample\n=======\n* 请求\n**GET /delivery_ws/delivery-session-list&auth_token=xxx**\n\n* 响应\n\n * http code: 200\n * 数据\n\n.. code-block:: python\n\n [\n {\n \"sessionID\": 1,\n \"plateNumber\": \"ZA000001\",\n \"isLocked\": 0,\n },\n {\n \"sessionID\": 2,\n \"plateNumber\": \"ZA000002\",\n \"isLocked\": 0,\n },\n {\n \"sessionID\": 3,\n \"plateNumber\": \"ZA000003\",\n \"isLocked\": 0,\n }\n ]\n\n**************************************\nget-delivery-session(获取发货会话详情)\n**************************************\n\nrequest\n=======\n\n**GET /delivery_ws/delivery-session?id=<int>&auth_token=<str>**\n\nresponse\n========\n\n* 200 - 成功\n\n.. code-block:: python\n\n {\n \"id\": <int>, # 发货会话id\n \"plate\": <str>, # 车牌号\n \"store_bills\": { \n <str>: # 订单编号\n {\n <str>: # 子订单编号\n [ \n {\n \"id\": <int>, # 仓单ID\n \"harbor\": <str>, # 装卸点\n \"product_name\": <str>, # 产品名称\n \"customer_name\": <str>, # 客户名称\n \"pic_url\": <str>, # 图片链接\n \"unit\": <str>, # 单位\n }\n ...\n ]\n }\n ...\n } # 卸货任务列表,按创建时间,由新到旧进行排序\n }\n\n* 404/401 \n\n.. code-block:: python\n\n \"actual error reason\"\n \n\nexample\n=======\n\n.. code-block:: python\n\n {\n \"id\": 1, \n \"plate\": \"浙A 00001\",\n \"store_bills\": {\n \"123465691233\": {\n \"1\":\n [\n {\n \"id\": 1,\n \"habor\": \"卸货点1\",\n \"product_name\": \"螺丝\",\n \"customer_name\": \"宁波紧固件厂\",\n \"pic_url\": \"xxxxxxxx\",\n \"unit\": \"件\", \n },\n {\n \"id\": 2,\n \"habor\": \"卸货点2\",\n \"product_name\": \"螺母\",\n \"customer_name\": \"宁波紧固件厂\",\n \"pic_url\": \"xxxxxxxx\",\n \"unit\": \"件\", \n },\n ]\n \"2\":\n [\n {\n \"id\": 3,\n \"habor\": \"卸货点2\",\n \"product_name\": \"螺丝刀\",\n \"customer_name\": \"宁波紧固件厂\",\n \"pic_url\": \"xxxxxxxx\",\n \"unit\": \"件\", \n },\n ]\n }\n }\n }\n\n***********************************\npost-delivery-task(创建发货任务)\n***********************************\n\n已经完成的仓单不能反复提交, 只能选择同一个订单的一个或多个仓单,只能有一个未完成仓单\n\n此接口需要装卸工权限\n\nrequest\n=======\n\n**POST /delivery_ws/delivery-task?sid=<int>&is_finished=[0|1]&remain=<int>&auth_token=<str>**\n\n.. code-block:: python\n \n [\n {\n \"store_bill_id\": <int>, # 处理的仓单号\n \"is_finished\": <1|0>, # 该仓单是否完全装货, 1代表完全装货\n }\n ...\n ]\n\n* sid - 发货会话id\n* is_finished - 是否发货会话结束, 1代表结束\n* auth_token - login返回的token\n* \\*remain - 未完成件数(计件类型)或重量(计重类型),若有为完成仓单,为必填项\n\nresponse\n========\n\n* 200 - 成功\n\n.. code-block:: python\n\n {\n \"store_bill_id_list\": [\n <int>+, # 已经完成的仓单列表,其规则具体见[ticket 224]\n ],\n \"actor_id\": <int>, \n \"id\": <int>, # 新生成的发货任务ID\n }\n\n* 403/401 - 失败\n\n.. code-block:: python\n\n \"actual reason\"\n\n***********************************\nretrive-quality-inspection(打回质检单)\n***********************************\n\n前一天提交的或者生成的工单、仓单已经排产或者发货的都不能打回质检单\n\n此操作需要质检员权限\n\nrequest\n=======\n\n**PUT /manufacture_ws/work-command/<int>?action=214&auth_token=<str>**\n\n* work_command_id - 工单id\n* action - 见 :py:mod:`lite_mms.constants.work_command` 中对各种工单操作的说明\n\nresponse\n========\n\n* 200 - 成功\n\n 返回数据请参考 :ref:`assign-work-command`, 即处于结束状态的原工单\n \n* 403/401 - 失败\n\n.. code-block:: python\n\n \"actual reason\"\n\n\nexample\n=======\n\n 请参考 :ref:`assign-work-command`\n\n***********************************\nquick-carry-forward(快速结转)\n***********************************\n\n班组长可以将工单快速结转,使工单完成的部分先质检剩下的继续做\n此操作需要质检员权限\n\nrequest\n=======\n\n**PUT /manufacture_ws/work-command/<int>?action=215**\n\n* work_command_id - 工单id\n* action - 见 :py:mod:`lite_mms.constants.work_command` 中对各种工单操作的说明\n\nresponse\n========\n\n* 200 - 成功\n\n 返回数据请参考 :ref:`assign-work-command`, 即处于结束状态的原工单\n \n* 403/401 - 失败\n\n.. code-block:: python\n\n \"actual reason\"\n\n\nexample\n=======\n\n 请参考 :ref:`assign-work-command`\n\n********************\n临时保存质检报告列表\n********************\n\nrequest\n=======\n\n**PUT /manufacture_ws/quality-inspection-report-list?work_command_id=<work_command_id>**\n\nresponse\n========\n\n* 200 - 成功\n\n.. code-bolck:: python\n\n [\n {\n result: <int>, # 质检结果,\n weight: <int>, # 质检重量,\n quantity: <int>, # 质检数量, 若是计重类型的订单,可以不传\n }\n ]\n\n**<multiple_raw_picture_data>**\n\n* work_command_id - 工单id\n* actor_id - 发起人id,这里为质检员\n* multiple_raw_picture_data - 多个图片文件,文件名为 **n.jpeg**, n从0开始计算,\n 对应第N个质检报告,例如\"2.jpeg\"对应第3个质检报告,这里允许质检报告没有对应的\n 图片\n" }, { "alpha_fraction": 0.5670318007469177, "alphanum_fraction": 0.5681538581848145, "avg_line_length": 35.28087615966797, "blob_id": "533e5458c448c343bfc4f8c924a703fc1b3f1ea8", "content_id": "a762f16503c2cbdbc989ebbc6ad115e2ebb3c059", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19205, "license_type": "no_license", "max_line_length": 120, "num_lines": 502, "path": "/lite_mms/apis/order.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: Yangminghua\r\n\"\"\"\r\nfrom datetime import datetime, date, timedelta\r\nimport sys\r\nfrom flask import url_for, request\r\nfrom lite_mms.utilities import _\r\nfrom sqlalchemy import and_, or_\r\nfrom sqlalchemy.orm.exc import NoResultFound\r\nfrom werkzeug.utils import cached_property\r\nfrom lite_mms import models\r\nfrom lite_mms.apis import ModelWrapper\r\nimport lite_mms.constants as constants\r\nfrom lite_mms.utilities import do_commit\r\nfrom work_flow_repr.utils import make_tree\r\n\r\n\r\nclass OrderWrapper(ModelWrapper):\r\n @classmethod\r\n def get_list(cls, index=0, cnt=sys.maxint, after=None, customer_id=None,\r\n unfinished=False, customer_order_number=None,\r\n accountable_only=False, undispatched_only=False,\r\n deliverable_only=False, desc=None):\r\n query = models.Order.query\r\n if accountable_only or deliverable_only:\r\n # 只要有一个仓单尚未发货\r\n query = query.filter(models.Order.sub_order_list.any(\r\n models.SubOrder.store_bill_list.any(\r\n and_(models.StoreBill.weight > 0,\r\n models.StoreBill.delivery_task_id == None))))\r\n if accountable_only: # 可盘点的订单要求所有的工单都已经生产完毕\r\n # 所有的子订单都已经排产 == 不存在子订单,其剩余质量>0\r\n query = query.filter(\r\n ~models.Order.sub_order_list.any(\r\n models.SubOrder.remaining_quantity > 0))\r\n # 所有的子订单的工单都已经生成完毕==不存在子订单,其有工单未完成\r\n query = query.filter(~models.Order.sub_order_list.any(\r\n models.SubOrder.work_command_list.any(\r\n models.WorkCommand.status != constants.work_command\r\n .STATUS_FINISHED)))\r\n if undispatched_only:\r\n query = query.filter(~models.Order.dispatched)\r\n if customer_id:\r\n query = query.join(models.GoodsReceipt,\r\n models.GoodsReceipt.id == models.Order\r\n .goods_receipt_id).join(\r\n models.Customer,\r\n models.Customer.id == models.GoodsReceipt.customer_id).filter(\r\n models.Customer.id == customer_id)\r\n if after:\r\n query = query.filter(models.Order.create_time > after)\r\n if customer_order_number:\r\n query = query.filter(models.Order.customer_order_number.like(\r\n \"%\" + customer_order_number + \"%\"))\r\n if unfinished:\r\n query = query.filter(models.Order.finish_time == None).filter(\r\n models.Order.dispatched == True).filter(\r\n models.Order.sub_order_list.any(\r\n or_(models.SubOrder.remaining_quantity > 0,\r\n models.SubOrder.work_command_list.any(\r\n models.WorkCommand.status != constants.work_command.STATUS_FINISHED))))\r\n\r\n count = query.count()\r\n if desc:\r\n query = query.order_by(models.Order.create_time.desc())\r\n query = query.offset(index).limit(cnt)\r\n return [OrderWrapper(order) for order in query.all()], count\r\n\r\n @classmethod\r\n def get_order(cls, order_id):\r\n \"\"\"\r\n get order from database\r\n :return: the order with given id or None if fail\r\n \"\"\"\r\n if not order_id:\r\n return None\r\n try:\r\n return OrderWrapper(models.Order.query.filter(\r\n models.Order.id == order_id).one())\r\n except NoResultFound:\r\n return None\r\n\r\n @classmethod\r\n def new_order(cls, goods_receipt_id, order_type, creator_id):\r\n \"\"\"\r\n create a new order in database\r\n :return: the newly create order if there's corresponding goods receipt\r\n :raise: ValueError\r\n \"\"\"\r\n from lite_mms.apis import cargo\r\n\r\n goods_receipt = cargo.get_goods_receipt(goods_receipt_id)\r\n\r\n try:\r\n creator = models.User.query.filter_by(id=creator_id).one()\r\n except NoResultFound:\r\n raise ValueError(_(u\"没有此用户%d\" % creator_id))\r\n\r\n if order_type not in (\r\n constants.STANDARD_ORDER_TYPE, constants.EXTRA_ORDER_TYPE):\r\n raise ValueError(_(u\"非法的订单类型%d\" % order_type))\r\n else:\r\n order = models.Order(goods_receipt=goods_receipt, creator=creator)\r\n do_commit(order)\r\n if order_type == constants.STANDARD_ORDER_TYPE:\r\n sub_orders = []\r\n for entry in goods_receipt.goods_receipt_entries:\r\n sub_order = models.SubOrder(order=order,\r\n product=entry.product,\r\n weight=entry.weight,\r\n pic_path=entry.pic_path,\r\n harbor=entry.harbor,\r\n quantity=entry.weight,\r\n unit=u'KG',\r\n default_harbor=entry.harbor)\r\n sub_orders.append(sub_order)\r\n\r\n do_commit(sub_orders)\r\n return OrderWrapper(order)\r\n\r\n def __eq__(self, other):\r\n return isinstance(other, OrderWrapper) and other.id == self.id\r\n\r\n @property\r\n def measured_by_weight(self):\r\n return all(sub_order.measured_by_weight for sub_order in\r\n self.sub_order_list) if self.sub_order_list else False\r\n\r\n @property\r\n def qi_weight(self):\r\n return sum(so.qi_weight for so in self.sub_order_list)\r\n\r\n @property\r\n def urgent(self):\r\n return any(sub_order.urgent for sub_order in self.sub_order_list)\r\n\r\n @property\r\n def product_list(self):\r\n return [sb.product for sb in self.sub_order_list]\r\n\r\n @property\r\n def net_weight(self):\r\n \"\"\"\r\n 即收货重量\r\n \"\"\"\r\n return sum(entry.weight for entry in self.goods_receipt.goods_receipt_entries)\r\n\r\n @cached_property\r\n def remaining_weight(self):\r\n return sum(\r\n sub_order.remaining_weight for sub_order in self.sub_order_list)\r\n\r\n @cached_property\r\n def remaining_quantity(self):\r\n return sum(\r\n sub_order.remaining_quantity for sub_order in self.sub_order_list)\r\n\r\n @cached_property\r\n def delivered_weight(self):\r\n return sum(\r\n sub_order.delivered_weight for sub_order in self.sub_order_list)\r\n\r\n @cached_property\r\n def to_deliver_weight(self):\r\n return sum(\r\n sub_order.to_deliver_weight for sub_order in self.sub_order_list)\r\n\r\n @cached_property\r\n def to_deliver_store_bill_list(self):\r\n import itertools\r\n\r\n return list(\r\n itertools.chain.from_iterable(sub_order.to_deliver_store_bill_list for sub_order in self.sub_order_list))\r\n\r\n @cached_property\r\n def manufacturing_weight(self):\r\n \"\"\"\r\n 生产中重量\r\n \"\"\"\r\n return sum(sub_order.manufacturing_weight for sub_order in self.sub_order_list)\r\n\r\n @cached_property\r\n def manufacturing_work_command_list(self):\r\n import itertools\r\n\r\n return list(itertools.chain.from_iterable(\r\n sub_order.manufacturing_work_command_list for sub_order in self.sub_order_list))\r\n\r\n @property\r\n def can_refine(self):\r\n return self.sub_order_list and all(sb.refined for sb in self.sub_order_list)\r\n\r\n @property\r\n def can_account(self):\r\n # 所有的子订单已经排产\r\n ret = all(so.remaining_quantity == 0 for so in self.sub_order_list)\r\n # 所有子订单都已经生产完毕\r\n for so in self.sub_order_list:\r\n ret = ret and all(wc.status == constants.work_command.STATUS_FINISHED for wc in so.work_command_list)\r\n # 至少有一个仓单尚未发货\r\n ret = ret and any(\r\n any(sb.weight > 0 and not sb.delivery_task for sb in so.store_bill_list) for so in self.sub_order_list)\r\n return ret\r\n\r\n @property\r\n def customer(self):\r\n return self.goods_receipt.customer\r\n\r\n @property\r\n def to_work_weight(self):\r\n return sum(sum(work_command.org_weight for work_command in\r\n sub_order.pre_work_command_list) for sub_order in\r\n self.sub_order_list)\r\n\r\n @property\r\n def done_work_command_list(self):\r\n ret = []\r\n for sub_order in self.sub_order_list:\r\n ret.extend(sub_order.done_work_command_list)\r\n return ret\r\n\r\n @property\r\n def done_work_weight(self):\r\n return sum(sum(work_command.processed_weight for work_command in\r\n sub_order.done_work_command_list) for sub_order in self\r\n .sub_order_list)\r\n\r\n @property\r\n def todo_work_cnt(self):\r\n return sum(len(sub_order.pre_work_command_list) for sub_order in self.sub_order_list)\r\n\r\n @property\r\n def order_type(self):\r\n return self.sub_order_list[\r\n 0].order_type if self.sub_order_list else constants \\\r\n .EXTRA_ORDER_TYPE\r\n\r\n def update(self, **kwargs):\r\n for k, v in kwargs.items():\r\n if hasattr(self.model, k) and v not in (None, u''):\r\n setattr(self.model, k, v)\r\n do_commit(self.model)\r\n\r\n @property\r\n def warning(self):\r\n return self.net_weight > (self.remaining_weight + self.to_work_weight +\r\n self.manufacturing_weight + self.qi_weight +\r\n self.to_deliver_weight + self.delivered_weight)\r\n\r\n @property\r\n def url(self):\r\n from lite_mms.permissions.order import schedule_order, view_order\r\n if view_order.can():\r\n return url_for(\"order.order\", id_=self.id, url=request.url)\r\n elif schedule_order.can():\r\n return url_for(\"schedule.order\", id_=self.id, url=request.url)\r\n else:\r\n return \"\"\r\n\r\n @cached_property\r\n def qi_work_command_list(self):\r\n import itertools\r\n return list(itertools.chain.from_iterable(sub_order.qi_work_command_list for sub_order in self.sub_order_list))\r\n\r\n @cached_property\r\n def work_command_list(self):\r\n import itertools\r\n return list(itertools.chain.from_iterable(sub_order.work_command_list for sub_order in self.sub_order_list))\r\n\r\n def add_todo(self):\r\n from lite_mms.apis import auth, todo\r\n for to in auth.get_user_list(constants.groups.SCHEDULER):\r\n todo.new_todo(to, todo.DISPATCH_ORDER, self)\r\n\r\n @property\r\n def log_list(self):\r\n from lite_mms.apis.log import LogWrapper\r\n\r\n ret = LogWrapper.get_log_list(str(self.id), self.model.__class__.__name__)\r\n for sub_order in self.sub_order_list:\r\n ret.extend(sub_order.log_list)\r\n return sorted(ret, lambda a, b: cmp(a.create_time, b.create_time), reverse=True)\r\n\r\n @property\r\n def work_flow_json(self):\r\n try:\r\n return make_tree(self.goods_receipt)\r\n except AttributeError, e:\r\n raise Exception(e.message)\r\n\r\n\r\nclass SubOrderWrapper(ModelWrapper):\r\n\r\n @classmethod\r\n def new_sub_order(cls, **kwargs):\r\n \"\"\"新建计件类型的子订单。\r\n \"\"\"\r\n order = get_order(kwargs[\"order_id\"])\r\n if not order:\r\n raise ValueError(_(u'订单%d不存在') % kwargs[\"order_id\"])\r\n\r\n try:\r\n harbor = models.Harbor.query.filter(\r\n models.Harbor.name == kwargs[\"harbor_name\"]).one()\r\n except NoResultFound:\r\n raise ValueError(_(u'装卸点%(harbor)s不存在') % kwargs[\"harbor_name\"])\r\n\r\n try:\r\n product = models.Product.query.filter(\r\n models.Product.id == kwargs[\"product_id\"]).one()\r\n except NoResultFound:\r\n raise ValueError(_(u'产品%(product_id)不存在') % kwargs[\"product_id\"])\r\n\r\n sb = models.SubOrder(harbor=harbor,\r\n product=product,\r\n spec=kwargs[\"spec\"],\r\n type=kwargs[\"type\"],\r\n order=order,\r\n urgent=kwargs[\"urgent\"],\r\n returned=kwargs[\"returned\"],\r\n tech_req=kwargs[\"tech_req\"],\r\n quantity=kwargs[\"quantity\"],\r\n unit=kwargs[\"unit\"],\r\n due_time=kwargs[\"due_time\"],\r\n order_type=constants.EXTRA_ORDER_TYPE,\r\n weight=kwargs[\"weight\"])\r\n\r\n return SubOrderWrapper(do_commit(sb))\r\n\r\n @property\r\n def goods_receipt(self):\r\n return self.order.goods_receipt\r\n\r\n @property\r\n def customer(self):\r\n return self.goods_receipt.customer\r\n\r\n @property\r\n def measured_by_weight(self):\r\n return self.order_type == constants.STANDARD_ORDER_TYPE\r\n\r\n @property\r\n def pic_url(self):\r\n if self.pic_path:\r\n return url_for(\"serv_pic\", filename=self.pic_path)\r\n else:\r\n return \"\"\r\n\r\n @classmethod\r\n def get_sub_order(cls, sub_order_id):\r\n if not sub_order_id:\r\n return None\r\n try:\r\n return SubOrderWrapper(\r\n models.SubOrder.query.filter_by(\r\n id=sub_order_id).one())\r\n except NoResultFound:\r\n return None\r\n\r\n def update(self, **kwargs):\r\n if self.model.order.dispatched:\r\n raise ValueError(u\"已下发的订单不能再修改\")\r\n for k, v in kwargs.items():\r\n if hasattr(self.model, k) and v != u'':\r\n if k.__eq__(\"due_time\"):\r\n setattr(self.model, k, datetime.strptime(v, '%Y-%m-%d'))\r\n continue\r\n setattr(self.model, k, v)\r\n if k.__eq__(\r\n \"weight\") and self.order_type == constants.STANDARD_ORDER_TYPE:\r\n setattr(self.model, \"quantity\", v)\r\n if k.__eq__(\"quantity\") and not self.model.order.dispatched:\r\n self.model.remaining_quantity = v\r\n do_commit(self.model)\r\n\r\n def end(self):\r\n self.model.finish_time = datetime.now()\r\n do_commit(self.model)\r\n\r\n def delete(self):\r\n do_commit(self.model, \"delete\")\r\n\r\n def __eq__(self, other):\r\n return isinstance(other, SubOrderWrapper) and other.id == self.id\r\n\r\n @cached_property\r\n def pre_work_command_list(self):\r\n return [work_command for work_command in self.work_command_list if\r\n work_command.status in (\r\n constants.work_command.STATUS_DISPATCHING,\r\n constants.work_command.STATUS_REFUSED)]\r\n\r\n @cached_property\r\n def manufacturing_work_command_list(self):\r\n manufacturing_status_set = {constants.work_command.STATUS_ASSIGNING,\r\n constants.work_command.STATUS_ENDING,\r\n constants.work_command.STATUS_LOCKED}\r\n return [work_command for work_command in self.work_command_list if\r\n work_command.status in manufacturing_status_set]\r\n\r\n @property\r\n def qi_work_command_list(self):\r\n return [work_command for work_command in self.work_command_list if\r\n work_command.status == constants.work_command.STATUS_QUALITY_INSPECTING]\r\n\r\n @cached_property\r\n def done_work_command_list(self):\r\n return [work_command for work_command in self.work_command_list if\r\n work_command.status == constants.work_command\r\n .STATUS_FINISHED and work_command.procedure and (\r\n not work_command.parent_qir or work_command.parent_qir.result == constants.quality_inspection.FINISHED)]\r\n\r\n @cached_property\r\n def remaining_weight(self):\r\n \"\"\"\r\n 未预排产重量\r\n \"\"\"\r\n return self.remaining_quantity * self.weight / self.quantity\r\n\r\n @cached_property\r\n def delivered_weight(self):\r\n ret = {}\r\n for sb in self.store_bill_list:\r\n if sb.delivery_task_id:\r\n ret.setdefault(sb.delivery_task_id, sb.delivery_task)\r\n return sum(dt.weight for dt in ret.values())\r\n\r\n @cached_property\r\n def manufacturing_weight(self):\r\n return sum(\r\n work_command.org_weight for work_command in self\r\n .manufacturing_work_command_list)\r\n\r\n @property\r\n def qi_weight(self):\r\n return sum(work_command.processed_weight for work_command in self.qi_work_command_list)\r\n\r\n @cached_property\r\n def to_deliver_weight(self):\r\n return sum(store_bill.weight for store_bill in self.to_deliver_store_bill_list)\r\n\r\n @cached_property\r\n def to_deliver_store_bill_list(self):\r\n return [store_bill for store_bill in self.store_bill_list if not store_bill.delivery_task_id]\r\n\r\n @property\r\n def log_list(self):\r\n from lite_mms.apis.log import LogWrapper\r\n\r\n ret = LogWrapper.get_log_list(str(self.id), self.model.__class__.__name__)\r\n return sorted(ret, lambda a, b: cmp(a.create_time, b.create_time), reverse=True)\r\n\r\n @property\r\n def refined(self):\r\n return self.due_time and self.product.name != constants.DEFAULT_PRODUCT_NAME\r\n\r\ndef get_order_type_list():\r\n t1 = dict(id=constants.STANDARD_ORDER_TYPE,\r\n name=constants.STANDARD_ORDER_TYPE_NAME)\r\n t2 = dict(id=constants.EXTRA_ORDER_TYPE,\r\n name=constants.EXTRA_ORDER_TYPE_NAME)\r\n return [t1, t2]\r\n\r\n\r\ndef get_customer_list(time_span, dispatched=False):\r\n \"\"\"\r\n 获取指定时间段内有订单的客户\r\n \"\"\"\r\n cst_q = models.Customer.query.join(models.GoodsReceipt).join(\r\n models.Order)\r\n if dispatched:\r\n customers = cst_q.filter(models.Order.dispatched == True).filter(\r\n models.Order.finish_time == None).distinct()\r\n else:\r\n should_after = get_should_after_date(time_span)\r\n customers = cst_q.filter(\r\n models.Order.create_time > should_after).distinct()\r\n return customers\r\n\r\n\r\ndef get_should_after_date(time_span):\r\n if time_span == \"day\":\r\n # date类型的str方法能够自动按照ISO_8601转换为字符串。而且,sqlalchemy\r\n # 能够将这种字符串转换为时间\r\n should_after = date.today()\r\n elif time_span == \"week\":\r\n should_after = date.today() - timedelta(7)\r\n elif time_span == \"month\":\r\n should_after = date.today() - timedelta(30)\r\n else: # 不限时间,那么我们不加此限制\r\n should_after = date.fromtimestamp(0L)\r\n return should_after\r\n\r\n\r\nnew_order = OrderWrapper.new_order\r\nget_order = OrderWrapper.get_order\r\nget_order_list = OrderWrapper.get_list\r\nget_sub_order = SubOrderWrapper.get_sub_order\r\n\r\nif __name__ == \"__main__\":\r\n pass\r\n" }, { "alpha_fraction": 0.49635037779808044, "alphanum_fraction": 0.540145993232727, "avg_line_length": 17.571428298950195, "blob_id": "8751c9762a613b72615ac306603d73ae06c6e860", "content_id": "e7c15af1d5f47ca20ac6566e6e60c4795b130749", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 173, "license_type": "no_license", "max_line_length": 29, "num_lines": 7, "path": "/lite_mms/constants/quality_inspection.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\r\nFINISHED = 1 #: 通过并结束\r\nNEXT_PROCEDURE = 2 #: 通过转下道工序\r\nREPAIR = 3 #: 返修\r\nREPLATE = 4 #: 返镀\r\nDISCARD = 5 #: 报废\r\n" }, { "alpha_fraction": 0.5748744010925293, "alphanum_fraction": 0.6331658363342285, "avg_line_length": 24.236841201782227, "blob_id": "34fc4972c8c8acc85406d8d1216fb79fb9fc0c00", "content_id": "c51cac9463599f0186c25e636024cf05fcd9ae36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1351, "license_type": "no_license", "max_line_length": 41, "num_lines": 38, "path": "/lite_mms/constants/work_command.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\r\nSTATUS_DISPATCHING = 1 #: 待排产\r\nSTATUS_ASSIGNING = 2 #: 待分配\r\nSTATUS_LOCKED = 3 #: 锁定, 待车间主任确认回收\r\nSTATUS_ENDING = 4 #: 待结转或结束\r\nSTATUS_QUALITY_INSPECTING = 7 #: 待质检\r\nSTATUS_REFUSED = 8 #: 车间主任打回\r\nSTATUS_FINISHED = 9 #: 已经结束\r\n\r\nACT_CHECK = 201 #: (调度员)检货\r\nACT_DISPATCH = 202 #: (调度员)排产\r\nACT_ASSIGN = 203 #: (车间主任)分配工单\r\nACT_ADD_WEIGHT = 204 #: (班组长)增加工单白件重量\r\nACT_END = 205 #: (班组长)请求结束 \r\nACT_CARRY_FORWARD = 206 #: (班组长)请求结转\r\nACT_REFUSE = 209 #: (车间主任)打回工单\r\nACT_RETRIEVAL = 210 #: (调度员)请求回收工单\r\nACT_AFFIRM_RETRIEVAL = 211 #: (车间主任)确认回收\r\nACT_QI = 212 #: (质检员)质检\r\nACT_REFUSE_RETRIEVAL = 213 #: (车间主任)拒绝回收\r\nACT_RETRIVE_QI = 214 #:(质检员)取消质检报告\r\nACT_QUICK_CARRY_FORWARD = 215 #:(班组长)快速结转\r\n\r\n# handle types\r\nHT_NORMAL = 1 #:正常加工\r\nHT_REPLATE = 2 #:返镀\r\nHT_REPAIRE = 3 #:返修\r\n\r\nPROCEDURE_FIRST = 1#:第一道工序\r\nPROCEDURE_END = 2#:合格,结束\r\nPROCEDURE_NEXT = 3#:质检完毕转下道工序\r\n\r\nCAUSE_NORMAL = 1 # 预排产\r\nCAUSE_NEXT = 2 # 转下道工序\r\nCAUSE_REPAIR = 3 # 返修\r\nCAUSE_REPLATE = 4 # 返镀\r\nCAUSE_CARRY = 5 # 结转" }, { "alpha_fraction": 0.6034665107727051, "alphanum_fraction": 0.6114986538887024, "avg_line_length": 28.94936752319336, "blob_id": "16a2cd060145082ebf5f8bb02678fece3e7a48db", "content_id": "2a272a80b9eea0e0d34238e39b6daf978b771091", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5261, "license_type": "no_license", "max_line_length": 116, "num_lines": 158, "path": "/lite_mms/portal/delivery/actions.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom flask import redirect, url_for, request\nfrom flask.ext.databrowser.action import BaseAction, DirectAction, DeleteAction\n\nfrom lite_mms.utilities.decorators import committed\nfrom lite_mms import constants\n\n\nclass CloseAction(BaseAction):\n def test_enabled(self, model):\n if model.status in [constants.delivery.STATUS_CLOSED, constants.delivery.STATUS_DISMISSED]:\n return -2\n if not all(task.weight for task in model.delivery_task_list):\n return -3\n return 0\n\n def op(self, obj):\n from lite_mms.portal.delivery.fsm import fsm\n from flask.ext.login import current_user\n\n fsm.reset_obj(obj)\n fsm.next(constants.delivery.ACT_CLOSE, current_user)\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"发货会话%s已经被关闭\",\n -3: u\"发货会话%s有发货任务没有称重,请确保所有的发货任务都已经称重!\"}\n\n\nclass OpenAction(BaseAction):\n def test_enabled(self, model):\n if model.status != constants.delivery.STATUS_CLOSED:\n return -2\n if any(cn.MSSQL_ID for cn in model.consignment_list):\n return -3\n return 0\n\n def op(self, obj):\n from lite_mms.portal.delivery.fsm import fsm\n from flask.ext.login import current_user\n\n fsm.reset_obj(obj)\n fsm.next(constants.delivery.ACT_OPEN, current_user)\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"发货会话%s处在打开状态, 只有已经关闭的会话才能被打开\",\n -3: u\"发货会话%s存在已导入旧系统的发货单,无法重新打开\"}\n\n\nclass CreateConsignmentAction(DirectAction):\n \"\"\"\n 生成发货单是很特殊的action。需要传入额外的参数。\n \"\"\"\n\n def test_enabled(self, model):\n if model.consignment_list:\n if all(not cn.stale for cn in model.consignment_list) and len(\n model.consignment_list) == len(model.customer_list):\n return -2\n if any(cn.MSSQL_ID for cn in model.consignment_list):\n return -3\n if any(cn.pay_in_cash and cn.is_paid for cn in model.consignment_list):\n return -5\n elif not model.delivery_task_list:\n return -4\n return 0\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"发货会话%s已生成发货单\",\n -3: u\"发货会话%s存在已导入旧系统的发货单,无法重新生成\",\n -4: u\"发货会话%s没有发货任务,请先生成发货任务\",\n -5: u\"发货会话%s的发货单已支付\"}\n\n\nclass BatchPrintConsignment(DirectAction):\n def op_upon_list(self, objs, model_view):\n for obj in objs:\n model_view.do_update_log(obj, self.name)\n return redirect(url_for(\"consignment.batch_print_consignment\", delivery_session_id=[obj.id for obj in objs],\n url=request.url))\n\n def test_enabled(self, model):\n if not model.consignment_list:\n return -2\n if any(cn.pay_in_cash and not cn.is_paid for cn in model.consignment_list):\n return -3\n return 0\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"发货会话%s未生成发货单\", -3: u\"发货会话%s有未支付的发货单\"}\n\n\nclass PayAction(BaseAction):\n def test_enabled(self, model):\n if model.stale:\n return -2\n return 0\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"发货单%s已过时,请联系收发员重新生成\"}\n\n @committed\n def op(self, obj):\n obj.is_paid = True\n obj.remove_todo()\n\n\nclass PreviewConsignment(DirectAction):\n def op_upon_list(self, objs, model_view):\n return redirect(url_for(\"delivery.consignment_preview\", id_=objs[0].id, url=request.url))\n\n\nclass DeleteDeliverySession(DeleteAction):\n def test_enabled(self, model):\n if model.consignment_list:\n return -2\n return 0\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"发货会话%s已经生成了发货单,请先删除对应发货单以后再删除此发货会话!\"}\n\n def op(self, obj):\n from lite_mms.apis.todo import remove_todo, WEIGH_DELIVERY_TASK\n\n for task in obj.delivery_task_list:\n remove_todo(WEIGH_DELIVERY_TASK, task.id)\n super(DeleteDeliverySession, self).op(obj)\n\n\nclass DeleteConsignment(DeleteAction):\n def test_enabled(self, model):\n if model.MSSQL_ID:\n return -2\n return 0\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"已导入到MSSQL的发货单不能删除\"}\n\n\nclass PersistConsignmentAction(BaseAction):\n def test_enabled(self, model):\n if model.MSSQL_ID:\n return -2\n return 0\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"已导入到MSSQL的发货单不能删除\"}\n\n def op(self, obj):\n obj.persist()\n\n def op_upon_list(self, objs, model_view):\n error = \"\"\n try:\n for obj in objs:\n self._op(obj, model_view)\n except ValueError, e:\n error += unicode(e.message)\n return \"\", error" }, { "alpha_fraction": 0.5607182383537292, "alphanum_fraction": 0.5628962516784668, "avg_line_length": 46.843971252441406, "blob_id": "ef5743f9ae2c6f029b66bc22667b32c01f465e98", "content_id": "bedb2ffe56d63e806c0a6664066314aab6c69fef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21947, "license_type": "no_license", "max_line_length": 118, "num_lines": 423, "path": "/lite_mms/portal/order/views.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: Yangminghua\r\n\"\"\"\r\nfrom collections import OrderedDict\r\nfrom datetime import date\r\n\r\nfrom flask import (request, url_for, render_template, abort, flash, redirect,\r\n json, current_app)\r\nfrom flask.ext.login import current_user, login_required\r\nfrom flask.ext.principal import PermissionDenied, Permission\r\nfrom flask.ext.databrowser import ModelView, filters\r\nfrom flask.ext.databrowser.column_spec import (InputColumnSpec, LinkColumnSpec, ColumnSpec, TableColumnSpec,\r\n ImageColumnSpec, PlaceHolderColumnSpec)\r\nfrom wtforms import Form, TextField, IntegerField, validators, BooleanField, DateField, HiddenField\r\n\r\nfrom lite_mms import constants\r\nfrom lite_mms.portal.order import order_page\r\nfrom lite_mms.utilities import decorators\r\nfrom lite_mms.permissions import SchedulerPermission, CargoClerkPermission\r\nfrom lite_mms.models import Order, SubOrder, Product, Customer\r\nfrom lite_mms.portal.order.filters import category_filter, only_unfinished_filter, no_individual\r\n\r\n\r\nclass OrderModelView(ModelView):\r\n list_template = \"order/order-list.html\"\r\n\r\n def try_create(self):\r\n raise PermissionDenied\r\n\r\n can_batchly_edit = False\r\n\r\n @login_required\r\n def try_view(self, processed_objs=None):\r\n pass\r\n\r\n def __list_filters__(self):\r\n if SchedulerPermission.can():\r\n ret = [\r\n filters.EqualTo(\"finish_time\", value=None),\r\n filters.EqualTo(\"refined\", value=True),\r\n filters.EqualTo(\"dispatched\", value=True),\r\n only_unfinished_filter,\r\n ]\r\n else:\r\n ret = []\r\n if current_app.config['HIDE_INDIVIDUAL']:\r\n ret.append(no_individual)\r\n return ret\r\n\r\n __list_columns__ = [\"id\", \"customer_order_number\", \"goods_receipt.customer\", \"net_weight\", \"remaining_weight\",\r\n PlaceHolderColumnSpec(col_name=\"manufacturing_work_command_list\", label=u\"生产中重量\",\r\n template_fname=\"order/todo-work-command-list-snippet.html\",\r\n doc=u\"若大于0,请敦促车间生产\"),\r\n PlaceHolderColumnSpec(col_name=\"qi_work_command_list\", label=u\"待质检重量\",\r\n template_fname=\"order/qi-list-snippet.html\"),\r\n PlaceHolderColumnSpec(col_name=\"done_work_command_list\", label=u\"已完成重量\",\r\n template_fname=\"order/done-work-command-list-snippet.html\",\r\n doc=u\"指订单下所有是最后一道工序的工单,这类工单的工序后质量之和\"),\r\n PlaceHolderColumnSpec(col_name=\"to_deliver_store_bill_list\", label=u\"待发货重量\",\r\n template_fname=\"order/store-bill-list-snippet.html\"),\r\n \"delivered_weight\", \"create_time\", \"dispatched_time\", \"goods_receipt\",\r\n ColumnSpec(\"urgent\",\r\n formatter=lambda v, obj: u\"<span class='text-danger'>是</span>\" if v else u\"否\"),\r\n ColumnSpec(\"refined\",\r\n formatter=lambda v, obj: u\"<span class='text-danger'>否</span>\" if not v else u\"是\")]\r\n\r\n def repr_obj(self, obj):\r\n return unicode(obj) + \"<br /><p class='text-center'><small class='muted'>\" + unicode(\r\n obj.goods_receipt.customer) + \"</small></p>\"\r\n\r\n __sortable_columns__ = [\"id\", \"customer_order_number\", \"goods_receipt.customer\", \"create_time\", \"goods_receipt\"]\r\n\r\n __column_labels__ = {\"customer_order_number\": u\"订单号\", \"goods_receipt.customer\": u\"客户\", \"create_time\": u\"创建时间\",\r\n \"goods_receipt\": u\"收货单\", \"net_weight\": u\"收货重量\", \"remaining_weight\": u\"待调度重量\",\r\n \"delivered_weight\": u\"已发货重量\", \"refined\": u\"完善\", \"urgent\": u\"加急\", \"product\": u\"产品\",\r\n \"category\": u\"类型\", \"dispatched_time\": u\"下发时间\"}\r\n\r\n __column_docs__ = {\"remaining_weight\": u\"若大于0,请敦促调度员排产\"}\r\n\r\n __column_formatters__ = {\r\n \"urgent\": lambda v, obj: u\"是\" if v else u\"否\",\r\n \"customer_order_number\": lambda v, obj: v.join(\r\n [\"\" if not obj.warning else '<i class=\" fa fa-exclamation-triangle\"></i>',\r\n u\"<b>(退货)</b>\" if any(so.returned for so in obj.sub_order_list) else \"\"]),\r\n \"remaining_weight\": lambda v, obj: unicode(v + obj.to_work_weight),\r\n \"refined\": lambda v, obj: u\"是\" if v else u\"否\",\r\n \"create_time\": lambda v, obj: v.strftime(\"%m-%d %H\") + u\"点\",\r\n \"dispatched_time\": lambda v, obj: v.strftime(\"%m-%d %H\") + u\"点\" if v and obj.dispatched else \"\"}\r\n\r\n def get_column_filters(self):\r\n from datetime import datetime, timedelta\r\n\r\n today = datetime.today()\r\n yesterday = today.date()\r\n week_ago = (today - timedelta(days=7)).date()\r\n _30days_ago = (today - timedelta(days=30)).date()\r\n ret = [\r\n filters.EqualTo(\r\n \"goods_receipt.customer\", name=u\"是\",\r\n options=(\r\n [(i.id, i.name) for i in Customer.query.all() if u'个体' not in i.name] if\r\n current_app.config['HIDE_INDIVIDUAL'] else\r\n [(i.id, i.name) for i in Customer.query.all()]\r\n )\r\n ),\r\n filters.BiggerThan(\"create_time\", name=u\"在\", options=[\r\n (yesterday, u'一天内'), (week_ago, u'一周内'), (_30days_ago, u'30天内')]),\r\n category_filter\r\n ]\r\n if not SchedulerPermission.can():\r\n ret.append(only_unfinished_filter)\r\n return ret\r\n\r\n def preprocess(self, model):\r\n from lite_mms.apis.order import OrderWrapper\r\n\r\n return OrderWrapper(model)\r\n\r\n def get_customized_actions(self, processed_objs=None):\r\n __customized_actions__ = []\r\n if CargoClerkPermission.can():\r\n from lite_mms.portal.order.actions import dispatch_action, mark_refined_action, account_action, \\\r\n new_extra_order_action\r\n\r\n if processed_objs:\r\n if not processed_objs[0].refined:\r\n __customized_actions__.append(mark_refined_action)\r\n if not processed_objs[0].dispatched and not processed_objs[0].measured_by_weight:\r\n __customized_actions__.append(new_extra_order_action)\r\n elif not processed_objs[0].dispatched:\r\n __customized_actions__.append(dispatch_action)\r\n if processed_objs[0].can_account:\r\n __customized_actions__.append(account_action)\r\n else:\r\n __customized_actions__ = [dispatch_action, mark_refined_action, account_action]\r\n return __customized_actions__\r\n\r\n def patch_row_attr(self, idx, row):\r\n if not row.refined:\r\n return {\"class\": \"warning\", \"title\": u\"此订单没有完善,请先完善订单\"}\r\n elif row.urgent and row.remaining_quantity:\r\n return {\"class\": \"danger\", \"title\": u\"此订单请加急完成\"}\r\n elif row.warning:\r\n return {\"title\": u\"此订单的收货重量大于未分配重量,生产中重量,已发货重量,待发货重量之和\"}\r\n\r\n def url_for_object(self, model, **kwargs):\r\n if model:\r\n return url_for(\"order.order\", id_=model.id, **kwargs)\r\n else:\r\n return url_for(\"order.order\", **kwargs)\r\n\r\n __default_order__ = (\"id\", \"desc\")\r\n\r\n def get_form_columns(self, obj=None):\r\n form_columns = OrderedDict()\r\n form_columns[u\"订单详情\"] = [\r\n \"customer_order_number\", ColumnSpec(\"goods_receipt.customer\"),\r\n ColumnSpec(\"goods_receipt\", css_class=\"control-text\", label=u\"收货单\"), \"net_weight\",\r\n ColumnSpec(\"create_time\"),\r\n ColumnSpec(\"dispatched_time\", formatter=lambda v, obj: v if v and obj.dispatched else \"\"),\r\n PlaceHolderColumnSpec(\"log_list\", label=u\"日志\", template_fname=\"logs-snippet.html\")]\r\n\r\n form_columns[u\"子订单列表\"] = [\r\n PlaceHolderColumnSpec(\"sub_order_list\", template_fname=\"order/sub-order-list-snippet.html\", label=\"\")]\r\n if SchedulerPermission.can():\r\n from lite_mms.portal.manufacture.views import work_command_view\r\n\r\n form_columns[u\"工单列表\"] = [TableColumnSpec(\"work_command_list\", label=\"\", col_specs=[\r\n LinkColumnSpec(\"id\", label=u\"编号\", anchor=lambda v: v,\r\n formatter=lambda v, obj: work_command_view.url_for_object(obj, url=request.url)),\r\n ColumnSpec(\"sub_order.id\", label=u\"子订单编号\"), ColumnSpec(\"product\", label=u\"产品名称\"),\r\n ColumnSpec(\"urgent\", label=u\"加急\",\r\n formatter=lambda v, obj: u\"<span class='text-danger'>是</span>\" if v else u\"否\"),\r\n ColumnSpec(\"sub_order.returned\", label=u\"退镀\",\r\n formatter=lambda v, obj: u\"<span class='text-danger'>是</span>\" if v else u\"否\"),\r\n ColumnSpec(\"org_weight\", label=u\"工序前重量\"), ColumnSpec(\"org_cnt\", label=u\"工序前数量\"),\r\n ColumnSpec(\"unit\", label=u\"单位\"), ColumnSpec(\"processed_weight\", label=u\"工序后重量\"),\r\n ColumnSpec(\"processed_cnt\", label=u\"工序后数量\"), ColumnSpec(\"tech_req\", label=u\"技术要求\"),\r\n ColumnSpec(\"department\", label=u\"车间\"), ColumnSpec(\"team\", label=u\"班组\"),\r\n ColumnSpec(\"qi\", label=u\"质检员\"), ColumnSpec(\"status_name\", label=u\"状态\")])]\r\n\r\n form_columns[u'订单流程图'] = [\r\n PlaceHolderColumnSpec('work_flow_json', template_fname='order/order-work-flow-snippet.html', label='')]\r\n return form_columns\r\n\r\n def try_edit(self, processed_objs=None):\r\n Permission.union(SchedulerPermission, CargoClerkPermission).test()\r\n if processed_objs and processed_objs[0].refined or processed_objs[0].dispatched:\r\n raise PermissionDenied\r\n\r\n def edit_hint_message(self, obj, read_only=False):\r\n if read_only:\r\n if SchedulerPermission.can():\r\n return u\"正在排产订单%s\" % obj.customer_order_number\r\n else:\r\n if obj.refined:\r\n return u\"订单%s已标记完善,不能修改\" % obj.customer_order_number\r\n if obj.refined:\r\n return u\"订单%s已下发,不能修改\" % obj.customer_order_number\r\n return \"\"\r\n else:\r\n return super(OrderModelView, self).edit_hint_message(obj, read_only)\r\n\r\n\r\nclass SubOrderModelView(ModelView):\r\n \"\"\"\r\n\r\n \"\"\"\r\n can_batchly_edit = False\r\n\r\n edit_template = \"order/sub-order.html\"\r\n\r\n def try_edit(self, processed_objs=None):\r\n Permission.union(SchedulerPermission, CargoClerkPermission).test()\r\n\r\n if processed_objs:\r\n if processed_objs[0].order.refined or processed_objs[0].order.dispatched:\r\n raise PermissionDenied\r\n\r\n @login_required\r\n def try_view(self, processed_objs=None):\r\n pass\r\n\r\n def edit_hint_message(self, obj, read_only=False):\r\n if read_only:\r\n if obj.order.refined:\r\n return u\"子订单%s已标记完善,不能修改\" % obj.id\r\n if obj.order.dispatched:\r\n return u\"子订单%s已下发,不能修改\" % obj.id\r\n else:\r\n return super(SubOrderModelView, self).edit_hint_message(obj, read_only)\r\n\r\n def get_form_columns(self, obj=None):\r\n\r\n form_columns = [ColumnSpec(\"id\", label=u\"编号\"), ColumnSpec(\"create_time\"), ColumnSpec(\"harbor\"),\r\n InputColumnSpec(\"product\", group_by=Product.product_type),\r\n InputColumnSpec(\"due_time\", validators=[validators.Required(message=u\"该字段不能为空\")]), \"weight\"]\r\n if obj and obj.order_type == constants.EXTRA_ORDER_TYPE:\r\n form_columns.extend([\"quantity\", \"unit\", \"spec\", \"type\"])\r\n form_columns.extend([\"tech_req\", \"urgent\", \"returned\",\r\n PlaceHolderColumnSpec(\"pic_url\", label=u\"图片\", template_fname=\"pic-snippet.html\",\r\n form_width_class=\"col-lg-3\"),\r\n PlaceHolderColumnSpec(\"log_list\", label=u\"日志\", template_fname=\"logs-snippet.html\")])\r\n return form_columns\r\n\r\n __column_labels__ = {\"product\": u\"产品\", \"weight\": u\"净重(公斤)\", \"harbor\": u\"卸货点\", \"urgent\": u\"加急\", \"returned\": u\"退镀\",\r\n \"tech_req\": u\"技术要求\", \"create_time\": u\"创建时间\", \"due_time\": u\"交货日期\", \"quantity\": u\"数量\",\r\n \"unit\": u\"数量单位\", \"type\": u\"型号\", \"spec\": u\"规格\"}\r\n\r\n def preprocess(self, obj):\r\n from lite_mms.apis.order import SubOrderWrapper\r\n\r\n return SubOrderWrapper(obj)\r\n\r\n def on_model_change(self, form, model):\r\n if model.order_type == constants.STANDARD_ORDER_TYPE:\r\n model.quantity = model.weight\r\n model.remaining_quantity = model.quantity\r\n\r\n\r\nfrom nav_bar import NavBar\r\n\r\norder_model_view = OrderModelView(Order, u\"订单\")\r\nsub_order_model_view = SubOrderModelView(SubOrder, u\"子订单\")\r\nsub_nav_bar = NavBar()\r\nsub_nav_bar.register(lambda: order_model_view.url_for_list(order_by=\"id\", desc=\"1\", category=\"\"), u\"所有订单\",\r\n enabler=lambda: category_filter.unfiltered(request.args.get(\"category\", None)))\r\nsub_nav_bar.register(\r\n lambda: order_model_view.url_for_list(order_by=\"id\", desc=\"1\", category=str(category_filter.UNDISPATCHED_ONLY)),\r\n u\"仅展示待下发订单\", enabler=lambda: request.args.get(\"category\", \"\") == str(category_filter.UNDISPATCHED_ONLY))\r\nsub_nav_bar.register(\r\n lambda: order_model_view.url_for_list(order_by=\"id\", desc=\"1\", category=category_filter.DELIVERABLE_ONLY),\r\n u\"仅展示可发货订单\", enabler=lambda: request.args.get(\"category\", \"\") == str(category_filter.DELIVERABLE_ONLY))\r\nsub_nav_bar.register(\r\n lambda: order_model_view.url_for_list(order_by=\"id\", desc=\"1\", category=category_filter.ACCOUNTABLE_ONLY),\r\n u\"仅展示可盘点订单\", enabler=lambda: request.args.get(\"category\", \"\") == str(category_filter.ACCOUNTABLE_ONLY))\r\n\r\n\r\ndef hint_message(model_view):\r\n filter_ = [filter_ for filter_ in model_view.parse_filters() if filter_.col_name == \"category\"][0]\r\n if not filter_.has_value():\r\n return \"\"\r\n filter_.value = int(filter_.value)\r\n\r\n if filter_.value == category_filter.UNDISPATCHED_ONLY:\r\n return u\"未下发订单未经收发员下发,调度员不能排产,请敦促收发员完善订单并下发\"\r\n elif filter_.value == category_filter.DELIVERABLE_ONLY:\r\n return u\"可发货订单中全部或部分产品可以发货,注意请催促质检员及时打印仓单\"\r\n elif filter_.value == category_filter.ACCOUNTABLE_ONLY:\r\n return u\"可盘点订单已经生产完毕(指已经全部分配给车间生产,最终生产完成,并通过质检),\" \\\r\n u\"但是仍然有部分仓单没有发货。盘点后,这部分仓单会自动关闭\"\r\n return \"\"\r\n\r\n\r\n@order_page.route(\"/new-sub-order\", methods=[\"GET\", \"POST\"])\r\[email protected](\"/order/new-extra-sub-order.html\")\r\[email protected]_bar_set\r\ndef new_sub_order():\r\n \"\"\"\r\n 创建新的计件类型的子订单(只有计件类型的订单能够增加子订单)\r\n \"\"\"\r\n if request.method == \"GET\":\r\n from lite_mms import apis\r\n\r\n order = apis.order.get_order(request.args.get(\"order_id\", type=int))\r\n if not order:\r\n abort(404)\r\n if order.dispatched or order.refined:\r\n return redirect(url_for(\"error\", error=u\"已下发或已标记完善的订单不能新增子订单\",\r\n url=url_for(\"order.order\", id=order.id)))\r\n from lite_mms.constants import DEFAULT_PRODUCT_NAME\r\n\r\n return dict(titlename=u'新建子订单', order=order,\r\n DEFAULT_PRODUCT_NAME=DEFAULT_PRODUCT_NAME,\r\n product_types=apis.product.get_product_types(),\r\n products=json.dumps(apis.product.get_products()),\r\n harbor_list=apis.harbor.get_harbor_list(),\r\n team_list=apis.manufacture.get_team_list())\r\n else:\r\n class NewSubOrderForm(Form):\r\n order_id = IntegerField('order_id', [validators.required()])\r\n product = IntegerField('product', [validators.required()])\r\n spec = TextField('spec', [validators.required()])\r\n type = TextField('type', [validators.required()])\r\n tech_req = TextField('tech_req')\r\n due_time = DateField('due_time',\r\n [validators.required()])\r\n urgent = BooleanField('urgent')\r\n returned = BooleanField('returned')\r\n unit = TextField('unit')\r\n quantity = IntegerField('quantity')\r\n weight = IntegerField('weight', [validators.required()])\r\n harbor = TextField('harbor', [validators.required()])\r\n\r\n form = NewSubOrderForm(request.form)\r\n order_id = form.order_id.data\r\n due_time = form.due_time.data\r\n if date.today() > due_time:\r\n return redirect(url_for(\"error\", error=u\"错误的交货日期\", url=url_for(\"order.order\", id_=order_id)))\r\n from lite_mms import apis\r\n\r\n try:\r\n sb = apis.order.SubOrderWrapper.new_sub_order(order_id=order_id, product_id=form.product.data,\r\n spec=form.spec.data, type=form.type.data,\r\n tech_req=form.tech_req.data, due_time=str(due_time),\r\n urgent=form.urgent.data, weight=form.weight.data,\r\n harbor_name=form.harbor.data, returned=form.returned.data,\r\n unit=form.unit.data, quantity=form.quantity.data)\r\n flash(u\"新建成功!\")\r\n except ValueError, e:\r\n flash(unicode(e), \"error\")\r\n return redirect(url_for('order.order', id_=order_id))\r\n\r\n\r\n@order_page.route('/work-command', methods=['GET', 'POST'])\r\[email protected](\"order/work-command.html\")\r\[email protected]_bar_set\r\ndef work_command():\r\n \"\"\"\r\n 生成一个新的工单\r\n \"\"\"\r\n if request.method == \"GET\":\r\n from lite_mms import apis\r\n\r\n sub_order = apis.order.SubOrderWrapper.get_sub_order(\r\n request.args.get(\"sub_order_id\", type=int))\r\n if not sub_order:\r\n abort(404)\r\n try:\r\n dep = apis.harbor.get_harbor_model(sub_order.harbor.name).department\r\n return dict(sub_order=sub_order, procedure_list=dep.procedure_list, department=dep, titlename=u\"预排产\")\r\n except AttributeError:\r\n abort(404)\r\n else:\r\n from lite_mms.apis import manufacture, order\r\n\r\n class PreScheduleForm(Form):\r\n sub_order_id = HiddenField('sub_order_id', [validators.required()])\r\n schedule_weight = IntegerField('schedule_weight',\r\n [validators.required()])\r\n procedure = IntegerField('procedure')\r\n tech_req = TextField('tech_req')\r\n schedule_count = IntegerField('schedule_count')\r\n urgent = BooleanField('urgent')\r\n url = HiddenField(\"url\")\r\n\r\n form = PreScheduleForm(request.form)\r\n sub_order = order.get_sub_order(form.sub_order_id.data)\r\n if not sub_order:\r\n abort(404)\r\n if form.validate():\r\n try:\r\n inst = manufacture.new_work_command(\r\n sub_order_id=sub_order.id,\r\n org_weight=form.schedule_weight.data,\r\n procedure_id=form.procedure.data,\r\n org_cnt=form.schedule_count.data,\r\n urgent=form.urgent.data,\r\n tech_req=form.tech_req.data)\r\n if inst:\r\n from lite_mms.apis.todo import remove_todo, DISPATCH_ORDER\r\n\r\n remove_todo(DISPATCH_ORDER, sub_order.order.id)\r\n\r\n from lite_mms.basemain import timeline_logger\r\n\r\n timeline_logger.info(u\"新建\",\r\n extra={\"obj\": inst,\r\n \"actor\": current_user if current_user.is_authenticated else None,\r\n \"action\": u\"新建\", \"obj_pk\": inst.id})\r\n\r\n if inst.sub_order.returned:\r\n flash(u\"成功创建工单(编号%d),请提醒质检员赶快处理\" % inst.id)\r\n else:\r\n flash(u\"成功创建工单(编号%d)\" % inst.id)\r\n except ValueError as a:\r\n return render_template(\"error.html\", msg=a.message,\r\n back_url=form.url.data or url_for('order.order', id_=sub_order.order.id)), 403\r\n return redirect(form.url.data or url_for('order.order', id_=sub_order.order.id))\r\n else:\r\n return render_template(\"error.html\", msg=form.errors,\r\n back_url=url_for('order.order', id_=sub_order.order.id)), 403\r\n" }, { "alpha_fraction": 0.6837607026100159, "alphanum_fraction": 0.6837607026100159, "avg_line_length": 17.5, "blob_id": "77112fb883189dfa2388db3c1b7d393f9fc631f0", "content_id": "c414291274c385b24f0e1af3ada77704b306076d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 117, "license_type": "no_license", "max_line_length": 35, "num_lines": 6, "path": "/lite_mms/portal/misc/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "from flask import Blueprint\r\n\r\nmisc = Blueprint(\"misc\", __name__) \r\n\r\nfrom . import ajax\r\nfrom . import webservices\r\n" }, { "alpha_fraction": 0.7617021203041077, "alphanum_fraction": 0.7627659440040588, "avg_line_length": 27.484848022460938, "blob_id": "ccc902e985f6d1e526b1523b9a42ff197b5f08a5", "content_id": "f3494894d255a6ef9526e4b12729dd62c452e09a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1124, "license_type": "no_license", "max_line_length": 66, "num_lines": 33, "path": "/lite_mms/permissions/accounts.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n针对用户对象的权限,将用户管理相关的权限\n\"\"\"\nfrom collections import namedtuple\nfrom flask.ext.principal import Permission\n\nAccountManagement = namedtuple(\"user\", [\"method\"])\n\n# 针对班组长的管理权限\nViewDepartmentLeader = AccountManagement(\"view_account\")\nEditDepartmentLeader = AccountManagement(\"edit_account\")\nNewDepartmentLeader = AccountManagement(\"new_account\")\nDelDepartmentLeader = AccountManagement(\"delete_account\")\n\nview_dl = Permission(ViewDepartmentLeader)\nview_dl.brief = u\"查看车间主任账户信息的权限\"\n\nedit_dl = Permission(EditDepartmentLeader)\nedit_dl.brief = u\"修改车间主任账户信息的权限\"\n\nnew_dl = Permission(NewDepartmentLeader)\nnew_dl.brief = u\"创建车间主任账户的权限\"\n\ndel_dl = Permission(DelDepartmentLeader)\ndel_dl.brief = u\"删除车间主任账户的权限\"\n\nadmin_dl = Permission(ViewDepartmentLeader, EditDepartmentLeader, \n NewDepartmentLeader, DelDepartmentLeader)\nadmin_dl.brief = u\"对车间主任帐号有增删改查权限\"\n\nif __name__ == \"__main__\":\n print view_dl.brief\n" }, { "alpha_fraction": 0.5997304320335388, "alphanum_fraction": 0.6037735939025879, "avg_line_length": 25.481481552124023, "blob_id": "c8ed9af29ab558a6ad45b7504f4a20ee184e4627", "content_id": "2993541280e2d32440b72dcb958a91b9890062b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 758, "license_type": "no_license", "max_line_length": 89, "num_lines": 27, "path": "/lite_mms/portal/manufacture/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\nfrom flask import Blueprint, redirect, url_for\r\n\r\nmanufacture_page = Blueprint(\"manufacture\", __name__, static_folder=\"static\",\r\n template_folder=\"templates\")\r\n\r\nfrom lite_mms.portal.manufacture import views\r\n\r\nfrom lite_mms.basemain import data_browser, nav_bar\r\n\r\nextra_params = {\r\n \"list_view\": {\r\n \"nav_bar\": nav_bar,\r\n \"titlename\": u\"工单列表\",\r\n },\r\n \"form_view\": {\r\n \"nav_bar\": nav_bar,\r\n \"titlename\": u\"编辑工单\"\r\n }\r\n\r\n}\r\ndata_browser.register_model_view(views.work_command_view, manufacture_page, extra_params)\r\n\r\n\r\n@manufacture_page.route(\"/\")\r\ndef index():\r\n return redirect(url_for(\"manufacture.work_command_list\", status__in_ex=\"(1, 8)\"))\r\n" }, { "alpha_fraction": 0.759856641292572, "alphanum_fraction": 0.759856641292572, "avg_line_length": 29.88888931274414, "blob_id": "d0fae92ce9c035ef81b6db00c70556d5c7d76fcb", "content_id": "980a6e8c2ad7bf8e807a3547c4cd2649125878ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 279, "license_type": "no_license", "max_line_length": 66, "num_lines": 9, "path": "/lite_mms/portal/order_ws/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "from flask import Blueprint\n\norder_ws = Blueprint(\"order_ws\", __name__, static_folder=\"static\",\n template_folder=\"templates\")\n\nfrom lite_mms.apis.auth import load_user_from_token\norder_ws.before_request(load_user_from_token)\n\nfrom lite_mms.portal.order_ws import webservices\n\n" }, { "alpha_fraction": 0.6007326245307922, "alphanum_fraction": 0.66300368309021, "avg_line_length": 14.571428298950195, "blob_id": "68f03dfcfda96077ceece4f1631d732394946a11", "content_id": "a781ad9e3192f0013aaf0d50c6ba77f8f79e2a3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 546, "license_type": "no_license", "max_line_length": 72, "num_lines": 35, "path": "/alembic/versions/3288ac4ef7b5_team_can_be_nullable.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"team can be nullable\r\r\r\rRevision ID: 3288ac4ef7b5\r\rRevises: d9c0f19bdf7\r\rCreate Date: 2013-04-22 11:10:35.980000\r\r\r\r\"\"\"\r\r\r\r# revision identifiers, used by Alembic.\r\rrevision = '3288ac4ef7b5'\r\rdown_revision = 'd9c0f19bdf7'\r\rfrom alembic import op\r\rimport sqlalchemy as sa\r\r\rdef upgrade():\r op.alter_column(\"TB_CONSIGNMENT_PRODUCT\", 'team_id', nullable=True,\r existing_type=sa.Integer)\r\r\rdef downgrade():\r op.alter_column(\"TB_CONSIGNMENT_PRODUCT\", 'team_id', nullable=False,\r existing_type=sa.Integer)\r\r" }, { "alpha_fraction": 0.6298003196716309, "alphanum_fraction": 0.6850998401641846, "avg_line_length": 18.727272033691406, "blob_id": "03af6d65c20c5424d9ef46f83e4779b9c3126877", "content_id": "9030c72917d5f18241452d5248e4e9d6d8467b04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 679, "license_type": "no_license", "max_line_length": 86, "num_lines": 33, "path": "/alembic/versions/4e0b33cf96e0_modify_default_url.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\"\"\"modify default url\r\r\r\rRevision ID: 4e0b33cf96e0\r\rRevises: 43d2714c4448\r\rCreate Date: 2013-11-05 09:25:22.002000\r\r\r\r\"\"\"\r\r# revision identifiers, used by Alembic.\rrevision = '4e0b33cf96e0'\r\rdown_revision = '43d2714c4448'\r\rfrom alembic import op\r\rimport sqlalchemy as sa\r\r\rdef upgrade():\r op.execute(u'update TB_GROUP set default_url = \"/admin/\" where name=\"管理员\"')\r op.execute(u'update TB_GROUP set default_url = NULL where name=\"车间主任\"')\r\r\rdef downgrade():\r op.execute(u'update TB_GROUP set default_url = \"/admin2/\" where name=\"管理员\"')\r op.execute(u'update TB_GROUP set default_url = \"/manufacture/\" where name=\"车间主任\"')\r" }, { "alpha_fraction": 0.5795393586158752, "alphanum_fraction": 0.5822174549102783, "avg_line_length": 35.60784149169922, "blob_id": "e889bcafbffcd85d377de8a0b7f481e29b67c1e4", "content_id": "fdc2c5e66cf5a4d97d72628960596e65e1477979", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3812, "license_type": "no_license", "max_line_length": 119, "num_lines": 102, "path": "/lite_mms/portal/deduction/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nimport os\n\nfrom flask import Blueprint, redirect, url_for\nfrom lite_mms.basemain import data_browser\nfrom lite_mms.permissions.deduction import addDeduction, editDeduction, deleteDeduction\nfrom datetime import datetime\n\ndeduction_page = Blueprint(\"deduction\", __name__, static_folder=\"static\",\n template_folder=\"templates\")\n\n#from lite_mms.basemain import app\n#from flask.ext.admin import Admin\nfrom lite_mms.database import db\n#from flask.ext.admin.contrib.sqlamodel import ModelView\nfrom lite_mms import models\n#from lite_mms.database import db\n\n#class DeductionModelView(ModelView):\n #column_list = [\"weight\", \"remark\"]\n #column_filters = [\"weight\"]\n #column_labels = {\"name\": u\"名称\", \"leader_list\": u\"车间主任\"}\n #list_formatters = {\"leader_list\": lambda context, model, name: \", \".join([u.username for u in model.leader_list])}\n\n #def is_accessible(self):\n #return AdminPermission.can()\n\nfrom lite_mms.basemain import nav_bar\nfrom flask.ext.databrowser import ModelView\nfrom lite_mms.basemain import app\n\n@deduction_page.route('/')\ndef index():\n return redirect(url_for(\"deduction.deduction_list\"))\n\nclass DeductionModelView(ModelView):\n __create_columns__ = [\"id\", \"weight\", \"work_command\", \"team\", \"remark\"]\n\n __list_columns__ = [\"id\", \"weight\", \"work_command\", \"team\", \"actor\",\n \"create_time\", \"remark\"]\n\n __column_labels__ = {\n \"weight\": u\"重量\",\n \"work_command\": u\"工单号\",\n \"team\": u\"班组\",\n \"actor\": u\"质检员\",\n \"create_time\": u\"创建于\",\n \"remark\": u\"备注\",\n }\n\n __list_formatters__ = {\n \"team\": lambda model, v: v.name,\n \"weight\": lambda model, v: str(v) if v else \"\" + u'(公斤)',\n \"actor\": lambda model, v: v.username,\n \"create_time\": lambda model, v: v.strftime(\"%Y-%m-%d %H\") + u\"点\",\n \"remark\": lambda model, v: v or \"-\",\n \"work_command\": lambda model,v:v.id if v else \"-\"\n }\n form_formatters = {\"work_command\": lambda work_command: work_command.id,\n \"team\": lambda team:team.name,\n \"actor\": lambda actor:actor.username\n }\n\n __sortable_columns__ = [\"id\", \"weight\", \"work_command\", \"team\", \"actor\", \"create_time\"]\n\n from flask.ext.databrowser import filters\n from datetime import datetime, timedelta\n today = datetime.today()\n yesterday = today.date()\n week_ago = (today - timedelta(days=7)).date()\n _30days_ago = (today - timedelta(days=30)).date()\n __column_filters__ = [filters.EqualTo(\"team\", name=u\"是\", opt_formatter=lambda opt: opt.name),\n filters.BiggerThan(\"create_time\", name=u\"在\",\n options=[(yesterday, u'一天内'),\n (week_ago, u'一周内'),\n (_30days_ago, u'30天内')]),\n filters.EqualTo(\"id\", name=u\"是\"),\n filters.LessThan(\"weight\", name=u\"小于\"),\n filters.EqualTo(\"work_command\", name=u\"等于\", opt_formatter=lambda opt:opt.id)]\n\n def can_create(self):\n return addDeduction.can()\n\n def can_edit(self):\n return editDeduction.can()\n\n def can_delete(self):\n return deleteDeduction.can()\n\n def on_model_change(self, form, model):\n from flask.ext.login import current_user\n model.actor = current_user\n if not model.create_time:\n model.create_time = datetime.now()\n\nextra_params = {\n \"list_view\": {\n 'nav_bar': nav_bar\n }\n}\ndata_browser.register_model_view(DeductionModelView(models.Deduction), deduction_page,\n extra_params)\n" }, { "alpha_fraction": 0.637532114982605, "alphanum_fraction": 0.6928020715713501, "avg_line_length": 25.827587127685547, "blob_id": "ebd9654fbdd3432cf83446683d0bd548ff724369", "content_id": "21ea1b9d1d908886d85fff9ea66d525ba677303d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 778, "license_type": "no_license", "max_line_length": 118, "num_lines": 29, "path": "/alembic/versions/41614d172256_qi_group_add_permiss.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"qi_group add permissions\n\nRevision ID: 41614d172256\nRevises: 38c3b59444b6\nCreate Date: 2013-01-28 16:52:57.668206\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '41614d172256'\ndown_revision = '38c3b59444b6'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.execute(\n \"insert into TB_PERMISSION_AND_GROUP(permission_name, group_id)(select TB_PERMISSION.name, \"\n \"TB_GROUP.id from TB_PERMISSION,TB_GROUP where TB_PERMISSION.name like '%view_work_command' and TB_GROUP.name\"\n \" ='quality_inspector' )\"\n )\n\n\ndef downgrade():\n op.execute(\n \"delete from TB_PERMISSION_AND_GROUP where group_id in (select id from TB_GROUP where \"\n \"name='quality_inspector') and permission_name like '%view_work_command'\"\n )\n" }, { "alpha_fraction": 0.6332945227622986, "alphanum_fraction": 0.6358168125152588, "avg_line_length": 36.875, "blob_id": "d29a8f6291f9364066eee47b8ec39cdf71775226", "content_id": "dae07056da39278a3baa0edd9c6fede6ddc68cc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5238, "license_type": "no_license", "max_line_length": 110, "num_lines": 136, "path": "/lite_mms/portal/op/views.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport codecs\nimport csv\nimport cStringIO\nfrom datetime import datetime\nfrom flask import request\nfrom lite_mms.portal.op import op_page\nimport lite_mms.constants as constants\nfrom lite_mms.utilities import decorators, _\nfrom lite_mms.utilities.pagination import Pagination\n\ndef _trans_order_type(order_type):\n if order_type == constants.STANDARD_ORDER_TYPE:\n return _(u\"计重\")\n elif order_type == constants.EXTRA_ORDER_TYPE:\n return _(u\"计件\")\n else:\n return _(u\"未知\")\n\ndef _discard_report_wrapper(qir):\n return dict(id=qir.id, quantity=qir.quantity, weight=qir.weight,\n work_command_id=qir.work_command_id,\n order=qir.work_command.order,\n customer=qir.work_command.order.customer.name,\n unit=qir.work_command.unit,\n product_name=qir.work_command.sub_order.product.name,\n report_time=qir.report_time,\n reporter=qir.reporter.username,\n department=qir.work_command.department.name,\n team=qir.work_command.team.name)\n\n@op_page.route(\"/\", methods=[\"GET\"])\[email protected](\"op/operation-manager-list.html\")\[email protected]_bar_set\ndef index():\n return dict(titlename=_(u\"运营管理\"))\n\n@op_page.route(\"/discard-report-list\", methods=[\"GET\"])\[email protected](\"op/discard-report-list.html\")\[email protected]_bar_set\ndef discard_report_list():\n page = request.args.get(\"page\", 1, type=int)\n page_size = constants.ITEMS_PER_PAGE\n import lite_mms.apis as apis\n qir_list, total_cnt = apis.quality_inspection.get_qir_list(\n idx=(page - 1) * page_size,\n cnt=page_size, finished_only=True,\n result=constants.quality_inspection.DISCARD)\n pagination = Pagination(page, page_size, total_cnt)\n dr_list = [_discard_report_wrapper(qir) for qir in qir_list]\n return dict(titlename=_(u\"报废单管理\"), dr_list=dr_list, pagination=pagination)\n\n\n@op_page.route(\"/team-performance\")\[email protected](\"op/team-performance.html\")\[email protected]_bar_set\ndef team_performance():\n import lite_mms.apis as apis\n page = request.args.get(\"page\", 1, type=int)\n orders, total_cnt = apis.order.get_order_list(\n (page - 1) * constants.ORDER_PER_PAGE, constants.ORDER_PER_PAGE)\n if orders is None:\n orders = []\n pagination = Pagination(page, constants.ORDER_PER_PAGE, total_cnt)\n\n department_list = apis.manufacture.get_department_list()\n team_list = []\n for dep in department_list:\n team_list.extend(apis.manufacture.get_team_list(dep.id))\n return dict(titlename=_(u\"班组绩效管理\"), order_list=orders,\n team_list=team_list, pagination=pagination, page=page)\n\n\n@op_page.route(\"/export.csv\", methods=[\"POST\"])\ndef export2csv():\n import lite_mms.apis as apis\n class UnicodeWriter:\n \"\"\"\n A CSV writer which will write rows to CSV file \"f\",\n which is encoded in the given encoding.\n \"\"\"\n\n def __init__(self, f, dialect=csv.excel, **kwds):\n # Redirect output to a queue\n self.queue = cStringIO.StringIO()\n self.writer = csv.writer(self.queue, dialect=dialect, **kwds)\n self.stream = f\n self.encoder = codecs.getincrementalencoder(\"UTF-8\")()\n self.stream.write(codecs.BOM_UTF8)\n\n def writerow(self, row):\n self.writer.writerow([s.encode(\"utf-8\") for s in row])\n # Fetch UTF-8 output from the queue ...\n data = self.queue.getvalue()\n data = data.decode(\"utf-8\")\n # ... and reencode it into the target encoding\n data = self.encoder.encode(data)\n # write to the target stream\n self.stream.write(data)\n # empty queue\n self.queue.truncate()\n\n def writerows(self, rows):\n for row in rows:\n self.writerow(row)\n\n\n from flask import Response\n\n try:\n from cStringIO import StringIO\n except ImportError:\n from StringIO import StringIO\n return_fileobj = StringIO()\n writer = UnicodeWriter(return_fileobj)\n fieldnames = [u'班组', u'生产日期', u'工单号', u'生产重量(公斤)', u'扣除重量(公斤']\n writer.writerow(fieldnames)\n begin_date_s = request.form.get(\"begin_date\")\n begin_date, end_date = None, None\n if begin_date_s:\n begin_date = datetime.strptime(begin_date_s,\"%Y-%m-%d\")\n end_date_s = request.form.get(\"end_date\")\n if end_date_s:\n end_date = datetime.strptime(end_date_s,\"%Y-%m-%d\")\n department_list = apis.manufacture.get_department_list()\n team_list = []\n for dep in department_list:\n team_list.extend(apis.manufacture.get_team_list(dep.id))\n for team in team_list:\n _dict = team.get_team_work_command_dict(begin_date, end_date)\n for item in _dict.items():\n for wc in item[1]:\n writer.writerow([team.name, item[0], str(wc.id), str(wc.processed_weight), str(wc.deduction)])\n response = Response(return_fileobj.getvalue(), mimetype='text/csv')\n response.headers['Content-Disposition'] = 'attachment; filename=export.csv'\n return response\n\n\n\n" }, { "alpha_fraction": 0.6457960605621338, "alphanum_fraction": 0.683363139629364, "avg_line_length": 15.411765098571777, "blob_id": "a3cc6dbb3d5f18e37cb75744146fc1ee38db578f", "content_id": "ca7b596535c145619ae7bd84af8e8554dad5a8e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 559, "license_type": "no_license", "max_line_length": 120, "num_lines": 34, "path": "/alembic/versions/e8e10d94c8e_add_creator_column.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"add creator column\r\r\r\rRevision ID: e8e10d94c8e\r\rRevises: 5a8040282a1f\r\rCreate Date: 2013-07-24 14:39:16.179000\r\r\r\r\"\"\"\r\r\r\r# revision identifiers, used by Alembic.\r\rrevision = 'e8e10d94c8e'\r\rdown_revision = '5a8040282a1f'\r\rfrom alembic import op\r\rimport sqlalchemy as sa\r\r\rdef upgrade():\r op.add_column(\"TB_GOODS_RECEIPT\", sa.Column(\"creator_id\", sa.Integer, sa.ForeignKey(\"TB_USER.id\", \"fk_creator_gr\")))\r\r\rdef downgrade():\r op.drop_constraint(\"fk_creator_gr\", \"TB_GOODS_RECEIPT\", type_=\"foreignkey\")\r op.drop_column(\"TB_GOODS_RECEIPT\", \"creator_id\")\r\r" }, { "alpha_fraction": 0.6144525408744812, "alphanum_fraction": 0.6201806664466858, "avg_line_length": 34.918697357177734, "blob_id": "37fbf43631905848e5a45bb85d6597d74531e0ac", "content_id": "3a330d3368b8dd76aa6a1621c71a9277cd767991", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4705, "license_type": "no_license", "max_line_length": 109, "num_lines": 123, "path": "/lite_mms/portal/order/ajax.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\nimport json\r\nfrom flask import request, render_template, url_for\r\nfrom lite_mms.utilities import _\r\nfrom lite_mms.portal.order import order_page\r\nfrom lite_mms.utilities import decorators\r\nfrom lite_mms.utilities.decorators import ajax_call\r\n\r\n\r\n@order_page.route(\"/ajax/customer-list\")\r\n@ajax_call\r\ndef customer_list():\r\n \"\"\"\r\n return the customers, params include:\r\n * unload_session_id\r\n \"\"\"\r\n unload_session_id = request.args.get(\"unload_session_id\", None)\r\n customers = []\r\n if unload_session_id:\r\n unload_session_id = int(unload_session_id)\r\n from lite_mms import apis\r\n\r\n unload_session = apis.cargo.get_unload_session(unload_session_id)\r\n if not unload_session.finish_time:\r\n return _(u\"卸货会话尚未结束\"), 403\r\n if any(task.weight == 0 for task in unload_session.task_list):\r\n return _(u\"请先对所有的卸货任务进行称重\"), 403\r\n acked_customer_id_list = set([gr.customer_id for gr in\r\n unload_session.goods_receipt_list])\r\n customers = [c for c in unload_session.customer_list if\r\n c.id not in acked_customer_id_list]\r\n if not customers:\r\n return _(u\"已经对所有的用户生成了收货单\"), 403\r\n return json.dumps([{\"id\": c.id, \"name\": c.name} for c in customers])\r\n\r\n\r\n@order_page.route(\"/ajax/order-modify\", methods=[\"POST\"])\r\n@ajax_call\r\ndef order_modify():\r\n from lite_mms import apis\r\n\r\n order = apis.order.get_order(request.form[\"order_id\"])\r\n if not order:\r\n return _(u\"不存在订单ID为%s的订单\" % request.form[\"order_id\"]), 403\r\n if any(\r\n sub_order.work_command_list for sub_order in order.sub_order_list):\r\n return _(u\"该订单已排产,请勿修改\"), 500\r\n try:\r\n order.update(customer_order_number=request.form[\"customer_order_number\"])\r\n return _(u\"修改成功\")\r\n except ValueError:\r\n return _(u\"修改失败\"), 403\r\n\r\n\r\n@order_page.route(\"/ajax/sub-order\", methods=[\"GET\"])\r\n@ajax_call\r\ndef ajax_sub_order():\r\n sub_order_id = request.args.get('id', type=int)\r\n if not sub_order_id:\r\n return _(u\"不存在该订单\"), 404\r\n from lite_mms import apis\r\n\r\n inst = apis.order.get_sub_order(sub_order_id)\r\n if not inst:\r\n return \"no sub order with id \" + str(sub_order_id), 404\r\n from lite_mms.basemain import nav_bar\r\n from lite_mms.constants import DEFAULT_PRODUCT_NAME\r\n\r\n param_dict = {'titlename': u'子订单详情', 'sub_order': inst, 'nav_bar': nav_bar,\r\n 'DEFAULT_PRODUCT_NAME': DEFAULT_PRODUCT_NAME}\r\n param_dict.update(product_types=apis.product.get_product_types())\r\n param_dict.update(products=json.dumps(apis.product.get_products()))\r\n param_dict.update(harbor_list=apis.harbor.get_harbor_list())\r\n purl = request.args.get(\"purl\")\r\n if purl is None or purl == \"None\":\r\n purl = url_for(\"order.order_list\")\r\n param_dict.update(purl=purl)\r\n return render_template(\"order/sub-order.html\", **param_dict)\r\n\r\n\r\n@order_page.route(\"/ajax/team-work-reports\", methods=[\"GET\"])\r\n@ajax_call\r\ndef team_work_reports():\r\n ret = {}\r\n from lite_mms.apis.order import get_order\r\n\r\n order = get_order(request.args.get(\"order_id\", type=int))\r\n for wc in order.done_work_command_list:\r\n try:\r\n ret[wc.team.name] += wc.processed_weight\r\n except KeyError:\r\n ret[wc.team.name] = wc.processed_weight\r\n return json.dumps(ret.items())\r\n\r\n\r\n@order_page.route(\"/ajax/team-manufacturing-reports\", methods=[\"GET\"])\r\n@ajax_call\r\ndef team_manufacturing_reports():\r\n from lite_mms.apis.order import get_order\r\n\r\n order = get_order(request.args.get(\"order_id\", type=int))\r\n d = {}\r\n for so in order.sub_order_list:\r\n for wc in so.manufacturing_work_command_list:\r\n team_name = wc.department.name + u\"车间:\" + (wc.team.name if wc.team else u\"尚未分配\") + u\"班组\"\r\n try:\r\n d[team_name] += wc.org_weight\r\n except KeyError:\r\n d[team_name] = wc.org_weight\r\n return json.dumps(sorted([dict(team=k, weight=v) for k, v in d.items()], key=lambda v: v[\"team\"]))\r\n\r\n\r\n@order_page.route(\"/ajax/store-bill-list\", methods=[\"GET\"])\r\n@ajax_call\r\ndef store_bill_list():\r\n from lite_mms.apis.order import get_order\r\n\r\n order = get_order(request.args.get(\"order_id\", type=int))\r\n ret = []\r\n for so in order.sub_order_list:\r\n for sb in so.store_bill_list:\r\n ret.append(dict(id=sb.id, product=so.product.name, spec=so.spec, type=so.type, weight=sb.weight))\r\n return json.dumps(ret)" }, { "alpha_fraction": 0.5803714990615845, "alphanum_fraction": 0.5812886953353882, "avg_line_length": 29.38848876953125, "blob_id": "6f2a88a5d59002904c0df09cb948918e99a5f039", "content_id": "147fba122d8de3e1011b5a28d3114e1b216fdcda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4525, "license_type": "no_license", "max_line_length": 89, "num_lines": 139, "path": "/lite_mms/apis/quality_inspection.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\nimport sys\r\nfrom flask import url_for\r\nfrom lite_mms.utilities import _\r\nfrom sqlalchemy.orm.exc import NoResultFound\r\nfrom lite_mms import models\r\nfrom lite_mms.constants import (work_command as wc_const,\r\n quality_inspection as qi_const)\r\nfrom lite_mms.apis import ModelWrapper\r\nfrom lite_mms.utilities import do_commit\r\n\r\n\r\nclass QIReportWrapper(ModelWrapper):\r\n @property\r\n def pic_url(self):\r\n if self.pic_path:\r\n return url_for(\"serv_pic\", filename=self.pic_path)\r\n else:\r\n return \"\"\r\n\r\n @property\r\n def small_pic_url(self):\r\n return url_for(\"serv_small_pic\", filename=self.pic_path) if self.pic_path else \"\"\r\n\r\n @property\r\n def reporter(self):\r\n return self.actor\r\n\r\n @property\r\n def partly_delivered(self):\r\n \"\"\"\r\n 若有对应的仓单正在被装货,或已经发货, 就认为这个质检报告部分已经被发货\r\n \"\"\"\r\n return any(sb.delivery_session for sb in self.store_bill_list)\r\n\r\n @classmethod\r\n def get(cls, id_):\r\n if not id_:\r\n return None\r\n try:\r\n return QIReportWrapper(\r\n models.QIReport.query.filter_by(id=id_).one())\r\n except NoResultFound:\r\n return None\r\n\r\n @classmethod\r\n def new(cls, actor_id, work_command_id, quantity, result, pic_path,\r\n report_time=None):\r\n from lite_mms.apis.manufacture import WorkCommandWrapper\r\n\r\n workcommand = WorkCommandWrapper.get_work_command(\r\n work_command_id)\r\n if not workcommand:\r\n raise ValueError(_(u\"无该工单%s\" % work_command_id))\r\n weight = workcommand.model.processed_unit_weight * quantity\r\n qi_report = models.QIReport(workcommand.model, quantity, weight,\r\n result, actor_id, report_time, pic_path)\r\n return QIReportWrapper(do_commit(qi_report))\r\n\r\n @classmethod\r\n def remove(cls, id_, actor_id):\r\n \"\"\"\r\n remove the quality inspection report on database\r\n \"\"\"\r\n qir = cls.get(id_)\r\n if not qir:\r\n raise ValueError(_(u\"无此报告单(%s)\" % id_))\r\n if qir.work_command.status != wc_const.STATUS_QUALITY_INSPECTING:\r\n raise ValueError(_(u\"已提交的质检单中的质检报告不能删除\"))\r\n do_commit(qir.model, action=\"delete\")\r\n return \"sucess\"\r\n\r\n @classmethod\r\n def update(cls, id_, actor_id, quantity=None, result=None, pic_path=None):\r\n \"\"\"\r\n update quality inspection report in database\r\n \"\"\"\r\n qir = cls.get(id_)\r\n if not qir:\r\n raise ValueError(_(u\"无此报告%s\" % id_))\r\n if quantity:\r\n qir.model.quantity = quantity\r\n if result is not None:\r\n qir.model.result = result\r\n if pic_path:\r\n qir.model.pic_path = pic_path\r\n qir.model.actor_id = actor_id\r\n return QIReportWrapper(do_commit(qir.model))\r\n\r\n @property\r\n def product(self):\r\n return self.work_command.sub_order.product\r\n\r\n @property\r\n def unit(self):\r\n return self.work_command.sub_order.unit\r\n\r\n\r\ndef get_qir_list(work_command_id=None, idx=0, cnt=sys.maxint,\r\n finished_only=False, result=None):\r\n \"\"\"\r\n get the quality inspection_report from database\r\n \"\"\"\r\n qir_q = models.QIReport.query\r\n if work_command_id:\r\n qir_q = qir_q.filter(models.QIReport.work_command_id ==\r\n work_command_id)\r\n if finished_only:\r\n # see sqlalchemy IS NULL\r\n qir_q = qir_q.filter(models.QIReport.report_time == None)\r\n if result:\r\n qir_q = qir_q.filter(models.QIReport.result == result)\r\n\r\n total_cnt = qir_q.count()\r\n qir_q = qir_q.offset(idx).limit(cnt)\r\n return [QIReportWrapper(qir) for qir in qir_q.all()], total_cnt\r\n\r\nget_qir = QIReportWrapper.get\r\nnew_QI_report = QIReportWrapper.new\r\nremove_qi_report = QIReportWrapper.remove\r\nupdate_qi_report = QIReportWrapper.update\r\n\r\n\r\ndef get_QI_result_list():\r\n return [\r\n (qi_const.FINISHED, u'通过'),\r\n (qi_const.NEXT_PROCEDURE, u'通过转下道工序'),\r\n (qi_const.REPAIR, u'返修'),\r\n (qi_const.REPLATE, u'返镀'),\r\n (qi_const.DISCARD, u'报废'),\r\n ]\r\n\r\n\r\ndef get_QI_result(result):\r\n for i in get_QI_result_list():\r\n if i[0] == result:\r\n return i[1]\r\n else:\r\n return u\"未知\"" }, { "alpha_fraction": 0.6019693613052368, "alphanum_fraction": 0.6025722622871399, "avg_line_length": 37.27820587158203, "blob_id": "c9287ea1efd8511500c4b82eddbc05795a7cac9f", "content_id": "4375d8a57a2f7865891ac7803ccee95be3577949", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 30503, "license_type": "no_license", "max_line_length": 141, "num_lines": 780, "path": "/lite_mms/apis/delivery.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding:UTF-8 -*-\nimport time\nimport sys\nfrom datetime import datetime\nfrom collections import OrderedDict\n\nfrom flask import url_for, render_template\nfrom sqlalchemy import or_\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom werkzeug.utils import cached_property\nimport yawf\n\nfrom lite_mms import models, constants\nimport lite_mms.apis.order\nfrom lite_mms import database\nfrom lite_mms.database import db\nimport lite_mms.apis.customer\nfrom lite_mms.apis import ModelWrapper\nfrom lite_mms.utilities import do_commit, to_timestamp\n\n\nclass DeliverySessionWrapper(ModelWrapper):\n @property\n def deleteable(self):\n return not bool(self.delivery_task_list)\n\n @property\n def is_locked(self):\n return bool(self.delivery_task_list and\n any(not t.weight for t in self.delivery_task_list) or\n yawf.token_bound(constants.work_flow.DELIVERY_TASK_WITH_ABNORMAL_WEIGHT, str(self.id)))\n\n @property\n def load_finish(self):\n return bool(self.finish_time)\n\n @cached_property\n def customer_list(self):\n return list(set([task.customer for task in self.delivery_task_list]))\n\n @cached_property\n def customer_id_list(self):\n return list(set([task.customer.id for task in self.delivery_task_list]))\n\n @property\n def with_person_des(self):\n return u'是' if self.with_person else u'否'\n\n @cached_property\n def need_store_bill(self):\n return not self.finish_time and (not self.store_bill_list or all(\n store_bill.delivery_task for store_bill in\n self.store_bill_list))\n\n def __repr__(self):\n return u\"<DeliverySession id:(%d) plate:(%r) tare:(%d) create_time:(\" \\\n u\"%s) finish_time:(%s)>\" % (\n self.id, self.plate, self.tare,\n self.create_time.strftime(\"%Y-%m-%d[%H:%M:%S]\"),\n self.finish_time.strftime(\n \"%Y-%m-%d[%H:%M:%S]\") if self.finish_time else \"-\")\n\n @classmethod\n def new_delivery_session(cls, plate, tare, with_person=False):\n \"\"\"create delivery session\n :param cls:\n :param plate:\n :param tare:\n :return:a newly delivery session\n \"\"\"\n plate = plate.upper()\n try:\n models.Plate.query.filter(\n models.Plate.name == plate).one()\n except NoResultFound:\n do_commit(models.Plate(name=plate))\n return DeliverySessionWrapper(\n do_commit(models.DeliverySession(plate, tare, with_person)))\n\n def update(self, **kwargs):\n if kwargs.get(\"store_bill_list\"):\n models.StoreBill.query.filter(\n models.StoreBill.id.in_(kwargs.get(\"store_bill_list\"))).update(\n {\"delivery_session_id\": self.id},\n synchronize_session='fetch')\n db.session.commit()\n if kwargs.has_key(\"finish_time\"):\n if kwargs.get(\"finish_time\"):\n models.StoreBill.query.filter(\n models.StoreBill.delivery_session_id == self.id,\n models.StoreBill.delivery_task_id == None).update(\n {\"delivery_session_id\": None})\n self.model.finish_time = datetime.fromtimestamp(\n kwargs[\"finish_time\"])\n db.session.add(self.model)\n else:\n self.model.finish_time = None\n db.session.add(self.model)\n db.session.commit()\n\n def add_store_bill_list(self, store_bill_id_list):\n if store_bill_id_list:\n models.StoreBill.query.filter(\n models.StoreBill.id.in_(store_bill_id_list)).update(\n {\"delivery_session_id\": self.id}, synchronize_session='fetch')\n db.session.commit()\n\n else:\n raise ValueError(u'至少要有一个仓单')\n\n @property\n def can_finish(self):\n return not self.finish_time and all(\n ut.weight for ut in self.delivery_task_list)\n\n def finish(self):\n if self.can_finish:\n self.update(finish_time=time.time())\n return True\n return False\n\n def reopen(self):\n if self.finish_time:\n self.update(finish_time=None)\n return True\n return False\n\n @cached_property\n def stale(self):\n return len(self.consignment_list) != len(self.customer_list) or any(cn.stale for cn in self.consignment_list)\n\n def gc_consignment_list(self):\n \"\"\"\n delete the consignment which has not entry converted from current\n delivery_session's delivery_task\n \"\"\"\n for cn in self.consignment_list:\n if cn.customer.id not in self.customer_id_list:\n do_commit(cn.model, \"delete\")\n\n @property\n def log_list(self):\n\n from lite_mms.apis.log import LogWrapper\n\n ret = LogWrapper.get_log_list(str(self.id), self.model.__class__.__name__)\n\n for task in self.delivery_task_list:\n ret.extend(task.log_list)\n return sorted(ret, lambda a, b: cmp(a.create_time, b.create_time), reverse=True)\n\nclass DeliveryTaskWrapper(ModelWrapper):\n @classmethod\n def new_delivery_task(cls, actor_id, finished_store_bill_list,\n unfinished_store_bill, remain=None):\n \"\"\"\n 创建一个新的卸货任务,若有部分完成的仓单,需要将没有完成的部分生成一个新的仓单, 这个仓单是完成的\n :param cls:\n :param actor_id:\n :param finished_store_bill_id_list:\n :param unfinished_store_bill_id:\n :param remain:\n :return:\n \"\"\"\n if unfinished_store_bill and not remain:\n raise ValueError(u\"需要remain字段\")\n if unfinished_store_bill:\n # 创建一个已经完成的新仓单\n new_sb = models.StoreBill(unfinished_store_bill.qir)\n new_sb.quantity = max(1,\n unfinished_store_bill.quantity - remain)\n new_sb.weight = int(\n unfinished_store_bill.unit_weight * new_sb.quantity)\n new_sb.delivery_session = unfinished_store_bill.delivery_session\n new_sb.printed = True\n finished_store_bill_list.append(new_sb)\n # 重新计算未完成仓单的数量,重量, 并且加入到已有的完成仓单列表中\n new_sb.harbor = unfinished_store_bill.harbor\n # 必须先计算净重\n unfinished_store_bill.weight = int(\n unfinished_store_bill.unit_weight * remain)\n unfinished_store_bill.quantity = remain\n unfinished_store_bill.delivery_session = None\n\n if len(finished_store_bill_list) == 0:\n raise ValueError(u\"至少需要一个仓单\")\n ds = finished_store_bill_list[0].delivery_session\n dt = models.DeliveryTask(ds, actor_id)\n actor = models.User.query.get(actor_id)\n for sb in finished_store_bill_list:\n sb.delivery_task = dt\n dt.quantity = sum(sb.quantity for sb in finished_store_bill_list)\n\n dt.returned_weight = sum(\n sb.weight for sb in finished_store_bill_list if sb.sub_order.returned)\n if unfinished_store_bill:\n do_commit([unfinished_store_bill, dt] + finished_store_bill_list)\n StoreBillWrapper(new_sb).do_create_log(\n u\"由剩余%s公斤的仓单%s装货、分裂产生\" % (unfinished_store_bill.weight, unfinished_store_bill.id), actor=actor)\n StoreBillWrapper(new_sb).do_update_log(u\"装货,发货会话%s、发货任务%s\" % (ds.id, dt.id))\n StoreBillWrapper(unfinished_store_bill).do_update_log(u\"装货、分裂出%s公斤的仓单%s\" % (new_sb.weight, new_sb.id),\n actor=actor)\n else:\n do_commit([dt] + finished_store_bill_list)\n for sb in finished_store_bill_list:\n StoreBillWrapper(sb).do_update_log(u\"装货,发货会话%s、发货任务%s\" % (ds.id, dt.id))\n\n from lite_mms.apis.todo import new_todo, WEIGH_DELIVERY_TASK\n from lite_mms.apis.auth import get_user_list\n\n for to in get_user_list(constants.groups.CARGO_CLERK):\n new_todo(to, WEIGH_DELIVERY_TASK, dt)\n dt = DeliveryTaskWrapper(dt)\n if dt.consignment:\n dt.consignment.staled()\n return dt\n\n @property\n def store_bill_id_list(self):\n return [sb.id for sb in self.store_bill_list]\n\n @property\n def log_list(self):\n from lite_mms.apis.log import LogWrapper\n\n ret = LogWrapper.get_log_list(str(self.id), self.model.__class__.__name__)\n return sorted(ret, lambda a, b: cmp(a.create_time, b.create_time), reverse=True)\n\n @property\n def pic_url_list(self):\n return [(store_bill.id, store_bill.pic_url) for store_bill in self.store_bill_list if store_bill.pic_url]\n\n @cached_property\n def last_weight(self):\n session = get_delivery_session(self.delivery_session_id)\n idx = get_delivery_session(\n self.delivery_session_id).delivery_task_list.index(self)\n if idx <= 0:\n return session.tare\n else:\n last_task = session.delivery_task_list[idx - 1]\n return last_task.weight + last_task.last_weight\n\n @classmethod\n def get_delivery_task(cls, task_id):\n if not task_id:\n return None\n try:\n return DeliveryTaskWrapper(\n models.DeliveryTask.query.filter_by(\n id=task_id).one())\n except NoResultFound:\n return None\n\n def update(self, **kwargs):\n if kwargs.get(\"weight\"):\n self.weight = kwargs['weight']\n\n total_org_weight = float(\n sum([sb.weight for sb in self.store_bill_list]))\n for sb in self.store_bill_list:\n sb.model.weight = int(\n round(self.weight * sb.weight / total_org_weight))\n from lite_mms import constants\n\n if sb.sub_order.order_type == constants.STANDARD_ORDER_TYPE:\n sb.model.quantity = sb.model.weight\n if self.consignment:\n self.consignment.staled()\n elif kwargs.get(\"returned_weight\"):\n self.model.returned_weight = kwargs[\"returned_weight\"]\n if self.consignment:\n self.consignment.staled()\n # 这也说明,若是计件类型的仓单,数量不会根据称重进行调整\n elif kwargs.get(\"is_last\"):\n self.model.is_last = kwargs[\"is_last\"]\n do_commit(self.model)\n return self\n\n def __eq__(self, other):\n return isinstance(other, DeliveryTaskWrapper) and other.id == self.id\n\n @property\n def consignment(self):\n for consignment in self.delivery_session.consignment_list:\n if consignment.customer.id == self.customer.id:\n return consignment\n return None\n\n @property\n def team_list(self):\n from lite_mms.utilities.functions import deduplicate\n\n return deduplicate(\n [sb.qir.work_command.team for sb in self.store_bill_list],\n lambda x: x.model)\n\n @property\n def sub_order_list(self):\n from lite_mms.utilities.functions import deduplicate\n\n return deduplicate([sb.sub_order for sb in self.store_bill_list],\n lambda x: x.model)\n\n @property\n def spec_type_list(self):\n return [\"-\".join((sub_order.spec, sub_order.type)) for sub_order in\n self.sub_order_list if sub_order.spec or sub_order.type]\n\n @property\n def unit(self):\n if self.sub_order_list:\n return self.sub_order_list[0].unit\n else:\n return \"\"\n\n def delete(self):\n ds = self.delivery_session\n do_commit(self.model, \"delete\")\n from lite_mms.portal.delivery.fsm import fsm\n\n fsm.reset_obj(ds)\n from flask.ext.login import current_user\n from lite_mms.basemain import timeline_logger\n\n timeline_logger.info(u\"删除了发货任务%d\" % self.id,\n extra={\"obj\": self.delivery_session.model,\n \"obj_pk\": self.delivery_session.id,\n \"action\": u\"删除发货任务\",\n \"actor\": current_user})\n fsm.next(constants.delivery.ACT_WEIGHT, current_user)\n\n from lite_mms.apis import todo\n # delete todo\n todo.remove_todo(todo.WEIGH_DELIVERY_TASK, self.id)\n return True\n\n\nclass ConsignmentWrapper(ModelWrapper):\n @classmethod\n def get_list(cls, delivery_session_id=None, is_paid=None,\n exporting=False, pay_in_cash=False, customer_id=0, idx=0,\n cnt=sys.maxint):\n cons_q = models.Consignment.query\n if is_paid is not None:\n cons_q = cons_q.filter(\n models.Consignment.is_paid == is_paid)\n if pay_in_cash:\n cons_q = cons_q.filter(\n models.Consignment.pay_in_cash == True)\n if delivery_session_id:\n cons_q = cons_q.filter(\n models.Consignment.delivery_session_id == delivery_session_id)\n if exporting:\n cons_q = cons_q.filter(models.Consignment.MSSQL_ID == None)\n if customer_id:\n cons_q = cons_q.filter(models.Consignment.customer_id == customer_id)\n totalcnt = cons_q.count()\n return [ConsignmentWrapper(c) for c in\n cons_q.offset(idx).limit(cnt).all()], totalcnt\n\n @cached_property\n def measured_by_weight(self):\n sub_order_list = []\n for task in self.delivery_session.delivery_task_list:\n sub_order_list.extend(task.sub_order_list)\n return all(\n sub_order.measured_by_weight for sub_order in sub_order_list)\n\n @classmethod\n def get_consignment(cls, id_):\n if not id_:\n return None\n try:\n return ConsignmentWrapper(\n models.Consignment.query.filter_by(id=id_).one())\n except NoResultFound:\n return None\n\n @classmethod\n def create_or_update_consignment(cls, customer_id, delivery_session_id, pay_in_cash):\n try:\n consignment = ConsignmentWrapper(models.Consignment.query.filter(models.Consignment.customer_id == customer_id).filter(\n models.Consignment.delivery_session_id == delivery_session_id).one())\n if consignment.stale:\n consignment.add_product_entries()\n consignment.add_todo()\n except NoResultFound:\n return new_consignment(customer_id, delivery_session_id, pay_in_cash=pay_in_cash)\n\n def add_product_entries(self):\n self.product_list = []\n do_commit(self)\n for t in self.delivery_session.delivery_task_list:\n if t.customer.id == self.customer_id:\n self.add_product_entry(t)\n\n def add_product_entry(self, delivery_task):\n p = models.ConsignmentProduct(delivery_task.product, delivery_task, self)\n if delivery_task.team_list:\n p.team = delivery_task.team_list[0]\n p.weight = delivery_task.weight\n p.returned_weight = delivery_task.returned_weight\n if not delivery_task.quantity:\n delivery_task.quantity = sum(store_bill.quantity for store_bill in\n delivery_task.store_bill_list)\n p.quantity = delivery_task.quantity\n if delivery_task.sub_order_list:\n sb = delivery_task.sub_order_list[0]\n p.unit = sb.unit\n p.spec = sb.spec\n p.type = sb.type\n do_commit(p)\n\n def staled(self):\n self.stale = True\n do_commit(self.model)\n\n @classmethod\n def new_consignment(cls, customer_id, delivery_session_id, pay_in_cash):\n customer = lite_mms.apis.customer.get_customer(customer_id)\n if not customer:\n raise ValueError(u'没有此客户%d' % customer_id)\n delivery_session = lite_mms.apis.delivery.get_delivery_session(\n delivery_session_id)\n if not delivery_session:\n raise ValueError(u'没有此发货会话%d' % delivery_session_id)\n if customer not in set(task.customer for task in delivery_session.delivery_task_list):\n raise ValueError(\"delivery session %d has no customer %s\" % (delivery_session_id, customer.name))\n consignment = ConsignmentWrapper(do_commit(models.Consignment(customer, delivery_session, pay_in_cash)))\n from flask.ext.login import current_user\n if current_user.is_authenticated:\n consignment.actor = current_user\n consignment.add_product_entries()\n consignment.add_todo()\n return consignment\n\n def remove_todo(self):\n lite_mms.apis.todo.remove_todo(lite_mms.apis.todo.PAY_CONSIGNMENT, self.id)\n\n def add_todo(self):\n self.remove_todo()\n if self.pay_in_cash and not self.is_paid:\n for to in lite_mms.apis.auth.get_user_list(constants.groups.ACCOUNTANT):\n lite_mms.apis.todo.new_todo(to, lite_mms.apis.todo.PAY_CONSIGNMENT, self)\n\n @property\n def plate(self):\n return self.delivery_session.plate\n\n @classmethod\n def update(cls, id, **kwargs):\n consignment = ConsignmentWrapper.get_consignment(id)\n if consignment.MSSQL_ID:\n raise ValueError(u\"已导入原系统的发货单不能再修改\")\n for k, v in kwargs.items():\n if hasattr(consignment, k):\n setattr(consignment, k, v)\n if k == \"pay_in_cash\" and v and not consignment.pay_in_cash:\n consignment.add_todo()\n return ConsignmentWrapper(do_commit(consignment))\n\n def paid(self):\n self.model.is_paid = True\n do_commit(self.model)\n\n @classmethod\n def get_customer_list(cls):\n from lite_mms import apis\n\n return apis.customer.CustomerWrapper.get_customer_list(models.Consignment)\n\n @cached_property\n def delivery_task_list(self):\n task_list = []\n for task in self.delivery_session.delivery_task_list:\n if task.customer.id == self.customer.id:\n task_list.append(task)\n return task_list\n\n def persist(self):\n import json\n from socket import error\n from sqlalchemy.exc import SQLAlchemyError\n from lite_mms.apis import broker\n\n if self.MSSQL_ID:\n raise ValueError(u\"%d已保存\" % self.id)\n try:\n remote_consignments = broker.get_consignments(self.consignment_id)\n for c in remote_consignments:\n self.model.MSSQL_ID = c[\"MSSQL_ID\"]\n break\n else:\n mssql_id = json.loads(broker.export_consignment(self))\n self.model.MSSQL_ID = mssql_id[\"id\"]\n db.session.add(self.model)\n db.session.commit()\n except (ValueError, error):\n raise ValueError(u\"与远端连接异常\")\n except SQLAlchemyError:\n raise ValueError(u\"%d修改本地数据库失败\" % self.id)\n\n\nclass ConsignmentProductWrapper(ModelWrapper):\n @classmethod\n def get_product(cls, id_):\n current = models.ConsignmentProduct.query.get(id_)\n if current:\n return ConsignmentProductWrapper(current)\n else:\n return None\n\n def update(self, **kwargs):\n for k, v in kwargs.items():\n if hasattr(self.model, k):\n setattr(self.model, k, v)\n do_commit(self.model)\n\n\nclass StoreBillWrapper(ModelWrapper):\n @property\n def delivered(self):\n return bool(self.delivery_task)\n\n @property\n def pic_url(self):\n if self.qir.pic_path:\n return url_for(\"serv_pic\", filename=self.qir.pic_path)\n else:\n return \"\"\n\n @cached_property\n def product(self):\n return self.sub_order.product\n\n @property\n def product_name(self):\n return self.product.name\n\n @property\n def unit(self):\n return self.sub_order.unit\n\n @classmethod\n def get_store_bill(cls, store_bill_id):\n if not store_bill_id:\n return None\n try:\n return StoreBillWrapper(models.StoreBill.query.filter_by(id=store_bill_id).one())\n except NoResultFound:\n return None\n\n @classmethod\n def customer_bill_list(cls):\n store_bill_list = get_store_bill_list()[0]\n\n from itertools import groupby\n from operator import attrgetter\n\n getter = attrgetter(\"customer.name\")\n\n customer_list = []\n for customer, g in groupby(sorted(store_bill_list, key=lambda x: getter(x).encode(\"gbk\")),\n lambda x: getattr(x, \"customer\")):\n customer.store_bill_list = list(g)\n\n # store_bill_list不可能为空\n customer.measured_by_weight = any(\n store_bill.sub_order.measured_by_weight for store_bill in customer.store_bill_list)\n customer_list.append(customer)\n\n return customer_list\n\n @classmethod\n def update_store_bill(cls, store_bill_id, **kwargs):\n store_bill = StoreBillWrapper.get_store_bill(store_bill_id)\n if not store_bill:\n raise ValueError(u'没有此仓单%d' % store_bill_id)\n\n if kwargs.get(\"printed\", None):\n store_bill.model.printed = kwargs.get(\"printed\")\n\n if kwargs.get(\"harbor\"):\n try:\n harbor = models.Harbor.query.filter_by(\n name=kwargs.get(\"harbor\")).one()\n except NoResultFound:\n raise ValueError(u'没有此装卸点%s' % kwargs.get(\"harbor\"))\n store_bill.model.harbor = harbor\n\n if kwargs.get(\"delivery_session_id\"):\n store_bill.delivery_session_id = kwargs.get(\"delivery_session_id\")\n store_bill.delivery_task_id = kwargs.get(\"delivery_task_id\")\n if kwargs.get(\"weight\"):\n store_bill.weight = kwargs[\"weight\"]\n if kwargs.get(\"quantity\"):\n store_bill.quantity = kwargs[\"quantity\"]\n do_commit(store_bill.model)\n store_bill.do_update_log()\n return StoreBillWrapper(do_commit(store_bill))\n\n @property\n def log_list(self):\n from lite_mms.apis.log import LogWrapper\n\n ret = LogWrapper.get_log_list(str(self.id), self.model.__class__.__name__)\n return sorted(ret, lambda a, b: cmp(a.create_time, b.create_time), reverse=True)\n\n def do_create_log(self, message=\"\", actor=None):\n from flask.ext.login import current_user\n from lite_mms.basemain import timeline_logger\n timeline_logger.info(message or u\"创建仓单%d\" % self.id,\n extra={\"obj\": self.model,\n \"obj_pk\": self.id,\n \"action\": u\"创建\",\n \"actor\": actor or (current_user if current_user.is_authenticated else None)})\n\n def do_update_log(self, message=\"\", actor=None):\n from flask.ext.login import current_user\n from lite_mms.basemain import timeline_logger\n\n timeline_logger.info(message or u\"更新仓单%d\" % self.id,\n extra={\"obj\": self.model,\n \"obj_pk\": self.id,\n \"action\": u\"更新\",\n \"actor\": actor or (current_user if current_user.is_authenticated else None)})\n\n @property\n def previous_store_bill(self):\n if self.qir.store_bill_list and self.qir.store_bill_list[0].id != self.id:\n return self.qir.store_bill_list[0]\n return None\n\n @property\n def next_store_bill_list(self):\n if self.qir.store_bill_list and self.qir.store_bill_list[0].id == self.id:\n return [sb for sb in self.qir.store_bill_list if sb.id != self.id]\n return []\n\ndef get_delivery_session_list(idx=0, cnt=sys.maxint, unfinished_only=False,\n keywords=None):\n q = models.DeliverySession.query.filter(\n models.DeliverySession.plate != \"foo\")\n if unfinished_only:\n q = q.filter(models.DeliverySession.finish_time == None).join(\n models.StoreBill).filter(models.StoreBill.delivery_task == None)\n if keywords:\n q = q.join(models.DeliveryTask).join(models.StoreBill).join(\n models.Customer).filter(\n or_(models.DeliverySession.plate.like(\"%\" + keywords + \"%\"),\n models.Customer.name.like(\"%\" + keywords + \"%\")))\n total_cnt = q.count()\n return [DeliverySessionWrapper(ds) for ds in\n q.order_by(models.DeliverySession.create_time.desc()).offset(\n idx).limit(cnt).all()], total_cnt\n\ndef get_delivery_session(session_id):\n if not session_id:\n return None\n try:\n return DeliverySessionWrapper(models.DeliverySession.query.filter(\n models.DeliverySession.id == session_id).one())\n except NoResultFound:\n return None\n\ndef get_delivery_task_list(ds_id):\n return [DeliveryTaskWrapper(dt) for dt in\n models.DeliveryTask.query.filter_by(\n delivery_session_id=ds_id).all()]\n\ndef create_or_update_consignment(customer_id, delivery_session_id, pay_in_cash):\n try:\n cn = ConsignmentWrapper(models.Consignment.query.filter(\n models.Consignment.customer_id == customer_id).filter(\n models.Consignment.delivery_session_id == delivery_session_id).one())\n cn.pay_in_cash = pay_in_cash\n if cn.stale:\n cn.add_product_entries()\n cn.stale = False\n do_commit(cn)\n return cn\n except NoResultFound:\n return new_consignment(customer_id, delivery_session_id, pay_in_cash=pay_in_cash)\n\ndef get_store_bill_list(idx=0, cnt=sys.maxint, unlocked_only=True, qir_id=None,\n customer_id=\"\", delivery_session_id=None,\n printed_only=False, unprinted_only=False,\n should_after=None):\n # TODO 没有彻底测试\n q = models.StoreBill.query\n if delivery_session_id:\n q = q.filter(\n models.StoreBill.delivery_session_id == delivery_session_id)\n elif unlocked_only:\n q = q.filter(models.StoreBill.delivery_session_id == None)\n if qir_id:\n q = q.filter(models.StoreBill.qir_id == qir_id)\n if customer_id:\n q = q.filter(models.StoreBill.customer_id == customer_id)\n if printed_only:\n q = q.filter(models.StoreBill.printed == True)\n if unprinted_only:\n q = q.filter(models.StoreBill.printed == False)\n if should_after:\n # note, remember to included in \"\"\n q = q.filter(models.StoreBill.create_time > should_after)\n\n total_cnt = q.count()\n q = q.order_by(models.StoreBill.id.desc()).offset(idx).limit(cnt)\n return [StoreBillWrapper(sb) for sb in q.all()], total_cnt\n\ndef fake_delivery_task():\n fake_delivery_session = do_commit(models.DeliverySession(plate=\"foo\", tare=0, finish_time=datetime.now()))\n return do_commit(models.DeliveryTask(fake_delivery_session, None))\n\nnew_delivery_session = DeliverySessionWrapper.new_delivery_session\nget_consignment_list = ConsignmentWrapper.get_list\nget_consignment = ConsignmentWrapper.get_consignment\nnew_consignment = ConsignmentWrapper.new_consignment\nnew_delivery_task = DeliveryTaskWrapper.new_delivery_task\nget_delivery_task = DeliveryTaskWrapper.get_delivery_task\nget_store_bill = StoreBillWrapper.get_store_bill\nget_store_bill_customer_list = StoreBillWrapper.customer_bill_list\nupdate_store_bill = StoreBillWrapper.update_store_bill\n\ndef store_bill_remain_unacceptable(unfinished_store_bill, remain):\n return remain >= unfinished_store_bill.weight\n\n\nclass CreateDeliveryTaskWithAbnormalWeight(yawf.Policy):\n\n def __call__(self):\n # strong guaranteed here\n doc = database.codernity_db.get('id', self.node.tag, with_doc=True)\n delivery_session = get_delivery_session(doc['delivery_session_id'])\n remain = doc['remain']\n from lite_mms.apis import wraps\n finished_store_bill_list = [wraps(models.StoreBill.query.get(store_bill_id)) for store_bill_id in doc['finished_store_bill_id_list']]\n unfinished_store_bill = wraps(models.StoreBill.query.get(doc['unfinished_store_bill_id']))\n is_finished = doc['is_last_task']\n loader = models.User.query.get(doc['loader_id'])\n from lite_mms.portal.delivery_ws.webservices import create_delivery_task\n create_delivery_task(delivery_session, remain, finished_store_bill_list,\n unfinished_store_bill, loader, is_finished)\n\n @property\n def dependencies(self):\n return [('PermitDeliveryTaskWithAbnormalWeight',\n {'name': u'批准生成剩余重量异常的发货任务',\n 'handler_group': models.Group.query.filter(models.Group.id==constants.groups.CARGO_CLERK).one(),\n 'tag': self.node.tag,})]\n\n\n def on_delayed(self, unmet_node):\n\n from lite_mms.apis.todo import new_todo, PERMIT_DELIVERY_TASK_WITH_ABNORMAL_WEIGHT\n from lite_mms.apis.auth import get_user_list\n for user in get_user_list(unmet_node.handler_group_id):\n new_todo(user, PERMIT_DELIVERY_TASK_WITH_ABNORMAL_WEIGHT, unmet_node)\n\nclass PermitDeliveryTaskWithAbnormalWeight(yawf.Policy):\n\n @property\n def annotation(self):\n from lite_mms.apis import wraps\n doc = database.codernity_db.get('id', self.node.tag, with_doc=True)\n remain = doc['remain']\n unfinished_store_bill = wraps(models.StoreBill.query.get(doc['unfinished_store_bill_id']))\n d = OrderedDict()\n d[u'剩余仓单编号'] = unfinished_store_bill.id\n d[u'仓单原重'] = unfinished_store_bill.weight\n d[u'产品'] = unfinished_store_bill.sub_order.product.name + '(%s:%s)' % (unfinished_store_bill.sub_order.spec or '?',\n unfinished_store_bill.sub_order.type or '?')\n d[u'客户'] = unfinished_store_bill.sub_order.customer.name\n d[u'剩余重量'] = str(remain) + u'(公斤)'\n return d\n\nif __name__ == \"__main__\":\n pass\n" }, { "alpha_fraction": 0.6173020601272583, "alphanum_fraction": 0.6187683343887329, "avg_line_length": 36.88888931274414, "blob_id": "6d82492c474e124601c41a1fcb6e3b37e74c78bc", "content_id": "e1d036d6cd747c7b0be155f9d7964de00d811abf", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "Python", "length_bytes": 682, "license_type": "no_license", "max_line_length": 110, "num_lines": 18, "path": "/lite_mms/tools/fabfile.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom fabric.api import *\n\nenv.hosts = ['localhost']\nenv.passwords = {\"localhost\":\"xy1234\"}\nenv.user = \"xy\"\n\ndef deploy():\n home_dir = \"/srv/www/lite-mms/\"\n lite_mms_dir = \"/srv/www/lite-mms/git-lite-mms\"\n python_home_dir = \"/srv/www/lite-mms/env/bin/activate\"\n with cd(lite_mms_dir):\n sudo('cd lite-mms && git pull origin master', user=\"www-data\")\n with prefix('source %s' % python_home_dir):\n run('python -c \"import sys; print sys.path\"')\n sudo('cd lite-mms && pip install -r requirements.txt && python setup.py install', user='www-data')\n sudo('service uwsgi restart')\n sudo('service nginx restart')\n" }, { "alpha_fraction": 0.6496565341949463, "alphanum_fraction": 0.6506378650665283, "avg_line_length": 42.39130401611328, "blob_id": "185e115c81d6d480237236dbe5287e66f631ccf3", "content_id": "2075f157962e4c56e4a7369587fa168ca5f3a81a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1055, "license_type": "no_license", "max_line_length": 99, "num_lines": 23, "path": "/lite_mms/portal/order/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\nfrom flask import Blueprint, redirect, url_for\r\nfrom flask.ext.login import login_required\r\nfrom lite_mms.basemain import data_browser, nav_bar\r\n\r\norder_page = Blueprint(\"order\", __name__, static_folder=\"static\", template_folder=\"templates\")\r\n\r\n\r\n@order_page.route(\"/\")\r\ndef index():\r\n return redirect(url_for(\"order.order_list\"))\r\n\r\n\r\nfrom lite_mms.portal.order import ajax, views, filters\r\n\r\nextra_params = {\"list_view\": {\"nav_bar\": nav_bar, \"sub_nav_bar\": views.sub_nav_bar,\r\n \"hint_message\": views.hint_message, \"titlename\": u\"订单管理\"},\r\n \"form_view\": {\"nav_bar\": nav_bar, \"titlename\": u\"订单详情\"}}\r\ndata_browser.register_model_view(views.order_model_view, order_page, extra_params=extra_params)\r\n\r\nextra_params = {\"list_view\": {\"nav_bar\": nav_bar, \"titlename\": u\"子订单管理\"},\r\n \"form_view\": {\"nav_bar\": nav_bar, \"titlename\": u\"子订单详情\"}}\r\ndata_browser.register_model_view(views.sub_order_model_view, order_page, extra_params=extra_params)" }, { "alpha_fraction": 0.5717905163764954, "alphanum_fraction": 0.5764358043670654, "avg_line_length": 29.753246307373047, "blob_id": "10c43f79d035271562e10368e36e73cc0369da70", "content_id": "9d8e194209945a42c9d460f187dce8c99db5da4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2374, "license_type": "no_license", "max_line_length": 90, "num_lines": 77, "path": "/lite_mms/apis/broker.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n@author: Yangminghua\n@version: $\n与MSSQL交互\n\"\"\"\n\nimport httplib\nimport json\nfrom lite_mms.basemain import app\n\n\ndef get_connection():\n return httplib.HTTPConnection(app.config[\"BROKER_IP\"],\n app.config[\"BROKER_PORT\"],\n timeout=app.config[\"BROKER_TIMEOUT\"])\n\n\ndef _get_data_from_remote(data_type, **kwargs):\n connection = get_connection()\n if kwargs:\n first = True\n query = \"\"\n for k, v in kwargs.iteritems():\n query += \"%s%s=%s\" % (\"?\" if first else \"&\", k, v)\n first = False\n connection.request(\"GET\", \"/\" + data_type + query)\n else:\n connection.request(\"GET\", \"/\" + data_type)\n rv = connection.getresponse()\n if rv.status != 200:\n raise ValueError(rv.read())\n obj = json.loads(rv.read())\n return obj\n\n\ndef import_products():\n return _get_data_from_remote(\"products\")\n\n\ndef import_types():\n return _get_data_from_remote(\"product-types\")\n\n\ndef import_customers():\n return _get_data_from_remote(\"customers\")\n\n\ndef import_consignments():\n return _get_data_from_remote(\"consignments\")\n\n\ndef get_consignments(consignment_id):\n return _get_data_from_remote(\"consignments\", PaperID=consignment_id)\n\n\ndef export_consignment(consignment):\n def consignment2dict(consignment):\n _dic = {\"consignment_id\": consignment.consignment_id,\n \"customer_id\": consignment.customer.MSSQL_ID,\n \"plate\": consignment.delivery_session.plate,\n \"weight\": sum(product.weight for product in consignment.product_list),\n \"quantity\": sum(product.quantity for product in consignment.product_list),\n \"product_list\": [{\"id\": p.product.MSSQL_ID,\n \"name\": p.product.name,\n \"quantity\": p.quantity,\n \"weight\": p.weight,\n \"isReturned\": 1 if p.returned_weight else 0} for p in\n consignment.product_list]}\n return _dic\n\n connection = get_connection()\n connection.request(\"POST\", \"/consignments\", json.dumps(consignment2dict(consignment)))\n rv = connection.getresponse()\n if rv.status != 200:\n raise ValueError(rv.read())\n return rv.read()\n" }, { "alpha_fraction": 0.5881683826446533, "alphanum_fraction": 0.640500545501709, "avg_line_length": 27.354839324951172, "blob_id": "3bb2e88ce4c39f6537e26a8ecebd336492c61050", "content_id": "cd90157379f26eed06e3c1f04e241df0d8b75567", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 879, "license_type": "no_license", "max_line_length": 71, "num_lines": 31, "path": "/alembic/versions/18d5259ad2f7_add_todo_table.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"add TODO table\n\nRevision ID: 18d5259ad2f7\nRevises: 335ff300f22b\nCreate Date: 2013-04-29 19:25:35.921755\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '18d5259ad2f7'\ndown_revision = '335ff300f22b'\n\nfrom datetime import datetime\nfrom alembic import op\nimport sqlalchemy as sa\n\ndef upgrade():\n op.create_table(\n \"TB_TODO\", \n sa.Column(\"id\", sa.Integer, primary_key=True),\n sa.Column(\"user_id\", sa.Integer, sa.ForeignKey(\"TB_USER.id\")),\n sa.Column(\"obj_pk\", sa.String(64)),\n sa.Column(\"create_time\", sa.DateTime, default=datetime.now),\n sa.Column(\"actor_id\", sa.Integer, sa.ForeignKey(\"TB_USER.id\")),\n sa.Column(\"action\", sa.String(64)),\n sa.Column(\"priority\", sa.Integer),\n sa.Column(\"msg\", sa.String(128)),\n sa.Column(\"context_url\", sa.String(256)))\n\ndef downgrade():\n op.drop_table(\"TB_TODO\")\n" }, { "alpha_fraction": 0.5698403120040894, "alphanum_fraction": 0.5732767581939697, "avg_line_length": 34.855072021484375, "blob_id": "de834a1b4cbf657fa299e1b1a76e6a9279e99ee4", "content_id": "b94fcc503fd6f0cacc4804914ff9b29aeb1346e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4947, "license_type": "no_license", "max_line_length": 83, "num_lines": 138, "path": "/lite_mms/utilities/logger_daemon.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n@author: Yangminghua\n@version: $\n\"\"\"\nimport os\nimport sys\nimport fcntl\nimport logging\nimport logging.handlers\nimport daemon\n\nclass FileLikeLogger:\n \"\"\"wraps a logging.Logger into a file like object\"\"\"\n\n def __init__(self, logger):\n self.logger = logger\n\n def write(self, str):\n str = str.rstrip() #get rid of all tailing newlines and white space\n if str: #don't log emtpy lines\n for line in str.split('\\n'):\n self.logger.critical(line) #critical to log at any logLevel\n\n def flush(self):\n for handler in self.logger.handlers:\n handler.flush()\n\n def close(self):\n for handler in self.logger.handlers:\n handler.close()\n\n\n\nclass PidFile(object):\n \"\"\"Context manager that locks a pid file. Implemented as class\n not generator because daemon.py is calling .__exit__() with no parameters\n instead of the None, None, None specified by PEP-343.\"\"\"\n # pylint: disable=R0903\n\n def __init__(self, path):\n self.path = path\n self.pidfile = None\n\n def __enter__(self):\n self.pidfile = open(self.path, \"a+\")\n try:\n fcntl.flock(self.pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)\n except IOError:\n raise SystemExit(\"Already running according to \" + self.path)\n self.pidfile.seek(0)\n self.pidfile.truncate()\n self.pidfile.write(str(os.getpid()))\n self.pidfile.flush()\n self.pidfile.seek(0)\n return self.pidfile\n\n def __exit__(self, exc_type=None, exc_value=None, exc_tb=None):\n try:\n self.pidfile.close()\n except IOError as err:\n # ok if file was just closed elsewhere\n if err.errno != 9:\n raise\n os.remove(self.path)\n\n\ndef openFilesFromLoggers(loggers):\n \"\"\"returns the open files used by file-based handlers of the specified\n loggers\"\"\"\n openFiles = []\n for logger in loggers:\n for handler in logger.handlers:\n if hasattr(handler, 'stream') and\\\n hasattr(handler.stream, 'fileno'):\n openFiles.append(handler.stream)\n return openFiles\n\n\nclass LoggingDaemonContext(daemon.DaemonContext):\n def _addLoggerFiles(self):\n \"\"\"adds all files related to loggers_preserve to files_preserve\"\"\"\n for logger in [self.stdout_logger, self.stderr_logger]:\n if logger:\n self.loggers_preserve.append(logger)\n loggerFiles = openFilesFromLoggers(self.loggers_preserve)\n self.files_preserve.extend(loggerFiles)\n\n def __init__(self, chroot_directory=None, working_directory='/', umask=0,\n uid=None, gid=None, prevent_core=True, detach_process=None,\n files_preserve=None, loggers_preserve=None, pidfile=None,\n stdout_logger=None, stderr_logger=None, signal_map=None):\n if not loggers_preserve: loggers_preserve = []\n if not files_preserve: files_preserve = []\n self.stdout_logger = stdout_logger\n self.stderr_logger = stderr_logger\n self.loggers_preserve = loggers_preserve\n\n devnull_in = open(os.devnull, 'r+')\n devnull_out = open(os.devnull, 'w+')\n files_preserve.extend([devnull_in, devnull_out])\n\n daemon.DaemonContext.__init__(self,\n chroot_directory=chroot_directory,\n working_directory=working_directory,\n umask=umask,\n uid=uid,\n gid=gid,\n prevent_core=prevent_core,\n detach_process=detach_process,\n files_preserve=files_preserve,\n pidfile=pidfile,\n stdin=devnull_in,\n stdout=devnull_out,\n stderr=devnull_out,\n signal_map=signal_map)\n\n def open(self):\n self._addLoggerFiles()\n daemon.DaemonContext.open(self)\n if self.stdout_logger:\n fileLikeObj = FileLikeLogger(self.stdout_logger)\n sys.stdout = fileLikeObj\n if self.stderr_logger:\n fileLikeObj = FileLikeLogger(self.stderr_logger)\n sys.stderr = fileLikeObj\n\n @classmethod\n def getRotFileLogger(cls, name, filePath, logLevel=logging.DEBUG, format=None):\n format = format or '%(message)s'\n my_logger = logging.getLogger(name)\n my_logger.setLevel(logLevel)\n handler = logging.handlers.RotatingFileHandler(\n filePath, maxBytes=2000, backupCount=2)\n formatter = logging.Formatter(format)\n handler.setFormatter(formatter)\n my_logger.addHandler(handler)\n return my_logger" }, { "alpha_fraction": 0.6617873907089233, "alphanum_fraction": 0.6671802997589111, "avg_line_length": 29.186046600341797, "blob_id": "589d0f2ef551f17657033468b0678eb838fd5294", "content_id": "5cac6e2f2fc03321b3aa24090773891024b4b575", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1362, "license_type": "no_license", "max_line_length": 112, "num_lines": 43, "path": "/lite_mms/portal/manufacture/actions.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom flask import redirect, url_for, request, json\nfrom flask.ext.databrowser import action\nfrom flask.ext.login import current_user\nfrom lite_mms import constants\nfrom lite_mms.apis import wraps\n\n\nclass ScheduleAction(action.DirectAction):\n\n def op_upon_list(self, objs, model_view):\n return redirect(\n url_for(\"manufacture.schedule\", _method=\"GET\", work_command_id=json.dumps([obj.id for obj in objs]),\n url=request.url))\n\n def test_enabled(self, model):\n if model.status in (constants.work_command.STATUS_DISPATCHING, constants.work_command.STATUS_REFUSED):\n return 0\n else:\n return -2\n\n def _get_forbidden_msg_formats(self):\n return {-2: u\"只有状态为待排产或者车间主任打回的工单才能排产\"}\n\n\nclass RetrieveAction(action.BaseAction):\n\n def op(self, obj):\n wraps(obj).go(actor_id=current_user.id, action=constants.work_command.ACT_RETRIEVAL)\n\n def test_enabled(self, model):\n if model.status in (constants.work_command.STATUS_ASSIGNING, constants.work_command.STATUS_ENDING):\n return 0\n else:\n return -2\n\n def _get_forbidden_msg_formats(self):\n return {-2: u\"状态不符合\"}\n\n\nschedule_action = ScheduleAction(u\"排产\")\n\nretrieve_action = RetrieveAction(u\"回收\")\n" }, { "alpha_fraction": 0.6234567761421204, "alphanum_fraction": 0.6234567761421204, "avg_line_length": 35.75, "blob_id": "79836823ff8c26ce1be522143c9e6511b46c4f60", "content_id": "eb4e43f6f10a028f8345d5629b27e772a1bf1ceb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 162, "license_type": "no_license", "max_line_length": 73, "num_lines": 4, "path": "/docs/source/constants/default.rst", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\r\ntypes of order\r\n==============\r\n.. automodule:: lite_mms.constants.default\r\n :members: STANDARD_ORDER_TYPE, REIGE_ORDER_TYPE, JINGUJIAN_ORDER_TYPE\r\n \r\n \r\n" }, { "alpha_fraction": 0.6440397500991821, "alphanum_fraction": 0.6456953883171082, "avg_line_length": 34.588233947753906, "blob_id": "823ec181a4986739ab135555afb61a8b307a03e6", "content_id": "999ae74be974625381db92ef9e50497c3acad878", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 624, "license_type": "no_license", "max_line_length": 119, "num_lines": 17, "path": "/lite_mms/portal/quality_inspection/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom flask import Blueprint\nfrom flask.ext.login import login_required\n\nfrom lite_mms.basemain import data_browser, nav_bar\n\nfrom lite_mms.portal.quality_inspection.views import qir_model_view\n\nqir_page = Blueprint(\"qir\", __name__, static_folder=\"static\", template_folder=\"templates\")\ndata_browser.register_model_view(qir_model_view, qir_page, {\"form_view\": {\"nav_bar\": nav_bar, \"titlename\": u\"质检报告\"},\n \"list_view\": {\"nav_bar\": nav_bar, \"titlename\": u\"质检报告列表\"}})\n\n\n@qir_page.before_request\n@login_required\ndef _():\n pass" }, { "alpha_fraction": 0.47780677676200867, "alphanum_fraction": 0.5104438662528992, "avg_line_length": 35.36585235595703, "blob_id": "83175499823950c62f3dd07b22e9006c0c537447", "content_id": "90b2195e40b0f648858dc279212d0cd1fe6b6bf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1532, "license_type": "no_license", "max_line_length": 83, "num_lines": 41, "path": "/alembic/versions/d9c0f19bdf2_add_log_table.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"add log table\r\n\r\nRevision ID: d9c0f19bdf2\r\nRevises: 4bc13c7caa37\r\nCreate Date: 2013-03-20 09:42:40.802000\r\n\r\n\"\"\"\r\n\r\n# revision identifiers, used by Alembic.\r\nrevision = 'd9c0f19bdf2'\r\ndown_revision = '4bc13c7caa37'\r\n\r\nfrom datetime import datetime\r\nfrom alembic import op\r\nimport sqlalchemy as sa\r\n\r\n\r\ndef upgrade():\r\n op.create_table(\"TB_LOG\",\r\n sa.Column(\"id\", sa.Integer, primary_key=True),\r\n sa.Column(\"actor_id\", sa.Integer, sa.ForeignKey(\"TB_USER.id\")),\r\n sa.Column(\"obj_cls\", sa.String(64), nullable=False),\r\n sa.Column(\"obj_pk\", sa.String(64), nullable=False),\r\n sa.Column(\"obj\", sa.String(64), nullable=False),\r\n sa.Column(\"action\", sa.String(64), nullable=False),\r\n sa.Column(\"create_time\", sa.DateTime, default=datetime.now),\r\n sa.Column(\"name\", sa.String(64)),\r\n sa.Column(\"level\", sa.String(64)),\r\n sa.Column(\"module\", sa.String(64)),\r\n sa.Column(\"func_name\", sa.String(64)),\r\n sa.Column(\"line_no\", sa.Integer),\r\n sa.Column(\"thread\", sa.Integer),\r\n sa.Column(\"thread_name\", sa.String(64)),\r\n sa.Column(\"process\", sa.Integer),\r\n sa.Column(\"message\", sa.String(256)),\r\n sa.Column(\"args\", sa.String(64)),\r\n sa.Column(\"extra\", sa.String(64)))\r\n\r\n\r\ndef downgrade():\r\n op.drop_table(\"TB_LOG\")\r\n" }, { "alpha_fraction": 0.5976095795631409, "alphanum_fraction": 0.6015936136245728, "avg_line_length": 21.81818199157715, "blob_id": "ac00e292b3b0bec37b013e66b2786f5822efacf8", "content_id": "bb432998785b3558fe2f53aea3d1c162a1009639", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 251, "license_type": "no_license", "max_line_length": 77, "num_lines": 11, "path": "/lite_mms/portal/import_data/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n@author: Yangminghua\n@version: $\n\"\"\"\nfrom flask import Blueprint\n\nimport_data_page = Blueprint(\"import_data\", __name__, static_folder=\"static\",\n template_folder=\"templates\")\n\nfrom . import views\n" }, { "alpha_fraction": 0.5319271087646484, "alphanum_fraction": 0.5396079421043396, "avg_line_length": 38.831050872802734, "blob_id": "ad66a19162a434cf54b48adca73aae2ccd500498", "content_id": "e0d649e0c524c983fc924ff5a97a74ca75720dcb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9097, "license_type": "no_license", "max_line_length": 188, "num_lines": 219, "path": "/lite_mms/test/at/steps/manufacture.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nimport json\nfrom StringIO import StringIO\n\nfrom flask import url_for\nfrom flask.ext.login import current_user\nfrom sqlalchemy import and_\nfrom pyfeature import step\n\nimport lite_mms\nfrom lite_mms import models\nfrom lite_mms.basemain import app\nfrom lite_mms.test.utils import login, client_login\nfrom lite_mms.constants import (quality_inspection as qi_const,\n work_command as wc_const)\n\n\n@step(u'调度员对子订单进行预排产(\\d+)公斤')\ndef _(step, weight, sub_order):\n with app.test_request_context():\n with app.test_client() as c:\n login('s', 's', c)\n rv = c.post('/order/work-command',\n data=dict(sub_order_id=sub_order.id,\n schedule_weight=weight))\n assert rv.status_code == 302\n\n\n@step(u'一条重量是(\\d+)公斤的工单生成了')\ndef _(step, weight, sub_order):\n model = models.WorkCommand\n return model.query.filter(and_(model.org_weight == weight,\n model.sub_order_id == sub_order.id)).one()\n\n\n@step(u'原子订单的剩余重量是(\\d+)公斤')\ndef _(step, weight, sub_order):\n assert int(sub_order.resync().remaining_quantity) == int(weight)\n\n\n@step(u'调度员将工单排产给车间')\ndef _(step, wc, department):\n with app.test_request_context():\n with app.test_client() as c:\n login('s', 's', c)\n rv = c.post('/manufacture/schedule/[%d]' % wc.id, data=dict(department_id=department.id, procedure_id=1))\n assert rv.status_code == 302\n\n\n@step(u'车间主任将看到工单')\ndef _(step, wc, department):\n with app.test_request_context():\n with app.test_client() as c:\n auth_token = client_login('dl', 'dl', c)\n url = '/manufacture_ws/work-command-list?department_id=%s&\\\nstatus=%d&auth_token=%s'\n rv = c.get(url % (department.id,\n lite_mms.constants.work_command.STATUS_ASSIGNING,\n auth_token))\n assert rv.status_code == 200\n d = json.loads(rv.data)['data'][0]\n assert d['customerName'] == \\\n wc.sub_order.order.goods_receipt.customer.name\n assert d['department']['id'] == department.id\n assert d['department']['name'] == department.name\n assert d['id'] == wc.id\n assert d['orderID'] == wc.sub_order.order.id\n assert d['subOrderId'] == wc.sub_order.id\n assert d['orgWeight'] == wc.org_weight\n\n\n@step(u'车间主任将工单分配到班组')\ndef _(step, wc, department, team):\n with app.test_request_context():\n with app.test_client() as c:\n auth_token = client_login('dl', 'dl', c)\n url = '/manufacture_ws/work-command/%d?action=%d&team_id=%s\\\n&auth_token=%s'\n rv = c.put(url % (wc.id,\n lite_mms.constants.work_command.ACT_ASSIGN,\n team.id,\n auth_token))\n assert rv.status_code == 200\n\n\n@step(u'班组长将看到工单')\ndef _(step, wc, team):\n with app.test_request_context():\n with app.test_client() as c:\n auth_token = client_login('tl', 'tl', c)\n rv = c.get('/manufacture_ws/work-command-list?team_id=%s&status=%d&auth_token=%s' % (team.id, lite_mms.constants.work_command.STATUS_ENDING, auth_token))\n assert rv.status_code == 200\n d = json.loads(rv.data)['data'][0]\n assert d['customerName'] == wc.sub_order.order.goods_receipt.customer.name\n assert d['team']['id'] == team.id\n assert d['team']['name'] == team.name\n assert d['id'] == wc.id\n assert d['orderID'] == wc.sub_order.order.id\n assert d['subOrderId'] == wc.sub_order.id\n assert d['orgWeight'] == wc.org_weight\n\n\n\n@step(u'班组长增加重量(\\d+)公斤, 并且结束')\ndef _(step, weight, wc):\n with app.test_request_context():\n with app.test_client() as c:\n auth_token = client_login('tl', 'tl', c)\n rv = c.put('/manufacture_ws/work-command/%d?action=%d&weight=%d&is_finished=1&auth_token=%s' % (wc.id, lite_mms.constants.work_command.ACT_ADD_WEIGHT, int(weight), auth_token))\n assert rv.status_code == 200\n\n@step(u'班组长增加重量(\\d+)公斤$')\ndef _(step, weight, wc):\n with app.test_request_context():\n with app.test_client() as c:\n auth_token = client_login('tl', 'tl', c)\n rv = c.put('/manufacture_ws/work-command/%d?action=%d&weight=%d&auth_token=%s' % (wc.id, lite_mms.constants.work_command.ACT_ADD_WEIGHT, int(weight), auth_token))\n assert rv.status_code == 200\n\n@step(u'工单的工序后重量是(\\d+)公斤')\ndef _(step, weight, wc):\n assert wc.resync().processed_weight == int(weight)\n\n@step(u'质检员可以看到工单')\ndef _(step, wc, team):\n with app.test_request_context():\n with app.test_client() as c:\n auth_token = client_login('qi', 'qi', c)\n rv = c.get('/manufacture_ws/work-command-list?status=%d&auth_token=%s' % (lite_mms.constants.work_command.STATUS_QUALITY_INSPECTING, auth_token))\n assert rv.status_code == 200\n d = json.loads(rv.data)['data'][0]\n assert d['customerName'] == wc.sub_order.order.goods_receipt.customer.name\n assert d['team']['id'] == team.id\n assert d['team']['name'] == team.name\n assert d['id'] == wc.id\n assert d['orderID'] == wc.sub_order.order.id\n assert d['subOrderId'] == wc.sub_order.id\n assert d['orgWeight'] == wc.org_weight\n\n@step(u'质检员全部通过该工单')\ndef _(step, wc):\n with app.test_request_context():\n with app.test_client() as c:\n auth_token = client_login('qi', 'qi', c)\n url = url_for('manufacture_ws.work_command',\n work_command_id=wc.id,\n action=wc_const.ACT_QI,\n auth_token=auth_token)\n rv = c.put(url,\n data={\n '0.jpeg': (StringIO('foo jpg 0'), '0.jpeg'),\n '1.jpeg': (StringIO('foo jpg 1'), '1.jpeg'),\n 'qirList':\n json.dumps([{'result': qi_const.FINISHED,\n 'weight': wc.processed_weight}])\n })\n assert rv.status_code == 200\n url = url_for('manufacture_ws.work_command', work_command_id=wc.id,\n auth_token=auth_token)\n rv = c.get(url)\n assert rv.status_code == 200\n d = json.loads(rv.data)\n assert len(d['qirList']) == 1\n qir_dict = d['qirList'][0]\n assert qir_dict['result'] == qi_const.FINISHED\n assert qir_dict['weight'] == wc.processed_weight\n assert qir_dict['quantity'] == wc.processed_weight\n assert qir_dict['actorId'] == current_user.id\n return qir_dict\n\n@step(u'该工单已经结束')\ndef _(step, wc):\n assert wc.resync().status == lite_mms.constants.work_command.STATUS_FINISHED\n\n@step(u'一条对应的仓单生成了')\ndef _(step, qir, harbor):\n model = models.StoreBill\n return model.query.filter(and_(model.qir_id==qir['id'],\n model.weight==qir['weight'],\n model.harbor_name==harbor.name)).one()\n\n\n@step(u'质检员保存质检结果')\ndef _(step, wc):\n with app.test_client() as c:\n auth_token = client_login('qi', 'qi', c)\n url = url_for('manufacture_ws.quality_inspection_report_list',\n work_command_id=wc.id,\n auth_token=auth_token)\n qir_list = [{'result': qi_const.FINISHED,\n 'weight': wc.processed_weight}]\n rv = c.put(url,\n data={\n '0.jpeg': (StringIO('foo jpg 0'), '0.jpg'),\n '1.jpeg': (StringIO('foo jpg 1'), '1.jpg'),\n 'qirList': json.dumps(qir_list)\n })\n assert rv.status_code == 200\n return qir_list\n\n\n@step(u'工单的质检报告列表正确保存了')\ndef _(step, wc, qir_list):\n with app.test_client() as c:\n auth_token = client_login('qi', 'qi', c)\n url = url_for('manufacture_ws.work_command', work_command_id=wc.id,\n auth_token=auth_token)\n rv = c.get(url)\n assert rv.status_code == 200\n wc_dict = json.loads(rv.data)\n assert len(wc_dict['qirList']) == 1\n qir_dict1 = wc_dict['qirList'][0]\n qir_dict2 = qir_list[0]\n\n assert qir_dict1['result'] == qi_const.FINISHED\n assert qir_dict1['weight'] == qir_dict2['weight']\n # 标准类型的质检单,重量与数量相同\n assert qir_dict1['quantity'] == qir_dict2['weight']\n assert qir_dict1['actorId'] == current_user.id\n" }, { "alpha_fraction": 0.46341463923454285, "alphanum_fraction": 0.4664634168148041, "avg_line_length": 16.263158798217773, "blob_id": "5d395d3f58e8f63dc111a7a46e9bc062ec1733a7", "content_id": "745e7ba0a7d936922adf0d3ef7cb497619e4a2f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 328, "license_type": "no_license", "max_line_length": 42, "num_lines": 19, "path": "/docs/source/index.rst", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": ".. lite-mms-doc Documentation master file.\n\n#######################################\nWelcome to lite-mms-doc's Documentation\n#######################################\n\n\n.. toctree::\n :maxdepth: 1\n \n webservices.rst \n mannual.rst\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n" }, { "alpha_fraction": 0.6042553186416626, "alphanum_fraction": 0.6085106134414673, "avg_line_length": 20.454545974731445, "blob_id": "04d5459e882de98e0c88f59db183d0c274a5c47a", "content_id": "be21d5b6bf22a5b137c627945cf83a128c9325bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 235, "license_type": "no_license", "max_line_length": 67, "num_lines": 11, "path": "/lite_mms/portal/search/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n@author: Yangminghua\n@version: $\n\"\"\"\nfrom flask import Blueprint\n\nsearch_page = Blueprint(\"search\", __name__, static_folder=\"static\",\n template_folder=\"templates\")\n\nfrom . import views" }, { "alpha_fraction": 0.6091192364692688, "alphanum_fraction": 0.6114575266838074, "avg_line_length": 31.075000762939453, "blob_id": "4ecc3aa85c8ead96ed9d935206df576918dfc056", "content_id": "7adfe93ab52bb4674b56852dee6a5889ae1cfd7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2616, "license_type": "no_license", "max_line_length": 103, "num_lines": 80, "path": "/lite_mms/portal/timeline/views.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nimport numbers\nfrom datetime import datetime, timedelta\nfrom flask import request\nfrom . import time_line_page\nfrom lite_mms.utilities.decorators import templated, nav_bar_set\nfrom lite_mms.apis import wraps\nfrom lite_mms.models import Log\nfrom lite_mms import models\n\nfrom flask.ext.databrowser import ModelView\nfrom flask.ext.databrowser.filters import EqualTo, Between\nfrom flask.ext.login import current_user\nfrom flask.ext.principal import PermissionDenied\n\nfrom flask.ext.databrowser import filters\n\n\nclass ObjClsFilter(filters.BaseFilter):\n UNLOAD_SESSION = 1\n GOODS_RECEIPT = 2\n ORDER = 3\n WORK_COMMAND = 4\n\n def set_sa_criterion(self, query):\n if isinstance(self.value, numbers.Number) or self.value.isdigit():\n self.value = int(self.value)\n obj_cls = \"\"\n if self.value == self.UNLOAD_SESSION:\n obj_cls = \"UnloadSession\"\n elif self.value == self.GOODS_RECEIPT:\n obj_cls = \"GoodsReceipt\"\n elif self.value == self.ORDER:\n obj_cls = \"Order\"\n elif self.value == self.WORK_COMMAND:\n obj_cls = \"WorkCommand\"\n if obj_cls:\n query = query.filter(Log.obj_cls == obj_cls)\n return query\n\n\nclass MyBetween(Between):\n format = \"%Y-%m-%d\"\n\n @property\n def input_type(self):\n return \"date\", \"date\"\n\n\nmy_between = MyBetween(\"create_time\", u\"从\", sep=u\"到\",\n default_value=[datetime.now().strftime(MyBetween.format),\n (datetime.now() + timedelta(days=7)).strftime(MyBetween.format)])\n\nobj_cls_fltr = ObjClsFilter(\"obj_class\", name=u\"是\", hidden=True,\n options=[(ObjClsFilter.UNLOAD_SESSION, u\"卸货会话\"),\n (ObjClsFilter.GOODS_RECEIPT, u\"收货会话\"),\n (ObjClsFilter.ORDER, u\"订单\"),\n (ObjClsFilter.WORK_COMMAND, u\"工单\")])\n\n\nclass TimeLineModelView(ModelView):\n def scaffold_list(self, objs):\n return [wraps(obj) for obj in objs]\n\n __default_order__ = (\"create_time\", \"desc\")\n\n list_template = \"timeline/timeline.html\"\n\n __column_labels__ = {\"actor\": u\"操作员\", \"create_time\": u\"创建时间\"}\n\n def try_view(self, processed_obj=None):\n if current_user.is_anonymous:\n raise PermissionDenied\n\n def get_column_filters(self):\n return [EqualTo(\"actor\", u\"是\", default_value=current_user.id),\n my_between, obj_cls_fltr]\n\n\ntime_line_model_view = TimeLineModelView(Log, u\"日志\")\n" }, { "alpha_fraction": 0.5557634830474854, "alphanum_fraction": 0.5595059990882874, "avg_line_length": 30.034883499145508, "blob_id": "35deacc318d8c7d4e3707fd298b714d86ea72912", "content_id": "311b9bd6ff81b3771921f427e79cc800431f5d62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2728, "license_type": "no_license", "max_line_length": 78, "num_lines": 86, "path": "/lite_mms/apis/product.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding:UTF-8 -*-\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom lite_mms import models\nfrom lite_mms.utilities import do_commit\n\ndef get_product_types():\n \"\"\"\n get the product types\n :return a list of dict, each dict has keys \"id\", \"name\"\n \"\"\"\n return [dict(id=t.id, name=t.name, MSSQL_ID=t.MSSQL_ID) for t in\n models.ProductType.query.all()]\n\n\ndef get_product_type(id_):\n \"\"\"\n get the product types\n :return a list of dict, each dict has keys \"id\", \"name\"\n \"\"\"\n if not id_:\n raise ValueError(u\"产品类型ID不能为空\")\n t = models.ProductType.query.filter(models.ProductType.id == id_).one()\n return dict(id=t.id, name=t.name, MSSQL_ID=t.MSSQL_ID)\n\n\ndef post_types(data):\n count = 0\n for type in data:\n try:\n models.ProductType.query.filter(\n models.ProductType.name == type[\"name\"]).one()\n except NoResultFound:\n do_commit(\n models.ProductType(name=type[\"name\"], MSSQL_ID=type[\"id\"]))\n count += 1\n return u\"成功添加%d条产品类型信息\" % count\n\n\ndef get_products():\n \"\"\"\n get the products\n :return a dict, the keys are product type id, the values are a list of \n dict, each dict has keys \"id\", \"name\". for example:\n {\n '1': [{\"id\": 1, \"name\": \"product a\"}, {\"id\": 2, \"name\": \"product b\"}],\n '2': [{\"id\": 3, \"name\": \"product c\"}],\n }\n \"\"\"\n products = models.Product.query.filter(models.Product.enabled==True).all()\n ret = {}\n for p in products:\n ret.setdefault(str(p.product_type_id), []).append(\n dict(id=p.id, name=p.name, MSSQL_ID=p.MSSQL_ID))\n return ret\n\n\ndef get_product(**kwargs):\n \"\"\"\n :return the model of product\n \"\"\"\n try:\n query_ = models.Product.query\n for k, v in kwargs.items():\n if not hasattr(models.Product, k):\n return None\n query_ = query_.filter(getattr(models.Product, k) == v)\n return query_.one()\n except NoResultFound:\n return None\n\n\ndef post_product(data):\n count = 0\n for k, v in data.items():\n product_type = models.ProductType.query.filter(\n models.ProductType.MSSQL_ID == int(k)).one()\n for product in v:\n try:\n models.Product.query.filter(\n models.Product.name == product[\"name\"]).filter(\n models.Product.product_type == product_type).one()\n except NoResultFound:\n do_commit(models.Product(product[\"name\"], product_type,\n MSSQL_ID=product[\"id\"]))\n count += 1\n return u\"成功添加%d条产品信息\" % count\n\n\n\n" }, { "alpha_fraction": 0.7516778707504272, "alphanum_fraction": 0.7785235047340393, "avg_line_length": 72.5, "blob_id": "186e4ab5e52582562b9484e5503ed85004e18b18", "content_id": "c3611f8b193910de642339a40fd31cb82d47a79f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 149, "license_type": "no_license", "max_line_length": 81, "num_lines": 2, "path": "/lite_mms/constants/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "from lite_mms.constants.default import * # pylint: disable=W0401\r\nfrom .import cargo, groups, quality_inspection, work_command, delivery, work_flow\r\n" }, { "alpha_fraction": 0.6492281556129456, "alphanum_fraction": 0.6500857472419739, "avg_line_length": 23.25, "blob_id": "d7abce38ae3e73e84989b79ba0a619f422176122", "content_id": "22c9ada6b69c98afbb1c1c4e8440bf61e7032520", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1172, "license_type": "no_license", "max_line_length": 114, "num_lines": 48, "path": "/lite_mms/portal/dashboard/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom flask import Blueprint, render_template\nfrom flask.ext.principal import PermissionDenied\nfrom lite_mms.utilities.decorators import templated, nav_bar_set\n\ndashboard = Blueprint(name=\"dashboard\", import_name=__name__, static_folder=\"static\", template_folder=\"templates\")\n\n\nclass Widget(object):\n def __init__(self, name, description, template_file=None):\n self.name = name\n self.description = description\n self.template_file = template_file or \"dashboard/widget.html\"\n\n def template(self):\n return render_template(self.template_file, widget=self)\n\n @property\n def data(self):\n return self.query()\n\n def query(self):\n return NotImplemented\n\n def try_view(self):\n return True\n\n\nDASHBOARD_WIDGETS = []\nfrom . import widgets\n\n\ndef _get_widgets():\n result = []\n for i in DASHBOARD_WIDGETS:\n try:\n i.try_view()\n result.append(i)\n except PermissionDenied:\n pass\n return result\n\n\[email protected](\"/\")\n@templated(\"dashboard/index.html\")\n@nav_bar_set\ndef index():\n return {\"titlename\": u\"仪表盘\", \"widgets\": _get_widgets()}\n\n\n" }, { "alpha_fraction": 0.6716417670249939, "alphanum_fraction": 0.7910447716712952, "avg_line_length": 14, "blob_id": "6a33d58087ab3621b60087dceb81061eed1f5168", "content_id": "85fc30260dfa71796e42e9fb89a2928651623670", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 134, "license_type": "no_license", "max_line_length": 34, "num_lines": 9, "path": "/broker/config.ini", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "[SQLServer]\nSQLServerHost=127.0.0.1\\SQLEXPRESS\nPort=\nDatabaseName=newjhy\nUser=sa\nPassword=123456\n[Broker]\nHost=127.0.0.1\nPort=9090" }, { "alpha_fraction": 0.5716630220413208, "alphanum_fraction": 0.5725747346878052, "avg_line_length": 39.93283462524414, "blob_id": "3937021bf644415bd7e6cfac775e609e0929042d", "content_id": "c2d7871e91acbce46227cfcc0d723bddfe0a2cdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5700, "license_type": "no_license", "max_line_length": 115, "num_lines": 134, "path": "/lite_mms/portal/store/views.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom flask import redirect, url_for, json, abort, render_template\nfrom werkzeug.utils import cached_property\nfrom wtforms.validators import Required\nfrom flask.ext.login import login_required\nfrom flask.ext.databrowser import ModelView, filters\nfrom flask.ext.databrowser.column_spec import ColumnSpec, InputColumnSpec, PlaceHolderColumnSpec\nfrom flask.ext.principal import PermissionDenied\n\nfrom lite_mms import models\nfrom lite_mms.basemain import nav_bar\nfrom lite_mms.apis.delivery import StoreBillWrapper\nfrom lite_mms.permissions import QualityInspectorPermission\nfrom lite_mms.portal.store import store_bill_page\nfrom lite_mms.utilities import decorators\n\n_printed = u\"<i class='fa fa-ticket fa-fw' title='已打印'></i>\"\n_unprinted = u\"<i class='fa fa-square-o fa-fw' title='未打印'></i>\"\n\n\nclass StoreBillModelView(ModelView):\n __default_order__ = (\"id\", \"desc\")\n\n __list_columns__ = [\"id\", \"customer\", \"product\", \"weight\", \"quantity\", \"sub_order.order.customer_order_number\",\n \"qir\", \"qir.actor\", \"printed\", \"create_time\", \"qir.work_command\", \"harbor\"]\n\n __column_labels__ = {\"id\": u\"仓单号\",\n \"customer\": u\"客户\",\n \"product\": u\"产品\",\n \"weight\": u\"重量(公斤)\",\n \"quantity\": u\"数量\",\n \"sub_order.order.customer_order_number\": u\"订单号\",\n \"qir\": u\"质检报告\",\n \"qir.actor\": u\"质检员\",\n \"create_time\": u\"创建时间\",\n \"qir.work_command\": u\"工单号\",\n \"printed\": u\"打印\",\n \"harbor\": u\"存放点\",\n \"pic_url\": u\"图片\"}\n\n __column_formatters__ = {\"printed\": lambda v, obj: _printed if v else _unprinted,\n \"harbor\": lambda v, model: v if v else \"\"}\n\n def preprocess(self, obj):\n return StoreBillWrapper(obj)\n\n def try_create(self):\n raise PermissionDenied\n\n class Undeliveried(filters.Only):\n def set_sa_criterion(self, q):\n if self.value:\n return q.filter(models.StoreBill.delivery_session == None).filter(\n models.StoreBill.delivery_task == None)\n else:\n return q\n\n @cached_property\n def attr(self):\n return self.col_name\n\n __column_filters__ = [filters.EqualTo(\"customer\", u\"是\"),\n filters.Only(\"printed\", display_col_name=u\"只展示未打印\", test=lambda v: v == False,\n notation=\"__only_printed\"),\n Undeliveried(\"undeliveried\", display_col_name=u\"只展示未发货\", test=None,\n notation=\"__undeliveried\")]\n\n def try_edit(self, processed_objs=None):\n def _try_edit(obj):\n if obj and obj.delivery_session and obj.delivery_task:\n raise PermissionDenied\n\n QualityInspectorPermission.test()\n if isinstance(processed_objs, (list, tuple)):\n for obj in processed_objs:\n _try_edit(obj)\n else:\n _try_edit(processed_objs)\n\n def edit_hint_message(self, obj, read_only=False):\n if read_only:\n if QualityInspectorPermission.can():\n return u\"仓单-%s已发货,不能编辑\" % obj.id\n else:\n return u\"您没有修改的权限\"\n else:\n return super(StoreBillModelView, self).edit_hint_message(obj, read_only)\n\n def get_form_columns(self, obj=None):\n columns = [ColumnSpec(\"id\"), \"qir.work_command\", \"customer\", \"product\",\n InputColumnSpec(\"harbor\", validators=[Required(u\"不能为空\")]), \"weight\"]\n if obj and not StoreBillWrapper(obj).sub_order.measured_by_weight:\n columns.extend([\"quantity\",\n ColumnSpec(\"unit\", label=u\"单位\"), ColumnSpec(\"sub_order.spec\", label=u\"型号\"),\n ColumnSpec(\"sub_order.type\", label=u\"规格\"), ])\n columns.extend([ColumnSpec(\"create_time\"),\n ColumnSpec(\"printed\", label=u\"是否打印\", formatter=lambda v, obj: u\"是\" if v else u\"否\"),\n ColumnSpec(\"sub_order.id\", label=u\"子订单号\"), \"sub_order.order.customer_order_number\",\n PlaceHolderColumnSpec(\"pic_url\", label=u\"图片\", template_fname=\"pic-snippet.html\",\n form_width_class=\"col-lg-3\"),\n PlaceHolderColumnSpec(\"log_list\", label=u\"日志\", template_fname=\"logs-snippet.html\")])\n return columns\n\n def get_customized_actions(self, processed_objs=None):\n if QualityInspectorPermission.can():\n from .actions import PreviewPrintAction\n\n return [PreviewPrintAction(u\"打印预览\")]\n else:\n return []\n\n @login_required\n def try_view(self, processed_objs=None):\n pass\n\n\nstore_bill_view = StoreBillModelView(models.StoreBill, u\"仓单\")\n\n\n@store_bill_page.route('/')\ndef index():\n return redirect(url_for(\"store_bill.store_bill_list\"))\n\n\n@store_bill_page.route(\"/store-bill-preview/<ids_>\")\[email protected]_bar_set\ndef store_bill_preview(ids_):\n if not ids_:\n abort(404)\n import lite_mms.apis as apis\n\n store_bill_list = [apis.delivery.get_store_bill(id_) for id_ in json.loads(ids_)]\n return render_template(\"store/batch-print-preview.html\", titlename=u\"仓单预览\", store_bill_list=store_bill_list,\n nav_bar=nav_bar)" }, { "alpha_fraction": 0.6079012751579285, "alphanum_fraction": 0.6187194585800171, "avg_line_length": 29.288835525512695, "blob_id": "ac8cbdfe4b31ad6405e22e4507f1c6dd0cd01a73", "content_id": "7ae2d4410e6bbbaa9706a9b1993403034b4ac471", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13405, "license_type": "no_license", "max_line_length": 118, "num_lines": 412, "path": "/lite_mms/test/at/steps/cargo.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n这里是test_cargo.py 的具体实现。\n\"\"\"\nfrom datetime import datetime\nfrom flask import g, _request_ctx_stack, session\nfrom pyfeature import *\n\nfrom lite_mms import models\nfrom lite_mms.basemain import app, timeline_logger\nfrom lite_mms.database import db\nfrom lite_mms.utilities import do_commit\n\nfrom lite_mms.test.utils import client_login\n\n#patch logger\ntimeline_logger.handlers = []\napp.config[\"CSRF_ENABLED\"] = False\napp.config[\"WTF_CSRF_ENABLED\"] = False\n\n\ndef refresh(obj):\n return db.session.query(obj.__class__).filter(obj.__class__.id == obj.id).one()\n\n\n@step(u\"收发员创建UnloadSession, 毛重是(\\d+)公斤\")\ndef _(step, weight, plate_):\n return do_commit(models.UnloadSession(plate_=plate_, gross_weight=weight))\n\n\n@step(u\"装卸工进行卸货,该货物来自(.+)\")\ndef _(step, customer_name, customer, harbor, product, us, is_last):\n from lite_mms.constants.cargo import STATUS_WEIGHING\n\n us.status = STATUS_WEIGHING\n return do_commit(models.UnloadTask(customer=customer, unload_session=us, harbor=harbor, creator=None, pic_path=\"\",\n product=product, is_last=is_last))\n\n\[email protected]_request\ndef patch():\n \"\"\"\n needn't login in\n \"\"\"\n g.identity.can = lambda p: True\n from lite_mms.apis.auth import UserWrapper\n\n user = UserWrapper(models.User.query.first())\n session['current_group_id'] = user.groups[0].id\n _request_ctx_stack.top.user = user\n\n\n@step(u\"收发员称重(\\d+)公斤\")\ndef _(step, weight, unload_task):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(\"/cargo/weigh-unload-task/%d\" % unload_task.id,\n data={\"weight\": weight, \"product_type\": 1, \"product\": 1, \"customer\": unload_task.customer.id})\n assert 302 == rv.status_code\n\n\n@step(u\"卸货会话已经关闭\")\ndef _(step, us):\n us = refresh(us)\n from lite_mms.constants.cargo import STATUS_CLOSED\n\n assert STATUS_CLOSED == us.status\n\n\n@step(u\"收发员生成收货单\")\ndef _(step, us):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(\"/cargo/unload-session/%d\" % us.id, data={\"__action__\": u\"生成收货单\"})\n assert 302 == rv.status_code\n return db.session.query(models.GoodsReceipt).filter(models.GoodsReceipt.unload_session_id == us.id).all()\n\n\n@step(u\"该收货单中包含一个项目,该项目的客户是(.+), 项目的重量是(\\d+)公斤\")\ndef _(step, customer_name, weight, gr_list):\n assert 1 == len(gr_list)\n assert customer_name == gr_list[0].customer.name\n assert int(weight) == sum(entry.weight for entry in gr_list[0].goods_receipt_entries)\n\n\n@step(u\"装卸工此时不能进行卸货\")\ndef _(step, us):\n with app.test_request_context():\n with app.test_client() as c:\n auth_token = client_login('l', 'l', c)\n rv = c.get(\"/cargo_ws/unload-session-list?auth_token=\" + auth_token)\n from flask import json\n\n assert not [i for i in json.loads(rv.data)[\"data\"] if not i[\"isLocked\"]]\n\n\n@step(u\"卸货会话没有关闭\")\ndef _(step, us):\n us = refresh(us)\n from lite_mms.constants.cargo import STATUS_CLOSED\n\n assert STATUS_CLOSED != us.status\n\n\n@step(u\"该会话中包含两个项目\")\ndef _(step, gr_list):\n assert 2 == len(gr_list)\n\n\n@step(u\"项目的客户是(.+), 项目的重量是(\\d+)公斤\")\ndef _(step, customer_name, weight, gr):\n assert customer_name == gr.customer.name\n assert int(weight) == sum(entry.weight for entry in gr.goods_receipt_entries)\n\n\n@step(u\"收发员创建卸货会话, 其状态是待称重\")\ndef _(step):\n plate_ = do_commit(models.Plate(name=u\"浙F oofoo\"))\n return do_commit(models.UnloadSession(plate_=plate_, gross_weight=1000))\n\n\n@step(u\"装卸工创建卸货任务\")\ndef _(step, customer, harbor, product, us):\n from lite_mms.constants.cargo import STATUS_WEIGHING, STATUS_LOADING\n\n us.status = STATUS_WEIGHING\n ut = do_commit(models.UnloadTask(customer=customer, unload_session=us, harbor=harbor, creator=None, pic_path=\"\",\n product=product, is_last=False))\n us.status = STATUS_LOADING\n return ut\n\n\n@step(u\"修改卸货会话的车牌号为(.+)\")\ndef _(step, plate_name, us):\n plate_ = do_commit(models.Plate(name=plate_name))\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(u\"/cargo/unload-session/%d\" % us.id, data={\"plate_\": plate_name})\n assert 302 == rv.status_code\n\n\n@step(u\"修改卸货会话的毛重为(\\d+)公斤\")\ndef _(step, weight, us):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(u\"/cargo/unload-session/%d\" % us.id, data={\"gross_weight\": int(weight)})\n assert 302 == rv.status_code\n\n\n@step(u\"卸货会话的车牌号为浙B 00002\")\ndef _(step, us):\n us = refresh(us)\n assert u\"浙B 00002\" == us.plate\n\n\n@step(u\"卸货会话的重量为(\\d+)公斤\")\ndef _(step, weight, us):\n us = refresh(us)\n assert int(weight) == us.gross_weight\n\n\n@step(u\"修改卸货任务的重量为(\\d+)公斤\")\ndef _(step, weight, ut):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(u\"/cargo/unload-task/%d\" % ut.id, data={\"weight\": weight})\n assert 302 == rv.status_code\n\n\n@step(u\"卸货任务的重量是(\\d+)公斤\")\ndef _(step, weight, ut):\n ut = refresh(ut)\n assert int(weight) == ut.weight\n\n\n@step(u\"关闭卸货会话\")\ndef _(step, us):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(\"/cargo/unload-session/%d\" % us.id, data={\"__action__\": u\"关闭\"})\n assert 302 == rv.status_code\n\n\n@step(u\"不能修改卸货会话\")\ndef _(step, us):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(u\"/cargo/unload-session/%d\" % us.id, data={\"gross_weight\": 123123})\n assert 403 == rv.status_code\n\n\n@step(u\"不能修改卸货任务\")\ndef _(step, ut):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(u\"/cargo/unload-task/%d\" % ut.id, data={\"weight\": 12312})\n assert 403 == rv.status_code\n\n\n@step(u\"未关闭的卸货会话\")\ndef _(step):\n from random import choice\n import string\n\n plate_ = do_commit(models.Plate(name=u\"浙%s %s%s%s%s%s\" % (\n choice(string.ascii_lowercase), choice(string.ascii_lowercase), choice(string.ascii_lowercase),\n choice(string.ascii_lowercase), choice(string.ascii_lowercase), choice(string.ascii_lowercase))))\n return do_commit(models.UnloadSession(plate_=plate_, gross_weight=1000))\n\n\n@step(u\"已称重的卸货任务\")\ndef _(step, us, customer, harbor, product):\n from lite_mms.constants.cargo import STATUS_WEIGHING, STATUS_LOADING\n\n us.status = STATUS_WEIGHING\n ut = do_commit(models.UnloadTask(customer=customer, unload_session=us, harbor=harbor, creator=None, pic_path=\"\",\n product=product, is_last=False, weight=5000))\n us.status = STATUS_LOADING\n return ut\n\n\n@step(u\"未称重的卸货任务\")\ndef _(step, us, customer, harbor, product):\n from lite_mms.constants.cargo import STATUS_WEIGHING\n\n ut = do_commit(models.UnloadTask(customer=customer, unload_session=us, harbor=harbor, creator=None, pic_path=\"\",\n product=product, is_last=False))\n us.status = STATUS_WEIGHING\n return ut\n\n\n@step(u\"删除卸货任务\")\ndef _(step, ut):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(\"/cargo/ajax/unload-task/%d\" % ut.id, data={\"action\": u\"delete\"})\n return rv.status_code\n\n\n@step(u\"无法删除\")\ndef _(step, status_code):\n assert 403 == status_code\n\n\n@step(u\"删除成功\")\ndef _(step, status_code):\n assert 200 == status_code\n\n\n@step(u\"未称重未关闭的卸货会话\")\ndef _(step, customer, harbor, product):\n from random import choice\n import string\n\n plate_ = do_commit(models.Plate(name=u\"浙%s %s%s%s%s%s\" % (\n choice(string.ascii_lowercase), choice(string.ascii_lowercase), choice(string.ascii_lowercase),\n choice(string.ascii_lowercase), choice(string.ascii_lowercase), choice(string.ascii_lowercase))))\n us = do_commit(models.UnloadSession(plate_=plate_, gross_weight=100000))\n from lite_mms.constants.cargo import STATUS_WEIGHING\n\n ut = do_commit(models.UnloadTask(customer=customer, unload_session=us, harbor=harbor, creator=None, pic_path=\"\",\n product=product, is_last=False))\n us.status = STATUS_WEIGHING\n return us\n\n\n@step(u\"收发员关闭卸货会话\")\ndef _(step, us):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(\"/cargo/unload-session/%d\" % us.id, data={\"__action__\": u\"关闭\"})\n return rv.status_code\n\n\n@step(u\"关闭失败\")\ndef _(step, status_code):\n assert 403 == status_code\n\n\n@step(u\"收发员称重卸货会话\")\ndef _(step, us):\n us = refresh(us)\n for ut in us.task_list:\n ut.weight = 4000\n from lite_mms.constants.cargo import STATUS_LOADING\n\n us.status = STATUS_LOADING\n do_commit(us)\n\n\n@step(u\"关闭成功\")\ndef _(step, status_code):\n assert 302 == status_code\n\n\n@step(u\"正在装货的车辆\")\ndef _(step, plate_name):\n plate_ = do_commit(models.Plate(name=plate_name))\n do_commit(models.UnloadSession(plate_=plate_, gross_weight=123))\n return plate_\n\n\n@step(u\"收发员创建新卸货会话\")\ndef _(step):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.get(\"/cargo/unload-session\")\n from bs4 import BeautifulSoup\n\n soup = BeautifulSoup(rv.data)\n return [i[\"value\"] for i in soup.find_all(\"option\")]\n\n\n@step(u\"车辆列表中无上述车辆\")\ndef _(step, plate, plate_list):\n assert plate.name not in plate_list\n\n\n@step(u\"卸货会话已关闭,未生成收货单\")\ndef _(step, customer, harbor, plate, product):\n us = do_commit(models.UnloadSession(plate_=plate, gross_weight=123123123))\n from lite_mms.constants.cargo import STATUS_CLOSED\n\n us.status = STATUS_CLOSED\n import datetime\n\n us.finish_time = datetime.datetime.now()\n do_commit(us)\n ut = do_commit(models.UnloadTask(customer=customer, unload_session=us, harbor=harbor, creator=None, pic_path=\"\",\n product=product, is_last=False))\n return us\n\n\n@step(u\"收发员重新打开卸货会话\")\ndef _(step, us):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(\"/cargo/unload-session/%d\" % us.id, data={\"__action__\": u\"打开\"})\n assert 302 == rv.status_code\n\n\n@step(u\"收发员修改其卸货任务的重量为(\\d+)KG\")\ndef _(step, weight, us):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(\"/cargo/unload-task/%d\" % us.task_list[0].id, data={\"weight\": weight})\n assert 302 == rv.status_code\n\n\n@step(u\"生成收货单。其产品重量为(\\d+)KG\")\ndef _(step, weight, us):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(\"/cargo/unload-session/%d\" % us.id, data={\"__action__\": u\"生成收货单\"})\n assert 302 == rv.status_code\n gr = models.GoodsReceipt.query.order_by(models.GoodsReceipt.id.desc()).first()\n assert int(weight) == sum(i.weight for i in gr.goods_receipt_entries)\n return gr\n\n\n@step(u\"收货单未过时\")\ndef _(step, gr):\n from lite_mms.apis import wraps\n\n assert not wraps(gr).stale\n\n\n@step(u\"又新增一卸货任务\")\ndef _(step, us):\n with app.test_request_context():\n with app.test_client() as c:\n auth_token = client_login('l', 'l', c)\n rv = c.post(\n u\"/cargo_ws/unload-task?actor_id=1&customer_id=1&harbour=foo车间&is_finished=1&session_id=%d\"\n u\"&auth_token=%s\" % (\n us.id, auth_token))\n assert 200 == rv.status_code\n rv = c.post(\"/cargo/weigh-unload-task/%s\" % rv.data,\n data={\"weight\": 2213, \"product_type\": 1, \"product\": 1, \"customer\": 1})\n assert 302 == rv.status_code\n\n\n@step(u\"收货单过时\")\ndef _(step, gr):\n from lite_mms.apis import wraps\n\n assert wraps(gr).stale\n\n\n@step(u\"不能修改收货单\")\ndef _(step, gr):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(\"/goods_receipt/goods-receipt/%d\" % gr.id)\n assert 403 == rv.status_code\n\n\n@step(u\"重新生成收货单\")\ndef _(step, us):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(\"/cargo/unload-session/%d\" % us.id, data={\"__action__\": u\"生成收货单\"})\n assert 302 == rv.status_code\n return models.GoodsReceipt.query.filter(models.GoodsReceipt.unload_session_id == us.id).all()\n\n\n@step(u\"生成订单\")\ndef _(step, gr):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(\"/goods_receipt/goods-receipt/%d\" % gr.id, data={\"__action__\": u\"生成计重类型订单\"})\n assert 302 == rv.status_code\n" }, { "alpha_fraction": 0.46061643958091736, "alphanum_fraction": 0.47602739930152893, "avg_line_length": 24.545454025268555, "blob_id": "bc5f87c20b87b9ccd1e2f1b423de7ec717a59d3a", "content_id": "b13a7051630004716dbf395fea99c04f9f035e5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 702, "license_type": "no_license", "max_line_length": 46, "num_lines": 22, "path": "/lite_mms/constants/groups.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n基本的用户角色\r\n\"\"\"\r\n\r\nDEPARTMENT_LEADER = 1 #: 车间主任\r\nTEAM_LEADER = 2 #: 班组长\r\nLOADER = 3 #: 装卸工\r\nQUALITY_INSPECTOR = 4 #: 质检员\r\nCARGO_CLERK = 5 #: 收发员\r\nSCHEDULER = 6 #: 调度员\r\nACCOUNTANT = 7 #: 财会人员\r\nADMINISTRATOR = 8 #: 管理员\r\n\r\nGROUP_NAME_LIST = {DEPARTMENT_LEADER: u\"车间主任\",\r\n TEAM_LEADER: u\"班组长\",\r\n LOADER: u\"装卸工\",\r\n QUALITY_INSPECTOR: u\"质检员\",\r\n CARGO_CLERK: u\"收发员\",\r\n SCHEDULER: u\"调度员\",\r\n ACCOUNTANT: u\"财会人员\",\r\n ADMINISTRATOR: u\"管理员\"}\r\n" }, { "alpha_fraction": 0.4747619032859802, "alphanum_fraction": 0.4995238184928894, "avg_line_length": 35.842105865478516, "blob_id": "29737ff36a646a4a45127ecdf491a0661a11b07a", "content_id": "675dc469f61fd3a154ff1af61f6f140c28d48a99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2100, "license_type": "no_license", "max_line_length": 83, "num_lines": 57, "path": "/alembic/versions/43d2714c4448_.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"empty message\n\nRevision ID: 43d2714c4448\nRevises: 2dda2c7c7e83\nCreate Date: 2013-09-21 20:43:41.755716\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '43d2714c4448'\ndown_revision = '26777e9808c2'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n\n # create model Node\n op.create_table(\"TB_NODE\", \n sa.Column('id', sa.Integer),\n sa.Column('work_flow_id', sa.Integer),\n sa.Column('name', sa.String(64)),\n sa.Column('approved', sa.Boolean),\n sa.Column('failed', sa.Boolean),\n sa.Column('create_time', sa.DateTime),\n sa.Column('handle_time', sa.DateTime),\n sa.Column('policy_name', sa.String(64)),\n sa.Column('tag', sa.String(32)),\n sa.Column('handler_group_id', sa.Integer),\n sa.ForeignKeyConstraint(['handler_group_id'], ['TB_GROUP.id']),\n sa.PrimaryKeyConstraint('id'))\n\n # create model WorkFlow\n op.create_table('TB_WORK_FLOW',\n sa.Column('id', sa.Integer),\n sa.Column('tag', sa.String(32)),\n sa.Column('annotation', sa.String(64)),\n sa.Column('status', sa.Integer),\n sa.Column('failed', sa.Boolean),\n sa.Column('root_node_id', sa.Integer),\n sa.Column('current_node_id', sa.Integer),\n sa.Column('token', sa.String(32)),\n sa.ForeignKeyConstraint(['root_node_id'], ['TB_NODE.id']),\n sa.ForeignKeyConstraint(['current_node_id'], ['TB_NODE.id']),\n sa.PrimaryKeyConstraint('id'))\n\n op.create_foreign_key('fk_work_flow_node', \n 'TB_NODE',\n 'TB_WORK_FLOW',\n ['work_flow_id'],\n ['id'])\n\ndef downgrade():\n op.drop_constraint('fk_work_flow_node', \"TB_NODE\", 'foreignkey')\n op.drop_table(\"TB_WORK_FLOW\")\n op.drop_table(\"TB_NODE\")\n" }, { "alpha_fraction": 0.6244813203811646, "alphanum_fraction": 0.6929460763931274, "avg_line_length": 18.95652198791504, "blob_id": "f6b29fd9baf7f06ea98df0fe736418f0901b0734", "content_id": "91b26d071f69daedb5b59233d72007b63ec6a65b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 482, "license_type": "no_license", "max_line_length": 64, "num_lines": 23, "path": "/alembic/versions/2f9253b0fa2d_table_tb_consignment.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"table TB_CONSIGNMENT add column MSSQL_ID\r\n\r\nRevision ID: 2f9253b0fa2d\r\nRevises: None\r\nCreate Date: 2013-01-22 16:32:31.080000\r\n\r\n\"\"\"\r\n\r\n# revision identifiers, used by Alembic.\r\nrevision = '2f9253b0fa2d'\r\ndown_revision = '2c1c00ece93d'\r\n\r\nfrom alembic import op\r\nimport sqlalchemy as sa\r\nfrom sqlalchemy import Column, Integer\r\n\r\n\r\ndef upgrade():\r\n op.add_column(\"TB_CONSIGNMENT\", Column(\"MSSQL_ID\", Integer))\r\n\r\n\r\ndef downgrade():\r\n op.drop_column(\"TB_CONSIGNMENT\", \"MSSQL_ID\")\r\n" }, { "alpha_fraction": 0.5885714292526245, "alphanum_fraction": 0.5942857265472412, "avg_line_length": 28.16666603088379, "blob_id": "07c3960285b0ac699798673bbf3a2073706e06c5", "content_id": "2288d6e99d5c5b5d7b714ceeac9acbde7ae9b49a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 175, "license_type": "no_license", "max_line_length": 68, "num_lines": 6, "path": "/lite_mms/portal/report/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\nfrom flask import Blueprint\n\nreport_page = Blueprint(\"report\", __name__, static_folder=\"static\", \n template_folder=\"templates\")\n" }, { "alpha_fraction": 0.6178937554359436, "alphanum_fraction": 0.6244175434112549, "avg_line_length": 42.79591751098633, "blob_id": "9d35897f866e60ef36e9fe6d33c4a8284cb722e1", "content_id": "a9b2af1f1bf048bbef34277e55f93b208a83dcc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2198, "license_type": "no_license", "max_line_length": 96, "num_lines": 49, "path": "/lite_mms/features/then.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom hashlib import md5\nfrom collections import namedtuple\nfrom lettuce import step, world\nfrom nose.tools import assert_equals\nfrom flask import url_for\n\n@step(u'用户\\((.*):(.*)\\)登陆后, 可以:')\ndef after_login_then_could(step, username, password):\n from lite_mms.basemain import app\n from lite_mms.permissions import permissions\n import flask.ext.principal as principal\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(url_for(\"auth.login\"), data=dict(username=username, password=password)) \n assert rv.status_code == 302\n from flask.ext.login import current_user\n for perm_dict in step.hashes:\n need = permissions[perm_dict[\"permission\"]][\"needs\"][0]\n perm = principal.Permission(need)\n assert perm.can()\n\n@step(u'用户\\((.*):(.*)\\)登陆后, 不可以:')\ndef after_login_then_could(step, username, password):\n from lite_mms.basemain import app\n from lite_mms.permissions import permissions\n import flask.ext.principal as principal\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(url_for(\"auth.login\"), data=dict(username=username, password=password)) \n assert rv.status_code == 302\n from flask.ext.login import current_user\n for perm_dict in step.hashes:\n need = permissions[perm_dict[\"permission\"]][\"needs\"][0]\n perm = principal.Permission(need)\n assert not perm.can()\n\n@step(u'用户\\((.*):(.*)\\)登陆后, 获取的内容是\"(.*)\"')\ndef after_login_then_redirect_to(step, username, password, content):\n from lite_mms.basemain import app\n from lite_mms.permissions import permissions\n import flask.ext.principal as principal\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(url_for(\"auth.login\"), \n data=dict(username=username, password=password), \n follow_redirects=True) \n assert_equals(rv.status_code, 200)\n assert_equals(rv.data.decode(\"utf-8\"), content)\n" }, { "alpha_fraction": 0.617241382598877, "alphanum_fraction": 0.617241382598877, "avg_line_length": 40.42856979370117, "blob_id": "1d0474b759f9d242aa20c5584d7686e62d3fd539", "content_id": "a0a35660ed881755be5aa9d3b79be10f4aedd975", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 306, "license_type": "no_license", "max_line_length": 159, "num_lines": 7, "path": "/lite_mms/templates/work_flow_repr/goods_receipt.html", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "<ul class=\"nav nav-pills nav-stacked\">\n{% for task in goods_receipt.unload_session.task_list %}\n <li>\n [{{task.create_time.strftime(\"%m-%d %H:%S\") }}] - 装卸工[<em>{{ task.creator.username }}]</em>在<em>{{task.harbor.name}}</em>卸货<strong>{{task.weight}}</strong>公斤\n </li>\n{% endfor %}\n</ul>\n" }, { "alpha_fraction": 0.6350515484809875, "alphanum_fraction": 0.692783534526825, "avg_line_length": 13.666666984558105, "blob_id": "36e04fda5030e4864163469187a7f74d9c967cb7", "content_id": "0a8842a6b8060e06c33c6736582abfe02a3d05fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 485, "license_type": "no_license", "max_line_length": 82, "num_lines": 33, "path": "/alembic/versions/d424258bb9c_add_stale_to_consign.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"add stale to consignment\r\r\r\rRevision ID: d424258bb9c\r\rRevises: 233cdabdfe51\r\rCreate Date: 2013-05-28 16:49:14.181000\r\r\r\r\"\"\"\r\r\r\r# revision identifiers, used by Alembic.\r\rrevision = 'd424258bb9c'\r\rdown_revision = '233cdabdfe51'\r\rfrom alembic import op\r\rimport sqlalchemy as sa\r\r\rdef upgrade():\r op.add_column(\"TB_CONSIGNMENT\", sa.Column(\"stale\", sa.Boolean, default=False))\r op.execute(\"UPDATE TB_CONSIGNMENT SET STALE=0\")\r\rdef downgrade():\r op.drop_column(\"TB_CONSIGNMENT\", \"stale\")\r\r" }, { "alpha_fraction": 0.7129629850387573, "alphanum_fraction": 0.7148148417472839, "avg_line_length": 24.66666603088379, "blob_id": "b8554c527970b464cfcf61d650ddd815b1784601", "content_id": "325778089663a6a96226949c57863c92c6e05ce8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 560, "license_type": "no_license", "max_line_length": 62, "num_lines": 21, "path": "/lite_mms/database.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom lite_mms.basemain import app\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = app.config[\"DBSTR\"]\nfrom flask.ext.sqlalchemy import SQLAlchemy\ndb = SQLAlchemy(app)\n\nfrom CodernityDB.database import Database\n\ncodernity_db = Database(app.config['CODERNITY_DATABASE_PATH'])\nif codernity_db.exists():\n codernity_db.open()\n codernity_db.reindex()\nelse:\n codernity_db.create()\n\napp.config[\"MONGODB_DB\"] = \"localhost\"\n\ndef init_db():\n # 必须要import models, 否则不会建立表\n from lite_mms import models\n db.create_all()\n\n" }, { "alpha_fraction": 0.5360496044158936, "alphanum_fraction": 0.5410798192024231, "avg_line_length": 25.357797622680664, "blob_id": "e90155eff54a47b9cfbd79f87d45e8d7c6eb22b5", "content_id": "734fdbf915c3b7bf6eda5002a377008d02e94c95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6134, "license_type": "no_license", "max_line_length": 79, "num_lines": 218, "path": "/lite_mms/utilities/functions.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\nimport os\r\nimport types\r\nimport time\r\nfrom datetime import datetime\r\n\r\n#from tornado import locale\r\n#user_locale = locale.get(app.config[\"LOCALE\"])\r\n#_ = user_locale.translate\r\n# TODO do translate in future\r\n_ = lambda x, **kwargs: x\r\n\r\n\r\ndef dictview(fields, d):\r\n items = []\r\n for field in fields:\r\n if isinstance(field, types.StringType):\r\n items.append((field, d.get(field)))\r\n elif isinstance(field, types.TupleType):\r\n items.append((field[0], d.get(field[1])))\r\n return dict(items)\r\n\r\n\r\ndef convert_time(d):\r\n for k, v in d.items():\r\n if k == u\"due_time\":\r\n d[k] = datetime.strptime(v, '%Y-%m-%d')\r\n if k == u\"finish_time\":\r\n d[k] = datetime.strptime(v, '%Y-%m-%d %H:%M:%S')\r\n\r\n\r\ndef find_first(iterable, f):\r\n return ([o for o in iterable if f(o)] or [None])[0]\r\n\r\n\r\ndef to_timestamp(dt):\r\n if isinstance(dt, datetime):\r\n return int(time.mktime(dt.timetuple()))\r\n elif isinstance(dt, time.struct_time):\r\n return int(time.mktime(dt))\r\n elif not dt:\r\n return None\r\n else:\r\n raise ValueError(\"%s can't convert to timestamp\" % str(dt))\r\n\r\n\r\ndef action_name(action):\r\n from lite_mms.constants import work_command\r\n\r\n if action == work_command.ACT_CHECK:\r\n return _(u\"<检货>\")\r\n elif action == work_command.ACT_DISPATCH:\r\n return _(u\"<排产>\")\r\n elif action == work_command.ACT_ASSIGN:\r\n return _(u\"<分配>\")\r\n elif action == work_command.ACT_ADD_WEIGHT:\r\n return _(u\"<增加重量>\")\r\n elif action == work_command.ACT_END:\r\n return _(u\"<请求结束>\")\r\n elif action == work_command.ACT_CARRY_FORWARD:\r\n return _(u\"<请求结转>\")\r\n elif action == work_command.ACT_REFUSE:\r\n return _(u\"<打回工单>\")\r\n elif action == work_command.ACT_RETRIEVAL:\r\n return _(u\"<回收>\")\r\n elif action == work_command.ACT_AFFIRM_RETRIEVAL:\r\n return _(u\"<确认回收>\")\r\n elif action == work_command.ACT_QI:\r\n return _(u\"<质检>\")\r\n elif action == work_command.ACT_QUICK_CARRY_FORWARD:\r\n return _(u\"<快速结转>\")\r\n elif action == work_command.ACT_RETRIVE_QI:\r\n return _(u\"<取消质检报告>\")\r\n elif action == work_command.ACT_REFUSE_RETRIEVAL:\r\n return _(u\"<拒绝回收>\")\r\n else:\r\n return _(u\"<未知>\")\r\n\r\n\r\ndef status_name(status):\r\n from lite_mms.constants import work_command\r\n\r\n if status == work_command.STATUS_DISPATCHING:\r\n return _(u\"<待排产>\")\r\n elif status == work_command.STATUS_ASSIGNING:\r\n return _(u\"<待分配>\")\r\n elif status == work_command.STATUS_LOCKED:\r\n return _(u\"<锁定, 待车间主任确认回收>\")\r\n elif status == work_command.STATUS_ENDING:\r\n return _(u\"<待请求结转或结束>\")\r\n elif status == work_command.STATUS_QUALITY_INSPECTING:\r\n return _(u\"<待质检>\")\r\n elif status == work_command.STATUS_REFUSED:\r\n return _(u\"<车间主任打回>\")\r\n elif status == work_command.STATUS_FINISHED:\r\n return _(u\"<已经结束>\")\r\n\r\n\r\ndef repr_wtforms_error(errors):\r\n return \";\".join(\"%s: %s\" % (k, \",\".join(v)) for k, v in errors.items())\r\n\r\n\r\ndef fslice(iterable, predict):\r\n a = []\r\n b = []\r\n for i in iterable:\r\n if predict(i):\r\n a.append(i)\r\n else:\r\n b.append(i)\r\n return a, b\r\n\r\n\r\nclass Config(object):\r\n __instance__ = None\r\n\r\n @classmethod\r\n def instance(cls):\r\n if cls.__instance__ is None:\r\n cls.__instance__ = Config()\r\n return cls.__instance__\r\n\r\n def __init__(self):\r\n import lite_mms.default_settings as config1\r\n\r\n self.config1 = config1\r\n try:\r\n if 'LITE_MMS_HOME' in os.environ:\r\n os.chdir(os.environ[\"LITE_MMS_HOME\"])\r\n from lite_mms import config\r\n\r\n self.config2 = config.__dict__\r\n else:\r\n self.config2 = {}\r\n except ImportError:\r\n self.config2 = {}\r\n import types\r\n\r\n d = types.ModuleType('config3')\r\n d.__file__ = \"config.py\"\r\n try:\r\n execfile(\"config.py\", d.__dict__)\r\n self.config3 = d\r\n except IOError:\r\n self.config3 = {}\r\n\r\n def __getattr__(self, name):\r\n try:\r\n return getattr(self.config3, name)\r\n except AttributeError:\r\n pass\r\n try:\r\n return getattr(self.config2, name)\r\n except AttributeError:\r\n pass\r\n try:\r\n return getattr(self.config1, name)\r\n except AttributeError:\r\n raise AttributeError(\"no such option: \" + name)\r\n\r\n\r\ndef do_commit(obj, action=\"add\"):\r\n from lite_mms.database import db\r\n\r\n if action == \"add\":\r\n if isinstance(obj, types.ListType) or isinstance(obj, types.TupleType):\r\n db.session.add_all(obj)\r\n else:\r\n db.session.add(obj)\r\n elif action == \"delete\":\r\n db.session.delete(obj)\r\n db.session.commit()\r\n return obj\r\n\r\n\r\ndef check_raise(obj, f, ExceptionCls, msg=u\"\"):\r\n if f(obj):\r\n raise ExceptionCls(msg)\r\n return obj\r\n\r\n\r\ndef get_or_404(cls, id_):\r\n from lite_mms.database import db\r\n from lite_mms.apis import ModelWrapper, wraps\r\n\r\n assert issubclass(cls, db.Model) or issubclass(cls, ModelWrapper)\r\n\r\n return wraps(cls.query.get_or_404(id_))\r\n\r\n\r\ndef _seek(seq, idfun):\r\n seen = set()\r\n if idfun is None:\r\n idfun = lambda x: x\r\n for x in seq:\r\n try:\r\n x_ = idfun(x)\r\n except:\r\n continue\r\n if x_ in seen:\r\n continue\r\n seen.add(x_)\r\n yield x\r\n\r\n\r\ndef deduplicate(seq, idfun=None):\r\n return list(_seek(seq=seq, idfun=idfun))\r\n\r\n\r\ndef camel_case(str_):\r\n import re\r\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', str_)\r\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()\r\n\r\n\r\ndef gen_qir_pic_path(idx):\r\n return 'qir-' + datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\") + '_' + \\\r\n str(idx) + \".jpeg\"\r\n" }, { "alpha_fraction": 0.5702959895133972, "alphanum_fraction": 0.5718815922737122, "avg_line_length": 29.53333282470703, "blob_id": "f43c7aa4635636fee5d4854142f8ec356c750b57", "content_id": "8078d8db148fc4c92f31043eb8169d7c4d1cda1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1910, "license_type": "no_license", "max_line_length": 77, "num_lines": 60, "path": "/lite_mms/apis/customer.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding:UTF-8 -*-\r\nfrom sqlalchemy.orm.exc import NoResultFound\r\nfrom lite_mms import models\r\nfrom lite_mms.apis import ModelWrapper\r\nfrom lite_mms.utilities import do_commit\r\n\r\nclass CustomerWrapper(ModelWrapper):\r\n def __str__(self):\r\n return self.name\r\n\r\n def __eq__(self, other):\r\n return isinstance(other, CustomerWrapper) and other.id == self.id\r\n\r\n def __hash__(self):\r\n return hash(self.id)\r\n\r\n @classmethod\r\n def get_list(cls):\r\n \"\"\"\r\n get customer list from database\r\n \"\"\"\r\n return [CustomerWrapper(c) for c in models.Customer.query.all()]\r\n\r\n\r\n @classmethod\r\n def get_customer(cls, customer_id):\r\n \"\"\"\r\n get a customer by id from database\r\n :return: the customer of given id or None if there's no such customer\r\n \"\"\"\r\n if not customer_id:\r\n return None\r\n try:\r\n return CustomerWrapper(models.Customer.query.filter(\r\n models.Customer.id == customer_id).one())\r\n except NoResultFound:\r\n return None\r\n\r\n @classmethod\r\n def get_customer_list(cls, model):\r\n q = models.Customer.query\r\n if model:\r\n q = q.join(model).filter(model.customer != None)\r\n return [CustomerWrapper(customer) for customer in q.all()]\r\n\r\ndef post_customers(data):\r\n count = 0\r\n for customer in data:\r\n try:\r\n models.Customer.query.filter(\r\n models.Customer.name == customer[\"name\"]).one()\r\n except NoResultFound:\r\n do_commit(models.Customer(name=customer[\"name\"],\r\n abbr=customer[\"short\"],\r\n MSSQL_ID=customer[\"id\"]))\r\n count += 1\r\n return u\"成功添加%d条客户信息\" % count\r\n\r\nget_customer_list = CustomerWrapper.get_list\r\nget_customer = CustomerWrapper.get_customer\r\n" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7811447978019714, "avg_line_length": 31.55555534362793, "blob_id": "86dd9b4104893c2a753a3c548a9ba531b196fb2d", "content_id": "75f4735040b103e22333c9b197f431b545d05e34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 311, "license_type": "no_license", "max_line_length": 57, "num_lines": 9, "path": "/lite_mms/permissions/department.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom collections import namedtuple\nfrom flask.ext.principal import Permission\n\nDepartmentManagement = namedtuple(\"department\", \"method\")\nEditDepartment = DepartmentManagement(\"edit_department\")\n\nedit_department = Permission(EditDepartment)\nedit_department = u\"编辑车间的权限\"\n\n\n\n\n" }, { "alpha_fraction": 0.569904088973999, "alphanum_fraction": 0.5731844305992126, "avg_line_length": 40.238014221191406, "blob_id": "d6eaad38b4e59e9fa6f3081e0ef34466d24a2e36", "content_id": "26f1eba54b015d84364c88a2cf36d902f97aba2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25319, "license_type": "no_license", "max_line_length": 119, "num_lines": 584, "path": "/lite_mms/portal/cargo/views.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom collections import OrderedDict\nimport re\nimport json\n\nfrom flask import request, abort, url_for, render_template, flash, g\nfrom flask.ext.login import login_required\nfrom sqlalchemy import exists, and_\nfrom flask.ext.databrowser import ModelView\nfrom flask.ext.databrowser.action import BaseAction\nfrom flask.ext.databrowser.column_spec import (InputColumnSpec, ColumnSpec,\n PlaceHolderColumnSpec, ListColumnSpec,\n TableColumnSpec, LinkColumnSpec)\n\nfrom flask.ext.principal import PermissionDenied\nfrom werkzeug.utils import redirect\nfrom wtforms import Form, IntegerField, validators\n\nfrom lite_mms.portal.cargo import cargo_page, fsm, gr_page\nfrom lite_mms.utilities import decorators, get_or_404\nfrom lite_mms.permissions import CargoClerkPermission, AdminPermission\nfrom lite_mms.basemain import nav_bar\nimport lite_mms.constants.cargo as cargo_const\nfrom lite_mms.database import db\nfrom lite_mms.models import (UnloadSession, Plate, GoodsReceipt,\n GoodsReceiptEntry, Product, UnloadTask, DeliverySession)\nfrom lite_mms.apis.cargo import UnloadSessionWrapper, UnloadTaskWrapper, GoodsReceiptWrapper, GoodsReceiptEntryWrapper\n\n\n@cargo_page.route('/')\ndef index():\n return redirect(unload_session_model_view.url_for_list())\n\n\n@gr_page.route('/')\ndef index():\n return redirect(goods_receipt_model_view.url_for_list(order_by=\"create_time\", desc=1))\n\n\nclass UnloadSessionModelView(ModelView):\n edit_template = \"cargo/unload-session.html\"\n\n can_batchly_edit = False\n\n def try_edit(self, objs=None):\n CargoClerkPermission.test()\n\n def _try_edit(obj_):\n if obj_ and obj_.finish_time:\n raise PermissionDenied\n\n if isinstance(objs, (list, tuple)):\n for obj_ in objs:\n _try_edit(obj_)\n else:\n _try_edit(objs)\n\n def repr_obj(self, obj):\n return unicode(obj) + \"(\" + cargo_const.desc_status(\n obj.status) + \")\" + \"<br /><p class='text-center'><small class='muted'>\" + '&nbsp;' + \",\".join(\n [unicode(customer) for customer in obj.customer_list]) + \"</small></p>\"\n\n def get_list_columns(self):\n def gr_item_formatter(v, obj):\n # 格式化每个收货单,未打印或者过期,需要提示出来\n ret = unicode(v)\n v = GoodsReceiptWrapper(v)\n if not v.printed:\n ret += u'<small class=\"text-danger\"> (未打印)</small>'\n if v.stale:\n ret += u'<small class=\"text-danger\"> (过期)</small>'\n return ret\n\n return [\"id\", \"plate_\", \"create_time\", \"finish_time\", \"with_person\", \"status\",\n ListColumnSpec(\"customer_list_unwrapped\", label=u\"客 户\", compressed=True),\n ListColumnSpec(\"goods_receipt_list_unwrapped\",\n label=u\"收货单\",\n compressed=True,\n item_col_spec=ColumnSpec(\"\", formatter=gr_item_formatter))]\n\n __column_labels__ = {\"id\": u\"编号\", \"plate_\": u\"车辆\", \"create_time\": u\"创建时间\", \"finish_time\": u\"结束时间\",\n \"with_person\": u\"驾驶室\", \"status\": u\"状态\", \"goods_receipt_list\": u\"收货单\", \"gross_weight\": u\"净重\"}\n\n def patch_row_attr(self, idx, obj):\n test = len(obj.customer_list) > len(obj.goods_receipt_list)\n stale = False\n unprinted = False\n for gr in obj.goods_receipt_list:\n if not gr.printed:\n unprinted = True\n if gr.stale:\n stale = True\n if test or stale:\n return {\n \"title\": u\"有客户收货单没有生成,或者存在已经过期的收货单, 强烈建议您重新生成收货单!\",\n \"class\": \"danger\"}\n elif unprinted:\n return {\n \"title\": u\"有客户收货单没有打印\",\n \"class\": \"warning\"}\n\n __column_formatters__ = {\n \"create_time\": lambda v, obj: v.strftime(\"%m月%d日 %H点\").decode(\"utf-8\"),\n \"finish_time\": lambda v, obj: v.strftime(\"%m月%d日 %H点\").decode(\"utf-8\") if v else \"--\",\n \"with_person\": lambda v, obj: u'有人' if v else u'无人',\n \"status\": lambda v, obj: cargo_const.desc_status(v),\n }\n\n __default_order__ = (\"id\", \"desc\")\n\n __sortable_columns__ = [\"id\", \"plate\", \"create_time\", \"finish_time\"]\n\n from flask.ext.databrowser import filters\n from datetime import datetime, timedelta\n\n today = datetime.today()\n yesterday = today.date()\n week_ago = (today - timedelta(days=7)).date()\n _30days_ago = (today - timedelta(days=30)).date()\n\n __column_filters__ = [filters.BiggerThan(\"create_time\", name=u\"在\", default_value=str(yesterday),\n options=[(yesterday, u'一天内'), (week_ago, u'一周内'),\n (_30days_ago, u'30天内')]),\n filters.EqualTo(\"plate_\", name=u\"是\"),\n filters.Only(\"status\", display_col_name=u\"仅展示未完成会话\", test=lambda col: ~col.in_(\n [cargo_const.STATUS_CLOSED, cargo_const.STATUS_DISMISSED]), notation=\"__only_unclosed\"),\n ]\n\n def try_view(self, processed_objs=None):\n from flask.ext.principal import Permission\n\n Permission.union(CargoClerkPermission, AdminPermission).test()\n\n def preprocess(self, model):\n return UnloadSessionWrapper(model)\n\n def get_customized_actions(self, model_list=None):\n from lite_mms.portal.cargo.actions import (CloseAction, OpenAction,\n CreateReceiptAction, BatchPrintGoodsReceipt,\n DeleteUnloadSessionAction)\n\n class _PrintGoodsReceipt(BaseAction):\n def op_upon_list(self, objs, model_list):\n obj = objs[0]\n return redirect(url_for(\"goods_receipt.goods_receipts_batch_print\",\n id_=\",\".join([str(gr.id) for gr in obj.goods_receipt_list]), url=request.url))\n\n action_list = []\n create_action = CreateReceiptAction(u\"生成收货单\")\n if model_list is None: # for list\n action_list.extend([CloseAction(u\"关闭\"), OpenAction(u\"打开\"), create_action,\n DeleteUnloadSessionAction(u\"删除\", None)])\n else:\n if len(model_list) == 1:\n if model_list[0].status in [cargo_const.STATUS_CLOSED, cargo_const.STATUS_DISMISSED]:\n action_list.append(OpenAction(u\"打开\"))\n else:\n action_list.append(CloseAction(u\"关闭\"))\n if create_action.test_enabled(model_list[0]) == 0:\n action_list.append(create_action)\n if model_list[0].goods_receipt_list:\n action_list.append(_PrintGoodsReceipt(u\"打印收货单\"))\n return action_list\n\n def get_list_help(self):\n return render_template(\"cargo/us-list-help.html\")\n\n # ================= FORM PART ============================\n def get_create_columns(self):\n def filter_plate(q):\n unfinished_us_list = UnloadSession.query.filter(UnloadSession.finish_time == None)\n unfinished_ds_list = DeliverySession.query.filter(DeliverySession.finish_time == None)\n plates = [us.plate for us in unfinished_us_list]\n plates.extend(ds.plate for ds in unfinished_ds_list)\n return q.filter(~Plate.name.in_(plates))\n # return q.filter(\n # and_(~exists().where(UnloadSession.plate == Plate.name).where(UnloadSession.finish_time == None),\n # ~exists().where(DeliverySession.finish_time == None).where(DeliverySession.plate == Plate.name)))\n\n return [InputColumnSpec(\"plate_\", filter_=filter_plate),\n InputColumnSpec(\"with_person\", label=u\"驾驶室是否有人\"),\n \"gross_weight\"]\n\n def edit_hint_message(self, obj, read_only=False):\n if read_only:\n return u\"已关闭的卸货会话不能修改\"\n else:\n return super(UnloadSessionModelView, self).edit_hint_message(obj, read_only)\n\n __form_columns__ = OrderedDict()\n __form_columns__[u\"详细信息\"] = [\n \"plate_\",\n InputColumnSpec(\"gross_weight\", label=u\"毛重\"),\n InputColumnSpec(\"with_person\", label=u\"驾驶室是否有人\"),\n ColumnSpec(\"status\", label=u\"状态\", formatter=lambda v, obj: cargo_const.desc_status(v)),\n InputColumnSpec(\"create_time\", label=u\"创建时间\", read_only=True),\n InputColumnSpec(\"finish_time\", label=u\"结束时间\", read_only=True),\n PlaceHolderColumnSpec(col_name=\"log_list\", label=u\"日志\", template_fname=\"logs-snippet.html\")\n ]\n __form_columns__[u\"收货任务列表\"] = [\n PlaceHolderColumnSpec(col_name=\"task_list\", label=u\"\",\n template_fname=\"cargo/unload-task-list-snippet.html\")]\n __form_columns__[u\"收货单列表\"] = [\n PlaceHolderColumnSpec(col_name=\"goods_receipt_list\", label=u\"\", template_fname=\"cargo/gr-list-snippet.html\")]\n\n def get_edit_help(self, objs):\n return render_template(\"cargo/us-edit-help.html\")\n\n def get_create_help(self):\n return render_template(\"cargo/us-create-help.html\")\n\n\nunload_session_model_view = UnloadSessionModelView(UnloadSession, u\"卸货会话\")\n\n\nclass PlateModelView(ModelView):\n can_edit = False\n create_template = \"cargo/plate.html\"\n\n __create_columns__ = __form_columns__ = [\n InputColumnSpec(\"name\",\n doc=u'车牌号的形式应当是\"省份缩写+字母+空格+五位数字或字母\"',\n validators=[\n validators.Regexp(u'^[\\u4E00-\\u9FA3][a-z]\\s*[a-z0-9]{5}$', flags=re.IGNORECASE | re.U,\n message=u\"格式错误\")]),\n ]\n\n def populate_obj(self, form):\n # normalize plate\n name = form[\"name\"].data\n m = re.match(u'^(?P<part1>[\\u4E00-\\u9FA3][a-z])\\s*(?P<part2>[a-z0-9]{5})$', name, re.IGNORECASE | re.U)\n name = m.groupdict()[\"part1\"] + ' ' + m.groupdict()[\"part2\"]\n name = name.upper()\n return Plate(name=name)\n\n\nplate_model_view = PlateModelView(Plate, u\"车辆\")\n\n\nclass GoodsReceiptEntryModelView(ModelView):\n @login_required\n def try_view(self, processed_objs=None):\n pass\n\n __form_columns__ = [\n InputColumnSpec(\"product\", group_by=Product.product_type, label=u\"产品\",\n filter_=lambda q: q.filter(Product.enabled == True)),\n InputColumnSpec(\"goods_receipt\", label=u\"收货单\", read_only=True),\n InputColumnSpec(\"weight\", label=u\"重量\"),\n InputColumnSpec(\"harbor\", label=u\"装卸点\"),\n PlaceHolderColumnSpec(\"pic_url\", label=u\"图片\", template_fname=\"pic-snippet.html\", form_width_class=\"col-lg-3\")]\n\n def preprocess(self, obj):\n return GoodsReceiptEntryWrapper(obj)\n\n def try_edit(self, objs=None):\n # 若收货单已经生成了订单,或者收货单已经过时,那么不能进行修改\n def _try_edit(obj):\n if obj:\n if isinstance(obj, self.data_browser.db.Model):\n obj = GoodsReceiptEntryWrapper(obj)\n if obj.goods_receipt.stale or obj.goods_receipt.order:\n raise PermissionDenied\n\n CargoClerkPermission.test()\n\n if isinstance(objs, list) or isinstance(objs, tuple):\n return any(_try_edit(obj) for obj in objs)\n else:\n return _try_edit(objs)\n\n def edit_hint_message(self, obj, read_only=False):\n if read_only:\n if obj.goods_receipt.stale:\n return u\"收货单过时,不能修改\"\n elif obj.goods_receipt.order:\n return u\"收货单已生成订单,不能修改\"\n else:\n return u\"\"\n else:\n return super(GoodsReceiptEntryModelView, self).edit_hint_message(obj, read_only)\n\n\ngoods_receipt_entry_view = GoodsReceiptEntryModelView(GoodsReceiptEntry, u\"收货单产品\")\n\n\n@cargo_page.route(\"/weigh-unload-task/<int:id_>\", methods=[\"GET\", \"POST\"])\[email protected](\"/cargo/unload-task.html\")\ndef weigh_unload_task(id_):\n from lite_mms import apis\n from lite_mms.apis import todo\n\n task = apis.cargo.get_unload_task(id_)\n if not task:\n abort(404)\n if request.method == 'GET':\n return dict(plate=task.unload_session.plate, task=task, nav_bar=nav_bar,\n product_types=apis.product.get_product_types(),\n products=json.dumps(apis.product.get_products()),\n customers=apis.customer.get_customer_list(),\n titlename=u\"收货任务\")\n else: # POST\n class _ValidationForm(Form):\n weight = IntegerField('weight', [validators.required()])\n customer = IntegerField('customer', [validators.required()])\n product = IntegerField('product')\n\n form = _ValidationForm(request.form)\n if form.validate():\n customer = apis.customer.get_customer(form.customer.data)\n weight = task.last_weight - form.weight.data\n if weight < 0 or not customer:\n abort(403)\n task.update(weight=weight, product_id=form.product.data, customer=customer)\n from flask.ext.login import current_user\n\n fsm.fsm.reset_obj(task.unload_session)\n fsm.fsm.next(cargo_const.ACT_WEIGHT, current_user)\n todo.remove_todo(todo.WEIGH_UNLOAD_TASK, id_)\n return redirect(\n request.form.get(\"url\", unload_session_model_view.url_for_object(model=task.unload_session.model)))\n else:\n if request.form.get(\"action\") == \"delete\":\n if task.delete():\n flash(u\"删除卸货任务%d成功\" % task.id)\n return redirect(request.form.get(\"url\", unload_session_model_view.url_for_object(\n model=task.unload_session.model)))\n return redirect(url_for(\"error\", errors=form.errors,\n url=unload_session_model_view.url_for_object(model=task.unload_session.model)))\n\n\nclass UnloadTaskModelView(ModelView):\n __form_columns__ = [\n ColumnSpec(\"id\", label=u\"编号\"),\n ColumnSpec(\"customer\", label=u\"客户\"),\n InputColumnSpec(\"product\", group_by=Product.product_type, label=u\"产品\",\n filter_=lambda q: q.filter(Product.enabled == True)),\n InputColumnSpec(\"weight\", label=u\"重量\"),\n InputColumnSpec(\"harbor\", label=u\"装卸点\"),\n PlaceHolderColumnSpec(col_name=\"pic_url\", label=u\"图片\", template_fname=\"pic-snippet.html\",\n form_width_class=\"col-lg-3\"),\n PlaceHolderColumnSpec(col_name=\"log_list\", label=u\"日志\", template_fname=\"logs-snippet.html\"), ]\n\n def preprocess(self, obj):\n return UnloadTaskWrapper(obj)\n\n def try_create(self):\n raise PermissionDenied\n\n def try_edit(self, objs=None):\n CargoClerkPermission.test()\n\n if any(obj.unload_session.status == cargo_const.STATUS_CLOSED for obj in objs):\n raise PermissionDenied\n\n def edit_hint_message(self, objs, read_only=False):\n if read_only:\n return u\"本卸货会话已经关闭,所以不能修改卸货任务\"\n return super(UnloadTaskModelView, self).edit_hint_message(objs, read_only)\n\n @login_required\n def try_view(self, processed_objs=None):\n pass\n\n\nunload_task_model_view = UnloadTaskModelView(UnloadTask, u\"卸货任务\")\n\n\nclass GoodsReceiptModelView(ModelView):\n edit_template = \"cargo/goods-receipt.html\"\n\n can_batchly_edit = True\n\n __default_order__ = (\"create_time\", \"desc\")\n\n def try_create(self):\n raise PermissionDenied\n\n def preprocess(self, obj):\n return GoodsReceiptWrapper(obj)\n\n @login_required\n def try_view(self, processed_objs=None):\n pass\n\n __sortable_columns__ = [\"id\", \"create_time\"]\n\n __list_columns__ = [\"id\", \"receipt_id\", \"customer\", \"unload_session.plate\",\n InputColumnSpec(\"order\", formatter=lambda v, obj: v or \"--\", label=u\"订单\"),\n ColumnSpec(\"printed\", formatter=lambda v, obj: u\"是\" if v else u\"否\", label=u\"是否打印\"),\n ColumnSpec(\"stale\", formatter=lambda v, obj: u\"是\" if v else u\"否\", label=u\"是否过时\"),\n ColumnSpec(\"create_time\",\n formatter=lambda v, obj: v.strftime(\"%y年%m月%d日 %H时%M分\").decode(\"utf-8\"),\n label=u\"创建时间\"), ColumnSpec(\"creator\"),\n ListColumnSpec(\"goods_receipt_entries\", label=u\"产品\", compressed=True,\n item_col_spec=ColumnSpec(\"\", formatter=lambda v, obj: unicode(\n v.product.product_type) + u\"-\" + unicode(v.product)))]\n\n def patch_row_attr(self, idx, obj):\n if obj.stale:\n return {\n \"class\": \"danger\",\n \"title\": u\"本收货单已经过时,请回到卸货会话重新生成\"\n }\n if not obj.printed:\n return {\n \"class\": \"warning\",\n \"title\": u\"本收货单尚未打印\"\n }\n\n from flask.ext.databrowser import filters\n from datetime import datetime, timedelta\n\n today = datetime.today()\n yesterday = today.date()\n week_ago = (today - timedelta(days=7)).date()\n _30days_ago = (today - timedelta(days=30)).date()\n\n class NoneOrder(filters.Only):\n def set_sa_criterion(self, q):\n if self.value:\n return q.filter(GoodsReceipt.order == None)\n else:\n return q\n\n __column_filters__ = [filters.BiggerThan(\"create_time\", name=u\"在\", default_value=str(yesterday),\n options=[(yesterday, u'一天内'), (week_ago, u'一周内'),\n (_30days_ago, u'30天内')]),\n filters.EqualTo(\"customer\", name=u\"是\"),\n filters.Only(\"printed\", display_col_name=u\"仅展示未打印收货单\", test=lambda col: ~col,\n notation=\"__only_unprinted\"),\n NoneOrder(\"order\", display_col_name=u\"仅展示未生成订单\", test=None, notation=\"__none\")]\n\n __form_columns__ = OrderedDict()\n __form_columns__[u\"详细信息\"] = [\n \"receipt_id\", \"customer\", \"unload_session.plate\",\n ColumnSpec(\"create_time\", label=u\"创建时间\"),\n ColumnSpec(\"creator\"),\n ColumnSpec(\"printed\", label=u\"是否打印\",\n formatter=lambda v,\n obj: u\"是\" if v else u'<span class=\"text-danger\">否</span>'),\n ColumnSpec(\"stale\", label=u\"是否过时\",\n formatter=lambda v, obj: u'<span class=\"text-danger\">是</span>' if v else u\"否\"),\n PlaceHolderColumnSpec(\"log_list\", label=u\"日志\", template_fname=\"logs-snippet.html\")]\n\n __form_columns__[u\"产品列表\"] = [\n TableColumnSpec(\n \"goods_receipt_entries\", label=\"\", preprocess=lambda obj: GoodsReceiptWrapper(obj),\n col_specs=[\n LinkColumnSpec(\"id\", label=u\"编号\", anchor=lambda v: v,\n formatter=lambda v, obj: goods_receipt_entry_view.url_for_object(obj, url=request.url)),\n ColumnSpec(\"product\", label=u\"产品\"),\n ColumnSpec(\"product.product_type\", label=u\"产品类型\"),\n ColumnSpec(\"weight\", label=u\"净重(公斤)\"),\n PlaceHolderColumnSpec(col_name=\"pic_url\", label=u\"图片\",\n template_fname=\"pic-snippet.html\",\n form_width_class=\"col-lg-3\")])]\n\n __column_labels__ = {\"receipt_id\": u'编 号', \"customer\": u'客 户', \"unload_session.plate\": u\"车牌号\",\n \"printed\": u'是否打印', \"stale\": u\"是否过时\", \"create_time\": u\"创建时间\", \"order\": u\"订 单\",\n \"creator\": u\"创建者\"}\n\n def get_customized_actions(self, objs=None):\n from lite_mms.portal.cargo.actions import PrintGoodsReceipt, BatchPrintGoodsReceipt, CreateOrderAction, \\\n CreateExtraOrderAction, ViewOrderAction, DeleteGoodsReceiptAction\n\n delete_goods_receipt_action = DeleteGoodsReceiptAction(u\"删除\")\n if not objs:\n if g.request_from_mobile:\n return [delete_goods_receipt_action]\n else:\n return [BatchPrintGoodsReceipt(u\"批量打印\"), delete_goods_receipt_action]\n else:\n def _get_actions(obj):\n if obj.order:\n return [ViewOrderAction(u\"查看订单\")]\n else:\n _actions = [CreateOrderAction(u\"生成计重类型订单\"), CreateExtraOrderAction(u\"生成计件类型订单\")]\n if not obj.printed:\n _actions.append(delete_goods_receipt_action)\n return _actions\n\n if isinstance(objs, (list, tuple)):\n if len(objs) == 1:\n actions = _get_actions(objs[0])\n else:\n actions = []\n else:\n actions = _get_actions(objs)\n if not g.request_from_mobile:\n actions.append(PrintGoodsReceipt(u\"打印\"))\n return actions\n\n def try_edit(self, objs=None):\n def _try_edit(obj):\n if obj:\n if isinstance(obj, self.data_browser.db.Model):\n obj = self.preprocess(obj)\n if obj.stale or obj.order:\n raise PermissionDenied\n\n CargoClerkPermission.test()\n\n if isinstance(objs, (list, tuple)):\n return any(_try_edit(obj) for obj in objs)\n else:\n return _try_edit(objs)\n\n def edit_hint_message(self, obj, read_only=False):\n if read_only:\n if obj.order:\n return u\"已生成订单的收货单不能修改\"\n else:\n return u\"已过时的收货单不能修改\"\n else:\n return super(GoodsReceiptModelView, self).edit_hint_message(obj, read_only)\n\n def batch_edit_hint_message(self, objs, read_only=False):\n if read_only:\n obj_ids = \",\".join([obj.receipt_id for obj in objs])\n for obj in objs:\n if obj.order:\n return u\"收货单%s已生成订单,不能批量修改%s\" % (obj.receipt_id, obj_ids)\n elif obj.stale:\n return u\"收货单%s已过时,不能批量修改%s\" % (obj.receipt_id, obj_ids)\n else:\n return u\"存在不能修改的收货单\"\n else:\n return super(GoodsReceiptModelView, self).edit_hint_message(objs, read_only)\n\n def get_batch_form_columns(self, preprocessed_objs=None):\n return [\"customer\", \"receipt_id\", \"create_time\", \"printed\"]\n\n\ngoods_receipt_model_view = GoodsReceiptModelView(GoodsReceipt, u\"收货单\")\n\n\n@cargo_page.route(\"/goods-receipt-preview/<int:id_>\")\[email protected](\"cargo/goods-receipt-preview.html\")\[email protected]_bar_set\ndef goods_receipt_preview(id_):\n from lite_mms import apis\n\n receipt = apis.cargo.get_goods_receipt(id_)\n per_page = apis.config.get(\"print_count_per_page\", 5.0, type=float)\n import math\n\n pages = int((len(receipt.goods_receipt_entries) - 1) / per_page) + 1\n if not receipt:\n abort(404)\n return {\"receipt\": receipt, \"titlename\": u\"收货单打印预览\", \"pages\": pages, \"per_page\": per_page}\n\n\ndef refresh_gr(id_):\n from lite_mms import apis\n\n receipt = apis.cargo.get_goods_receipt(id_)\n\n if not receipt:\n abort(404)\n if not receipt.stale:\n return redirect(url_for(\"error\", errors=u\"收货单%d未过时,不需要更新\" % id_))\n else:\n receipt.add_product_entries()\n return redirect(request.args.get(\"url\") or url_for(\"goods_receipt.goods_receipt\", id_=id_))\n\n\n@gr_page.route(\"/goods-receipts-batch-print/<id_>\")\[email protected](\"cargo/goods-receipts-batch-print.html\")\[email protected]_bar_set\ndef goods_receipts_batch_print(id_):\n from lite_mms import apis\n\n per_page = apis.config.get(\"print_count_per_page\", 5, type=int)\n gr_list = [get_or_404(GoodsReceipt, i) for i in id_.split(\",\")]\n pages = 0\n for gr in gr_list:\n gr.printed = True\n import math\n\n pages += int(math.ceil(len(gr.unload_task_list) / per_page))\n db.session.commit()\n return {\"gr_list\": gr_list, \"titlename\": u\"批量打印\",\n \"per_page\": per_page, \"pages\": pages, \"url\": request.args.get(\"url\", \"/\")}\n" }, { "alpha_fraction": 0.578401505947113, "alphanum_fraction": 0.5802218317985535, "avg_line_length": 43.690521240234375, "blob_id": "66b952f7a6e10661a7496dbfdb3a8746f9e47ce6", "content_id": "72b609f815034607f91eb6a0aea5dc34f012cd0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24800, "license_type": "no_license", "max_line_length": 122, "num_lines": 517, "path": "/lite_mms/portal/delivery/views.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: Yangminghua\r\n\"\"\"\r\nfrom collections import OrderedDict\r\nfrom flask import request, abort, render_template, url_for, flash, json\r\nfrom werkzeug.utils import redirect\r\nfrom wtforms import Form, IntegerField, validators, HiddenField\r\nfrom lite_mms.portal.delivery import delivery_page\r\nfrom lite_mms.permissions import CargoClerkPermission, AccountantPermission\r\nfrom lite_mms.utilities import decorators\r\n\r\nfrom flask.ext.login import current_user, login_required\r\nfrom flask.ext.principal import PermissionDenied\r\nfrom sqlalchemy import exists, and_\r\nfrom flask.ext.databrowser import ModelView, filters\r\nfrom flask.ext.databrowser.column_spec import ColumnSpec, ListColumnSpec, PlaceHolderColumnSpec, TableColumnSpec, \\\r\n InputColumnSpec, ImageColumnSpec\r\nfrom lite_mms import models, constants\r\nfrom lite_mms.apis.delivery import ConsignmentWrapper, DeliverySessionWrapper\r\n\r\n_with_person = u'<span class=\"icon-stack\" title=\"有人\"><i class=\"icon-sign-blank icon-stack-base\"></i><i ' \\\r\n u'class=\"icon-user icon-light\"></i></span>'\r\n\r\n_with_out_person = u'<span class=\"icon-stack\" title=\"空\"><i class=\"icon-check-empty icon-stack-base\"></i></span>'\r\n\r\n\r\nclass DeliverySessionModelView(ModelView):\r\n can_batchly_edit = False\r\n column_hide_backrefs = False\r\n edit_template = \"delivery/delivery-session.html\"\r\n list_template = \"delivery/delivery-session-list.html\"\r\n\r\n __sortable_columns__ = (\"create_time\", \"finish_time\")\r\n\r\n def get_list_columns(self):\r\n def gr_item_formatter(v, obj):\r\n # 格式化每个发货单,未打印或者过期,需要提示出来\r\n ret = unicode(v)\r\n if v.pay_in_cash and not v.is_paid:\r\n ret += u'<small class=\"text-danger\"> (未支付)</small>'\r\n if not v.MSSQL_ID:\r\n ret += u'<small class=\"text-danger\"> (未导入)</small>'\r\n if v.stale:\r\n ret += u'<small class=\"text-danger\"> (过期)</small>'\r\n return ret\r\n\r\n return [\"id\", \"plate_\", ColumnSpec(\"tare\", label=u\"净重(公斤)\", formatter=lambda v, obj: sum(\r\n dt.weight for dt in obj.delivery_task_list)), \"create_time\", \"finish_time\", \"with_person\", \"status\",\r\n ListColumnSpec(\"customer_list_unwrapped\", label=u\"客 户\", compressed=True),\r\n ListColumnSpec(\"consignment_list_unwrapped\", label=u\"发货单\", compressed=True,\r\n item_col_spec=ColumnSpec(\"\", formatter=gr_item_formatter))]\r\n\r\n @login_required\r\n def try_view(self, processed_objs=None):\r\n pass\r\n\r\n __column_labels__ = {\"id\": u\"编号\", \"plate_\": u\"车辆\", \"create_time\": u\"创建时间\", \"tare\": u\"皮重(公斤)\",\r\n \"with_person\": u\"驾驶室\", \"finish_time\": u\"结束时间\", \"status\": u\"状态\"}\r\n\r\n __column_formatters__ = {\r\n \"status\": lambda v, obj: constants.delivery.desc_status(v),\r\n \"create_time\": lambda v, obj: v.strftime(\"%m月%d日 %H点\").decode(\"utf-8\"),\r\n \"finish_time\": lambda v, obj: v.strftime(\"%m月%d日 %H点\").decode(\"utf-8\") if v else \"--\",\r\n \"with_person\": lambda v, obj: u'有人' if v else u'无人',\r\n }\r\n\r\n from datetime import datetime, timedelta\r\n\r\n today = datetime.today()\r\n yesterday = today.date()\r\n week_ago = (today - timedelta(days=7)).date()\r\n _30days_ago = (today - timedelta(days=30)).date()\r\n __column_filters__ = [filters.BiggerThan(\"create_time\", name=u\"在\", default_value=str(yesterday),\r\n options=[(yesterday, u'一天内'), (week_ago, u'一周内'),\r\n (_30days_ago, u'30天内')]),\r\n filters.EqualTo(\"plate_\", name=u\"是\"),\r\n filters.Only(\"status\", display_col_name=u\"仅展示未完成会话\", test=lambda col: ~col.in_(\r\n [constants.delivery.STATUS_CLOSED, constants.delivery.STATUS_DISMISSED]),\r\n notation=\"__only_unclosed\")]\r\n\r\n def get_form_columns(self, obj=None):\r\n __form_columns__ = OrderedDict()\r\n\r\n __form_columns__[u\"发货会话详情\"] = [ColumnSpec(\"id\"), \"plate_\", \"tare\", \"with_person\",\r\n ColumnSpec(\"create_time\"),\r\n ColumnSpec(\"finish_time\"),\r\n PlaceHolderColumnSpec(col_name=\"log_list\", label=u\"日志\",\r\n template_fname=\"logs-snippet.html\")]\r\n\r\n __form_columns__[u\"发货任务列表\"] = [\r\n PlaceHolderColumnSpec(\"delivery_task_list\", label=\"\",\r\n template_fname=\"delivery/delivery-task-list-snippet.html\")]\r\n\r\n __form_columns__[u\"发货单列表\"] = [\r\n PlaceHolderColumnSpec(\"consignment_list\", label=\"\",\r\n template_fname=\"delivery/consignment-list-snippet.html\")]\r\n if obj and obj.status not in [constants.delivery.STATUS_CLOSED, constants.delivery.STATUS_DISMISSED]:\r\n __form_columns__[u\"已选择仓单列表\"] = [\r\n PlaceHolderColumnSpec(\"store_bill_list\", label=\"\",\r\n template_fname=\"delivery/store-bill-list-snippet.html\")]\r\n return __form_columns__\r\n\r\n __default_order__ = (\"create_time\", \"desc\")\r\n\r\n def __list_filters__(self):\r\n return [filters.NotEqualTo(\"plate\", name=u\"\", value=\"foo\")]\r\n\r\n def preprocess(self, obj):\r\n return DeliverySessionWrapper(obj)\r\n\r\n def patch_row_attr(self, idx, obj):\r\n test = len(obj.customer_list) > len(obj.consignment_list)\r\n stale = False\r\n unimported = False\r\n for cn in obj.consignment_list:\r\n if not cn.MSSQL_ID:\r\n unimported = True\r\n if cn.stale:\r\n stale = True\r\n if test or stale:\r\n return {\r\n \"title\": u\"有客户发货单没有生成,或者存在已经过期的发货单, 强烈建议您重新生成发货单!\",\r\n \"class\": \"danger\"}\r\n elif unimported:\r\n return {\r\n \"title\": u\"有客户发货单未导入\",\r\n \"class\": \"warning\"}\r\n\r\n def get_create_columns(self):\r\n def filter_plate(q):\r\n unfinished_us_list = models.UnloadSession.query.filter(models.UnloadSession.finish_time == None)\r\n unfinished_ds_list = models.DeliverySession.query.filter(models.DeliverySession.finish_time == None)\r\n plates = [us.plate for us in unfinished_us_list]\r\n plates.extend(ds.plate for ds in unfinished_ds_list)\r\n return q.filter(~models.Plate.name.in_(plates))\r\n\r\n columns = OrderedDict()\r\n columns[u\"基本信息\"] = [InputColumnSpec(\"plate_\", filter_=filter_plate),\r\n InputColumnSpec(\"with_person\", label=u\"驾驶室是否有人\"), \"tare\"]\r\n columns[u\"已选择仓单列表\"] = [\r\n PlaceHolderColumnSpec(\"store_bill_list\", label=\"\", template_fname=\"delivery/store-bill-list-snippet.html\",\r\n as_input=True)]\r\n return columns\r\n\r\n def get_customized_actions(self, model_list=None):\r\n from lite_mms.portal.delivery.actions import CloseAction, OpenAction, CreateConsignmentAction, \\\r\n BatchPrintConsignment, DeleteDeliverySession\r\n\r\n action_list = []\r\n if model_list is None: # for list\r\n action_list.extend([CloseAction(u\"关闭\"), OpenAction(u\"打开\"), CreateConsignmentAction(u\"生成发货单\"),\r\n BatchPrintConsignment(u\"打印发货单\"), DeleteDeliverySession(u\"删除\")])\r\n else:\r\n if len(model_list) == 1:\r\n if model_list[0].status in [constants.delivery.STATUS_CLOSED, constants.delivery.STATUS_DISMISSED]:\r\n action_list.append(OpenAction(u\"打开\"))\r\n else:\r\n action_list.append(CloseAction(u\"关闭\"))\r\n if model_list[0].stale:\r\n action_list.append(CreateConsignmentAction(u\"生成发货单\"))\r\n if model_list[0].consignment_list:\r\n action_list.append(BatchPrintConsignment(u\"打印发货单\"))\r\n return action_list\r\n\r\n def try_edit(self, processed_objs=None):\r\n def _try_edit(obj):\r\n if obj and obj.finish_time or obj.status in [constants.delivery.STATUS_CLOSED,\r\n constants.delivery.STATUS_DISMISSED]:\r\n raise PermissionDenied\r\n\r\n if isinstance(processed_objs, (list, tuple)):\r\n for obj_ in processed_objs:\r\n _try_edit(obj_)\r\n else:\r\n _try_edit(processed_objs)\r\n\r\n def edit_hint_message(self, obj, read_only=False):\r\n if read_only:\r\n return u\"发货会话%s已关闭,不能修改\" % obj.id\r\n else:\r\n return super(DeliverySessionModelView, self).edit_hint_message(obj, read_only)\r\n\r\n def get_edit_help(self, objs):\r\n return render_template(\"delivery/ds-edit-help.html\")\r\n\r\n def get_list_help(self):\r\n return render_template(\"delivery/ds-list-help.html\")\r\n\r\n\r\n@delivery_page.route(\"/weigh-delivery-task/<int:id_>\", methods=[\"GET\", \"POST\"])\r\ndef weigh_delivery_task(id_):\r\n class DeliveryTaskForm(Form):\r\n weight = IntegerField(\"weight\", [validators.required()])\r\n url = HiddenField(\"url\")\r\n from lite_mms.apis.delivery import get_delivery_task\r\n from lite_mms.basemain import nav_bar\r\n\r\n task = get_delivery_task(id_)\r\n if not task:\r\n abort(404)\r\n if request.method == \"POST\":\r\n form = DeliveryTaskForm(request.form)\r\n if form.validate():\r\n weight = form.weight.data - task.last_weight\r\n result = task.update(weight=weight)\r\n if not result:\r\n abort(500)\r\n import fsm\r\n from lite_mms.apis import todo\r\n\r\n fsm.fsm.reset_obj(task.delivery_session)\r\n fsm.fsm.next(constants.delivery.ACT_WEIGHT, current_user)\r\n todo.remove_todo(todo.WEIGH_DELIVERY_TASK, id_)\r\n else:\r\n if request.form.get(\"action\") == \"delete\":\r\n try:\r\n task.delete()\r\n flash(u\"删除发货任务成功\")\r\n except:\r\n abort(403)\r\n else:\r\n return render_template(\"validation-error.html\", errors=form.errors,\r\n back_url=delivery_session_view.url_for_object(model=task.unload_session.model),\r\n nav_bar=nav_bar), 403\r\n return redirect(form.url.data or url_for(\"delivery.delivery_session\", id_=task.delivery_session_id))\r\n else:\r\n return render_template(\"delivery/delivery-task.html\", titlename=u\"发货任务称重\", task=task, nav_bar=nav_bar)\r\n\r\n\r\n@delivery_page.route(\"/create-consignment-list/<int:id_>\", methods=[\"POST\"])\r\ndef create_consignment_list(id_):\r\n from lite_mms.apis.delivery import get_delivery_session, create_or_update_consignment\r\n\r\n delivery_session = get_delivery_session(id_)\r\n if not delivery_session:\r\n abort(404)\r\n\r\n data = request.form.get(\"customer-pay_mod\")\r\n dict_ = json.loads(data)\r\n for k, v in dict_.items():\r\n try:\r\n create_or_update_consignment(customer_id=int(k), delivery_session_id=id_,\r\n pay_in_cash=int(v))\r\n except ValueError, e:\r\n flash(u\"发货会话%s生成发货单失败,原因:%s\" % (id_, unicode(e)), \"error\")\r\n break\r\n else:\r\n delivery_session.gc_consignment_list()\r\n flash(u\"发货会话%s生成发货单成功!\" % id_)\r\n return redirect(request.form.get(\"url\", url_for(\"delivery.delivery_session_list\")))\r\n\r\n\r\nclass DeliveryTaskModelView(ModelView):\r\n\r\n def get_form_columns(self, obj=None):\r\n columns = [ColumnSpec(\"id\", label=u\"编号\"), InputColumnSpec(\"weight\", label=u\"重量(公斤)\")]\r\n measured_by_weight = obj and obj.store_bill_list and any(\r\n store_bill.sub_order.measured_by_weight for store_bill in self.preprocess(obj).store_bill_list)\r\n if obj and not measured_by_weight:\r\n columns.extend([InputColumnSpec(\"quantity\", label=u\"数量\"), ColumnSpec(\"unit\", label=u\"单位\")])\r\n\r\n columns.append(ListColumnSpec(\"store_bill_list\", label=u\"仓单列表\", css_class=\"list-group\",\r\n item_css_class=\"list-group-item\", form_width_class=\"col-lg-3\"))\r\n\r\n if obj and not measured_by_weight:\r\n columns.append(ListColumnSpec(\"spec_type_list\", label=u\"规格-型号列表\", css_class=\"list-group\",\r\n item_css_class=\"list-group-item\", form_width_class=\"col-lg-3\"))\r\n columns.extend([ListColumnSpec(\"pic_url_list\", label=u\"图片\",\r\n formatter=lambda v, obj: None if not v else [i[-1] for i in v],\r\n item_col_spec=ImageColumnSpec(\"\", css_class=\"img-polaroid\",\r\n alt=obj.product.name if obj and obj.product else \"\"),\r\n css_class=\"list-group\",\r\n form_width_class=\"col-lg-3\",\r\n item_css_class=\"list-group-item\"),\r\n PlaceHolderColumnSpec(\"log_list\", label=u\"日志\", template_fname=\"logs-snippet.html\")])\r\n return columns\r\n\r\n def preprocess(self, obj):\r\n from lite_mms.apis.delivery import DeliveryTaskWrapper\r\n\r\n return DeliveryTaskWrapper(obj)\r\n\r\n def try_edit(self, objs=None):\r\n if any(obj.delivery_session.status in [constants.delivery.STATUS_CLOSED, constants.delivery.STATUS_DISMISSED]\r\n for obj in objs):\r\n raise PermissionDenied\r\n\r\n def edit_hint_message(self, objs, read_only=False):\r\n if read_only:\r\n return u\"发货会话已经关闭,所以不能修改发货任务\"\r\n return super(DeliveryTaskModelView, self).edit_hint_message(objs, read_only)\r\n\r\n def on_model_change(self, form, model):\r\n obj = self.preprocess(model)\r\n if obj.consignment:\r\n obj.consignment.staled()\r\n\r\n @login_required\r\n def try_view(self, processed_objs=None):\r\n pass\r\n\r\n\r\nclass ConsignmentModelView(ModelView):\r\n __default_order__ = (\"create_time\", \"desc\")\r\n\r\n def try_create(self):\r\n raise PermissionDenied\r\n\r\n def try_edit(self, processed_objs=None):\r\n from lite_mms.permissions.roles import CargoClerkPermission\r\n\r\n if not CargoClerkPermission.can():\r\n raise PermissionDenied\r\n if any(processed_obj.MSSQL_ID is not None for processed_obj in processed_objs) or any(\r\n processed_obj.stale for processed_obj in processed_objs) or any(\r\n processed_obj.is_paid and processed_obj.pay_in_cash for processed_obj in processed_objs):\r\n raise PermissionDenied\r\n\r\n def edit_hint_message(self, obj, read_only=False):\r\n if read_only:\r\n if obj.MSSQL_ID:\r\n return u\"发货单%s已插入MSSQL,不能修改\" % obj.consignment_id\r\n elif obj.stale:\r\n return u\"发货单%s已过时,需要重新生成\" % obj.consignment_id\r\n elif obj.is_paid:\r\n return u\"发货单%s已支付,不能修改\" % obj.consignment_id\r\n else:\r\n return u\"您没有修改发货单%s的权限\" % obj.consignment_id\r\n else:\r\n return super(ConsignmentModelView, self).edit_hint_message(obj, read_only)\r\n\r\n can_batchly_edit = False\r\n\r\n def patch_row_attr(self, idx, row):\r\n if row.stale:\r\n return {\"class\": u\"danger\", \"title\": u\"发货单已过时,请重新生成\"}\r\n\r\n def get_customized_actions(self, processed_objs=None):\r\n from .actions import PayAction, PreviewConsignment, DeleteConsignment, PersistConsignmentAction\r\n\r\n ret = [PreviewConsignment(u\"打印预览\")]\r\n if not processed_objs:\r\n ret.append(DeleteConsignment(u\"删除\"))\r\n\r\n if AccountantPermission.can() and isinstance(processed_objs, (list, tuple)):\r\n if any(obj.pay_in_cash and not obj.is_paid for obj in processed_objs):\r\n ret.append(PayAction(u\"支付\"))\r\n if processed_objs and any(not processed_obj.MSSQL_ID for processed_obj in processed_objs):\r\n ret.append(PersistConsignmentAction(u\"导入\"))\r\n return ret\r\n\r\n def __list_filters__(self):\r\n\r\n if AccountantPermission.can():\r\n return [filters.EqualTo(\"pay_in_cash\", value=True)]\r\n return []\r\n\r\n __sortable_columns__ = (\"create_time\", \"customer\", \"is_paid\")\r\n\r\n def get_list_columns(self):\r\n return [\"id\", \"consignment_id\", \"delivery_session\", \"actor\", \"create_time\", \"customer\", \"pay_in_cash\",\r\n ColumnSpec(\"is_paid\", formatter=lambda v, obj: u\"是\" if v else u\"否\"), ColumnSpec(\"notes\", trunc=8),\r\n \"MSSQL_ID\"]\r\n\r\n\r\n __column_labels__ = {\"consignment_id\": u\"发货单编号\", \"customer\": u\"客户\", \"delivery_session\": u\"车牌号\",\r\n \"actor\": u\"发起人\", \"delivery_session.id\": u\"发货会话\", \"create_time\": u\"创建时间\", \"is_paid\": u\"是否支付\",\r\n \"pay_in_cash\": u\"支付方式\", \"notes\": u\"备注\", \"MSSQL_ID\": u\"MSSQL编号\"}\r\n\r\n __column_formatters__ = {\"actor\": lambda v, obj: u\"--\" if v is None else v,\r\n \"pay_in_cash\": lambda v, obj: u\"现金支付\" if v else u\"月结\",\r\n \"MSSQL_ID\": lambda v,\r\n obj: v if v is not None else u\"<span class='text-danger'>未导入</span>\"}\r\n\r\n def get_column_filters(self):\r\n not_paid_default = AccountantPermission.can()\r\n return [filters.EqualTo(\"customer\", name=u\"是\"),\r\n filters.Only(\"is_paid\", display_col_name=u\"只展示未付款发货单\", test=lambda col: col == False,\r\n notation=u\"is_paid\", default_value=not_paid_default),\r\n filters.Only(\"MSSQL_ID\", display_col_name=u\"只展示未导出发货单\", test=lambda col: col == None,\r\n notation=\"is_export\", default_value=False)]\r\n\r\n def get_form_columns(self, obj=None):\r\n self.__form_columns__ = OrderedDict()\r\n self.__form_columns__[u\"发货单详情\"] = [ColumnSpec(\"consignment_id\"), ColumnSpec(\"actor\"),\r\n ColumnSpec(\"create_time\"), ColumnSpec(\"customer\"),\r\n ColumnSpec(\"delivery_session\")]\r\n from lite_mms.permissions.roles import CargoClerkPermission\r\n\r\n if CargoClerkPermission.can():\r\n self.__form_columns__[u\"发货单详情\"].extend((\"notes\", InputColumnSpec(\"pay_in_cash\", label=u\"现金支付\")))\r\n else:\r\n self.__form_columns__[u\"发货单详情\"].extend(\r\n (ColumnSpec(\"notes\"), ColumnSpec(\"pay_in_cash\", formatter=lambda v, obj: u\"现金支付\" if v else u\"月结\")))\r\n if obj and obj.pay_in_cash:\r\n self.__form_columns__[u\"发货单详情\"].append(ColumnSpec(\"is_paid\", formatter=lambda v, obj: u\"是\" if v else u\"否\"))\r\n\r\n col_specs = [ColumnSpec(\"id\", label=u\"编号\"),\r\n ColumnSpec(\"product\", label=u\"产品\",\r\n formatter=lambda v, obj: unicode(v.product_type) + \"-\" + unicode(v)),\r\n ColumnSpec(\"weight\", label=u\"重量(公斤)\")]\r\n sum_fields = [\"weight\"]\r\n\r\n if obj and not self.preprocess(obj).measured_by_weight:\r\n col_specs.extend([ColumnSpec(\"spec\", label=u\"型号\"), ColumnSpec(\"type\", label=u\"规格\"),\r\n ColumnSpec(\"quantity\", label=u\"数量\"), ColumnSpec(\"unit\", label=u\"单位\")])\r\n sum_fields.append(\"quantity\")\r\n\r\n col_specs.extend([ColumnSpec(\"returned_weight\", label=u\"退镀重量(公斤)\"),\r\n ColumnSpec(\"team\", label=u\"生产班组\")])\r\n sum_fields.append(\"returned_weight\")\r\n\r\n self.__form_columns__[u\"产品列表\"] = [\r\n TableColumnSpec(\"product_list_unwrapped\", label=\"\", col_specs=col_specs, sum_fields=sum_fields)]\r\n\r\n return self.__form_columns__\r\n\r\n def preprocess(self, obj):\r\n return ConsignmentWrapper(obj)\r\n\r\n def on_model_change(self, form, model):\r\n self.preprocess(model).add_todo()\r\n\r\n @login_required\r\n def try_view(self, processed_objs=None):\r\n pass\r\n\r\n\r\nclass ConsignmentProductModelView(ModelView):\r\n __column_labels__ = {\"id\": u\"编号\", \"product\": u\"产品\", \"weight\": u\"净重(公斤)\", \"returned_weight\": u\"退镀重量(公斤)\",\r\n \"team\": u\"班组\", \"quantity\": u\"数量\", \"unit\": u\"单位\", \"spec\": u\"型号\", \"type\": u\"规格\"}\r\n\r\n def try_edit(self, processed_objs=None):\r\n from lite_mms import permissions\r\n\r\n permissions.CargoClerkPermission.test()\r\n if processed_objs[0].consignment.MSSQL_ID is not None or processed_objs[0].consignment.stale:\r\n raise PermissionDenied\r\n\r\n def edit_hint_message(self, obj, read_only=False):\r\n from lite_mms import permissions\r\n\r\n if not permissions.CargoClerkPermission.can():\r\n return u\"您不能修改本发货单,因为您不是收发员\"\r\n if obj.consignment.MSSQL_ID is not None:\r\n return u\"您不能修改本发货单,该发货单已经插入原有系统\"\r\n return super(ConsignmentProductModelView, self).edit_hint_message(obj, read_only)\r\n\r\n def get_form_columns(self, obj=None):\r\n columns = [ColumnSpec(\"id\"), InputColumnSpec(\"product\", group_by=models.Product.product_type), \"weight\"]\r\n\r\n if obj and not ConsignmentWrapper(obj.consignment).measured_by_weight:\r\n columns.extend([\"quantity\", \"unit\", \"spec\", \"type\"])\r\n columns.extend([\"returned_weight\", \"team\"])\r\n return columns\r\n\r\n @login_required\r\n def try_view(self, processed_objs=None):\r\n pass\r\n\r\n\r\ndelivery_session_view = DeliverySessionModelView(models.DeliverySession, u\"发货会话\")\r\ndelivery_task_view = DeliveryTaskModelView(models.DeliveryTask, u\"发货任务\")\r\nconsigment_model_view = ConsignmentModelView(models.Consignment, u\"发货单\")\r\nconsigment_product_model_view = ConsignmentProductModelView(models.ConsignmentProduct, u\"发货单项\")\r\n\r\n\r\n@delivery_page.route('/')\r\ndef index():\r\n return redirect(url_for(\"delivery.delivery_session_list\"))\r\n\r\n\r\n@delivery_page.route(\"/store-bill-list\")\r\n@delivery_page.route(\"/store-bill-list/<int:delivery_session_id>\", methods=['POST', 'GET'])\r\[email protected]()\r\[email protected](\"/delivery/store-bill-list.html\")\r\[email protected]_bar_set\r\ndef store_bill_add(delivery_session_id=None):\r\n import lite_mms.apis as apis\r\n\r\n if request.method == 'POST':\r\n store_bill_id_list = request.form.getlist('store_bill_list', type=int)\r\n delivery_session = apis.delivery.get_delivery_session(\r\n delivery_session_id)\r\n delivery_session.add_store_bill_list(store_bill_id_list)\r\n return redirect(\r\n request.form.get(\"url\") or url_for('delivery.delivery_session',\r\n id_=delivery_session_id))\r\n else:\r\n customers = apis.delivery.get_store_bill_customer_list()\r\n d = dict(titlename=u'选择仓单', customer_list=customers)\r\n if delivery_session_id:\r\n d[\"delivery_session_id\"] = delivery_session_id\r\n return d\r\n\r\n\r\n@delivery_page.route(\"/consignment_preview/<int:id_>\", methods=[\"GET\"])\r\[email protected](\"/delivery/consignment-preview.html\")\r\[email protected]_bar_set\r\ndef consignment_preview(id_):\r\n from flask.ext.principal import Permission\r\n\r\n Permission.union(CargoClerkPermission, AccountantPermission).test()\r\n\r\n import lite_mms.apis as apis\r\n\r\n cons = apis.delivery.get_consignment(id_)\r\n if not cons:\r\n abort(404)\r\n else:\r\n per_page = apis.config.get(\"print_count_per_page\", 5.0, type=float)\r\n import math\r\n\r\n pages = int(math.ceil(len(cons.product_list) / per_page))\r\n return dict(plate=cons.plate, consignment=cons, titlename=u'发货单详情',\r\n pages=pages, per_page=per_page)\r\n" }, { "alpha_fraction": 0.6287878751754761, "alphanum_fraction": 0.631313145160675, "avg_line_length": 27.35714340209961, "blob_id": "417edb0b72edbfdbde36f080db85cdbd0f4ff930", "content_id": "2efb0a295cc95ef25e4b1cbb67485ffa6b923c4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 396, "license_type": "no_license", "max_line_length": 69, "num_lines": 14, "path": "/lite_mms/apis/config.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom lite_mms import models\n\n\ndef get(name, default=None, type=None):\n try:\n rv = models.Config.query.filter(\n models.Config.property_name == name).one().property_value\n if type is not None:\n rv = type(rv)\n except (KeyError, ValueError, NoResultFound):\n rv = default\n return rv" }, { "alpha_fraction": 0.6532905101776123, "alphanum_fraction": 0.6966292262077332, "avg_line_length": 14.574999809265137, "blob_id": "d48691822eae450746483bdb9f67c7f01b33d3d7", "content_id": "f0e168db04d7bf212a2c17c5e78ed4960d71fc5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 623, "license_type": "no_license", "max_line_length": 147, "num_lines": 40, "path": "/alembic/versions/2dda2c7c7e83_add_pwc_id.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"add previous_work_command_id column\r\r\r\rRevision ID: 2dda2c7c7e83\r\rRevises: 430e5c7bc3aa\r\rCreate Date: 2013-07-23 17:07:43.708000\r\r\r\r\"\"\"\r\r\r\r# revision identifiers, used by Alembic.\r\rrevision = '2dda2c7c7e83'\r\rdown_revision = 'e8e10d94c8e'\r\r\r\rfrom alembic import op\r\rimport sqlalchemy as sa\r\r\r\r\r\rdef upgrade():\r op.add_column(\"TB_WORK_COMMAND\", sa.Column(\"previous_work_command_id\", sa.Integer, sa.ForeignKey(\"TB_WORK_COMMAND.id\", name=\"fk_previous_wc\")))\r\r\r\rdef downgrade():\r op.drop_constraint(\"fk_previous_wc\", \"TB_WORK_COMMAND\", type_=\"foreignkey\")\r op.drop_column(\"TB_WORK_COMMAND\", \"previous_work_command_id\")\r" }, { "alpha_fraction": 0.6127272844314575, "alphanum_fraction": 0.7018181681632996, "avg_line_length": 13.102563858032227, "blob_id": "680fe28d0e1874a52e3fe1afe6f9e009ff39da3f", "content_id": "d56c65a8478e7dc05fac9794df718bdc6ca7a807", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 550, "license_type": "no_license", "max_line_length": 100, "num_lines": 39, "path": "/alembic/versions/56765d423498_add_column_status_to.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"add column 'status' to delivery table\r\r\r\rRevision ID: 56765d423498\r\rRevises: 35979bf471d6\r\rCreate Date: 2013-05-21 09:27:20.960000\r\r\r\r\"\"\"\r\r\r\r# revision identifiers, used by Alembic.\r\rrevision = '56765d423498'\r\rdown_revision = '35979bf471d6'\r\r\r\rfrom alembic import op\r\rimport sqlalchemy as sa\r\r\r\r\r\rdef upgrade():\r op.add_column(\"TB_DELIVERY_SESSION\", sa.Column(\"status\", sa.Integer, default=1, nullable=False))\r op.execute(\"UPDATE TB_DELIVERY_SESSION SET STATUS = 3\")\r\rdef downgrade():\r\r op.drop_column(\"TB_DELIVERY_SESSION\", \"status\")\r" }, { "alpha_fraction": 0.5949612259864807, "alphanum_fraction": 0.645348846912384, "avg_line_length": 19.639999389648438, "blob_id": "b141131774c529b6875806187a56e96b88987ba8", "content_id": "330197f0f3f9df9d70be3f57183abafa6455cb39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 530, "license_type": "no_license", "max_line_length": 75, "num_lines": 25, "path": "/alembic/versions/d9c0f19bdf5_add_completed_time_t.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"add completed_time to work_command\n\nRevision ID: d9c0f19bdf5\nRevises: d9c0f19bdf4\nCreate Date: 2013-03-31 11:31:57.969339\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'd9c0f19bdf5'\ndown_revision = 'd9c0f19bdf4'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.add_column(\"TB_WORK_COMMAND\", \n sa.Column(\"completed_time\", sa.DateTime, doc=u\"生产完毕的时间\"),\n )\n\n\ndef downgrade():\n op.drop_column(\"TB_WORK_COMMAND\", \"completed_time\")\n" }, { "alpha_fraction": 0.617782473564148, "alphanum_fraction": 0.6223875284194946, "avg_line_length": 36.643836975097656, "blob_id": "e0d85bdc75d9e7bd7df351affa316feeff32f03b", "content_id": "b71390aca7eb6f4368060aed2cdc9a4f185fdc4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2921, "license_type": "no_license", "max_line_length": 109, "num_lines": 73, "path": "/lite_mms/portal/auth/views.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\nfrom flask import (request, render_template, redirect, url_for, current_app,\r\n session, session)\r\nfrom flask.ext.principal import (Principal, Identity, AnonymousIdentity,\r\n identity_changed)\r\nfrom flask.ext.login import current_user\r\nfrom lite_mms.portal.auth import auth\r\nfrom flask.ext.principal import identity_changed, Identity, AnonymousIdentity\r\nfrom lite_mms.utilities import _\r\nfrom lite_mms.utilities.decorators import after_this_request\r\nfrom wtforms import PasswordField, TextField, Form, HiddenField\r\nfrom flask.ext.login import login_user, logout_user, login_required, \\\r\n current_user\r\nfrom lite_mms.exceptions import AuthenticateFailure\r\n\r\n\r\[email protected](\"/login\", methods=[\"GET\", \"POST\"])\r\ndef login():\r\n if request.method == \"GET\":\r\n if current_user.is_anonymous:\r\n return render_template(\"auth/login.html\", titlename=u'登录')\r\n return redirect(\"/\")\r\n else:\r\n class LoginForm(Form):\r\n username = TextField()\r\n password = PasswordField()\r\n next_url = HiddenField()\r\n\r\n form = LoginForm(request.form)\r\n if form.validate():\r\n username = form.username.data\r\n password = form.password.data\r\n try:\r\n import lite_mms.apis as apis\r\n\r\n user = apis.auth.authenticate(username, password)\r\n except AuthenticateFailure:\r\n return render_template(\"auth/login.html\", error=_(u\"用户名或者密码错误\"), titlename=u\"请登录\"), 403\r\n if not user.enabled:\r\n return render_template(\"auth/login.html\", error=_(u\"该账户已禁用, 请使用其它账户\"), titlename=u\"请登录\"), 403\r\n if not login_user(user):\r\n return render_template(\"auth/login.html\", error=_(u\"登陆失败\"), titlename=u\"请登录\"), 403\r\n\r\n identity_changed.send(current_app._get_current_object(), identity=Identity(user.id))\r\n return redirect(form.next_url.data or \"/\")\r\n else:\r\n return render_template(\"auth/login.html\", error=_(u\"请输入用户名及密码\"), titlename=u\"请登录\"), 403\r\n\r\[email protected](\"/logout\")\r\n@login_required\r\ndef logout():\r\n try:\r\n logout_user()\r\n except Exception: # in case sesson expire\r\n pass\r\n for key in ('identity.name', 'identity.auth_type'):\r\n session.pop(key, None)\r\n\r\n identity_changed.send(current_app._get_current_object(),\r\n identity=AnonymousIdentity())\r\n\r\n next_url = request.args.get(\"next\", \"/\")\r\n return redirect(next_url)\r\n\r\[email protected](\"/switch-group/<int:id_>\")\r\ndef switch_group(id_):\r\n # let it happen at once\r\n session['current_group_id'] = id_\r\n @after_this_request\r\n def set_group_id(response):\r\n response.set_cookie('current_group_id', str(id_))\r\n return response\r\n return redirect(\"/\")\r\n\r\n" }, { "alpha_fraction": 0.6036092042922974, "alphanum_fraction": 0.6048537492752075, "avg_line_length": 31.795917510986328, "blob_id": "968b30f4185425fa5f24145fc0c72cb2023c5110", "content_id": "4f7553c0d0b31cfdd4af189307f2256e9d0dcc4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1639, "license_type": "no_license", "max_line_length": 133, "num_lines": 49, "path": "/lite_mms/portal/timeline/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom datetime import datetime, timedelta\nfrom flask import Blueprint, request\n\ntime_line_page = Blueprint(\"timeline\", __name__, static_folder=\"static\",\n template_folder=\"templates\")\n\nfrom lite_mms.portal.timeline import views\nfrom lite_mms.basemain import data_browser, nav_bar\n\nfrom nav_bar import NavBar\n\n\ndef get_sub_nav_bar():\n sub_nav_bar = NavBar()\n\n def _register_obj_cls(id_, title):\n kwargs = dict(request.args)\n if id_:\n kwargs[\"obj_class\"] = id_\n else:\n try:\n del kwargs[\"obj_class\"]\n except KeyError:\n pass\n sub_nav_bar.register(lambda: views.time_line_model_view.url_for_list(**kwargs), title,\n enabler=lambda: views.obj_cls_fltr.real_value == str(id_) if id_ else not views.obj_cls_fltr.real_value)\n\n _register_obj_cls(None, u\"所有\")\n _register_obj_cls(views.ObjClsFilter.UNLOAD_SESSION, u\"卸货会话\")\n _register_obj_cls(views.ObjClsFilter.GOODS_RECEIPT, u\"收货单\")\n _register_obj_cls(views.ObjClsFilter.ORDER, u\"订单\")\n _register_obj_cls(views.ObjClsFilter.WORK_COMMAND, u\"工单\")\n return sub_nav_bar\n\n\ndef get_extra_params():\n return {\n \"list_view\": {\n \"nav_bar\": nav_bar,\n \"sub_nav_bar\": get_sub_nav_bar(),\n \"titlename\": u\"时间线\",\n \"today\": datetime.today().date(),\n \"yesterday\": datetime.today().date() - timedelta(days=1)\n },\n }\n\n\ndata_browser.register_model_view(views.time_line_model_view, time_line_page, extra_params=get_extra_params)\n" }, { "alpha_fraction": 0.6426056623458862, "alphanum_fraction": 0.6707746386528015, "avg_line_length": 19.11111068725586, "blob_id": "b6df3ba47b13e6048585c12de2e801a2b0ba68b5", "content_id": "61681bd5bf61aa9750343e3c6312568631747ec3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 600, "license_type": "no_license", "max_line_length": 46, "num_lines": 27, "path": "/lite_mms/constants/default.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\nfrom lite_mms.utilities import _\r\n\r\n\r\nSTANDARD_RECEIPT_TEMPLATE_ID = 1\r\nEXTRA_RECEIPT_TEMPLATE_ID = 2\r\nDEFAULT_PRODUCT_TYPE_NAME = _(u\"默认加工件\")\r\nDEFAULT_PRODUCT_NAME = _(u\"默认加工件\")\r\nDEFAULT_TECH_REQ = _(u\"默认\")\r\n\r\nITEMS_PER_PAGE = 15\r\nUNLOAD_SESSION_PER_PAGE = 15\r\nSTORE_BILL_PER_PAGE = 15\r\nDELIVERY_SESSION_PER_PAGE = 15\r\nORDER_PER_PAGE = 15\r\n\r\n# order types\r\n\r\nSTANDARD_ORDER_TYPE = 1\r\nEXTRA_ORDER_TYPE = 2\r\n\r\nEXTRA_ORDER_TYPE_NAME = u\"计件\"\r\nSTANDARD_ORDER_TYPE_NAME = u\"计重\"\r\n\r\nADMIN_USER_ID = 1\r\n\r\nPRINT_COUNT_PER_PAGE = u\"print_count_per_page\"" }, { "alpha_fraction": 0.5973984003067017, "alphanum_fraction": 0.5990244150161743, "avg_line_length": 34.17647171020508, "blob_id": "f0e5cfd0efc053fc680aebd1bd71940d20d46442", "content_id": "f4fadbd03684ef074d8d2ec7d89e3260e79200f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3191, "license_type": "no_license", "max_line_length": 107, "num_lines": 85, "path": "/lite_mms/portal/delivery/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\n\r\nfrom flask import Blueprint, redirect, request, abort\r\nfrom flask.ext.login import login_required\r\nfrom lite_mms.utilities.decorators import templated\r\n\r\ndelivery_page = Blueprint(\"delivery\", __name__, static_folder=\"static\", template_folder=\"templates\")\r\n\r\nconsignment_page = Blueprint(\"consignment\", __name__, static_folder=\"static\", template_folder=\"templates\")\r\n\r\nfrom lite_mms.portal.delivery import views, ajax\r\n\r\nfrom lite_mms.basemain import data_browser, nav_bar\r\n\r\nextra_params = {\r\n \"list_view\": {\r\n \"nav_bar\": nav_bar,\r\n \"titlename\": u\"发货单列表\",\r\n },\r\n \"form_view\": {\r\n \"nav_bar\": nav_bar,\r\n \"titlename\": u\"编辑发货单\",\r\n }\r\n}\r\ndata_browser.register_model_view(views.consigment_model_view, consignment_page, extra_params)\r\n\r\nextra_params = {\r\n \"form_view\": {\r\n \"nav_bar\": nav_bar,\r\n \"titlename\": u\"编辑发货单项\",\r\n }\r\n}\r\ndata_browser.register_model_view(views.consigment_product_model_view, consignment_page, extra_params)\r\n\r\nfrom lite_mms.apis import delivery\r\n\r\nget_customer_list = delivery.get_store_bill_customer_list\r\n\r\ndata_browser.register_model_view(views.delivery_session_view, delivery_page,\r\n extra_params={\"list_view\": {\"nav_bar\": nav_bar, \"titlename\": u\"发货会话列表\"},\r\n \"create_view\": {\"nav_bar\": nav_bar, \"titlename\": u\"新建发货会话\",\r\n \"get_customer_list\": get_customer_list},\r\n \"form_view\": {\"nav_bar\": nav_bar, \"titlename\": u\"编辑发货会话\"}})\r\n\r\ndata_browser.register_model_view(views.delivery_task_view, delivery_page,\r\n extra_params={\"form_view\": {\"nav_bar\": nav_bar, \"titlename\": u\"编辑任务会话\"}})\r\n\r\n\r\n@consignment_page.route(\"/\")\r\ndef index():\r\n return redirect(views.consigment_model_view.url_for_list())\r\n\r\n\r\n@consignment_page.before_request\r\n@login_required\r\ndef _default():\r\n pass\r\n\r\n\r\n@consignment_page.route(\"/batch-print/\")\r\n@templated(\"delivery/batch-print-consignment.html\")\r\ndef batch_print_consignment():\r\n from lite_mms import apis\r\n\r\n delivery_session_id_list = request.args.getlist(\"delivery_session_id\", type=int)\r\n if not delivery_session_id_list:\r\n abort(404)\r\n error_message = \"\"\r\n consignment_list = []\r\n\r\n per_page = apis.config.get(\"print_count_per_page\", 5, type=int)\r\n for delivery_session in [apis.delivery.get_delivery_session(id_) for id_ in delivery_session_id_list]:\r\n\r\n for cn in delivery_session.consignment_list:\r\n if not cn.MSSQL_ID:\r\n try:\r\n cn.persist()\r\n except ValueError:\r\n error_message += u\"发货单%s,\" % cn.id\r\n\r\n consignment_list.append(cn)\r\n if error_message:\r\n error_message += u\"插入MSSQL失败,请手工插入\"\r\n return {\"consignment_list\": consignment_list, \"error_message\": error_message,\r\n \"per_page\": per_page, \"nav_bar\": nav_bar, \"url\": request.args.get(\"url\"), \"titlename\": u\"批量打印\"}\r\n" }, { "alpha_fraction": 0.5170660614967346, "alphanum_fraction": 0.5196078419685364, "avg_line_length": 33, "blob_id": "05d56823d222db488ec6163f33132ba997bc8971", "content_id": "8c9b368c8075a3122b4575717976cd9ef12672e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2806, "license_type": "no_license", "max_line_length": 93, "num_lines": 81, "path": "/lite_mms/tools/set_portal_as_service.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nBRIEF\n 将portal设置为系统服务,web server目前仅仅支持nginx。不要利用sudo来执行此\n 脚本\nSYNOPSIS\n python set_portal_as_service.py [options]\nOPTIONS\n -h \n show this help\n -e <work environment directory>\n the service will read the config file under this directory\n -p <port>\n --undo \n\"\"\"\nfrom getopt import getopt\nimport sys\nimport os\nimport subprocess\n\nif __name__ == \"__main__\":\n \n opts, _ = getopt(sys.argv[1:], \"he:p:\", \"undo\")\n\n undo = False\n for o, v in opts:\n if o == \"-e\":\n work_env_dir = v\n work_env_dir = os.path.abspath(work_env_dir)\n elif o == \"-p\":\n port = int(v)\n elif o == \"-h\":\n print __doc__\n exit(1)\n elif o == \"--undo\":\n undo = True\n else:\n print \"unknown option: \" + v\n print __doc__\n exit(1)\n\n if not undo:\n try:\n work_env_dir\n port\n except NameError:\n print __doc__\n exit(1)\n server_fpath = os.path.join(sys.prefix, \"share/lite-mms/lite-mms\")\n if not os.path.exists(server_fpath):\n print \"Error: \" + server_fpath + \" doesn't exist\"\n exit(1)\n\n # install as uwsgi app\n subprocess.call([\"sudo\", \"./add_uwsgi_app.sh\"])\n subprocess.call([\"sudo\", \"service\", \"uwsgi\", \"restart\", \"lite-mms\"])\n \n # add nginx site\n with open(server_fpath) as server_fd:\n s = server_fd.read()\n s = s.replace(\"${PORT}\", str(port))\n s = s.replace(\"${PYHOME}\", sys.prefix)\n s = s.replace(\"${PYENV}\", work_env_dir)\n import lite_mms\n s = s.replace(\"${STATIC_DIR}\", os.path.join(lite_mms.__path__[0], \"static\"))\n import tempfile\n tmp_fd, tmp_fname = tempfile.mkstemp()\n os.close(tmp_fd)\n with open(tmp_fname, \"w\") as tmp_fd:\n tmp_fd.write(s) \n subprocess.call([\"sudo\", \"mv\", tmp_fname, \"/etc/nginx/sites-available/lite-mms\"])\n subprocess.call([\"sudo\", \"ln\", \"-sf\", \"/etc/nginx/sites-available/lite-mms\",\n \"/etc/nginx/sites-enabled/lite-mms\"])\n subprocess.call([\"sudo\", \"service\", \"nginx\", \"restart\"])\n else:\n subprocess.call([\"sudo\", \"rm\", \"/etc/nginx/sites-available/lite-mms\"])\n subprocess.call([\"sudo\", \"rm\", \"/etc/nginx/sites-enabled/lite-mms\"])\n subprocess.call([\"sudo\", \"service\", \"nginx\", \"restart\"])\n subprocess.call([\"sudo\", \"rm\", \"/etc/uwsgi/apps-available/lite-mms.xml\"])\n subprocess.call([\"sudo\", \"rm\", \"/etc/uwsgi/apps-enabled/lite-mms.xml\"])\n subprocess.call([\"sudo\", \"service\", \"uwsgi\", \"stop\", \"lite-mms\"])\n" }, { "alpha_fraction": 0.6628041863441467, "alphanum_fraction": 0.6651216745376587, "avg_line_length": 30.962963104248047, "blob_id": "2eb29be8e00bf6ed4b6a09dd3078741ce74cd574", "content_id": "da108e601094af061fbf2b7dae3d7768eac6688a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 863, "license_type": "no_license", "max_line_length": 146, "num_lines": 27, "path": "/lite_mms/apis/plate.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n@author: Yangminghua\n@version: $\n\"\"\"\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom lite_mms import models\nfrom lite_mms.apis import ModelWrapper\n\ndef get_plate_list(status=None):\n def _get_condition(plate_q, status):\n if status == \"unloading\":\n model = models.UnloadSession\n elif status == \"delivering\":\n model = models.DeliverySession\n else:\n return plate_q\n return plate_q.join(model, model.plate == models.Plate.name).filter(\n model.finish_time == None)\n\n return [p.name for p in _get_condition(models.Plate.query, status).all()]\n\nclass PlateWrapper(ModelWrapper):\n\n @property\n def unloading(self):\n return models.UnloadSession.query.filter(models.UnloadSession.plate==self.name).filter(models.UnloadSession.finish_time==None).count() > 0\n" }, { "alpha_fraction": 0.5935607552528381, "alphanum_fraction": 0.6047179102897644, "avg_line_length": 31.752687454223633, "blob_id": "8fea2da4ef44511208139114373b56746eaeafc4", "content_id": "f001947b8963889e16f3d9b9f997d434a283d5bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3303, "license_type": "no_license", "max_line_length": 81, "num_lines": 93, "path": "/lite_mms/portal/delivery/ajax.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\nimport json\r\nfrom flask import request, render_template, abort, flash\r\nfrom socket import error\r\nfrom wtforms import Form, IntegerField, BooleanField, TextField\r\nfrom lite_mms.portal.delivery import delivery_page\r\nfrom lite_mms.utilities.decorators import ajax_call\r\nfrom lite_mms.utilities import _\r\n\r\n\r\n@delivery_page.route(\"/ajax/consignment-list\", methods=[\"GET\"])\r\n@ajax_call\r\ndef consignment_list():\r\n session_id = request.args.get(\"delivery_session_id\", type=int)\r\n if session_id is not None:\r\n import lite_mms.apis as apis\r\n\r\n consignments, totalcnt = apis.delivery.get_consignment_list(session_id)\r\n if not consignments:\r\n return _(u\"当前没有任何发货单\"), 404\r\n return json.dumps(\r\n [dict(id=c.id, customer=c.customer.name,\r\n consignment_id=c.consignment_id) for c in consignments])\r\n else:\r\n return _(u\"未选择发货会话\"), 403\r\n\r\n\r\n@delivery_page.route(\"/ajax/consignment\", methods=[\"POST\"])\r\n@ajax_call\r\ndef ajax_consignment():\r\n class _ConsignmentForm(Form):\r\n id = IntegerField(\"id\")\r\n\r\n form = _ConsignmentForm(request.form)\r\n consignment_id = form.id.data\r\n if consignment_id:\r\n import lite_mms.apis as apis\r\n cons = apis.delivery.get_consignment(consignment_id)\r\n if not cons:\r\n return _(u\"不存在该发货单%d\" % consignment_id), 404\r\n elif not cons.MSSQL_ID:\r\n try:\r\n cons.persist()\r\n except ValueError, error:\r\n return unicode(error.message), 403\r\n return _(u\"更新成功\")\r\n else:\r\n return _(u\"数据错误\"), 404\r\n\r\n\r\n@delivery_page.route(\"/ajax/customer-list\")\r\n@ajax_call\r\ndef customer_list():\r\n \"\"\"\r\n return the customers, params include:\r\n * delivery_session_id\r\n \"\"\"\r\n delivery_session_id = request.args.get(\"delivery_session_id\", type=int)\r\n customers = []\r\n if delivery_session_id is not None:\r\n import lite_mms.apis as apis\r\n\r\n delivery_session = apis.delivery.get_delivery_session(\r\n delivery_session_id)\r\n if not delivery_session.finish_time:\r\n return _(u\"发货会话尚未结束\"), 403\r\n if any(task.weight == 0 for task in delivery_session.delivery_task_list):\r\n return _(u\"请先对所有的发货任务进行称重\"), 403\r\n\r\n acked_customer_id_list = set([gr.customer_id for gr in\r\n delivery_session.consignment_list])\r\n customers = [c for c in delivery_session.customer_list if\r\n c.id not in acked_customer_id_list]\r\n if not customers:\r\n return _(u\"已经对所有的客户生成了发货单\"), 403\r\n\r\n return json.dumps([{\"id\": c.id, \"name\": c.name} for c in customers])\r\n\r\n@delivery_page.route(\"/ajax/delivery-task/<int:id_>\", methods=[\"POST\"])\r\n@ajax_call\r\ndef delivery_task(id_):\r\n from lite_mms import apis\r\n task = apis.delivery.get_delivery_task(id_)\r\n if not task:\r\n abort(404)\r\n if task.weight:\r\n return _(u\"已称重的发货任务不能删除\"), 403\r\n try:\r\n task.delete()\r\n flash(u\"删除成功\")\r\n return \"success\"\r\n except Exception, e:\r\n return unicode(e), 403" }, { "alpha_fraction": 0.5365448594093323, "alphanum_fraction": 0.5653377771377563, "avg_line_length": 36.425533294677734, "blob_id": "f441d7e83d4d3837f42f80d59c51ced2fe1e5257", "content_id": "e58f5f2eb615b7c96c88ecffaa9d405355c0130d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1806, "license_type": "no_license", "max_line_length": 77, "num_lines": 47, "path": "/alembic/versions/185ce9f63e22_move_deduction.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"move deduction\r\n\r\nRevision ID: 185ce9f63e22\r\nRevises: 2ca6fa63fb40\r\nCreate Date: 2013-01-24 10:13:04.855000\r\n\r\n\"\"\"\r\n\r\n# revision identifiers, used by Alembic.\r\nrevision = '185ce9f63e22'\r\ndown_revision = '2ca6fa63fb40'\r\n\r\nfrom alembic import op\r\nimport sqlalchemy as sa\r\n\r\n\r\ndef upgrade():\r\n op.create_table(\"TB_DEDUCTION\", sa.Column('id', sa.Integer),\r\n sa.Column('weight', sa.Integer),\r\n sa.Column('work_command_id', sa.Integer),\r\n sa.Column('actor_id', sa.Integer),\r\n sa.Column('team_id', sa.Integer, nullable=False),\r\n sa.Column('create_time', sa.DateTime),\r\n sa.Column('remark', sa.String(256)),\r\n sa.ForeignKeyConstraint(['work_command_id'],\r\n ['TB_WORK_COMMAND.id'], ),\r\n sa.ForeignKeyConstraint(['actor_id'], ['TB_USER.id'], ),\r\n sa.ForeignKeyConstraint(['team_id'], ['TB_TEAM.id'], ),\r\n sa.PrimaryKeyConstraint('id'))\r\n\r\n op.execute(\r\n \"INSERT INTO tb_deduction ( weight, work_command_id, team_id, \"\r\n \"actor_id, create_time ) SELECT deduction, tb_work_command.id, \"\r\n \"tb_work_command.team_id, tb_user.id, NOW() FROM tb_work_command, \"\r\n \"tb_user WHERE tb_work_command.deduction > 0 AND tb_user.username = \"\r\n \"'qi';commit;\")\r\n\r\n op.drop_column(\"TB_WORK_COMMAND\", \"deduction\")\r\n\r\n\r\ndef downgrade():\r\n op.add_column(\"TB_WORK_COMMAND\", sa.Column(\"deduction\", sa.Integer))\r\n op.execute(\r\n \"UPDATE TB_WORK_COMMAND SET TB_WORK_COMMAND.deduction = ( SELECT \"\r\n \"weight FROM TB_DEDUCTION WHERE TB_WORK_COMMAND.id = TB_DEDUCTION\"\r\n \".work_command_id); commit;\")\r\n op.drop_table(\"TB_DEDUCTION\")\r\n" }, { "alpha_fraction": 0.6044657230377197, "alphanum_fraction": 0.6108452677726746, "avg_line_length": 30.399999618530273, "blob_id": "e39d96f8fdd1f68acd1b9321cd9a688c3e83456a", "content_id": "3406aa2d90e6d7094296dc090569b7b6ce85762e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 651, "license_type": "no_license", "max_line_length": 117, "num_lines": 20, "path": "/lite_mms/portal/store/actions.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom flask.ext.databrowser.action import DirectAction\nfrom flask import redirect, url_for, request, json\n\n\nclass PreviewPrintAction(DirectAction):\n def op_upon_list(self, objs, model_view):\n if objs:\n for obj in objs:\n obj.printed = True\n return redirect(\n url_for(\"store_bill.store_bill_preview\", ids_=json.dumps([obj.id for obj in objs]), url=request.url))\n\n def test_enabled(self, model):\n if not model.harbor:\n return -2\n return 0\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"仓单%s没有存放点,请先修改\"}" }, { "alpha_fraction": 0.6754068732261658, "alphanum_fraction": 0.7115732431411743, "avg_line_length": 29.55555534362793, "blob_id": "973986057e65bfc16839f632ea1cc50da12e2fbe", "content_id": "e88fc4e05dd2d7d17ae38b97d3474eeb9a1f899f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1150, "license_type": "no_license", "max_line_length": 112, "num_lines": 36, "path": "/alembic/versions/2ca6fa63fb40_grant_export_consign.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\n\"\"\"grant export_consignment permission to account\n\nRevision ID: 2ca6fa63fb40\nRevises: 2f9253b0fa2d\nCreate Date: 2013-01-22 18:30:26.463733\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '2ca6fa63fb40'\ndown_revision = '2f9253b0fa2d'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n # 增加权限data.export_consignment\n from lite_mms.models import Permission\n t = Permission.__table__\n op.bulk_insert(t, [{\"name\": \"data.export_consignment\"}])\n # 将权限赋予组accountant\n from lite_mms.models import permission_and_group_table as t\n import lite_mms.constants as constants\n op.bulk_insert(t, [{\"permission_name\": \"data.export_consignment\", \"group_id\": constants.groups.ACCOUNTANT}])\n\ndef downgrade():\n # 将权限从组accountant中删除\n from lite_mms.models import permission_and_group_table as t\n op.execute(t.delete().where(t.c.permission_name==\"data.export_consignment\"))\n # 删除权限data.export_consignment\n from lite_mms.models import Permission\n t = Permission.__table__\n op.execute(t.delete().where(t.c.name==\"data.export_consignment\"))\n \n\n" }, { "alpha_fraction": 0.4437263309955597, "alphanum_fraction": 0.4688601791858673, "avg_line_length": 45.138553619384766, "blob_id": "63597f0e2f264b87c7f1d81b544ba31d7bd59ef6", "content_id": "68b642f04c99727280e727b83ae6cc7710cfad94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16046, "license_type": "no_license", "max_line_length": 81, "num_lines": 332, "path": "/lite_mms/tools/make_test_data.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n\"\"\"\n本脚本用于创建测试数据,是为了帮助进行随意测试。本脚本基于数据库的初始化脚本\n\"\"\"\n\nfrom hashlib import md5\nfrom datetime import datetime, date\nfrom lite_mms.constants import (groups, work_command as wc_const,\n quality_inspection, cargo as cargo_const,\n delivery as delivery_const)\nimport lite_mms.basemain\nimport lite_mms.constants as const\nfrom setuptools import Command\nfrom lite_mms.models import *\nfrom lite_mms.utilities import do_commit\nfrom lite_mms.database import db, init_db\n\n\nclass InitializeTestDB(Command):\n def initialize_options(self):\n \"\"\"init options\"\"\"\n pass\n\n def finalize_options(self):\n \"\"\"finalize options\"\"\"\n pass\n\n def run(self):\n from lite_mms.tools import build_db\n db.drop_all()\n init_db()\n build_db.build_db()\n\n # 创建产品类型以及产品\n product_type1 = do_commit(ProductType(name=u\"A\"))\n product_type2 = do_commit(ProductType(name=u\"B\"))\n product1 = do_commit(Product(name=u'A01', product_type=product_type1))\n product2 = do_commit(Product(name=u'A02', product_type=product_type1))\n product3 = do_commit(Product(name=u'A03', product_type=product_type1))\n product4 = do_commit(Product(name=u'B01', product_type=product_type2))\n\n # 创建用户\n cargo_clerk = Group.query.get(groups.CARGO_CLERK)\n department_leader = Group.query.get(groups.DEPARTMENT_LEADER)\n team_leader = Group.query.get(groups.TEAM_LEADER)\n quality_inspector = Group.query.get(groups.QUALITY_INSPECTOR)\n loader = Group.query.get(groups.LOADER)\n # 收发员\n cc = do_commit(User(username='cc', password=md5('cc').hexdigest(),\n groups=[cargo_clerk]))\n # 车间1主任\n d1_dl = do_commit(\n User(username='d1', password=md5('d1').hexdigest(),\n groups=[department_leader]))\n # 车间2主任\n d2_dl = do_commit(\n User(username='d2', password=md5('d2').hexdigest(),\n groups=[department_leader]))\n # 超级车间主任\n super_dl = do_commit(\n User(username='super_dl', password=md5('super_dl').hexdigest(),\n groups=[department_leader]))\n # 班组101班组长\n t101_tl = do_commit(\n User(username='t101', password=md5('t101').hexdigest(),\n groups=[team_leader]))\n # 质检员\n qi = do_commit(\n User(username='qi', password=md5('qi').hexdigest(),\n groups=[quality_inspector]))\n # 装卸工\n l = do_commit(User(username='l', password=md5('l').hexdigest(),\n groups=[loader]))\n\n # 创建车间和班组\n department1 = do_commit(Department(name=u\"车间1\",\n leader_list=[d1_dl, super_dl]))\n department2 = do_commit(Department(name=u\"车间2\",\n leader_list=[d2_dl, super_dl]))\n team1 = do_commit(Team(name=u\"班组101\", department=department1,\n leader_list=[t101_tl]))\n\n # 创建工序\n procedure1 = do_commit(Procedure(name=u\"工序1\",\n department_list=[department1,\n department2]))\n procedure2 = do_commit(Procedure(name=u\"工序2\",\n department_list=[department2]))\n\n # 初始化装卸点\n harbor1 = do_commit(Harbor(name=u\"装卸点1\", department=department1))\n harbor2 = do_commit(Harbor(name=u\"装卸点2\", department=department2))\n\n # 初始化车辆\n vehicle1 = do_commit(Plate(name=u\"浙A 00001\"))\n vehicle2 = do_commit(Plate(name=u\"浙A 00002\"))\n vehicle3 = do_commit(Plate(name=u\"浙A 00003\"))\n\n # 初始化客户\n customer1 = do_commit(Customer(u\"宁波机床场\", \"nbjcc\"))\n customer2 = do_commit(Customer(u\"宁力紧固件\", \"nljgj\"))\n customer3 = do_commit(Customer(u\"宁波造船场\", \"nbzcc\"))\n\n # 收货环节\n # - 车上有人, 有两个任务, 分别来自不同的客户, 并且都已经称重\n unload_session1 = do_commit(\n UnloadSession(plate_=vehicle1,\n gross_weight=10000,\n with_person=True,\n finish_time=datetime.now(),\n status=cargo_const.STATUS_CLOSED))\n default_product = Product.query.filter(\n Product.name == const.DEFAULT_PRODUCT_NAME).one()\n do_commit(UnloadTask(unload_session=unload_session1,\n harbor=harbor1,\n customer=customer1, creator=l,\n product=default_product,\n pic_path=\"0.png\",\n weight=1000))\n do_commit(UnloadTask(unload_session=unload_session1,\n harbor=harbor2,\n customer=customer2,\n creator=l, product=product2,\n pic_path=\"1.jpg\",\n weight=3000))\n # - 车上无人, 有三个任务,来自两个客户, 有一个尚未称重\n unload_session2 = do_commit(\n UnloadSession(plate_=vehicle2, gross_weight=10000,\n with_person=False,\n status=cargo_const.STATUS_WEIGHING))\n do_commit(UnloadTask(unload_session=unload_session2, harbor=harbor1,\n customer=customer2, creator=l, product=product2,\n pic_path=\"2.png\",\n weight=1000))\n do_commit(UnloadTask(unload_session=unload_session2,\n harbor=harbor2, customer=customer3, creator=l,\n product=product3, pic_path=\"3.png\",\n weight=4000))\n do_commit(UnloadTask(unload_session=unload_session2, harbor=harbor2,\n customer=customer3, creator=l,\n product=product4,\n pic_path=\"4.png\"))\n # - 车上无人,正在等待装货\n do_commit(UnloadSession(plate_=vehicle3, gross_weight=10000,\n with_person=False,\n status=cargo_const.STATUS_LOADING))\n\n # 生成收货会话和收货项, 注意这里故意不为某些客户生成收货单\n goods_receipt1 = do_commit(\n GoodsReceipt(customer1, unload_session1))\n do_commit(GoodsReceiptEntry(goods_receipt=goods_receipt1, weight=1000,\n product=product1, harbor=harbor1))\n do_commit(GoodsReceiptEntry(goods_receipt=goods_receipt1, weight=3000,\n product=product2, harbor=harbor2))\n goods_receipt2 = do_commit(\n GoodsReceipt(customer2, unload_session1))\n # 生成订单, 注意这里故意不为某些收货会话生成订单\n # - 生成一个已经下发的订单\n order1 = do_commit(\n Order(goods_receipt1, creator=cc, dispatched=True, refined=True))\n # - 生成一个尚未下发的订单\n do_commit(Order(goods_receipt2, creator=cc))\n # 生成子订单,注意这里故意不为某些订单生成子订单\n # - 生成计重类型的子订单, 还有50公斤没有分配出去\n sub_order1 = do_commit(\n SubOrder(product1, 300, harbor1, order1, 300, \"KG\",\n due_time=date.today(), default_harbor=harbor1,\n returned=True))\n do_commit(SubOrder(product2, 1000, harbor2, order1, 1000, \"KG\",\n due_time=date.today(), default_harbor=harbor2,\n returned=True))\n # - 生成计件类型的子订单,\n sub_order2 = do_commit(\n SubOrder(product=product3, weight=3000,\n harbor=harbor2,\n order=order1, quantity=10,\n unit=u'桶',\n order_type=const.EXTRA_ORDER_TYPE,\n due_time=date.today(), default_harbor=harbor2))\n\n # 生成工单\n # - DISPATCHING STATUS\n do_commit(WorkCommand(sub_order=sub_order1,\n org_weight=50,\n procedure=procedure1,\n tech_req=u\"工单1的技术要求\",\n urgent=False, org_cnt=50,\n pic_path=\"1.jpg\"))\n do_commit(WorkCommand(sub_order=sub_order2,\n org_weight=300,\n procedure=procedure1,\n tech_req=u'foo tech requirements',\n org_cnt=1))\n\n # - ASSIGNING STATUS\n do_commit(WorkCommand(sub_order=sub_order1,\n org_weight=50,\n procedure=procedure1,\n tech_req=u\"工单2的技术要求\",\n urgent=False, org_cnt=50,\n department=department1,\n status=wc_const.STATUS_ASSIGNING,\n pic_path=\"1.jpg\"))\n do_commit(WorkCommand(sub_order=sub_order2,\n org_weight=300,\n procedure=procedure1,\n tech_req=u\"foo tech requirements\",\n urgent=False,\n org_cnt=1,\n department=department1,\n status=wc_const.STATUS_ASSIGNING,\n pic_path=\"1.jpg\"))\n # - ENDING STATUS\n do_commit(WorkCommand(sub_order=sub_order1,\n org_weight=50,\n procedure=procedure2,\n tech_req=u\"工单3的技术要求\",\n urgent=False, org_cnt=100,\n pic_path=\"1.jpg\",\n status=wc_const.STATUS_ENDING,\n department=department1,\n team=team1))\n do_commit(WorkCommand(sub_order=sub_order2,\n org_weight=300,\n procedure=procedure2,\n tech_req=u\"foo tech requirements\",\n urgent=False,\n org_cnt=1,\n pic_path=\"1.jpg\",\n status=wc_const.STATUS_ENDING,\n department=department1,\n team=team1))\n # - QUALITY INSPECTING STATUS\n work_command4 = WorkCommand(sub_order=sub_order1,\n org_weight=50,\n procedure=procedure2,\n tech_req=u\"工单4的技术要求\",\n urgent=False, org_cnt=50,\n pic_path=\"1.jpg\",\n status=wc_const.STATUS_QUALITY_INSPECTING,\n department=department1,\n team=team1,\n processed_weight=50)\n work_command5 = WorkCommand(sub_order=sub_order2,\n org_weight=300,\n procedure=procedure2,\n tech_req=u\"foo tech requirements\",\n urgent=False,\n org_cnt=1,\n pic_path=\"1.jpg\",\n status=wc_const.STATUS_QUALITY_INSPECTING,\n department=department1,\n team=team1,\n processed_weight=300,\n processed_cnt=1)\n do_commit([work_command4, work_command5])\n\n # - FINISHED STATUS\n work_command6 = WorkCommand(sub_order=sub_order1,\n org_weight=50,\n processed_weight=50,\n procedure=procedure2,\n tech_req=u\"foo tech requirements\",\n urgent=False, org_cnt=50,\n processed_cnt=50,\n pic_path=\"1.jpg\",\n status=wc_const.STATUS_FINISHED,\n department=department1,\n team=team1)\n work_command6.completed_time = datetime.now()\n work_command7 = WorkCommand(sub_order=sub_order2,\n org_weight=600,\n org_cnt=2,\n processed_weight=600,\n processed_cnt=2,\n procedure=procedure2,\n tech_req=u\"foo tech requirements\",\n urgent=False,\n pic_path=\"1.jpg\",\n status=wc_const.STATUS_FINISHED,\n department=department1,\n team=team1)\n work_command7.completed_time = datetime.now()\n do_commit([work_command6, work_command7])\n\n qir1 = do_commit(QIReport(work_command6, 20, 20,\n quality_inspection.FINISHED, qi.id,\n pic_path='1.jpg'))\n do_commit(QIReport(work_command6, 10, 10,\n quality_inspection.NEXT_PROCEDURE, qi.id,\n pic_path='1.jpg'))\n do_commit(QIReport(work_command6, 10, 10,\n quality_inspection.REPAIR, qi.id,\n pic_path='1.jpg'))\n do_commit(QIReport(work_command6, 10, 10,\n quality_inspection.REPLATE, qi.id,\n pic_path='1.jpg'))\n\n qir3 = do_commit(QIReport(work_command7, 1, 300,\n quality_inspection.FINISHED, qi.id,\n pic_path='1.jpg'))\n do_commit(QIReport(work_command7, 1, 300,\n quality_inspection.REPLATE, qi.id,\n pic_path='1.jpg'))\n\n delivery_session = DeliverySession(plate=vehicle1.name,\n tare=2300,\n status=delivery_const.STATUS_CLOSED)\n do_commit(delivery_session)\n delivery_task = do_commit(DeliveryTask(delivery_session, cc.id))\n store_bill1 = StoreBill(qir1)\n store_bill1.delivery_task = delivery_task\n store_bill2 = StoreBill(qir3)\n store_bill2.delivery_task = delivery_task\n do_commit([store_bill1, store_bill2])\n\n consignment = Consignment(customer1, delivery_session, True)\n consignment.actor = cc\n consignment.notes = \"\".join(str(i) for i in xrange(100))\n consignment.MSSQL_ID = 1\n do_commit(consignment)\n cp = ConsignmentProduct(product1, delivery_task, consignment)\n cp.unit = u\"桶\"\n cp.weight = 100\n cp.returned_weight = 50\n do_commit(cp)\n\nif __name__ == \"__main__\":\n from distutils.dist import Distribution\n InitializeTestDB(Distribution()).run()\n" }, { "alpha_fraction": 0.6698606014251709, "alphanum_fraction": 0.6750870943069458, "avg_line_length": 28.384614944458008, "blob_id": "5ab9b4b128e202a56aab094de74900e182a96d1d", "content_id": "e6439a7db714657dbe2d2d49bfadf84fecd7c9cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1202, "license_type": "no_license", "max_line_length": 94, "num_lines": 39, "path": "/lite_mms/portal/import_data/views.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n@author: Yangminghua\n@version: $\n\"\"\"\nfrom flask import abort, url_for, json\nfrom socket import error\nfrom lite_mms.portal.import_data import import_data_page\nfrom lite_mms.utilities import decorators\n\n@import_data_page.route(\"/\")\[email protected](\"/data/index.html\")\[email protected]_bar_set\ndef index():\n return dict(titlename=u\"导入数据管理\")\n\n\n@import_data_page.route(\"/consignments\")\[email protected](\"result.html\")\[email protected]_bar_set\ndef consignments():\n from lite_mms.permissions.data import export_consignment\n\n decorators.permission_required(export_consignment, (\"POST\",))\n from lite_mms import apis\n\n try:\n persisting_consignments, totalcnt = apis.delivery.get_consignment_list(exporting=True)\n content = u\"读出%d条发货单信息,\" % len(persisting_consignments)\n count = 0\n for consignment in persisting_consignments:\n consignment.persist()\n count += 1\n content += u\"成功导出%d条发货单\" % count\n\n return dict(titlename=u\"导出成功\", content=content,\n back_url=url_for('.index'))\n except ValueError, e:\n abort(500, e)\n\n\n" }, { "alpha_fraction": 0.6100217700004578, "alphanum_fraction": 0.657952070236206, "avg_line_length": 18.863636016845703, "blob_id": "42c03d2d786f30362efc953baffb718c8b0e3dc6", "content_id": "cb4f9d6b183ff642eff5d77300e0e1fcdccbc7da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 459, "license_type": "no_license", "max_line_length": 71, "num_lines": 22, "path": "/alembic/versions/2c1c00ece93d_add_column.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"Add Column\r\n\r\nRevision ID: 2c1c00ece93d\r\nRevises: None\r\nCreate Date: 2013-01-21 16:29:16.970000\r\n\r\n\"\"\"\r\n\r\n# revision identifiers, used by Alembic.\r\nrevision = '2c1c00ece93d'\r\ndown_revision = None\r\n\r\nfrom alembic import op\r\nimport sqlalchemy as sa\r\nfrom sqlalchemy import Column, Integer, ForeignKey\r\n\r\ndef upgrade():\r\n op.add_column('TB_SUB_ORDER',\r\n Column('team_id', Integer, ForeignKey(\"TB_TEAM.id\")))\r\n\r\ndef downupgrade():\r\n pass\r\n" }, { "alpha_fraction": 0.6225218176841736, "alphanum_fraction": 0.630452036857605, "avg_line_length": 26.413043975830078, "blob_id": "78839079c179a98943a0372549bf2feb740dc6fe", "content_id": "0384fa2e457d80c1d7520c6e2f8bc12d0f7d5bb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1307, "license_type": "no_license", "max_line_length": 77, "num_lines": 46, "path": "/lite_mms/portal/store/ajax.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n@author: Yangminghua\n@version: $\n\"\"\"\nfrom flask import request\nfrom lite_mms.portal.store import store_bill_page\nfrom lite_mms.utilities.decorators import ajax_call\nimport json\nfrom lite_mms.utilities import _\n\n@store_bill_page.route(\"/ajax/store-bill\", methods=['PUT'])\n@ajax_call\ndef ajax_store_bill():\n \"\"\"\n return the customers, params include:\n * delivery_session_id\n \"\"\"\n store_bill_id = request.form[\"id\"]\n if store_bill_id is not None:\n from lite_mms import apis\n\n try:\n apis.delivery.update_store_bill(int(store_bill_id), printed=True)\n return \"\"\n except ValueError, e:\n return unicode(e), 403\n return u\"需要ID\", 403\n\n\n@store_bill_page.route(\"/ajax/customer-list\", methods=['GET'])\n@ajax_call\ndef customer_list():\n \"\"\"\n 返回一定时间段内,有仓单的客户列表\n \"\"\"\n time_span = request.args.get(\"time_span\", \"unlimited\")\n if time_span not in [\"unlimited\", \"week\", \"month\"]:\n raise _(\"参数time_span非法\"), 403\n if time_span == \"unlimited\":\n time_span = \"\"\n from lite_mms import apis\n\n customers = apis.store.get_customer_list(time_span=time_span)\n return json.dumps(\n [dict(name=c.name, abbr=c.abbr, id=c.id) for c in customers])\n" }, { "alpha_fraction": 0.5480501651763916, "alphanum_fraction": 0.5529248118400574, "avg_line_length": 34.04878234863281, "blob_id": "533fd85c9819c67f9643488119ec8e4452288a51", "content_id": "87dd75335395bd2d7c7ae8729e35279d2aa734bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1440, "license_type": "no_license", "max_line_length": 112, "num_lines": 41, "path": "/lite_mms/apis/log.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom flask import request\nfrom lite_mms.apis import ModelWrapper\nfrom lite_mms import models\n\nmodel_map = {k: v for k, v in models.__dict__.items() if hasattr(v, \"_sa_class_manager\")}\n\n\nclass LogWrapper(ModelWrapper):\n @classmethod\n def get_log_list(cls, pk, model_name):\n return [LogWrapper(l) for l in\n models.Log.query.filter(models.Log.obj_pk == pk).filter(models.Log.obj_cls == model_name).all()]\n\n @property\n def obj_class(self):\n try:\n return model_map.get(self.obj_cls).__modelname__\n except (TypeError, AttributeError):\n return u\"未知\"\n\n @property\n def url_map(self):\n def _obj_wrap(str_, id_):\n from lite_mms.basemain import app\n from lite_mms.utilities import camel_case\n\n for endpoint, url in app.url_map._rules_by_endpoint.iteritems():\n if endpoint.endswith(camel_case(str_)):\n args = url[0].arguments\n if args:\n return url[0].build({enumerate(args).next()[1]: id_,\n \"url\": request.url})[1]\n else:\n return url[0].build({\"id\": id_, \"url\": request.url})[1]\n\n return self.obj_pk, _obj_wrap(self.obj_cls, self.obj_pk) if self.obj_cls else \"\"\n\n @property\n def create_date(self):\n return self.create_time.date()" }, { "alpha_fraction": 0.5613793134689331, "alphanum_fraction": 0.5627586245536804, "avg_line_length": 31.954545974731445, "blob_id": "6a1a6f4cc1455817840ceec587f2f21823cca5db", "content_id": "d71466c6a6e3a498272d3c55ac9c3a8d12e18097", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1450, "license_type": "no_license", "max_line_length": 78, "num_lines": 44, "path": "/lite_mms/log/handler.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom datetime import datetime\nimport logging\nfrom lite_mms.models import Log\nfrom lite_mms.utilities import do_commit\nfrom lite_mms.apis import ModelWrapper\n\n\nclass DBHandler(logging.Handler):\n \"\"\"\n Handler for logging message to the database table \"log\"\n \"\"\"\n\n def emit(self, record):\n log = Log()\n obj = getattr(record, \"obj\", None)\n if obj:\n log.obj = unicode(obj)\n obj_cls = getattr(record, \"obj_cls\", None)\n if obj_cls:\n log.obj_cls = obj_cls\n else:\n if obj:\n if isinstance(obj, ModelWrapper):\n log.obj_cls = obj.model.__class__.__name__\n else:\n log.obj_cls = obj.__class__.__name__\n obj_pk = getattr(record, \"obj_pk\", None)\n if obj_pk:\n log.obj_pk = obj_pk\n log.actor = getattr(record, \"actor\", None)\n log.action = getattr(record, \"action\", \"\")\n log.create_time = datetime.now()\n log.message = record.msg[:Log.message.property.columns[0].type.length]\n #log.name = record.name\n #log.level = record.levelname\n #log.module = record.module\n #log.func_name = record.funcName\n #log.line_no = record.lineno\n #log.thread = record.thread\n #log.thread_name = record.threadName\n #log.process = record.process\n #log.args = str(record.args)\n do_commit(log)\n" }, { "alpha_fraction": 0.6489441990852356, "alphanum_fraction": 0.6496983170509338, "avg_line_length": 27.5053768157959, "blob_id": "16c6294476d2aaad97f9bc6b91a7cd4a2074e6d1", "content_id": "c7c9ce7ceec4d965a9953bd0a7806ab05bbd01c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2672, "license_type": "no_license", "max_line_length": 115, "num_lines": 93, "path": "/lite_mms/portal/delivery/fsm.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom lite_sm import StateMachine, RuleSpecState, State, InvalidAction\nfrom lite_mms.basemain import timeline_logger\nfrom lite_mms.constants import delivery\nfrom lite_mms.permissions import CargoClerkPermission\nfrom lite_mms.utilities.decorators import committed\n\n\nclass DeliverySessionFSM(StateMachine):\n def reset_obj(self, obj):\n if obj.status == delivery.STATUS_LOADING:\n self.set_current_state(state_loading)\n elif obj.status == delivery.STATUS_WEIGHING:\n self.set_current_state(state_weighing)\n elif obj.status == delivery.STATUS_CLOSED:\n self.set_current_state(state_closed)\n self.obj = obj\n\n def do_log(self, action, actor):\n msg = \"\"\n self.logger.info(msg, extra={\"obj\": self.obj.model, \"actor\": actor, \"action\": delivery.desc_action(action),\n \"obj_pk\": self.obj.id})\n\n\nfsm = DeliverySessionFSM(logger=timeline_logger)\n\n\nclass StateLoading(RuleSpecState):\n status = delivery.STATUS_LOADING\n\n def __unicode__(self):\n return u\"正在装货\"\n\n @committed\n def side_effect(self, **kwargs):\n self.obj.status = delivery.STATUS_LOADING\n self.obj.finish_time = None\n return self.obj.model\n\n\nstate_loading = StateLoading(fsm, {\n delivery.ACT_LOAD: (delivery.STATUS_WEIGHING, None),\n delivery.ACT_CLOSE: (delivery.STATUS_CLOSED, None)\n})\n\n\nclass StateWeighing(State):\n status = delivery.STATUS_WEIGHING\n\n def __unicode__(self):\n return u\"等待称重\"\n\n @committed\n def side_effect(self, **kwargs):\n self.obj.status = delivery.STATUS_WEIGHING\n return self.obj.model\n\n def next(self, action):\n CargoClerkPermission.test()\n if action == delivery.ACT_WEIGHT:\n if self.obj.delivery_task_list[-1].is_last:\n return state_closed\n return state_loading\n else:\n raise InvalidAction(fsm.invalid_info(action, self))\n\n\nstate_weighing = StateWeighing(fsm)\n\n\nclass StateClosed(RuleSpecState):\n status = delivery.STATUS_CLOSED\n\n def __unicode__(self):\n return u\"关闭\"\n\n @committed\n def side_effect(self, **kwargs):\n CargoClerkPermission.test()\n for sb in self.obj.store_bill_list:\n if sb.delivery_session and sb.delivery_task is None:\n sb.delivery_session = None\n\n self.obj.status = delivery.STATUS_CLOSED\n from datetime import datetime\n\n self.obj.finish_time = datetime.now()\n return self.obj.model\n\n\nstate_closed = StateClosed(fsm, {\n delivery.ACT_OPEN: (delivery.STATUS_LOADING, CargoClerkPermission)\n})\n\n" }, { "alpha_fraction": 0.6639072895050049, "alphanum_fraction": 0.7119205594062805, "avg_line_length": 23.15999984741211, "blob_id": "2205a8488393fb16d59e119452ae2a9b32e2e90e", "content_id": "a7cc5d7aa0770c2d9ddc7fb4b13a72b04ecee83f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 604, "license_type": "no_license", "max_line_length": 93, "num_lines": 25, "path": "/alembic/versions/38c3b59444b6_alert_unloadsession_.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"alert unloadsession add with_person\n\nRevision ID: 38c3b59444b6\nRevises: 185ce9f63e22\nCreate Date: 2013-01-28 14:39:58.618228\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '38c3b59444b6'\ndown_revision = '185ce9f63e22'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.add_column(\"TB_UNLOAD_SESSION\", sa.Column(\"with_person\", sa.Boolean, default=False))\n op.add_column(\"TB_DELIVERY_SESSION\", sa.Column(\"with_person\", sa.Boolean, default=False))\n\n\n\ndef downgrade():\n op.drop_column(\"TB_UNLOAD_SESSION\", \"with_person\")\n op.drop_column(\"TB_DELIVERY_SESSION\", \"with_person\")\n" }, { "alpha_fraction": 0.6123260259628296, "alphanum_fraction": 0.6858847141265869, "avg_line_length": 11.268292427062988, "blob_id": "a9134eb9ba1953b5fd9d35f5748b89eac500b384", "content_id": "368b1e10076a0a18e4c15fd28aa36ac5c592b5fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 503, "license_type": "no_license", "max_line_length": 79, "num_lines": 41, "path": "/alembic/versions/335ff300f22b_add_enabled_column.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"add enabled column to 'TB_PRODUCT'\r\r\r\rRevision ID: 335ff300f22b\r\rRevises: 1e9ee2636f8a\r\rCreate Date: 2013-04-25 16:09:30.092000\r\r\r\r\"\"\"\r\r\r\r# revision identifiers, used by Alembic.\r\rrevision = '335ff300f22b'\r\rdown_revision = '1e9ee2636f8a'\r\r\r\rfrom alembic import op\r\rimport sqlalchemy as sa\r\r\r\r\r\rdef upgrade():\r\r op.add_column(\"TB_PRODUCT\", sa.Column(\"enabled\", sa.Boolean, default=True))\r\r op.execute(\"UPDATE TB_PRODUCT SET ENABLED=1\")\r\rdef downgrade():\r\r op.drop_column(\"TB_PRODUCT\", \"enabled\")\r" }, { "alpha_fraction": 0.6817180514335632, "alphanum_fraction": 0.6817180514335632, "avg_line_length": 47.55555725097656, "blob_id": "ce30dccde818f7c5b375d7166fa09a386c0e7a4a", "content_id": "c9103c05b93fb654d25ca523393b5f06d208b9cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 908, "license_type": "no_license", "max_line_length": 271, "num_lines": 18, "path": "/docs/source/constants/work_command.rst", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\r\n\r\nstatus of work command\r\n======================\r\n\r\n.. automodule:: lite_mms.constants.work_command\r\n :members: STATUS_DISPATCHING, STATUS_ASSIGNING, STATUS_LOCKED, STATUS_ENDING, STATUS_AFFIRMING_END, STATUS_AFFIRMING_CARRY_FORWARD, STATUS_QUALITY_INSPECTING, STATUS_REFUSED, STATUS_FINISHED, STATUS_AFTER_CARRY_FORWARD\r\n\r\n\r\nhandle type of work command\r\n===========================\r\n\r\n.. automodule:: lite_mms.constants.work_command\r\n :members: FIRST_PROCESS_TYPE, RETURN_PLATE_TYPE, RETURN_REPAIRE_TYPE\r\n \r\naction upon work command\r\n========================\r\n\r\n.. automodule:: lite_mms.constants.work_command\r\n :members: ACT_CHECK, ACT_DISPATCH, ACT_ASSIGN, ACT_ADD_WEIGHT, ACT_REQUEST_END, ACT_REQUEST_CARRY_FORWARD, ACT_AFFIRM_END, ACT_AFFIRM_CARRY_FORWARD, ACT_REFUSE, ACT_RETRIEVAL, ACT_AFFIRM_RETRIEVAL, ACT_QI, ACT_REFUSE_RETRIEVAL, ACT_RETRIVE_QI, ACT_QUICK_CARRY_FORWARD\r\n\r\n \r\n \r\n" }, { "alpha_fraction": 0.5215641260147095, "alphanum_fraction": 0.5250144004821777, "avg_line_length": 39.30232620239258, "blob_id": "b82791a7002a2fc656083192dc380f73e610c7b6", "content_id": "2eea413f9d5c0dc2c5bef432fd34aeb0927ca7c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1739, "license_type": "no_license", "max_line_length": 104, "num_lines": 43, "path": "/lite_mms/tools/set_blt_as_service.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n\"\"\"\n\nimport os\nimport sys\nimport subprocess\nimport tempfile\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 1:\n print \"usage: python set_blt_as_service.py [work_env_dir|--undo]\"\n exit(-1) \n\n if sys.argv[1] == \"--undo\":\n subprocess.call([\"sudo\", \"rm\", \"/etc/init/lite-mms-blt\"])\n subprocess.call([\"sudo\", \"rm\", \"/etc/init.d/lite-mms-blt\"])\n subprocess.call([\"sudo\", \"service\", \"lite-mms-blt\", \"restart\"])\n else:\n work_env_dir = os.path.abspath(sys.argv[1])\n init_script_fpath = os.path.join(sys.prefix, \"share/lite-mms/lite-mms-blt\")\n\n if not os.path.exists(init_script_fpath):\n print \"Error: \" + init_script_fpath + \" doesn't exist\"\n exit(-1)\n\n with file(init_script_fpath) as init_script_fd:\n s = init_script_fd.read()\n if os.environ.has_key(\"VIRTUAL_ENV\"):\n s = s.replace(\"${EXEC_VIRTUAL_ENV_ACTIVATE}\", \n \". \" + os.path.join(os.environ[\"VIRTUAL_ENV\"] + \"/bin/activate\"))\n else:\n s = s.replace(\"${EXEC_VIRTUAL_ENV_ACTIVATE}\", \"\")\n s = s.replace(\"${WORK_ENV_DIR}\", work_env_dir)\n tmp_fd, tmp_fname = tempfile.mkstemp()\n os.close(tmp_fd)\n with open(tmp_fname, \"w\") as f:\n f.write(s)\n subprocess.call([\"sudo\", \"cp\", tmp_fname, \"/etc/init/lite-mms-blt\"]) \n os.unlink(tmp_fname)\n subprocess.call([\"sudo\", \"ln\", \"-sf\", \"/etc/init/lite-mms-blt\", \"/etc/init.d/lite-mms-blt\"])\n subprocess.call([\"sudo\", \"chmod\", \"u+x\", \"/etc/init.d/lite-mms-blt\"])\n subprocess.call([\"sudo\", \"service\", \"lite-mms-blt\", \"restart\"])\n \n\n" }, { "alpha_fraction": 0.602150559425354, "alphanum_fraction": 0.6129032373428345, "avg_line_length": 24.363636016845703, "blob_id": "1c27c65884998fb5cb5d686babb4cac8ce863b2a", "content_id": "20ac249aefd0b2de0199b7a7a88b6b1e2ac85c5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 279, "license_type": "no_license", "max_line_length": 55, "num_lines": 11, "path": "/lite_mms/tools/create_codernity_db.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\nimport sys\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print 'Usage: create_codernity_db.py <db_path>'\n sys.exit(1)\n\n from CodernityDB.database import Database\n codernity_db = Database(sys.argv[1])\n codernity_db.create()\n" }, { "alpha_fraction": 0.5930232405662537, "alphanum_fraction": 0.6860465407371521, "avg_line_length": 18.4761905670166, "blob_id": "30d6ed1b5007ac15f509bf3fa66c3d2dc35f9ab8", "content_id": "437351c169ba6362e9718951b5a159097416ba4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "no_license", "max_line_length": 47, "num_lines": 21, "path": "/alembic/versions/2a4cf5743519_remove_the_printed_c.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"remove the printed column of TB_Consignment\r\n\r\nRevision ID: 2a4cf5743519\r\nRevises: 41614d172256\r\nCreate Date: 2013-02-26 10:28:22.937000\r\n\r\n\"\"\"\r\n\r\n# revision identifiers, used by Alembic.\r\nrevision = '2a4cf5743519'\r\ndown_revision = '41614d172256'\r\n\r\nfrom alembic import op\r\nimport sqlalchemy as sa\r\n\r\n\r\ndef upgrade():\r\n op.drop_column(\"TB_CONSIGNMENT\", \"PRINTED\")\r\n\r\ndef downgrade():\r\n op.add_column(\"TB_CONSIGNMENT\", \"PRINTED\")\r\n" }, { "alpha_fraction": 0.5167322754859924, "alphanum_fraction": 0.5259186625480652, "avg_line_length": 29.44329833984375, "blob_id": "6f6b08369e1e5d1a75ff546fc72774bbda7c4c5c", "content_id": "fe266d57dc5bf81f4466e4dd59c210c016881b0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3048, "license_type": "no_license", "max_line_length": 66, "num_lines": 97, "path": "/lite_mms/exceptions.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "import types\r\n\r\nclass AuthenticateFailure(Exception):\r\n code = 30001\r\n name = \"authenticate-failure\"\r\n\r\n def __init__(self, description=None):\r\n Exception.__init__(self, '%d %s' % (self.code, self.name))\r\n if description is not None:\r\n if isinstance(description, types.StringType):\r\n description = description.decode(\"utf-8\")\r\n self.description = description\r\n\r\n def __str__(self):\r\n return unicode(self).encode('utf-8')\r\n\r\n def __unicode__(self):\r\n if 'description' in self.__dict__:\r\n txt = self.description\r\n else:\r\n txt = self.name\r\n return u'%d: %s' % (self.code, txt)\r\n\r\n def __repr__(self):\r\n return '<%s \\'%s\\'>' % (self.__class__.__name__, self)\r\n\r\nclass PropertyError(Exception):\r\n code = 30003\r\n name = \"property-error\"\r\n\r\n def __init__(self, description=None):\r\n Exception.__init__(self, '%d %s' % (self.code, self.name))\r\n if description is not None:\r\n if isinstance(description, types.StringType):\r\n description = description.decode(\"utf-8\")\r\n self.description = description\r\n\r\n def __str__(self):\r\n return unicode(self).encode('utf-8')\r\n\r\n def __unicode__(self):\r\n if 'description' in self.__dict__:\r\n txt = self.description\r\n else:\r\n txt = self.name\r\n return u'%d: %s' % (self.code, txt)\r\n\r\n def __repr__(self):\r\n return '<%s \\'%s\\'>' % (self.__class__.__name__, self)\r\n\r\nclass InvalidAction(Exception):\r\n code = 30004\r\n name = \"invalid-action\"\r\n\r\n def __init__(self, description=None):\r\n Exception.__init__(self, '%d %s' % (self.code, self.name))\r\n if description is not None:\r\n if isinstance(description, types.StringType):\r\n description = description.decode(\"utf-8\")\r\n self.description = description\r\n\r\n def __str__(self):\r\n return unicode(self).encode('utf-8')\r\n\r\n def __unicode__(self):\r\n if 'description' in self.__dict__:\r\n txt = self.description\r\n else:\r\n txt = self.name\r\n return u'%d: %s' % (self.code, txt)\r\n\r\n def __repr__(self):\r\n return '<%s \\'%s\\'>' % (self.__class__.__name__, self)\r\n\r\nclass InvalidStatus(Exception):\r\n code = 30005\r\n name = \"invalid-status\"\r\n\r\n def __init__(self, description=None):\r\n Exception.__init__(self, '%d %s' % (self.code, self.name))\r\n if description is not None:\r\n if isinstance(description, types.StringType):\r\n description = description.decode(\"utf-8\")\r\n self.description = description\r\n\r\n def __str__(self):\r\n return unicode(self).encode('utf-8')\r\n\r\n def __unicode__(self):\r\n if 'description' in self.__dict__:\r\n txt = self.description\r\n else:\r\n txt = self.name\r\n return u'%d: %s' % (self.code, txt)\r\n\r\n def __repr__(self):\r\n return '<%s \\'%s\\'>' % (self.__class__.__name__, self)" }, { "alpha_fraction": 0.601307213306427, "alphanum_fraction": 0.6688452959060669, "avg_line_length": 9.904762268066406, "blob_id": "a2d8d5edfeaf074e8a9ccf6a173b877dcbd4f35c", "content_id": "6d82bc18a0666749d46ecab9b08bb8274f351920", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 459, "license_type": "no_license", "max_line_length": 66, "num_lines": 42, "path": "/alembic/versions/34726d8933e3_modify_sub_order_due.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"modify sub_order due_time's type\r\r\r\rRevision ID: 34726d8933e3\r\rRevises: d424258bb9c\r\rCreate Date: 2013-06-04 16:19:07.402000\r\r\r\r\"\"\"\r\r\r\r# revision identifiers, used by Alembic.\r\rrevision = '34726d8933e3'\r\rdown_revision = 'd424258bb9c'\r\r\r\rfrom alembic import op\r\rimport sqlalchemy as sa\r\r\r\r\r\rdef upgrade():\r\r\r op.alter_column(\"TB_SUB_ORDER\", \"due_time\", type_=sa.Date)\r\r\r\rdef downgrade():\r\r op.alter_column(\"TB_SUB_ORDER\", \"due_time\", type_=sa.DateTime)\r\r" }, { "alpha_fraction": 0.5817211866378784, "alphanum_fraction": 0.5819782614707947, "avg_line_length": 31.53232765197754, "blob_id": "74c57aace5e6418262ea57a422c2df50a4a9164b", "content_id": "ba1632b80d0e0509374cbb7a23c793eacafc3a37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15991, "license_type": "no_license", "max_line_length": 117, "num_lines": 464, "path": "/lite_mms/apis/cargo.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding:UTF-8 -*-\r\nimport sys\r\nfrom flask import url_for\r\nfrom flask.ext.babel import _\r\nfrom sqlalchemy import or_\r\nfrom sqlalchemy.orm.exc import NoResultFound\r\nfrom werkzeug.utils import cached_property\r\nfrom lite_mms import models, constants\r\nfrom lite_mms.apis import ModelWrapper\r\nfrom lite_mms.utilities import do_commit\r\n\r\n\r\ng_status_desc = {\r\n constants.cargo.STATUS_LOADING: u\"正在卸货\",\r\n constants.cargo.STATUS_WEIGHING: u\"等待称重\",\r\n constants.cargo.STATUS_CLOSED: u\"关闭\",\r\n constants.cargo.STATUS_DISMISSED: u\"取消\",\r\n}\r\n\r\n\r\nclass UnloadSessionWrapper(ModelWrapper):\r\n @property\r\n def deleteable(self):\r\n return not bool(self.task_list)\r\n\r\n @property\r\n def is_locked(self):\r\n return bool(\r\n self.task_list and any(not t.weight for t in self.task_list))\r\n\r\n @property\r\n def load_finish(self):\r\n return bool(self.finish_time)\r\n\r\n @property\r\n def finished(self):\r\n \"\"\"\r\n 已经关闭,并且所有的unload task都已经称重, 注意与closeable的区别\r\n \"\"\"\r\n return bool(\r\n self.finish_time and all(t.weight for t in self.task_list))\r\n\r\n @property\r\n def status_desc(self):\r\n return g_status_desc.get(self.status) or u\"未知\"\r\n\r\n @cached_property\r\n def customer_list(self):\r\n return list(set([task.customer for task in self.task_list]))\r\n\r\n @cached_property\r\n def customer_id_list(self):\r\n return [customer.id for customer in self.customer_list]\r\n\r\n @property\r\n def closeable(self):\r\n return not self.finish_time and all(ut.weight for ut in self.task_list)\r\n\r\n @property\r\n def closed(self):\r\n \"\"\"\r\n 已经关闭(不能再添加unload task)\r\n \"\"\"\r\n return bool(self.finish_time)\r\n\r\n @property\r\n def log_list(self):\r\n from lite_mms.apis.log import LogWrapper\r\n\r\n ret = LogWrapper.get_log_list(str(self.id), self.model.__class__.__name__)\r\n for task in self.task_list:\r\n ret.extend(task.log_list)\r\n return sorted(ret, lambda a, b: cmp(a.create_time, b.create_time))\r\n\r\n @property\r\n def with_person_des(self):\r\n return u'是' if self.with_person else u'否'\r\n\r\n def __repr__(self):\r\n s_create_time = self.create_time.strftime(\"%Y-%m-%d[%H:%M:%S]\")\r\n s_finish_time = self.finish_time.strftime(\"%Y-%m-%d[%H:%M:%S]\") \\\r\n if self.finish_time else \"-\"\r\n return \"<UnloadSession (%d) (%r) (%d) (%s) (%s)>\" % (self.id,\r\n self.plate,\r\n self.gross_weight,\r\n s_create_time,\r\n s_finish_time)\r\n\r\n def update(self, finish_time):\r\n \"\"\"\r\n update the unload session's scalar attribute persistently\r\n only finish_time could be updated\r\n :return: the updated unload session if succeed, otherwise None\r\n \"\"\"\r\n self.model.finish_time = finish_time\r\n do_commit(self.model)\r\n\r\n def gc_goods_receipts(self):\r\n \"\"\"\r\n delete the goods_receipt which has not entry converted from current\r\n unload_session's unload_task_list\r\n \"\"\"\r\n for gr in self.goods_receipt_list:\r\n if gr.customer.id not in self.customer_id_list:\r\n do_commit(gr.model, \"delete\")\r\n\r\n def clean_goods_receipts(self):\r\n \"\"\"\r\n Iterator the customers and create a goods_receipt.\r\n Then delete the unnecessary goods_receipts.\r\n \"\"\"\r\n for id_ in self.customer_id_list:\r\n create_or_update_goods_receipt(unload_session_id=self.id,\r\n customer_id=id_)\r\n\r\n self.gc_goods_receipts()\r\n\r\n @cached_property\r\n def goods_receipt_stale(self):\r\n return any(gr.stale for gr in self.goods_receipt_list)\r\n\r\n\r\nclass UnloadTaskWrapper(ModelWrapper):\r\n @property\r\n def pic_url(self):\r\n if self.pic_path:\r\n return url_for(\"serv_pic\", filename=self.pic_path)\r\n else:\r\n return \"\"\r\n\r\n @property\r\n def log_list(self):\r\n from lite_mms.apis.log import LogWrapper\r\n\r\n return LogWrapper.get_log_list(str(self.id), self.model.__class__.__name__)\r\n\r\n def update(self, **kwargs):\r\n \"\"\"\r\n update scalar attributes of unload task in database\r\n only **weight** and **product_id** allowed\r\n \"\"\"\r\n if kwargs.get(\"weight\"):\r\n self.model.weight = kwargs[\"weight\"]\r\n if kwargs.get(\"product_id\"):\r\n try:\r\n self.model.product = models.Product.query.filter(\r\n models.Product.id == kwargs[\"product_id\"]).one()\r\n except NoResultFound:\r\n raise ValueError(u\"无此产品%s\" % kwargs[\"product_id\"])\r\n if kwargs.get(\"customer\"):\r\n self.model.customer = kwargs[\"customer\"]\r\n do_commit(self.model)\r\n\r\n @property\r\n def last_weight(self):\r\n idx = self.unload_session.task_list.index(self)\r\n if idx <= 0:\r\n return self.unload_session.gross_weight\r\n else:\r\n last_task = self.unload_session.task_list[idx - 1]\r\n return last_task.last_weight - last_task.weight\r\n\r\n def __eq__(self, other):\r\n return isinstance(other, UnloadTaskWrapper) and other.id == self.id\r\n\r\n @cached_property\r\n def goods_receipt(self):\r\n for goods_receipt in self.unload_session.goods_receipt_list:\r\n if goods_receipt.customer.id == self.customer.id:\r\n return goods_receipt\r\n else:\r\n return None\r\n\r\n @property\r\n def url(self):\r\n if self.weight:\r\n return url_for(\"cargo.unload_task\", id_=self.id)\r\n else:\r\n return url_for(\"cargo.weigh_unload_task\", id_=self.id)\r\n\r\n def delete(self):\r\n us = self.unload_session\r\n do_commit(self.model, \"delete\")\r\n from lite_mms.portal.cargo.fsm import fsm\r\n fsm.reset_obj(us)\r\n from flask.ext.login import current_user\r\n from lite_mms.basemain import timeline_logger\r\n\r\n timeline_logger.info(u\"删除了卸货任务%d\" % self.id,\r\n extra={\"obj\": self.unload_session.model,\r\n \"obj_pk\": self.unload_session.id,\r\n \"action\": u\"删除卸货任务\",\r\n \"actor\": current_user})\r\n fsm.next(constants.cargo.ACT_WEIGHT, current_user)\r\n\r\n from lite_mms.apis import todo\r\n # delete\r\n todo.remove_todo(todo.WEIGH_UNLOAD_TASK, self.id)\r\n return True\r\n\r\n\r\nclass GoodsReceiptWrapper(ModelWrapper):\r\n def __repr__(self):\r\n return u\"<GoodsReceiptWrapper %d customer-%s>\" % (\r\n self.id, self.customer.name)\r\n\r\n @cached_property\r\n def unload_task_list(self):\r\n task_list = []\r\n for task in self.unload_session.task_list:\r\n if task.customer.id == self.customer.id:\r\n task_list.append(task)\r\n return task_list\r\n\r\n def update(self, **kwargs):\r\n for k, v in kwargs.items():\r\n if hasattr(self.model, k):\r\n setattr(self.model, k, v)\r\n do_commit(self.model)\r\n\r\n @property\r\n def log_list(self):\r\n from lite_mms.apis.log import LogWrapper\r\n\r\n ret = LogWrapper.get_log_list(str(self.id), self.model.__class__.__name__)\r\n for entry in self.goods_receipt_entries:\r\n ret.extend(LogWrapper.get_log_list(str(entry.id), \"GoodsReceiptEntry\"))\r\n return sorted(ret, lambda a, b: cmp(a.create_time, b.create_time))\r\n\r\n @property\r\n def stale(self):\r\n \"\"\"\r\n 若卸货会话的结束时间晚于收货单的创建时间(即卸货会话在创建收货单之后又打开了),并且的确修改了收货单对应的产品信息,\r\n 我们认为收货单是过时的\r\n \"\"\"\r\n if self.unload_session.finish_time and self.unload_session.finish_time > self.create_time:\r\n _entries = [(entry.product.id, entry.weight) for entry in\r\n self.goods_receipt_entries]\r\n _uts = [(ut.product.id, ut.weight) for ut in self.unload_task_list]\r\n return sorted(_entries) != sorted(_uts)\r\n return False\r\n\r\n def add_product_entries(self):\r\n for entry in self.goods_receipt_entries:\r\n do_commit(entry, \"delete\")\r\n for ut in self.unload_task_list:\r\n do_commit(\r\n models.GoodsReceiptEntry(product=ut.product, weight=ut.weight,\r\n goods_receipt=self.model,\r\n harbor=ut.harbor,\r\n pic_path=ut.pic_path))\r\n self.model.printed = False\r\n do_commit(self.model)\r\n\r\n def delete(self):\r\n do_commit(self.model, \"delete\")\r\n\r\n\r\nclass GoodsReceiptEntryWrapper(ModelWrapper):\r\n @property\r\n def pic_url(self):\r\n if self.pic_path:\r\n return url_for(\"serv_pic\", filename=self.pic_path)\r\n else:\r\n return \"\"\r\n\r\n\r\ndef get_unload_session_list(idx=0, cnt=sys.maxint, unfinished_only=False,\r\n keywords=None):\r\n \"\"\"\r\n get all the unloading sessions in certain range, ordered by create_time\r\n descentally\r\n :param idx: the beginning of the range\r\n :type idx: int\r\n :param cnt: the number of unload sessions to get\r\n :type cnt: int\r\n :return: the unloading sessions between idx and \"idx + cnt\" and the\r\n number of all unload sessions, when there's no sessions, the\r\n first part will be None\r\n :rtype: (iterable of UnloadSession|None, total_session_count)\r\n \"\"\"\r\n query = models.UnloadSession.query\r\n if unfinished_only:\r\n query = query.filter(models.UnloadSession.finish_time == None)\r\n if keywords:\r\n query = query.join(models.UnloadTask).join(models.Customer).filter(\r\n or_(models.UnloadSession.plate.like(\"%\" + keywords + \"%\"),\r\n models.Customer.name.like(\"%\" + keywords + \"%\")))\r\n total_cnt = query.count()\r\n query = query.order_by(\r\n models.UnloadSession.create_time.desc()).offset(idx).limit(cnt)\r\n\r\n return [UnloadSessionWrapper(us) for us in\r\n query.all()], total_cnt\r\n\r\n\r\ndef get_unload_session(session_id):\r\n \"\"\"\r\n get unload session from database of given id\r\n :param session_id:\r\n :return: unload session of given id if succeed or None\r\n \"\"\"\r\n if not session_id:\r\n return None\r\n try:\r\n return UnloadSessionWrapper(\r\n models.UnloadSession.query.filter(\r\n models.UnloadSession.id == session_id).one())\r\n except NoResultFound:\r\n return None\r\n\r\n\r\ndef new_unload_session(plate, gross_weight, with_person=False):\r\n \"\"\"\r\n create an unload session\r\n :return: the newly created unload session\r\n \"\"\"\r\n plate = plate.upper()\r\n try:\r\n models.Plate.query.filter(\r\n models.Plate.name == plate).one()\r\n except NoResultFound:\r\n do_commit(models.Plate(name=plate))\r\n\r\n return UnloadSessionWrapper(do_commit(\r\n models.UnloadSession(plate=plate, gross_weight=gross_weight,\r\n with_person=with_person)))\r\n\r\n\r\ndef get_goods_receipts_list(unload_session_id):\r\n \"\"\"\r\n get goods receipt belonging to given unload_session_id from database\r\n :return: a list of goods receipt\r\n \"\"\"\r\n if not unload_session_id:\r\n return []\r\n return [GoodsReceiptWrapper(gr) for gr in\r\n models.GoodsReceipt.query.filter(\r\n models.GoodsReceipt.unload_session_id == unload_session_id)\r\n .all()]\r\n\r\n\r\ndef get_goods_receipt(id_):\r\n \"\"\"\r\n get goods receipt from database\r\n :return: the goods receipt with given id, or None\r\n \"\"\"\r\n if not id_:\r\n return None\r\n try:\r\n return GoodsReceiptWrapper(models.GoodsReceipt.query.filter(\r\n models.GoodsReceipt.id == id_).one())\r\n except NoResultFound:\r\n return None\r\n\r\n\r\ndef new_goods_receipt(customer_id, unload_session_id):\r\n \"\"\"\r\n create a goods receipt for a customer in database\r\n :return: the newly created goods receipt\r\n :raise: ValueError - 若参数发生错误\r\n \"\"\"\r\n import lite_mms.apis as apis\r\n\r\n customer = apis.customer.get_customer(customer_id)\r\n if not customer:\r\n raise ValueError(u\"没有该客户(%d)\" % int(customer_id))\r\n unload_session = get_unload_session(unload_session_id)\r\n if not unload_session:\r\n raise ValueError(u\"没有该卸货会话(%d)\" % int(unload_session_id))\r\n from flask.ext.login import current_user\r\n\r\n model = do_commit(\r\n models.GoodsReceipt(customer=customer.model, creator=current_user if current_user.is_authenticated else None,\r\n unload_session=unload_session.model))\r\n gr = GoodsReceiptWrapper(model)\r\n gr.add_product_entries()\r\n return gr\r\n\r\n\r\ndef create_or_update_goods_receipt(customer_id, unload_session_id):\r\n try:\r\n gr = GoodsReceiptWrapper(models.GoodsReceipt.query.filter(\r\n models.GoodsReceipt.customer_id == customer_id).filter(\r\n models.GoodsReceipt.unload_session_id == unload_session_id).one())\r\n if gr.stale:\r\n gr.add_product_entries()\r\n return gr\r\n except NoResultFound:\r\n return new_goods_receipt(customer_id, unload_session_id)\r\n\r\n\r\ndef new_unload_task(session_id, harbor, customer_id, creator_id,\r\n pic_path, is_last=False):\r\n \"\"\"\r\n 持久化创建一个unload task\r\n :return: 若创建成功,返回创建的unload task\r\n :rtype: UnloadTaskWrapper\r\n :raise:\r\n * ValueError - 如果参数发生错误\r\n \"\"\"\r\n\r\n try:\r\n harbor = models.Harbor.query.filter(models.Harbor.name == harbor).one()\r\n except NoResultFound:\r\n raise ValueError(u\"没有该装卸点\" + harbor)\r\n\r\n try:\r\n creator = models.User.query.filter(models.User.id == creator_id).one()\r\n except NoResultFound:\r\n raise ValueError(_(u\"没有该用户(%d)\" % int(creator_id)))\r\n\r\n try:\r\n customer = models.Customer.query.filter(\r\n models.Customer.id == customer_id).one()\r\n except NoResultFound:\r\n raise ValueError(_(u\"没有该客户(%d)\" % int(customer_id)))\r\n\r\n import lite_mms.apis as apis\r\n\r\n product = apis.product.get_product(name=constants.DEFAULT_PRODUCT_NAME)\r\n if not product:\r\n raise ValueError(_(u\"没有该产品\" + constants.DEFAULT_PRODUCT_NAME))\r\n\r\n unload_session = get_unload_session(session_id)\r\n if not unload_session:\r\n raise ValueError(_(u\"没有该卸货会话(%d)\" % int(session_id)))\r\n\r\n if unload_session.finish_time:\r\n raise ValueError(u\"该卸货会话(%d)已经结束\" % int(session_id))\r\n\r\n ut = do_commit(models.UnloadTask(\r\n unload_session=unload_session.model,\r\n harbor=harbor,\r\n customer=customer,\r\n creator=creator,\r\n pic_path=pic_path,\r\n product=product, is_last=is_last))\r\n\r\n from lite_mms.apis.todo import new_todo, WEIGH_UNLOAD_TASK\r\n from lite_mms.apis.auth import get_user_list\r\n\r\n for to in get_user_list(constants.groups.CARGO_CLERK):\r\n new_todo(to, WEIGH_UNLOAD_TASK, ut)\r\n\r\n return UnloadTaskWrapper(ut)\r\n\r\n\r\ndef get_unload_task(task_id):\r\n \"\"\"\r\n get unload task by id from database\r\n :return: the unload task by given id if there do be such task or None\r\n \"\"\"\r\n if not task_id:\r\n return None\r\n try:\r\n return UnloadTaskWrapper(models.UnloadTask.query.filter(\r\n models.UnloadTask.id == task_id).one())\r\n except NoResultFound:\r\n return None\r\n\r\n\r\nif __name__ == \"__main__\":\r\n pass\r\n" }, { "alpha_fraction": 0.6128158569335938, "alphanum_fraction": 0.6498194932937622, "avg_line_length": 34.74193572998047, "blob_id": "2cf97ff9200d9ff46bba358de34420217a9f411c", "content_id": "578ff219bc7bacd0768f6522440fee3ea4bda47f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1108, "license_type": "no_license", "max_line_length": 113, "num_lines": 31, "path": "/alembic/versions/d9c0f19bdf6_reset_default_url_fo.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"reset default url for admin group\n\nRevision ID: d9c0f19bdf5 \nRevises: d9c0f19bdf5\nCreate Date: 2013-04-01 16:49:52.141337\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'd9c0f19bdf6'\ndown_revision = 'd9c0f19bdf5'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n from lite_mms.constants import groups\n group_table = sa.sql.table(\"TB_GROUP\", \n sa.Column(\"id\", sa.Integer, primary_key=True),\n sa.Column(\"name\", sa.String(32), nullable=False, unique=True),\n sa.Column(\"default_url\", sa.String(256)))\n op.execute(group_table.update().where(group_table.c.id==groups.ADMINISTRATOR).values(default_url=\"/admin2/\"))\n\ndef downgrade():\n from lite_mms.constants import groups\n group_table = sa.sql.table(\"TB_GROUP\", \n sa.Column(\"id\", sa.Integer, primary_key=True),\n sa.Column(\"name\", sa.String(32), nullable=False, unique=True),\n sa.Column(\"default_url\", sa.String(256)))\n op.execute(group_table.update().where(group_table.c.id==groups.ADMINISTRATOR).values(default_url=\"/admin/\"))\n" }, { "alpha_fraction": 0.7652916312217712, "alphanum_fraction": 0.7667140960693359, "avg_line_length": 30.954545974731445, "blob_id": "4811c7b8f14008c87793a01a70cddf3ced1f5268", "content_id": "0060fe18caae68697c7483164718e214f5011bbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 731, "license_type": "no_license", "max_line_length": 68, "num_lines": 22, "path": "/lite_mms/permissions/work_command.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n@author: Yangminghua\n@version: $\n\"\"\"\nfrom collections import namedtuple\nfrom flask.ext.principal import Permission\n\nWorkCommandManagement = namedtuple(\"work_command\", [\"method\"])\n\nViewWorkCommand = WorkCommandManagement(\"view_work_command\")\nScheduleWorkCommand = WorkCommandManagement(\"schedule_work_command\")\n\nview_work_command = Permission(ViewWorkCommand)\nview_work_command.brief = u\"查看工单的权限\"\nschedule_work_command = Permission(ScheduleWorkCommand)\nschedule_work_command.brief = u\"调度工单的权限\"\n\nif __name__ == \"__main__\":\n from lite_mms.permissions.order import ViewOrder ,ScheduleOrder\n print ViewWorkCommand == ViewOrder\n print ScheduleOrder == ScheduleWorkCommand\n" }, { "alpha_fraction": 0.5985662937164307, "alphanum_fraction": 0.5985662937164307, "avg_line_length": 27.86206817626953, "blob_id": "300806e042e65cb653201bedf9a3839e49654463", "content_id": "8d2d41d67e14f8d61d7957a2063056256a3a4c26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1674, "license_type": "no_license", "max_line_length": 79, "num_lines": 58, "path": "/setup.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "from distutils.core import setup\nfrom setuptools import find_packages\nfrom setuptools.command.test import test as TestCommand\nimport sys\nimport os.path\n\nPACKAGE = \"lite_mms\"\nNAME = \"lite-mms\"\nDESCRIPTION = \"\"\nAUTHOR = \"\"\nAUTHOR_EMAIL = \"\"\nURL = \"\"\nVERSION = __import__(PACKAGE).__version__\nDOC = __import__(PACKAGE).__doc__\n\n\nclass PyTest(TestCommand):\n def finalize_options(self):\n TestCommand.finalize_options(self)\n self.test_args = []\n self.test_suite = True\n\n def run_tests(self):\n import pytest\n\n errno = pytest.main(self.test_args)\n sys.exit(errno)\n\nsetup(\n name=NAME,\n version=VERSION,\n long_description=__doc__,\n description=DESCRIPTION,\n author=AUTHOR,\n author_email=AUTHOR_EMAIL,\n license=\"\",\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n scripts=['lite_mms/bin/lite-mms-admin.py'],\n data_files=[(os.path.join(sys.prefix, \"share/lite-mms\"),\n ['lite_mms/data/readme.txt', 'lite_mms/data/config.py.sample',\n 'lite_mms/data/lite-mms-blt', 'lite_mms/data/lite-mms']),\n (os.path.join(sys.prefix, \"share/lite-mms/tools\"),\n ['lite_mms/tools/build_db.py',\n \"lite_mms/tools/set_blt_as_service.py\",\n \"lite_mms/tools/set_portal_as_service.py\",\n \"lite_mms/tools/add_uwsgi_app.sh\", \n 'lite_mms/tools/make_test_data.py'])],\n tests_require=['pytest'],\n cmdclass={'test': PyTest},\n entry_points={\n \"distutils.commands\": [\n \"make_test_data = lite_mms.tools.make_test_data:InitializeTestDB\",\n ]\n }\n\n)\n" }, { "alpha_fraction": 0.7202572226524353, "alphanum_fraction": 0.7202572226524353, "avg_line_length": 33.44444274902344, "blob_id": "143959be8cd4a432af0a11c9010a24b86aa70b24", "content_id": "e4a5ed707f53377693ea5f312430059a588d958a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 311, "license_type": "no_license", "max_line_length": 72, "num_lines": 9, "path": "/lite_mms/portal/delivery_ws/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "from flask import Blueprint\n\ndelivery_ws = Blueprint(\"delivery_ws\", __name__, static_folder=\"static\",\n template_folder=\"templates\")\n\nfrom lite_mms.apis.auth import load_user_from_token\ndelivery_ws.before_request(load_user_from_token)\n\nfrom lite_mms.portal.delivery_ws import webservices\n\n" }, { "alpha_fraction": 0.5887541174888611, "alphanum_fraction": 0.6229327321052551, "avg_line_length": 29.233333587646484, "blob_id": "70fe8da1dcb1ffcf92a5756fc8986122fd477a60", "content_id": "10e9a6efa436c4983157932bdaccaa254d39482b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 907, "license_type": "no_license", "max_line_length": 94, "num_lines": 30, "path": "/alembic/versions/d9c0f19bdf4_add_desc_to_permissi.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"add desc to Permission\n\nRevision ID: d9c0f19bdf4\nRevises: 4b191d5efa1e\nCreate Date: 2013-03-28 11:42:39.474538\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'd9c0f19bdf4'\ndown_revision = '4b191d5efa1e'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.add_column(\"TB_PERMISSION\", \n sa.Column(\"desc\", sa.String(64), default=\"\"))\n perm_table = sa.sql.table(\"TB_PERMISSION\", \n sa.Column(\"name\", sa.String(64), primary_key=True),\n sa.Column(\"desc\", sa.String(64), default=\"\"))\n conn = op.get_bind()\n from lite_mms.permissions import permissions\n for perm in conn.execute(perm_table.select()):\n desc = permissions[perm.name][\"brief\"]\n op.execute(perm_table.update().where(perm_table.c.name==perm.name).values(desc=desc)) \n\ndef downgrade():\n op.drop_column(\"TB_PERMISSION\", \"desc\")\n" }, { "alpha_fraction": 0.6790123581886292, "alphanum_fraction": 0.6913580298423767, "avg_line_length": 26, "blob_id": "6ca9da593ad39474cb9921ba596bc5a897b44b91", "content_id": "597e39e8502f517b923fafe7f49880b319213780", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 111, "license_type": "no_license", "max_line_length": 55, "num_lines": 3, "path": "/lite_mms/constants/work_flow.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\nDELIVERY_TASK_WITH_ABNORMAL_WEIGHT = u'发货任务剩余重量异常批准工作流'\n" }, { "alpha_fraction": 0.569553792476654, "alphanum_fraction": 0.635170578956604, "avg_line_length": 19.567567825317383, "blob_id": "3ada1805ced6b94ffd430c6bed28662ed05f6c32", "content_id": "cfe7cf43e98e9646b7946c8709a843ade6ea4825", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 784, "license_type": "no_license", "max_line_length": 96, "num_lines": 37, "path": "/alembic/versions/318cae8ec27e_add_config_table.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\"\"\"add Config Table\r\r\r\rRevision ID: 318cae8ec27e\r\rRevises: 3288ac4ef7b5\r\rCreate Date: 2013-04-15 18:01:54.714000\r\r\r\r\"\"\"\r\r\r\r# revision identifiers, used by Alembic.\r\rrevision = '318cae8ec27e'\r\rdown_revision = '3288ac4ef7b5'\r\rfrom alembic import op\r\rimport sqlalchemy as sa\r\r\rdef upgrade():\r op.create_table(\"TB_CONFIG\", sa.Column(\"id\", sa.Integer, primary_key=True),\r sa.Column(\"property_name\", sa.String(64), nullable=False),\r sa.Column(\"property_desc\", sa.String(64)),\r sa.Column(\"property_value\", sa.String(64), nullable=False))\r op.execute(u\"INSERT INTO TB_CONFIG VALUES (1, 'print_count_per_page', '打印时展示的每页产品数', '5');\")\r\rdef downgrade():\r op.drop_table(\"TB_CONFIG\")\r\r" }, { "alpha_fraction": 0.6420454382896423, "alphanum_fraction": 0.6439393758773804, "avg_line_length": 23, "blob_id": "b8e3706bb49d6a7f1849622c8e72d7dc4838dbf5", "content_id": "143ead824c63e3f2cec238eec9c2577e25728a54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 528, "license_type": "no_license", "max_line_length": 74, "num_lines": 22, "path": "/lite_mms/apis/harbor.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n@author: Yangminghua\n@version: $\n\"\"\"\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom lite_mms import models\n\ndef get_harbor_list(department_id=None):\n query_ = models.Harbor.query\n if department_id:\n query_ = query_.filter(models.Harbor.department_id==department_id)\n return query_.all()\n\ndef get_harbor_model(name):\n if not name:\n return None\n try:\n return models.Harbor.query.filter(\n models.Harbor.name == name).one()\n except:\n return None\n" }, { "alpha_fraction": 0.7217125296592712, "alphanum_fraction": 0.7217125296592712, "avg_line_length": 39.75, "blob_id": "854ea401800a14e0a41278791cd3138da92e7a29", "content_id": "b3dc988a825b168c8a4aef701944d1c7d2da144d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 327, "license_type": "no_license", "max_line_length": 78, "num_lines": 8, "path": "/lite_mms/portal/manufacture_ws/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "from flask import Blueprint\n\nmanufacture_ws = Blueprint(\"manufacture_ws\", __name__, static_folder=\"static\",\n template_folder=\"templates\")\nfrom lite_mms.apis.auth import load_user_from_token\nmanufacture_ws.before_request(load_user_from_token)\n\nfrom lite_mms.portal.manufacture_ws import webservices\n\n" }, { "alpha_fraction": 0.5883928537368774, "alphanum_fraction": 0.5910714268684387, "avg_line_length": 35.129032135009766, "blob_id": "3b53b8374583a23266d8c7f6b70ec3b79182bb2b", "content_id": "3da8552f6494882e59424db62bc3f0caa9dbf783", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3544, "license_type": "no_license", "max_line_length": 144, "num_lines": 93, "path": "/lite_mms/portal/work_flow/views.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nfrom flask import request, render_template\nfrom flask.ext.login import current_user, login_required\nfrom flask.ext.databrowser import ModelView, column_spec, action, filters\nfrom flask.ext.principal import PermissionDenied\n\nimport yawf\n\nfrom lite_mms.portal.work_flow import work_flow_page\nfrom lite_mms.database import codernity_db\nfrom lite_mms import models\nfrom lite_mms.permissions.work_flow import handle_node\n\n\ndef _get_literally_status(status, obj):\n\n if status == yawf.constants.WORK_FLOW_EXECUTED:\n return u'执行完毕'\n elif status == yawf.constants.WORK_FLOW_APPROVED:\n return u'已批准(执行出错)'\n elif status == yawf.constants.WORK_FLOW_PROCESSING:\n return u'处理中'\n elif status == yawf.constants.WORK_FLOW_REFUSED:\n return u'拒绝'\n else:\n return u'未知'\n\nclass _RefuseNode(action.BaseAction):\n def test_enabled(self, node):\n if node.handle_time != None:\n return -2\n return 0\n\n def op(self, node):\n node.refuse()\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"该任务已经被处理\"}\n\n_refuse_node = _RefuseNode(u'拒绝')\n\nclass _ApproveNode(action.BaseAction):\n\n def test_enabled(self, node):\n if node.handle_time != None:\n return -2\n return 0\n\n def op(self, node):\n node.approve()\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"该任务已经被处理\"}\n\n_approve_node = _ApproveNode(u'批准')\n\nclass NodeModelView(ModelView):\n \n can_batchly_edit = False\n\n def try_create(self):\n raise PermissionDenied\n \n def try_edit(self, objs=None):\n handle_node.test()\n\n __list_columns__ = [column_spec.ColumnSpec('work_flow.id', label=u'工作流编号'),\n column_spec.ColumnSpec('name', label=u'名称'),\n column_spec.PlaceHolderColumnSpec('annotation', label=u'描述', \n template_fname='work-flow/permit-delivery-task-with-abnormal-weight-annotation.html'),\n column_spec.ColumnSpec('create_time', label=u'创建时间', \n formatter=lambda v, obj: v.strftime('%Y年%m月%d日 %H:%M').decode('utf-8')), \n column_spec.ColumnSpec('handle_time', label=u'处理时间', \n formatter=lambda v, obj: v.strftime('%Y年%m月%d日 %H:%M').decode('utf-8') if v else '--'),\n column_spec.ColumnSpec('work_flow.status', label=u'工作流状态',\n formatter=_get_literally_status )]\n\n __sortable_columns__ = ['work_flow.id', 'create_time']\n\n __default_order__ = (\"create_time\", \"desc\")\n\n __column_filters__ = [filters.EqualTo('work_flow.id', name=u'是', display_col_name=u'工作流编号'),\n filters.Only('handle_time', display_col_name=u'仅展示待处理工作流', test=lambda col: col==None, default_value=True,\n notation=\"__only_unhandled\"),\n filters.Between('create_time', name=u'介于', display_col_name=u'创建时间')]\n\n def get_customized_actions(self, objs=None):\n return [_refuse_node, _approve_node]\n\n def __list_filters__(self):\n return [filters.EqualTo('handler_group_id', value=current_user.group.id), ]\n\nnode_model_view = NodeModelView(models.Node, u'工作流任务')\n" }, { "alpha_fraction": 0.5636277198791504, "alphanum_fraction": 0.7725545763969421, "avg_line_length": 28.25, "blob_id": "05f87c9cd2b492792ef70d6be6267154159cd65f", "content_id": "989255516a1ffe7a34515f0a73454f97db54d2c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 2106, "license_type": "no_license", "max_line_length": 124, "num_lines": 72, "path": "/requirements.freeze.txt", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "APScheduler==2.1.1\nBabel==1.3\nBrownie==0.5.1\nCodernityDB==0.4.2\nFabric==1.5.1\nFlask==0.10.1\nFlask-Admin==1.0.4\nFlask-Babel==0.9\n-e git+https://github.com/xiechao06/Flask-DataBrowser.git@2468574a813df7287b55c2e358ad2147eb62c745#egg=Flask_DataBrowser-dev\nFlask-DebugToolbar==0.8.0\nFlask-Login==0.2.4\nFlask-Mail==0.9.0\n-e git+https://github.com/xiechao06/Flask-NavBar.git@35909ef3ae73e6b18cacf188584fbb81d9366a01#egg=Flask_NavBar-dev\nFlask-Principal==0.3.3\nFlask-SQLAlchemy==0.16\nFlask-WTF==0.8.3\nGeraldo==0.4.17\nHamlish-Jinja==0.3.0\nJinja2==2.7\nMako==0.8.1\nMarkupSafe==0.18\nMySQL-python==1.2.3\nPillow==2.2.1\nPyYAML==3.10\nPygments==1.6\nSQLAlchemy==0.8.1\nTempita==0.5.1\nWTForms==1.0.2\nWerkzeug==0.9.1\nalembic==0.5.0\nargparse==1.2.1\nbeautifulsoup4==4.1.3\nblinker==1.2\ncolorama==0.2.4\ncssselect==0.7.1\ndecorator==3.4.0\ndistribute==0.6.24\ndocutils==0.9.1\n-e git+https://github.com/xiechao06/Flask-Report.git@ed8a6b2858d14504a6e464b622fdf2ffeb4810d9#egg=flask_report-dev\nimport-file==1.11\nipython==1.1.0\nitsdangerous==0.21\n-e git+https://github.com/PuZheng/lite-mms.git@78d9e3e6364c9a2353abbac3866411fa1d5d86a6#egg=lite_mms-dev\n-e git+https://github.com/xiechao06/lite-sm.git@9204dcaba550ab8da9450576ba95c54c93259406#egg=lite_sm-dev\n-e git+https://github.com/xiechao06/lite-task-flow.git@3217d9692a43f5d4d38744cb5fa8c1886071c08f#egg=lite_task_flow-dev\nlockfile==0.9.1\nlogilab-astng==0.24.1\nlogilab-common==0.58.3\nlxml==3.2.3\nmock==1.0.1\n-e git+https://github.com/xiechao06/nav-bar.git@a6090d416e0a3c5a32bc5a64b694e41c4e6d11c6#egg=nav_bar-dev\nnose==1.2.1\nparamiko==1.9.0\npath.py==3.0.1\npy==1.4.12\npycrypto==2.6\n-e git+https://github.com/xiechao06/pyfeature.git@92e086490ab44384dc21ecea65592c302273feab#egg=pyfeature-dev\npyflakes==0.7.2\npylint==0.26.0\npyquery==1.2.4\npytest==2.3.4\npython-daemon==1.6\npytz==2013b\nreportlab==2.7\nspeaklater==1.3\nsqlparse==0.1.8\ntornado==2.4\ntransaction==1.3.0\n-e git+https://github.com/xiechao06/WorkFlowRepr.git@4f7c4ea0a9b449c75aeb762124c96c97d0676454#egg=work_flow_repr-dev\nwsgiref==0.1.2\n-e git+https://github.com/xiechao06/yawf.git@dc581f919c853eed866684c11082dac1a6522d83#egg=yawf-dev\nzope.interface==4.0.5\n" }, { "alpha_fraction": 0.6984924674034119, "alphanum_fraction": 0.7010050415992737, "avg_line_length": 32.16666793823242, "blob_id": "ad24b35b90c4e1384f2165d0b50bcceb3f1fe23a", "content_id": "1d03976988c0304e319a93b7b134f2eb02766398", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 398, "license_type": "no_license", "max_line_length": 120, "num_lines": 12, "path": "/Makefile", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "GH_PAGES_SOURCES = docs\ngh-pages:\n\tgit checkout gh-pages\n\trm -rf build _sources _static \n\tgit checkout master $(GH_PAGES_SOURCES)\n\tgit reset HEAD\n\tcd docs; make html; cd ..;\n\tcp -rf docs/build/html/* ./\n\trm -rf $(GH_PAGES_SOURCES) build upload\n\tgit add -A\n\tgit commit -m \"Generated gh-pages for `git log master -1 --pretty=short --abbrev-commit`\" && git push origin gh-pages; \n\tgit checkout master\n" }, { "alpha_fraction": 0.759856641292572, "alphanum_fraction": 0.759856641292572, "avg_line_length": 30, "blob_id": "d39061c1dbcd444a2f939d3431d4a89367122bcb", "content_id": "8ba1784341d890120ad307cc47e3667007f31a03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 279, "license_type": "no_license", "max_line_length": 67, "num_lines": 9, "path": "/lite_mms/portal/cargo_ws/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "from flask import Blueprint\n\ncargo_ws = Blueprint(\"cargo_ws\", __name__, static_folder=\"static\", \n template_folder=\"templates\")\n\nfrom lite_mms.apis.auth import load_user_from_token\ncargo_ws.before_request(load_user_from_token)\n\nfrom lite_mms.portal.cargo_ws import webservices\n" }, { "alpha_fraction": 0.6897506713867188, "alphanum_fraction": 0.698060929775238, "avg_line_length": 18, "blob_id": "e9db4490ed3fcaf756f94fbc1fc8b2d99faba112", "content_id": "5eec0f3450a85a7598be09200097435c37f7c4ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 361, "license_type": "no_license", "max_line_length": 58, "num_lines": 19, "path": "/README.md", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "lite-mms\n========\n\n## packages required\n\n* libmysqlclient-dev\n* libxml2-dev \n* libxslt1-dev\n\n\n## use mysql as database\n\n```sql\nmysql> create user 'foo-user' identified by 'foo-password'\nmysql> create database foo_db character set 'utf8';\nmysql> grant all on foo_db.* to 'foo-user';\nmysql> flush privileges;\n```\nand set DBSTR to \"mysql://foo-user:foo-password@\"\n" }, { "alpha_fraction": 0.5636160969734192, "alphanum_fraction": 0.5710565447807312, "avg_line_length": 38.52941131591797, "blob_id": "0af46b99efe9ca9eb885dc2c22a1c20463aa8c75", "content_id": "d5133de9f71c9ea3777bff438ff42ae3952fd4c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2688, "license_type": "no_license", "max_line_length": 100, "num_lines": 68, "path": "/lite_mms/bin/lite-mms-admin.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nSYNOPSIS\n python build_db.py [options]\nOPTIONS\n help <command>\n show this help, or help to command\n initenv <dir>\n initialize a customized environment\n runserver <options>\n run portal service, note you should execute this command under your\n customized environment, else you can't read your config file\n runblt\n run BLT service, note you should execute this command under your\n customized environment, else you can't read your config file\n\"\"\"\nimport sys\nimport subprocess\nimport os\nimport shutil\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 1 or sys.argv[1] == \"help\":\n try:\n command = sys.argv[2]\n if command == \"initenv\":\n print \"initenv <dir>\"\n print \"initialize a customized environment\"\n elif command == \"runserver\":\n subprocess.call([\"python\", \"-m\", \"lite_mms.runserver\", \"-h\"]) \n elif command == \"runblt\":\n subprocess.call([\"python\", \"-m\", \"lite_mms.BLT\", \"-h\"])\n except IndexError:\n print __doc__\n finally:\n exit(0)\n elif sys.argv[1] == \"runserver\":\n subprocess.call([\"python\", \"-m\", \"lite_mms.runserver\"] + sys.argv[2:])\n elif sys.argv[1] == \"runblt\":\n subprocess.call([\"python\", \"-m\", \"lite_mms.BLT\"] + sys.argv[2:])\n elif sys.argv[1] == \"initenv\":\n if len(sys.argv) != 3:\n print __doc__\n exit(-1)\n if os.path.exists(sys.argv[2]):\n print \"Error: \" + sys.argv[2] + \" exists\"\n exit(-1)\n os.makedirs(sys.argv[2])\n os.chdir(sys.argv[2])\n config_fpath = os.path.join(sys.prefix, \"share/lite-mms/config.py.sample\")\n if not os.path.exists(config_fpath):\n print \"Error: \" + config_fpath + \"doesn't exists, make sure your installation completed\"\n shutil.copy(config_fpath, \"config.py\")\n readme_fpath = os.path.join(sys.prefix, \"share/lite-mms/readme.txt\")\n if not os.path.exists(readme_fpath):\n print \"Error: \" + readme_fpath + \"doesn't exists, make sure your installation completed\"\n exit(-1)\n shutil.copy(readme_fpath, \"readme.txt\")\n tools_dir = os.path.join(sys.prefix, \"share/lite-mms/tools\")\n if not os.path.exists(tools_dir):\n print \"Error: \" + tools_dir + \"doesn't exists, make sure your installation completed\"\n exit(-1)\n shutil.copytree(tools_dir, \"tools\")\n subprocess.call([\"chmod\", \"u+x\", \"tools/add_uwsgi_app.sh\"])\n else:\n print \"unkown option: \" + sys.argv[1]\n print __doc__\n" }, { "alpha_fraction": 0.5584989190101624, "alphanum_fraction": 0.5739514231681824, "avg_line_length": 29.200000762939453, "blob_id": "869bdfc46f392b5921f5d1cd6a5850795b09a000", "content_id": "dd1458e777155b7d219b2ed22b14f5f6cc7df001", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 453, "license_type": "no_license", "max_line_length": 64, "num_lines": 15, "path": "/lite_mms/test/utils.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nimport json\n\n\ndef login(username, password, app):\n rv = app.post('/auth/login', data=dict(username=username,\n password=password))\n assert rv.status_code == 302\n\n\ndef client_login(username, password, app):\n rv = app.post('/auth_ws/login?username=%s&password=%s' %\n (username, password))\n assert rv.status_code == 200\n return json.loads(rv.data)['token']\n" }, { "alpha_fraction": 0.5792372226715088, "alphanum_fraction": 0.5839493274688721, "avg_line_length": 35.90652084350586, "blob_id": "7ab06715379fd3418010031b8768e2c16d7a6f87", "content_id": "1bcbfacbadef6a5cd4aae0a901b4ebbfed728db1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 34297, "license_type": "no_license", "max_line_length": 116, "num_lines": 920, "path": "/lite_mms/models.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom datetime import datetime\n\nimport flask.ext.databrowser as databrowser\nfrom sqlalchemy.ext.declarative import declared_attr\nfrom sqlalchemy.orm.properties import ColumnProperty\n\nfrom lite_mms import constants\nfrom lite_mms.database import db\n\npermission_and_group_table = db.Table(\"TB_PERMISSION_AND_GROUP\",\n db.Column(\"permission_name\",\n db.String(64),\n db.ForeignKey(\n 'TB_PERMISSION.name')),\n db.Column(\"group_id\", db.Integer,\n db.ForeignKey(\"TB_GROUP.id\")))\n\nuser_and_group_table = db.Table('TB_ASSOCIATION',\n db.Column('user_id', db.Integer,\n db.ForeignKey('TB_USER.id')),\n db.Column('group_id', db.Integer,\n db.ForeignKey('TB_GROUP.id')))\n\ndepartment_and_user_table = db.Table(\"TB_DEPARTMENT_AND_USER\",\n db.Column(\"department_id\", db.Integer,\n db.ForeignKey(\n 'TB_DEPARTMENT.id')),\n db.Column(\"user_id\", db.Integer,\n db.ForeignKey('TB_USER.id')))\n\nprocedure_and_department_table = db.Table(\"TB_PROCEDURE_AND_DEPARTMENT\",\n db.Column(\"procedure_id\", db.Integer,\n db.ForeignKey(\n \"TB_PROCEDURE.id\")),\n db.Column(\"department_id\",\n db.Integer,\n db.ForeignKey(\n \"TB_DEPARTMENT.id\")))\n\nuser_and_team_table = db.Table(\"TB_USER_AND_TEAM\", db.Column(\"team_id\", db.Integer, db.ForeignKey(\"TB_TEAM.id\")),\n db.Column(\"leader_id\", db.Integer, db.ForeignKey(\"TB_USER.id\")))\nclass _ResyncMixin(object):\n\n\n\n def resync(self):\n\n pk = databrowser.utils.get_primary_key(self.__class__)\n fresh_obj = self.query.filter(getattr(self.__class__, pk)==getattr(self, pk)).one()\n props = self.__class__._sa_class_manager.mapper.iterate_properties\n\n for p in props:\n if isinstance(p, ColumnProperty) and not p.is_primary:\n setattr(self, p.key, getattr(fresh_obj, p.key))\n return self\n\n\n\nclass Permission(db.Model):\n __tablename__ = \"TB_PERMISSION\"\n __modelname__ = u\"权限\"\n name = db.Column(db.String(64), primary_key=True)\n desc = db.Column(db.String(64), default=\"\")\n\n def __unicode__(self):\n return self.name + '(' + self.desc + ')'\n\n def __repr__(self):\n return \"<Permission: %s>\" % self.name.encode(\"utf-8\")\n\n\nclass Group(db.Model):\n __tablename__ = \"TB_GROUP\"\n __modelname__ = u\"用户组\"\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(32), nullable=False, unique=True)\n permissions = db.relationship(\"Permission\",\n secondary=permission_and_group_table)\n default_url = db.Column(db.String(256))\n\n def __unicode__(self):\n return self.name\n\n def __repr__(self):\n return \"<Group: %d>\" % self.id\n\n\nclass User(db.Model):\n __tablename__ = \"TB_USER\"\n __modelname__ = u\"用户\"\n\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(32), nullable=False, unique=True)\n password = db.Column(db.String(128), nullable=False, doc=u\"这里保存的是密码明文的MD5值\")\n groups = db.relationship(\"Group\", secondary=user_and_group_table,\n backref=\"users\")\n tag = db.Column(db.String(32), nullable=True)\n enabled = db.Column(db.Boolean, default=True)\n\n def __unicode__(self):\n return self.username\n\n def __repr__(self):\n return \"<User %d>\" % self.id\n\nclass UnloadSession(db.Model):\n __modelname__ = u\"卸货会话\"\n __tablename__ = \"TB_UNLOAD_SESSION\"\n\n id = db.Column(db.Integer, primary_key=True)\n plate = db.Column(db.String(32), db.ForeignKey('TB_PLATE.name'), nullable=False)\n plate_ = db.relationship(\"Plate\")\n gross_weight = db.Column(db.Integer, nullable=False)\n with_person = db.Column(db.Boolean, default=False)\n status = db.Column(db.Integer, default=constants.cargo.STATUS_LOADING, nullable=False)\n create_time = db.Column(db.DateTime, default=datetime.now)\n finish_time = db.Column(db.DateTime)\n goods_receipt_list = db.relationship(\n \"GoodsReceipt\", backref=\"unload_session\",\n cascade=\"all, delete-orphan\"\n )\n\n def __unicode__(self):\n return self.plate\n\n def __repr__(self):\n return \"<UnloadSession %d>\" % self.id\n\nclass UnloadTask(db.Model):\n __modelname__ = u\"卸货任务\"\n __tablename__ = \"TB_UNLOAD_TASK\"\n\n id = db.Column(db.Integer, primary_key=True)\n session_id = db.Column(db.Integer, db.ForeignKey('TB_UNLOAD_SESSION.id'))\n unload_session = db.relationship(\"UnloadSession\", backref=db.backref(\"task_list\", cascade=\"all, delete-orphan\"))\n harbor_name = db.Column(db.String(32), db.ForeignKey('TB_HABOR.name'))\n harbor = db.relationship(\"Harbor\")\n customer_id = db.Column(db.Integer, db.ForeignKey('TB_CUSTOMER.id'))\n customer = db.relationship(\"Customer\")\n creator_id = db.Column(db.Integer, db.ForeignKey('TB_USER.id'))\n creator = db.relationship(\"User\")\n pic_path = db.Column(db.String(256))\n create_time = db.Column(db.DateTime, default=datetime.now)\n weight = db.Column(db.Integer, default=0)\n product_id = db.Column(db.Integer, db.ForeignKey(\"TB_PRODUCT.id\"))\n product = db.relationship(\"Product\")\n is_last = db.Column(db.Boolean, default=False)\n\n def __unicode__(self):\n return unicode(self.id)\n\n def __repr__(self):\n return \"<UnloadTask %d>\" % self.id\n\n\nclass Customer(db.Model):\n __modelname__ = u\"客户\"\n __tablename__ = \"TB_CUSTOMER\"\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(32), nullable=False, unique=True)\n abbr = db.Column(db.String(32))\n enabled = db.Column(db.Boolean, default=True)\n MSSQL_ID = db.Column(db.Integer, default=0, nullable=False)\n\n\n def __init__(self, name, abbr, MSSQL_ID=0):\n self.name = name\n self.abbr = abbr\n self.MSSQL_ID = MSSQL_ID\n\n def __unicode__(self):\n return self.name\n\n def __repr__(self):\n return \"<Customer %s>\" % self.id\n\n\nclass Harbor(db.Model):\n __modelname__ = u\"装卸点\"\n __tablename__ = \"TB_HABOR\"\n name = db.Column(db.String(32), nullable=False, primary_key=True)\n department_id = db.Column(db.Integer, db.ForeignKey(\"TB_DEPARTMENT.id\"))\n department = db.relationship(\"Department\", backref=\"harbor_list\", doc=u\"装卸点卸载的待加工件将默认分配给此车间\")\n\n\n def __unicode__(self):\n return unicode(self.name)\n\n def __repr__(self):\n return \"<Harbor %s>\" % self.name\n\n\nclass ProductType(db.Model):\n __modelname__ = u\"产品类型\"\n __tablename__ = \"TB_PRODUCT_TYPE\"\n id = db.Column(db.Integer, primary_key=True)\n MSSQL_ID = db.Column(db.Integer, default=0, nullable=True)\n name = db.Column(db.String(32), unique=True)\n\n def __init__(self, name, MSSQL_ID=0):\n self.name = name\n self.MSSQL_ID = MSSQL_ID\n\n def __unicode__(self):\n return self.name\n\n def __repr__(self):\n return \"<ProductType: %d>\" % self.id\n\n\nclass Product(db.Model):\n __modelname__ = u\"产品\"\n __tablename__ = \"TB_PRODUCT\"\n id = db.Column(db.Integer, primary_key=True)\n MSSQL_ID = db.Column(db.Integer, default=0, nullable=True)\n name = db.Column(db.String(32))\n product_type_id = db.Column(db.Integer,\n db.ForeignKey(\"TB_PRODUCT_TYPE.id\"))\n product_type = db.relationship(\"ProductType\", backref=\"products\")\n enabled = db.Column(db.Boolean, default=True)\n\n def __init__(self, name, product_type, MSSQL_ID=0):\n self.name = name\n self.product_type = product_type\n self.MSSQL_ID = MSSQL_ID\n\n def __unicode__(self):\n return self.name\n\n def __repr__(self):\n return \"<Product %d>\" % self.id\n\n\nclass Department(db.Model):\n __modelname__ = u\"车间\"\n __tablename__ = \"TB_DEPARTMENT\"\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(32), nullable=False, unique=True)\n team_list = db.relationship(\"Team\", backref=\"department\")\n leader_list = db.relationship(\"User\", secondary=department_and_user_table,\n backref=\"department_list\")\n\n\n def __unicode__(self):\n return self.name\n\n def __repr__(self):\n return \"<Department %d>\" % self.id\n\nclass Team(db.Model):\n __modelname__ = u\"班组\"\n __tablename__ = \"TB_TEAM\"\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(32), nullable=False, unique=True)\n department_id = db.Column(db.Integer, db.ForeignKey('TB_DEPARTMENT.id'), nullable=False)\n leader_list = db.relationship(\"User\", secondary=user_and_team_table, backref=\"team_list\")\n\n def __unicode__(self):\n return self.name\n\n def __repr__(self):\n return \"<Team %s>\" % self.id\n\nclass GoodsReceipt(db.Model):\n __modelname__ = u\"收货单\"\n __tablename__ = \"TB_GOODS_RECEIPT\"\n\n id = db.Column(db.Integer, primary_key=True)\n receipt_id = db.Column(db.String(20), unique=True)\n customer_id = db.Column(db.Integer, db.ForeignKey('TB_CUSTOMER.id'))\n customer = db.relationship(Customer)\n unload_session_id = db.Column(db.Integer,\n db.ForeignKey('TB_UNLOAD_SESSION.id'))\n create_time = db.Column(db.DateTime, default=datetime.now)\n printed = db.Column(db.Boolean, default=False)\n order = db.relationship(\n \"Order\", backref=db.backref(\"goods_receipt\", uselist=False),\n cascade=\"all, delete-orphan\", uselist=False)\n creator_id = db.Column(db.Integer, db.ForeignKey(\"TB_USER.id\"))\n creator = db.relationship(\"User\")\n\n def __init__(self, customer, unload_session, create_time=None, creator=None):\n self.customer = customer\n self.unload_session = unload_session\n self.create_time = create_time or datetime.now()\n self.creator = creator\n self.receipt_id = self.id_generator()\n\n def id_generator(self):\n return self.create_time.strftime('%Y%m%d%H%M%S%f')\n\n def __unicode__(self):\n return self.receipt_id\n\n def __repr__(self):\n return \"<GoodsReceipt %d>\" % self.id\n\n\nclass GoodsReceiptEntry(db.Model):\n __modelname__ = u\"收货单项\"\n __tablename__ = \"TB_GOODS_RECEIPT_ENTRY\"\n\n id = db.Column(db.Integer, primary_key=True)\n goods_receipt_id = db.Column(db.Integer,\n db.ForeignKey(\"TB_GOODS_RECEIPT.id\"))\n goods_receipt = db.relationship(\"GoodsReceipt\",\n backref=\"goods_receipt_entries\")\n weight = db.Column(db.Integer, nullable=False)\n product_id = db.Column(db.Integer, db.ForeignKey(\"TB_PRODUCT.id\"))\n product = db.relationship(\"Product\")\n harbor_name = db.Column(db.String(32), db.ForeignKey('TB_HABOR.name'))\n harbor = db.relationship(\"Harbor\")\n pic_path = db.Column(db.String(256))\n\n def __unicode__(self):\n return unicode(self.id)\n\n def __repr__(self):\n return \"<GoodsReceiptProduct %d>\" % self.id\n\n\nclass Order(db.Model):\n __modelname__ = u\"订单\"\n __tablename__ = \"TB_ORDER\"\n\n id = db.Column(db.Integer, primary_key=True)\n customer_order_number = db.Column(db.String(20), unique=True)\n goods_receipt_id = db.Column(db.Integer,\n db.ForeignKey('TB_GOODS_RECEIPT.id'))\n create_time = db.Column(db.DateTime)\n finish_time = db.Column(db.DateTime)\n sub_order_list = db.relationship(\n \"SubOrder\", backref=\"order\",\n cascade=\"all, delete-orphan\")\n dispatched = db.Column(db.Boolean)\n creator_id = db.Column(db.Integer, db.ForeignKey(\"TB_USER.id\"))\n creator = db.relationship(\"User\")\n refined = db.Column(db.Boolean, default=False)\n dispatched_time = db.Column(db.DateTime)\n\n def __init__(self, goods_receipt, creator,\n create_time=None, finish_time=None, dispatched=False, refined=False):\n self.goods_receipt = goods_receipt\n self.create_time = create_time or datetime.now()\n self.finish_time = finish_time\n self.customer_order_number = goods_receipt.receipt_id\n self.dispatched = dispatched\n self.creator = creator\n self.refined = refined\n\n def __unicode__(self):\n return self.customer_order_number\n\n def __repr__(self):\n return \"<Order %s>\" % self.id\n\n\nclass SubOrder(db.Model, _ResyncMixin):\n __modelname__ = u\"子订单\"\n __tablename__ = \"TB_SUB_ORDER\"\n\n id = db.Column(db.Integer, primary_key=True)\n product_id = db.Column(db.Integer, db.ForeignKey(\"TB_PRODUCT.id\"))\n product = db.relationship(\"Product\")\n\n task_id = db.Column(db.Integer, db.ForeignKey(\"TB_UNLOAD_TASK.id\"))\n unload_task = db.relationship(\"UnloadTask\", backref=db.backref(\n \"sub_order\", uselist=False), uselist=False)\n\n default_harbor_name = db.Column(db.String(32), db.ForeignKey(\"TB_HABOR.name\"))\n default_harbor = db.relationship(\"Harbor\",\n primaryjoin=\"Harbor.name == SubOrder.default_harbor_name\")\n spec = db.Column(db.String(64))\n type = db.Column(db.String(64))\n weight = db.Column(db.Integer, default=0)\n harbor_name = db.Column(db.String(32), db.ForeignKey('TB_HABOR.name'))\n harbor = db.relationship(\"Harbor\",\n primaryjoin=\"Harbor.name == SubOrder.harbor_name\")\n order_id = db.Column(db.Integer, db.ForeignKey(\"TB_ORDER.id\"))\n urgent = db.Column(db.Boolean)\n returned = db.Column(db.Boolean)\n pic_path = db.Column(db.String(256))\n tech_req = db.Column(db.String(64))\n create_time = db.Column(db.DateTime)\n finish_time = db.Column(db.DateTime)\n quantity = db.Column(db.Integer, default=0)\n unit = db.Column(db.String(16), default=u'')\n due_time = db.Column(db.Date)\n order_type = db.Column(db.Integer)\n remaining_quantity = db.Column(db.Integer)\n work_command_list = db.relationship(\"WorkCommand\",\n backref=db.backref(\n \"sub_order\", uselist=False),\n cascade=\"all, delete-orphan\"\n )\n\n\n @property\n def unit_weight(self):\n try:\n return self.weight / float(self.quantity)\n except ZeroDivisionError:\n return 0\n\n def __init__(self, product, weight, harbor, order,\n quantity, unit, order_type=constants.STANDARD_ORDER_TYPE,\n create_time=None, finish_time=None, urgent=False,\n returned=False, pic_path=\"\", tech_req=\"\", due_time=None,\n spec=\"\", type=\"\", default_harbor=None):\n self.product = product\n self.spec = spec\n self.type = type\n self.weight = weight\n self.harbor = harbor\n self.remaining_quantity = self.quantity = quantity\n self.unit = unit\n self.order = order\n self.create_time = create_time or datetime.now()\n self.finish_time = finish_time\n self.urgent = urgent\n self.returned = returned\n self.pic_path = pic_path\n self.tech_req = tech_req\n self.due_time = due_time\n self.order_type = order_type\n self.default_harbor = default_harbor\n\n def __unicode__(self):\n return unicode(self.id)\n\n def __repr__(self):\n return \"<SubOrder %d>\" % self.id\n\n\nclass WorkCommand(db.Model, _ResyncMixin):\n __modelname__ = u\"工单\"\n __tablename__ = \"TB_WORK_COMMAND\"\n\n id = db.Column(db.Integer, primary_key=True)\n create_time = db.Column(db.DateTime)\n department = db.relationship(\"Department\", order_by=User.id,\n backref=\"work_comman_list\")\n department_id = db.Column(db.Integer, db.ForeignKey(\"TB_DEPARTMENT.id\"),\n nullable=True)\n last_mod = db.Column(db.DateTime, doc=u\"上次对工单修改的时间\")\n completed_time = db.Column(db.DateTime, doc=u\"生产完毕的时间\")\n org_cnt = db.Column(db.Integer)\n org_weight = db.Column(db.Integer)\n urgent = db.Column(db.Boolean)\n previous_procedure_id = db.Column(db.Integer,\n db.ForeignKey(\"TB_PROCEDURE.id\"))\n previous_procedure = db.relationship(\"Procedure\",\n primaryjoin=\"Procedure\"\n \".id==WorkCommand\"\n \".previous_procedure_id\")\n procedure_id = db.Column(db.Integer, db.ForeignKey(\"TB_PROCEDURE.id\"))\n procedure = db.relationship(\"Procedure\",\n primaryjoin=\"Procedure.id==WorkCommand\"\n \".procedure_id\")\n processed_cnt = db.Column(db.Integer)\n processed_weight = db.Column(db.Integer)\n status = db.Column(db.Integer)\n sub_order_id = db.Column(db.Integer, db.ForeignKey(\"TB_SUB_ORDER.id\"))\n tag = db.Column(db.String(32))\n team = db.relationship(\"Team\", backref=\"work_comman_list\")\n team_id = db.Column(db.Integer, db.ForeignKey(\"TB_TEAM.id\"), nullable=True)\n tech_req = db.Column(db.String(32))\n qir_list = db.relationship(\"QIReport\", backref=\"work_command\",\n cascade=\"all, delete-orphan\",\n primaryjoin=\"WorkCommand.id==QIReport\"\n \".work_command_id\")\n pic_path = db.Column(db.String(256))\n handle_type = db.Column(db.Integer)\n previous_work_command_id = db.Column(db.Integer, db.ForeignKey(\"TB_WORK_COMMAND.id\"))\n previous_work_command = db.relationship(\"WorkCommand\", backref=db.backref(\"next_work_command_list\"),\n primaryjoin=\"WorkCommand.id==WorkCommand.previous_work_command_id\",\n uselist=False, remote_side=id)\n\n @property\n def unit_weight(self):\n try:\n return self.org_weight / float(self.org_cnt)\n except ZeroDivisionError:\n return 0\n\n @property\n def processed_unit_weight(self):\n try:\n return self.processed_weight / float(self.processed_cnt)\n except ZeroDivisionError:\n return 0\n\n def __init__(self, sub_order, org_weight, procedure, urgent=False,\n status=constants.work_command.STATUS_DISPATCHING, department=None,\n create_time=None,\n last_mod=datetime.now(),\n processed_weight=0, team=None, previous_procedure=None,\n tag=\"\", tech_req=\"\", org_cnt=0, processed_cnt=0, pic_path=\"\",\n handle_type=constants.work_command.HT_NORMAL,\n previous_work_command=None):\n self.sub_order = sub_order\n self.urgent = urgent\n self.org_weight = org_weight\n self.procedure = procedure\n self.status = status\n self.create_time = create_time or datetime.now()\n self.last_mod = last_mod\n self.processed_weight = processed_weight\n self.team = team\n self.department = department\n self.previous_procedure = previous_procedure\n self.tag = tag\n self.tech_req = tech_req\n self.org_cnt = org_cnt\n self.processed_cnt = processed_cnt\n self.pic_path = pic_path\n self.handle_type = handle_type\n self.previous_work_command = previous_work_command\n\n def set_status(self, new_status):\n \"\"\"\n set new status, and UPDATE last_mod field, so DON'T UPDATE STATUS\n DIRECTLY!\n \"\"\"\n self.status = new_status\n self.last_mod = datetime.now()\n\n def __unicode__(self):\n return unicode(self.id)\n\n def __repr__(self):\n return \"<WorkCommand %d>\" % self.id\n\n\nclass QIReport(db.Model):\n __modelname__ = u\"质检报告\"\n __tablename__ = \"TB_QI_REPORT\"\n\n id = db.Column(db.Integer, primary_key=True)\n work_command_id = db.Column(db.Integer,\n db.ForeignKey(\"TB_WORK_COMMAND.id\"))\n generated_work_command_id = db.Column(db.Integer,\n db.ForeignKey(\"TB_WORK_COMMAND.id\"))\n generated_work_command = db.relationship(\"WorkCommand\",\n backref=db.backref(\"parent_qir\",\n uselist=False),\n primaryjoin=\"WorkCommand.id==QIReport.generated_work_command_id\")\n quantity = db.Column(db.Integer)\n weight = db.Column(db.Integer)\n result = db.Column(db.Integer)\n report_time = db.Column(db.DateTime)\n actor_id = db.Column(db.Integer, db.ForeignKey(\"TB_USER.id\"))\n actor = db.relationship(User)\n pic_path = db.Column(db.String(256))\n\n def __init__(self, work_command, quantity, weight, result, actor_id,\n report_time=None, pic_path=\"\"):\n self.work_command = work_command\n self.quantity = quantity\n self.weight = weight\n self.result = result\n self.actor_id = actor_id\n self.report_time = report_time or datetime.now()\n self.pic_path = pic_path\n\n def __unicode__(self):\n return unicode(self.id)\n\n def __repr__(self):\n return \"<QIReport %d>\" % self.id\n\nclass DeliverySession(db.Model):\n __modelname__ = u\"发货会话\"\n __tablename__ = \"TB_DELIVERY_SESSION\"\n\n id = db.Column(db.Integer, primary_key=True)\n plate = db.Column(db.String(32), db.ForeignKey(\"TB_PLATE.name\"), nullable=False)\n plate_ = db.relationship(\"Plate\")\n tare = db.Column(db.Integer, nullable=False)\n create_time = db.Column(db.DateTime, default=datetime.now)\n finish_time = db.Column(db.DateTime)\n with_person = db.Column(db.Boolean, default=False)\n delivery_task_list = db.relationship(\"DeliveryTask\",\n backref=db.backref(\"delivery_session\",\n uselist=False),\n cascade=\"all, delete-orphan\")\n status = db.Column(db.Integer, default=constants.delivery.STATUS_LOADING, nullable=False)\n\n def __unicode__(self):\n return self.plate\n\n def __repr__(self):\n return \"<DeliverySession %d>\" % self.id\n\n\nclass StoreBill(db.Model):\n __modelname__ = u\"仓单\"\n __tablename__ = \"TB_STORE_BILL\"\n\n id = db.Column(db.Integer, primary_key=True)\n\n harbor_name = db.Column(db.String(32), db.ForeignKey('TB_HABOR.name'))\n harbor = db.relationship(\"Harbor\")\n sub_order_id = db.Column(db.Integer, db.ForeignKey(\"TB_SUB_ORDER.id\"))\n sub_order = db.relationship(\"SubOrder\",\n backref=db.backref(\"store_bill_list\",\n cascade=\"all, delete-orphan\"))\n qir_id = db.Column(db.Integer, db.ForeignKey(\"TB_QI_REPORT.id\"))\n qir = db.relationship(\"QIReport\",\n backref=db.backref(\"store_bill_list\",\n cascade=\"all\"))\n quantity = db.Column(db.Integer)\n weight = db.Column(db.Integer, default=0)\n customer_id = db.Column(db.Integer, db.ForeignKey(\"TB_CUSTOMER.id\"))\n customer = db.relationship(\"Customer\")\n delivery_session_id = db.Column(db.Integer,\n db.ForeignKey(\"TB_DELIVERY_SESSION.id\"),\n nullable=True)\n delivery_session = db.relationship(\"DeliverySession\",\n backref=\"store_bill_list\")\n delivery_task_id = db.Column(db.Integer,\n db.ForeignKey(\"TB_DELIVERY_TASK.id\"),\n nullable=True)\n delivery_task = db.relationship(\"DeliveryTask\", backref=\"store_bill_list\")\n create_time = db.Column(db.DateTime)\n printed = db.Column(db.Boolean, default=False)\n\n @property\n def unit_weight(self):\n try:\n return self.weight / float(self.quantity)\n except ZeroDivisionError:\n return 0\n\n def __init__(self, qir, create_time=None):\n self.qir = qir\n self.weight = qir.weight\n self.quantity = qir.quantity\n self.customer_id = qir.work_command.sub_order.order.goods_receipt \\\n .customer_id\n self.create_time = create_time or datetime.now()\n self.sub_order = qir.work_command.sub_order\n\n\n def __unicode__(self):\n return unicode(self.id)\n\n def __repr__(self):\n return \"<StoreBill %d>\" % self.id\n\nclass DeliveryTask(db.Model):\n __modelname__ = u\"发货任务\"\n __tablename__ = \"TB_DELIVERY_TASK\"\n\n id = db.Column(db.Integer, primary_key=True)\n delivery_session_id = db.Column(db.Integer,\n db.ForeignKey(\"TB_DELIVERY_SESSION.id\"))\n actor_id = db.Column(db.Integer, db.ForeignKey(\"TB_USER.id\"))\n actor = db.relationship(\"User\")\n create_time = db.Column(db.DateTime, default=datetime.now)\n quantity = db.Column(db.Integer)\n weight = db.Column(db.Integer, default=0)\n returned_weight = db.Column(db.Integer, default=0)\n is_last = db.Column(db.Boolean, default=False)\n\n def __init__(self, delivery_session, actor_id,\n create_time=None):\n self.delivery_session = delivery_session\n self.actor_id = actor_id\n self.create_time = create_time or datetime.now()\n\n @property\n def customer(self):\n if self.store_bill_list:\n return self.store_bill_list[0].customer\n else:\n return \"\"\n\n @property\n def product(self):\n if self.store_bill_list:\n sb = self.store_bill_list[0]\n return sb.qir.work_command.sub_order.product\n else:\n return None\n\n def __unicode__(self):\n return unicode(self.id)\n\n def __repr__(self):\n return \"<DeliveryTask %d>\" % self.id\n\n\nclass Consignment(db.Model):\n __modelname__ = u\"发货单\"\n __tablename__ = \"TB_CONSIGNMENT\"\n\n id = db.Column(db.Integer, primary_key=True)\n consignment_id = db.Column(db.String(20), unique=True)\n delivery_session_id = db.Column(db.Integer,\n db.ForeignKey(\"TB_DELIVERY_SESSION.id\"))\n delivery_session = db.relationship(\"DeliverySession\",\n backref=\"consignment_list\")\n actor_id = db.Column(db.Integer, db.ForeignKey(\"TB_USER.id\"))\n actor = db.relationship(\"User\")\n create_time = db.Column(db.DateTime, default=datetime.now)\n customer_id = db.Column(db.Integer, db.ForeignKey(\"TB_CUSTOMER.id\"))\n customer = db.relationship(\"Customer\")\n pay_in_cash = db.Column(db.Boolean, default=False)\n is_paid = db.Column(db.Boolean, default=False)\n notes = db.Column(db.String(256))\n MSSQL_ID = db.Column(db.Integer)\n stale = db.Column(db.Boolean, default=False)\n\n def __init__(self, customer, delivery_session, pay_in_cash,\n create_time=None):\n self.delivery_session = delivery_session\n self.customer = customer\n self.pay_in_cash = pay_in_cash\n self.create_time = create_time or datetime.now()\n self.consignment_id = self.id_generator()\n\n def id_generator(self):\n return self.create_time.strftime('%Y%m%d%H%M%S%f')\n\n def __unicode__(self):\n return unicode(self.consignment_id)\n\n def __repr__(self):\n return \"<Consignment %d>\" % self.id\n\n\nclass Procedure(db.Model):\n __modelname__ = u\"工序\"\n __tablename__ = \"TB_PROCEDURE\"\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(32), unique=True)\n department_list = db.relationship(\"Department\",\n secondary=procedure_and_department_table,\n backref=\"procedure_list\", doc=u\"只有这里罗列的车间允许执行此工序\")\n\n def __unicode__(self):\n return self.name\n\n def __repr__(self):\n return \"<Procedure %d>\" % self.id\n\n\nclass Deduction(db.Model):\n __modelname__ = u\"扣重记录\"\n __tablename__ = \"TB_DEDUCTION\"\n\n id = db.Column(db.Integer, primary_key=True)\n weight = db.Column(db.Integer, doc=u\"单位为公斤\", nullable=False)\n work_command_id = db.Column(db.Integer,\n db.ForeignKey(\"TB_WORK_COMMAND.id\"))\n work_command = db.relationship(\"WorkCommand\", backref=\"deduction_list\")\n team_id = db.Column(db.Integer, db.ForeignKey(\"TB_TEAM.id\"),\n nullable=False)\n team = db.relationship(\"Team\", backref=\"deduction_list\")\n actor_id = db.Column(db.Integer, db.ForeignKey(\"TB_USER.id\"),\n nullable=False)\n actor = db.relationship(User)\n create_time = db.Column(db.DateTime, default=datetime.now)\n remark = db.Column(db.String(256))\n\n def __init__(self, weight=None, actor=None, team=None, work_command=None,\n create_time=None, remark=None):\n self.weight = weight\n self.work_command = work_command\n self.actor = actor\n self.team = team\n self.create_time = create_time or datetime.now()\n self.remark = remark\n\n def __unicode__(self):\n return unicode(self.id)\n\n def __repr__(self):\n return \"<Deduction %d>\" % self.id\n\n\nclass ConsignmentProduct(db.Model):\n __modelname__ = u\"发货单产品\"\n __tablename__ = \"TB_CONSIGNMENT_PRODUCT\"\n\n id = db.Column(db.Integer, primary_key=True)\n consignment_id = db.Column(db.Integer, db.ForeignKey(\"TB_CONSIGNMENT.id\"),\n nullable=False)\n consignment = db.relationship(\"Consignment\", backref=db.backref(\"product_list\", cascade=\"all, delete-orphan\"))\n product_id = db.Column(db.Integer, db.ForeignKey(\"TB_PRODUCT.id\"),\n nullable=False)\n product = db.relationship(\"Product\")\n delivery_task_id = db.Column(db.Integer,\n db.ForeignKey(\"TB_DELIVERY_TASK.id\"),\n nullable=False)\n delivery_task = db.relationship(\"DeliveryTask\")\n weight = db.Column(db.Integer)\n quantity = db.Column(db.Integer)\n unit = db.Column(db.String(16), default=u\"桶\")\n spec = db.Column(db.String(64))\n type = db.Column(db.String(64))\n returned_weight = db.Column(db.Integer)\n team_id = db.Column(db.Integer, db.ForeignKey(\"TB_TEAM.id\"))\n team = db.relationship(\"Team\")\n\n def __init__(self, product, delivery_task, consignment):\n self.product = product\n self.delivery_task = delivery_task\n self.consignment = consignment\n\n def __unicode__(self):\n return unicode(self.id)\n\n def __repr__(self):\n return \"<DeliveryProduct %d>\" % self.id\n\n\nclass Plate(db.Model):\n __modelname__ = u\"车辆\"\n __col_desc__ = {\n u\"车牌号\": \"name\"\n }\n __tablename__ = \"TB_PLATE\"\n\n name = db.Column(db.String(64), primary_key=True)\n\n def __init__(self, name):\n self.name = name\n\n def __unicode__(self):\n return self.name\n\n def __repr__(self):\n return \"<Plate %s>\" % self.name\n\nclass Log(db.Model):\n __modelname__ = u\"操作记录\"\n __tablename__ = \"TB_LOG\"\n\n # MAIN PART\n id = db.Column(db.Integer, primary_key=True)\n actor_id = db.Column(db.Integer, db.ForeignKey(\"TB_USER.id\"))\n actor = db.relationship(\"User\")\n obj_cls = db.Column(db.String(64))\n obj_pk = db.Column(db.String(64))\n obj = db.Column(db.String(64))\n action = db.Column(db.String(64))\n create_time = db.Column(db.DateTime, default=datetime.now)\n\n\n # SUPPLEMENT PART\n name = db.Column(db.String(64))\n level = db.Column(db.String(64))\n module = db.Column(db.String(64))\n func_name = db.Column(db.String(64))\n line_no = db.Column(db.Integer)\n thread = db.Column(db.Integer)\n thread_name = db.Column(db.String(64))\n process = db.Column(db.Integer)\n message = db.Column(db.String(256))\n args = db.Column(db.String(64))\n extra = db.Column(db.String(64))\n\n\n def __unicode__(self):\n return u\"[%s]: 用户%s对%s(%s)执行了(%s)操作\" % (\n self.create_time.strftime(\"%Y-%m-%d %H:%M:%S\"), self.actor.username,\n self.obj_cls, self.obj, self.action)\n\nclass TODO(db.Model):\n __modelname__ = u\"待办事项\"\n __tablename__ = \"TB_TODO\"\n\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer, db.ForeignKey(\"TB_USER.id\"))\n user = db.relationship(\"User\", primaryjoin=\"TODO.user_id==User.id\")\n obj_pk = db.Column(db.String(64))\n create_time = db.Column(db.DateTime, default=datetime.now)\n actor_id = db.Column(db.Integer, db.ForeignKey(\"TB_USER.id\"))\n actor = db.relationship(\"User\", primaryjoin=\"TODO.actor_id==User.id\")\n action = db.Column(db.String(64))\n priority = db.Column(db.Integer)\n msg = db.Column(db.String(128))\n context_url = db.Column(db.String(256))\n\n\nclass Config(db.Model):\n __modelname__ = u\"配置项\"\n __tablename__ = \"TB_CONFIG\"\n\n id = db.Column(db.Integer, primary_key=True)\n property_name = db.Column(db.String(64), nullable=False)\n property_desc = db.Column(db.String(64))\n property_value = db.Column(db.String(64), nullable=False)\n\n def __unicode__(self):\n return self.property_name\n\n\nfrom yawf.node_mixin import NodeMixin\n\n\nclass Node(db.Model, NodeMixin):\n __tablename__ = 'TB_NODE'\n __modelname__ = '工作流节点'\n\n @declared_attr\n def handler_group_id(self):\n return db.Column(db.Integer, db.ForeignKey('TB_GROUP.id'))\n\n @declared_attr\n def handler_group(self):\n return db.relationship('Group')\n\n" }, { "alpha_fraction": 0.5873016119003296, "alphanum_fraction": 0.5951653122901917, "avg_line_length": 43.303226470947266, "blob_id": "7efc5e7861d4f52e54b3e70b30e1d199a0654b4a", "content_id": "4b75c8dad6983716164d18ca9faecfbf869325ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7243, "license_type": "no_license", "max_line_length": 125, "num_lines": 155, "path": "/lite_mms/portal/delivery_ws/webservices.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nimport json\nfrom datetime import datetime\n\nfrom flask import request\nfrom flask.ext.login import current_user\nfrom flask.ext.principal import PermissionDenied\n\nimport yawf\n\nfrom lite_mms.utilities import _\nfrom lite_mms.portal.delivery_ws import delivery_ws\nfrom lite_mms.utilities import to_timestamp, get_or_404\nfrom lite_mms.utilities.decorators import (webservice_call, login_required_webservice, \n permission_required_webservice)\nimport lite_mms.apis as apis\nfrom lite_mms import models\nfrom lite_mms import database\nfrom lite_mms import constants\nfrom lite_mms.permissions.roles import LoaderPermission\n\n\n@delivery_ws.route(\"/delivery-session-list\", methods=[\"GET\"])\n@webservice_call(\"json\")\n@login_required_webservice\ndef delivery_session_list():\n \"\"\"\n get **unfinished** delivery sessions from database, accept no arguments\n \"\"\"\n import lite_mms.apis as apis\n delivery_sessions, total_cnt = apis.delivery.get_delivery_session_list(unfinished_only=True)\n data = [{'plateNumber': ds.plate, 'sessionID': ds.id, 'isLocked': int(ds.is_locked)} for ds in\n delivery_sessions]\n return json.dumps(data)\n\n\n@delivery_ws.route(\"/delivery-session\", methods=[\"GET\"])\n@webservice_call(\"json\")\n@login_required_webservice\ndef delivery_session():\n \"\"\"\n get delivery session from database\n \"\"\"\n _id = request.args.get(\"id\", type=int)\n if not _id:\n return _(u\"需要id字段\"), 403\n import lite_mms.apis as apis\n\n ds = apis.delivery.get_delivery_session(_id)\n if not ds:\n return _(u\"没有如下发货会话\") + str(_id), 404\n ret = dict(id=ds.id, plate=ds.plate)\n # store_bills是个两层结构,第一层是order,第二层主键是suborder\n store_bills = {}\n for sb in ds.store_bill_list:\n if not sb.delivery_task: # not delivered yet\n sub_order_2_store_bill = store_bills.setdefault(str(sb.sub_order.order.customer_order_number), {})\n sb_list = sub_order_2_store_bill.setdefault(sb.sub_order.id, [])\n sb_list.append(dict(id=sb.id, harbor=sb.harbor.name,\n product_name=sb.product_name,\n spec=sb.sub_order.spec,\n type=sb.sub_order.type,\n customer_name=sb.customer.name,\n pic_url=sb.pic_url, unit=sb.sub_order.unit,\n weight=sb.weight))\n ret.update(store_bills=store_bills)\n return json.dumps(ret)\n\n\n@delivery_ws.route(\"/delivery-task\", methods=[\"POST\"])\n@webservice_call(\"json\")\n@permission_required_webservice(LoaderPermission)\ndef delivery_task():\n is_finished = request.args.get(\"is_finished\", type=int)\n remain = request.args.get(\"remain\", type=int)\n\n json_sb_list = json.loads(request.data)\n if len(json_sb_list) == 0:\n return _(u\"至少需要一个仓单\"), 403\n finished_store_bill_id_list = []\n unfinished_store_bill_id_list = []\n for json_sb in json_sb_list:\n if json_sb[\"is_finished\"]:\n try:\n finished_store_bill_id_list.append(int(json_sb[\"store_bill_id\"]))\n except ValueError:\n return _(u\"仓单id只能为非整数\"), 403\n else:\n try:\n unfinished_store_bill_id_list.append(int(json_sb[\"store_bill_id\"]))\n except ValueError:\n return _(u\"仓单id只能为非整数\"), 403\n if len(unfinished_store_bill_id_list) > 1:\n return _(u\"最多只有一个仓单可以部分完成\"), 403\n if unfinished_store_bill_id_list:\n if not remain:\n return _(u\"需要remain字段\"), 403\n\n delivery_session_id = request.args.get(\"sid\", type=int)\n\n if yawf.token_bound(constants.work_flow.DELIVERY_TASK_WITH_ABNORMAL_WEIGHT, str(delivery_session_id)):\n return u'本卸货会话有待处理的工作流,请先敦促工作人员处理该工作流', 403\n\n ds = apis.delivery.get_delivery_session(delivery_session_id)\n if not ds:\n return _(u\"需要发货会话字段\"), 403\n id_list = [store_bill.id for store_bill in ds.store_bill_list]\n for id_ in finished_store_bill_id_list + unfinished_store_bill_id_list:\n if id_ not in id_list:\n return _(u\"仓单%s未关联到发货会话%s\" % (id_, delivery_session_id)), 403\n\n unfinished_store_bill = get_or_404(models.StoreBill,\n unfinished_store_bill_id_list[0]) if unfinished_store_bill_id_list else None\n if unfinished_store_bill and apis.delivery.store_bill_remain_unacceptable(unfinished_store_bill, remain):\n try:\n doc = database.codernity_db.insert(dict(delivery_session_id=delivery_session_id,\n remain=remain,\n finished_store_bill_id_list=finished_store_bill_id_list,\n unfinished_store_bill_id=unfinished_store_bill.id,\n loader_id=current_user.id,\n is_last_task=is_finished))\n # 保存token,以避免重复提交工作流, 显然,对于一个卸货会话而言,只能同时存在一个正在处理的工作流\n work_flow = yawf.new_work_flow(constants.work_flow.DELIVERY_TASK_WITH_ABNORMAL_WEIGHT,\n lambda work_flow: models.Node(work_flow=work_flow,\n name=u\"生成异常剩余重量的发货任务\",\n policy_name='CreateDeliveryTaskWithAbnormalWeight'),\n tag_creator=lambda work_flow: doc['_id'], token=str(delivery_session_id))\n work_flow.start()\n except yawf.exceptions.WorkFlowDelayed, e:\n return \"\", 201\n else:\n finished_store_bill_list = [get_or_404(models.StoreBill, store_bill_id) for store_bill_id in\n finished_store_bill_id_list]\n try:\n dt = create_delivery_task(ds, remain, finished_store_bill_list, unfinished_store_bill,\n current_user, is_finished)\n ret = dict(id=dt.actor_id, actor_id=dt.actor_id, store_bill_id_list=dt.store_bill_id_list)\n return json.dumps(ret)\n except KeyError:\n return _(u\"不能添加发货任务\"), 403\n except (ValueError, PermissionDenied) as e:\n return unicode(e), 403\n\n\ndef create_delivery_task(ds, remain, finished_store_bill_id_list, unfinished_store_bill, loader,\n is_finished):\n from lite_mms.portal.delivery.fsm import fsm\n\n fsm.reset_obj(ds)\n fsm.next(constants.delivery.ACT_LOAD, loader)\n dt = apis.delivery.new_delivery_task(loader.id, finished_store_bill_id_list, unfinished_store_bill, remain)\n if is_finished: # 发货会话结束\n dt.update(is_last=True)\n dt.delivery_session.update(finish_time=to_timestamp(datetime.now()))\n return dt\n" }, { "alpha_fraction": 0.7597172856330872, "alphanum_fraction": 0.7632508873939514, "avg_line_length": 24.636363983154297, "blob_id": "b3f9442711473486c924972d31653051e9717e78", "content_id": "ffe640da1ed41e476c4ec3a8c2c96510d54303cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 299, "license_type": "no_license", "max_line_length": 51, "num_lines": 11, "path": "/lite_mms/permissions/work_flow.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\nfrom collections import namedtuple\nfrom flask.ext.principal import Permission\n\nWorkFlowManagement = namedtuple(\"user\", [\"method\"])\n\nHandleNodeNeed = WorkFlowManagement('handle_node')\n\nhandle_node = Permission(HandleNodeNeed)\nhandle_node.brief = u'处理工作流的权限'\n\n" }, { "alpha_fraction": 0.8005780577659607, "alphanum_fraction": 0.8020231127738953, "avg_line_length": 26.68000030517578, "blob_id": "6244bda0bd78c240cd037f64dc274d668dedaae6", "content_id": "f0bc5668643636ea0d0d9fbd4318c4123ec499ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 748, "license_type": "no_license", "max_line_length": 57, "num_lines": 25, "path": "/lite_mms/permissions/deduction.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nfrom collections import namedtuple\nfrom flask.ext.principal import Permission\n\nDeductionManagement = namedtuple(\"deduction\", [\"method\"])\n\nViewDeduction = DeductionManagement(\"view_deduction\")\n\nAddDeduction = DeductionManagement(\"add_deduction\")\n\nEditDeduction = DeductionManagement(\"edit_deduction\")\n\nDeleteDeduction = DeductionManagement(\"delete_deduction\")\n\nview_deduction = Permission(ViewDeduction)\nview_deduction.brief = u\"查看扣重的权限\"\n\naddDeduction = Permission(AddDeduction)\naddDeduction.brief = u\"增加扣重的权限\"\n\neditDeduction = Permission(EditDeduction)\neditDeduction.brief = u'修改扣重的权限'\n\ndeleteDeduction = Permission(DeleteDeduction)\ndeleteDeduction.brief = u'删除扣重的权限'\n" }, { "alpha_fraction": 0.7694703936576843, "alphanum_fraction": 0.7710280418395996, "avg_line_length": 28.18181800842285, "blob_id": "65dc540452f0a5b3a6536ff2300ec35151f70f80", "content_id": "e7185c90787ab3812128e86fdbfd1c701ca26607", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 730, "license_type": "no_license", "max_line_length": 64, "num_lines": 22, "path": "/lite_mms/permissions/order.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n针对订单对象的权限,将用户管理相关的权限\n\"\"\"\nfrom collections import namedtuple\nfrom flask.ext.principal import Permission\n\nSubOrderManagement = namedtuple(\"sub_order\", [\"method\"])\n\nEditSubOrderWeight = SubOrderManagement(\"edit_sub_order_weight\")\n\nedit_sub_order_weight = Permission(EditSubOrderWeight) \nedit_sub_order_weight.brief = u\"修改子订单重量的权限\"\n\nOrderManagement = namedtuple(\"order\", [\"method\"])\nViewOrder = OrderManagement(\"view_order\")\nScheduleOrder = OrderManagement(\"schedule_order\")\n\nview_order = Permission(ViewOrder)\nview_order.brief = u\"查看订单的权限\"\nschedule_order = Permission(ScheduleOrder)\nschedule_order.brief = u\"调度订单的权限\"\n" }, { "alpha_fraction": 0.6357465982437134, "alphanum_fraction": 0.7285068035125732, "avg_line_length": 20.047618865966797, "blob_id": "133eb5cfe70d1b889bec68f85b38dc0b79a112e0", "content_id": "227fb5f3c1c17cf897276c7c6feecbc14d8c90a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 442, "license_type": "no_license", "max_line_length": 86, "num_lines": 21, "path": "/alembic/versions/3fa49daed5cf_add_column_enabled_t.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"add column enabled to Customer\n\nRevision ID: 3fa49daed5cf\nRevises: 2c6eb11ac2d7\nCreate Date: 2013-07-05 10:25:47.646022\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '3fa49daed5cf'\ndown_revision = '2c6eb11ac2d7'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.add_column(\"TB_CUSTOMER\", sa.Column(\"enabled\", sa.Boolean, server_default='1'))\n\ndef downgrade():\n op.drop_column('TB_CUSTOMER', 'enabled')\n" }, { "alpha_fraction": 0.6610169410705566, "alphanum_fraction": 0.6610169410705566, "avg_line_length": 27, "blob_id": "4d3c91c4dbb6a059b445f7d00e445efd9686960a", "content_id": "f9588c42fc42351b0ad063893d0c97f601cb9ada", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 59, "license_type": "no_license", "max_line_length": 41, "num_lines": 2, "path": "/docs/source/constants/groups.rst", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\r\n.. automodule:: lite_mms.constants.groups\r\n :members: " }, { "alpha_fraction": 0.6517379879951477, "alphanum_fraction": 0.6557486653327942, "avg_line_length": 38.3684196472168, "blob_id": "dad5bb1adc509f557156a2251ecffa5885f565fc", "content_id": "25fe2987364f7a70b7be563c7362f32988f57aac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1504, "license_type": "no_license", "max_line_length": 77, "num_lines": 38, "path": "/lite_mms/portal/search/views.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n@author: Yangminghua\n@version: $\n\"\"\"\nfrom flask import request\nfrom lite_mms.permissions import CargoClerkPermission\nfrom lite_mms.permissions.order import view_order, schedule_order\nfrom lite_mms.permissions.work_command import view_work_command\nfrom lite_mms.utilities import decorators\nfrom lite_mms.portal.search import search_page\n\n@search_page.route(\"/search\")\[email protected](\"/search/search-result.html\")\[email protected]_bar_set\ndef search():\n import lite_mms.apis as apis\n\n keywords = request.args.get(\"content\")\n wc_list = order_list = unload_session_list = delivery_session_list = None\n if keywords:\n if view_order.can() or schedule_order.can():\n order_list = apis.order.get_order_list(\n customer_order_number=keywords)[0]\n if view_work_command.can():\n wc_list = apis.manufacture.get_work_command_list(\n keywords=keywords, status_list=0)[0]\n if CargoClerkPermission.can():\n unload_session_list = apis.cargo.get_unload_session_list(\n keywords=keywords)[0]\n delivery_session_list = apis.delivery.get_delivery_session_list(\n keywords=keywords)[0]\n return dict(titlename=u'搜索结果',\n order_list=order_list,\n keywords=keywords,\n work_command_list=wc_list,\n unload_session_list=unload_session_list,\n delivery_session_list=delivery_session_list)\n" }, { "alpha_fraction": 0.6130403876304626, "alphanum_fraction": 0.7321048974990845, "avg_line_length": 22.915254592895508, "blob_id": "19963c687a18b1b2ae27538c191da2098d5e3627", "content_id": "653d8fdb073088121354377d4e007d1cfa823c78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1411, "license_type": "no_license", "max_line_length": 83, "num_lines": 59, "path": "/requirements.txt", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "Babel>=0.9.6\nFabric>=1.5.1\nFlask-Babel>=0.8\nFlask-DebugToolbar>=0.8.0\nFlask-Login>=0.2.4\n-e git+https://github.com/xiechao06/Flask-NavBar.git#egg=Flask_NavBar-dev\nFlask-Principal>=0.3.3\n-e git+https://github.com/xiechao06/Flask-Report.git#egg=Flask_Report-dev\nFlask-SQLAlchemy>=0.16\nFlask-WTF>=0.8.3\nHamlish-Jinja>=0.3.0\nJinja2>=2.7\nMako>=0.8.1\nMarkupSafe>=0.18\nMySQL-python>=1.2.3\nPyYAML>=3.10\nPygments>=1.6\nSQLAlchemy>=0.8.1\nWTForms>=1.0.2\nWerkzeug>=0.9.1\nalembic>=0.5.0\nargparse>=1.2.1\nbeautifulsoup4>=4.1.3\nblinker>=1.2\ncolorama>=0.2.4\ncssselect>=0.7.1\ndecorator>=3.4.0\ndistribute>=0.6.24\ndocutils>=0.9.1\nimport-file>=1.11\nitsdangerous>=0.21\n-e git+https://github.com/xiechao06/lite-sm.git#egg=lite_sm-dev\nlockfile>=0.9.1\nlogilab-astng>=0.24.1\nlogilab-common>=0.58.3\nmock>=1.0.1\n-e git+https://github.com/xiechao06/nav-bar.git#egg=nav_bar-dev\nnose>=1.2.1\nparamiko>=1.9.0\npath.py>=3.0.1\npy>=1.4.12\npycrypto>=2.6\npyflakes>=0.7.2\npytest>=2.3.4\npytz>=2013b\nreportlab>=2.7\nspeaklater>=1.3\ntransaction>=1.3.0\ntwill>=0.9\nwsgiref>=0.1.2\nzope.interface>=4.0.5\nAPScheduler>=2.1.1\nFlask-Mail>=0.9.0\n-e git+https://github.com/xiechao06/WorkFlowRepr.git#egg=work_flow_repr-dev\nCodernityDB>=0.4.2\n-e git+https://github.com/xiechao06/pyfeature.git#egg=pyfeature-dev\n-e git+https://github.com/xiechao06/Flask-DataBrowser.git#egg=Flask_DataBrowser-dev\n-e git+https://github.com/xiechao06/yawf.git#egg=yawf-dev\nPillow>=2.2.1\n" }, { "alpha_fraction": 0.5970330238342285, "alphanum_fraction": 0.6000605225563049, "avg_line_length": 44.24657440185547, "blob_id": "20c49f67fa0c4db6060b49b52488c493888dba41", "content_id": "3d10ec9c28b16364067471d0210d1786cc0ae615", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3651, "license_type": "no_license", "max_line_length": 136, "num_lines": 73, "path": "/lite_mms/portal/order/filters.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport numbers\nfrom sqlalchemy import or_\nfrom flask.ext.databrowser import filters\nfrom lite_mms.models import Order, WorkCommand, SubOrder\nfrom lite_mms import constants\n\nclass CategoryFilter(filters.BaseFilter):\n\n UNDISPATCHED_ONLY = 1\n DELIVERABLE_ONLY = 2\n ACCOUNTABLE_ONLY = 3\n\n def set_sa_criterion(self, query):\n from lite_mms import models\n from sqlalchemy import and_\n from lite_mms import constants\n if isinstance(self.value, numbers.Number) or self.value.isdigit():\n self.value = int(self.value)\n if self.value == self.ACCOUNTABLE_ONLY or self.value == self.DELIVERABLE_ONLY:\n # 只要有一个仓单尚未发货\n query = query.filter(models.Order.sub_order_list.any(\n models.SubOrder.store_bill_list.any(\n and_(models.StoreBill.weight > 0,\n models.StoreBill.delivery_task_id == None))))\n if self.value == self.ACCOUNTABLE_ONLY: # 可盘点的订单要求所有的工单都已经生产完毕\n # 所有的子订单都已经排产 == 不存在子订单,其剩余质量>0\n query = query.filter(\n ~models.Order.sub_order_list.any(\n models.SubOrder.remaining_quantity > 0))\n # 所有的子订单的工单都已经生成完毕==不存在子订单,其有工单未完成\n query = query.filter(~models.Order.sub_order_list.any(\n models.SubOrder.work_command_list.any(\n models.WorkCommand.status != constants.work_command\n .STATUS_FINISHED)))\n elif self.value == self.UNDISPATCHED_ONLY:\n query = query.filter(~models.Order.dispatched)\n elif self.value == self.WARNING_ONLY:\n # 所有的子订单都已经排产 == 不存在子订单,其剩余质量>0\n query = query.filter(\n ~models.Order.sub_order_list.any(\n models.SubOrder.remaining_quantity > 0))\n # 所有的子订单的工单都已经生成完毕==不存在子订单,其有工单未完成\n query = query.filter(~models.Order.sub_order_list.any(\n models.SubOrder.work_command_list.any(\n models.WorkCommand.status != constants.work_command\n .STATUS_FINISHED)))\n\n\n return query\n\ncategory_filter = CategoryFilter(\"category\", name=u\"是\", options=[(CategoryFilter.UNDISPATCHED_ONLY, u\"仅展示待下发订单\"),\n (CategoryFilter.DELIVERABLE_ONLY, u\"仅展示可发货订单\"), (CategoryFilter.ACCOUNTABLE_ONLY, u\"仅展示可盘点订单\")],\n hidden=True)\n\n\ndef only_finished_filter_test(col):\n manufacturing_status_set = {constants.work_command.STATUS_ASSIGNING,\n constants.work_command.STATUS_ENDING,\n constants.work_command.STATUS_LOCKED}\n return col.any(or_(SubOrder.work_command_list.any(WorkCommand.status.in_(manufacturing_status_set)), SubOrder.remaining_quantity>0))\n\nonly_unfinished_filter = filters.Only(\n 'sub_order_list', display_col_name=u'仅展示未生产完毕订单',\n test=only_finished_filter_test, notation='__unfinished_only'\n)\n\nclass NotContains(filters.BaseFilter):\n __notation__ = \"__not_contains\"\n __operator__ = lambda self, attr, value: ~attr.like(value.join([\"%\", \"%\"]))\n\nno_individual = NotContains(u'goods_receipt.customer.name', value=u'个体')\n" }, { "alpha_fraction": 0.7166236042976379, "alphanum_fraction": 0.7192075848579407, "avg_line_length": 29.578947067260742, "blob_id": "ce62e4ba4b546f9981cbe47635505bdc968550bc", "content_id": "a64e3b40a83fc2f528523abaabad6cbfe81a341c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1239, "license_type": "no_license", "max_line_length": 132, "num_lines": 38, "path": "/lite_mms/portal/dashboard/widgets.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom . import Widget, DASHBOARD_WIDGETS\nfrom sqlalchemy import func\n\nfrom lite_mms import models, constants\nfrom lite_mms.database import db\nfrom lite_mms.permissions.roles import AdminPermission\n\n\nclass ManufactureWidget(Widget):\n def query(self):\n return db.session.query(func.sum(models.WorkCommand.org_weight).label(u\"生成中重量\")).filter(\n models.WorkCommand.status != constants.work_command.STATUS_FINISHED)\n\n @property\n def data(self):\n return int(self.query().first()[0])\n\n def try_view(self):\n AdminPermission.test()\n\nmanufacture_widget = ManufactureWidget(name=u\"生产中重量\", description=u\"生成中工单的总重量\")\n\n\nclass ToDeliveryWidget(Widget):\n def query(self):\n return db.session.query(func.sum(models.StoreBill.weight).label(u\"待发货重量\")).filter(models.StoreBill.delivery_task_id == None)\n\n @property\n def data(self):\n return int(self.query().first()[0])\n\n def try_view(self):\n AdminPermission.test()\n\nto_delivery_widget = ToDeliveryWidget(name=u\"待发货重量\", description=u\"待发货的仓单的总重量\")\nDASHBOARD_WIDGETS.append(manufacture_widget)\nDASHBOARD_WIDGETS.append(to_delivery_widget)" }, { "alpha_fraction": 0.665142297744751, "alphanum_fraction": 0.6722561120986938, "avg_line_length": 34.78181838989258, "blob_id": "915f8567831f3f083b40d1d152e8344d16dae5fb", "content_id": "a98e08a7553b06ce8baf46d68c7972beda8f1c61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2056, "license_type": "no_license", "max_line_length": 98, "num_lines": 55, "path": "/lite_mms/features/given.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom lettuce import step, world\nfrom hashlib import md5\nfrom collections import namedtuple\n\n@step(u'创建如下权限:')\ndef create_permissions(step):\n from lite_mms import models\n for perm_dict in step.hashes:\n perm = models.Permission(name=perm_dict[\"name\"])\n world.db.session.add(perm)\n world.db.session.commit()\n\n@step(u'创建用户组\"(.*)\", 关联如下权限:')\ndef create_group_with_permissions(step, group_name):\n from lite_mms import models\n group = models.Group(group_name)\n import random\n group.id = random.randint(99999, 199999)\n for perm_dict in step.hashes:\n perm = models.Permission.query.filter(models.Permission.name==perm_dict[\"name\"]).one()\n group.permissions.append(perm)\n world.db.session.add(group)\n world.db.session.commit()\n\n@step(u'创建如下用户:')\ndef create_user(step):\n from lite_mms import models\n for user_dict in step.hashes:\n group = models.Group.query.filter(models.Group.name==user_dict[\"group\"]).one()\n user = models.User(user_dict[\"username\"], md5(user_dict[\"password\"]).hexdigest(), [group])\n world.db.session.add(user)\n world.db.session.commit()\n\n@step(u'在系统中安装如下权限:')\ndef install_permissions(step):\n from lite_mms.permissions import install_permission, reset_permissions\n for perm_dict in step.hashes:\n install_permission(perm_dict[\"permission\"], [namedtuple(perm_dict[\"need\"], [])], \"\")\n\n@step(u\"生成如下用户组:\")\ndef create_groups(step):\n from lite_mms import models\n for group_dict in step.hashes:\n group = models.Group(group_dict[\"group_name\"], group_dict[\"default_url\"])\n world.db.session.add(group)\n world.db.session.commit()\n\n@step(u\"创建如下view:\")\ndef create_views(step):\n from flask import url_for\n from lite_mms.basemain import app\n for view_dict in step.hashes:\n exec('def %s(): return \"%s\"' % (view_dict[\"name\"], view_dict[\"content\"]))\n app.route(view_dict[\"url\"])(locals()[view_dict[\"name\"]])\n" }, { "alpha_fraction": 0.6111111044883728, "alphanum_fraction": 0.6755555272102356, "avg_line_length": 19.454545974731445, "blob_id": "11e9e1c95a9597514e26f7af285624e38e619e43", "content_id": "47c023d30297342eb2c940394c8e164eb3eff97d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 450, "license_type": "no_license", "max_line_length": 76, "num_lines": 22, "path": "/alembic/versions/d9c0f19bdf7_add_status.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"add is_last to unload task\n\nRevision ID: 51242e27bc6\nRevises: d9c0f19bdf3\nCreate Date: 2013-03-26 11:03:42.724269\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'd9c0f19bdf7'\ndown_revision = 'd9c0f19bdf6'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.add_column(\"TB_UNLOAD_SESSION\",\n sa.Column(\"status\", sa.Integer, default=1, nullable=False))\n\ndef downgrade():\n op.drop_column(\"TB_UNLOAD_SESSION\", \"status\")\n" }, { "alpha_fraction": 0.5923721790313721, "alphanum_fraction": 0.5926426649093628, "avg_line_length": 47.02597427368164, "blob_id": "f878f77b1dae446d6030f8a81a4fb1fad592e2e7", "content_id": "23e5bb2fb16440fc11a3202f9978f6870a7953c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3925, "license_type": "no_license", "max_line_length": 110, "num_lines": 77, "path": "/lite_mms/portal/admin/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nimport socket\n\nfrom flask import Blueprint, request, url_for, redirect\nfrom lite_mms.basemain import data_browser, nav_bar\n\nadmin_page = Blueprint(\"admin\", __name__, static_folder=\"static\", template_folder=\"templates\")\n\nfrom lite_mms.portal.admin.views import (user_model_view, group_model_view,\n department_model_view,\n team_model_view, harbor_model_view,\n procedure_model_view, config_model_view,\n customer_model_view, product_model_view)\nfrom nav_bar import NavBar\n\nsub_nav_bar = NavBar()\nsub_nav_bar.register(lambda: user_model_view.url_for_list(), u\"用户管理\",\n enabler=lambda: user_model_view.within_domain(request.url, \"admin\"), group=u\"对象管理\")\nsub_nav_bar.register(lambda: group_model_view.url_for_list(), u\"用户组管理\",\n enabler=lambda: group_model_view.within_domain(request.url, \"admin\"), group=u\"对象管理\")\nsub_nav_bar.register(lambda: customer_model_view.url_for_list(), u\"客户管理\",\n enabler=lambda: customer_model_view.within_domain(request.url, \"admin\"), group=u\"对象管理\")\nsub_nav_bar.register(lambda: department_model_view.url_for_list(), u\"车间管理\",\n enabler=lambda: department_model_view.within_domain(request.url, \"admin\"), group=u\"对象管理\")\nsub_nav_bar.register(lambda: team_model_view.url_for_list(), u\"班组管理\",\n enabler=lambda: team_model_view.within_domain(request.url, \"admin\"), group=u\"对象管理\")\nsub_nav_bar.register(lambda: harbor_model_view.url_for_list(), u\"装卸点管理\",\n enabler=lambda: harbor_model_view.within_domain(request.url, \"admin\"), group=u\"对象管理\")\nsub_nav_bar.register(lambda: procedure_model_view.url_for_list(), u\"工序管理\",\n enabler=lambda: procedure_model_view.within_domain(request.url, \"admin\"), group=u\"对象管理\")\nsub_nav_bar.register(lambda: product_model_view.url_for_list(), u\"产品管理\",\n enabler=lambda: product_model_view.within_domain(\n request.url, \"admin\"), group=u\"对象管理\")\nsub_nav_bar.register(lambda: config_model_view.url_for_list(), u\"配置项管理\",\n enabler=lambda: config_model_view.within_domain(\n request.url, \"admin\"), group=u\"对象管理\")\nsub_nav_bar.register(lambda: url_for(\"admin.broker_index\"), u\"数据导入\",\n enabler=lambda: \"admin/broker\" in request.url, group=u\"其它管理\")\n\n\n@admin_page.route(\"/\")\ndef index():\n return redirect(url_for(\"admin.user_list\"))\n\n\ndef _do_register(model_name, model_view):\n extra_params = {\n \"list_view\": {\n \"nav_bar\": nav_bar,\n \"sub_nav_bar\": sub_nav_bar,\n \"titlename\": model_name + u\"管理\",\n },\n \"create_view\": {\n \"nav_bar\": nav_bar,\n \"sub_nav_bar\": sub_nav_bar,\n \"titlename\": u\"创建\" + model_name,\n },\n \"form_view\": {\n \"nav_bar\": nav_bar,\n \"sub_nav_bar\": sub_nav_bar,\n \"titlename\": u\"编辑\" + model_name,\n }\n }\n data_browser.register_model_view(model_view, admin_page, extra_params=extra_params)\n\n\nfor mn, mv in [(u\"用户\", user_model_view), (u\"用户组\", group_model_view),\n (u\"车间\", department_model_view), (u\"班组\", team_model_view),\n (u\"装卸点\", harbor_model_view), (u\"工序\", procedure_model_view),\n (u\"配置项\", config_model_view), (u\"客户\", customer_model_view),\n (u\"产品\", product_model_view)]:\n _do_register(mn, mv)\n\n\n@admin_page.errorhandler(socket.error)\ndef connection_refused(e):\n return redirect(url_for(\"error\", errors=u\"无法连接\", detail=e))" }, { "alpha_fraction": 0.6794871687889099, "alphanum_fraction": 0.6794871687889099, "avg_line_length": 25, "blob_id": "659a167468c7e6599d48703a5dcc3de91e0cbec1", "content_id": "4b48a416f35b895f3ae1d4c69f3f95ff26f188f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 312, "license_type": "no_license", "max_line_length": 82, "num_lines": 12, "path": "/lite_mms/tools/add_uwsgi_app.sh", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#! /bin/sh\n# this script could be sudo\ncat << \"EOF\" > /etc/uwsgi/apps-available/lite-mms.xml\n<uwsgi>\n <uid>www-data</uid>\n <gid>www-data</gid>\n <socket>/tmp/lite-mms.sock</socket>\n <plugins>python</plugins>\n</uwsgi>\nEOF\n\nln -sf /etc/uwsgi/apps-available/lite-mms.xml /etc/uwsgi/apps-enabled/lite-mms.xml\n" }, { "alpha_fraction": 0.5497767329216003, "alphanum_fraction": 0.5526707172393799, "avg_line_length": 47.967613220214844, "blob_id": "c5535cd39c0239ec9a532eb2d38f04a70cfe51aa", "content_id": "ea2018405719f77a1be3bb3d51bd74fb330a74f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12514, "license_type": "no_license", "max_line_length": 119, "num_lines": 247, "path": "/lite_mms/portal/manufacture/views.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nfrom collections import OrderedDict\nfrom flask import url_for, request, render_template, abort, flash, redirect, json\n\nfrom flask.ext.databrowser import ModelView, filters, column_spec\nfrom flask.ext.login import login_required, current_user\nfrom flask.ext.principal import PermissionDenied\nfrom wtforms import Form, validators, HiddenField, BooleanField, TextField, IntegerField\n\nfrom lite_mms import constants\nfrom lite_mms.basemain import nav_bar\nfrom lite_mms.models import WorkCommand\nfrom lite_mms.apis.manufacture import get_wc_status_list, get_status_list, get_handle_type_list, get_department_list\nfrom lite_mms.permissions import SchedulerPermission\nfrom lite_mms.portal.manufacture import manufacture_page\n\n\nclass WorkCommandView(ModelView):\n __list_columns__ = [\"id\", \"sub_order.order.customer_order_number\", \"department\", \"team\", \"org_weight\", \"org_cnt\",\n \"sub_order.unit\", \"urgent\", \"sub_order.returned\", \"tech_req\", \"handle_type\", \"status\",\n \"procedure\", \"previous_procedure\", \"order.goods_receipt.customer\"]\n\n __column_labels__ = {\"id\": u\"编号\", \"department\": u\"车间\", \"team\": u\"班组\", \"sub_order.unit\": u\"单位\",\n \"sub_order.returned\": u\"退镀\", \"urgent\": u\"加急\", \"org_weight\": u\"重量(公斤)\", \"org_cnt\": u\"数量\",\n \"handle_type\": u\"处理类型\", \"tech_req\": u\"技术要求\", \"status\": u\"状态\", \"procedure\": u\"工序\",\n \"previous_procedure\": u\"上道工序\", \"sub_order.order.customer_order_number\": u\"订单编号\",\n \"sub_order\": u\"子订单编号\", \"order.goods_receipt.customer\": u\"客户\"}\n\n __default_order__ = (\"id\", \"desc\")\n\n __sortable_columns__ = [\"sub_order.order.customer_order_number\", \"urgent\", \"sub_order.returned\"]\n\n def preprocess(self, obj):\n from lite_mms import apis\n\n return apis.manufacture.WorkCommandWrapper(obj)\n\n def patch_row_attr(self, idx, row):\n if row.status != constants.work_command.STATUS_FINISHED and (row.urgent or row.sub_order.returned):\n return {\"class\": \"danger\", \"title\": u\"退镀或加急\"}\n\n from datetime import datetime, timedelta\n\n today = datetime.today()\n yesterday = today.date()\n week_ago = (today - timedelta(days=7)).date()\n _30days_ago = (today - timedelta(days=30)).date()\n\n class In_Filter(filters.BaseFilter):\n __notation__ = \"__in_ex\"\n\n def __operator__(self, attr, value):\n return attr.in_(set(value))\n\n __column_filters__ = [\n In_Filter(\"status\", u\"是\", options=[i[:2] for i in get_status_list()], display_col_name=u\"状态\"),\n filters.BiggerThan(\"create_time\", name=u\"在\", display_col_name=u\"创建时间\",\n options=[(yesterday, u'一天内'), (week_ago, u'一周内'), (_30days_ago, u'30天内')]),\n filters.Contains(\"sub_order.order.customer_order_number\", name=u\"包含\", display_col_name=u\"订单编号\"),\n filters.EqualTo(\"sub_order.order.id\", name=\"\", hidden=True),\n filters.Only(\"urgent\", display_col_name=u\"只展示加急\", test=lambda v: v == True, notation=\"__urgent\"),\n filters.Only(\"sub_order.returned\", display_col_name=u\"只展示退镀\", test=lambda v: v == True, notation=\"__returned\"),\n filters.EqualTo(\"department\", u\"是\")]\n\n f = lambda v, model: u\"<span class='text-danger'>是</span>\" if v else u\"否\"\n\n __column_formatters__ = {\n \"status\": lambda v, model: get_wc_status_list().get(v)[0],\n \"department\": lambda v, model: v if v else \"\",\n \"team\": lambda v, model: v if v else \"\",\n \"sub_order.returned\": f,\n \"urgent\": f,\n \"procedure\": lambda v, model: v if v else \"\",\n \"previous_procedure\": lambda v, model: v if v else \"\",\n \"handle_type\": lambda v, model: get_handle_type_list().get(v, u\"未知\")\n }\n\n def repr_obj(self, obj):\n return u\"\"\"\n <span>\n %(wc)s - <small>%(customer)s</small>\n <small class='pull-right text-muted'>\n %(datetime)s \n </small>\n </span> \n \"\"\" % {\"wc\": unicode(obj), \"customer\": obj.order.goods_receipt.customer,\n \"datetime\": obj.create_time.strftime(\"%m-%d %H:%M\")}\n\n def try_create(self):\n raise PermissionDenied\n\n @login_required\n def try_view(self, processed_objs=None):\n pass\n\n def try_edit(self, processed_objs=None):\n SchedulerPermission.test()\n if processed_objs and processed_objs[\n 0].status == constants.work_command.STATUS_DISPATCHING:\n return True\n else:\n raise PermissionDenied\n\n def edit_hint_message(self, obj, read_only=False):\n if read_only:\n if not SchedulerPermission.can():\n return u\"无修改订单的权限\"\n else:\n return u\"工单%d已进入生产流程,不能修改\" % obj.id\n else:\n return super(WorkCommandView, self).edit_hint_message(obj, read_only)\n\n def get_customized_actions(self, processed_objs=None):\n from .actions import schedule_action, retrieve_action\n\n def _get_status_filter(desc):\n for i in get_status_list():\n if i[1] == desc:\n return i[0]\n else:\n return None\n\n if processed_objs:\n if all(schedule_action.test_enabled(obj) == 0 for obj in processed_objs):\n return [schedule_action]\n elif all(retrieve_action.test_enabled(obj) == 0 for obj in processed_objs):\n return [retrieve_action]\n else:\n if self.__column_filters__[0].value == unicode(_get_status_filter(u\"待生产\")):\n return [schedule_action]\n elif self.__column_filters__[0].value == unicode(_get_status_filter(u\"生产中\")):\n return [retrieve_action]\n elif self.__column_filters__[0].has_value:\n return [schedule_action, retrieve_action]\n return []\n\n def get_form_columns(self, obj=None):\n\n form_columns = OrderedDict()\n c = column_spec.ColumnSpec(\"\", formatter=lambda v, obj: u\"%s-%s\" % (v.id, v.cause_name) if v else \"\")\n\n form_columns[u\"工单信息\"] = [column_spec.ColumnSpec(\"id\"), column_spec.ColumnSpec(\"org_weight\"),\n column_spec.ColumnSpec(\"org_cnt\"), column_spec.ColumnSpec(\"sub_order.unit\"),\n column_spec.ColumnSpec(\"sub_order.spec\", label=u\"规格\"),\n column_spec.ColumnSpec(\"sub_order.type\", label=u\"型号\"),\n \"urgent\", \"sub_order.returned\", \"tech_req\",\n column_spec.ColumnSpec(\"cause_name\", label=u\"产生原因\"),\n column_spec.ColumnSpec(\"previous_work_command\", label=u\"上级工单\",\n formatter=lambda v, obj: u\"%s-%s\" % (\n v.id, v.cause_name) if v else \"\"),\n column_spec.ListColumnSpec(\"next_work_command_list\", label=u\"下级工单\",\n item_col_spec=c),\n column_spec.PlaceHolderColumnSpec(\"log_list\", label=u\"日志\",\n template_fname=\"logs-snippet.html\")]\n form_columns[u\"加工信息\"] = [column_spec.ColumnSpec(\"department\"),\n column_spec.ColumnSpec(\"team\"),\n column_spec.ColumnSpec(\"procedure\"),\n column_spec.ColumnSpec(\"previous_procedure\"),\n column_spec.ColumnSpec(\"processed_weight\", label=u\"工序后重量\"),\n column_spec.ColumnSpec(\"processed_cnt\", label=u\"工序后数量\"),\n column_spec.ColumnSpec(\"status_name\", label=u\"状态\"),\n column_spec.ColumnSpec(\"completed_time\", label=u\"生产结束时间\"),\n column_spec.ColumnSpec(\"handle_type\", label=u\"处理类型\",\n formatter=lambda v, obj: get_handle_type_list().get(v, u\"未知\"))]\n if obj and obj.qir_list:\n from lite_mms.apis.quality_inspection import get_QI_result_list\n from lite_mms.portal.quality_inspection.views import qir_model_view\n\n def result(qir):\n for i in get_QI_result_list():\n if qir.result == i[0]:\n status = i[1]\n break\n else:\n status = u\"未知\"\n return u\"<a href='%s'>质检单%s%s了%s(公斤)</a>\" % (\n qir_model_view.url_for_object(qir, url=request.url), qir.id, status, qir.weight)\n\n form_columns[u\"质检信息\"] = [column_spec.ListColumnSpec(\"qir_list\", label=u\"质检结果\",\n formatter=lambda v, obj: [result(qir) for qir in v])]\n\n form_columns[u\"订单信息\"] = [column_spec.ColumnSpec(\"sub_order\"),\n column_spec.ColumnSpec(\"sub_order.order\", label=u\"订单号\")]\n return form_columns\n\nwork_command_view = WorkCommandView(WorkCommand)\n\n\ndef _wrapper(department):\n return dict(id=department.id, name=department.name,\n procedure_list=[dict(id=p.id, name=p.name) for p in\n department.procedure_list])\n\n\n@manufacture_page.route('/schedule/<work_command_id>', methods=['GET', 'POST'])\ndef schedule(work_command_id):\n import lite_mms.apis as apis\n\n work_command_list = [apis.manufacture.get_work_command(id_) for id_ in json.loads(work_command_id)]\n if request.method == 'GET':\n if 1 == len(work_command_list):\n work_command = work_command_list[0]\n return render_template(\"manufacture/schedule-work-command.html\", titlename=u'排产', nav_bar=nav_bar,\n department_list=[_wrapper(d) for d in get_department_list()],\n work_command=work_command)\n else:\n from lite_mms.utilities.functions import deduplicate\n\n department_set = deduplicate([wc.department for wc in work_command_list], lambda x: x.name)\n\n param_dic = {'titlename': u'批量排产', 'department_list': [_wrapper(d) for d in get_department_list()],\n 'work_command_list': work_command_list,\n 'default_department_id': department_set[0].id if len(department_set) == 1 else None}\n\n return render_template(\"manufacture/batch-schedule.html\", nav_bar=nav_bar, **param_dic)\n else: # POST\n class WorkCommandForm(Form):\n url = HiddenField('url')\n procedure_id = IntegerField('procedure_id')\n department_id = IntegerField('department_id', [validators.required()])\n tech_req = TextField('tech_req')\n urgent = BooleanField('urgent')\n\n form = WorkCommandForm(request.form)\n if form.validate():\n department = apis.manufacture.get_department(form.department_id.data)\n if not department:\n abort(404)\n if not form.procedure_id.data and any(not work_command.procedure for work_command in work_command_list):\n abort(403)\n for work_command in work_command_list:\n if work_command:\n d = dict(tech_req=form.tech_req.data,\n urgent=form.urgent.data,\n department_id=department.id)\n if form.procedure_id.data:\n d.update(procedure_id=form.procedure_id.data)\n\n work_command.go(actor_id=current_user.id,\n action=constants.work_command.ACT_DISPATCH,\n **d)\n else:\n abort(404)\n flash(u\"工单(%s)已经被成功排产至车间(%s)\" % (work_command_id, department.name))\n return redirect(form.url.data or url_for(\"manufacture.work_command_list\"))\n else:\n return redirect(url_for(\"error\", error=form.errors))" }, { "alpha_fraction": 0.7228843569755554, "alphanum_fraction": 0.7502979636192322, "avg_line_length": 48.32352828979492, "blob_id": "edcfd3dbcd72693c37071d07f399834492ca6400", "content_id": "abab817c3dce186defc068b395d14851446d519c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1678, "license_type": "no_license", "max_line_length": 118, "num_lines": 34, "path": "/alembic/versions/53c00532a76_order_add_refined.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"order_add_refined\n\nRevision ID: 53c00532a76\nRevises: 2a4cf5743519\nCreate Date: 2013-02-27 16:40:36.958412\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '53c00532a76'\ndown_revision = '2a4cf5743519'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.add_column(\"TB_ORDER\", sa.Column(\"refined\", sa.Boolean, default=False))\n op.execute(\"update tb_order t set refined=1 where t.dispatched=1; commit;\")\n op.execute(\"INSERT INTO TB_PERMISSION (name)values('deduction.addDeduction')\")\n op.execute(\"INSERT INTO TB_PERMISSION (name)values('deduction.deleteDeduction')\")\n op.execute(\"INSERT INTO TB_PERMISSION (name)values('deduction.editDeduction')\")\n op.execute(\"INSERT INTO TB_PERMISSION_AND_GROUP(permission_name,group_id)VALUES('deduction.addDeduction',4)\")\n op.execute(\"INSERT INTO TB_PERMISSION_AND_GROUP(permission_name,group_id)VALUES('deduction.deleteDeduction',4)\")\n op.execute(\"INSERT INTO TB_PERMISSION_AND_GROUP(permission_name,group_id)VALUES('deduction.editDeduction',4)\")\n\ndef downgrade():\n op.drop_column(\"TB_ORDER\", \"refined\")\n op.execute(\"DELETE FROM TB_PERMISSION_AND_GROUP WHERE permission_name='deduction.addDeduction' and group_id=4\")\n op.execute(\"DELETE FROM TB_PERMISSION_AND_GROUP WHERE permission_name='deduction.deleteDeduction' and group_id=4\")\n op.execute(\"DELETE FROM TB_PERMISSION_AND_GROUP WHERE permission_name='deduction.editDeduction' and group_id=4\")\n op.execute(\"DELETE FROM TB_PERMISSION WHERE name='deduction.addDeduction'\")\n op.execute(\"DELETE FROM TB_PERMISSION WHERE name='deduction.deleteDeduction'\")\n op.execute(\"DELETE FROM TB_PERMISSION WHERE name='deduction.editDeduction'\")\n\n" }, { "alpha_fraction": 0.48623189330101013, "alphanum_fraction": 0.502173900604248, "avg_line_length": 40.4923095703125, "blob_id": "15e4b6d457378ced193d2816b7194513984dcf0b", "content_id": "dd20624e7de00994121b9f7d12029caa879bf1e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2760, "license_type": "no_license", "max_line_length": 78, "num_lines": 65, "path": "/alembic/versions/4bc13c7caa37_add_spec_type.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"add spec_type\r\n\r\nRevision ID: 4bc13c7caa37\r\nRevises: 196b293a6da2\r\nCreate Date: 2013-03-12 11:44:10.906000\r\n\r\n\"\"\"\r\n\r\n# revision identifiers, used by Alembic.\r\nrevision = '4bc13c7caa37'\r\ndown_revision = '196b293a6da2'\r\n\r\nfrom alembic import op\r\nfrom sqlalchemy import Column,Integer,String,ForeignKey\r\n\r\n\r\ndef upgrade():\r\n from lite_mms.models import ConsignmentProduct\r\n\r\n op.create_table(ConsignmentProduct.__tablename__,\r\n Column('id', Integer(), primary_key=True, nullable=False),\r\n Column('consignment_id', Integer(),\r\n ForeignKey('TB_CONSIGNMENT.id'), nullable=False),\r\n Column('product_id', Integer(),\r\n ForeignKey('TB_PRODUCT.id'), nullable=False),\r\n Column('delivery_task_id', Integer(),\r\n ForeignKey('TB_DELIVERY_TASK.id'), nullable=False),\r\n Column('weight', Integer()),\r\n Column('quantity', Integer()),\r\n Column('unit', String(length=16), default=''),\r\n Column('spec', String(length=64)),\r\n Column('type', String(length=64)),\r\n Column('returned_weight', Integer()),\r\n Column('team_id', Integer(), ForeignKey('TB_TEAM.id'),\r\n nullable=True))\r\n\r\n from lite_mms.utilities import do_commit\r\n from lite_mms.apis.delivery import get_delivery_session_list\r\n delivery_session_list = get_delivery_session_list()[0]\r\n for delivery_session in delivery_session_list:\r\n for consignment in delivery_session.consignment_list:\r\n for t in delivery_session.delivery_task_list:\r\n if t.customer:\r\n if t.customer.id == consignment.customer_id:\r\n p = ConsignmentProduct(t.product, t, consignment)\r\n if t.team_list:\r\n p.team = t.team_list[0]\r\n p.weight = t.weight\r\n p.returned_weight = t.returned_weight\r\n if not t.quantity:\r\n t.quantity = sum(\r\n store_bill.quantity for store_bill in\r\n t.store_bill_list)\r\n p.quantity = t.quantity\r\n sb = t.sub_order_list.next()\r\n p.unit = sb.unit\r\n p.spec = sb.spec\r\n p.type = sb.type\r\n do_commit((p, t))\r\n else:\r\n do_commit(t, \"delete\")\r\n\r\ndef downgrade():\r\n from lite_mms.models import ConsignmentProduct\r\n op.drop_table(ConsignmentProduct.__tablename__)" }, { "alpha_fraction": 0.5493370294570923, "alphanum_fraction": 0.5500258207321167, "avg_line_length": 35.789588928222656, "blob_id": "5fb8513cd1cd32a14185453aba09d100c1aac78e", "content_id": "863470cec5ef43ff439807c248063d9cfce38b94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17861, "license_type": "no_license", "max_line_length": 116, "num_lines": 461, "path": "/lite_mms/apis/manufacture.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\nimport sys\r\nfrom datetime import datetime\r\n\r\nfrom werkzeug.datastructures import MultiDict\r\nfrom flask import url_for, request\r\nfrom flask.ext.babel import _\r\nfrom sqlalchemy.orm.exc import NoResultFound\r\nfrom wtforms import (Form, IntegerField, ValidationError, TextField,\r\n BooleanField, validators)\r\nfrom werkzeug.utils import cached_property\r\n\r\nimport lite_mms.constants as constants\r\nfrom lite_mms import models\r\nfrom lite_mms.apis import ModelWrapper\r\nfrom lite_mms.utilities import do_commit\r\n\r\nclass WorkCommandWrapper(ModelWrapper):\r\n @property\r\n def qi(self):\r\n if self.qir_list:\r\n return self.qir_list[0].actor\r\n else:\r\n return None\r\n\r\n @property\r\n def finish_time(self):\r\n if self.status == constants.work_command.STATUS_FINISHED:\r\n return self.last_mod\r\n return None\r\n\r\n @cached_property\r\n def status_name(self):\r\n return get_wc_status_list().get(self.status)[0]\r\n\r\n @cached_property\r\n def status_describe(self):\r\n return get_wc_status_list().get(self.status)[1]\r\n\r\n @property\r\n def product(self):\r\n return self.sub_order.product\r\n\r\n @cached_property\r\n def handle_type_name(self):\r\n return get_handle_type_list().get(self.handle_type)\r\n\r\n @property\r\n def pic_url(self):\r\n if self.pic_path:\r\n return url_for(\"serv_pic\", filename=self.pic_path)\r\n else:\r\n return \"\"\r\n\r\n @property\r\n def small_pic_url(self):\r\n return url_for(\"serv_small_pic\", filename=self.pic_path) if self.pic_path else \"\"\r\n\r\n @cached_property\r\n def harbor(self):\r\n return self.sub_order.harbor\r\n\r\n @property\r\n def order(self):\r\n return self.sub_order.order\r\n\r\n @property\r\n def unit(self):\r\n return self.sub_order.unit\r\n\r\n @property\r\n def default_department(self):\r\n for d in get_department_list():\r\n if self.harbor in d.harbor_list:\r\n return d\r\n return None\r\n\r\n @property\r\n def delivered_weight(self):\r\n return sum(sum(sb.weight for sb in qir.store_bill_list if sb.delivered) for qir in self.qir_list)\r\n\r\n @property\r\n def to_delivery_weight(self):\r\n return sum(sum(sb.weight for sb in qir.store_bill_list if not sb.delivered) for qir in self.qir_list)\r\n\r\n @property\r\n def passed_weight(self):\r\n return sum(qir.weight for qir in self.qir_list if qir.result==constants.quality_inspection.FINISHED)\r\n\r\n @classmethod\r\n def new_work_command(cls, sub_order_id, org_weight, org_cnt, procedure_id,\r\n urgent, tech_req=\"\", pic_path=\"\"):\r\n \"\"\"\r\n\r\n :param cls:\r\n :param sub_order_id:\r\n :param org_weight:\r\n :param org_cnt:\r\n :param procedure_id:\r\n :param urgent:\r\n :param tech_req:\r\n :param pic_path:\r\n :return: 新生成的WorkCommandWrapper\r\n :raise: ValueError 如果参数错误\r\n \"\"\"\r\n\r\n from lite_mms.apis import order\r\n\r\n try:\r\n sub_order = order.get_sub_order(sub_order_id).model\r\n except AttributeError:\r\n raise ValueError(_(u\"没有该子订单%d\" % sub_order_id))\r\n\r\n if not org_cnt:\r\n if sub_order.order_type == constants.EXTRA_ORDER_TYPE:\r\n raise ValueError(_(u\"需要schedule_count字段\"))\r\n else:\r\n org_cnt = org_weight\r\n\r\n if procedure_id:\r\n try:\r\n procedure = models.Procedure.query.filter(\r\n models.Procedure.id == procedure_id).one()\r\n except NoResultFound:\r\n raise ValueError(_(u\"没有该工序\"))\r\n else:\r\n procedure = None\r\n\r\n if sub_order.remaining_quantity < org_cnt:\r\n raise ValueError(_(u\"子订单的未排产数量小于%d\" % org_cnt))\r\n org_weight = int(sub_order.unit_weight * org_cnt)\r\n\r\n work_command = models.WorkCommand(sub_order=sub_order,\r\n org_weight=org_weight,\r\n procedure=procedure,\r\n tech_req=tech_req,\r\n urgent=urgent, org_cnt=org_cnt,\r\n pic_path=pic_path or sub_order\r\n .pic_path)\r\n if sub_order.returned:\r\n work_command.processed_cnt = work_command.org_cnt\r\n work_command.processed_weight = work_command.org_weight\r\n work_command.status = constants.work_command\\\r\n .STATUS_QUALITY_INSPECTING\r\n sub_order.remaining_quantity -= org_cnt\r\n\r\n do_commit([sub_order, work_command])\r\n\r\n return WorkCommandWrapper(work_command)\r\n\r\n @classmethod\r\n def get_list(cls, status_list, harbor=None, department_id=None,\r\n normal=None, team_id=None, start=0, cnt=sys.maxint,\r\n keywords=None, order_id=None, date=None):\r\n \"\"\"get the work command list from database, sorted by last mod time\r\n descentally\r\n :param status_list: the status of to retrieve, should be a list of integers\r\n \"\"\"\r\n import types\r\n\r\n wc_q = models.WorkCommand.query.join(models.SubOrder)\r\n\r\n if isinstance(status_list, types.ListType):\r\n wc_q = wc_q.filter(models.WorkCommand.status.in_(status_list))\r\n if department_id:\r\n wc_q = wc_q.filter(\r\n models.WorkCommand.department_id == department_id)\r\n if team_id:\r\n wc_q = wc_q.filter(models.WorkCommand.team_id == team_id)\r\n if harbor and harbor != u\"全部\":\r\n wc_q = wc_q.filter(\r\n models.SubOrder.harbor_name == harbor)\r\n if normal:\r\n wc_q = wc_q.filter(models.WorkCommand.org_weight > 0)\r\n if keywords:\r\n wc_q = wc_q.filter(\r\n models.WorkCommand.id.like(\"%\" + keywords + \"%\"))\r\n if order_id:\r\n wc_q = wc_q.filter(models.WorkCommand.sub_order_id.in_(\r\n [sub_order.id for sub_order in models.SubOrder.query.filter(\r\n models.SubOrder.order_id == order_id)]))\r\n if date:\r\n wc_q = wc_q.filter(models.WorkCommand.last_mod > date)\r\n total_cnt = wc_q.count()\r\n wc_q = wc_q.order_by(models.SubOrder.returned.desc()).order_by(\r\n models.WorkCommand.urgent.desc()).order_by(\r\n models.SubOrder.returned.desc()).order_by(\r\n models.WorkCommand.create_time.asc()).offset(start).limit(cnt)\r\n return [WorkCommandWrapper(wc) for wc in wc_q.all()], total_cnt\r\n\r\n @classmethod\r\n def get_work_command(cls, id_):\r\n \"\"\"\r\n get work command from database\r\n :return: WorkCommandWrapper or None\r\n \"\"\"\r\n if not id_:\r\n return None\r\n try:\r\n return WorkCommandWrapper(\r\n models.WorkCommand.query.filter(\r\n models.WorkCommand.id == id_).one())\r\n except NoResultFound:\r\n return None\r\n\r\n\r\n def update(self, **kwargs):\r\n for k, v in kwargs.items():\r\n if hasattr(self.model, k):\r\n setattr(self.model, k, v)\r\n do_commit(self.model)\r\n\r\n def go(self, actor_id, **kwargs):\r\n class _ValidationForm(Form):\r\n def add_value(self, **kwargs):\r\n try:\r\n self.__values.update(kwargs)\r\n except AttributeError:\r\n self.__values = {}\r\n self.__values.update(kwargs)\r\n\r\n @property\r\n def values(self):\r\n try:\r\n ret = self.__values\r\n except AttributeError:\r\n ret = {}\r\n ret.update(self.data)\r\n # remove none values\r\n for k, v in ret.items():\r\n if v is None:\r\n ret.pop(k)\r\n return ret\r\n\r\n def validate_team_id(self, field): # pylint: disable=R0201\r\n if self.action.data == constants.work_command.ACT_ASSIGN:\r\n if not field:\r\n raise ValidationError(\"team_id required when \"\r\n \"assigning work command\")\r\n try:\r\n self.add_value(\r\n team=TeamWrapper.get_team(field.data).model)\r\n except AttributeError:\r\n raise ValidationError(\r\n \"no such team \" + str(field.data))\r\n\r\n def validate_department_id(self, field):\r\n if self.action.data == constants.work_command.ACT_DISPATCH:\r\n if not field:\r\n raise ValidationError(\"department_id required when \"\r\n \"dispatching work command\")\r\n try:\r\n self.add_value(\r\n department=DepartmentWrapper.get_department(\r\n field.data).model)\r\n except AttributeError:\r\n raise ValidationError(\r\n \"no such department \" + str(field.data))\r\n\r\n valid_actions = [constants.work_command.ACT_DISPATCH,\r\n constants.work_command.ACT_ASSIGN,\r\n constants.work_command.ACT_ADD_WEIGHT,\r\n constants.work_command.ACT_END,\r\n constants.work_command.ACT_CARRY_FORWARD,\r\n constants.work_command.ACT_RETRIEVAL,\r\n constants.work_command.ACT_REFUSE,\r\n constants.work_command.ACT_AFFIRM_RETRIEVAL,\r\n constants.work_command.ACT_QI,\r\n constants.work_command.ACT_REFUSE_RETRIEVAL,\r\n constants.work_command.ACT_RETRIVE_QI,\r\n constants.work_command.ACT_QUICK_CARRY_FORWARD]\r\n action = IntegerField(\"action\", [validators.AnyOf(valid_actions)])\r\n team_id = IntegerField(\"team id\")\r\n department_id = IntegerField(\"department id\")\r\n quantity = IntegerField(\"quantity\")\r\n weight = IntegerField(\"weight\")\r\n tech_req = TextField(\"tech_req\")\r\n urgent = BooleanField(\"urgent\")\r\n deduction = IntegerField(\"deduction\")\r\n procedure_id = IntegerField(\"procedure_id\")\r\n\r\n\r\n\r\n form = _ValidationForm(MultiDict(kwargs))\r\n if not form.validate():\r\n raise ValueError(form.errors)\r\n from .work_command_state import work_command_sm\r\n if not work_command_sm.logger:\r\n from lite_mms.basemain import timeline_logger\r\n work_command_sm.logger = timeline_logger\r\n try:\r\n work_command_sm.reset_obj(work_command=self.model)\r\n d = form.values\r\n if 'qir_list' in kwargs:\r\n d.update([('qir_list', kwargs['qir_list'])])\r\n work_command_sm.next(actor=models.User.query.get(actor_id), **d)\r\n except Exception, e:\r\n raise ValueError(e.message)\r\n self.model.last_mod = datetime.now()\r\n do_commit(self.model)\r\n\r\n\r\n @property\r\n def retrievable(self):\r\n return self.status in [constants.work_command.STATUS_ASSIGNING,\r\n constants.work_command.STATUS_ENDING]\r\n\r\n @property\r\n def deduction(self):\r\n return sum(deduction.weight for deduction in self.deduction_list)\r\n\r\n\r\n @property\r\n def action_list(self):\r\n if self.status == constants.work_command.STATUS_DISPATCHING:\r\n return [{\"name\": u\"排产\", \"method\": \"GET\",\r\n \"url\": url_for(\"manufacture.schedule\"),\r\n \"extra\": {\"work_command_id\": self.id}}]\r\n elif self.status == constants.work_command.STATUS_ASSIGNING:\r\n return [{\"name\": u\"回收\", \"method\": \"POST\",\r\n \"url\": url_for(\"manufacture.retrieve\"),\r\n \"extra\": {\"work_command_id\": self.id}}]\r\n\r\n @property\r\n def url(self):\r\n from lite_mms.permissions.work_command import view_work_command\r\n\r\n if view_work_command.can():\r\n return url_for(\"manufacture.work_command\", id_=self.id,\r\n url=request.url)\r\n else:\r\n return \"\"\r\n\r\n @property\r\n def log_list(self):\r\n from lite_mms.apis.log import LogWrapper\r\n\r\n ret = LogWrapper.get_log_list(str(self.id), self.model.__class__.__name__)\r\n return sorted(ret, lambda a, b: cmp(a.create_time, b.create_time), reverse=True)\r\n\r\n @property\r\n def cause(self):\r\n if self.previous_work_command:\r\n if not self.parent_qir:\r\n return constants.work_command.CAUSE_CARRY\r\n elif self.parent_qir.result == constants.quality_inspection.REPAIR:\r\n return constants.work_command.CAUSE_REPAIR\r\n elif self.parent_qir.result == constants.quality_inspection.REPLATE:\r\n return constants.work_command.CAUSE_REPLATE\r\n elif self.parent_qir.result == constants.quality_inspection.NEXT_PROCEDURE:\r\n return constants.work_command.CAUSE_NEXT\r\n return constants.work_command.CAUSE_NORMAL\r\n\r\n _cause_name = {constants.work_command.CAUSE_NORMAL: u\"预排产\", constants.work_command.CAUSE_NEXT: u\"转下道工序\",\r\n constants.work_command.CAUSE_REPAIR: u\"返修\", constants.work_command.CAUSE_REPLATE: u\"返镀\",\r\n constants.work_command.CAUSE_CARRY: u\"结转\"}\r\n\r\n @property\r\n def cause_name(self):\r\n return self._cause_name.get(self.cause, u\"预排产\")\r\n\r\nclass DepartmentWrapper(ModelWrapper):\r\n @classmethod\r\n def get_list(cls):\r\n return [DepartmentWrapper(d) for d in models.Department.query.all()]\r\n\r\n @classmethod\r\n def get_department(cls, id_):\r\n if not id_:\r\n return None\r\n try:\r\n return DepartmentWrapper(\r\n models.Department.query.filter(\r\n models.Department.id == id_).one())\r\n except NoResultFound:\r\n return None\r\n\r\n\r\nclass TeamWrapper(ModelWrapper):\r\n @classmethod\r\n def get_list(cls, department_id=None):\r\n \"\"\"\r\n get teams from database\r\n :rtype: ListType\r\n \"\"\"\r\n query_ = models.Team.query\r\n if department_id:\r\n query_ = query_.filter(models.Team.department_id == department_id)\r\n return [TeamWrapper(team) for team in query_.all()]\r\n\r\n\r\n @classmethod\r\n def get_team(cls, id_):\r\n \"\"\"\r\n get team from database according to id_\r\n :return TeamWrapper or None\r\n \"\"\"\r\n if not id_:\r\n return None\r\n try:\r\n return TeamWrapper(models.Team.query.filter(\r\n models.Team.id == id_).one())\r\n except NoResultFound:\r\n return None\r\n\r\n def get_team_work_command_dict(self, begin_date=None, end_date=None):\r\n #只计算生产完毕的\r\n wc_dict = {}\r\n for wc in get_work_command_list(\r\n status_list=[constants.work_command.STATUS_FINISHED],\r\n team_id=self.id)[0]:\r\n list_ = wc_dict.setdefault(wc.create_time.strftime(\"%Y-%m-%d\"), [])\r\n flag = True\r\n if begin_date:\r\n flag = flag and (wc.create_time.date() >= begin_date.date())\r\n if end_date:\r\n flag = flag and (wc.create_time.date() <= end_date.date())\r\n if flag and wc.org_weight > 0:\r\n list_.append(wc)\r\n return wc_dict\r\n\r\n\r\ndef get_status_list():\r\n return [\r\n ((constants.work_command.STATUS_DISPATCHING, constants.work_command.STATUS_REFUSED), u'待生产', u\"需要调度员排产的工单\"),\r\n ((constants.work_command.STATUS_ENDING, constants.work_command.STATUS_ASSIGNING,\r\n constants.work_command.STATUS_LOCKED), u'生产中', u\"进入生产环节的工单\"),\r\n (constants.work_command.STATUS_QUALITY_INSPECTING, u'待质检',\r\n u\"待质检员质检完成的工单\"),\r\n (constants.work_command.STATUS_FINISHED, u'已完成', u\"已经结束生产的工单\"),\r\n ]\r\n\r\n\r\ndef get_wc_status_list():\r\n return {\r\n constants.work_command.STATUS_DISPATCHING: (u'待排产', u'待调度员排产'),\r\n constants.work_command.STATUS_ASSIGNING: ( u'待分配', u'待车间主任分配'),\r\n constants.work_command.STATUS_LOCKED: (u'锁定', u'调度员已请求回收,待车间主任处理'),\r\n constants.work_command.STATUS_ENDING: (u'待请求结转或结束', u'待班组长结转或结束'),\r\n constants.work_command.STATUS_QUALITY_INSPECTING: (\r\n u'待质检', u'待质检员质检完成'),\r\n constants.work_command.STATUS_REFUSED: (u'车间主任打回', u'调度员分配后,被车间主任打回'),\r\n constants.work_command.STATUS_FINISHED: (u'已结束', u'已经结束生产'),\r\n }\r\n\r\n\r\ndef get_handle_type_list():\r\n return {\r\n constants.work_command.HT_NORMAL: u'正常加工',\r\n constants.work_command.HT_REPAIRE: u'返修',\r\n constants.work_command.HT_REPLATE: u'返镀'\r\n }\r\n\r\n\r\nget_work_command_list = WorkCommandWrapper.get_list\r\nget_work_command = WorkCommandWrapper.get_work_command\r\nnew_work_command = WorkCommandWrapper.new_work_command\r\nget_team_list = TeamWrapper.get_list\r\nget_team = TeamWrapper.get_team\r\nget_department_list = DepartmentWrapper.get_list\r\nget_department = DepartmentWrapper.get_department\r\n" }, { "alpha_fraction": 0.5395488142967224, "alphanum_fraction": 0.541043758392334, "avg_line_length": 38.878047943115234, "blob_id": "7d60a45ca822ba8bf699134d7b1b0c36f0a6b243", "content_id": "909a7a9f2d8c6a1f612ec952d199925df03132b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15388, "license_type": "no_license", "max_line_length": 125, "num_lines": 369, "path": "/lite_mms/portal/admin/views.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nimport json\nimport numbers\nimport codecs\nimport csv\nimport cStringIO\n\nfrom wtforms import Form, DateField\nfrom flask import flash, redirect, url_for, request, render_template\nfrom flask.ext.databrowser import ModelView, column_spec, filters\nfrom flask.ext.databrowser.action import DeleteAction\nfrom flask.ext.databrowser.filters import BaseFilter, Contains\nfrom flask.ext.principal import Permission, PermissionDenied\n\nfrom lite_mms.models import (User, Group, Department, Team, Procedure,\n Harbor, Config, Customer, Product)\nimport lite_mms.constants as constants\nimport lite_mms.constants.groups as groups_const\nfrom lite_mms.permissions.roles import AdminPermission, CargoClerkPermission\nfrom lite_mms.portal.admin import admin_page\nfrom lite_mms.basemain import nav_bar\nfrom lite_mms.utilities.decorators import templated\n\n\nclass AdminModelView(ModelView):\n can_batchly_edit = False\n list_template = \"admin/list.html\"\n create_template = edit_template = \"admin/object.html\"\n\n def try_view(self, objs=None):\n AdminPermission.test()\n\n def try_edit(self, objs=None):\n AdminPermission.test()\n\n\nclass UserModelView(AdminModelView):\n edit_template = create_template = \"admin/user.html\"\n column_hide_backrefs = False\n\n __list_columns__ = [\"id\", \"username\", column_spec.PlaceHolderColumnSpec(\"groups\", label=u\"用户组\",\n template_fname=\"admin/user-groups-snippet.html\"),\n 'enabled']\n __column_labels__ = {\"id\": u\"编号\", \"username\": u\"用户名\", \"group\": u\"用户组\", \"password\": u\"密码(md5加密)\",\n \"groups\": u\"用户组列表\", 'enabled': u'激活'}\n __column_formatters__ = {\"enabled\": lambda v, obj: u\"是\" if v else u\"否\"}\n\n class UserDeleteAction(DeleteAction):\n\n def test_enabled(self, obj):\n if obj.id == constants.ADMIN_USER_ID:\n return -2\n return 0\n\n def get_forbidden_msg_formats(self):\n return {\n -2: u\"您不能删除超级管理员!\"\n }\n\n def get_column_filters(self):\n class UserGroupFilter(BaseFilter):\n\n def set_sa_criterion(self, query):\n if isinstance(self.value, numbers.Number) or self.value.isdigit():\n self.value = int(self.value)\n query = query.filter(User.groups.any(Group.id == self.value))\n return query\n\n return [UserGroupFilter(u\"group\", name=u\"是\", options=[(group.id, group.name) for group in Group.query.all()]),\n Contains(u'username', name=u'包含')]\n\n # ============ FORM PART ===========================\n __create_columns__ = __form_columns__ = [\"username\", \"password\", \"groups\", 'enabled']\n\n\nuser_model_view = UserModelView(User, u\"用户\")\n\n\nclass CustomerModelView(AdminModelView):\n def try_view(self, objs=None):\n Permission.union(AdminPermission, CargoClerkPermission).test()\n\n __column_labels__ = {\"id\": u\"编号\", \"name\": u\"名称\", \"abbr\": u\"拼音首字母简写\", \"enabled\": u\"是否激活\",\n \"MSSQL_ID\": u\"MsSQL数据库对应ID\"}\n __column_formatters__ = {\"enabled\": lambda v, obj: u\"是\" if v else u\"否\"}\n __form_columns__ = [column_spec.InputColumnSpec('id', read_only=True), 'name', 'abbr', 'enabled',\n column_spec.InputColumnSpec('MSSQL_ID', read_only=True)]\n __batch_form_columns__ = ['enabled']\n can_batchly_edit = True\n\n\ncustomer_model_view = CustomerModelView(Customer, u\"客户\")\n\n\nclass GroupModelView(AdminModelView):\n __list_columns__ = [\"id\", \"name\"]\n __column_labels__ = {\"id\": u\"编号\", \"name\": u\"组名\", \"permissions\": u\"权限列表\"}\n\n class GroupDeleteAction(DeleteAction):\n\n def test_enabled(self, obj):\n if obj.id in {groups_const.DEPARTMENT_LEADER,\n groups_const.TEAM_LEADER,\n groups_const.LOADER,\n groups_const.QUALITY_INSPECTOR,\n groups_const.CARGO_CLERK,\n groups_const.SCHEDULER,\n groups_const.ACCOUNTANT,\n groups_const.ADMINISTRATOR}:\n return -2\n return 0\n\n def get_forbidden_msg_formats(self):\n return {\n -2: u\"您不能删除系统内建用户组!\"\n }\n\n __customized_actions__ = [GroupDeleteAction(u\"删除\", AdminPermission)]\n\n # ======================= FORM PART ==================================\n __form_columns__ = __create_columns__ = [\"name\", \"permissions\"]\n\n\ngroup_model_view = GroupModelView(Group, u\"用户组\")\n\n\nclass DepartmentModelView(AdminModelView):\n __list_columns__ = [\"id\", \"name\",\n column_spec.PlaceHolderColumnSpec(\"team_list\", label=u\"班组列表\",\n template_fname=\"admin/department-team-list-snippet.html\"),\n column_spec.PlaceHolderColumnSpec(\"leader_list\", label=u\"车间主任\",\n template_fname=\"admin/department-leader-list-snippet.html\"),\n column_spec.PlaceHolderColumnSpec(\"procedure_list\", label=u\"允许工序\",\n template_fname=\"admin/department-procedure-list-snippet\"\n \".html\")]\n\n __create_columns__ = __form_columns__ = [\"name\",\n column_spec.InputColumnSpec(\"leader_list\",\n label=u\"车间主任列表\",\n opt_filter=lambda obj: any((\n group.id ==\n groups_const\n .DEPARTMENT_LEADER)\n for group in\n obj.groups),\n doc=u'只有用户组是\"车间主任\", 才能作为车间主任'),\n \"procedure_list\"]\n\n __column_labels__ = {\"id\": u\"编号\", \"name\": u\"名称\", \"leader_list\": u\"车间主任列表\", \"procedure_list\": u\"车间允许工序列表\"}\n\n __customized_actions__ = [DeleteAction(u\"删除\", AdminPermission)]\n\n def populate_obj(self, form):\n return Department(name=form.name.data, leaders=form.leader_list.data)\n\n\ndepartment_model_view = DepartmentModelView(Department, u\"车间\")\n\n\nclass TeamModelView(AdminModelView):\n __list_columns__ = [\"id\", \"name\", \"department\",\n column_spec.ColumnSpec(\"leader_list\",\n formatter=lambda v, obj: \",\".join([unicode(i) for i in v]))]\n\n __create_columns__ = __form_columns__ = [\"name\",\n column_spec.InputColumnSpec(\"leader_list\",\n filter_=lambda q: q.filter(User.groups.any(\n Group.id == groups_const.TEAM_LEADER)),\n doc=u'只有用户组是\"班组长\",才能作为班组长'), \"department\"]\n\n __column_labels__ = {\"id\": u\"编号\", \"name\": u\"名称\", \"leader_list\": u\"班组长列表\", \"department\": u\"所属车间\"}\n\n __customized_actions__ = [DeleteAction(u\"删除\", AdminPermission)]\n\n def populate_obj(self, form):\n return Team(name=form.name.data, department=form.department.data, leader=form.leader_list.data)\n\n\nteam_model_view = TeamModelView(Team, u\"班组\")\n\n\nclass HarborModelView(AdminModelView):\n __list_columns__ = [\"name\", \"department\"]\n __column_labels__ = {\"name\": u\"名称\", \"department\": u\"默认车间\"}\n __create_columns__ = __form_columns__ = [\"name\", \"department\"]\n __customized_actions__ = [DeleteAction(u\"删除\", AdminPermission)]\n\n\nharbor_model_view = HarborModelView(Harbor, u\"装卸点\")\n\n\nclass ProcedureModelView(AdminModelView):\n __column_labels__ = {\"name\": u\"名称\", \"department_list\": u\"可以执行此工序的车间\"}\n __create_columns__ = __form_columns__ = [\"name\", \"department_list\"]\n __customized_actions__ = [DeleteAction(u\"删除\", AdminPermission)]\n\n\nprocedure_model_view = ProcedureModelView(Procedure, u\"工序\")\n\n\nclass ConfigModelView(AdminModelView):\n __column_labels__ = {\"property_name\": u\"属性名称\", \"property_desc\": u\"描述\",\n \"property_value\": u\"值\"}\n\n def try_create(self):\n raise PermissionDenied\n\n __form_columns__ = [\n column_spec.InputColumnSpec(\"property_name\", label=u\"属性名称\",\n read_only=True),\n \"property_desc\",\n \"property_value\"]\n\n\nconfig_model_view = ConfigModelView(Config, u\"配置项\")\n\n\nclass ProductModelView(AdminModelView):\n \"\"\"\n 产品的管理类\n \"\"\"\n can_batchly_edit = True\n __list_columns__ = [\"id\", \"MSSQL_ID\", \"name\", \"product_type\", \"enabled\"]\n __column_labels__ = {\"id\": u\"产品编号\", \"MSSQL_ID\": u\"在mssql的编号\",\n \"name\": u\"名称\", \"product_type\": u\"产品类型\",\n \"enabled\": u\"是否启用\"}\n __column_formatters__ = {\"enabled\": lambda v, obj: u\"是\" if v else u\"否\"}\n __column_filters__ = [filters.EqualTo(\"product_type\", name=u\"是\")]\n __batch_form_columns__ = [\"product_type\", \"enabled\"]\n\n\nproduct_model_view = ProductModelView(Product, u\"产品\")\n\n\n@admin_page.route(\"/broker/index.html\")\n@templated(\"/admin/broker/index.html\")\ndef broker_index():\n from lite_mms.portal.admin import sub_nav_bar\n\n return {\"nav_bar\": nav_bar, \"sub_nav_bar\": sub_nav_bar, \"titlename\": u\"数据导入\"}\n\n\n@admin_page.route(\"/broker/products.html\")\ndef import_products():\n import lite_mms.apis as apis\n\n types_data = apis.broker.import_types()\n content1 = u\"读入%d条产品类型信息,\" % len(types_data)\n products_data = apis.broker.import_products()\n content2 = u\"读入%d条产品信息,\" % sum(len(v) for v in products_data.values())\n content1 += apis.product.post_types(types_data)\n content2 += apis.product.post_product(products_data)\n flash(u\"导入成功: \" + content1 + \",\" + content2, 'success')\n return redirect(url_for(\"admin.broker_index\"))\n\n\n@admin_page.route(\"/broker/customers.html\")\ndef import_customers():\n import lite_mms.apis as apis\n\n customers = apis.broker.import_customers()\n content = u\"读入%d条客户信息,\" % len(customers)\n content += apis.customer.post_customers(customers)\n flash(u\"导入成功: \" + content, 'success')\n return redirect(url_for(\"admin.broker_index\"))\n\n\n@admin_page.route(\"/broker/consigments.html\")\ndef export_consignments():\n import lite_mms.apis as apis\n\n current_consignments, totalcnt = apis.delivery.get_consignment_list(exporting=True)\n content = u\"读出%d条发货单信息,\" % len(current_consignments)\n count = 0\n for consignment in current_consignments:\n try:\n consignment.persist()\n except ValueError, e:\n return redirect(url_for(\"error\", errors=e))\n count += 1\n content += u\"成功导出%d条发货单\" % count\n flash(u\"导出成功: \" + content, 'success')\n return redirect(url_for(\"admin.broker_index\"))\n\n\n@admin_page.route(\"/broker/team-performance.html\", methods=[\"GET\", \"POST\"])\ndef team_performance():\n class _DateForm(Form):\n begin_date = DateField(\"begin_date\")\n end_date = DateField(\"end\")\n\n if request.method == \"GET\":\n form = _DateForm(request.args)\n begin_date = form.begin_date.data\n end_date = form.end_date.data\n\n if not begin_date or not end_date:\n #TODO no result yet\n pass\n elif begin_date > end_date:\n begin_date, end_date = end_date, begin_date\n\n from lite_mms.portal.admin import sub_nav_bar\n\n return render_template(\"/admin/broker/team-performance.html\",\n titlename=u\"班组绩效管理\", begin_date=begin_date,\n end_date=end_date, nav_bar=nav_bar, sub_nav_bar=sub_nav_bar)\n else:\n class UnicodeWriter:\n \"\"\"\n A CSV writer which will write rows to CSV file \"f\",\n which is encoded in the given encoding.\n \"\"\"\n\n def __init__(self, f, dialect=csv.excel, **kwds):\n # Redirect output to a queue\n self.queue = cStringIO.StringIO()\n self.writer = csv.writer(self.queue, dialect=dialect,\n **kwds)\n self.stream = f\n self.encoder = codecs.getincrementalencoder(\"UTF-8\")()\n self.stream.write(codecs.BOM_UTF8)\n\n def writerow(self, row):\n self.writer.writerow([s.encode(\"utf-8\") for s in row])\n # Fetch UTF-8 output from the queue ...\n data = self.queue.getvalue()\n data = data.decode(\"utf-8\")\n # ... and reencode it into the target encoding\n data = self.encoder.encode(data)\n # write to the target stream\n self.stream.write(data)\n # empty queue\n self.queue.truncate()\n\n def writerows(self, rows):\n for row in rows:\n self.writerow(row)\n\n\n from flask import Response\n import lite_mms.apis as apis\n\n try:\n from cStringIO import StringIO\n except ImportError:\n from StringIO import StringIO\n return_fileobj = StringIO()\n writer = UnicodeWriter(return_fileobj)\n fieldnames = [u'车间', u'班组', u'生产日期', u'工单号', u'生产重量(公斤)', u'扣除重量(公斤)']\n writer.writerow(fieldnames)\n form = _DateForm(request.form)\n begin_date = form.begin_date.data\n end_date = form.end_date.data\n if begin_date > end_date:\n begin_date, end_date = end_date, begin_date\n\n for team in apis.manufacture.get_team_list():\n _dict = team.get_team_work_command_dict(begin_date, end_date)\n for item in _dict.items():\n for wc in item[1]:\n writer.writerow(\n [team.department.name, team.name, item[0],\n str(wc.id), str(wc.processed_weight),\n str(wc.deduction)])\n response = Response(return_fileobj.getvalue(), mimetype='text/csv')\n response.headers[\n 'Content-Disposition'] = 'attachment; filename=export.csv'\n return response\n\n" }, { "alpha_fraction": 0.25, "alphanum_fraction": 0.3035714328289032, "avg_line_length": 10.199999809265137, "blob_id": "b4d92cf8047f262d2e434c5710adc38acc3dbe49", "content_id": "1052a5890325e0b74a6a175eff1a1214f3a41c06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 56, "license_type": "no_license", "max_line_length": 21, "num_lines": 5, "path": "/lite_mms/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"\n lite-mms\n ~~~~~~~~\n\"\"\"\n__version__ = \"1.0.1\"\n" }, { "alpha_fraction": 0.7203579545021057, "alphanum_fraction": 0.7203579545021057, "avg_line_length": 38.6363639831543, "blob_id": "57b18f33718b0495b886aac0a4ed69c31321602a", "content_id": "be9238ba332e36138769664cfb608f8800209d19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 447, "license_type": "no_license", "max_line_length": 101, "num_lines": 11, "path": "/lite_mms/portal/order_ws/webservices.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "from lite_mms.portal.order_ws import order_ws\r\nfrom lite_mms.utilities.decorators import webservice_call, login_required_webservice\r\nimport json\r\n\r\n@order_ws.route(\"/customer-list\")\r\n@webservice_call(\"json\")\r\n@login_required_webservice\r\ndef customer_list():\r\n import lite_mms.apis as apis\r\n customers = apis.customer.get_customer_list()\r\n return json.dumps([{\"id\": c.id, \"name\": c.name, \"abbr\": c.abbr} for c in customers if c.enabled])\r\n" }, { "alpha_fraction": 0.5813586115837097, "alphanum_fraction": 0.5829383730888367, "avg_line_length": 25.375, "blob_id": "fcc5371ae6d684f01979911c99acb9ca8c111a7f", "content_id": "2d0f67d9dcace9fb8235360f0b5a1b0f20578e7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 661, "license_type": "no_license", "max_line_length": 73, "num_lines": 24, "path": "/lite_mms/portal/work_flow/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\nfrom flask import Blueprint, render_template, request\n\nwork_flow_page = Blueprint(\"work_flow\", __name__, static_folder=\"static\",\n template_folder=\"templates\")\n\nfrom lite_mms.portal.work_flow.views import node_model_view\nfrom lite_mms.basemain import data_browser, nav_bar\n\nextra_params = {\n \"list_view\": {\n \"nav_bar\": nav_bar,\n \"titlename\": u\"工作流任务列表\",\n },\n \"form_view\": {\n \"nav_bar\": nav_bar,\n \"titlename\": u\"处理工作流任务\",\n }\n\n}\n\ndata_browser.register_model_view(node_model_view, \n work_flow_page, extra_params)\n" }, { "alpha_fraction": 0.7196765542030334, "alphanum_fraction": 0.7358490824699402, "avg_line_length": 60.83333206176758, "blob_id": "82bb08bd962306a9d9b1f0095944f409887fa44d", "content_id": "a8a76a1c7e7814205d91d19cbc80e461691b17b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 371, "license_type": "no_license", "max_line_length": 127, "num_lines": 6, "path": "/lite_mms/tools/collcet_translations.sh", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\npo1=`python -c \"from flask.ext import databrowser; print databrowser.__path__[0]\"`\"/translations/zh_CN/LC_MESSAGES/messages.po\"\npo2=`python -c \"from flask.ext import report; print report.__path__[0]\"`\"/translations/zh_CN/LC_MESSAGES/messages.po\"\nmsgcat $po1 $po2 | sed '/fuzzy/d' > translations/zh_CN/LC_MESSAGES/messages.po\npybabel compile -d translations\n" }, { "alpha_fraction": 0.565504252910614, "alphanum_fraction": 0.5862393975257874, "avg_line_length": 23.090909957885742, "blob_id": "71d2e45494cb7f3fc24c8949026dabe8e322f7d5", "content_id": "237cdf2932609fce8c83afdbc856fb2777c268d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1061, "license_type": "no_license", "max_line_length": 82, "num_lines": 44, "path": "/alembic/versions/4b191d5efa1e_add_column_goods_rec.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"add column goods_receipt_id to table TB_UNLOAD_TASK\r\r\r\rRevision ID: 4b191d5efa1e\r\rRevises: 51242e27bc6\r\rCreate Date: 2013-03-27 17:05:46.094000\r\r\r\r\"\"\"\r\r\r\r# revision identifiers, used by Alembic.\r\rrevision = '4b191d5efa1e'\r\rdown_revision = '51242e27bc6'\r\rfrom alembic import op\r\rimport sqlalchemy as sa\r\r\rdef upgrade():\r op.add_column(\"TB_UNLOAD_TASK\", sa.Column(\"goods_receipt_id\", sa.Integer,\r sa.ForeignKey(\r \"TB_GOODS_RECEIPT.id\")))\r from lite_mms.utilities import do_commit\r from lite_mms.apis.cargo import get_unload_session_list\r us_list = get_unload_session_list()[0]\r for us in us_list:\r for ut in us.task_list:\r for receipt in us.goods_receipt_list:\r if receipt.customer_id == ut.customer_id:\r ut.goods_receipt = receipt\r do_commit(ut)\r\rdef downgrade():\r op.drop_constraint(\"tb_unload_task_ibfk_6\",\"TB_UNLOAD_TASK\",type=\"foreignkey\")\r op.drop_column(\"TB_UNLOAD_TASK\", \"goods_receipt_id\")\r\r" }, { "alpha_fraction": 0.6209573149681091, "alphanum_fraction": 0.6222509741783142, "avg_line_length": 19.864864349365234, "blob_id": "9b9c79cbcd1c5e9d263ae174fcf53aa528d86c53", "content_id": "f4390499753869db68bf95b1efd9ef146b553a1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 773, "license_type": "no_license", "max_line_length": 61, "num_lines": 37, "path": "/lite_mms/tools/deploy_web_hook.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# -*- coding: UTF-8 -*-\n\"\"\"\nA WEB HOOK for github\nSYNOPSIS\n python deploy_web_hook.py [options]\nOPTIONS\n -h \n show this help\n -p <port>\n the port of server runs on\n -s <host>\n the ip of the server runs on\n -f <fabfile>\n the fabfile to execute\n\"\"\"\nimport sys\nimport subprocess\nimport json\nfrom getopt import getopt\nfrom flask import Flask, request\n\n\napp = Flask(__name__)\n\nfabfile = \"fabfile.py\"\n\[email protected](\"/deploy\", methods=[\"POST\"])\ndef deploy():\n subprocess.call([\"fab\", \"-f\", fabfile, \"deploy\"])\n return \"done\"\n\[email protected](\"/make-test-data\")\ndef make_test_data():\n # we only deploy when push to origin/master\n subprocess.call([\"fab\", \"-f\", fabfile, \"make_test_data\"])\n return \"done\"\n\n" }, { "alpha_fraction": 0.7737069129943848, "alphanum_fraction": 0.7758620977401733, "avg_line_length": 24.77777862548828, "blob_id": "c62379e42110610f321371e033e8f6273feebbd1", "content_id": "47e3e5130ccb0be92c332ce7ad64a6f7e71b10c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 544, "license_type": "no_license", "max_line_length": 66, "num_lines": 18, "path": "/lite_mms/permissions/cargo.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n针对装卸货流程的权限管理\n\"\"\"\nfrom collections import namedtuple\nfrom flask.ext.principal import Permission\n\nUnloadSessionManagement = namedtuple(\"user\", [\"method\"])\n\n# 针对班组长的管理权限\nEditUnloadSession = UnloadSessionManagement(\"edit_unload_session\")\nNewUnloadSession = UnloadSessionManagement(\"new_unload_session\")\n\nedit_us = Permission(EditUnloadSession)\nedit_us.brief = u\"修改卸货会话的权限\"\n\nnew_us = Permission(NewUnloadSession)\nnew_us.brief = u\"创建卸货会话的权限\"\n" }, { "alpha_fraction": 0.6474428772926331, "alphanum_fraction": 0.647660493850708, "avg_line_length": 32.77941131591797, "blob_id": "6443e1464bb38ec3c0374667af63a77004496c7d", "content_id": "29c60c1220577eb97070c59aed54b940cb6b4bb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4851, "license_type": "no_license", "max_line_length": 119, "num_lines": 136, "path": "/lite_mms/apis/todo.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom flask import url_for\nfrom . import ModelWrapper\nfrom lite_mms import models\nfrom lite_mms.utilities import do_commit\nfrom lite_mms import database\nfrom .notify import notifications\n\n\nclass TODOWrapper(ModelWrapper):\n @property\n def create_date(self):\n return self.create_time.date()\n\n\ndef new_todo(whom, action, obj=None, msg=\"\", sender=None, **kwargs):\n \"\"\"\n 告诉\"whom\"对\"obj\"执行\"action\" \n :param whom: who should be responsible for this todo\n :type whom: models.User\n :param unicode action: what should do\n :param obj: action should be performed upon which\n :param msg: supplementary message\n :param sender: who send this message, if not specified, we regard SYSTEM\n send this todo\n :Param kwargs: supplementary information\n \"\"\"\n todo = do_commit(todo_factory.render(whom, action, obj, msg, sender, **kwargs))\n notify(whom.id, todo.id)\n\n\ndef notify(user_id, to_do_id):\n notifications.add(user_id, to_do_id)\n\n\ndef delete_todo(id_):\n do_commit(models.TODO.query.get(id_), \"delete\")\n\n\ndef remove_todo(action, obj_pk):\n for to_do in models.TODO.query.filter(models.TODO.action == action).filter(models.TODO.obj_pk == obj_pk).all():\n do_commit(to_do, \"delete\")\n\n\nclass ToDoFactory(object):\n def __init__(self):\n self.__map = {}\n\n def render(self, whom, action, obj, msg, sender, **kwargs):\n return self.__map[action](whom, action, obj, msg, sender, **kwargs)\n\n def upon(self, action):\n def _(strategy):\n self.__map[action] = strategy\n\n return _\n\n\ntodo_factory = ToDoFactory()\n\n\ndef get_all_notify(user_id):\n id_list = notifications.pop(user_id)\n if id_list:\n return [TODOWrapper(i) for i in models.TODO.query.filter(models.TODO.id.in_(id_list)).all()]\n return []\n\n\nWEIGH_UNLOAD_TASK = u\"weigh_unload_task\"\nWEIGH_DELIVERY_TASK = u\"weigh_delivery_task\"\nPAY_CONSIGNMENT = u\"pay_consignment\"\nDISPATCH_ORDER = u\"dispatch_order\"\nPERMIT_DELIVERY_TASK_WITH_ABNORMAL_WEIGHT = u'permit_delivery_task_with_abnormal_weight'\n\n\n@todo_factory.upon(WEIGH_UNLOAD_TASK)\ndef weigh_unload_task(whom, action, obj, msg, sender, **kwargs):\n \"\"\"\n 称重任务\n \"\"\"\n from lite_mms.basemain import data_browser\n\n msg = u'装卸工%s完成了一次来自%s(车牌号\"%s\")卸货任务,请称重!' % (obj.creator.username, obj.customer.name, obj.unload_session.plate) + (\n msg and \" - \" + msg)\n return models.TODO(user=whom, action=action, obj_pk=obj.id, actor=sender,\n msg=msg,\n context_url=data_browser.get_form_url(obj.unload_session))\n\n\n@todo_factory.upon(WEIGH_DELIVERY_TASK)\ndef weigh_delivery_task(whom, action, obj, msg, sender, **kwargs):\n \"\"\"\n 称重任务\n \"\"\"\n from lite_mms.basemain import data_browser\n\n msg = u'装卸工%s完成了一次来自%s(车牌号\"%s\")发货任务,请称重!' % (obj.actor.username, obj.customer.name, obj.delivery_session.plate) + (\n msg and \" - \" + msg)\n return models.TODO(user=whom, action=action, obj_pk=obj.id, actor=sender,\n msg=msg,\n context_url=data_browser.get_form_url(obj.delivery_session))\n\n\n@todo_factory.upon(PAY_CONSIGNMENT)\ndef pay_consignment(whom, action, obj, msg, sender, **kwargs):\n \"\"\"\n 收款任务\n \"\"\"\n from lite_mms.basemain import data_browser\n\n msg = u'收发员%s创建了一张来自%s(车牌号%s)的发货单,请收款!' % (\n obj.actor.username if obj.actor else \"\", obj.customer.name, obj.delivery_session.plate) + (msg and \" - \" + msg)\n return models.TODO(user=whom, action=action, obj_pk=obj.id, actor=sender, msg=msg,\n context_url=data_browser.get_form_url(obj))\n\n\n@todo_factory.upon(DISPATCH_ORDER)\ndef dispatch_order(whom, action, obj, msg, sender, **kwargs):\n \"\"\"\n 下发订单\n \"\"\"\n from lite_mms.basemain import data_browser\n\n msg = u'收发员%s下发了一张编号是%s的订单,请预排产!' % (obj.creator.username if obj.creator else \"\",\n obj.customer_order_number) + (msg and \" - \" + msg)\n return models.TODO(user=whom, action=action, obj_pk=obj.id, actor=sender, msg=msg,\n context_url=data_browser.get_form_url(obj))\n\n\n@todo_factory.upon(PERMIT_DELIVERY_TASK_WITH_ABNORMAL_WEIGHT)\ndef permit_delivery_task_with_abnormal_weight(whom, action, obj, msg, sender, **kwargs):\n doc = database.codernity_db.get('id', obj.tag, with_doc=True)\n loader = models.User.query.get(doc['loader_id'])\n msg = u'装卸工%s完成了剩余重量异常的发货任务,请处理!' % loader.username\n return models.TODO(user=whom, action=action, obj_pk=obj.id, actor=sender, msg=msg,\n context_url=url_for('work_flow.node_list'))\n\n" }, { "alpha_fraction": 0.5884861350059509, "alphanum_fraction": 0.5906183123588562, "avg_line_length": 29.33333396911621, "blob_id": "7db2f8c375755d375040dd389a9812ae4141b51d", "content_id": "1775970b47fb0b677eb5257c8f39905a3fc419f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 938, "license_type": "no_license", "max_line_length": 64, "num_lines": 30, "path": "/lite_mms/utilities/state_machine.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "class State:\r\n @property\r\n def last_status(self):\r\n return self.last_state.status\r\n\r\n def run(self):\r\n assert 0, \"run not implemented\"\r\n\r\n def next(self, input):\r\n assert 0, \"next not implemented\"\r\n\r\n\r\nclass StateMachine(object):\r\n def __init__(self, init_state, logger=None):\r\n self.current_state = init_state\r\n self.current_state.sm = self\r\n self.logger = logger\r\n\r\n def next(self, action, *args, **kwargs):\r\n last_state = self.current_state\r\n self.current_state = last_state.next(action)\r\n self.current_state.last_state = last_state\r\n self.current_state.action = action\r\n self.current_state.sm = self\r\n self.current_state.run(*args, **kwargs)\r\n if self.logger:\r\n self.do_log(action, *args, **kwargs)\r\n\r\n def do_log(self, action, *args, **kwargs):\r\n self.logger.info(u\"action:%s\" % action, *args, **kwargs)" }, { "alpha_fraction": 0.5866881608963013, "alphanum_fraction": 0.5904455184936523, "avg_line_length": 40.377777099609375, "blob_id": "1fcea2ee4ce31baa01d39cc2e506e01e7655adc9", "content_id": "be52f64bb7d1b43b632447ce2af18e2cd83e15f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1969, "license_type": "no_license", "max_line_length": 111, "num_lines": 45, "path": "/lite_mms/test/at/test_order.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom lite_mms import constants\nfrom pyfeature import Feature, Scenario, given, when, and_, then, flask_sqlalchemy_setup, clear_hooks\n\nfrom lite_mms.basemain import app\nfrom lite_mms.database import db\n\n\ndef generate(times=1):\n from random import choice\n import string\n\n temp = \"\"\n for i in range(times):\n temp += choice(string.letters)\n return temp\n\n\ndef test():\n flask_sqlalchemy_setup(app, db, create_step_prefix=u\"创建\",\n model_name_getter=lambda model: model.__name__,\n attr_name_getter=lambda model, attr: model.__col_desc__.get(attr, attr),\n set_step_pattern=u'(\\w+)([\\.\\w+]+)设置为(.+)')\n\n with Feature(u\"订单测试\",step_files=[\"lite_mms.test.at.steps.order\"]):\n with Scenario(u\"准备数据\"):\n plate = given(u\"创建Plate\", name=generate(5))\n product_type_default = and_(u\"创建ProductType\", name=constants.DEFAULT_PRODUCT_TYPE_NAME)\n product_default = and_(u\"创建Product\", name=constants.DEFAULT_PRODUCT_NAME,\n product_type=product_type_default)\n group = and_(u'创建Group(cargo_clerk)', name='cargo_clerk', default_url='/cargo/unload-session-list')\n and_(u\"创建User\", username=\"cc\", password=\"cc\", groups=[group])\n customer = and_(u\"创建Customer\", name=generate(5), abbr=generate(2))\n department = and_(u\"创建Department\", name=generate(5))\n harbor = and_(u\"创建Harbor\", name=generate(5), department=department)\n\n with Scenario(u\"最简单流程\"):\n gr = given(u\"收货单\", customer, harbor)\n order = and_(u\"生成订单\", gr, order_type=constants.STANDARD_ORDER_TYPE)\n when(u\"完善订单\", order)\n status_code = and_(u\"下发订单\", order)\n then(u\"操作成功\", status_code)\n\nif __name__ == '__main__':\n test()\n\n" }, { "alpha_fraction": 0.6718146800994873, "alphanum_fraction": 0.6737451553344727, "avg_line_length": 23.619047164916992, "blob_id": "34eef52dfd700832d969d8da6516dc1388ec93f0", "content_id": "bba816ba17e9852db1a772dd516caa54bd76fc2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 576, "license_type": "no_license", "max_line_length": 119, "num_lines": 21, "path": "/lite_mms/utilities/contexts.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n@author: Yangminghua\n@version: $\n\"\"\"\nfrom contextlib import contextmanager\nfrom lite_mms.basemain import app\n\n\n@contextmanager\ndef keep_db_session_alive():\n \"\"\"\n 该上下文用于确保db session在request context弹出的时候,不会被删除(而flask-sqlalchemy会自动将db session删除)\n \"\"\"\n import mock\n\n patcher = mock.patch.dict(app.__dict__, {\n \"teardown_appcontext_funcs\": [f for f in app.teardown_appcontext_funcs if f.__module__ != \"flask_sqlalchemy\"]})\n patcher.start()\n yield\n patcher.stop()\n\n" }, { "alpha_fraction": 0.5937866568565369, "alphanum_fraction": 0.6096131205558777, "avg_line_length": 35.911109924316406, "blob_id": "860cc37fa613df8a42b50b581f8141c98e2df1fc", "content_id": "3810915eb2f1fc9cfff7a7ab40e17a4ad13a062a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1740, "license_type": "no_license", "max_line_length": 107, "num_lines": 45, "path": "/lite_mms/portal/auth_ws/webservices.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\nfrom lite_mms.portal.auth_ws import auth_ws\r\nfrom lite_mms.utilities.decorators import webservice_call\r\nfrom lite_mms.exceptions import AuthenticateFailure\r\nfrom flask import abort, request\r\nimport json\r\nfrom lite_mms.utilities import _\r\nfrom lite_mms.constants import groups\r\n\r\n@auth_ws.route(\"/login\", methods=[\"POST\"])\r\n@webservice_call(\"json\")\r\ndef login():\r\n username = request.args.get(\"username\", type=str)\r\n password = request.args.get(\"password\", type=str)\r\n if not username or not password:\r\n return _(u\"需要username或者password字段\"), 403\r\n try:\r\n import lite_mms.apis as apis\r\n\r\n user = apis.auth.authenticate(username, password)\r\n if not user.can_login_client:\r\n return json.dumps({\r\n 'reason': u'该用户不能在客户端登录'\r\n }), 403\r\n except AuthenticateFailure as inst:\r\n return json.dumps({\r\n 'reason': unicode(inst)\r\n }), 403\r\n return json.dumps(\r\n dict(username=user.username,\r\n teamID=\",\".join([str(team.id) for team in user.team_list]) if user.team_list else \"\",\r\n userID=user.id, departmentID=\",\".join([str(department.id) for department in\r\n user.department_list]) if user.department_list else \"\",\r\n userGroup=user.groups[0].id, token=user.get_auth_token()))\r\n\r\nif __name__ == \"__main__\":\r\n try:\r\n # pylint: disable=F0401,W0611\r\n from lite_mms.instance.portal.auth import webservices_main\r\n # pylint: enable=F0401,W0611\r\n except ImportError:\r\n import traceback\r\n\r\n print \"can't import webservice_main.py\"\r\n traceback.print_exc()\r\n" }, { "alpha_fraction": 0.5132570862770081, "alphanum_fraction": 0.5139868855476379, "avg_line_length": 45.08744430541992, "blob_id": "8454430f282440e991e4d82fca63b30d40e71628", "content_id": "0251a59a60a84995c92ff081077142d137c37b88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21273, "license_type": "no_license", "max_line_length": 115, "num_lines": 446, "path": "/lite_mms/apis/work_command_state.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom datetime import datetime\n\nfrom flask.ext.babel import _\nfrom lite_sm import StateMachine, State, InvalidAction\n\nfrom lite_mms.exceptions import InvalidStatus\nfrom lite_mms import constants, models\nfrom lite_mms.utilities import action_name, status_name, do_commit\n\n\nclass WorkCommandState(State):\n status = \"DEFAULT\"\n\n def next(self, action):\n raise InvalidAction(_(u\"%(status)s状态不允许进行%(action)s操作\" %\n {\"action\": action_name(action),\n \"status\": status_name(self.status)}))\n\n\nclass StateDispatching(WorkCommandState):\n \"\"\"\n the initial state\n \"\"\"\n status = constants.work_command.STATUS_DISPATCHING\n\n def next(self, action):\n if action == constants.work_command.ACT_DISPATCH:\n return state_assigning\n else:\n raise InvalidAction(_(u\"%(status)s状态不允许进行%(action)s操作\" %\n {\"action\": action_name(action),\n \"status\": status_name(self.status)}))\n\n def side_effect(self, **kwargs):\n self.sm.obj.set_status(constants.work_command.STATUS_DISPATCHING)\n if self.last_status == constants.work_command.STATUS_LOCKED:\n # 根据车间主任之前填写的工序后重量/数量,将原有工单的重量修正后\n # 返回\n old_wc = self.sm.obj\n old_wc.org_weight -= kwargs[\"weight\"]\n if old_wc.org_weight <= 0:\n # 至少保证为1, 这同时也意味着原有工单的重量不准确,所以不能\n # 进行回收\n old_wc.org_weight = 1\n processed_weight = kwargs[\"weight\"]\n\n if old_wc.sub_order.order_type == constants.EXTRA_ORDER_TYPE:\n old_wc.org_cnt -= kwargs[\"quantity\"]\n processed_quantity = kwargs[\"quantity\"]\n else:\n old_wc.org_cnt = old_wc.org_weight\n processed_quantity = processed_weight\n if old_wc.org_cnt <= 0:\n # 至少保证为1, 这同时也意味着原有工单的数量不准确,所以不能\n # 进行回收\n old_wc.org_cnt = 1\n\n if processed_weight and processed_quantity:\n new_wc = models.WorkCommand(sub_order=old_wc.sub_order,\n org_weight=processed_weight,\n procedure=old_wc.procedure,\n urgent=old_wc.urgent,\n status=constants.work_command.STATUS_QUALITY_INSPECTING,\n department=old_wc.department,\n processed_weight=processed_weight,\n team=old_wc.team,\n previous_procedure=old_wc.previous_procedure,\n tag=old_wc.tag,\n tech_req=old_wc.tech_req,\n org_cnt=processed_quantity,\n processed_cnt=processed_quantity,\n pic_path=old_wc.pic_path,\n handle_type=old_wc.handle_type,\n previous_work_command=old_wc)\n do_commit(new_wc)\n\n self.sm.obj.department = None\n self.sm.obj.team = None\n\n\nclass StateRefused(WorkCommandState):\n \"\"\"\n in fact, it is just an alias of STATUS_DISPATCHING\n \"\"\"\n\n status = constants.work_command.STATUS_REFUSED\n\n def next(self, action):\n if action == constants.work_command.ACT_DISPATCH:\n return state_assigning\n else:\n raise InvalidAction(_(u\"%(status)s状态不允许进行%(action)s操作\" %\n {\"action\": action_name(action),\n \"status\": status_name(self.status)}))\n\n def side_effect(self, **kwargs):\n self.sm.obj.set_status(constants.work_command.STATUS_REFUSED)\n\n\nclass StateAssigning(WorkCommandState):\n status = constants.work_command.STATUS_ASSIGNING\n\n def next(self, action):\n if action == constants.work_command.ACT_ASSIGN:\n return state_ending\n elif action == constants.work_command.ACT_REFUSE:\n return state_refused\n elif action == constants.work_command.ACT_RETRIEVAL:\n return state_dispatching\n else:\n raise InvalidAction(_(u\"%(status)s状态不允许进行%(action)s操作\" %\n {\"action\": action_name(action),\n \"status\": status_name(self.status)}))\n\n def side_effect(self, **kwargs):\n self.sm.obj.set_status(constants.work_command.STATUS_ASSIGNING)\n if kwargs.get(\"department\"):\n self.sm.obj.department = kwargs[\"department\"]\n self.sm.obj.tech_req = kwargs[\"tech_req\"]\n if kwargs.get(\"procedure_id\"):\n self.sm.obj.procedure_id = kwargs.get(\"procedure_id\")\n self.sm.obj.team = None\n if not self.sm.obj.department:\n raise InvalidStatus(_(u\"%(status)s状态必须有department字段\") % {\n \"status\": status_name(self.status)})\n\n\nclass StateEnding(WorkCommandState):\n status = constants.work_command.STATUS_ENDING\n\n def next(self, action):\n if action == constants.work_command.ACT_ADD_WEIGHT:\n return self\n elif action == constants.work_command.ACT_RETRIEVAL:\n return state_locked\n elif action == constants.work_command.ACT_END:\n return state_quality_inspecting\n elif action == constants.work_command.ACT_CARRY_FORWARD:\n if self.sm.obj.processed_cnt == 0: # carry forward COMPLETELY\n return state_assigning\n else:\n return state_quality_inspecting\n elif action == constants.work_command.ACT_QUICK_CARRY_FORWARD:\n return state_ending\n else:\n raise InvalidAction(_(u\"%(status)s状态不允许进行%(action)s操作\" %\n {\"action\": action_name(action),\n \"status\": status_name(self.status)}))\n\n def side_effect(self, **kwargs):\n if self.last_action == constants.work_command.ACT_QUICK_CARRY_FORWARD:\n old_wc = self.sm.obj\n\n new_wc = models.WorkCommand(sub_order=old_wc.sub_order,\n org_weight=old_wc.processed_weight,\n procedure=old_wc.procedure,\n status=constants.work_command\n .STATUS_QUALITY_INSPECTING,\n team=old_wc.team,\n department=old_wc.department,\n previous_procedure=old_wc\n .previous_procedure,\n tag=old_wc.tag,\n tech_req=old_wc.tech_req,\n org_cnt=old_wc.processed_cnt,\n pic_path=old_wc.pic_path,\n handle_type=old_wc.handle_type,\n processed_weight=old_wc.processed_weight,\n processed_cnt=old_wc.processed_cnt,\n previous_work_command=old_wc)\n new_wc.completed_time = datetime.now()\n\n remain_quantity = old_wc.org_cnt - old_wc.processed_cnt\n if remain_quantity <= 0:\n remain_quantity = 1\n remain_weight = int(\n self.sm.obj.unit_weight * remain_quantity)\n\n old_wc.org_cnt = remain_quantity\n old_wc.org_weight = remain_weight\n old_wc.processed_cnt = 0\n old_wc.processed_weight = 0\n do_commit([old_wc, new_wc])\n\n else:\n self.sm.obj.set_status(constants.work_command.STATUS_ENDING)\n if \"team\" in kwargs: # when it comes by ACT_ASSIGN\n self.sm.obj.team = kwargs[\"team\"]\n\n if self.last_status == constants.work_command.STATUS_ENDING:\n try:\n self.sm.obj.processed_weight += kwargs[\"weight\"]\n except KeyError:\n raise InvalidAction(_(u\"该操作需要weight字段\"))\n if self.sm.obj.sub_order.order_type == constants.EXTRA_ORDER_TYPE: # 计件类型\n try:\n self.sm.obj.processed_cnt += kwargs[\"quantity\"]\n except KeyError:\n raise InvalidAction(_(u\"该操作需要quantity字段\"))\n else: # 普通类型\n self.sm.obj.processed_cnt = self.sm.obj \\\n .processed_weight\n\n\nclass StateQualityInspecting(WorkCommandState):\n status = constants.work_command.STATUS_QUALITY_INSPECTING\n\n def next(self, action):\n if action == constants.work_command.ACT_QI:\n return state_finished\n else:\n raise InvalidAction(_(u\"%(status)s状态不允许进行%(action)s操作\" %\n {\"action\": action_name(action),\n \"status\": status_name(self.status)}))\n\n def side_effect(self, **kwargs):\n self.sm.obj.set_status(\n constants.work_command.STATUS_QUALITY_INSPECTING)\n if self.last_status == constants.work_command.STATUS_ENDING:\n if self.last_action == constants.work_command.ACT_CARRY_FORWARD:\n old_wc = self.sm.obj\n remain_quantity = old_wc.org_cnt - old_wc.processed_cnt\n if remain_quantity <= 0:\n remain_quantity = 1\n remain_weight = int(\n self.sm.obj.unit_weight * remain_quantity)\n new_wc = models.WorkCommand(sub_order=old_wc.sub_order,\n org_weight=remain_weight,\n procedure=old_wc.procedure,\n status=constants.work_command\n .STATUS_ASSIGNING,\n previous_procedure=old_wc\n .previous_procedure,\n tag=old_wc.tag,\n tech_req=old_wc.tech_req,\n org_cnt=remain_quantity,\n pic_path=old_wc.pic_path,\n handle_type=old_wc.handle_type,\n department=old_wc.department,\n previous_work_command=old_wc)\n\n old_wc.org_cnt -= new_wc.org_cnt #: 实际工作的黑件数\n old_wc.org_weight -= new_wc.org_weight\n\n do_commit([new_wc, old_wc])\n\n self.sm.obj.completed_time = datetime.now()\n do_commit(self.sm.obj)\n elif self.last_status == constants.work_command.STATUS_FINISHED:\n old_wc = self.sm.obj\n from lite_mms.apis.quality_inspection import QIReportWrapper\n\n qir_list = [QIReportWrapper(qir) for qir in old_wc.qir_list]\n if not qir_list:\n raise InvalidAction(u'该工单没有质检报告,不能取消质检结果')\n # 若某个质检报告生成的仓单已经完全发货或者部分发货, 不能取消质检报告\n if any(qir.partly_delivered for qir in qir_list):\n raise InvalidAction(u'新生成的仓单已经发货,不能取消质检报告')\n generate_wc_list = [\n qi_report.generated_work_command for qi_report\n in qir_list if qi_report.generated_work_command]\n if any(wc.status not in [constants.work_command.STATUS_DISPATCHING,\n constants.work_command.STATUS_ASSIGNING,\n constants.work_command.STATUS_REFUSED]\n for wc in generate_wc_list):\n raise InvalidAction(u'新生成的工单已经分配,不能取消质检报告')\n\n # 删除工单的质检报告中,完全没有发货的仓单\n models.StoreBill.query.filter(models.StoreBill.qir_id.in_(\n [qir.id for qir in qir_list])).delete(\"fetch\")\n # 删除工单的质检报告生成的工单\n wc_id_list = [qir.generated_work_command_id for qir in qir_list]\n models.QIReport.query.filter(\n models.QIReport.work_command_id == old_wc.id).update(\n {\"generated_work_command_id\": None})\n models.WorkCommand.query.filter(\n models.WorkCommand.id.in_(wc_id_list)).delete(\n \"fetch\")\n old_wc.deduction_list = []\n\n\nclass StateFinished(WorkCommandState):\n status = constants.work_command.STATUS_FINISHED\n\n def next(self, action):\n if action == constants.work_command.ACT_RETRIVE_QI:\n return state_quality_inspecting\n else:\n raise InvalidAction(_(u\"%(status)s状态不允许进行%(action)s操作\" %\n {\"action\": action_name(action),\n \"status\": status_name(self.status)}))\n\n def side_effect(self, **kwargs):\n self.sm.obj.set_status(constants.work_command.STATUS_FINISHED)\n if self.last_status == constants.work_command.STATUS_QUALITY_INSPECTING:\n old_wc = self.sm.obj\n procedure = \"\"\n previous_procedure = \"\"\n handle_type = \"\"\n status = \"\"\n department = None\n\n from lite_mms.database import db\n\n old_wc.qir_list = []\n db.session.add_all([models.QIReport(old_wc,\n qir_dict['quantity'],\n qir_dict['weight'],\n qir_dict['result'],\n qir_dict['actor_id'],\n pic_path=qir_dict['pic_path']) for qir_dict in kwargs['qir_list']])\n\n for qir in old_wc.qir_list:\n if qir.result == constants.quality_inspection.FINISHED:\n sb = models.StoreBill(qir)\n if self.sm.obj.team:\n sb.printed = True\n sb.harbor = self.sm.obj.team.department.harbor_list[0]\n db.session.add(sb)\n continue\n elif qir.result == constants.quality_inspection.DISCARD:\n # use QIReport as discard report\n continue\n elif qir.result == constants.quality_inspection.NEXT_PROCEDURE:\n handle_type = constants.work_command.HT_NORMAL\n procedure = None\n previous_procedure = old_wc.procedure\n status = constants.work_command.STATUS_DISPATCHING\n department = None\n elif qir.result == constants.quality_inspection.REPAIR:\n handle_type = constants.work_command.HT_REPAIRE\n procedure = old_wc.procedure\n previous_procedure = old_wc.previous_procedure # 可能有三道工序\n status = constants.work_command.STATUS_ASSIGNING if old_wc.department else constants \\\n .work_command.STATUS_DISPATCHING\n # 这个工单可能是由退货产生的。\n department = old_wc.department\n elif qir.result == constants.quality_inspection.REPLATE:\n handle_type = constants.work_command.HT_REPLATE\n procedure = old_wc.procedure\n previous_procedure = old_wc.previous_procedure\n status = constants.work_command.STATUS_ASSIGNING if old_wc.department else constants \\\n .work_command.STATUS_DISPATCHING\n department = old_wc.department\n new_wc = models.WorkCommand(sub_order=old_wc.sub_order,\n org_weight=qir.weight,\n status=status,\n tech_req=old_wc.tech_req,\n org_cnt=qir.quantity,\n procedure=procedure,\n previous_procedure=previous_procedure,\n pic_path=qir.pic_path,\n handle_type=handle_type,\n department=department,\n previous_work_command=old_wc)\n\n db.session.add(new_wc)\n qir.generated_work_command = new_wc\n db.session.add(qir)\n if kwargs.get(\"deduction\"):\n db.session.add(models.Deduction(weight=kwargs[\"deduction\"],\n work_command=old_wc,\n actor=kwargs[\"actor\"],\n team=old_wc.team))\n db.session.commit()\n\nclass StateLocked(WorkCommandState):\n status = constants.work_command.STATUS_LOCKED\n\n def next(self, action):\n if action == constants.work_command.ACT_AFFIRM_RETRIEVAL:\n return state_dispatching\n elif action == constants.work_command.ACT_REFUSE_RETRIEVAL:\n # TODO should inform scheduler\n return state_ending\n else:\n raise InvalidAction(_(u\"%(status)s状态不允许进行%(action)s操作\" %\n {\"action\": action_name(action),\n \"status\": status_name(self.status)}))\n\n def side_effect(self, **kwargs):\n self.sm.obj.set_status(constants.work_command.STATUS_LOCKED)\n\n\nclass WorkCommandSM(StateMachine):\n def reset_obj(self, work_command):\n self.obj = work_command\n if work_command.status == constants.work_command.STATUS_DISPATCHING:\n self.set_current_state(state_dispatching)\n elif work_command.status == constants.work_command.STATUS_ASSIGNING:\n self.set_current_state(state_assigning)\n elif work_command.status == constants.work_command.STATUS_ENDING:\n self.set_current_state(state_ending)\n elif work_command.status == constants.work_command.STATUS_LOCKED:\n self.set_current_state(state_locked)\n elif work_command.status == constants.work_command.STATUS_QUALITY_INSPECTING:\n self.set_current_state(state_quality_inspecting)\n elif work_command.status == constants.work_command.STATUS_REFUSED:\n self.set_current_state(state_refused)\n elif work_command.status == constants.work_command.STATUS_FINISHED:\n self.set_current_state(state_finished)\n else:\n raise InvalidStatus(_(u\"工单%(wc_id)d的状态%(status)d是非法的\" %\n {\"status\": work_command.status,\n \"wc_id\": work_command.id}))\n\n def next(self, action, actor=None, *args, **kwargs):\n self.last_state = self.current_state\n self.last_action = action\n self.current_state = self.last_state.next(action)\n self.current_state.last_state = self.last_state\n self.current_state.action = action\n self.current_state.sm = self\n kwargs[\"actor\"] = actor\n self.current_state.side_effect(*args, **kwargs)\n\n # notify the actors\n for actor_ in self.current_state.actors:\n self.sm.notify_next_actor(actor_)\n\n # log\n if self.logger:\n self.do_log(action, actor)\n\n def do_log(self, action, actor=None):\n if not actor:\n from flask.ext.login import current_user\n\n if current_user.is_authenticated:\n actor = current_user\n self.logger.info(u\"操作: %s\" % action_name(action),\n extra={\"obj\": self.obj, \"actor\": actor,\n \"action\": action_name(action),\n \"obj_pk\": self.obj.id})\n\n\nwork_command_sm = WorkCommandSM()\n\nstate_dispatching = StateDispatching(work_command_sm)\nstate_assigning = StateAssigning(work_command_sm)\nstate_ending = StateEnding(work_command_sm)\nstate_locked = StateLocked(work_command_sm)\nstate_quality_inspecting = StateQualityInspecting(work_command_sm)\nstate_refused = StateRefused(work_command_sm)\nstate_finished = StateFinished(work_command_sm)\n" }, { "alpha_fraction": 0.6160558462142944, "alphanum_fraction": 0.6771378517150879, "avg_line_length": 12.302325248718262, "blob_id": "c4d2212ba24ae54208614d73ffa352a876678738", "content_id": "fc2f63a61fae8098715f08aac71cc259e856cd22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 573, "license_type": "no_license", "max_line_length": 96, "num_lines": 43, "path": "/alembic/versions/2c6eb11ac2d7_default_url_of_sched.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"default url of schedule\r\r\r\rRevision ID: 2c6eb11ac2d7\r\rRevises: 34726d8933e3\r\rCreate Date: 2013-06-07 09:37:33.926000\r\r\r\r\"\"\"\r\r\r\r# revision identifiers, used by Alembic.\r\rrevision = '2c6eb11ac2d7'\r\rdown_revision = '34726d8933e3'\r\r\r\rfrom alembic import op\r\rimport sqlalchemy as sa\r\r\r\r\r\rdef upgrade():\r\r op.execute(\"UPDATE TB_GROUP SET default_url='/order/' WHERE (id='6') \")\r\r op.execute(\"UPDATE TB_GROUP SET default_url='/consignment/consignment-list' WHERE (id='7')\")\r\r\r\rdef downgrade():\r\r op.execute(\"UPDATE TB_GROUP SET default_url='/schedule/' WHERE (id='6') \")\r\r" }, { "alpha_fraction": 0.35930734872817993, "alphanum_fraction": 0.4386724531650543, "avg_line_length": 13.557894706726074, "blob_id": "12f26eae85a0b76a59374a98d34b80b707c2daea", "content_id": "4ccd584964e6455a99e4b6988ca8523d578229da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2308, "license_type": "no_license", "max_line_length": 73, "num_lines": 95, "path": "/docs/source/mannual.rst", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "####\n简介\n####\nlite-mms是一个轻量级的物料管理系统,包括如下主要流程:\n\n* 卸货(即收货)流程\n相关角色包括收发员和装卸工。\n\n* 生产流程\n相关角色包括调度员,车间主任,班组长以及质量检验员。\n \n* 发货流程\n相关角色包括调度员,装卸工,财会人员。\n\n########\n预设数据\n########\n\n* 车间\n\n * 一号车间\n * 二号车间\n * 三号车间\n * 抛砂车间\n * 整修车间\n\n* 班组\n\n ==== ========\n 班组 所属车间\n ==== ========\n 101 一号车间 \n 201 二号车间\n 202 二号车间\n 203 二号车间\n 301 三号车间\n 302 三号车间\n 401 抛砂车间\n 501 整修车间\n ==== ========\n\n* 装卸点\n\n ======= ======== \n 装卸点 所属车间\n ======= ========\n 装卸点1 一号车间\n 装卸点2 二号车间\n 装卸点3 三号车间\n 装卸点4 抛砂车间\n 装卸点5 整修车间\n ======= ========\n\n* 用户\n\n ===== ===== ============\n 用户 密码 说明\n ===== ===== ============\n admin admin 管理员\n cc cc 收发员\n l l 装卸工\n s s 调度员\n qi qi 质检员\n a a 财会人员\n cj1 cj1 车间1主任\n cj2 cj2 车间2主任\n cj3 cj3 车间3主任\n pscj pscj 抛砂车间主任\n zxcj zxcj 整修车间主任\n 101 101 101班组长 \n 201 201 201班组长\n 202 202 202班组长\n 203 203 203班组长\n 301 301 301班组长\n 302 302 302班组长\n 401 401 401班组长\n 501 501 501班组长\n ===== ===== ============\n\n########\n名词解释\n########\n请见trac\n\n########\n卸货流程\n########\n\n********\n流程简述\n********\n\n当有待加工件送达时,收发员发起卸货会话。每个卸货会话针对一台车辆,包括一个或多个卸货任务,每个卸货任务由装卸工填写,然后由收发员进行称重。\n卸货会话完成后,会为每个客户生成一个收货单。生成收货单的同时,会生成一张订单。每个订单会为每种产品生成多个子订单(但是计件类型不会,具体见下文)。\n同时收发员也可以去完善子订单的信息。\n\n\n\n" }, { "alpha_fraction": 0.6165048480033875, "alphanum_fraction": 0.6213592290878296, "avg_line_length": 22.25, "blob_id": "c0dc1d19b54ad36d2ce9ba2b84e1e59c1b31fd0d", "content_id": "2781a9d17829627498e551815fda10e0157e0fe6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 206, "license_type": "no_license", "max_line_length": 58, "num_lines": 8, "path": "/lite_mms/portal/auth/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\n\r\nfrom flask import Blueprint\r\n\r\nauth = Blueprint(\"auth\", __name__, static_folder=\"static\",\r\n template_folder=\"templates\")\r\n\r\nfrom lite_mms.portal.auth import views\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.45899054408073425, "alphanum_fraction": 0.4637224078178406, "avg_line_length": 68.22222137451172, "blob_id": "a7045081f21318604a1542a6c38759408dadd5ce", "content_id": "54ca0796e871d008f65a6e4227cc73d862d4fb6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 634, "license_type": "no_license", "max_line_length": 81, "num_lines": 9, "path": "/lite_mms/utilities/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "from lite_mms.utilities.functions import (dictview, find_first,\r\n to_timestamp, convert_time,\r\n action_name, _, status_name,\r\n repr_wtforms_error, fslice,\r\n Config, do_commit, check_raise,\r\n get_or_404, deduplicate, camel_case,\r\n gen_qir_pic_path)\r\nfrom lite_mms.utilities.jinja_filters import (url_for_other_page, datetimeformat)\r\nfrom lite_mms.utilities.pagination import Pagination\r\n\r\n" }, { "alpha_fraction": 0.5424790978431702, "alphanum_fraction": 0.543175458908081, "avg_line_length": 30.91111183166504, "blob_id": "604d72bacdc27fb9d69ee8f1c6b48418f80ba6c4", "content_id": "b635c607932f11a08b0f47d83a813f2276e49cd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1448, "license_type": "no_license", "max_line_length": 99, "num_lines": 45, "path": "/lite_mms/portal/cargo/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\nfrom flask import Blueprint\n\ncargo_page = Blueprint(\"cargo\", __name__, static_folder=\"static\", template_folder=\"templates\")\n\ngr_page = Blueprint(\"goods_receipt\", __name__, static_folder=\"static\", template_folder=\"templates\")\n\nfrom lite_mms.portal.cargo.views import (unload_session_model_view,\n plate_model_view,\n goods_receipt_entry_view,\n goods_receipt_model_view,\n unload_task_model_view)\n\nfrom lite_mms.basemain import data_browser, nav_bar\n\n\ndef _do_register(model_view, bp):\n extra_params = {\n \"list_view\": {\n \"nav_bar\": nav_bar,\n \"titlename\": model_view.model_name + u\"列表\",\n },\n \"create_view\": {\n \"nav_bar\": nav_bar,\n \"titlename\": u\"创建\" + model_view.model_name,\n },\n \"form_view\": {\n \"nav_bar\": nav_bar,\n \"titlename\": u\"编辑\" + model_view.model_name,\n }\n\n }\n data_browser.register_model_view(model_view, bp, extra_params)\n\n\nfor model_view in [unload_session_model_view, goods_receipt_entry_view,\n plate_model_view,\n unload_task_model_view]:\n _do_register(model_view, cargo_page)\n\nfor model_view in [goods_receipt_model_view]:\n _do_register(model_view, gr_page)\n\nfrom . import views, ajax\n" }, { "alpha_fraction": 0.6302250623703003, "alphanum_fraction": 0.6318327784538269, "avg_line_length": 24.91666603088379, "blob_id": "27084c6f1309ebdb6623c5191619a59da91025c6", "content_id": "9565589ea9fcb10517c517ea4e1d9488d231866d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 672, "license_type": "no_license", "max_line_length": 67, "num_lines": 24, "path": "/lite_mms/features/terrain.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport tempfile\nimport os\nfrom lettuce import *\n\[email protected]_feature\ndef setup(feature):\n from lite_mms.basemain import app\n from lite_mms.database import db, init_db\n db_fd, db_fname = tempfile.mkstemp()\n os.close(db_fd)\n app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///\" + db_fname\n try:\n db.init_app(app)\n except AssertionError: # 这是因为flask禁止在一次请求之后再次init_app, 而\n # 使用lettuce, 这是不可避免的\n pass \n init_db()\n world.db = db\n world.db_fname = db_fname\n\[email protected]_feature\ndef teardown(feature):\n os.unlink(world.db_fname)\n" }, { "alpha_fraction": 0.6201743483543396, "alphanum_fraction": 0.6214196681976318, "avg_line_length": 29.884614944458008, "blob_id": "9ce13fd7dbef37678a7cdf790263c7648a2bfdbb", "content_id": "558f97e0835497dfc93c0e99e254f8c800ba4296", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 819, "license_type": "no_license", "max_line_length": 104, "num_lines": 26, "path": "/lite_mms/portal/store/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n@author: Yangminghua\n@version: $\n\"\"\"\nfrom flask import Blueprint, render_template, request\nfrom flask.ext.login import login_required\nfrom lite_mms.utilities.decorators import nav_bar_set\n\nstore_bill_page = Blueprint(\"store_bill\", __name__, static_folder=\"static\",\n template_folder=\"templates\")\n\nfrom . import ajax\nfrom .views import store_bill_view\n\nfrom lite_mms.basemain import data_browser, nav_bar\n\ndata_browser.register_model_view(store_bill_view, store_bill_page,\n extra_params={\"list_view\": {\"nav_bar\": nav_bar, \"titlename\": u\"仓单列表\"},\n \"form_view\": {\"nav_bar\": nav_bar, \"titlename\": u\"编辑仓单\"}})\n\n\n@store_bill_page.before_request\n@login_required\ndef _():\n pass\n" }, { "alpha_fraction": 0.5312199592590332, "alphanum_fraction": 0.5360230803489685, "avg_line_length": 25.024999618530273, "blob_id": "7cd7022100521707270a1d3f7084e04321786f43", "content_id": "c38db09ea94da61acebda065a9bb90cdcdd1358c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1041, "license_type": "no_license", "max_line_length": 75, "num_lines": 40, "path": "/lite_mms/apis/notify.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom collections import deque\n\n\nclass Notification(object):\n __slots__ = \"dictionary\",\n\n __maxsize__ = 5\n\n def __init__(self, *args, **kwargs):\n self.dictionary = {}\n if \"maxsize\" in kwargs:\n self.__maxsize__ = int(kwargs.get(\"maxsize\"))\n\n def delete(self, key):\n \"\"\"Deletes the `key` from the dictionary.\"\"\"\n if key in self.dictionary:\n del self.dictionary[key]\n return 1\n return 0\n\n def add(self, key, val):\n q = self.dictionary.setdefault(key, deque(maxlen=self.__maxsize__))\n q.appendleft(val)\n return 1\n\n def pop(self, key):\n \"\"\"Retrieves a value of the `key` from the internal dictionary.\"\"\"\n try:\n q = self.dictionary.pop(key)\n return list(q)\n except KeyError:\n return []\n\n def __repr__(self):\n modname = \"\" if __name__ == \"__main__\" else __name__ + \".\"\n return \"<%s %r>\" % (modname, self.dictionary)\n\n\nnotifications = Notification()\n" }, { "alpha_fraction": 0.568061888217926, "alphanum_fraction": 0.5803728699684143, "avg_line_length": 31.869047164916992, "blob_id": "064d20c80375d99547865ba5f64425bb008047b5", "content_id": "434f29717856f3ef0679f05374b7d4f90e221aa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2993, "license_type": "no_license", "max_line_length": 77, "num_lines": 84, "path": "/lite_mms/portal/cargo/ajax.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\nimport json\r\nfrom flask import request, flash\r\nfrom sqlalchemy.exc import SQLAlchemyError\r\nfrom wtforms import Form, TextField, IntegerField\r\nfrom lite_mms import constants\r\nfrom lite_mms.portal.cargo import cargo_page\r\nfrom lite_mms.utilities import get_or_404, do_commit\r\nfrom lite_mms.utilities.decorators import ajax_call\r\nfrom lite_mms.models import UnloadSession, GoodsReceipt, UnloadTask\r\nfrom flask.ext.babel import _\r\n\r\n\r\n@cargo_page.route(\"/ajax/receipts-list\", methods=[\"GET\"])\r\n@ajax_call\r\ndef receipts_list():\r\n session_id = request.args.get(\"unload_session_id\", type=int)\r\n if session_id is not None:\r\n import lite_mms.apis as apis\r\n\r\n receipts = apis.cargo.get_goods_receipts_list(session_id)\r\n if not receipts:\r\n return _(u\"当前没有任何收货单\"), 404\r\n return json.dumps([dict(id=r.id, receipt_id=str(r.receipt_id),\r\n customer=r.customer.name)\r\n for r in receipts])\r\n else:\r\n return u\"未选择卸货会话\", 403\r\n\r\n\r\n@cargo_page.route(\"/ajax/goods-receipt\", methods=[\"POST\"])\r\n@ajax_call\r\ndef ajax_receipt():\r\n class _POST_Form(Form):\r\n id = TextField(\"id\")\r\n task_id = TextField(\"task_id\")\r\n product_id = TextField(\"product_id\")\r\n weight = IntegerField(\"weight\")\r\n\r\n form = _POST_Form(request.form)\r\n receipt_id = form.id.data\r\n\r\n if receipt_id:\r\n try:\r\n import lite_mms.apis as apis\r\n\r\n apis.cargo.get_goods_receipt(receipt_id).update(\r\n printed=True)\r\n return _(u\"更新成功\")\r\n except SQLAlchemyError:\r\n return _(u\"更新失败\"), 403\r\n except AttributeError:\r\n return _(u\"无此收货单\"), 404\r\n else:\r\n task_id = form.task_id.data\r\n product_id = form.product_id.data\r\n weight = form.weight.data or '' #integer field默认值为None。所以需要将None设置为''\r\n import lite_mms.apis as apis\r\n\r\n ut = apis.cargo.get_unload_task(task_id)\r\n if not ut or not (product_id or weight):\r\n return _(u\"数据错误\"), 404\r\n try:\r\n if ut.sub_order:\r\n ut.sub_order.update(product_id=product_id, weight=weight)\r\n ut.update(product_id=product_id, weight=weight)\r\n return _(u\"更新成功\")\r\n except ValueError, e:\r\n return unicode(e), 403\r\n except SQLAlchemyError:\r\n return _(u\"更新失败\"), 403\r\n\r\n@cargo_page.route(\"/ajax/unload-task/<int:id_>\", methods=[\"POST\"])\r\n@ajax_call\r\ndef unload_task(id_):\r\n if request.form[\"action\"] == \"delete\":\r\n ut = get_or_404(UnloadTask, id_)\r\n if ut.weight != 0:\r\n return u\"已经称重的卸货任务不能删除\", 403\r\n else:\r\n if ut.delete():\r\n flash(u\"删除卸货任务%d成功\" % ut.id)\r\n return \"success\"\r\n return \"error\", 403" }, { "alpha_fraction": 0.4942900240421295, "alphanum_fraction": 0.5024779438972473, "avg_line_length": 44.5, "blob_id": "3d54d90fbaa95c6418364b4850af4fbee8291c7d", "content_id": "75581b0af7809deab78cf4e63c7beb1c5a595b40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5261, "license_type": "no_license", "max_line_length": 78, "num_lines": 102, "path": "/lite_mms/test/at/test_manufacture.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nfrom hashlib import md5\n\nfrom pyfeature import (Feature, Scenario, when, and_, then,\n flask_sqlalchemy_setup, clear_hooks)\n\nimport lite_mms\nfrom lite_mms.constants import groups as groups_const\nfrom lite_mms.basemain import app\nfrom lite_mms.database import db\n\n\ndef test():\n flask_sqlalchemy_setup(\n app, db, create_step_prefix=u\"创建\",\n model_name_getter=lambda model: model.__name__,\n attr_name_getter=lambda model, attr: model.__col_desc__.get(attr,\n attr),\n set_step_pattern=u'(\\w+)([\\.\\w+]+)设置为(.+)')\n\n with Feature(u'工单测试', step_files=['lite_mms.test.at.steps.manufacture']):\n with Scenario(u'准备数据'):\n cargo_clerk_group = and_(u'创建Group(cargo_clerk)',\n id=lite_mms.constants.groups.CARGO_CLERK)\n cargo_clerk = and_(u'创建User', username='cc',\n password=md5('cc').hexdigest(),\n groups=[cargo_clerk_group])\n scheduler_group = and_(u'创建Group(scheduler)',\n id=lite_mms.constants.groups.SCHEDULER)\n and_(u'创建User', username='s', password=md5('s').hexdigest(),\n groups=[scheduler_group])\n customer = and_(u'创建Customer', name='foo', abbr='foo')\n plate = and_(u'创建Plate', name='foo')\n unload_session = and_(u'创建UnloadSession', plate_=plate,\n gross_weight=5000)\n goods_receipt = and_(u'创建GoodsReceipt', customer=customer,\n unload_session=unload_session,\n creator=cargo_clerk)\n order = and_(u'创建Order', goods_receipt=goods_receipt,\n creator=cargo_clerk)\n product_type = and_(u'创建ProductType', name='foo')\n product = and_(u'创建Product', name='foo',\n product_type=product_type)\n harbor = and_(u'创建Harbor', name='foo')\n sub_order = and_(u'创建SubOrder', product=product, weight=100,\n harbor=harbor, order=order, quantity=100,\n unit='KG')\n department_leader_group = and_(u'创建Group(department_leader)',\n id=groups_const.DEPARTMENT_LEADER)\n department_leader = and_(u'创建User', username='dl',\n password=md5('dl').hexdigest(),\n groups=[department_leader_group])\n department = and_(u'创建Department', name='foo',\n leader_list=[department_leader],\n harbor_list=[harbor])\n team_leader_group = and_(u'创建Group(team_leader)',\n id=groups_const.TEAM_LEADER)\n team_leader = and_(u'创建User', username='tl',\n password=md5('tl').hexdigest(),\n groups=[team_leader_group])\n team = and_(u'创建Team', name='foo', department=department,\n leader_list=[team_leader])\n quality_inspector_group = and_(u'创建Group(quality_inspector)',\n id=groups_const.QUALITY_INSPECTOR)\n and_(u'创建User', username='qi',\n password=md5('qi').hexdigest(),\n groups=[quality_inspector_group])\n\n with Scenario(u'最简流程'):\n when(u'调度员对子订单进行预排产60公斤', sub_order)\n wc = then(u'一条重量是60公斤的工单生成了', sub_order)\n and_(u'原子订单的剩余重量是40公斤', sub_order)\n when(u'调度员将工单排产给车间', wc, department)\n then(u'车间主任将看到工单', wc, department)\n then(u'车间主任将工单分配到班组', wc, department, team)\n then(u'班组长将看到工单', wc, team)\n\n when(u'班组长增加重量20公斤', wc)\n when(u'班组长增加重量30公斤', wc)\n when(u'班组长增加重量50公斤, 并且结束', wc)\n and_(u'工单的工序后重量是100公斤', wc)\n\n then(u'质检员可以看到工单', wc, team)\n\n qir = when(u'质检员全部通过该工单', wc)\n then(u'该工单已经结束', wc)\n and_(u'一条对应的仓单生成了', qir, harbor)\n\n with Scenario(u'临时保存质检报告'):\n when(u'调度员对子订单进行预排产40公斤', sub_order)\n wc = then(u'一条重量是40公斤的工单生成了', sub_order)\n and_(u'调度员将工单排产给车间', wc, department)\n and_(u'车间主任将工单分配到班组', wc, department, team)\n and_(u'班组长增加重量40公斤, 并且结束', wc)\n\n qir_list = when(u'质检员保存质检结果', wc)\n then(u'工单的质检报告列表正确保存了', wc, qir_list)\n\n clear_hooks()\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.6459695100784302, "alphanum_fraction": 0.6633986830711365, "avg_line_length": 22.157894134521484, "blob_id": "b322f51e41512a9d52584085c217fda23fb5748d", "content_id": "1162538a3dcf3176f7f2b5375658f5ffc4abdfa5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 924, "license_type": "no_license", "max_line_length": 82, "num_lines": 38, "path": "/lite_mms/default_settings.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\n\"\"\"\r\nthis is the default settings, don't insert into your customized settings!\r\n\"\"\"\r\n\r\nDEBUG = True\r\nSECRET_KEY = \"5L)0K%,i.;*i/s(\"\r\nSECURITY_SALT = \"mohnooso\"\r\n\r\n#DB config\r\nimport os.path\r\nimport sys\r\n#if os.path.exists(\"lite_mms.db\"):\r\nDBSTR = \"sqlite:///lite_mms.db\"\r\n#else:\r\n# DBSTR = \"sqlite:///\" + os.path.join(sys.prefix, \"share/lite-mms/lite_mms.db\")\r\nSQLALCHEMY_ECHO = True\r\n\r\nUPLOAD_FOLDER = \"upload\"\r\n\r\nBROKER_IP = \"192.168.0.161\"\r\nBROKER_PORT = 9090\r\nBROKER_TIMEOUT = 2 #单位秒\r\nSQLALCHEMY_ECHO=True\r\nLOCALE = \"zh_CN\"\r\nBABEL_DEFAULT_LOCALE = \"zh_CN\"\r\n# the option could be \"web\", \"webservice\" or \"both\"(which stands for both as\r\n# web and webservice)\r\nSERVE_TYPE = \"both\"\r\n\r\nimport os\r\nLOG_FILE = os.path.join(os.getcwd(), \"lite-mms.log\")\r\nREPORT_DIR = 'report_conf'\r\nSENDERS = []\r\nCODERNITY_DATABASE_PATH = \"codernity_db\"\r\nFLASK_REPORT_SEND_NOTIFICATION = False\r\n\r\nHIDE_INDIVIDUAL = False\r\n" }, { "alpha_fraction": 0.664195716381073, "alphanum_fraction": 0.6649370193481445, "avg_line_length": 32.296295166015625, "blob_id": "7d491a04c0f8e2376c93a94a387cf531a9bb2d9b", "content_id": "76eb65b35f878b7ec14138ee2ee20772feee03eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2766, "license_type": "no_license", "max_line_length": 157, "num_lines": 81, "path": "/lite_mms/portal/cargo/fsm.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom lite_sm import StateMachine, State, RuleSpecState, InvalidAction\nfrom lite_mms.constants import cargo as cargo_const\nfrom lite_mms.permissions.roles import CargoClerkPermission\nfrom lite_mms.utilities.decorators import committed\nfrom lite_mms.basemain import timeline_logger\n\nclass UnloadSessionFSM(StateMachine):\n\n def reset_obj(self, obj):\n if obj.status == cargo_const.STATUS_LOADING:\n self.set_current_state(state_loading)\n elif obj.status == cargo_const.STATUS_WEIGHING:\n self.set_current_state(state_weighing)\n elif obj.status == cargo_const.STATUS_CLOSED:\n self.set_current_state(state_closed)\n self.obj = obj\n\n def do_log(self, action, actor):\n #msg = u\"用户(%s)对卸货会话%s执行了%s操作,卸货会话的状态从(%s)转变为(%s)\" % (actor.username, self.obj, cargo_const.desc_action(action), self.last_state, self.current_state)\n msg = \"\"\n self.logger.info(msg, extra={\"obj\": self.obj.model, \"actor\": actor, \"action\": cargo_const.desc_action(action), \"obj_pk\": self.obj.id})\n\nfsm = UnloadSessionFSM(logger=timeline_logger)\n\nclass StateLoading(RuleSpecState):\n status = cargo_const.STATUS_LOADING\n\n def __unicode__(self):\n return u\"正在卸载\"\n \n @committed\n def side_effect(self, **kwargs):\n self.obj.status = cargo_const.STATUS_LOADING\n self.obj.finish_time = None\n return self.obj.model\n\nstate_loading = StateLoading(fsm, {\n cargo_const.ACT_LOAD: (cargo_const.STATUS_WEIGHING, None),\n cargo_const.ACT_CLOSE: (cargo_const.STATUS_CLOSED, None)\n})\n\nclass StateWeighing(State):\n status = cargo_const.STATUS_WEIGHING\n\n def __unicode__(self):\n return u\"等待称重\"\n\n @committed\n def side_effect(self, **kwargs):\n self.obj.status = cargo_const.STATUS_WEIGHING \n return self.obj.model\n\n def next(self, action):\n CargoClerkPermission.test()\n if action == cargo_const.ACT_WEIGHT:\n if self.obj.task_list and self.obj.task_list[-1].is_last:\n return state_closed\n return state_loading\n else:\n raise InvalidAction(fsm.invalid_info(action, self))\n\nstate_weighing = StateWeighing(fsm)\n\nclass StateClosed(RuleSpecState):\n status = cargo_const.STATUS_CLOSED\n\n def __unicode__(self):\n return u\"关闭\"\n\n @committed\n def side_effect(self, **kwargs):\n CargoClerkPermission.test()\n self.obj.status = cargo_const.STATUS_CLOSED\n from datetime import datetime\n self.obj.finish_time = datetime.now()\n return self.obj.model\n\nstate_closed = StateClosed(fsm, {\n cargo_const.ACT_OPEN: (cargo_const.STATUS_LOADING, CargoClerkPermission)\n})\n\n" }, { "alpha_fraction": 0.5191325545310974, "alphanum_fraction": 0.5261008143424988, "avg_line_length": 40.82663345336914, "blob_id": "97e292d00db28bd0cf97c74d3a199b436d4feb37", "content_id": "33498483e2bb01c9cb70690aeba1b3750b531b98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16765, "license_type": "no_license", "max_line_length": 83, "num_lines": 398, "path": "/lite_mms/portal/manufacture_ws/webservices.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8\nimport time\nfrom datetime import datetime, date, timedelta\nimport json\nimport os\nimport types\nfrom flask import request\nfrom flask.ext.login import current_user\nfrom flask.ext.babel import _\nfrom wtforms import (Form, IntegerField, StringField, validators,\n ValidationError)\nimport lite_mms\nfrom lite_mms import apis\nfrom lite_mms import models\nfrom lite_mms.utilities import get_or_404\nfrom lite_mms.basemain import app\nimport lite_mms.constants.work_command as wc_const\nfrom lite_mms import constants\nfrom lite_mms.portal.manufacture_ws import manufacture_ws\nfrom lite_mms.utilities.decorators import (webservice_call,\n login_required_webservice,\n permission_required_webservice)\nfrom lite_mms.utilities import to_timestamp, gen_qir_pic_path\nfrom lite_mms.database import db\nfrom lite_mms.permissions.roles import (TeamLeaderPermission,\n DepartmentLeaderPermission,\n QualityInspectorPermission)\n\n\ndef _qir2dict(qir):\n return dict(id=qir.id, actorId=qir.actor_id, quantity=qir.quantity,\n weight=qir.weight, result=qir.result,\n picUrl=qir.pic_url, smallPicUrl=qir.small_pic_url)\n\n\ndef _work_command_to_dict(wc):\n qirs, total_cnt = lite_mms.apis.quality_inspection.get_qir_list(wc.id)\n\n return dict(id=wc.id,\n customerName=wc.order.customer.name,\n department=dict(id=wc.department.id,\n name=wc.department.name) if wc.department\n else \"\",\n isUrgent=1 if wc.urgent else 0,\n spec=wc.sub_order.spec,\n type=wc.sub_order.type,\n lastMod=to_timestamp(wc.last_mod),\n orderID=wc.sub_order.order_id,\n orderNum=wc.sub_order.order.customer_order_number,\n orderCreateTime=time.mktime(wc.sub_order.order.create_time.\n timetuple()),\n orderType=wc.sub_order.order_type,\n orgCount=wc.org_cnt,\n orgWeight=wc.org_weight,\n picPath=wc.pic_url,\n smallPicPath=wc.small_pic_url,\n previousProcedure=wc.previous_procedure.name if wc\n .previous_procedure else \"\",\n procedure=wc.procedure.name if wc.procedure else \"\",\n processedCount=wc.processed_cnt,\n processedWeight=wc.processed_weight or 0,\n productName=wc.sub_order.product.name,\n status=wc.status,\n subOrderId=wc.sub_order_id,\n team=dict(id=wc.team.id, name=wc.team.name) if wc.team else \"\",\n technicalRequirements=wc.tech_req,\n handleType=wc.handle_type,\n deduction=wc.deduction,\n unit=wc.unit,\n rejected=int(wc.sub_order.returned),\n qirList=[_qir2dict(qir) for qir in qirs])\n\n\n@manufacture_ws.route(\"/work-command-list\", methods=[\"GET\"])\n@webservice_call(\"json\")\n@login_required_webservice\ndef work_command_list():\n class _ValidationForm(Form):\n def validate_status(self, field):\n status_list = field.data.split(\",\")\n valid_status = [wc_const.STATUS_DISPATCHING,\n wc_const.STATUS_ASSIGNING,\n wc_const.STATUS_ENDING,\n wc_const.STATUS_LOCKED,\n wc_const.STATUS_REFUSED,\n wc_const.STATUS_QUALITY_INSPECTING,\n wc_const.STATUS_FINISHED]\n if not all(status.isdigit() and int(status) in valid_status for\n status in status_list):\n raise ValidationError(\"status must be one of \" +\n \", \".join(str(i) for i in valid_status))\n\n department_id = IntegerField(u\"department id\")\n team_id = IntegerField(u\"team id\")\n start = IntegerField(u\"start\")\n cnt = IntegerField(u\"count\")\n status = StringField(u\"status\", [validators.DataRequired()])\n\n form = _ValidationForm(request.args)\n if form.validate():\n status_list = [int(status) for status in form.status.data.split(',')]\n param_dict = dict(status_list=status_list)\n\n if len(status_list) == 1 and \\\n status_list[0] == wc_const.STATUS_FINISHED:\n param_dict[\"date\"] = datetime.now().date() - timedelta(days=1)\n if form.department_id.data is not None:\n param_dict.update(department_id=form.department_id.data)\n if form.team_id.data is not None:\n param_dict.update(team_id=form.team_id.data)\n if form.start.data is not None:\n param_dict.update(start=form.start.data)\n if form.cnt.data is not None:\n param_dict.update(cnt=form.cnt.data)\n\n wc_list, total_cnt = apis.manufacture.get_work_command_list(\n **param_dict)\n return json.dumps(\n dict(data=[_work_command_to_dict(wc) for wc in wc_list],\n totalCnt=total_cnt))\n else:\n # we disable E1101, since it's a bug of pylint\n return str(form.errors), 412\n\n\n@manufacture_ws.route(\"/team-list\", methods=[\"GET\"])\n@webservice_call(\"json\")\ndef team_list():\n department_id = request.args.get(\"department_id\", type=int)\n if department_id is None:\n teams = lite_mms.models.Team.query.all()\n return json.dumps([dict(name=t.name, id=t.id) for t in teams])\n else:\n teams = apis.manufacture.get_team_list(department_id)\n return json.dumps([dict(name=t.name, id=t.id) for t in teams])\n\n\n@manufacture_ws.route(\"/department-list\", methods=[\"GET\"])\n@webservice_call(\"json\")\ndef department_list():\n departments = lite_mms.models.Department.query.all()\n return json.dumps([dict(id=d.id, name=d.name,\n team_id_list=[t.id for t in d.team_list])\n for d in departments])\n\n\n@manufacture_ws.route(\"/work-command/<work_command_id>\",\n methods=[\"GET\", \"PUT\"])\n@webservice_call(\"json\")\ndef work_command(work_command_id):\n if request.method == 'PUT':\n action = request.args.get('action', type=int)\n if action in {wc_const.ACT_ASSIGN,\n wc_const.ACT_REFUSE,\n wc_const.ACT_AFFIRM_RETRIEVAL,\n wc_const.ACT_REFUSE_RETRIEVAL}:\n permission = DepartmentLeaderPermission\n elif action in {wc_const.ACT_ADD_WEIGHT,\n wc_const.ACT_END,\n wc_const.ACT_CARRY_FORWARD,\n wc_const.ACT_QUICK_CARRY_FORWARD}:\n permission = TeamLeaderPermission\n else:\n permission = QualityInspectorPermission\n\n func = permission_required_webservice(permission)(_work_command)\n else:\n func = login_required_webservice(_work_command)\n return func(work_command_id)\n\n\ndef _work_command(work_command_id):\n if request.method == 'GET':\n wc = get_or_404(models.WorkCommand, work_command_id)\n return json.dumps(_work_command_to_dict(wc))\n else: # PUT\n class _ValidationForm(Form):\n def validate_team_id(self, field):\n if self.action.data == wc_const.ACT_ASSIGN:\n if field.data is None:\n raise ValidationError(\"team required when assigning \\\nwork command\")\n\n def validate_weight(self, field):\n if self.action.data == wc_const.ACT_ADD_WEIGHT or \\\n self.action.data == wc_const.ACT_AFFIRM_RETRIEVAL:\n if field.data is None:\n raise ValidationError(_(\"需要weight字段\"))\n\n def validate_is_finished(self, field):\n if field.data is not None:\n if field.data not in [0, 1]:\n raise ValidationError(\"is finished should be 0 or 1\")\n\n quantity = IntegerField(u\"quantity\")\n weight = IntegerField(u\"weight\")\n remain_weight = IntegerField(u\"remain_weight\")\n team_id = IntegerField(u\"team id\")\n action = IntegerField(u\"action\", [validators.DataRequired()])\n is_finished = IntegerField(u\"is finished\")\n deduction = IntegerField(u\"deduction\")\n\n form = _ValidationForm(request.args)\n if form.validate():\n if form.action.data == wc_const.ACT_ASSIGN:\n try:\n wc = get_or_404(models.WorkCommand, work_command_id)\n wc.go(actor_id=current_user.id, action=form.action.data,\n team_id=form.team_id.data)\n except ValueError, e:\n return unicode(e), 403\n result = wc\n elif form.action.data == wc_const.ACT_AFFIRM_RETRIEVAL:\n kwargs = {\"weight\": form.weight.data}\n try:\n wc = get_or_404(models.WorkCommand, work_command_id)\n\n if not wc.sub_order.measured_by_weight:\n kwargs.update(quantity=form.quantity.data)\n wc.go(actor_id=current_user.id, action=form.action.data,\n **kwargs)\n except ValueError, e:\n return unicode(e), 403\n result = wc\n elif form.action.data == wc_const.ACT_ADD_WEIGHT:\n kwargs = {\"weight\": form.weight.data}\n try:\n wc = get_or_404(models.WorkCommand, work_command_id)\n\n if not wc.sub_order.measured_by_weight:\n kwargs.update(quantity=form.quantity.data)\n wc.go(actor_id=current_user.id, action=form.action.data,\n **kwargs)\n if form.is_finished.data:\n wc.go(actor_id=current_user.id,\n action=wc_const.ACT_END)\n except ValueError, e:\n return unicode(e), 403\n result = wc\n elif form.action.data == wc_const.ACT_QI:\n try:\n wc = get_or_404(models.WorkCommand, work_command_id)\n\n qir_pic_path_map = {}\n\n for path, f in request.files.items():\n idx = int(path.split(\".\")[0])\n pic_path = gen_qir_pic_path(idx)\n f.save(os.path.join(app.config[\"UPLOAD_FOLDER\"], pic_path))\n qir_pic_path_map[idx] = pic_path\n\n qir_list = [dict(result=qir['result'],\n weight=qir['weight'],\n quantity=qir.get('quantity'),\n actor_id=current_user.id,\n pic_path=qir_pic_path_map.get(idx, \"\"))\n for idx, qir in\n enumerate(json.loads(request.form['qirList']))]\n if wc.sub_order.order_type == \\\n constants.STANDARD_ORDER_TYPE:\n for qir in qir_list:\n qir['quantity'] = qir['weight']\n else:\n for qir in qir_list:\n if qir['quantity'] is None:\n return u'计件类型工单质检时必须上传数量', 403\n wc.go(actor_id=current_user.id, action=form.action.data,\n deduction=form.deduction.data or 0,\n qir_list=qir_list)\n except ValueError, e:\n return unicode(e), 403\n result = wc\n elif form.action.data in [wc_const.ACT_CARRY_FORWARD,\n wc_const.ACT_REFUSE_RETRIEVAL,\n wc_const.ACT_END,\n wc_const.ACT_REFUSE]:\n try:\n wc_id_list = [int(wc_id) for wc_id in\n work_command_id.split(\",\")]\n except ValueError:\n return \"work command id should be integer\", 403\n result = []\n # TODO may be it could be done batchly\n for _work_command_id in wc_id_list:\n wc = get_or_404(models.WorkCommand, _work_command_id)\n\n try:\n wc.go(actor_id=current_user.id,\n action=form.action.data)\n except ValueError, e:\n return unicode(e), 403\n result.append(wc)\n if len(result) == 1:\n result = result[0]\n # pylint: enable=R0912\n elif form.action.data == wc_const.ACT_RETRIVE_QI:\n\n try:\n wc = get_or_404(models.WorkCommand, work_command_id)\n\n if wc.last_mod.date() < date.today():\n return u'不能取消今天以前的质检单', 403\n\n wc.go(actor_id=current_user.id, action=form.action.data)\n except ValueError, e:\n return unicode(e), 403\n result = wc\n elif form.action.data == wc_const.ACT_QUICK_CARRY_FORWARD:\n try:\n wc = get_or_404(models.WorkCommand, work_command_id)\n\n if wc.processed_weight <= 0:\n return u'未加工过的工单不能快速结转', 403\n\n wc.go(actor_id=current_user.id, action=form.action.data)\n except ValueError, e:\n return unicode(e), 403\n result = wc\n else:\n return \"error action\", 403\n if isinstance(result, types.ListType):\n return json.dumps([_work_command_to_dict(wc_) for wc_ in\n result])\n else:\n return json.dumps(_work_command_to_dict(result))\n else:\n return str(form.errors), 403\n\n\ndef _handle_delete():\n from lite_mms.apis import quality_inspection\n\n id_ = request.args.get(\"id\", type=int)\n if not id_:\n return \"id and required\", 403\n try:\n return quality_inspection.remove_qi_report(id_=id_,\n actor_id=current_user.id)\n except ValueError, e:\n return unicode(e), 403\n\n\n@manufacture_ws.route(\"/off-duty\", methods=[\"POST\"])\n@login_required_webservice\ndef off_duty():\n if not current_user.is_anonymous:\n cnt = 0\n from lite_mms.apis import manufacture\n\n for team in current_user.team_list:\n wc_list, total_cnt = manufacture.get_work_command_list(\n status_list=[wc_const.STATUS_ENDING],\n team_id=team.id)\n for wc in wc_list:\n try:\n wc.go(actor_id=current_user.id,\n action=wc_const.ACT_CARRY_FORWARD)\n cnt += 1\n except ValueError, e:\n return unicode(e), 403\n return str(cnt)\n else:\n return \"actor id is required\", 403\n\n\n@manufacture_ws.route('/quality-inspection-report-list', methods=['PUT'])\n@permission_required_webservice(QualityInspectorPermission)\ndef quality_inspection_report_list():\n\n work_command_id = request.args.get('work_command_id', type=int)\n wc = get_or_404(models.WorkCommand, work_command_id)\n\n qir_list = json.loads(request.form['qirList'])\n if wc.sub_order.order_type == constants.STANDARD_ORDER_TYPE:\n for qir in qir_list:\n qir['quantity'] = qir['weight']\n else:\n for qir in qir_list:\n if qir['quantity'] is None:\n return u'计件类型工单质检时必须上传数量', 403\n\n # clear the original qir list\n wc.qir_list = []\n qir_pic_path_map = {}\n\n for path, f in request.files.items():\n idx = int(path.split(\".\")[0])\n pic_path = gen_qir_pic_path(idx)\n f.save(os.path.join(app.config[\"UPLOAD_FOLDER\"], pic_path))\n qir_pic_path_map[idx] = pic_path\n\n for idx, qir_dict in enumerate(qir_list):\n db.session.add(models.QIReport(wc.model, qir_dict['quantity'],\n qir_dict['weight'], qir_dict['result'],\n current_user.id,\n pic_path=qir_pic_path_map.get(idx, '')))\n db.session.commit()\n return \"\"\n" }, { "alpha_fraction": 0.6411150097846985, "alphanum_fraction": 0.6550522446632385, "avg_line_length": 29.88888931274414, "blob_id": "33d93ab87f2080b52cd2a97572f8f548e30fcdb0", "content_id": "e0c0bfb3339635aadf4ea1b5d8e83ffaabb37630", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 287, "license_type": "no_license", "max_line_length": 68, "num_lines": 9, "path": "/lite_mms/utilities/jinja_filters.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "from flask import request,url_for\r\n\r\ndef url_for_other_page(page):\r\n args = request.args.copy()\r\n args['page'] = page\r\n return url_for(request.endpoint, **args) # pylint: disable=W0142\r\n\r\ndef datetimeformat(value, format='%H:%M / %d-%m-%Y'):\r\n return value.strftime(format)\r\n" }, { "alpha_fraction": 0.6800000071525574, "alphanum_fraction": 0.7275675535202026, "avg_line_length": 30.89655113220215, "blob_id": "6530fb2a768f1b662fcd60f58b03c3c1be31a1ef", "content_id": "79885d5e65eec452b3ce2785e54bcc64f688171e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 925, "license_type": "no_license", "max_line_length": 175, "num_lines": 29, "path": "/alembic/versions/35979bf471d6_let_the_default_url_.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"let the default url of accountant point to new congignment list\n\nRevision ID: 35979bf471d6\nRevises: 18d5259ad2f7\nCreate Date: 2013-05-03 18:45:20.162994\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '35979bf471d6'\ndown_revision = '18d5259ad2f7'\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.sql import table, column\n\nfrom lite_mms.constants import groups\ngroup_table = table(\n \"TB_GROUP\",\n sa.Column(\"id\", sa.Integer, primary_key=True),\n sa.Column(\"name\", sa.String(32), nullable=False, unique=True),\n sa.Column(\"default_url\", sa.String(256))\n)\n\ndef upgrade():\n op.execute(group_table.update().where(group_table.c.id==groups.ACCOUNTANT).values({\"default_url\": \"/consignment/consignment-list?order_by=create_time&desc=1&customer=1\"}))\n\ndef downgrade():\n op.execute(group_table.update().where(group_table.c.id==groups.ACCOUNTANT).values({\"default_url\": \"/delivery/consignment-list\"}))\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6683333516120911, "avg_line_length": 24, "blob_id": "50ad980ba64a88f3b6da273f0951f65c2115fa24", "content_id": "449d64b4d231b271110ebdc14807baf106bd5e5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 608, "license_type": "no_license", "max_line_length": 66, "num_lines": 24, "path": "/lite_mms/portal/todo/views.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom flask.ext.databrowser import ModelView, filters\nfrom flask.ext.login import login_required, current_user\nfrom lite_mms.apis import wraps\n\nfrom lite_mms import models\n\n\nclass TODOView(ModelView):\n __default_order__ = (\"id\", \"desc\")\n\n list_template = \"todo/o-list.html\"\n\n def __list_filters__(self):\n return [filters.EqualTo(\"user_id\", value=current_user.id)]\n\n def scaffold_list(self, models):\n return [wraps(obj) for obj in models]\n\n @login_required\n def try_view(self, list_=None):\n pass\n\nto_do_view = TODOView(models.TODO, u\"待办事项\")\n" }, { "alpha_fraction": 0.621082603931427, "alphanum_fraction": 0.6346153616905212, "avg_line_length": 32.819278717041016, "blob_id": "b5ce26283eeecd5766f959ad97af3383d27727be", "content_id": "eaf6594301b648707754d6728efaecd93267a938", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2892, "license_type": "no_license", "max_line_length": 111, "num_lines": 83, "path": "/lite_mms/test/at/steps/order.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom flask import g, _request_ctx_stack, session\nfrom pyfeature import step\n\nfrom lite_mms import models, constants\nfrom lite_mms.basemain import timeline_logger, app\nfrom lite_mms.utilities import do_commit\n\ntimeline_logger.handlers = []\n\napp.config[\"CSRF_ENABLED\"] = False\napp.config[\"WTF_CSRF_ENABLED\"] = False\n\ndef generate(times=1):\n from random import choice\n import string\n\n temp = \"\"\n for i in range(times):\n temp += choice(string.letters)\n return temp\n\[email protected]_request\ndef patch():\n \"\"\"\n needn't login in\n \"\"\"\n g.identity.can = lambda p: True\n from lite_mms.apis.auth import UserWrapper\n user = UserWrapper(models.User.query.first())\n session['current_group_id'] = user.groups[0].id\n _request_ctx_stack.top.user = user\n\n\n@step(u\"收货单\")\ndef _(step, customer, harbor):\n plate = do_commit(models.Plate(name=generate(5)))\n unload_session = do_commit(models.UnloadSession(plate_=plate, gross_weight=50000))\n product_type = do_commit(models.ProductType(name=generate(5)))\n product = do_commit(models.Product(name=generate(5), product_type=product_type))\n procedure = do_commit(models.Procedure(name=generate(5)))\n goods_receipt = do_commit(models.GoodsReceipt(customer=customer, unload_session=unload_session))\n for i in xrange(3):\n goods_receipt_entry = do_commit(\n models.GoodsReceiptEntry(goods_receipt=goods_receipt, product=product, weight=5000, harbor=harbor))\n return goods_receipt\n\n\n@step(u\"生成订单\")\ndef _(step, goods_receipt, order_type):\n if order_type == constants.STANDARD_ORDER_TYPE:\n action = u\"生成计重类型订单\"\n else:\n action = u\"生成计件类型订单\"\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(\"/goods_receipt/goods-receipt/%d\" % goods_receipt.id, data={\"__action__\": action})\n assert 302 == rv.status_code\n return models.Order.query.order_by(models.Order.id.desc()).first()\n\n\n@step(u\"完善订单\")\ndef _(step, order):\n for count, sub_order in enumerate(order.sub_order_list):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(\"/order/sub-order/%d\" % sub_order.id, data={\"due_time\": \"2013-08-09\"})\n assert 302 == rv.status_code\n if count == len(order.sub_order_list) - 1:\n rv = c.post(\"/order/order/%d\" % order.id, data={\"__action__\": u\"标记为完善\"})\n assert 302 == rv.status_code\n\n\n@step(u\"下发订单\")\ndef _(step, order):\n with app.test_request_context():\n with app.test_client() as c:\n rv = c.post(\"/order/order/%s\" % order.id, data={\"__action__\": u\"下发\"})\n return rv.status_code\n\n@step(u\"操作成功\")\ndef _(step, status_code):\n assert 302 == status_code\n\n" }, { "alpha_fraction": 0.6083915829658508, "alphanum_fraction": 0.6550116539001465, "avg_line_length": 18.5, "blob_id": "f26d6ae2cd4aaa85a05ab98100f03d137a531f07", "content_id": "d07af8403ca95e805537f4c2cc059afb26f33656", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 429, "license_type": "no_license", "max_line_length": 65, "num_lines": 22, "path": "/alembic/versions/51242e27bc6_add_is_last_to_unloa.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"add is_last to unload task\n\nRevision ID: 51242e27bc6\nRevises: d9c0f19bdf3\nCreate Date: 2013-03-26 11:03:42.724269\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '51242e27bc6'\ndown_revision = 'd9c0f19bdf2'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.add_column(\"TB_UNLOAD_TASK\", \n sa.Column(\"is_last\", sa.Boolean, default=False))\n\ndef downgrade():\n op.drop_column(\"TB_UNLOAD_TASK\", \"is_last\")\n" }, { "alpha_fraction": 0.7799999713897705, "alphanum_fraction": 0.7833333611488342, "avg_line_length": 32.22222137451172, "blob_id": "fe657d7c8a397847b105173817402b5574d0bcb1", "content_id": "dcbec5cb943b7ec19672f841f9ac476b281a6858", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 316, "license_type": "no_license", "max_line_length": 56, "num_lines": 9, "path": "/lite_mms/permissions/data.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nfrom collections import namedtuple\nfrom flask.ext.principal import Permission\n\nDataManagement = namedtuple(\"data\", [\"method\"])\nExportConsignment = DataManagement(\"export_consignment\")\n\nexport_consignment = Permission(ExportConsignment)\nexport_consignment.brief = u\"导出发货单的权限\"\n\n" }, { "alpha_fraction": 0.5972780585289001, "alphanum_fraction": 0.60006183385849, "avg_line_length": 36.46428680419922, "blob_id": "c35c45e550c2437696e29b4cfd7770b01f9c56a1", "content_id": "da3a92d56d3554b0ea7ae3d95e5a4e09433c10ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3245, "license_type": "no_license", "max_line_length": 87, "num_lines": 84, "path": "/lite_mms/portal/cargo_ws/webservices.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\nfrom datetime import datetime\r\nimport json\r\nimport os.path\r\n\r\nfrom flask import request\r\nfrom flask.ext.login import current_user\r\nfrom wtforms import validators, Form, IntegerField, StringField\r\n\r\nfrom lite_mms.portal.cargo_ws import cargo_ws\r\nfrom lite_mms.utilities.decorators import (webservice_call, login_required_webservice, \r\n permission_required_webservice)\r\nfrom lite_mms.basemain import app\r\nfrom lite_mms.permissions.roles import LoaderPermission\r\n\r\n\r\n@cargo_ws.route(\"/unload-session-list\", methods=[\"GET\"])\r\n@webservice_call(\"json\")\r\n@login_required_webservice\r\ndef unload_session_list():\r\n \"\"\"\r\n get **unfinished** unload sessions from database, accept no arguments\r\n \"\"\"\r\n\r\n import lite_mms.apis as apis\r\n\r\n unload_sessions, total_cnt = apis.cargo.get_unload_session_list(\r\n unfinished_only=True)\r\n data = [{'plateNumber': us.plate, 'sessionID': us.id,\r\n 'isLocked': int(us.is_locked)} for us in\r\n unload_sessions]\r\n return json.dumps(dict(data=data, total_cnt=total_cnt))\r\n\r\n\r\n@cargo_ws.route(\"/harbour-list\", methods=[\"GET\"])\r\n@cargo_ws.route(\"/harbor-list\", methods=[\"GET\"])\r\n@login_required_webservice\r\ndef harbour_list():\r\n from lite_mms.apis.harbor import get_harbor_list\r\n\r\n return json.dumps([harbor.name for harbor in get_harbor_list()])\r\n\r\n\r\n@cargo_ws.route(\"/unload-task\", methods=[\"POST\"])\r\n@permission_required_webservice(LoaderPermission)\r\ndef unload_task():\r\n\r\n class _ValidationForm(Form):\r\n session_id = IntegerField(\"session id\", [validators.DataRequired()])\r\n harbour = StringField(\"harbour\", [validators.DataRequired()])\r\n customer_id = IntegerField(\"customer id\", [validators.DataRequired()])\r\n is_finished = IntegerField(\"is finished\", default=0)\r\n\r\n try:\r\n f = request.files.values()[0]\r\n except IndexError:\r\n f = None\r\n pic_path = \"\"\r\n if f:\r\n pic_path = datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S.jpg\")\r\n f.save(os.path.join(app.config[\"UPLOAD_FOLDER\"], pic_path))\r\n form = _ValidationForm(request.args)\r\n if not form.validate():\r\n return json.dumps(form.errors), 403\r\n import lite_mms.apis as apis\r\n\r\n try:\r\n unload_session = apis.cargo.get_unload_session(form.session_id.data)\r\n from lite_mms.portal.cargo.fsm import fsm\r\n from lite_mms.constants import cargo as cargo_const\r\n if unload_session:\r\n fsm.reset_obj(unload_session)\r\n fsm.next(cargo_const.ACT_LOAD, current_user)\r\n new_task = apis.cargo.new_unload_task(session_id=unload_session.id,\r\n harbor=form.harbour.data,\r\n customer_id=form.customer_id.data,\r\n creator_id=current_user.id,\r\n pic_path=pic_path,\r\n is_last=form.is_finished.data)\r\n return json.dumps(new_task.id)\r\n else:\r\n return u\"无此卸货会话%d\" % form.session_id.data\r\n except Exception, e: \r\n return unicode(e), 403\r\n\r\n" }, { "alpha_fraction": 0.6305969953536987, "alphanum_fraction": 0.7002487778663635, "avg_line_length": 31.5, "blob_id": "4623f07e7dc48996b7ca13dab06e42e8084b4937", "content_id": "f745e7f1506889584a2572e344c52815bc2d2e5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 804, "license_type": "no_license", "max_line_length": 229, "num_lines": 24, "path": "/alembic/versions/196b293a6da2_update_returned_weig.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"update returned_weight\r\n\r\nRevision ID: 196b293a6da2\r\nRevises: 53c00532a76\r\nCreate Date: 2013-03-11 10:09:46.289000\r\n\r\n\"\"\"\r\n\r\n# revision identifiers, used by Alembic.\r\nrevision = '196b293a6da2'\r\ndown_revision = '53c00532a76'\r\n\r\nfrom alembic import op\r\nimport sqlalchemy as sa\r\n\r\n\r\ndef upgrade():\r\n op.add_column(\"TB_DELIVERY_TASK\", sa.Column(\"returned_weight\", sa.Integer))\r\n op.execute(\"UPDATE TB_DELIVERY_TASK T SET T.RETURNED_WEIGHT = ( SELECT SUM(S.WEIGHT) FROM TB_STORE_BILL S, TB_SUB_ORDER O WHERE S.SUB_ORDER_ID = O.ID AND O.RETURNED = 1 AND S.DELIVERY_TASK_ID = T.ID GROUP BY T.ID ); COMMIT;\")\r\n op.execute(\"UPDATE TB_DELIVERY_TASK T SET T.RETURNED_WEIGHT = 0 WHERE T.RETURNED_WEIGHT IS NULL; COMMIT;\")\r\n\r\n\r\ndef downgrade():\r\n op.drop_column(\"TB_DELIVERY_TASK\", \"returned_weight\")\r\n" }, { "alpha_fraction": 0.5621035695075989, "alphanum_fraction": 0.5685782432556152, "avg_line_length": 29.893877029418945, "blob_id": "a377d99d4117173a0824456c3ce56006db6f8665", "content_id": "4fc3f2763dd1bd03d7e4383bd69ed0db8b7a3e07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7572, "license_type": "no_license", "max_line_length": 79, "num_lines": 245, "path": "/broker/BrokerService.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n@author: Yangminghua\n@version: $\n\"\"\"\nimport ConfigParser\nimport json\nimport os\nimport sys\nfrom pyodbc import DatabaseError\nimport types\nimport datetime\nimport tornado.ioloop\nimport tornado.web\nimport win32serviceutil\nimport win32service\nimport win32event\n\ncursor = None\n\n\ndef get_config():\n cf = ConfigParser.ConfigParser()\n cf.readfp(open(os.path.join(sys.prefix, \"config.ini\")))\n return cf\n\n\ndef init_db():\n import pyodbc\n\n args = get_config()\n\n server = args.get(\"SQLServer\", \"SQLServerHost\")\n\n db = args.get(\"SQLServer\", \"DatabaseName\")\n\n user = args.get(\"SQLServer\", \"User\")\n\n password = args.get(\"SQLServer\", \"Password\")\n\n cnxn = pyodbc.connect(\n r'DRIVER={SQL SERVER};SERVER=%s;DATABASE=%s;CHARSET=UTF8;UID=%s;PWD'\n r'=%s' % (\n server, db, user, password))\n global cursor\n cursor = cnxn.cursor()\n\n\ndef main(host, port):\n init_db()\n handlers = [\n (r\"/\", IndexRequestHandler),\n (r\"/products\", ProductRequestHandler),\n (r\"/customers\", CustomerRequestHandler),\n (r\"/consignments\", ConsignmentRequestHandler),\n (r\"/product-types\", ProductTypeRequestHandler)\n ]\n application = tornado.web.Application(handlers)\n print \"Running on http://%(host)s:%(port)s/\" % {\"host\": host, \"port\": port}\n application.listen(port, address=host)\n tornado.ioloop.IOLoop.instance().start()\n\n\nclass BaseRequestHandler(tornado.web.RequestHandler):\n @tornado.web.asynchronous\n def get(self, *args, **kwargs):\n self._write(self._get, *args, **kwargs)\n\n @tornado.web.asynchronous\n def post(self, *args, **kwargs):\n self._write(self._post, *args, **kwargs)\n\n def _get(self, *args, **kwargs):\n pass\n\n def _post(self, *args, **kwargs):\n pass\n\n def _write(self, f, *args, **kwargs):\n try:\n result = f(*args, **kwargs)\n if isinstance(result, types.DictType) or \\\n isinstance(result, types.ListType):\n self.write(json.dumps(result))\n self.set_header(\"Content-Type\",\n \"application/json; charset=UTF-8\")\n else:\n self.write(result)\n self.finish()\n except Exception, e:\n self.send_error(403, exception=e)\n\n\nclass ProductRequestHandler(BaseRequestHandler):\n def _get(self, *args, **kwargs):\n ret = {}\n cursor.execute(\n \"select ProductId,ProductName,MateriaID from TotalProduct\")\n rows = cursor.fetchall()\n for row in rows:\n ret.setdefault(row.MateriaID, []).append(\n dict(id=row.ProductId,\n name=row.ProductName.strip().decode(\"GBK\")))\n return ret\n\n\nclass ProductTypeRequestHandler(BaseRequestHandler):\n def _get(self, *args, **kwargs):\n types = []\n cursor.execute(\n \"select MateriaID,MateriaName from TotalMateria where \"\n \"MateriaID in (select DISTINCT(MateriaID) from TotalProduct)\"\n )\n rows = cursor.fetchall()\n for row in rows:\n types.append(dict(id=row.MateriaID,\n name=row.MateriaName.strip().decode(\"GBK\")))\n return types\n\n\nclass CustomerRequestHandler(BaseRequestHandler):\n def _get(self, *args, **kwargs):\n customers = []\n cursor.execute(\n \"select companyid,companyname,pinyin from TotalClient where \"\n \"clienttype=2 and ifactive=0\")\n rows = cursor.fetchall()\n for row in rows:\n customers.append(\n dict(id=row.companyid,\n name=row.companyname.strip().decode(\"GBK\"),\n short=row.pinyin.strip().decode(\"GBK\")))\n return customers\n\n\nclass ConsignmentRequestHandler(BaseRequestHandler):\n def _post(self, *args, **kwargs):\n d = json.loads(self.request.body) if self.request.body else None\n if not d:\n self.send_error(status_code=403)\n consignment_id = d[\"consignment_id\"]\n customer_id = d[\"customer_id\"]\n plate = d[\"plate\"]\n weight = d[\"weight\"]\n quantity = d.get(\"quantity\", 0)\n product_list = d[\"product_list\"]\n\n cursor.execute(\n \"insert into OutDepotNew(PaperID,ClientID,AutoName,OutDate,\"\n \"AllWeight,PackNo,PiWeight,DeduceWeight,IfActive) values(?,\"\n \"?,?,?,?,?,?,?,?)\",\n (consignment_id, customer_id, plate, datetime.datetime.today(),\n weight, quantity, 0, 0, 1))\n row = cursor.execute(\"SELECT @@IDENTITY\").fetchone()\n id = int(row[0])\n\n for product in product_list:\n cursor.execute(\n \"insert into OutDepotDetail(OutPaperID,ProductID,Amount,\"\n \"Weight,IfRedo) values(?,?,?,?,?)\",\n (id, product[\"id\"], product.get(\"quantity\", 0),\n product[\"weight\"], product.get(\"isReturned\", 0)))\n try:\n cursor.commit()\n except DatabaseError, e:\n cursor.rollback()\n raise e\n return dict(id=id)\n\n def _get(self, *args, **kwargs):\n acceptances = []\n sql = \"select num, PaperID, ClientID from OutDepotNew\"\n PaperID = self.get_argument(\"PaperID\", \"\")\n if PaperID:\n sql += \" where PaperId = '%s'\" % PaperID\n cursor.execute(sql)\n rows = cursor.fetchall()\n for row in rows:\n acceptances.append(dict(id=row.PaperID.strip().decode(\"GBK\"),\n MSSQL_ID=row.num,\n clientID=row.ClientID))\n return acceptances\n\n\nclass IndexRequestHandler(tornado.web.RequestHandler):\n def get(self, *args, **kwargs):\n self.write(\"hello\")\n\n\nclass BrokerService(win32serviceutil.ServiceFramework):\n _svc_name_ = 'BrokerService'\n _svc_display_name_ = 'BrokerService'\n\n def __init__(self, *args):\n win32serviceutil.ServiceFramework.__init__(self, *args)\n self.log(u'init')\n self.stop_event = win32event.CreateEvent(None, 0, 0, None)\n\n def log(self, msg):\n import servicemanager\n\n servicemanager.LogInfoMsg(msg)\n\n def SvcDoRun(self):\n self.ReportServiceStatus(win32service.SERVICE_START_PENDING)\n try:\n self.ReportServiceStatus(win32service.SERVICE_RUNNING)\n self.start()\n self.log('wait')\n win32event.WaitForSingleObject(self.stop_event,\n win32event.INFINITE)\n self.log('done')\n except Exception, x:\n self.log('Exception : %s' % x)\n self.SvcStop()\n\n def SvcStop(self):\n self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n win32event.SetEvent(self.stop_event)\n self.ReportServiceStatus(win32service.SERVICE_STOPPED)\n\n def start(self):\n args = get_config()\n host = args.get(\"Broker\", \"Host\")\n port = args.get(\"Broker\", \"Port\")\n import sys\n from getopt import getopt\n\n opts, _ = getopt(sys.argv[1:], \"s:p:h\")\n for o, v in opts:\n if o == \"-s\":\n host = v\n elif o == \"-p\":\n port = int(v)\n elif o == \"-h\":\n print __doc__\n else:\n print \"unkown option: \" + o\n print __doc__\n self.log(u\"启动host:%s, port:%s\" % (host, port))\n main(host, port)\n\n\nif __name__ == '__main__':\n win32serviceutil.HandleCommandLine(BrokerService)" }, { "alpha_fraction": 0.5285381078720093, "alphanum_fraction": 0.5363886952400208, "avg_line_length": 24.931428909301758, "blob_id": "37c9199c38eb649c5d3a23023fde0e2087e17284", "content_id": "432085a32961914fc9b76aaaa48ab788b165951f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4757, "license_type": "no_license", "max_line_length": 79, "num_lines": 175, "path": "/lite_mms/utilities/decorators.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nhandy decorators\r\n\"\"\"\r\nfrom functools import wraps\r\nimport types\r\n\r\nfrom flask import request, abort, g\r\nfrom flask.templating import render_template, TemplateNotFound\r\nfrom flask.ext.login import current_user\r\nfrom flask.ext.principal import PermissionDenied\r\n\r\ndef templated(template):\r\n \"\"\"This is a method to put a named arguments into the template file\r\n :param template:the file to be added a argument\r\n \"\"\"\r\n\r\n def decorator(f):\r\n @wraps(f)\r\n def func(*args, **kwargs):\r\n template_temp = template\r\n if template_temp is None:\r\n template_temp = request.endpoint.replace('.', '/') + \".html\"\r\n result = f(*args, **kwargs)\r\n if result is None:\r\n result = dict()\r\n elif not isinstance(result, dict):\r\n return result\r\n try:\r\n # pylint: disable=W0142\r\n return render_template(template_temp, **result)\r\n # pylint: enable=W0142\r\n except TemplateNotFound:\r\n abort(404)\r\n\r\n return func\r\n\r\n return decorator\r\n\r\n\r\ndef title_postfix(postfix):\r\n \"\"\"join a value of titlename into the dict\r\n :param postfix:the url which going to access\r\n \"\"\"\r\n\r\n def decoator(f):\r\n def func(*args, **kwargs):\r\n inner_dict = f(*args, **kwargs)\r\n if isinstance(inner_dict, dict):\r\n inner_dict['titlename'] = postfix\r\n # pylint: disable=W0142\r\n return render_template(postfix, **inner_dict)\r\n # pylint: enable=W0142\r\n\r\n return func\r\n\r\n return decoator\r\n\r\n\r\ndef ajax_call(f):\r\n \"\"\"\r\n modify the name of the function(view), since there should be no 2 functions\r\n with the same in one bluepring\r\n \"\"\"\r\n\r\n def decorator(*args, **kwargs):\r\n return f(*args, **kwargs)\r\n\r\n decorator.__name__ = f.__name__ + \"_ajax_call\"\r\n return decorator\r\n\r\n\r\ndef webservice_call(response_format):\r\n \"\"\"\r\n 1. modify the name of the function(view), since there should be no 2\r\n functions\r\n with the same in one bluepring\r\n 2. modfiy the output of the view, change the \"Content-Type\" header\r\n @param response_format: the format of the result, only \"json\" supported\r\n @type response_format: str\r\n \"\"\"\r\n\r\n def decorator(f):\r\n def innerfunc(*args, **kwargs):\r\n rv = f(*args, **kwargs)\r\n if isinstance(rv, types.TupleType) or \\\r\n isinstance(rv, types.ListType):\r\n response = rv[0]\r\n code = rv[1]\r\n headers = rv[2] if len(rv) == 3 else {}\r\n else:\r\n response = rv\r\n code = 200\r\n headers = {}\r\n if response_format == \"json\":\r\n headers.update({'Content-Type': \"application/json\"})\r\n else:\r\n pass\r\n return response, code, headers\r\n\r\n innerfunc.__name__ = f.__name__\r\n return innerfunc\r\n\r\n return decorator\r\n\r\n\r\ndef nav_bar_set(f):\r\n @wraps(f)\r\n def decorator(*args, **kwargs):\r\n rv = f(*args, **kwargs)\r\n if isinstance(rv, dict):\r\n from lite_mms.basemain import nav_bar\r\n\r\n rv.update({'nav_bar': nav_bar})\r\n else:\r\n pass\r\n return rv\r\n\r\n return decorator\r\n\r\n\r\ndef committed(f):\r\n def _f(*args, **kwargs):\r\n ret = f(*args, **kwargs)\r\n from lite_mms.database import db\r\n\r\n if isinstance(ret, db.Model):\r\n from lite_mms.utilities import do_commit\r\n\r\n do_commit(ret)\r\n return ret\r\n\r\n return _f\r\n\r\n\r\ndef permission_required(permission, methods=(\"GET\",)):\r\n def decorator(f):\r\n def _f(*args, **kwargs):\r\n if request.method in methods:\r\n permission.test()\r\n return f(*args, **kwargs)\r\n\r\n return _f\r\n\r\n return decorator\r\n\r\ndef after_this_request(f):\r\n if not hasattr(g, 'after_request_callbacks'):\r\n g.after_request_callbacks = []\r\n g.after_request_callbacks.append(f)\r\n return f\r\n\r\ndef login_required_webservice(view):\r\n\r\n @wraps(view)\r\n def f(*args, **kwargs):\r\n if not current_user.is_authenticated:\r\n return u'您没有权限查看数据', 401\r\n return view(*args, **kwargs)\r\n\r\n return f\r\n\r\ndef permission_required_webservice(perm):\r\n\r\n def f(view):\r\n @wraps(view)\r\n def g(*args, **kwargs):\r\n try:\r\n perm.test()\r\n except PermissionDenied:\r\n return u'您无权执行此操作,需要权限: ' + perm.brief, 401\r\n return view(*args, **kwargs)\r\n return g\r\n\r\n return f\r\n" }, { "alpha_fraction": 0.6009389758110046, "alphanum_fraction": 0.6901408433914185, "avg_line_length": 11.878787994384766, "blob_id": "eea0ea140b8f8db746ce0c7de75361d7d73d82f2", "content_id": "9a28539eae6992679cdcf44c3b956cedd0b47f5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 426, "license_type": "no_license", "max_line_length": 72, "num_lines": 33, "path": "/alembic/versions/5a8040282a1f_add_dispatch_time_co.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"add dispatch_time column\r\r\r\rRevision ID: 5a8040282a1f\r\rRevises: 430e5c7bc3aa\r\rCreate Date: 2013-07-24 14:37:45.108000\r\r\r\r\"\"\"\r\r\r\r# revision identifiers, used by Alembic.\r\rrevision = '5a8040282a1f'\r\rdown_revision = '430e5c7bc3aa'\r\rfrom alembic import op\r\rimport sqlalchemy as sa\r\r\rdef upgrade():\r op.add_column(\"TB_ORDER\", sa.Column(\"dispatched_time\", sa.DateTime))\r\r\rdef downgrade():\r op.drop_column(\"TB_ORDER\", \"dispatched_time\")\r\r" }, { "alpha_fraction": 0.621375322341919, "alphanum_fraction": 0.6217895746231079, "avg_line_length": 40.63793182373047, "blob_id": "c2d4ff4a6cda1ad431b0a78a6c6bfab52507153f", "content_id": "70954d0613864e8dce0aca6c5617ebe1f473462e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2546, "license_type": "no_license", "max_line_length": 117, "num_lines": 58, "path": "/lite_mms/portal/quality_inspection/views.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom flask.ext.databrowser import ModelView, column_spec, filters\nfrom flask.ext.login import login_required\nfrom flask.ext.principal import PermissionDenied\nfrom lite_mms import models\nfrom lite_mms.permissions.roles import QualityInspectorPermission\nfrom lite_mms.apis.quality_inspection import get_QI_result_list, get_QI_result\n\n\nclass QIR(ModelView):\n @login_required\n def try_view(self, processed_objs=None):\n pass\n\n def try_create(self):\n raise PermissionDenied\n\n can_batchly_edit = False\n\n def try_edit(self, processed_objs=None):\n QualityInspectorPermission.test()\n raise PermissionDenied\n\n def edit_hint_message(self, obj, read_only=False):\n if read_only:\n if QualityInspectorPermission.can():\n return u\"质检报告%s不能在浏览器上修改\" % obj.id\n else:\n return u\"您没有修改质检报告%s的权限\" % obj.id\n else:\n return super(QIR, self).edit_hint_message(obj, read_only)\n\n __default_order__ = (\"id\", \"desc\")\n\n __list_columns__ = [\"id\", \"work_command_id\", \"weight\", \"quantity\",\n column_spec.ColumnSpec(\"result\", label=u\"质检结果\", formatter=lambda v, obj: get_QI_result(v)),\n column_spec.ColumnSpec(\"actor\", label=u\"质检员\"),\n column_spec.ImageColumnSpec(\"pic_url\", label=u\"图片\", css_class=\"img-responsive img-polaroid\")]\n\n __column_labels__ = {\"id\": u\"编号\", \"quantity\": u\"数量\", \"weight\": u\"重量\", \"work_command_id\": u\"工单号\"}\n\n __form_columns__ = [column_spec.ColumnSpec(\"id\"), \"weight\", \"quantity\",\n column_spec.ColumnSpec('unit', label=u\"单位\"),\n column_spec.SelectColumnSpec(col_name=\"result\", label=u\"质检结果\", choices=get_QI_result_list()),\n column_spec.ColumnSpec(\"work_command\", label=u\"工单编号\"),\n column_spec.ColumnSpec(\"report_time\", label=u\"创建时间\"),\n column_spec.ColumnSpec(\"actor\", label=u\"质检员\"),\n column_spec.PlaceHolderColumnSpec(\"pic_url\", template_fname=\"pic-snippet.html\", label=u\"图片\")]\n\n __column_filters__ = [filters.EqualTo(\"result\", display_col_name=u\"质检结果\", options=get_QI_result_list())]\n\n def preprocess(self, obj):\n from lite_mms.apis.quality_inspection import QIReportWrapper\n\n return QIReportWrapper(obj)\n\n\nqir_model_view = QIR(model=models.QIReport)" }, { "alpha_fraction": 0.5011547207832336, "alphanum_fraction": 0.5242494344711304, "avg_line_length": 16.826086044311523, "blob_id": "261680646be97fe0961a23c464e193d0db879d92", "content_id": "dca46d7cf1ead2a9aea2cc74aee837a546636cbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 433, "license_type": "no_license", "max_line_length": 54, "num_lines": 23, "path": "/lite_mms/tools/echo.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\" \r\nA simple echo server \r\n\"\"\" \r\n\r\nimport socket \r\n\r\nhost = '' \r\nport = 5000\r\nbacklog = 5 \r\nsize = 1024 \r\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \r\ns.bind((host,port)) \r\ns.listen(backlog) \r\nwhile 1: \r\n client, address = s.accept() \r\n while True:\r\n data = client.recv(size) \r\n if data: \r\n print data\r\n client.send(data) \r\n else:\r\n break\r\n client.close()\r\n" }, { "alpha_fraction": 0.6944444179534912, "alphanum_fraction": 0.6944444179534912, "avg_line_length": 33, "blob_id": "d88a09da00ef0b1068f062b6fc73044f2577ab11", "content_id": "fc3c42e4ddf0c3efbcb35b26e9ce5f7ebaf750ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 72, "license_type": "no_license", "max_line_length": 53, "num_lines": 2, "path": "/docs/source/constants/quality_inspection.rst", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\r\n.. automodule:: lite_mms.constants.quality_inspection\r\n :members:\r\n" }, { "alpha_fraction": 0.6258181929588318, "alphanum_fraction": 0.6378181576728821, "avg_line_length": 40.98473358154297, "blob_id": "906c6fc2d968e06602c1d4de220db118b625fe4a", "content_id": "d15bfdc17a8db794fd60b12747bc43d67ffe6d5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11524, "license_type": "no_license", "max_line_length": 152, "num_lines": 262, "path": "/lite_mms/test/at/steps/delivery.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nimport json\nfrom flask import g, _request_ctx_stack, session\nfrom pyfeature import step\nimport yawf\n\nfrom lite_mms import models, constants\nfrom lite_mms.apis.delivery import DeliverySessionWrapper\nfrom lite_mms.basemain import app, timeline_logger\nfrom lite_mms.utilities import do_commit\nfrom lite_mms.test.utils import login, client_login\n\ntimeline_logger.handlers = []\n\napp.config[\"CSRF_ENABLED\"] = False\napp.config[\"WTF_CSRF_ENABLED\"] = False\n\ndef generate(times=1):\n from random import choice\n import string\n\n temp = \"\"\n for i in range(times):\n temp += choice(string.letters)\n return temp\n\n@step(u\"收发员创建发货会话\")\ndef _(step, plate, tare):\n return do_commit(models.DeliverySession(plate_=plate, tare=tare))\n\n\n@step(u\"生成StoreBill\")\ndef _(step, customer, harbor, order_type=constants.STANDARD_ORDER_TYPE, weight=5000):\n plate = do_commit(models.Plate(name=generate(5)))\n unload_session = do_commit(models.UnloadSession(plate_=plate, gross_weight=50000))\n product_type = do_commit(models.ProductType(name=generate(5)))\n product = do_commit(models.Product(name=generate(5), product_type=product_type))\n procedure = do_commit(models.Procedure(name=generate(5)))\n goods_receipt = do_commit(models.GoodsReceipt(customer=customer, unload_session=unload_session))\n order = do_commit(models.Order(creator=None, goods_receipt=goods_receipt))\n if order_type == constants.STANDARD_ORDER_TYPE:\n sub_order = do_commit(\n models.SubOrder(harbor=harbor, order=order, product=product, quantity=weight, weight=weight, unit=\"KG\"))\n work_command = do_commit(\n models.WorkCommand(sub_order=sub_order, org_weight=weight, org_cnt=weight, procedure=procedure))\n qir = do_commit(models.QIReport(work_command=work_command, quantity=weight, weight=weight,\n result=constants.quality_inspection.FINISHED, actor_id=None))\n else:\n sub_order = models.SubOrder(harbor=harbor, order=order, product=product, quantity=weight/10, weight=weight, unit=u\"刀\",\n order_type=constants.EXTRA_ORDER_TYPE)\n work_command = do_commit(\n models.WorkCommand(sub_order=sub_order, org_weight=weight, org_cnt=weight/10, procedure=procedure))\n qir = do_commit(models.QIReport(work_command=work_command, quantity=weight/10, weight=weight,\n result=constants.quality_inspection.FINISHED, actor_id=None))\n return do_commit(models.StoreBill(qir=qir))\n\n\n@step(u\"收发员选择仓单\")\ndef _(step, delivery_session, store_bill_list):\n for store_bill in store_bill_list:\n store_bill.delivery_session = delivery_session\n do_commit(store_bill)\n\n\n@step(u\"装卸工全部装货、完全装货\")\ndef _(step, delivery_session, store_bill):\n with app.test_request_context():\n with app.test_client() as c:\n auth_token = client_login('l', 'l', c)\n rv = c.post(\"/delivery_ws/delivery-task?sid=%s&is_finished=1&remain=0&auth_token=%s\" % (delivery_session.id, auth_token),\n data=json.dumps([{\"store_bill_id\": store_bill.id, \"is_finished\": 1}]))\n assert 200 == rv.status_code\n delivery_task = models.DeliveryTask.query.filter(\n models.DeliveryTask.delivery_session == delivery_session).order_by(\n models.DeliveryTask.id.desc()).first()\n login('cc', 'cc', c)\n rv = c.post(\"/delivery/weigh-delivery-task/%d\" % delivery_task.id, data={\"weight\": 6500})\n assert rv.status_code == 302\n\n\n@step(u\"收发员生成发货单\")\ndef _(step, delivery_session):\n with app.test_request_context():\n with app.test_client() as c:\n login('cc', 'cc', c)\n rv = c.post(\"/delivery/create-consignment-list/%s\" % delivery_session.id,\n data={\"customer-pay_mod\": json.dumps({customer.id: 0 for customer in\n DeliverySessionWrapper(\n delivery_session).customer_list})})\n\n assert 302 == rv.status_code\n\n return models.Consignment.query.order_by(models.Consignment.id.desc()).first()\n\n\n@step(u\"发货单产品与仓单相同\")\ndef _(step, consignment, store_bill):\n assert len(consignment.product_list) == 1 and consignment.product_list[\n 0].product == store_bill.sub_order.product and \\\n consignment.product_list[0].weight == store_bill.weight and consignment.product_list[\n 0].quantity == store_bill.quantity\n\n\n@step(u\"已关闭的发货会话\")\ndef _(step, plate, tare):\n delivery_session = do_commit(\n models.DeliverySession(plate_=plate, tare=tare, status=constants.delivery.STATUS_CLOSED))\n return delivery_session\n\n@step(u\"修改发货会话\")\ndef _(step, delivery_session):\n with app.test_request_context():\n with app.test_client() as c:\n login('cc', 'cc', c)\n rv = c.post(\"/delivery/delivery-session/%d\" % delivery_session.id)\n return rv.status_code\n\n@step(u\"重新打开发货会话\")\ndef _(step, delivery_session):\n with app.test_request_context():\n with app.test_client() as c:\n login('cc', 'cc', c)\n rv = c.post(\"/delivery/delivery-session/%d\" % delivery_session.id, data={\"__action__\": u\"打开\"})\n assert 302 == rv.status_code\n\n\n@step(u\"可以修改发货会话\")\ndef _(step, delivery_session):\n with app.test_request_context():\n with app.test_client() as c:\n login('cc', 'cc', c)\n rv = c.post(\"/delivery/delivery-session/%d\" % delivery_session.id)\n assert 302 == rv.status_code\n\n\n@step(u\"发货任务$\")\ndef _(step, delivery_session):\n return do_commit(models.DeliveryTask(actor_id=None, delivery_session=delivery_session))\n\n\n@step(u\"修改发货任务\")\ndef _(step, delivery_task):\n with app.test_request_context():\n with app.test_client() as c:\n login('cc', 'cc', c)\n rv = c.post(\"/delivery/delivery-task/%d\" % delivery_task.id)\n return rv.status_code\n\n\n@step(u\"无法修改\")\ndef _(step, status_code):\n assert 403 == status_code\n\n\n@step(u\"修改成功\")\ndef _(step, status_code):\n assert 302 == status_code\n\n\n@step(u\"未打印的发货单\")\ndef _(step, customer, delivery_session, product):\n con = do_commit(models.Consignment(customer=customer, delivery_session=delivery_session, pay_in_cash=True))\n do_commit(models.ConsignmentProduct(consignment=con, delivery_task=delivery_session.delivery_task_list[0],\n product=product))\n return con\n\n\n@step(u\"修改发货单的产品\")\ndef _(step, consignment):\n with app.test_request_context():\n with app.test_client() as c:\n login('cc', 'cc', c)\n rv = c.post(\"/consignment/consignment-product/%d\" % consignment.product_list[0].id)\n return rv.status_code\n \n@step(u\"打印发货单\")\ndef _(step, consignment):\n consignment.MSSQL_ID = 50123\n do_commit(consignment)\n \n@step(u\"已生成发货单的发货会话\")\ndef _(step,plate,tare, customer, product):\n delivery_session = do_commit(\n models.DeliverySession(plate_=plate, tare=tare, status=constants.delivery.STATUS_CLOSED))\n delivery_task = do_commit(models.DeliveryTask(actor_id=None,delivery_session=delivery_session))\n con = do_commit((models.Consignment(customer=customer, delivery_session=delivery_session, pay_in_cash=True)))\n do_commit(models.ConsignmentProduct(consignment=con, delivery_task=delivery_session.delivery_task_list[0],\n product=product))\n return delivery_session\n\n@step(u\"新增发货任务\")\ndef _(step, delivery_session, store_bill):\n with app.test_request_context():\n with app.test_client() as c:\n login('cc', 'cc', c)\n rv = c.post(\"/delivery/store-bill-list/%d\" % delivery_session.id, data={\"store_bill_list\": store_bill.id})\n assert 302 == rv.status_code\n rv = c.post('/auth_ws/login?username=l&password=l')\n assert rv.status_code == 200\n auth_token = json.loads(rv.data)['token']\n rv = c.post(\"/delivery_ws/delivery-task?sid=%s&is_finished=1&remain=0&auth_token=%s\" % (delivery_session.id, auth_token),\n data=json.dumps([{\"store_bill_id\": store_bill.id, \"is_finished\": 1}]))\n assert 200 == rv.status_code\n\n@step(u\"提示需要重新生成发货单\")\ndef _(step, delivery_session):\n ds = DeliverySessionWrapper(delivery_session)\n assert ds.stale\n\n@step(u'创建发货任务, 包含两个仓单, 其中一个未完成, 剩余重量超过了原有仓单的重量')\ndef _(step, delivery_session, store_bill1, store_bill2):\n with app.test_client() as c:\n rv = c.post('/auth_ws/login?username=l&password=l')\n assert rv.status_code == 200\n auth_token = json.loads(rv.data)['token']\n rv = c.post(\"/delivery_ws/delivery-task?sid=%s&is_finished=1&auth_token=%s&remain=%d\" % (delivery_session.id, auth_token, store_bill2.weight+1),\n data=json.dumps([{\"store_bill_id\": store_bill1.id, \"is_finished\": 1}, \n {'store_bill_id': store_bill2.id, 'is_finished': 0}]))\n assert rv.status_code == 201 \n\n@step(u'不能再次创建发货任务,包含两个仓单,全部都完成')\ndef _(step, delivery_session, store_bill1, store_bill2):\n with app.test_client() as c:\n rv = c.post('/auth_ws/login?username=l&password=l')\n assert rv.status_code == 200\n auth_token = json.loads(rv.data)['token']\n rv = c.post(\"/delivery_ws/delivery-task?sid=%s&is_finished=1&auth_token=%s\" % (delivery_session.id, auth_token),\n data=json.dumps([{\"store_bill_id\": store_bill1.id, \"is_finished\": 1}, \n {'store_bill_id': store_bill2.id, 'is_finished': 1}]))\n print rv.data\n assert rv.status_code == 403 \n\n\n@step(u'一个异常发货任务申请生成了')\ndef _(step, codernity_db):\n from lite_mms.apis.delivery import PermitDeliveryTaskWithAbnormalWeight\n return models.Node.query.filter(models.Node.policy_name=='PermitDeliveryTaskWithAbnormalWeight').one().id\n\n\n@step(u'批准该申请')\ndef _(step, node_id):\n with app.test_client() as c:\n login('cc', 'cc', c)\n node = models.Node.query.get(node_id)\n node.approve()\n assert node.approved\n assert node.work_flow.status == yawf.constants.WORK_FLOW_EXECUTED\n\n@step(u'发货任务生成了, 存在一个未发货的仓单, 剩余重量是1001, 另外由两个仓单已经发货完毕, 其重量分别是2000, 1')\ndef _(step, delivery_session, store_bill_id1, store_bill_id2):\n dt = models.DeliveryTask.query.one()\n assert dt.is_last\n assert dt.delivery_session_id == delivery_session.id \n store_bill1 = models.StoreBill.query.get(store_bill_id1)\n store_bill2 = models.StoreBill.query.get(store_bill_id2)\n assert store_bill1.delivery_task_id == dt.id\n assert store_bill1.weight == 2000\n assert store_bill2.weight == 1001\n assert store_bill2.delivery_task is None\n new_sb = models.StoreBill.query.filter(models.StoreBill.id!=store_bill_id1).filter(models.StoreBill.id!=store_bill_id2).one()\n assert new_sb.delivery_task_id == dt.id\n assert new_sb.weight == 1\n" }, { "alpha_fraction": 0.7118644118309021, "alphanum_fraction": 0.7118644118309021, "avg_line_length": 27.66666603088379, "blob_id": "b7930e28261278ec8748a81199b4c7d0c8ca4a5c", "content_id": "13373f0cea29dfaee67ad5d5d24685f9eb6943b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 177, "license_type": "no_license", "max_line_length": 65, "num_lines": 6, "path": "/lite_mms/portal/auth_ws/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "from flask import Blueprint\n\nauth_ws = Blueprint(\"auth_ws\", __name__, static_folder=\"static\", \n template_folder=\"templates\")\n\nimport lite_mms.portal.auth_ws.webservices\n\n\n\n\n\n" }, { "alpha_fraction": 0.5271559357643127, "alphanum_fraction": 0.549153208732605, "avg_line_length": 39.761905670166016, "blob_id": "53cdb1e6ef4c16f1eb86b39d8bf049ec50bbadb2", "content_id": "aa72525a69344a5f9d6e7a8f09284a7ebf6c242d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6849, "license_type": "no_license", "max_line_length": 104, "num_lines": 126, "path": "/lite_mms/test/at/test_cargo.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\n# -*- coding: UTF-8 -*-\nfrom hashlib import md5\n\nfrom pyfeature import Feature, Scenario, given, and_, when, then, clear_hooks\nimport lite_mms\nfrom lite_mms.basemain import app\nfrom lite_mms.database import db\n\ndef test_cargo():\n from pyfeature import flask_sqlalchemy_setup\n\n flask_sqlalchemy_setup(app, db, create_step_prefix=u\"创建\",\n model_name_getter=lambda model: model.__name__,\n attr_name_getter=lambda model, attr: model.__col_desc__.get(attr, attr),\n set_step_pattern=u'(\\w+)([\\.\\w+]+)设置为(.+)')\n\n with Feature(u\"卸货会话生成收货单\", ['lite_mms.test.at.steps.cargo'], verbose=False):\n with Scenario(u\"准备数据\"):\n plate = given(u\"创建Plate(浙B 11112)\")\n harbor = and_(u\"创建Harbor(foo车间)\")\n customer = and_(u\"创建Customer(宁波机床厂)\", abbr=\"aaa\")\n customer2 = and_(u\"创建Customer(宁力紧固件)\", abbr=\"bbb\")\n dpt = and_(u\"创建ProductType(默认加工件)\")\n and_(u\"创建Product(默认加工件)\", product_type=dpt)\n product_type = and_(u\"创建ProductType(foo)\")\n product = and_(u\"创建Product(foo)\", product_type=product_type)\n cargo_clerk_group = and_(u'创建Group(cargo_clerk)', id=lite_mms.constants.groups.CARGO_CLERK, \n default_url='/cargo/unload-session-list')\n and_(u\"创建User\", username=\"cc\", password=md5(\"cc\").hexdigest(), groups=[cargo_clerk_group])\n loader_group = and_(u'创建Group(loader)', id=lite_mms.constants.groups.LOADER)\n and_(u'创建User', username=\"l\", password=md5(\"l\").hexdigest(), groups=[loader_group])\n\n with Scenario(u\"最简完整流程\"):\n us = when(u'收发员创建UnloadSession, 毛重是10000公斤', plate)\n ut = and_(u'装卸工进行卸货,该货物来自宁波机床厂', customer, harbor, product, us, is_last=True)\n and_(u'收发员称重8000公斤', ut)\n\n then(u\"卸货任务的重量是2000公斤\", ut)\n and_(u'卸货会话已经关闭', us)\n\n gr_list = when(u'收发员生成收货单', us)\n then(u'该收货单中包含一个项目,该项目的客户是宁波机床厂, 项目的重量是2000公斤', gr_list)\n\n with Scenario(u\"包含多次卸货任务的卸货会话\"):\n us = when(u'收发员创建UnloadSession, 毛重是10000公斤', plate)\n ut1 = and_(u'装卸工进行卸货,该货物来自宁波机床厂', customer, harbor, product, us, is_last=False)\n then(u'装卸工此时不能进行卸货', us)\n\n when(u'收发员称重8000公斤', ut1)\n then(u\"卸货任务的重量是2000公斤\", ut1)\n and_(u'卸货会话没有关闭', us)\n\n ut2 = when(u'装卸工进行卸货,该货物来自宁力紧固件', customer2, harbor, product, us, is_last=True)\n and_(u'收发员称重5000公斤', ut2)\n then(u'卸货任务的重量是3000公斤', ut2)\n and_(u\"卸货会话已经关闭\", us)\n\n gr_list = when(u'收发员生成收货单', us)\n then(u'该会话中包含两个项目', gr_list)\n and_(u'项目的客户是宁波机床厂, 项目的重量是2000公斤', gr_list[0])\n and_(u'项目的客户是宁力紧固件, 项目的重量是3000公斤', gr_list[1])\n\n with Scenario(u'除非卸货会话关闭,否则卸货会话都可以修改'):\n us = when(u'收发员创建卸货会话, 其状态是待称重')\n ut = and_(u'装卸工创建卸货任务', customer, harbor, product, us)\n and_(u'修改卸货会话的车牌号为浙B 00002', us)\n and_(u'修改卸货会话的毛重为10000公斤', us)\n then(u'卸货会话的车牌号为浙B 00002', us)\n and_(u'卸货会话的重量为10000公斤', us)\n and_(u'修改卸货任务的重量为2000公斤', ut)\n then(u'卸货任务的重量是2000公斤', ut)\n\n when(u'关闭卸货会话',us)\n then(u'不能修改卸货会话',us)\n and_(u'不能修改卸货任务',ut)\n\n with Scenario(u'收发员删除卸货任务'):\n us = given(u\"未关闭的卸货会话\")\n ut1 = and_(u\"已称重的卸货任务\", us, customer, harbor, product)\n ut2 = and_(u\"未称重的卸货任务\", us, customer, harbor, product)\n rv = when(u\"删除卸货任务\", ut1)\n then(u\"无法删除\", rv)\n rv = when(u\"删除卸货任务\", ut2)\n then(u\"删除成功\", rv)\n\n with Scenario(u'收发员强行关闭卸货会话'):\n us = given(u\"未称重未关闭的卸货会话\", customer, harbor, product)\n rv = when(u\"收发员关闭卸货会话\", us)\n then(u\"关闭失败\", rv)\n when(u\"收发员称重卸货会话\", us)\n rv = and_(u\"收发员关闭卸货会话\", us)\n then(u\"关闭成功\", rv)\n\n with Scenario(u'收发员创建卸货会话时,不能选择正在装货或者卸货的车辆'):\n plate_a = given(u\"正在装货的车辆\", plate_name=\"Ijkdplate_a\")\n plate_list = when(u\"收发员创建新卸货会话\")\n then(u\"车辆列表中无上述车辆\", plate_a, plate_list)\n\n with Scenario(u'收发员打开关闭的卸货会话,并且修改'):\n us = given(u\"卸货会话已关闭,未生成收货单\", customer, harbor,plate, product)\n when(u\"收发员重新打开卸货会话\", us)\n then(u\"收发员修改其卸货任务的重量为5000KG\", us)\n and_(u\"收发员关闭卸货会话\", us)\n gr = then(u\"生成收货单。其产品重量为5000KG\", us)\n when(u\"收发员重新打开卸货会话\", us)\n and_(u\"收发员修改其卸货任务的重量为6000KG\", us)\n then(u\"收货单未过时\", gr)\n when(u\"又新增一卸货任务\", us)\n then(u\"收货单过时\", gr)\n\n with Scenario(u'若收货单过时,或者已经生成了订单,那么不能修改收货单'):\n us = given(u\"卸货会话已关闭,未生成收货单\", customer, harbor,plate, product)\n gr_list = and_(u'收发员生成收货单', us)\n when(u\"收发员重新打开卸货会话\", us)\n and_(u'又新增一卸货任务',us)\n then(u'收货单过时', gr_list[0])\n and_(u'不能修改收货单', gr_list[0])\n\n gr_list = when(u'重新生成收货单', us)\n and_(u'生成订单',gr_list[0])\n then(u'不能修改收货单',gr_list[0])\n \n clear_hooks()\n\nif __name__ == \"__main__\":\n test_cargo()\n" }, { "alpha_fraction": 0.5672131180763245, "alphanum_fraction": 0.5803278684616089, "avg_line_length": 16, "blob_id": "8a2f551346561d23aa4c0b3d24b76cc93a36620c", "content_id": "3bd2738eac75d8b6676aaf55bcdb67c095d944ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 305, "license_type": "no_license", "max_line_length": 57, "num_lines": 18, "path": "/broker/setup.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n@author: Yangminghua\n@version: $\n\"\"\"\nfrom distutils.core import setup\nimport py2exe\nimport sys\n\nsetup(\n service=['BrokerService'],\n options={\n 'py2exe': {'includes': 'decimal','bundle_files':1\n }},\n zipfile=None,\n data_files=[(\".\", [\"config.ini\"])]\n\n)" }, { "alpha_fraction": 0.6383495330810547, "alphanum_fraction": 0.6893203854560852, "avg_line_length": 18.619047164916992, "blob_id": "9646302ceff1b7cbe2cd7cdc19c01495150321e1", "content_id": "5a50266b0c72f444d26a499b4642090bffa7b280", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 412, "license_type": "no_license", "max_line_length": 82, "num_lines": 21, "path": "/alembic/versions/430e5c7bc3aa_add_column_enabled_t.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"add column enabled to User\n\nRevision ID: 430e5c7bc3aa\nRevises: 3fa49daed5cf\nCreate Date: 2013-07-11 16:56:21.183231\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '430e5c7bc3aa'\ndown_revision = '3fa49daed5cf'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.add_column(\"TB_USER\", sa.Column(\"enabled\", sa.Boolean, server_default='1'))\n\ndef downgrade():\n op.drop_column('TB_USER', 'enabled')\n" }, { "alpha_fraction": 0.4772922098636627, "alphanum_fraction": 0.47900599241256714, "avg_line_length": 36.67741775512695, "blob_id": "13088b8ebae845c8cb3261fef1bf93556a52c905", "content_id": "bcdd3390617a79fed5d83eb7839f71656ef6a656", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1207, "license_type": "no_license", "max_line_length": 97, "num_lines": 31, "path": "/lite_mms/portal/todo/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom datetime import datetime, timedelta\nfrom flask import Blueprint, request, redirect, url_for, flash\nfrom lite_mms.basemain import data_browser, nav_bar\n\nfrom .views import to_do_view\n\nto_do_page = Blueprint(\"todo\", __name__, static_folder=\"static\",\n template_folder=\"templates\")\n\ndata_browser.register_model_view(to_do_view, to_do_page,\n extra_params={\n \"list_view\": {\n \"nav_bar\": nav_bar,\n \"titlename\": u\"待办事项\",\n \"today\": datetime.today().date(),\n \"yesterday\": datetime.today().date() - timedelta(days=1)\n }\n })\n\n\n@to_do_page.route(\"/delete/<int:id_>\", methods=[\"POST\"])\ndef delete(id_):\n from lite_mms.apis.todo import delete_todo\n\n try:\n delete_todo(id_)\n flash(u\"删除待办事项%d成功\" % id_)\n except:\n flash(u\"删除待办事项%d失败\" % id_, \"error\")\n return redirect(url_for(\"todo.todo_list\", _method=\"GET\"))" }, { "alpha_fraction": 0.6081157922744751, "alphanum_fraction": 0.6140748858451843, "avg_line_length": 30.74774742126465, "blob_id": "f623756e664c4a9f89f6ae9b153ed8690e234503", "content_id": "7d859d9bd65285193521d77d03957bf6fcd41fa3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3856, "license_type": "no_license", "max_line_length": 111, "num_lines": 111, "path": "/lite_mms/portal/order/actions.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom datetime import datetime\nfrom flask.ext.databrowser.action import BaseAction, DirectAction\nfrom flask import redirect, request, url_for\n\n\nclass DispatchAction(BaseAction):\n def op(self, model):\n model.update(dispatched=True, dispatched_time=datetime.now())\n model.add_todo()\n\n def test_enabled(self, model):\n if model.dispatched:\n return -2\n elif not model.refined:\n return -3\n return 0\n\n def get_forbidden_msg_formats(self):\n return {\n -2: u\"订单[%s]已经下发,不能重复下发\",\n -3: u\"订单[%s]没有完善,请先完善\"\n }\n\n def try_(self, preprocessed_objs):\n from lite_mms.permissions import CargoClerkPermission, AdminPermission\n from flask.ext.principal import Permission\n\n Permission.union(CargoClerkPermission, AdminPermission).test()\n\n\nclass AccountAction(BaseAction):\n def op(self, order):\n from lite_mms import apis\n\n for sub_order in order.sub_order_list:\n for store_bill in sub_order.store_bill_list:\n fake_delivery_task = apis.delivery.fake_delivery_task()\n if not store_bill.delivery_task:\n apis.delivery.update_store_bill(store_bill.id,\n delivery_session_id=fake_delivery_task.delivery_session.id,\n delivery_task_id=fake_delivery_task.id)\n sub_order.end()\n order.update(finish_time=datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n def try_(self, preprocessed_objs):\n from lite_mms.permissions import CargoClerkPermission, AdminPermission\n from flask.ext.principal import Permission\n\n Permission.union(CargoClerkPermission, AdminPermission).test()\n\n def test_enabled(self, model):\n if not model.can_account:\n return -1\n\n def get_forbidden_msg_formats(self):\n return {\n -1: u\"该订单不能盘点,原因可能是:没有排产完毕,正在生产,或者已经完全发货\"\n }\n\n\nclass MarkRefinedAction(BaseAction):\n def op(self, model):\n model.update(refined=True)\n\n def test_enabled(self, model):\n if model.refined:\n return -2\n elif not model.can_refine:\n return -3\n return 0\n\n def get_forbidden_msg_formats(self):\n return {\n -2: u\"订单[%s]已经标记为完善\",\n -3: u\"请先完善订单[%s]内容(添加子订单或者填写子订单的产品信息,完成时间),才能标记为完善\",\n }\n\n def try_(self, preprocessed_objs):\n from lite_mms.permissions import CargoClerkPermission, AdminPermission\n from flask.ext.principal import Permission\n\n Permission.union(CargoClerkPermission, AdminPermission).test()\n\n\nclass NewExtraOrder(DirectAction):\n def op_upon_list(self, objs, model_view):\n return redirect(url_for(\"order.new_sub_order\", url=request.url, _method=\"GET\", order_id=objs[0].id))\n\n def test_enabled(self, model):\n from lite_mms.apis.order import OrderWrapper\n\n order = OrderWrapper(model)\n if order.measured_by_weight:\n return -2\n if order.dispatched:\n return -3\n if order.refined:\n return -4\n return 0\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"只有计件类型的订单才能添加子订单\",\n -3: u\"订单%s已下发,不能添加子订单\",\n -4: u\"订单%s已完善,不能添加子订单\"}\n\n\ndispatch_action = DispatchAction(u\"下发\")\naccount_action = AccountAction(u\"盘点\")\nmark_refined_action = MarkRefinedAction(u\"标记为完善\")\nnew_extra_order_action = NewExtraOrder(u\"添加计件类型子订单\")\n" }, { "alpha_fraction": 0.6078193187713623, "alphanum_fraction": 0.6090335249900818, "avg_line_length": 28.962406158447266, "blob_id": "69c66a3d2f78be138a97429faef8dde2a8c10faf", "content_id": "3c45fc8896b4da957941ba94503491d5e5109f01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4190, "license_type": "no_license", "max_line_length": 133, "num_lines": 133, "path": "/lite_mms/apis/auth.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n用户类\r\n\"\"\"\r\nfrom hashlib import md5\r\n\r\nfrom flask import session, g, _request_ctx_stack, current_app, request\r\nimport flask.ext.login as login\r\nfrom flask.ext.principal import identity_changed, Identity, AnonymousIdentity\r\nfrom sqlalchemy.orm.exc import NoResultFound\r\nfrom lite_mms.exceptions import AuthenticateFailure\r\nfrom lite_mms.apis import ModelWrapper\r\nfrom lite_mms.basemain import app\r\nfrom itsdangerous import URLSafeTimedSerializer, BadTimeSignature\r\nfrom lite_mms.constants import groups\r\n\r\nclass UserWrapper(login.UserMixin, ModelWrapper):\r\n \"\"\"\r\n a wrapper of the actual user model\r\n \"\"\"\r\n __serializer__ = URLSafeTimedSerializer(secret_key=app.config.get('SECRET_KEY'), salt=app.config.get('SECURITY_SALT'))\r\n\r\n @property\r\n def default_url(self):\r\n return self.group.default_url\r\n\r\n @property\r\n def permissions(self):\r\n ret = set()\r\n for group in self.groups:\r\n for perm in group.permissions:\r\n ret.add(perm)\r\n return ret\r\n\r\n @property\r\n def group(self):\r\n for group in self.groups:\r\n if group.id == int(session['current_group_id']):\r\n return group\r\n return self.groups[0]\r\n\r\n @property\r\n def group_name(self):\r\n \"\"\"\r\n get the group name of the **FIRST** group that user belongs\r\n \"\"\"\r\n return self.group.name\r\n\r\n def __eq__(self, other):\r\n \"\"\"\r\n 比较。如果id相同,则认为相同\r\n :param other: 比较的对象\r\n :return:True or False\r\n \"\"\"\r\n return isinstance(other, UserWrapper) and self.id == other.id\r\n\r\n def __repr__(self):\r\n return \"<UserWrapper %s> \" % self.username\r\n\r\n @property\r\n def can_login_client(self):\r\n \"\"\"\r\n test if the user could login in client\r\n \"\"\"\r\n can_login_groups = { \r\n groups.DEPARTMENT_LEADER, \r\n groups.TEAM_LEADER, \r\n groups.LOADER, \r\n groups.QUALITY_INSPECTOR\r\n }\r\n return all(group.id in can_login_groups for group in self.groups)\r\n\r\n\r\n def get_auth_token(self):\r\n '''\r\n get the authentiaction token, see `https://flask-login.readthedocs.org/en/latest/#flask.ext.login.LoginManager.token_loader`_\r\n '''\r\n return self.__serializer__.dumps([self.id, self.username, self.password])\r\n\r\ndef get_user(id_):\r\n if not id_:\r\n return None\r\n # TODO 这里需要优化\r\n from lite_mms import models\r\n\r\n try:\r\n return UserWrapper(\r\n models.User.query.filter(models.User.id == id_).one())\r\n except NoResultFound:\r\n return None\r\n\r\ndef load_user_from_token():\r\n ctx = _request_ctx_stack.top\r\n token = request.args.get('auth_token')\r\n user_id = None\r\n identity = AnonymousIdentity()\r\n if token is None:\r\n ctx.user = current_app.login_manager.anonymous_user()\r\n else:\r\n try:\r\n ctx.user = get_user(UserWrapper.__serializer__.loads(token)[0])\r\n identity = Identity(ctx.user.id)\r\n # change identity to reset permissions\r\n except BadTimeSignature:\r\n ctx.user = current_app.login_manager.anonymous_user()\r\n identity_changed.send(current_app._get_current_object(), identity=identity)\r\n\r\ndef get_user_list(group_id=None):\r\n from lite_mms import models\r\n q = models.User.query\r\n if group_id:\r\n q = q.filter(models.User.groups.any(models.Group.id == group_id))\r\n return [UserWrapper(user) for user in q.all()]\r\n\r\ndef authenticate(username, password):\r\n \"\"\"\r\n authenticate a user, test if username and password mathing\r\n :return: an authenticated User or None if can't authenticated\r\n :rtype: User\r\n :raise: exceptions.AuthenticateFailure\r\n \"\"\"\r\n try:\r\n from lite_mms import models\r\n\r\n return UserWrapper(\r\n models.User.query.filter(models.User.username == username).filter(\r\n models.User.password == md5(password).hexdigest()).one())\r\n except NoResultFound:\r\n raise AuthenticateFailure(\"用户名或者密码错误\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n pass\r\n" }, { "alpha_fraction": 0.6241345405578613, "alphanum_fraction": 0.6567754745483398, "avg_line_length": 23.071428298950195, "blob_id": "e4660a81bacab507fed6b3b1f8dc6b6fac0e37f0", "content_id": "65ccec6c9b5702f4e1a66ac65d53aec3c1a8ab33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1011, "license_type": "no_license", "max_line_length": 116, "num_lines": 42, "path": "/alembic/versions/26777e9808c2_team_to_user_many_to.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"team to user, many to many\r\r\r\rRevision ID: 26777e9808c2\r\rRevises: 2dda2c7c7e83\r\rCreate Date: 2013-08-21 14:41:40.905000\r\r\r\r\"\"\"\r\r\r\r# revision identifiers, used by Alembic.\r\rrevision = '26777e9808c2'\r\rdown_revision = '2dda2c7c7e83'\r\rfrom alembic import op\r\rimport sqlalchemy as sa\r\r\rdef upgrade():\r op.create_table(\"TB_USER_AND_TEAM\", sa.Column(\"team_id\", sa.Integer, sa.ForeignKey(\"TB_TEAM.id\")),\r sa.Column(\"leader_id\", sa.Integer, sa.ForeignKey(\"TB_USER.id\")))\r\r op.execute(\"INSERT INTO TB_USER_AND_TEAM (team_id, leader_id) SELECT t.id, t.leader_id FROM TB_TEAM t\")\r\r op.drop_constraint(\"TB_TEAM_ibfk_2\", \"TB_TEAM\", type_=\"foreignkey\")\r op.drop_column(\"TB_TEAM\", \"leader_id\")\r\r\rdef downgrade():\r op.add_column(\"TB_TEAM\", sa.Column(\"leader_id\", sa.Integer, sa.ForeignKey(\"TB_User.id\", name=\"TB_TEAM_ibfk_2\")))\r op.execute(\r \"UPDATE TB_TEAM SET leader_id = (SELECT leader_id FROM TB_USER_AND_TEAM t WHERE t.team_id = TB_TEAM.id)\")\r op.drop_table(\"TB_USER_AND_TEAM\")\r" }, { "alpha_fraction": 0.5843949317932129, "alphanum_fraction": 0.6003184914588928, "avg_line_length": 17.41176414489746, "blob_id": "21cda1d788d1a2512c5d18820bd55f5a3a4e8419", "content_id": "8d3b2e2593b9034216188220a0dfdc8cfb4e9fd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 680, "license_type": "no_license", "max_line_length": 45, "num_lines": 34, "path": "/lite_mms/constants/cargo.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nSTATUS_LOADING = 1\nSTATUS_WEIGHING = 2\nSTATUS_CLOSED = 3\nSTATUS_DISMISSED = 4\n\nACT_LOAD = 1\nACT_WEIGHT = 2\nACT_CLOSE = 3\nACT_OPEN = 4\nACT_DISMISS = 5\n\n\ndef desc_action(action):\n if action == ACT_LOAD:\n return u\"卸货\"\n elif action == ACT_WEIGHT:\n return u\"称重\"\n elif action == ACT_CLOSE:\n return u\"关闭\"\n elif action == ACT_OPEN:\n return u\"打开\"\n return \"未知\"\n\ng_status_desc = {\n STATUS_LOADING: u\"正在卸货\",\n STATUS_WEIGHING: u\"等待称重\",\n STATUS_CLOSED: u\"关闭\",\n STATUS_DISMISSED: u\"取消\",\n}\n\ndef desc_status(status):\n return g_status_desc.get(status, u\"未知状态\")\n\n\n" }, { "alpha_fraction": 0.7116564512252808, "alphanum_fraction": 0.7116564512252808, "avg_line_length": 25.83333396911621, "blob_id": "b8b30b67d4baac172b8a08fa610ffdbb89db2e53", "content_id": "6b38d3d3feca5f3e4a471ca5b9d69cb7687bf315", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 163, "license_type": "no_license", "max_line_length": 65, "num_lines": 6, "path": "/lite_mms/portal/op/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "from flask import Blueprint\n\nop_page = Blueprint(\"op_page\", __name__, static_folder=\"static\", \n template_folder=\"templates\")\n\nimport lite_mms.portal.op.views\n\n\n" }, { "alpha_fraction": 0.6493710875511169, "alphanum_fraction": 0.650943398475647, "avg_line_length": 30.799999237060547, "blob_id": "baffadb3493cac9c45575eba3b1fe5578064e8fe", "content_id": "83f02786d6ccf8e6627efc2bdba594e3915328ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 676, "license_type": "no_license", "max_line_length": 71, "num_lines": 20, "path": "/lite_mms/apis/store.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nyour file description here\n\"\"\"\nfrom lite_mms.apis.customer import CustomerWrapper\nfrom lite_mms.models import Customer, StoreBill\n\ndef get_customer_list(time_span):\n \"\"\"\n 获取指定时间段内有仓单的客户\n \"\"\"\n import lite_mms.apis as apis\n\n if time_span not in [\"week\", \"month\", \"unlimited\"]:\n raise ValueError(\n u\"参数time_span值不能为%(time_span)s\" % {\"time_span\": time_span})\n after = apis.order.get_should_after_date(time_span)\n return [CustomerWrapper(customer) for customer in\n Customer.query.join(StoreBill).filter(\n StoreBill.create_time > after).distinct()]\n" }, { "alpha_fraction": 0.6407397389411926, "alphanum_fraction": 0.6415323615074158, "avg_line_length": 36.15121078491211, "blob_id": "736eb3e8c63e47fc76bd89bdd7756fccba8d33e6", "content_id": "24ce9c78156e04d0a9846d04ec765da7955d3799", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19401, "license_type": "no_license", "max_line_length": 183, "num_lines": 496, "path": "/lite_mms/basemain.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\nimport os\r\nfrom sqlalchemy.exc import SQLAlchemyError\r\nfrom flask import Flask, render_template, request, session, g, url_for, redirect\r\nfrom flask.ext.babel import Babel, gettext\r\nfrom flask.ext.nav_bar import FlaskNavBar\r\n\r\napp = Flask(__name__, instance_relative_config=True)\r\napp.config.from_object(\"lite_mms.default_settings\")\r\nif \"LITE_MMS_HOME\" in os.environ:\r\n app.config.from_pyfile(\r\n os.path.join(os.environ[\"LITE_MMS_HOME\"], \"config.py\"), silent=True)\r\napp.config.from_pyfile(os.path.join(os.getcwd(), \"config.py\"), silent=True)\r\nfrom flask.ext.login import LoginManager, current_user\r\nlogin_manager = LoginManager()\r\nlogin_manager.init_app(app)\r\nfrom flask.ext.principal import Principal, Permission\r\n\r\n\r\nimport yawf\r\n\r\nfrom lite_mms.database import db\r\nfrom lite_mms import models\r\nyawf.WorkFlowEngine(db, models.Node)\r\nimport yawf.models\r\nfrom lite_mms.apis.delivery import CreateDeliveryTaskWithAbnormalWeight, PermitDeliveryTaskWithAbnormalWeight\r\nyawf.register_policy(CreateDeliveryTaskWithAbnormalWeight)\r\nyawf.register_policy(PermitDeliveryTaskWithAbnormalWeight)\r\n\r\nprincipal = Principal(app)\r\n\r\nimport logging\r\nimport logging.handlers\r\n\r\nlogging.basicConfig(level=logging.DEBUG)\r\n\r\nfile_handler = logging.handlers.TimedRotatingFileHandler(\r\n app.config[\"LOG_FILE\"], 'D', 1, 10, \"utf-8\")\r\nfile_handler.setFormatter(\r\n logging.Formatter('%(asctime)s - %(levelname)s: %(message)s'))\r\nfile_handler.suffix = \"%Y%m%d.log\"\r\napp.logger.addHandler(file_handler)\r\n\r\nfrom lite_mms.log.handler import DBHandler\r\ntimeline_logger = logging.getLogger(\"timeline\")\r\ntimeline_logger.addHandler(DBHandler())\r\n# create upload files\r\n\r\nif not os.path.exists(app.config[\"UPLOAD_FOLDER\"]):\r\n os.makedirs(app.config[\"UPLOAD_FOLDER\"])\r\n\r\nbabel = Babel(app)\r\n\r\nnav_bar = FlaskNavBar(app)\r\n\r\nfrom flask.ext.databrowser import DataBrowser\r\nfrom lite_mms.database import db\r\nfrom lite_mms import constants\r\ndata_browser = DataBrowser(app, db, page_size=constants.ITEMS_PER_PAGE, logger=timeline_logger)\r\n\r\n# ============== REGISTER BLUEPRINT ========================\r\nserve_web = app.config[\"SERVE_TYPE\"] in [\"both\", \"web\"]\r\nserve_ws = app.config[\"SERVE_TYPE\"] in [\"both\", \"ws\"]\r\n\r\n\r\nif serve_web:\r\n from lite_mms.portal.report import report_page\r\n from flask.ext.report import FlaskReport\r\n from flask.ext.report.utils import collect_models\r\n from lite_mms import models\r\n\r\n def collect_model_names():\r\n ret = {}\r\n\r\n for k, v in models.__dict__.items():\r\n if hasattr(v, '_sa_class_manager'):\r\n ret[v.__tablename__] = v.__modelname__\r\n return ret\r\n\r\n class _FlaskReport(FlaskReport):\r\n\r\n def try_view_report(self):\r\n Permission.union(AdminPermission, AccountantPermission).test()\r\n\r\n def try_edit_data_set(self):\r\n Permission.union(AdminPermission, AccountantPermission).test()\r\n\r\n def try_edit_notification(self):\r\n AdminPermission.test()\r\n\r\n _FlaskReport(db, collect_models(models), app, report_page, {\r\n 'report_list': {\r\n 'nav_bar': nav_bar,\r\n },\r\n 'report': {\r\n 'nav_bar': nav_bar,\r\n },\r\n 'data_set': {\r\n 'nav_bar': nav_bar,\r\n },\r\n 'data_sets': {\r\n 'nav_bar': nav_bar,\r\n },\r\n 'notification_list': {\r\n 'nav_bar': nav_bar,\r\n },\r\n 'notification': {\r\n 'nav_bar': nav_bar,\r\n }\r\n }, collect_model_names())\r\n app.register_blueprint(report_page, url_prefix=\"/report\")\r\n from lite_mms.portal.store import store_bill_page\r\n app.register_blueprint(store_bill_page, url_prefix=\"/store\")\r\n from lite_mms.portal.deduction import deduction_page\r\n app.register_blueprint(deduction_page, url_prefix=\"/deduction\")\r\n from lite_mms.portal.auth import auth\r\n app.register_blueprint(auth, url_prefix=\"/auth\")\r\n from lite_mms.portal.cargo import cargo_page, gr_page\r\n app.register_blueprint(cargo_page, url_prefix='/cargo')\r\n app.register_blueprint(gr_page, url_prefix='/goods_receipt')\r\n from lite_mms.portal.delivery import delivery_page, consignment_page\r\n app.register_blueprint(delivery_page, url_prefix='/delivery')\r\n app.register_blueprint(consignment_page, url_prefix='/consignment')\r\n from lite_mms.portal.misc import misc\r\n app.register_blueprint(misc, url_prefix=\"/misc\")\r\n from lite_mms.portal.manufacture import manufacture_page\r\n app.register_blueprint(manufacture_page, url_prefix=\"/manufacture\")\r\n from lite_mms.portal.order import order_page\r\n app.register_blueprint(order_page, url_prefix=\"/order\")\r\n from lite_mms.portal.op import op_page\r\n app.register_blueprint(op_page, url_prefix=\"/op\")\r\n from lite_mms.portal.admin import admin_page\r\n app.register_blueprint(admin_page, url_prefix=\"/admin\")\r\n\r\n from lite_mms.portal.import_data import import_data_page\r\n app.register_blueprint(import_data_page, url_prefix=\"/import_data\")\r\n from lite_mms.portal.search import search_page\r\n app.register_blueprint(search_page, url_prefix=\"/search\")\r\n\r\n from lite_mms.portal.timeline import time_line_page\r\n app.register_blueprint(time_line_page, url_prefix=\"/timeline\")\r\n\r\n from lite_mms.portal.todo import to_do_page\r\n app.register_blueprint(to_do_page, url_prefix=\"/todo\")\r\n\r\n from lite_mms.portal.quality_inspection import qir_page\r\n app.register_blueprint(qir_page, url_prefix=\"/qir\")\r\n\r\n from lite_mms.portal.dashboard import dashboard\r\n app.register_blueprint(dashboard, url_prefix=\"/dashboard\")\r\n\r\n from lite_mms.portal.work_flow import work_flow_page\r\n app.register_blueprint(work_flow_page, url_prefix=\"/work-flow\")\r\n\r\nif serve_ws:\r\n\r\n from lite_mms.portal.auth_ws import auth_ws\r\n app.register_blueprint(auth_ws, url_prefix=\"/auth_ws\")\r\n from lite_mms.portal.cargo_ws import cargo_ws\r\n app.register_blueprint(cargo_ws, url_prefix='/cargo_ws')\r\n from lite_mms.portal.delivery_ws import delivery_ws\r\n app.register_blueprint(delivery_ws, url_prefix='/delivery_ws')\r\n from lite_mms.portal.order_ws import order_ws\r\n app.register_blueprint(order_ws, url_prefix=\"/order_ws\")\r\n from lite_mms.portal.manufacture_ws import manufacture_ws\r\n app.register_blueprint(manufacture_ws, url_prefix=\"/manufacture_ws\")\r\n\r\n\r\n# ====================== REGISTER NAV BAR ===================================\r\nfrom lite_mms.permissions.roles import (CargoClerkPermission, AccountantPermission, QualityInspectorPermission,\r\n AdminPermission, SchedulerPermission)\r\nfrom lite_mms.permissions.order import view_order, schedule_order\r\nnav_bar.register(cargo_page, name=u\"卸货会话\", permissions=[CargoClerkPermission], group=u\"卸货管理\")\r\nnav_bar.register(gr_page, name=u\"收货单\", permissions=[CargoClerkPermission], group=u\"卸货管理\")\r\nnav_bar.register(order_page, default_url='/order/order-list', name=u\"订单管理\",\r\n permissions=[view_order.union(schedule_order)])\r\nnav_bar.register(delivery_page, name=u'发货会话',\r\n permissions=[CargoClerkPermission], group=u\"发货管理\")\r\nnav_bar.register(consignment_page, name=u'发货单',\r\n permissions=[CargoClerkPermission.union(AccountantPermission)], group=u\"发货管理\")\r\nnav_bar.register(manufacture_page, name=u\"工单管理\",\r\n permissions=[SchedulerPermission])\r\nnav_bar.register(store_bill_page, name=u\"仓单管理\",\r\n default_url=\"/store/store-bill-list\",\r\n permissions=[QualityInspectorPermission])\r\nnav_bar.register(qir_page, name=u\"质检报告\", default_url=\"/qir/qireport-list\",\r\n permissions=[QualityInspectorPermission])\r\nnav_bar.register(deduction_page, name=u\"扣重管理\", default_url=\"/deduction/\",\r\n permissions=[QualityInspectorPermission])\r\nnav_bar.register(dashboard, name=u\"仪表盘\", permissions=[AdminPermission])\r\n\r\nnav_bar.register(time_line_page, name=u\"时间线\", default_url=\"/timeline/log-list\")\r\nnav_bar.register(admin_page, name=u\"管理中心\", default_url=\"/admin/user-list\", permissions=[AdminPermission])\r\nnav_bar.register(report_page, name=u\"报表列表\", default_url=\"/report/report-list\",\r\n permissions=[Permission.union(AdminPermission, AccountantPermission)], group=u'报表',\r\n enabler=lambda nav: request.path.startswith('/report/report'))\r\nnav_bar.register(report_page, name=u\"数据集合列表\", default_url=\"/report/data-sets\",\r\n permissions=[Permission.union(AdminPermission, AccountantPermission)], group=u'报表',\r\n enabler=lambda nav: request.path.startswith('/report/data-set'))\r\nnav_bar.register(report_page, name=u\"推送列表\", default_url=\"/report/notification-list\",\r\n permissions=[Permission.union(AdminPermission, AccountantPermission)], group=u'报表',\r\n enabler=lambda nav: request.path.startswith('/report/notification-list'))\r\nnav_bar.register(to_do_page, name=u\"待办事项\", default_url=\"/todo/todo-list\", count=0)\r\nnav_bar.register(work_flow_page, name=lambda: u\"工作流\",\r\n count=lambda: models.Node.query.filter(models.Node.handle_time == None).count(),\r\n default_url=\"/work-flow/node-list\", permissions=[CargoClerkPermission])\r\n\r\n#install jinja utilities\r\nfrom lite_mms.utilities import url_for_other_page, datetimeformat\r\nfrom lite_mms import permissions\r\n\r\napp.jinja_env.globals['url_for_other_page'] = url_for_other_page\r\napp.jinja_env.globals['permissions'] = permissions\r\napp.jinja_env.filters['_datetimeformat'] = datetimeformat\r\napp.jinja_env.add_extension(\"jinja2.ext.loopcontrols\")\r\n\r\nfrom flask.ext.principal import (identity_loaded, RoleNeed, UserNeed, PermissionDenied)\r\n\r\n@login_manager.user_loader\r\ndef load_user(user_id):\r\n from lite_mms.apis import auth\r\n return auth.get_user(user_id)\r\n\r\n\r\nfrom lite_mms.permissions.work_flow import HandleNodeNeed\r\n\r\n\r\n@identity_loaded.connect_via(app)\r\ndef permission_handler(sender, identity):\r\n\r\n from flask.ext import login\r\n\r\n identity.user = login.current_user\r\n if not identity.user:\r\n return\r\n if hasattr(identity.user, 'id'):\r\n identity.provides.add(UserNeed(unicode(identity.user.id)))\r\n\r\n if hasattr(identity.user, 'groups'):\r\n current_group_id = session.get('current_group_id')\r\n if current_group_id is None:\r\n current_group_id = request.cookies.get('current_group_id')\r\n if current_group_id is None:\r\n group = identity.user.groups[0]\r\n else:\r\n for group_ in identity.user.groups:\r\n if group_.id == current_group_id:\r\n group = group_\r\n break\r\n else:\r\n group = identity.user.groups[0]\r\n session['current_group_id'] = group.id\r\n identity.provides.add(RoleNeed(unicode(group.id)))\r\n\r\n if hasattr(identity.user, 'permissions'):\r\n for perm in identity.user.permissions:\r\n try:\r\n for need in permissions.permissions[perm.name][\"needs\"]:\r\n identity.provides.add(need)\r\n except KeyError:\r\n pass\r\n\r\n if os.path.dirname(request.path) == os.path.dirname(url_for('work_flow.node', id_=-1)):\r\n node = models.Node.query.get(os.path.basename(request.path))\r\n if node:\r\n if node.handler_group_id == current_user.group.id:\r\n identity.provides.add(HandleNodeNeed)\r\n\r\n\r\n#设置无权限处理器\r\[email protected](PermissionDenied)\r\[email protected](401)\r\ndef permission_denied(error):\r\n\r\n #如果用户已登录则显示无权限页面\r\n from flask import redirect, url_for\r\n if not current_user.is_anonymous:\r\n return redirect(url_for(\"error\", errors=u'请联系管理员获得访问权限!', url=request.args.get(\"url\")))\r\n #如果用户还未登录则转向到登录面\r\n return render_template(\"auth/login.html\",\r\n error=gettext(u\"请登录\"), next_url=request.url, titlename=u\"请登录\")\r\n\r\nif not app.debug:\r\n def sender_email(traceback):\r\n from flask.ext.mail import Mail, Message\r\n\r\n mail = Mail(app)\r\n senders = app.config.get(\"SENDERS\", [])\r\n if not senders:\r\n return\r\n msg = Message(subject=u\"%s %s时遇到异常\" % (request.method, request.url),\r\n html=traceback.render_summary(),\r\n sender=\"[email protected]\",\r\n recipients=senders)\r\n mail.send(msg)\r\n\r\n @app.errorhandler(Exception)\r\n def error(error):\r\n if isinstance(error, SQLAlchemyError):\r\n from lite_mms.database import db\r\n\r\n db.session.rollback()\r\n from werkzeug.debug.tbtools import get_current_traceback\r\n\r\n traceback = get_current_traceback(skip=1, show_hidden_frames=False,\r\n ignore_system_exceptions=True)\r\n app.logger.error(\"%s %s\" % (request.method, request.url))\r\n app.logger.error(traceback.plaintext)\r\n sender_email(traceback)\r\n return redirect(url_for(\"error\", errors=u\"%s %s时,系统异常\" % (request.method, request.url),\r\n detail=traceback.render_summary(), url=request.args.get(\"url\", \"/\")))\r\n\r\n\r\[email protected]_request\r\ndef call_after_request_callbacks(response):\r\n for callback in getattr(g, 'after_request_callbacks', ()):\r\n response = callback(response)\r\n return response\r\n\r\n\r\[email protected]\r\ndef get_locale():\r\n return \"zh_CN\"\r\n\r\n\r\[email protected]_request\r\ndef _():\r\n g.locale = get_locale()\r\n\r\nfrom work_flow_repr import Event\r\nfrom work_flow_repr.utils import ModelNode, annotate_model\r\nfrom lite_mms.models import (GoodsReceipt, Order, SubOrder, WorkCommand, Log, StoreBill)\r\n\r\n\r\nclass GoodsReceiptNode(ModelNode):\r\n @property\r\n def name(self):\r\n return u\"收货单\" + unicode(self.obj)\r\n\r\n @property\r\n def description(self):\r\n return render_template(\"work_flow_repr/goods_receipt.html\", goods_receipt=self.obj)\r\n\r\n @property\r\n def events(self):\r\n return [\r\n Event(self.obj.unload_session.create_time, u'开始卸货', _get_username(self.obj.creator) if self.obj.creator else ''),\r\n Event(self.obj.unload_session.finish_time, u'卸货完毕', \",\".join(\r\n _get_username(task.creator) for task in self.obj.unload_session.task_list)),\r\n Event(self.obj.order.create_time, u'生成订单', self.obj.order.creator.username),\r\n ]\r\n\r\n @property\r\n def target(self):\r\n return data_browser.get_form_url(self.obj)\r\n\r\n @property\r\n def children_model_groups(self):\r\n return [(u'订单', [self.obj.order]),]\r\n\r\n\r\nclass OrderNode(ModelNode):\r\n\r\n @property\r\n def name(self):\r\n return u\"订单\" + unicode(self.obj)\r\n\r\n @property\r\n def description(self):\r\n return ''\r\n\r\n @property\r\n def target(self):\r\n return data_browser.get_form_url(self.obj)\r\n\r\n @property\r\n def events(self):\r\n ret = [\r\n Event(self.obj.create_time, u'创建', _get_username(self.obj.creator), description=u'[%s] 创建' % str(self.obj.create_time), by=u'生成订单'),\r\n ]\r\n if self.obj.dispatched:\r\n ret.append(Event(self.obj.dispatched_time, u'下发订单', _get_username(self.obj.creator), description=u'[%s] 下发' % str(self.obj.dispatched_time)))\r\n return ret\r\n\r\n @property\r\n def children_model_groups(self):\r\n return [(u'子订单', self.obj.sub_order_list)]\r\n\r\n\r\nclass SubOrderNode(ModelNode):\r\n\r\n @property\r\n def name(self):\r\n return u\"子订单\" + unicode(self.obj)\r\n\r\n @property\r\n def description(self):\r\n return render_template(\"work_flow_repr/sub_order.html\", sub_order=self.obj)\r\n\r\n @property\r\n def target(self):\r\n return data_browser.get_form_url(self.obj)\r\n\r\n @property\r\n def events(self):\r\n ret = [\r\n Event(self.obj.create_time, u'创建', _get_username(self.obj.order.creator), by=u'生成子订单'),\r\n ]\r\n\r\n for wc in self.obj.work_command_list:\r\n if wc.cause == constants.work_command.CAUSE_NORMAL:\r\n ret.append(Event(wc.create_time, u'预排产', _get_username(self.obj.order.creator)))\r\n return ret\r\n\r\n @property\r\n def children_model_groups(self):\r\n return [\r\n (u'预排产工单', [wc for wc in self.obj.work_command_list if wc.cause == constants.work_command.CAUSE_NORMAL]), ]\r\n\r\n\r\nclass WorkCommandNode(ModelNode):\r\n\r\n @property\r\n def name(self):\r\n return u\"工单\" + unicode(self.obj)\r\n\r\n @property\r\n def description(self):\r\n return render_template('work_flow_repr/work-command.html', work_command=self.obj)\r\n\r\n @property\r\n def target(self):\r\n return data_browser.get_form_url(self.obj)\r\n\r\n @property\r\n def events(self):\r\n logs = Log.query.filter(Log.obj_cls == self.obj.model.__class__.__name__).filter(\r\n Log.obj_pk == self.obj.id).filter(Log.action != u'<增加重量>').filter(Log.action != u'新建').all()\r\n return [Event(self.obj.create_time, u'新建', _get_username(self.obj.order.creator),\r\n u'[%s]: 创建' % self.obj.create_time)] + [\r\n Event(log.create_time, log.action.strip('<>'), _get_username(self.obj.order.creator),\r\n u'[%s] %s' % (str(log.create_time), log.action.strip('<>'))) for log in logs]\r\n\r\n @property\r\n def children_model_groups(self):\r\n d = {}\r\n for wc in self.obj.next_work_command_list:\r\n d.setdefault(wc.cause, []).append(wc)\r\n\r\n store_bills = []\r\n for qir in self.obj.qir_list:\r\n for sb in qir.store_bill_list[:1]:\r\n store_bills.append(sb)\r\n\r\n return [(k, v) for k, v in d.items()] + [('仓单', store_bills)]\r\n\r\n\r\nclass StoreBillNode(ModelNode):\r\n\r\n @property\r\n def name(self):\r\n return u\"仓单\" + unicode(self.obj)\r\n\r\n @property\r\n def description(self):\r\n return render_template('work_flow_repr/store-bill.html', store_bill=self.obj)\r\n\r\n @property\r\n def target(self):\r\n return data_browser.get_form_url(self.obj)\r\n\r\n @property\r\n def events(self):\r\n ret = [\r\n Event(self.obj.create_time, u'创建', _get_username(self.obj.qir.actor), by='创建仓单', description=u'[%s] 创建' % str(self.obj.create_time))\r\n ]\r\n if self.obj.delivery_task:\r\n ret.append(Event(self.obj.delivery_task.create_time, u'发货', _get_username(self.obj.delivery_task.actor), description=u'[%s] 发货' % str(self.obj.delivery_task.create_time)))\r\n return ret\r\n\r\n @property\r\n def children_model_groups(self):\r\n next_store_bill_list = self.obj.next_store_bill_list\r\n if next_store_bill_list:\r\n return [(u'仓单', next_store_bill_list)]\r\n return []\r\n\r\n\r\ndef _get_username(obj):\r\n return obj.username if obj is not None else \"\"\r\n\r\nannotate_model(GoodsReceipt, GoodsReceiptNode)\r\nannotate_model(Order, OrderNode)\r\nannotate_model(SubOrder, SubOrderNode)\r\nannotate_model(WorkCommand, WorkCommandNode)\r\nannotate_model(StoreBill, StoreBillNode)\r\n\r\n" }, { "alpha_fraction": 0.6276150345802307, "alphanum_fraction": 0.6736401915550232, "avg_line_length": 10.093023300170898, "blob_id": "4da46376a1ed391780bbc6408960587d14376b05", "content_id": "3910718bb5f63596d9eb3e1c3cc51bde0509b6e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 478, "license_type": "no_license", "max_line_length": 102, "num_lines": 43, "path": "/alembic/versions/233cdabdfe51_add_is_last_to_deliv.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "\"\"\"add is_last to delivery-task\r\r\r\rRevision ID: 233cdabdfe51\r\rRevises: 56765d423498\r\rCreate Date: 2013-05-22 14:31:46.727000\r\r\r\r\"\"\"\r\r\r\r# revision identifiers, used by Alembic.\r\rrevision = '233cdabdfe51'\r\rdown_revision = '56765d423498'\r\r\r\rfrom alembic import op\r\rimport sqlalchemy as sa\r\r\r\r\r\rdef upgrade():\r\r op.add_column(\"TB_DELIVERY_TASK\", sa.Column(\"is_last\", sa.Boolean, default=False, nullable=False))\r\r\r\r\r\rdef downgrade():\r\r op.drop_column(\"TB_DELIVERY_TASK\", \"is_last\")\r\r" }, { "alpha_fraction": 0.620400071144104, "alphanum_fraction": 0.6223759055137634, "avg_line_length": 38.4900016784668, "blob_id": "c0afd4994695a8a0d5657b7cd1720cbcbce801aa", "content_id": "5439c09835229f87e0ddf01eaf3b7b68efa990d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4411, "license_type": "no_license", "max_line_length": 137, "num_lines": 100, "path": "/lite_mms/tools/build_db.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSYNOPSIS\r\n python build_db.py [options]\r\nBRIEF\r\n 本脚本用来初始化lite-mms, 包括预设的权限,用户组,帐号,权限,产品类型,产品等等, \r\n TODO: 目前这个脚本的初始化, 完全是基于金禾域的组织架构\r\nOPTIONS\r\n -h \r\n show this help\r\n -s <dbstr>\r\n the db connection string\r\n\"\"\"\r\nfrom hashlib import md5\r\nimport sys\r\nfrom getopt import getopt\r\nfrom flask import url_for\r\nfrom lite_mms.basemain import app\r\nimport lite_mms.constants.groups as groups\r\nimport lite_mms.constants as constants\r\nfrom lite_mms.permissions import permissions\r\nfrom lite_mms.utilities import do_commit\r\n\r\ndef build_db():\r\n msg = u\"初始化开始, 数据库是: \" + app.config[\"SQLALCHEMY_DATABASE_URI\"]\r\n app.logger.info(msg)\r\n import os\r\n dbstr = app.config[\"SQLALCHEMY_DATABASE_URI\"]\r\n if dbstr.startswith(\"sqlite\"):\r\n dir = os.path.split(dbstr[10:])[0]\r\n if dir and not os.path.exists(dir):\r\n os.makedirs(dir)\r\n from lite_mms.database import db, init_db\r\n from lite_mms import models\r\n db.drop_all()\r\n init_db()\r\n session = db.session\r\n\r\n # 初始化权限\r\n for k, v in permissions.items():\r\n do_commit(models.Permission(name=k, desc=v[\"brief\"]))\r\n\r\n with app.test_request_context():\r\n app.preprocess_request()\r\n # 初始化用户组,目前内置的用户组包括, 这些用户组本来就带有基于角色的权限\r\n # - 收发员\r\n cargo_clerk = models.Group(id=groups.CARGO_CLERK, name=u\"收发员\", default_url=url_for(\"cargo.index\"))\r\n cargo_clerk.permissions = models.Permission.query.filter(\r\n models.Permission.name.like(\"%view_order%\")).all()\r\n cargo_clerk = do_commit(cargo_clerk)\r\n # - 调度员\r\n scheduler = models.Group(id=groups.SCHEDULER, name=u\"调度员\", default_url=url_for(\"order.index\"))\r\n scheduler.permissions = models.Permission.query.filter(\r\n models.Permission.name.like(\r\n \"%schedule_order%\")).all() + models.Permission.query.filter(\r\n models.Permission.name.like(\"work_command%\")).all()\r\n scheduler = do_commit(scheduler)\r\n # - 车间主任\r\n department_leader = models.Group(id=groups.DEPARTMENT_LEADER, name=u\"车间主任\", default_url=url_for(\"manufacture.work_command_list\"))\r\n department_leader = do_commit(department_leader)\r\n # - 班组长\r\n team_leader = do_commit(models.Group(id=groups.TEAM_LEADER, name=u\"班组长\"))\r\n # - 质检员\r\n quality_inspector = models.Group(id=groups.QUALITY_INSPECTOR, name=u\"质检员\", default_url=url_for(\"store_bill.index\"))\r\n quality_inspector.permissions = models.Permission.query.filter(\r\n models.Permission.name.like(\"%view_work_command\")).all()\r\n quality_inspector = do_commit(quality_inspector)\r\n # - 装卸工\r\n loader = do_commit(models.Group(id=groups.LOADER, name=u\"装卸工\"))\r\n # - 财会人员\r\n accountant = models.Group(id=groups.ACCOUNTANT, name=u\"财会人员\", default_url=url_for(\"consignment.consignment_list\"))\r\n accountant.permissions = [models.Permission.query.filter(models.Permission.name.like(\"%export_consignment%\")).one()]\r\n accountant = do_commit(accountant)\r\n # - 管理员\r\n administrator = models.Group(id=groups.ADMINISTRATOR, name=u\"管理员\", default_url=url_for(\"admin.index\"))\r\n administrator.permissions = models.Permission.query.all()\r\n administrator = do_commit(administrator)\r\n\r\n # 初始化超级用户\r\n admin = models.User(username='admin', password=md5('admin').hexdigest(), groups=[administrator])\r\n admin.id = constants.ADMIN_USER_ID \r\n admin = do_commit(admin)\r\n\r\n # 设置默认产品类型和产品\r\n product_type_default = do_commit(models.ProductType(constants.DEFAULT_PRODUCT_TYPE_NAME))\r\n do_commit(models.Product(constants.DEFAULT_PRODUCT_NAME, product_type_default))\r\n session.flush()\r\n\r\n msg = u\"初始化完成\"\r\n app.logger.info(msg)\r\n\r\nif __name__ == \"__main__\":\r\n opts, _ = getopt(sys.argv[1:], \"s:h\")\r\n for o, v in opts:\r\n if o == \"-h\":\r\n print __doc__\r\n exit(1)\r\n else:\r\n print \"unknown option: \" + o\r\n build_db()\r\n" }, { "alpha_fraction": 0.5894498825073242, "alphanum_fraction": 0.6004521250724792, "avg_line_length": 46.73381423950195, "blob_id": "2558f35637942f3f090ce6d4496e45401f24c8f4", "content_id": "2aa5acddfab06b7e5cb4ca3b6ca651bf8d3c4ea0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7537, "license_type": "no_license", "max_line_length": 131, "num_lines": 139, "path": "/lite_mms/test/at/test_delivery.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\nfrom tempfile import mkdtemp\nfrom hashlib import md5\nimport shutil\n\nfrom pyfeature import (Feature, Scenario, given, when, and_, then, \n flask_sqlalchemy_setup, clear_hooks, before_each_feature, after_each_feature)\nimport mock\nimport yawf\n\nimport lite_mms\nfrom lite_mms import constants\n\nfrom lite_mms.basemain import app\nfrom lite_mms.database import db, codernity_db\n\nfrom CodernityDB.database import Database\n\ndef generate(times=1):\n from random import choice\n import string\n\n temp = \"\"\n for i in range(times):\n temp += choice(string.letters)\n return temp\n\npatcher = None\n\ndef test():\n \n @before_each_feature\n def setup(feature):\n app.config['CODERNITY_DATABASE_PATH'] = mkdtemp()\n global patcher\n patcher = mock.patch.dict(lite_mms.database.__dict__, \n {\n \"codernity_db\": Database(app.config['CODERNITY_DATABASE_PATH'])\n })\n patcher.start()\n lite_mms.database.codernity_db.create()\n \n\n @after_each_feature\n def teardown(feature):\n lite_mms.database.codernity_db.close()\n shutil.rmtree(app.config['CODERNITY_DATABASE_PATH'])\n patcher.stop()\n\n flask_sqlalchemy_setup(app, db, create_step_prefix=u\"创建\",\n model_name_getter=lambda model: model.__name__,\n attr_name_getter=lambda model, attr: model.__col_desc__.get(attr, attr),\n set_step_pattern=u'(\\w+)([\\.\\w+]+)设置为(.+)')\n\n with Feature(u\"发货会话测试\", step_files=[\"lite_mms.test.at.steps.delivery\"]):\n with Scenario(u\"准备数据\"):\n plate = given(u\"创建Plate\", name=generate(5))\n product_type_default = and_(u\"创建ProductType\", name=constants.DEFAULT_PRODUCT_TYPE_NAME)\n product_default = and_(u\"创建Product\", name=constants.DEFAULT_PRODUCT_NAME,\n product_type=product_type_default)\n group_cc = and_(u'创建Group(cargo_clerk)', name='cargo_clerk', \n id=constants.groups.CARGO_CLERK, default_url='/cargo/unload-session-list')\n and_(u\"创建User\", username=\"cc\", password=md5(\"cc\").hexdigest(), groups=[group_cc])\n group_loader = and_(u'创建Group(loader)', name='loader', id=constants.groups.LOADER)\n and_(u\"创建User\", username=\"l\", password=md5(\"l\").hexdigest(), groups=[group_loader])\n customer = and_(u\"创建Customer\", name=generate(5), abbr=generate(2))\n department = and_(u\"创建Department\", name=generate(5))\n harbor = and_(u\"创建Harbor\", name=generate(5), department=department)\n store_bill1 = and_(u\"生成StoreBill\", customer, harbor=harbor)\n store_bill2 = and_(u\"生成StoreBill\", customer, harbor=harbor)\n\n with Scenario(u\"创建发货会话,并生成发货单\"):\n delivery_session = when(u\"收发员创建发货会话\", plate=plate, tare=1500)\n then(u\"收发员选择仓单\", delivery_session, [store_bill1, store_bill2])\n and_(u\"装卸工全部装货、完全装货\", delivery_session, store_bill1)\n consignment = and_(u\"收发员生成发货单\", delivery_session)\n then(u\"发货单产品与仓单相同\", consignment, store_bill1)\n\n with Scenario(u\"修改发货会话\"):\n delivery_session = given(u\"已关闭的发货会话\", plate, tare=1000)\n status_code = when(u\"修改发货会话\", delivery_session)\n then(u\"无法修改\", status_code)\n when(u\"重新打开发货会话\", delivery_session)\n status_code = and_(u\"修改发货会话\", delivery_session)\n then(u\"修改成功\", status_code)\n\n with Scenario(u\"修改发货任务\"):\n delivery_session = given(u\"已关闭的发货会话\", plate, tare=1000)\n delivery_task = and_(u\"发货任务\", delivery_session)\n status_code = when(u\"修改发货任务\", delivery_task)\n then(u\"无法修改\", status_code)\n when(u\"重新打开发货会话\", delivery_session)\n status_code = and_(u\"修改发货任务\", delivery_task)\n then(u\"修改成功\", status_code)\n\n with Scenario(u\"修改发货单\"):\n consignment = given(u\"未打印的发货单\", customer, delivery_session, store_bill1.sub_order.product)\n status_code = when(u\"修改发货单的产品\", consignment)\n then(u\"修改成功\", status_code)\n when(u\"打印发货单\", consignment)\n status_code = and_(u\"修改发货单的产品\", consignment)\n then(u\"无法修改\", status_code)\n\n with Scenario(u\"对已生成发货单的发货会话,新增发货任务\"):\n delivery_session = given(u\"已生成发货单的发货会话\", plate, 1000, customer, store_bill1.sub_order.product)\n then(u\"重新打开发货会话\", delivery_session)\n when(u\"新增发货任务\", delivery_session, store_bill2)\n then(u\"提示需要重新生成发货单\", delivery_session)\n \n with Feature(u\"剩余重量异常\", step_files=[\"lite_mms.test.at.steps.delivery\"]):\n with Scenario(u'数据准备'):\n plate = given(u\"创建Plate\", name=generate(5))\n product_type_default = and_(u\"创建ProductType\", name=constants.DEFAULT_PRODUCT_TYPE_NAME)\n product_default = and_(u\"创建Product\", name=constants.DEFAULT_PRODUCT_NAME,\n product_type=product_type_default)\n group_cc = and_(u'创建Group(cargo_clerk)', name='cargo_clerk', \n id=constants.groups.CARGO_CLERK, default_url='/cargo/unload-session-list')\n and_(u\"创建User\", username=\"cc\", password=md5(\"cc\").hexdigest(), groups=[group_cc])\n group_loader = and_(u'创建Group(loader)', name='loader', id=constants.groups.LOADER)\n and_(u\"创建User\", username=\"l\", password=md5(\"l\").hexdigest(), groups=[group_loader])\n customer = and_(u\"创建Customer\", name=generate(5), abbr=generate(2))\n department = and_(u\"创建Department\", name=generate(5))\n harbor = and_(u\"创建Harbor\", name=generate(5), department=department)\n store_bill1 = and_(u\"生成StoreBill\", customer, harbor=harbor, weight=2000)\n store_bill2 = and_(u\"生成StoreBill\", customer, harbor=harbor, weight=1000)\n \n with Scenario(u'最简情况'):\n delivery_session = when(u\"收发员创建发货会话\", plate=plate, tare=1500)\n then(u\"收发员选择仓单\", delivery_session, [store_bill1, store_bill2])\n and_(u'创建发货任务, 包含两个仓单, 其中一个未完成, 剩余重量超过了原有仓单的重量', delivery_session, store_bill1, store_bill2)\n node_id = then(u'一个异常发货任务申请生成了', yawf.WorkFlowEngine.instance.db)\n then(u'不能再次创建发货任务,包含两个仓单,全部都完成', delivery_session, store_bill1, store_bill2)\n when(u'批准该申请', node_id)\n then(u'发货任务生成了, 存在一个未发货的仓单, 剩余重量是1001, 另外由两个仓单已经发货完毕, 其重量分别是2000, 1', delivery_session, store_bill1.id, store_bill2.id)\n\n clear_hooks()\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.47495362162590027, "alphanum_fraction": 0.5844155550003052, "avg_line_length": 18.962963104248047, "blob_id": "f3d90d38b36834d49f4698e790173e523d272db5", "content_id": "77a1e33a6cd98cbcaea1f529d3732bf67adbe9c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 539, "license_type": "no_license", "max_line_length": 49, "num_lines": 27, "path": "/tox.ini", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "[tox]\nenvlist = py27\n[testenv]\ndeps=\n pytest==2.3.4\n pylint==0.26.0\n Babel==0.9.6\n Brownie==0.5.1\n Flask==0.9\n Flask-Babel==0.8\n Flask-Login==0.1.3\n Flask-Principal==0.3.3\n MySQL-python==1.2.3\n SQLAlchemy==0.7.9\n WTForms==1.0.2\n Werkzeug==0.8.3\n Flask-Admin==1.0.3\n Flask-SQLAlchemy==0.16\n beautifulsoup4==4.1.3\n mock==1.0.1\n Pygments==1.5\n pyquery==1.2.4\n lxml>2.1\n twill==0.9\ncommands=\n py.test --junitxml=pytest_report.xml\n pylint -r n -f parseable lite_mms/__init__.py\n" }, { "alpha_fraction": 0.5745501518249512, "alphanum_fraction": 0.5803341865539551, "avg_line_length": 30.736841201782227, "blob_id": "0495a8e0ad36676a85b6fbcf26415dc32ee742a2", "content_id": "bb4aa5b41bd12bb43a68a6c826ccb4f457ed262b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3128, "license_type": "no_license", "max_line_length": 108, "num_lines": 95, "path": "/lite_mms/portal/index.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\nfrom flask import (redirect, send_from_directory, url_for, abort, render_template, request, json, g)\r\nfrom flask.ext.login import current_user, login_required\r\nfrom flask.helpers import safe_join\r\nfrom lite_mms.basemain import app, nav_bar\r\nfrom lite_mms.utilities import decorators\r\n\r\n\r\[email protected](\"/\")\r\ndef index():\r\n if current_user.is_authenticated:\r\n next_url = current_user.default_url\r\n else:\r\n next_url = url_for(\"auth.login\")\r\n if not next_url:\r\n return render_template(\"index.html\", nav_bar=nav_bar, titlename=u\"首页\")\r\n return redirect(next_url)\r\n\r\n\r\[email protected](\"/error\")\r\ndef error():\r\n errors = request.args[\"errors\"]\r\n if isinstance(errors, dict):\r\n return render_template(\"validation-error.html\", errors=errors, url=request.args.get(\"url\", \"/\"),\r\n nav_bar=nav_bar, titlename=u\"错误\"), 403\r\n else:\r\n return render_template(\"result.html\", errors=errors, url=request.args.get(\"url\", \"/\"),\r\n detail=request.args.get(\"detail\"), nav_bar=nav_bar, titlename=u\"错误\"), 403\r\n\r\n\r\[email protected](\"/result\")\r\ndef result():\r\n pass\r\n\r\n\r\[email protected](\"/index\")\r\[email protected](\"index.html\")\r\n@login_required\r\[email protected]_bar_set\r\ndef default():\r\n return dict(titelname=u\"首页\")\r\n\r\n\r\[email protected](\"/serv-pic/<filename>\")\r\ndef serv_pic(filename):\r\n return send_from_directory(app.config['UPLOAD_FOLDER'], filename)\r\n\r\n\r\ndef _resize_file(filename, size=(180, 180)):\r\n _dir = app.config['UPLOAD_FOLDER']\r\n new_filename = filename.replace(\".\", \"-%d%d.\" % size)\r\n import os\r\n\r\n if not os.path.exists(safe_join(_dir, new_filename)):\r\n from PIL import Image\r\n\r\n try:\r\n im = Image.open(safe_join(_dir, filename))\r\n ori_w, ori_h = im.size\r\n if ori_w > ori_h:\r\n _size = size[0], ori_h * size[1] / ori_w\r\n else:\r\n _size = ori_w * size[0] / ori_h, size[1]\r\n im.resize(_size, Image.ANTIALIAS).save(safe_join(_dir, new_filename), \"JPEG\")\r\n except IOError:\r\n pass\r\n return new_filename\r\n\r\n\r\[email protected](\"/serv-small-pic/<filename>\")\r\ndef serv_small_pic(filename):\r\n new_filename = _resize_file(filename)\r\n return send_from_directory(app.config['UPLOAD_FOLDER'], new_filename)\r\n\r\n\r\[email protected](\"/message\")\r\ndef ajax_new_message():\r\n if current_user.is_authenticated:\r\n from lite_mms.models import TODO\r\n from lite_mms.apis.todo import get_all_notify\r\n\r\n messages = [\r\n {\r\n \"create_time\": str(todo.create_time),\r\n \"actor\": todo.actor.username if todo.actor else \"\",\r\n \"action\": todo.action,\r\n \"msg\": todo.msg,\r\n \"context_url\": todo.context_url\r\n }\r\n for todo in get_all_notify(current_user.id)\r\n ]\r\n return json.dumps(\r\n {\"total_cnt\": TODO.query.filter(TODO.user_id == current_user.id).count(), \"messages\": messages})\r\n else:\r\n return json.dumps({\"total_cnt\": 0, \"messages\": []})\r\n\r\n" }, { "alpha_fraction": 0.4425036311149597, "alphanum_fraction": 0.44614264369010925, "avg_line_length": 26.459999084472656, "blob_id": "ea1fc27ef81169b065fc8a6a0ffee97a1235357d", "content_id": "23e800a1e8c5638d2389d7fe53e3474da44fd8c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1374, "license_type": "no_license", "max_line_length": 89, "num_lines": 50, "path": "/lite_mms/templates/admin/list.html", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "{% extends \"__data_browser__/list.html\" %}\n\n{% block __data_browser__hint_block %}\n {% if hint_message %}\n <div class=\"alert alert-info\">\n * {{ hint_message }}\n </div>\n {% endif %}\n{% endblock %}\n\n{% block __data_browser__custom_external_block %}\n <script type=\"text/javascript\">\n $(function () {\n $(\"#main-form\").attr(\"class\", \"col-lg-8\")\n });\n </script>\n{% endblock %}\n\n{% block body %}\n <div class=\"row\">\n <div class=\"col-lg-2\">\n <div class=\"well well-sm\">\n <ul class=\"nav nav-pills nav-stacked\">\n {% for group in sub_nav_bar.groups %}\n <li class=\"text-muted\"><h5>{{ group.name }}</h5></li>\n {% for nav_link in group.nav_links %}\n {% if nav_link.enabler() %}\n <li class=\"active text-center\">\n <a href=\"{{ nav_link.url }}\"><strong>{{ nav_link.anchor }}</strong></a>\n </li>\n {% else %}\n <li class=\"text-center\">\n <a href=\"{{ nav_link.url }}\">{{ nav_link.anchor }}</a>\n </li>\n {% endif %}\n {% endfor %}\n {% endfor %}\n </ul>\n </div>\n </div>\n {% block lists %}\n {{ super() }}\n {% endblock %}\n <div class=\"col-lg-2\">\n {% block filters %}\n {{ super() }}\n {% endblock %}\n </div>\n </div>\n{% endblock %}\n\n" }, { "alpha_fraction": 0.5329949259757996, "alphanum_fraction": 0.5341663360595703, "avg_line_length": 24.65625, "blob_id": "ac5fca13f7170d89d9c6d41c6ac916b618aa3d08", "content_id": "a2f847f7866a932d380737ed20a0deedc0fbe76d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2561, "license_type": "no_license", "max_line_length": 78, "num_lines": 96, "path": "/lite_mms/apis/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\nimport types\r\n\r\n_wrappers = {}\r\n\r\n\r\nclass ModelWrapper(object):\r\n def __init__(self, model):\r\n self.__model = model\r\n\r\n @property\r\n def model(self):\r\n return self.__model\r\n\r\n def __getattr__(self, name):\r\n unwrapped = False\r\n if name.endswith(\"unwrapped\"):\r\n name = name[0:-len(\"_unwrapped\")]\r\n unwrapped = True\r\n attr = getattr(self, name)\r\n else:\r\n attr = getattr(self.__model, name)\r\n if isinstance(attr, types.ListType) or isinstance(attr,\r\n types.TupleType):\r\n if unwrapped:\r\n return type(attr)(self.__unwrap(i) for i in attr)\r\n else:\r\n return type(attr)(self.__wrap(i) for i in attr)\r\n return attr if unwrapped else self.__wrap(attr)\r\n\r\n def __setattr__(self, key, value):\r\n if key != '_ModelWrapper__model':\r\n self.__model.__setattr__(key, value)\r\n else:\r\n self.__dict__[key] = value\r\n\r\n def __wrap(self, attr):\r\n from lite_mms.database import db\r\n\r\n if isinstance(attr, db.Model):\r\n return self.__do_wrap(attr)\r\n return attr\r\n\r\n def __unwrap(self, attr):\r\n\r\n if isinstance(attr, ModelWrapper):\r\n return attr.model\r\n return attr\r\n\r\n def __do_wrap(self, attr):\r\n try:\r\n return _wrappers[attr.__class__.__name__ + \"Wrapper\"](attr)\r\n except KeyError:\r\n return attr\r\n\r\n def __unicode__(self):\r\n return unicode(self.model)\r\n\r\n def __dir__(self):\r\n return self.model.__dict__.keys()\r\n\r\n\r\ndef wraps(model):\r\n try:\r\n return _wrappers[model.__class__.__name__ + \"Wrapper\"](model)\r\n except KeyError:\r\n return model\r\n\r\n\r\nimport auth\r\nimport cargo\r\nimport customer\r\nimport order\r\nimport manufacture\r\nimport quality_inspection\r\nimport delivery\r\nimport product\r\nimport store\r\nimport harbor\r\nimport broker\r\nimport plate\r\nimport log\r\nimport config\r\nimport todo\r\n\r\nfrom path import path\r\n\r\nfor fname in path(__path__[0]).files(\"[!_]*.py\"):\r\n fname = fname.basename()[:-len(\".py\")]\r\n package = __import__(str(\"lite_mms.apis.\" + fname), fromlist=[str(fname)])\r\n for k, v in package.__dict__.items():\r\n if isinstance(v, types.TypeType) and \\\r\n issubclass(v, ModelWrapper) and \\\r\n k.endswith(\"Wrapper\"):\r\n _wrappers[k] = v\r\n globals()[k] = v # install all the wrappers in this module\r\n\r\n" }, { "alpha_fraction": 0.5543683171272278, "alphanum_fraction": 0.5562539100646973, "avg_line_length": 32.8510627746582, "blob_id": "63ecba63787eb2ce9207cb3aff124f4eab6d6bdf", "content_id": "5923d1a992bb4c5cc3b3bfe34f36eb2ca0e85f6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1609, "license_type": "no_license", "max_line_length": 129, "num_lines": 47, "path": "/lite_mms/permissions/__init__.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n@author: Yangminghua\n@version: $\n\"\"\"\nfrom flask import session, render_template, request\nfrom flask.ext.login import current_user\nfrom lite_mms.utilities import _\nfrom path import path\n\n# 导入基于角色的权限\nfrom lite_mms.permissions.roles import (DepartmentLeaderPermission,\n QualityInspectorPermission,\n CargoClerkPermission,\n SchedulerPermission,\n AccountantPermission,\n AdminPermission)\n\n# do a little magic\npermissions = {}\nfrom flask.ext.principal import Permission, RoleNeed\n\ncur_dir = __path__[0]\n\nfor fname in path(cur_dir).files(\"[!_]*.py\"):\n fname = fname.basename()[:-len(\".py\")]\n if fname == \"roles\":\n continue\n package = __import__(str(\"lite_mms.permissions.\"+fname), fromlist=[str(fname)])\n for k, v in package.__dict__.items():\n if isinstance(v, Permission):\n permissions[package.__name__.split(\".\")[-1] + \".\" + k] = {\n \"needs\": v.needs,\n \"brief\": v.brief\n }\n\ndef reset_permissions():\n global permissions\n permissions = {}\n\ndef install_permission(perm_name, needs, brief):\n permissions[perm_name] = {\"needs\": needs, \"brief\": brief}\n \nif __name__ == \"__main__\":\n import pprint\n pprint.pprint(permissions)\n pprint.pprint(permissions[\"work_command.view_work_command\"][\"needs\"].pop() == permissions[\"order.view_order\"][\"needs\"].pop())\n" }, { "alpha_fraction": 0.48041775822639465, "alphanum_fraction": 0.48563969135284424, "avg_line_length": 32.017242431640625, "blob_id": "7d5ea2ea9c1878bd31895b27e7328cdf9c67f764", "content_id": "7e82e1512a1dd2de85932d27531b3e24ec63f60d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1915, "license_type": "no_license", "max_line_length": 105, "num_lines": 58, "path": "/lite_mms/static/js/print-area.js", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "(function(root, factory) {\n if (typeof define === 'function' && define.amd) {\n define([], factory);\n } else if (typeof exports === 'object') {\n module.exports = factory();\n } else {\n root.printArea = factory();\n }\n}(this, function() {\n 'use strict';\n function extractHead() {\n return Array.prototype.slice.apply(document.querySelectorAll('link'), [0])\n .filter(function(el){\n return el.getAttribute(\"rel\").toLowerCase() == \"stylesheet\";\n })\n .map(function(el){\n return '<link type=\"text/css\" rel=\"stylesheet\" href=\"' + el.getAttribute(\"href\") + '\" >';\n })\n .join('');\n }\n function printArea(el) {\n const head = extractHead();\n console.log(head);\n const iframe = document.createElement('iframe');\n document.body.appendChild(iframe);\n iframe.setAttribute('style', [\n ['border', 0],\n ['position', 'absolute'],\n ['width', 0],\n ['height', 0],\n ['left', 0],\n ['top', 0],\n ].map(p => p.join(':')).join(';'));\n iframe.setAttribute('src', '');\n iframe.setAttribute('id', new Date().getTime());\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument;\n } else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document;\n } else {\n iframe.doc = iframe.document;\n }\n (function(doc) {\n doc.open();\n doc.write('<html><head>' + head + '</head><body>' + el.outerHTML + '</body></html>')\n doc.close();\n }(iframe.doc));\n\n\n setTimeout((function(pw) {\n return function () {\n pw.focus();\n pw.print();\n };\n }(iframe.contentWindow || f)), 1000);\n }\n return printArea;\n}));\n" }, { "alpha_fraction": 0.6030042767524719, "alphanum_fraction": 0.6094420552253723, "avg_line_length": 20.18181800842285, "blob_id": "40dca77e0c20a6a2044b16d88c9c6868139b0c02", "content_id": "18bf30c8df71369aa3a2ed6f36e5f5f5ab93fd7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 466, "license_type": "no_license", "max_line_length": 87, "num_lines": 22, "path": "/lite_mms/data/lite-mms-blt", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\n${EXEC_VIRTUAL_ENV_ACTIVATE}\n\ncase \"$1\" in\nstart)\n cd ${WORK_ENV_DIR}\n python -m lite_mms.BLT --pidfile=/var/run/lite-mms-blt.pid\n ;;\nstop)\n kill `cat /var/run/lite-mms-blt.pid`\n ;;\nrestart)\n kill `cat /var/run/lite-mms-blt.pid`\n cd ${WORK_ENV_DIR}\n python -m lite_mms.BLT --pidfile=/var/run/lite-mms-blt.pid\n ;;\n*)\n echo \"Usage: $NAME {start|stop|restart|reload|force-reload|status|configtest}\" >&2 \n exit 1 \n ;;\nesac\n" }, { "alpha_fraction": 0.8247104287147522, "alphanum_fraction": 0.8254826068878174, "avg_line_length": 45.25, "blob_id": "b60148ae061330c639b9438c4954b2b2b3bc3a56", "content_id": "e082888626ba865ce53546eb63a6b02e8117936b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1419, "license_type": "no_license", "max_line_length": 84, "num_lines": 28, "path": "/lite_mms/permissions/roles.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n基于角色的用户权限\n\"\"\"\n\nfrom flask.ext.principal import Permission, RoleNeed \nfrom lite_mms.constants import groups\n\nDepartmentLeaderPermission = Permission(RoleNeed(unicode(groups.DEPARTMENT_LEADER)))\nDepartmentLeaderPermission.brief = u\"车间主任角色\"\nQualityInspectorPermission = Permission(RoleNeed(unicode(groups.QUALITY_INSPECTOR)))\nQualityInspectorPermission.brief = u\"质检员角色\"\nCargoClerkPermission = Permission(RoleNeed(unicode(groups.CARGO_CLERK)))\nCargoClerkPermission.brief = u\"收发员角色\"\nSchedulerPermission = Permission(RoleNeed(unicode(groups.SCHEDULER)))\nSchedulerPermission.brief = u\"调度员角色\"\nAccountantPermission = Permission(RoleNeed(unicode(groups.ACCOUNTANT)))\nAccountantPermission.brief = u\"财会人员角色\"\nAdminPermission = Permission(RoleNeed(unicode(groups.ADMINISTRATOR)))\nAdminPermission.brief = u\"管理员角色\"\nLoaderPermission = Permission(RoleNeed(unicode(groups.LOADER)))\nLoaderPermission.brief = u'装卸工角色'\nTeamLeaderPermission = Permission(RoleNeed(unicode(groups.TEAM_LEADER)))\nTeamLeaderPermission.brief = u'班组长角色'\nDepartmentLeaderPermission = Permission(RoleNeed(unicode(groups.DEPARTMENT_LEADER)))\nDepartmentLeaderPermission.brief = u'车间主任角色'\nQualityInspectorPermission = Permission(RoleNeed(unicode(groups.QUALITY_INSPECTOR)))\nQualityInspectorPermission.brief = u'质检员角色'\n" }, { "alpha_fraction": 0.5693877339363098, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 29, "blob_id": "7d82d80f5500a20977683dd3d5b3aedd90918b89", "content_id": "909b828ebff7cc8316f6fed5220b3ce843b53b04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1470, "license_type": "no_license", "max_line_length": 151, "num_lines": 49, "path": "/alembic/versions/1e9ee2636f8a_add_goods_receipt_en.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\"\"\"add goods receipt entry table\r\rRevision ID: 1e9ee2636f8a\r\rRevises: 318cae8ec27e\r\rCreate Date: 2013-04-23 11:40:57.400000\r\r\r\"\"\"\r\r\r\r# revision identifiers, used by Alembic.\rfrom lite_mms.utilities import do_commit\r\rrevision = '1e9ee2636f8a'\r\rdown_revision = '318cae8ec27e'\r\rfrom alembic import op\r\rimport sqlalchemy as sa\r\r\rdef upgrade():\r op.create_table(\"TB_GOODS_RECEIPT_ENTRY\",\r sa.Column(\"id\", sa.Integer, primary_key=True),\r sa.Column(\"goods_receipt_id\", sa.Integer,\r sa.ForeignKey(\"TB_GOODS_RECEIPT.id\")),\r sa.Column(\"weight\", sa.Integer),\r sa.Column(\"product_id\", sa.Integer, sa.ForeignKey(\"TB_PRODUCT.id\")),\r sa.Column(\"harbor_name\", sa.String(32), sa.ForeignKey(\"TB_HABOR.name\")),\r sa.Column(\"pic_path\", sa.String(256))\r )\r\r from lite_mms import apis\r for us in apis.cargo.get_unload_session_list()[0]:\r for gr in us.goods_receipt_list:\r gr.add_product_entries()\r\r op.add_column(\"TB_SUB_ORDER\", sa.Column(\"default_harbor_name\", sa.String(32), sa.ForeignKey(\"TB_HABOR.name\", name=\"tb_sub_order_fk_harbor_name1\")))\r\rdef downgrade():\r op.drop_table(\"TB_GOODS_RECEIPT_ENTRY\")\r op.drop_constraint(\"tb_sub_order_fk_harbor_name1\", \"TB_SUB_ORDER\",\r type_=\"foreignkey\")\r op.drop_column(\"TB_SUB_ORDER\", \"default_harbor_name\")\r" }, { "alpha_fraction": 0.6257568597793579, "alphanum_fraction": 0.6336749196052551, "avg_line_length": 28.410959243774414, "blob_id": "2f1d0492952ceeee95e393fa58ae529633057cdd", "content_id": "d73f28200a4f8cada207bd29ce82e522e23e276e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4622, "license_type": "no_license", "max_line_length": 108, "num_lines": 146, "path": "/lite_mms/portal/cargo/actions.py", "repo_name": "PuZheng/lite-mms", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom flask import url_for, redirect, request\nfrom flask.ext.databrowser.action import DeleteAction, BaseAction, DirectAction\nfrom flask.ext.login import current_user\nfrom lite_mms import constants\nfrom lite_mms.constants import cargo as cargo_const\n\n\nclass DeleteUnloadSessionAction(DeleteAction):\n def test_enabled(self, model):\n if model.goods_receipt_list:\n return -2\n return 0\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"收货会话%s已经生成了收货单,请先删除对应收货单以后再删除此收货会话!\"}\n\n def op(self, obj):\n from lite_mms.apis.todo import remove_todo, WEIGH_UNLOAD_TASK\n\n for task in obj.task_list:\n remove_todo(WEIGH_UNLOAD_TASK, task.id)\n super(DeleteUnloadSessionAction, self).op(obj)\n\n\nclass CloseAction(BaseAction):\n def test_enabled(self, model):\n if model.status in [cargo_const.STATUS_CLOSED, cargo_const.STATUS_DISMISSED]:\n return -2\n if not all(task.weight for task in model.task_list):\n return -3\n return 0\n\n def op(self, obj):\n from lite_mms.portal.cargo.fsm import fsm\n from flask.ext.login import current_user\n\n fsm.reset_obj(obj)\n fsm.next(cargo_const.ACT_CLOSE, current_user)\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"收货会话%s已经被关闭\",\n -3: u\"收货会话%s有卸货任务没有称重,请确保所有的卸货任务都已经称重!\"}\n\n\nclass OpenAction(BaseAction):\n def test_enabled(self, model):\n if model.status != cargo_const.STATUS_CLOSED:\n return -2\n return 0\n\n def op(self, obj):\n from lite_mms.portal.cargo.fsm import fsm\n from flask.ext.login import current_user\n\n fsm.reset_obj(obj)\n fsm.next(cargo_const.ACT_OPEN, current_user)\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"收货会话%s处在打开状态, 只有已经关闭的会话才能被打开\"}\n\n\nclass CreateReceiptAction(BaseAction):\n def test_enabled(self, model):\n if model.goods_receipt_list and all(not gr.stale for gr in model.goods_receipt_list) and len(\n model.goods_receipt_list) == len(model.customer_list):\n return -2\n elif not model.task_list:\n return -3\n return 0\n\n def op(self, obj):\n obj.clean_goods_receipts()\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"卸货会话%s已生成收货单\", -3: u\"卸货会话%s没有卸货任务,请先生成卸货任务\"}\n\n\nclass PrintGoodsReceipt(DirectAction):\n def op_upon_list(self, objs, model_view):\n model_view.do_update_log(objs[0], self.name)\n return redirect(url_for(\"cargo.goods_receipt_preview\", id_=objs[0].id, url=request.url))\n\n\nclass BatchPrintGoodsReceipt(DirectAction):\n def op_upon_list(self, objs, model_view):\n for obj in objs:\n model_view.do_update_log(obj, self.name)\n return redirect(\n url_for(\"goods_receipt.goods_receipts_batch_print\", id_=\",\".join([str(obj.id) for obj in objs]),\n url=request.url))\n\n\nclass CreateOrderAction(BaseAction):\n def test_enabled(self, model):\n if model.order:\n return -2\n return 0\n\n def op(self, obj):\n from lite_mms.apis.order import new_order\n\n new_order(obj.id, constants.STANDARD_ORDER_TYPE, current_user.id)\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"已生成订单\"}\n\n\nclass CreateExtraOrderAction(BaseAction):\n def test_enabled(self, model):\n if model.order:\n return -2\n return 0\n\n def op(self, obj):\n from lite_mms.apis.order import new_order\n\n new_order(obj.id, constants.EXTRA_ORDER_TYPE, current_user.id)\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"已生成订单\"}\n\n\nclass ViewOrderAction(DirectAction):\n def test_enabled(self, model):\n if model.order:\n return 0\n return -2\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"未生成订单\"}\n\n def op_upon_list(self, objs, model_view):\n return redirect(url_for(\"order.order\", id_=objs[0].order.id, url=request.url))\n\n\nclass DeleteGoodsReceiptAction(DeleteAction):\n def test_enabled(self, model):\n if model.order:\n return -2\n if model.printed:\n return -3\n return 0\n\n def get_forbidden_msg_formats(self):\n return {-2: u\"已生成订单的收货单不能删除\", -3: u\"已经打印的收货单不能删除\"}\n" } ]
184
honeydlck/shiyanlou-code
https://github.com/honeydlck/shiyanlou-code
ffbd97e82a5a17f4b2682927712cba570c177872
d05b48111899163e5757ada6826b1db32f641d6f
48c32252a58d9ae610c470d468923b079768446b
refs/heads/master
2020-09-20T20:40:19.134899
2019-11-28T06:41:02
2019-11-28T06:41:02
224,585,905
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3333333432674408, "alphanum_fraction": 0.44117647409439087, "avg_line_length": 19.399999618530273, "blob_id": "67d16114ac8c89d7799c43d4deed9d437b25afe5", "content_id": "4059975b9526b2416ad09ae53e0ec63b0899fa68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 102, "license_type": "no_license", "max_line_length": 39, "num_lines": 5, "path": "/jump7.py", "repo_name": "honeydlck/shiyanlou-code", "src_encoding": "UTF-8", "text": "for i in range(101):\n if i%7==0 or i%10==7 or i //10 ==7:\n pass\n else:\n print (i)\n" } ]
1
pjhalsli/configs
https://github.com/pjhalsli/configs
dc6626dea2827204ba8c31e36119a403b3746d02
0dd485ca8566a610abb9bc3a1e7b218a810167eb
2aedaca5a4ce4809a3ddf4d54b0d0c576e9c8a41
refs/heads/master
2021-07-02T03:38:28.877805
2021-06-28T22:42:09
2021-06-28T22:42:09
59,508,703
26
6
null
null
null
null
null
[ { "alpha_fraction": 0.5795232057571411, "alphanum_fraction": 0.6258981227874756, "avg_line_length": 18.818769454956055, "blob_id": "b7e8ec2fb1397c5637929da8e15259e762742075", "content_id": "8a857dae6e6a05ae93f9aaaa133ab4789f1568ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 6238, "license_type": "no_license", "max_line_length": 76, "num_lines": 309, "path": "/W541/polybar/config.B", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "# \n# # # \n# ### ### # # # ### ## ### \n# # # # # # ### # # # # # \n# ### ### ## # ### ### # \n# # ### \n#\n\n[color]\n\ntrans = #00000000\nwhite = #dddddd\nblack = #000000\n\n## Iceberg\n#bg = #161821\n#fg = #C6C8D1\n\n## Cherry\n#bg = #161821\n#fg = #BBBBBB\n\n## Dracula\nbg = 282a36\nfg = f8f8f2\n\n\nacolor = #FFFFFF\ncurgent = #EF5350\ncoccupied = #42A5F5\n\nshade1 = #212121\nshade2 = #2e3440\nshade3 = #616161\nshade4 = #757575\nshade5 = #9E9E9E\nshade6 = #BDBDBD\nshade7 = #D4D4D4\nshade8 = #EEEEEE\nashade8 = #2C2C2C\n\n## Material Colors\n\nred = #e53935\npink = #d81b60\npurple = #8e24aa\ndeep-purple = #5e35b1\nindigo = #3949ab\nblue = #1e88e5\nlight-blue = #039be5\ncyan = #00acc1\nteal = #00897b\ngreen = #43a047\nlight-green = #7cb342\nlime = #c0ca33\nyellow = #fdd835\namber = #ffb300\norange = #fb8c00\ndeep-orange = #f4511e\nbrown = #6d4c41\ngrey = #757575\nblue-gray = #546e7a\n\n;==========================================================\n\n[bar/def]\nwidth = 100%\nheight = 32\noffset-x = 0%\noffset-y = 0%\nbottom = false\nfixed-center = true\nline-size = 1\n\noverride-redirect = true\nwm-restack = bspwm\n\nbackground = ${color.bg}\nforeground = ${color.fg}\n\nborder-size = 0\n;border-top-size = 1\n;border-color = #B34F63\n\n;==========================================================\n\nfont-0 = \" Crisp Regular:pixelsize=8;2\"\nfont-1 = \"Iosevka Nerd Font:pixelsize=8;2\"\nfont-2 = \"icomoon:pixelsize=8;2\"\n\n;==========================================================\n\ncursor-click = pointer\ncursor-scroll = ns-resize\n\nscroll-up = i3wm-wsnext\nscroll-down = i3wm-wsprev\n\n;== Module Location ========================================================\n\nmodules-left = arch battery xwindow\nmodules-center = bspwm\nmodules-right = mpd volume xbacklight wlan date powermenu\n \n; xtra mods = battery mail updates weather bitcoin\n\n;== Modules ========================================================\n\n[module/arch]\ntype = custom/text\ncontent = \n;alt icons = \ncontent-padding = 2\ncontent-background = ${color.bg}\ncontent-foreground = ${color.fg}\nclick-left = rmenu_1\nclick-right = rmenu_wi_1\n\n\n[module/xwindow]\ntype = internal/xwindow\nlabel =  %title:0:25:...%\nlabel-padding = 2\nlabel-background = ${color.bg}\nlabel-foreground = ${color.fg}\n\n\n[module/bspwm]\ntype = internal/bspwm\npin-workspaces = false\nenable-click = true\nenable-scroll = true\nformat-padding = 1\n\nws-icon-0 = I;\nws-icon-1 = II;\nws-icon-2 = III;\nws-icon-3 = IV;\nws-icon-4 = V;\nws-icon-5 = VI;\nws-icon-6 = VII;\nws-icon-7 = VIII;\nws-icon-8 = IX;\nws-icon-9 = X;\n\nicon-default = \n\nformat = <label-state>\n;format-background = ${color.bg}\nlabel-background =${color.shade1}\nlabel-focused = ●\nlabel-occupied = ●\nlabel-urgent = ●\nlabel-empty = ●\n\nlabel-empty-padding = 1\nlabel-focused-padding = 1\nlabel-urgent-padding = 1\nlabel-occupied-padding = 1\n\nlabel-empty-foreground = #444444\nlabel-focused-foreground = #8BE9FD\nlabel-urgent-foreground = #FF5555\nlabel-occupied-foreground = #BD93F9\n\n\n;==========================================================\n\n[module/mpd]\ntype = internal/mpd\nformat-online = <toggle> <label-song> \n;format-online =  <label-song> \n;alt icons =   \nformat-online-foreground = ${color.fg}\nformat-online-background = ${color.bg}\nformat-online-padding = 2\n\nicon-play = 喇\nicon-pause = \n\nlabel-song-maxlen = 35\nlabel-song-ellipsis = true\n\n;==========================================================\n\n[module/pkg]\ntype = custom/script\nexec = updates.sh\nformat-background = ${color.bg}\nformat-padding = 2\ntail = true\n\n\n[module/battery]\ntype = internal/battery\nfull-at = 99\ntime-format = %H:%M\nbattery = BAT1\nadapter = AC\nformat-charging = <animation-charging> <label-charging>\nformat-charging-background = ${color.bg}\nformat-charging-padding = 2\nlabel-charging = %percentage%%\nlabel-charging-background = ${color.bg}\nformat-discharging = <ramp-capacity> <label-discharging>\nformat-discharging-background = ${color.bg}\nformat-discharging-padding = 2\nlabel-discharging = %percentage%% \nformat-full = <label-full>\nformat-full-background = ${color.bg}\nlabel-padding = 2\nlabel-charging-padding = 2\nformat-full-prefix = \" \"\nramp-capacity-0 = \nramp-capacity-1 = \nramp-capacity-2 = \nramp-capacity-3 = \nramp-capacity-4 = \nramp-capacity-5 = \nramp-capacity-6 = \nramp-capacity-7 = \nramp-capacity-8 = \nramp-capacity-9 = \n\nramp-capacity-0-foreground = ${color.red}\nramp-capacity-1-foreground = ${color.red}\nramp-capacity-foreground = ${color.fg}\nbar-capacity-width = 10\n\nanimation-charging-0 = \nanimation-charging-1 = \nanimation-charging-2 = \nanimation-charging-3 = \nanimation-charging-4 = \nanimation-charging-5 = \nanimation-charging-6 = \n\nanimation-charging-framerate = 750\n\n[module/volume]\ntype = internal/alsa\nformat-volume = <ramp-volume> <label-volume>\nformat-volume-padding = 2\nformat-volume-background = ${color.bg}\nformat-volume-foreground = ${color.fg}\nlabel-volume = %percentage%%\nlabel-muted = \"婢\"\nlabel-muted-background = ${color.bg}\nlabel-muted-padding = 2\n\nramp-volume-0 = 奄\nramp-volume-1 = 奄\nramp-volume-2 = 奔\nramp-volume-3 = 奔\nramp-volume-4 = 墳\nramp-volume-5 = 墳\nramp-volume-6 = 墳\n\n\n\n[module/xbacklight]\ntype = internal/xbacklight\nformat = <label>\nformat-foreground = ${color.fg}\nformat-background = ${color.bg}\n;format-padding = 2\nlabel = \" %percentage%\"\nlabel-background = ${color.bg} \nlabel-padding = 2\n\n\n[module/wlan]\ntype = internal/network\ninterface = wlp3s0\ninterval = 3.0\nformat-connected-background = ${color.bg}\nformat-padding = 2\ntail = true\nlabel-background =${color.shade3}\n\nformat-connected = <ramp-signal> <label-connected>\nlabel-connected = %essid%\nlabel-connected-background = ${color.bg}\n;format-disconnected =\nramp-signal-0 =\nlabel-connected-padding = 2\n\n\n[module/date]\ntype = internal/date\ninterval = 30\nlabel = %time%\nlabel-padding = 2\nlabel-background = ${color.bg}\ntime =  %H:%M\ntime-alt =  %d-%m-%Y\n\n[module/powermenu]\ntype = custom/text\ncontent = 襤\ncontent-padding = 2\ncontent-background = ${color.bg}\ncontent-foreground = ${color.fg}\nclick-left = pmenu_1\nclick-right = pmenu_1\n\n;== EOF ========================================================\n\n# vim: ft=sh\n" }, { "alpha_fraction": 0.7051542401313782, "alphanum_fraction": 0.7183441519737244, "avg_line_length": 34.970802307128906, "blob_id": "3e39f5dd52709698382631cc804a567784404da5", "content_id": "3b8c500fb551fe6436ca7f006c18f450ae6c8c17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4928, "license_type": "no_license", "max_line_length": 107, "num_lines": 137, "path": "/W541/.zshrc", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "# # \n# ## ## ### ### ### \n# # # # # # # \n# ## ## # # # ### \n#\n\nsource $(dirname $(gem which colorls))/tab_complete.sh\n\nexport NNN_PLUG='o:fzopen;p:mocplay;d:diffs;m:nmount;n:notes;v:imgviu;t:imgthumb'\n\n# Enable Powerlevel10k instant prompt. Should stay close to the top of ~/.zshrc.\n# Initialization code that may require console input (password prompts, [y/n]\n# confirmations, etc.) must go above this block, everything else may go below.\nif [[ -r \"${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh\" ]]; then\n source \"${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh\"\nfi\n\n# Enable Powerlevel10k instant prompt. Should stay close to the top of ~/.zshrc.\n# Initialization code that may require console input (password prompts, [y/n]\n# confirmations, etc.) must go above this block, everything else may go below.\n#if [[ -r \"${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh\" ]]; then\n# source \"${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh\"\n#fi\n\n# If you come from bash you might have to change your $PATH.\nexport PATH=$HOME/bin:/usr/local/bin:$PATH\n\n# Path to your oh-my-zsh installation.\nexport ZSH=$HOME/.oh-my-zsh\n\n# Set name of the theme to load --- if set to \"random\", it will\n# load a random theme each time oh-my-zsh is loaded, in which case,\n# to know which specific one was loaded, run: echo $RANDOM_THEME\n# See https://github.com/robbyrussell/oh-my-zsh/wiki/Themes\nZSH_THEME=\"absolute\"\n\n# Set list of themes to pick from when loading at random\n# ZSH_THEME_RANDOM_CANDIDATES=( \"robbyrussell\" \"agnoster\" )\n\n# Uncomment the following line to use case-sensitive completion.\n# CASE_SENSITIVE=\"true\"\n\n# Uncomment the following line to use hyphen-insensitive completion.\n# Case-sensitive completion must be off. _ and - will be interchangeable.\n# HYPHEN_INSENSITIVE=\"true\"\n\n# Uncomment the following line to disable bi-weekly auto-update checks.\n# DISABLE_AUTO_UPDATE=\"true\"\n\n# Uncomment the following line to change how often to auto-update (in days).\n# export UPDATE_ZSH_DAYS=13\n\n# Uncomment the following line to disable colors in ls.\n# DISABLE_LS_COLORS=\"true\"\n\n# Uncomment the following line to disable auto-setting terminal title.\n# DISABLE_AUTO_TITLE=\"true\"\n\n# Uncomment the following line to enable command auto-correction.\nENABLE_CORRECTION=\"true\"\nsetopt correctall\nexport CORRECT_IGNORE_FILE='.*'\n\n# Uncomment the following line to display red dots whilst waiting for completion.\nCOMPLETION_WAITING_DOTS=\"true\"\n\n# Uncomment the following line if you want to disable marking untracked files\n# under VCS as dirty. This makes repository status check for large repositories\n# much, much faster.\n# DISABLE_UNTRACKED_FILES_DIRTY=\"true\"\n\n# Uncomment the following line if you want to change the command execution time\n# stamp shown in the history command output.\n# You can set one of the optional three formats:\n# \"mm/dd/yyyy\"|\"dd.mm.yyyy\"|\"yyyy-mm-dd\"\n# or set a custom format using the strftime function format specifications,\n# see 'man strftime' for details.\n HIST_STAMPS=\"dd.mm.yyyy\"\n\n# Would you like to use another custom folder than $ZSH/custom?\n# ZSH_CUSTOM=/path/to/new-custom-folder\n\n# Which plugins would you like to load?\n# Standard plugins can be found in ~/.oh-my-zsh/plugins/*\n# Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/\n# Example format: plugins=(rails git textmate ruby lighthouse)\n# Add wisely, as too many plugins slow down shell startup.\nplugins=(archlinux git jump themes )\n\n\nsource $ZSH/oh-my-zsh.sh\n\n\n# User configuration\n\n# Import colorscheme from 'wal' asynchronously\n# & \n# Run the process in the background.\n# ( ) \n# Hide shell job control messages.\n#(cat ~/.cache/wal/sequences &)\n# For TTY support\n# source ~/.cache/wal/colors-tty.sh\n\n# export MANPATH=\"/usr/local/man:$MANPATH\"\n\n\n# You may need to manually set your language environment\n# export LANG=en_US.UTF-8\n\n\n# Preferred editor for local and remote sessions\n if [[ -n $SSH_CONNECTION ]]; then\n export EDITOR='vim'\n else\n export EDITOR='mvim'\n fi\n\n\n# Personal Shit\n[ -f ~/.fzf.colors ] && source ~/.fzf.colors\nalias 256='curl -s https://gist.githubusercontent.com/HaleTom/89ffe32783f89f403bba96bd7bcd1263/raw/ | bash'\nalias lock=\"i3lock -i Bilder/wp/wallhaven-670048_1920x1080.png -p win -f Source-Code-Pro\"\n#alias lockp=\"i3lock-fancy -p -f Source-Code-Pro-Medium -t 'Back Soon'\"\n#alias cheeze=\"./scripts/cheeze\"\nalias gcal='gcalcli --auth_host_name AUTH_HOST_NAME'\nalias eyes='cowsay -f eyes I Am Watching You'\nalias wttr='curl http://wttr.in trondheim'\nalias pb=\"curl -F 'f:1=@\"\nalias ytv=\"youtube-dl\"\nalias yta=\"youtube-dl --extract-audio --audio-format mp3 \"\nalias slurm='slurm -i wlp3s0'\nalias rsfetch=\"rsfetch -PdeHklrstuwp pacman ; panes\"\nalias cls=\"colorls\"\nalias up=\"pikaur -Syu\"\n# To customize prompt, run `p10k configure` or edit ~/.p10k.zsh.\n[[ ! -f ~/.p10k.zsh ]] || source ~/.p10k.zsh\n" }, { "alpha_fraction": 0.4943310618400574, "alphanum_fraction": 0.5071806311607361, "avg_line_length": 31.219512939453125, "blob_id": "14e26466f8d4a3a19057ebca9729bf4ec9374a5d", "content_id": "f7afe7f13832660e6185ef64b7c357067f5b3bc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1439, "license_type": "no_license", "max_line_length": 97, "num_lines": 41, "path": "/scripts-misc/fetch", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport platform, subprocess, re\n\nsubprocess.run('clear')\n\nuname = platform.uname()\nxid = subprocess.getoutput('xprop -root -notype _NET_SUPPORTING_WM_CHECK')\nxid=xid[-8:]\n\nBOLD = '\\033[1m'\nEND = '\\033[0m'\n\n\nhost = subprocess.getoutput('whoami')+\"@\"+uname[1]\n\ndistro = subprocess.getoutput('cat /etc/os-release')\ndistro = re.findall(r'_NAME=\\\"(.*)\\\"', distro)[0].lower()\n\nkernel = subprocess.getoutput('uname').lower()+' '+subprocess.getoutput('uname --kernel-release')\n\nwm = subprocess.getoutput('xprop -id '+xid+' -notype -len 100 -f _NET_WM_NAME 8t')\nwm = re.findall(r'_NET_WM_NAME = \\\"(\\w+)\\\"', wm)\nif len(wm) > 0:\n wm = wm[0].lower()\nelse:\n wm = 'none'\n\nuptime = subprocess.getoutput('uptime -p').replace('up ','')\nif uptime == '':\n uptime = 'meow'\n\n\nprint(''' ┌────────────────────┐''')\nprint(''' │ >_ │ {}'''.format(BOLD+host+END))\nprint(''' │ │ {}'''.format('-'*len(host)))\nprint(''' │ │ {}'''.format(BOLD+'distro: '+END+distro))\nprint(''' │ │ {}'''.format(BOLD+'kernel: '+END+kernel))\nprint(''' │ │ {}'''.format(BOLD+'wm: '+END+wm))\nprint(''' │ │ {}'''.format(BOLD+'uptime: '+END+uptime))\nprint(''' │ │''')\nprint(''' └────────────────────┘\\n''')\n \n" }, { "alpha_fraction": 0.5590550899505615, "alphanum_fraction": 0.5590550899505615, "avg_line_length": 41, "blob_id": "42f99619776aafe856f488071b04fe0a7a8cf49b", "content_id": "5466332ad9015e29fb02bc558c805996c699f967", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 127, "license_type": "no_license", "max_line_length": 114, "num_lines": 3, "path": "/scripts-misc/weechat_np", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nprintf '%s %s\\n' \"/me is listening to\" /exec -pipe \"$(mpc current --format \"\\\"%title%\\\" by %artist% \\[%album%\\]\")\"\n\n" }, { "alpha_fraction": 0.5662147998809814, "alphanum_fraction": 0.594369113445282, "avg_line_length": 17.423076629638672, "blob_id": "42087b16879d6a7c168c52f9a7f7af93651cdd29", "content_id": "93bcb51632569f9e44e4ccb03ed898fe81e041b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 974, "license_type": "no_license", "max_line_length": 69, "num_lines": 52, "path": "/W541/polybar/pmenu.sh", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n## Author : Aditya Shakya (adi1090x)\n## Mail : [email protected]\n## Github : @adi1090x\n## Reddit : @adi1090x\n\nrofi_command=\"rofi -theme $HOME/.config/polybar/color.rasi\"\n\n# Options\nshutdown=\"󰐥\"\nreboot=\"󰜉\"\nlock=\"󰤁\"\nsuspend=\"󰤄\"\nlogout=\"󰿅\"\n\n# Variable passed to rofi\noptions=\"$shutdown\\n$reboot\\n$lock\\n$suspend\\n$logout\"\n\n# Remapping movement\nxmodmap -e \"keycode 32 = Return\"\nxmodmap -e \"keycode 44 = Down\"\nxmodmap -e \"keycode 45 = Up\"\n\nchosen=\"$(echo -e \"$options\" | $rofi_command -dmenu -selected-row 2)\"\n\n# Reset Remapping\nxmodmap -e \"keycode 32 = o\"\nxmodmap -e \"keycode 44 = j\"\nxmodmap -e \"keycode 45 = k\"\n\ncase $chosen in\n $shutdown)\n sudo poweroff\n ;;\n $reboot)\n sudo reboot\n ;;\n $lock)\n betterlockscreen -l &\n ;;\n $suspend)\n mpc -q pause\n amixer set Master mute\n\tbetterlockscreen -l & \n\tsleep 0.5\n systemctl suspend\n ;;\n $logout)\n bspc quit\n ;;\nesac\n\n" }, { "alpha_fraction": 0.6040118932723999, "alphanum_fraction": 0.6092124581336975, "avg_line_length": 25.920000076293945, "blob_id": "c04da392b41500acd30b92805d2ae25a6e86fb8c", "content_id": "1531ed253adcf4f52c5d0d9f2d2d1ad433b01e9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1346, "license_type": "no_license", "max_line_length": 68, "num_lines": 50, "path": "/startpage/js/header.js", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "var header = (function() {\n\n var _bind = function() {\n window.addEventListener(\"resize\", function(event) {\n render();\n }, false);\n window.addEventListener(\"scroll\", function(event) {\n _addHeaderBackground();\n }, false);\n helper.eA(\".container\").forEach(function(arrayItem, index) {\n arrayItem.addEventListener(\"transitionend\", function() {\n render();\n }, false);\n });\n };\n\n var _addHeaderBackground = function() {\n var html = helper.e(\"html\");\n var header = helper.e(\".header\");\n var scrollPosition = document.documentElement.scrollTop;\n var fontSize = parseInt(getComputedStyle(html).fontSize, 10);\n if (scrollPosition > (fontSize * 2)) {\n helper.addClass(header, \"header-background\");\n } else {\n helper.removeClass(header, \"header-background\");\n };\n };\n\n var render = function() {\n var html = helper.e(\"html\");\n var header = helper.e(\".header\");\n var link = helper.e(\".link\");\n var height = parseInt(getComputedStyle(header).height, 10);\n // var fontSize = parseInt(getComputedStyle(html).fontSize, 10);\n // link.style.marginTop = (height + fontSize) + \"px\";\n link.style.marginTop = height + \"px\";\n };\n\n var init = function() {\n _bind();\n render();\n };\n\n // exposed methods\n return {\n init: init,\n render: render\n };\n\n})();\n" }, { "alpha_fraction": 0.694915235042572, "alphanum_fraction": 0.694915235042572, "avg_line_length": 10.800000190734863, "blob_id": "ebdac247a88c1b640a1f15021dc1dc1a5849f492", "content_id": "2adbd5e9cf16d5298ae9e675350553d5e17c409d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 118, "license_type": "no_license", "max_line_length": 35, "num_lines": 10, "path": "/W541/.xinitrc", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\n# START THE BEST MF WM IN THE WORLD\n\n[Cursor]\nxsetroot -cursor_name left_ptr\nxbanish &\n#wal -R\n\nexec bspwm\n" }, { "alpha_fraction": 0.5647768974304199, "alphanum_fraction": 0.6048717498779297, "avg_line_length": 29.72185516357422, "blob_id": "42f89ffbc35f4407a379ce150b7c10f4db6ecf90", "content_id": "5193dac892302e2785575e7607489b7cbaae9443", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4775, "license_type": "no_license", "max_line_length": 153, "num_lines": 151, "path": "/scripts-misc/envinfo", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# simple screen information script\n# similar to archey and screenfetch without annoying ASCII graphics\n\n# this script is provided with NO GUARANTEE and NO SUPPORT\n# if it breaks or does not do what you want, FIX IT YOURSELF\n\nVERSION=\"3.4\" # updated for changes to free -m\n\n# read wm names from a file\n#WMLIST='/usr/bin/wmlist'\n#wms=($(cat $WMLIST)) # read wmlist from file\n\n# or use wm array -- add any that need to be recognized\nwms=( 2bwm 2wm 9wm aewm afterstep ahwm alopex amiwm antiwm awesome blackbox bspwm catwm clfswm ctwm cwm dminiwm dragonflywm dwm echinus \\\n\teuclid-wm evilpoison evilwm fluxbox flwm fvwm-crystal goomwwm hcwm herbstluftwm i3 icewm jwm karmen larswm lwm matwm2 mcwm monsterwm \\\n\tmusca notion nwm olwm openbox oroborus pekwm ratpoison sapphire sawfish sscrotwm sithwm smallwm snapwm spectrwm stumpwm subtle tfwm tinywm tritium twm \\\n\tuwm vtwm w9wm weewm wind windowlab wm2 wmaker wmfs wmii wmx xfwm4 xmonad xoat yeahwm )\n\n# define colors for color-echo\nred=\"\\e[31m\"\ngrn=\"\\e[32m\"\nylw=\"\\e[33m\"\ncyn=\"\\e[36m\"\nblu=\"\\e[34m\"\nprp=\"\\e[35m\"\nrst=\"\\e[0m\"\n\ncolor-echo() { # print with colors\necho -e \" $ylw$1: $rst$2\"\n}\n\n#print-kernel() {\n#color-echo 'Kernel' \"$(uname -smr)\"\n#}\n\nprint-uptime() {\nup=$(</proc/uptime)\nup=${up//.*} # string before first . is seconds\ndays=$((${up}/86400)) # seconds divided by 86400 is days\nhours=$((${up}/3600%24)) # seconds divided by 3600 mod 24 is hours\nmins=$((${up}/60%60)) # seconds divided by 60 mod 60 is mins\ncolor-echo \"Uptime\" $days'd '$hours'h '$mins'm'\n}\n\nprint-shell() {\ncolor-echo 'Shell' $SHELL\n}\n\nprint-cpu() {\narm=$(grep ARM /proc/cpuinfo) # ARM procinfo uses different format\nif [[ \"$arm\" != \"\" ]]; then\n\tcpu=$(grep -m1 -i 'Processor' /proc/cpuinfo)\nelse\n\tcpu=$(grep -m1 -i 'model name' /proc/cpuinfo)\nfi\ncolor-echo 'CPU' \"${cpu#*: }\" # everything after colon is processor name\n}\n\nprint-gpu() {\ngpu=$(lspci | grep VGA | awk -F ': ' '{print $2}' | sed 's/(rev ..)//g')\ncolor-echo 'GPU' \"$gpu\"\n}\n\nprint-packages() {\npackages=$(pacman -Qs | grep local | wc -l)\ncolor-echo 'Packages' \"$packages\"\n}\n\nprint-disk() {\n# field 2 on line 2 is total, field 3 on line 2 is used\ndisk=$(df -h /home/ | awk 'NR==2 {total=$2; used=$3; print used\" / \"total}')\ncolor-echo 'Disk' \"$disk\"\n}\n\nprint-mem() {\n# field 2 on line 2 is total, field 3 on line 2 is used (in new format)\n# field 2 on line 2 is total, field 3 on line 3 is used (in old format)\n\nif [[ $(free -h) =~ \"buffers\" ]]; then # using old format\n\tmem=$(free -h | awk 'NR==2 {total=$2} NR==3 {used=$3; print used\" / \"total}')\nelse # using new format\n\tmem=$(free -h | awk 'NR==2 {total=$2} NR==2 {used=$3; print used\" / \"total}')\nfi\ncolor-echo 'Memory' \"$mem\"\n}\n\nprint-wm() {\nfor wm in ${wms[@]}; do # pgrep through wmname array\n\tpid=$(pgrep -x -u $USER $wm) # if found, this wmname has running process\n\tif [[ \"$pid\" ]]; then\n\t\tcolor-echo 'WM' $wm\n\t\tbreak\n\tfi\ndone\n}\n\nprint-de() {\nif [[ $(pgrep -x -u $USER lxsession) ]]; then # if lxsession is running, assume LXDE\n\tcolor-echo 'DE' 'LXDE'\nelif [ $(pgrep -x -u $USER xfce4-session) ]; then # if xfce4-session is running, assume Xfce\n\tcolor-echo 'DE' 'Xfce'\nfi\n}\n\nprint-distro() {\n[[ -e /etc/os-release ]] && source /etc/os-release\nif [[ -n \"$PRETTY_NAME\" ]]; then\n\tcolor-echo 'OS' \"$PRETTY_NAME\"\nelse\n\tcolor-echo 'OS' \"not found\"\nfi\n}\n\nprint-colors() {\nNAMES=('█ black' '█ red' '█ green' '█ yellow' '█ blue' '█ magenta' '█ cyan' '█ white')\nfor f in {0..7}; do\n\techo -en \"\\033[m\\033[$(($f+30))m ${NAMES[$f]}\" # normal colors\ndone\necho\nfor f in {0..7}; do\n\techo -en \"\\033[m\\033[1;$(($f+30))m ${NAMES[$f]}\" # bold colors\ndone\necho -e \"$rst\\n\"\n}\n\nif [[ $1 = '-v' ]]; then # print version information and exit\n\techo $(basename \"$0\") / version: $VERSION / wm count: ${#wms[*]}\n\texit\nfi\n\n#echo -e \"\\n $prp$USER@$HOSTNAME$rst\\n\"\necho\necho -en \"\\033[35;1m ,. ,. |\\033[0m\" && print-distro\necho -en \"\\033[35;1m || || |\\033[0m\" && print-uptime\necho -en \"\\033[35;1m ,''--''. |\\033[0m\" && print-shell\necho -en \"\\033[35;1m : (.)(.) : |\\033[0m\" && print-wm\necho -en \"\\033[35;1m ,' \\`. |\\033[0m\" && print-packages\n#echo -en \"\\033[35;1m : : |\\033[0m\" && print-kernel\necho -en \"\\033[35;1m : : |\\033[0m\" && print-cpu\necho -en \"\\033[35;1m -boo- \\`._m____m_,' |\\033[0m\" && print-gpu\necho\nprint-colors\n#\n#${redf} ▄██████▄${reset}\n#${redf}▄${whitef}█▀█${redf}██${whitef}█▀█${redf}██▄${reset}\n#${redf}█${whitef}▄▄█${redf}██${whitef}▄▄█${redf}███${reset}\n#${redf}████████████${reset}\n#${redf}██▀██▀▀██▀██${reset}\n#${redf}▀ ▀ ▀ ▀${reset}\n" }, { "alpha_fraction": 0.5759528875350952, "alphanum_fraction": 0.610753059387207, "avg_line_length": 19.808429718017578, "blob_id": "f08642544d3c2c2c0a759386755bc388dc8acc32", "content_id": "001206d088e063e091805854f7b8660e5c0b3c81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 5981, "license_type": "no_license", "max_line_length": 74, "num_lines": 261, "path": "/W541/polybar/config", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "; ██ ██\n; ██████ ░██ ██ ██░██\n; ░██░░░██ ██████ ░██ ░░██ ██ ░██ ██████ ██████\n; ░██ ░██ ██░░░░██ ░██ ░░███ ░██████ ░░░░░░██ ░░██░░█\n; ░██████ ░██ ░██ ░██ ░██ ░██░░░██ ███████ ░██ ░\n; ░██░░░ ░██ ░██ ░██ ██ ░██ ░██ ██░░░░██ ░██\n; ░██ ░░██████ ███ ██ ░██████ ░░████████░███\n; ░░ ░░░░░░ ░░░ ░░ ░░░░░ ░░░░░░░░ ░░░\n\n\n\n[colors]\nbg = #00000000\nfg = #F0D3C9\nbg-alt = #1A2026\nfg-alt = #F0D3C9\nsecondary = ${xrdb:color4}\nurgent = #FF79C6\n\n[fonts]\n\nfont-0 = \"VictorMono Nerd Font:pixelsize=13;2\"\n; For separator\nfont-1 = \"Hack Nerd Font:pixelsize=10;2\"\n\n\n;==============;\n; Bar Settings ;\n;==============;\n[bar/def]\nmonitor = ${env:MONITOR:}\nwidth = 100%\nheight = 36\nfixed-center = true\n\nbackground = #001A2026\nforeground = #F0D3C9 \n\noverline-size = 2\nunderline-size = 2\n\npadding-left = 0\npadding-right = 0\n\nmodule-margin-left = 0\nmodule-margin-right = 0\n\ninherit = fonts\n\nmodules-left = rofi bspwm left\nmodules-center = mpd\nmodules-right = right pkg volume xbacklight network battery date powermenu\n\n\n\nwm-restack = bspwm\n\nscroll-up = bspwm-desknext\nscroll-down = bspwm-deskprev\n\ncursor-click = pointer\ncursor-scroll = ns-resize\n\n; show, hide polybar \n; polybar-msg cmd hide/show\nenable-ipc = false\n\n;===========;\n; Separator ;\n;===========;\n[module/left]\ntype = custom/text\ncontent-background = ${colors.bg}\ncontent-foreground = ${colors.bg-alt}\ncontent = \"%{T2}█▓▒░%{T-}\"\n\n[module/right]\ntype = custom/text\ncontent-background = ${colors.bg\ncontent-foreground = ${colors.bg-alt}\ncontent = \"%{T2}░▒▓█%{T-}\"\n\n;==================;\n; BSPWM Workspaces ;\n;==================;\n[module/bspwm]\ntype = internal/bspwm\n\npin-workspaces = true\ninline-mode = false\nenable-click = true\nenable-scroll = false\nreverse-scroll = false\nfuzzy-match = true\n\nformat = <label-state><label-mode>\n\nlabel-focused = %name%\n\nlabel-focused-foreground = #ffffff\nlabel-focused-background = #1A2026\n\nlabel-focused-overline = #FB3696\nlabel-focused-padding = 1\n\nlabel-occupied = %name%\nlabel-occupied-padding = 1\nlabel-occupied-background = #1A2026\nlabel-occupied-foreground = #94CF95 \n\nlabel-urgent = %name%\nlabel-urgent-padding = 1\nlabel-urgent-background = #FB3696\nlabel-urgent-foreground = #ffffff\n\nlabel-empty = %name%\nlabel-empty-padding = 1\nlabel-empty-background = #1A2026\nlabel-empty-foreground = #777777\n\n\n[module/mpd]\ntype = custom/script\ninterval = 1\nformat-foreground = ${colors.fg}\nexec = ~/.config/polybar/mpd\n\n;===========;\n; Backlight ;\n;===========;\n[module/xbacklight]\ntype = internal/xbacklight\nformat = <label>\nlabel = %{F#F692B2}%{F-} %percentage%%\n\nformat-background = ${colors.bg-alt}\nformat-padding = 1\n\n;=========================;\n; Wireless Network / WiFi ;\n;=========================;\n[module/network]\ntype = internal/network\ninterface = wlp3s0\ninterval = 1\n\nformat-connected-padding = 1\nformat-disconnected-padding = 1\n\nformat-connected = <label-connected>\nformat-disconnected = <label-disconnected>\n\nformat-connected-background = ${colors.bg-alt}\nformat-disconnected-background = ${colors.bg-alt}\n\nlabel-connected = %{F#6EC1D6}直 %{F-}%essid%\nlabel-disconnected = %{F#6EC1D6}睊 %{F-}disconnected\n\n\n;==============;\n; Date + Clock ;\n;==============;\n[module/date]\ntype = internal/date\ninterval = 1\nlabel = %time%\n\ntime = %{F#7FE4D2} %{F-} %H:%M\ntime-alt = %{F#7FE4D2} %{F-} %d-%m-%Y\n\nformat-padding = 1\nformat-background = ${colors.bg-alt}\n\n;========;\n; Volume ;\n;========;\n[module/volume]\ntype = internal/alsa\nformat-volume = <ramp-volume> <label-volume>\nformat-muted = <label-muted>\nramp-volume-foreground = #7FE4D2\nformat-volume-padding = 1\nformat-muted-padding = 1\nformat-volume-background = ${colors.bg-alt}\nformat-muted-background = #6998B3\n\nformat-muted-prefix = \"%{F#9DDEAF}婢 %{F-} \"\nramp-volume-0 = \" \"\nramp-volume-1 = \"墳 \"\nramp-volume-2 = \" \"\n\n;=========;\n; Battery ;\n;=========;\n[module/battery]\ntype = internal/battery\npoll-interval = 1\nlabel-padding = 30\n\n; Use $ ls -1 /sys/class/power_supply/\nbattery = BAT0\nadapter = AC\nfull-at = 98\nbar-capacity-width = 10\n\nformat-charging = %{F#AF9DDE}<animation-charging>%{F-} <label-charging>\nformat-discharging = %{F#AF9DDE}<ramp-capacity>%{F-} <label-discharging>\nformat-full = %{F#B16286}<ramp-capacity>%{F-} <label-full>\n\nformat-full-padding = 1\nformat-charging-padding = 1\nformat-discharging-padding = 1\n\nformat-charging-background = ${colors.bg-alt}\nformat-full-background = ${colors.bg-alt}\nformat-discharging-background = ${colors.bg-alt}\n\nramp-capacity-0 = \"%{F#de373d}\"\nramp-capacity-1 = \"%{F#de373d}\"\nramp-capacity-2 = \"\"\nramp-capacity-3 = \"\"\nramp-capacity-4 = \"\"\nramp-capacity-5 = \"\"\nramp-capacity-6 = \"\"\nramp-capacity-7 = \"\"\nramp-capacity-8 = \"\"\nramp-capacity-9 = \"\"\n\nanimation-charging-0 = \" \"\nanimation-charging-1 = \" \"\nanimation-charging-2 = \" \"\nanimation-charging-3 = \" \"\nanimation-charging-4 = \" \"\nanimation-charging-5 = \" \"\nanimation-charging-6 = \" \"\nanimation-charging-framerate = 750\n\n\n;============;\n; Power Menu ;\n;============;\n[module/powermenu]\ntype = custom/script\nexec = echo \"\"\nformat-foreground = #CD84C8 \nformat-background = ${colors.bg-alt}\nclick-left = ~/.config/polybar/pmenu.sh\nformat-padding = 1\n;exec ~/.config/polybar/pmenu.sh\n\n\n;=====;\n[module/pkg]\ntype = custom/script\nformat-foreground = #FB6396\nexec = ~/.config/polybar/pkg\nclick-left = ~/.local/bin/update\nformat-background = #1A2026\nformat-padding = 1\n\n; vim:ft=dosini\n" }, { "alpha_fraction": 0.46905043721199036, "alphanum_fraction": 0.6186540722846985, "avg_line_length": 12.983490943908691, "blob_id": "5ab453bba33ba32257d271c116e2fb244e8c1c07", "content_id": "642bf30fc827f767759b2d9f6868e0c48a106ede", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 5929, "license_type": "no_license", "max_line_length": 39, "num_lines": 424, "path": "/W541/termite/config", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "# \n# # # # \n# ### ### ### ### ### ### \n# # ## # ### # # ## \n# ## ### # # # ## ## ### \n#\n\n### MISC ###\n\n[options]\nallow_bold = true\naudible_bell = false\nbold_is_bright = true\nbrowser = firefox\nclickable_url = true\n\ncursor_shape = underline\ncursor_blink = on \ncell_height_scale = 1.0\ncell_width_scale = 1.0\ndynamic_title = true\n\nfullscreen = true\nfilter_unmatched_urls = true\nhighlight = #30343e\nhyperlinks = false\nicon_name = terminal\n\nmouse_autohide = true\nscroll_on_keystroke = true\nurgent_on_bell = true\nscrollback_lines = 10000\nscroll_on_output = false\n\nsearch_wrap = true\nsize_hints = false\nscrollbar = off\nvisual_bell = true\n\n\n#--- APPEARANCE --- \n\nfont = Cousine Nerd Font Bold 15\n\n#[colors]\n# bliss\n# special\n#foreground = #f0d3c9\n#foreground_bold = #f0d3c9\n#cursor = #f0d3c9\n#background = #1C1B1D\n# black\n#color0 = #262727\n#color8 = #393b3b\n# red\n#color1 = #de9dac\n#color9 = #deaf9d\n# green\n#color2 = #9ddeaf\n#color10 = #9dded0\n# yellow\n#color3 = #ded09d\n#color11 = #ded09d\n# blue\n#color4 = #9dacde\n#color12 = #af9dde\n# magenta\n#color5 = #af9dde\n#color13 = #d09dde\n# cyan\n#color6 = #9dccde\n#color14 = #9dccde\n# white\n#color7 = #434545\n#color15 = #f0d3c9\n\n\n\n\n[colors]\n# E L L Y\n# special\nforeground = #c0c7ca\nforeground_bold = #c0c7ca\ncursor = #c0c7ca\nbackground = #111a1f\n\n# black\ncolor0 = #111a1f\ncolor8 = #868b8d\n\n# red\ncolor1 = #8d7856\ncolor9 = #8d7856\n\n# green\ncolor2 = #798362\ncolor10 = #798362\n\n# yellow\ncolor3 = #9b9257\ncolor11 = #9b9257\n\n# blue\ncolor4 = #63768a\ncolor12 = #63768a\n\n# magenta\ncolor5 = #738c9c\ncolor13 = #738c9c\n\n# cyan\ncolor6 = #6998b3\ncolor14 = #6998b3\n\n# white\ncolor7 = #c0c7ca\ncolor15 = #c0c7ca\n\n\n\n\n#[colors]\n# dark\n# special\n#foreground = #f9f9f9\n#foreground_bold = #f9f9f9\n#cursor = #f9f9f9\n#background = #373e4d\n\n# black\n#color0 = #434c5e\n#color8 = #4c566a\n\n# red\n#color1 = #fa5aa4\n#color9 = #fa74b2\n\n# green\n#color2 = #2be491\n#color10 = #44eb9f\n\n# yellow\n#color3 = #fa946e\n#color11 = #faa687\n\n# blue\n#color4 = #63c5ea\n#color12 = #7acbea\n\n# magenta\n#color5 = #cf8ef4\n#color13 = #d8a6f4\n\n# cyan\n#color6 = #89ccf7\n#color14 = #a1d5f7\n\n# white\n#color7 = #f9f9f9\n#color15 = #ffffff\n\n\n\n\n#[colors]\n# amarena wip\n# special\n#foreground = #ffffff\n#foreground_bold = #ffffff\n#cursor = #ffffff\n#background = #1a2026\n\n# black\n#color0 = #242d35\n#color8 = #526170\n\n# red\n#color1 = #fb6396\n#color9 = #f92d72\n\n# green\n#color2 = #94cf95\n#color10 = #6ccb6e\n\n# yellow\n#color3 = #f692b2\n#color11 = #f26190\n\n# blue\n#color4 = #6ec1d6\n#color12 = #4cb9d6\n\n# magenta\n#color5 = #cd84c8\n#color13 = #c269bc\n\n# cyan\n#color6 = #7fe4d2\n#color14 = #58d6bf\n\n# white\n#color7 = #ffffff\n#color15 = #f4f5f2\n\n\n\n#[colors]\n# JWR\n# special\n#foreground = #ffffff\n#foreground_bold = #ffffff\n#cursor = #ffffff\n#background = #1a2026\n\n# black\n#color0 = #333333\n#color8 = #3d3d3d\n\n# red\n#color1 = #8c4665\n#color9 = #bf4d80\n\n# green\n#color2 = #287373\n#color10 = #53a6a6\n\n# yellow\n#color3 = #7c7c99\n#color11 = #9e9ecb\n\n# blue\n#color4 = #395573\n#color12 = #477ab3\n\n# magenta\n#color5 = #5e468c\n#color13 = #7e62b3\n\n# cyan\n#color6 = #31658c\n#color14 = #6096bf\n\n# white\n#color7 = #899ca1\n#color15 = #c0c0c0\n\n\n#[colors]\n# Mountaineer\n# special\n#foreground = #f0f0f0\n#foreground_bold = #f0f0f0\n#cursor = #f0f0f0\n#background = #1a2026\n\n# black\n#color0 = #050505\n#color8 = #191919\n# red\n#color1 = #ac8a8c\n#color9 = #c49ea0\n# green\n#color2 = #8aac8b\n#color10 = #9ec49f\n# yellow\n#color3 = #aca98a\n#color11 = #c4c19e\n# blue\n#color4 = #8f8aac\n#color12 = #a39ec4\n# magenta\n#color5 = #ac8aac\n#color13 = #c49ec4\n# cyan\n#color6 = #8aabac\n#color14 = #9ec3c4\n# white\n#color7 = #f0f0f0\n#color15 = #fafafa\n\n\n\n#[colors]\n# DARKMACHINE\n# special\n#foreground = #c0c0c0\n#foreground_bold = #c0c0c0\n#cursor = #c0c0c0\n#background = #121212\n\n# black\n#color0 = #080808\n#color8 = #36393f\n# red\n#color1 = #515978\n#color9 = #778099\n# green\n#color2 = #3ea28d\n#color10 = #71c4ba\n# yellow\n#color3 = #4dc5ce\n#color11 = #5e767f\n# blue\n#color4 = #6ea2a5\n#color12 = #6abdc1\n# magenta\n#color5 = #a8a8a8\n#color13 = #4e4d80\n# cyan\n#color6 = #558188\n#color14 = #4fc8ce\n# white\n#color7 = #c0c0c0\n#color15 = #a6a8aa\n\n\n\n#[colors]\n# frost\n# special\n#foreground = #9bbbc6\n#foreground_bold = #9bbbc6\n#cursor = #9bbbc6\n#background = #1c1c23\n\n# black\n#color0 = #323246\n#color8 = #323246\n# red\n#color1 = #5a7882\n#color9 = #5a7882\n# green\n#color2 = #8c8ca0\n#color10 = #8c8ca0\n# yellow\n#color3 = #1e828c\n#color11 = #1e828c\n# blue\n#color4 = #3c788c\n#color12 = #3c788c\n# magenta\n#color5 = #6ea0b4\n#color13 = #6ea0b4\n# cyan\n#color6 = #6e8ca0\n##color14 = #6e8ca0\n# white\n#color7 = #96bec8\n#color15 = #96bec8\n\n\n#[colors]\n# CHERRY\n# special\n#foreground = #edeef0\n#foreground_bold = #edeef0\n#cursor = #edeef0\n#background = #102029\n# black\n#color0 = #102029\n#color8 = #0e374b\n# red\n#color1 = #c9647e\n#color9 = #d87e8f\n# green\n#color2 = #7caba3\n#color10 = #add4cf\n# yellow\n#color3 = #c7c8b7\n#color11 = #ebdecd\n# blue\n#color4 = #71aac5\n#color12 = #a7cbe3\n# magenta\n#color5 = #f4adb1\n#color13 = #f8cbce\n# cyan\n#color6 = #7cbbc0\n#color14 = #a5d3d9\n# white\n#color7 = #d9dbe3\n#color15 = #edeef0\n\n\n\n\n#[colors]\n# I C E B E R G\n# special\n#foreground = #c6c8d1\n#foreground_bold = #c6c8d1\n#cursor = #c6c8d1\n#background = #161821\n#background =rgba(22, 24, 33, 0.7)\n# black\n#color0 = #22262e\n#color8 = #6b7089\n# red\n#color1 = #e27878\n#color9 = #e98989\n# green\n#color2 = #b4be82\n#color10 = #c0ca8e\n# yellow\n#color3 = #e2a478\n#color11 = #e9b189\n# blue\n#color4 = #84a0c6\n#color12 = #91acd1\n# magenta\n#color5 = #a093c7\n#color13 = #ada0d3\n# cyan\n#color6 = #89b8c2\n#color14 = #95c4ce\n# white\n#color7 = #c6c8d1\n#color15 = #d2d4de\n\n\n\n\n# vim: ft=sh\n" }, { "alpha_fraction": 0.46367645263671875, "alphanum_fraction": 0.6149128079414368, "avg_line_length": 13.613445281982422, "blob_id": "4df5dd04030bff16c691ecaf9a20807cda0fbc43", "content_id": "d59f632e258e681d26a5ec2f6e6423232f953387", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 5217, "license_type": "no_license", "max_line_length": 49, "num_lines": 357, "path": "/E480/termite/config", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "# \n# # # # \n# ### ### ### ### ### ### \n# # ## # ### # # ## \n# ## ### # # # ## ## ### \n#\n\n### MISC ###\n\n[options]\nallow_bold = true\nclickable_url = true\n\nmouse_autohide = true \nscroll_on_keystroke = true\nurgent_on_bell = true\nscrollback_lines = 10000\ncursor_shape = underline\nbrowser = Firefox\n\n#--- APPEARANCE --- \nhighlight = #2f2f2f\n\n\n\nfont = SFMono Nerd Font Regular 10\n\n\n#[colors]\n# mg\n# special\n#foreground = #f0f0f0\n#foreground_bold = #f0f0f0\n#cursor = #f0f0f0\n#background = #1c1b1d\n# black\n#color0 = #303030\n#color8 = #3D3D3D\n# red\n#color1 = #D5BBBC\n#color9 = #DCC7C8\n# green\n#color2 = #BBD5BE\n#color10 = #C7DCCA\n# yellow\n#color3 = #D5D5BB\n#color11 = #C8C7DC\n# blue\n#color4 = #BCBBD5\n#color12 = #C8C7DB\n# magenta\n#color5 = #D5BBD3\n#color13 = #DCC7DB\n# cyan\n#color6 = #BBD5B4\n#color14 = #C7DCDC\n# white\n#color7 = #E7E7E7\n#color15 = #F0F0F0\n\n\n\n\n#[colors]\n# sd\n# special\n#foreground = #ffffff\n#foreground_bold = #ffffff\n#cursor = #ffffff\n#background = #262729\n# black\n#color0 = #686868\n#color8 = #454545\n# red\n#color1 = #eb7685\n#color9 = #eb465c\n# green\n#color2 = #46aab8\n#color10 = #148e9e\n# yellow\n#color3 = #e6bea3\n#color11 = #eb9c67\n# blue\n#color4 = #a3bee6\n#color12 = #4770ad\n# magenta\n#color5 = #a3a3e6\n#color13 = #6c6cb3\n# cyan\n#color6 = #a3cae6\n#color14 = #6c96b3\n# white\n#color7 = #d4d5d9\n#color15 = #b3b4b8\n\n\n\n[colors]\n# bliss\n# special\nforeground = #f0d3c9\nforeground_bold = #f0d3c9\ncursor = #f0d3c9\nbackground = #1c1b1d\n# black\ncolor0 = #262727\ncolor8 = #393b3b\n# red\ncolor1 = #de9dac\ncolor9 = #deaf9d\n# green\ncolor2 = #9ddeaf\ncolor10 = #9dded0\n# yellow\ncolor3 = #ded09d\ncolor11 = #ded09d\n# blue\ncolor4 = #9dacde\ncolor12 = #af9dde\n# magenta\ncolor5 = #af9dde\ncolor13 = #d09dde\n# cyan\ncolor6 = #9dccde\ncolor14 = #9dccde\n# white\ncolor7 = #434545\ncolor15 = #f0d3c9\n\n\n\n\n#[colors]\n# PINK delight\n# special\n#foreground = #f5f5f5\n#foreground_bold = #f5f5f5\n#cursor = #f5f5f5\n#background = #28243a\n\n# black\n#color0 = #28243a\n#color8 = #5e5e69\n\n# red\n#color1 = #df7191\n#color9 = #e17291\n\n# green\n#color2 = #81a2be\n#color10 = #81a2be\n\n# yellow\n#color3 = #ad5770\n#color11 = #ad5770\n\n# blue\n#color4 = #81a2be\n#color12 = #81a2be\n\n# magenta\n#color5 = #e17291\n#color13 = #e17291\n\n# cyan\n#color6 = #8abeb7\n#color14 = #8abeb7\n\n# white\n#color7 = #5e5e69\n#color15 = #f5f5f5\n\n\n\n#[colors]\n# mountaineer\n# special\n#foreground = #f0f0f0\n#foreground_bold = #f0f0f0\n#cursor = #f0f0f0\n#background = #050505\n# black\n#color0 = #050505\n#color8 = #4D4D4D\n# red\n#color1 = #AC8A8C\n#color9 = #C49EA0\n# green\n#color2 = #8AAC8B\n#color10 = #9EC49F\n# yellow\n#color3 = #ACA98A\n#color11 = #C4C19E\n# blue\n#color4 = #8F8AAC\n#color12 = #A19FB1\n# magenta\n#color5 = #AC8AAC\n#color13 = #B19DAB\n# cyan\n#color6 = #8AABAC\n#color14 = #C49EC4\n# white\n#color7 = #f0f0f0\n#color15 = #fafafa\n\n\n\n#[colors]\n# Base16 Pasque\n# Scheme: Gabriel Fontes (https://github.com/Misterio77)\n\n#foreground = #DEDCDF\n#foreground_bold = #DEDCDF\n#cursor = #DEDCDF\n#background = #271C3A\n\n# 16 color space\n#color0 = #271C3A\n#color1 = #A92258\n#color2 = #C6914B\n#color3 = #804ead\n#color4 = #8E7DC6\n#color5 = #953B9D\n#color6 = #7263AA\n#color7 = #DEDCDF\n#color8 = #5D5766\n#color9 = #A92258\n#color10 = #C6914B\n#color11 = #804ead\n#color12 = #8E7DC6\n#color13 = #953B9D\n#color14 = #7263AA\n#color15 = #BBAADD\n\n# 256 color space\n#color16 = #918889\n#color17 = #59325C\n#color18 = #100323\n#color19 = #3E2D5C\n#color20 = #BEBCBF\n#color21 = #EDEAEF\n\n\n\n#[colors]\n# frost\n# special\n#foreground = #9bbbc6\n#foreground_bold = #9bbbc6\n#cursor = #9bbbc6\n#background = #1c1c23\n\n# black\n#color0 = #323246\n#color8 = #323246\n\n# red\n#color1 = #5a7882\n#color9 = #5a7882\n\n# green\n#color2 = #8c8ca0\n#color10 = #8c8ca0\n\n# yellow\n#color3 = #1e828c\n#color11 = #1e828c\n\n# blue\n##color4 = #3c788c\n#color12 = #3c788c\n\n# magenta\n#color5 = #6ea0b4\n#color13 = #6ea0b4\n\n# cyan\n#color6 = #6e8ca0\n#color14 = #6e8ca0\n\n# white\n#color7 = #96bec8\n#color15 = #96bec8\n\n\n#[colors]\n# CHERRY\n# special\n#foreground = #edeef0\n#foreground_bold = #edeef0\n#cursor = #edeef0\n#background = #102029\n# black\n#color0 = #102029\n#color8 = #0e374b\n# red\n#color1 = #c9647e\n#color9 = #d87e8f\n# green\n#color2 = #7caba3\n#color10 = #add4cf\n# yellow\n#color3 = #c7c8b7\n#color11 = #ebdecd\n# blue\n#color4 = #71aac5\n#color12 = #a7cbe3\n# magenta\n#color5 = #f4adb1\n#color13 = #f8cbce\n# cyan\n#color6 = #7cbbc0\n#color14 = #a5d3d9\n# white\n#color7 = #d9dbe3\n#color15 = #edeef0\n\n\n\n\n#[colors]\n# I C E B E R G\n# special\n#foreground = #c6c8d1\n#foreground_bold = #c6c8d1\n#cursor = #c6c8d1\n#background = #161821\n#background =rgba(22, 24, 33, 0.7)\n# black\n#color0 = #22262e\n#color8 = #6b7089\n# red\n#color1 = #e27878\n#color9 = #e98989\n# green\n#color2 = #b4be82\n#color10 = #c0ca8e\n# yellow\n#color3 = #e2a478\n#color11 = #e9b189\n# blue\n#color4 = #84a0c6\n#color12 = #91acd1\n# magenta\n#color5 = #a093c7\n#color13 = #ada0d3\n# cyan\n#color6 = #89b8c2\n#color14 = #95c4ce\n# white\n#color7 = #c6c8d1\n#color15 = #d2d4de\n\n\n\n# vim: ft=sh\n" }, { "alpha_fraction": 0.54313725233078, "alphanum_fraction": 0.5568627715110779, "avg_line_length": 17.88888931274414, "blob_id": "f21cfcd442dee723c9409c893bd52185f2c205b8", "content_id": "c17b647614d8ae9eb1cf4b7cf3802d0d7983f151", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 510, "license_type": "no_license", "max_line_length": 118, "num_lines": 27, "path": "/scripts-misc/scrot-screencast script", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n# Screen record or screen shot\n\nreadonly pb=\"https://ptpb.pw/?u=1\"\n\npicture() {\n maim -d 1 --format png /dev/stdout | curl -sF c=@- \"$pb\" | sed \"s/$/.png/\" | xcmenu -ic\n}\n\nvideo() {\n tmp=$(mktemp --suffix=.mkv)\n ffmpeg -y -video_size \"$(wattr w \"$(lsw -r)\")x$(wattr h \"$(lsw -r)\")\" -framerate 25 -f x11grab -i \"$DISPLAY\" \"$tmp\"\n wait\n curl -sF c=@\"$tmp\" \"$pb\" | xcmenu -ic\n}\n\n## Main\n\n\ncase \"$1\" in\n snap)\n picture ;;\n vid)\n video ;; \n stop)\n pkill -SIGINT ffmpeg ;;\nesac\n" }, { "alpha_fraction": 0.48493149876594543, "alphanum_fraction": 0.5397260189056396, "avg_line_length": 25, "blob_id": "facd4865468efa46b97bc8e91ed0d2d6e27dc035", "content_id": "14a9b1dfe44d85ad7d61f86ee041ddea4afb612a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 367, "license_type": "no_license", "max_line_length": 56, "num_lines": 14, "path": "/W541/polybar/display_updates.sh", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# File : .config/polybar/display_updates.sh\n# Author : Morgareth <[email protected]>\n# Date : 10.08.2017\n# Last Modified Date: 10.08.2017\n# Last Modified By : Morgareth <[email protected]>\npac=$(checkupdates | wc -l)\naur=$(cower -u | wc -l)\n\ncheck=$((pac + aur))\nif [[ \"$check\" != \"0\" ]]\nthen\n echo \"$pac %{F#5b5b5b}%{F-} $aur\"\nfi\n\n" }, { "alpha_fraction": 0.43171805143356323, "alphanum_fraction": 0.4889867901802063, "avg_line_length": 55.75, "blob_id": "91f12a984da8fb46e6194e90a7ee8457e6ef72d3", "content_id": "4eac30a7c4b47c1ce64bdf9d4716d14a37cbd759", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 245, "license_type": "no_license", "max_line_length": 123, "num_lines": 4, "path": "/E480/polybar/mpd", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "#!/bin/sh\nstatus=\"$(mpc status 2>/dev/null | grep -oP '(pause|playing)')\"\n[ \"$status\" = \"playing\" ] &&\n\techo \" %{F#1C1B1D}%{T2}░▒▓█%{T-}%{F-}%{B#1C1B1D}%{F#9DCCDE}  %{F-} $(mpc current) %{B-}%{F#1c1b1d}%{T2}█▓▒░%{T-}%{F-} \"\n" }, { "alpha_fraction": 0.6807252764701843, "alphanum_fraction": 0.6988568902015686, "avg_line_length": 24.626262664794922, "blob_id": "0aa5093af674af141a4d3c8adc1afc9b4a8bfe93", "content_id": "10323ccb4f98483557ba45b06f96a1d3466a120f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2537, "license_type": "no_license", "max_line_length": 87, "num_lines": 99, "path": "/W541/bspwm/bspwmrc", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "#! /bin/sh\n#\n# # \n# ### ## ### # # ### ### ### \n# # # # # # ### ### # # \n# ### ## ### ### # # # ###\n# #\n#\n\n# Autostart Some Shit\nsxhkd &\npicom &\ndunst &\n$HOME/.config/polybar/launch.sh & \n\n#$HOME/.config/bspwm/scripts/borderless &\n\n# Wallpaper\n#hsetroot -solid '#4d5a60' &\nfeh --bg-tile Bilder/wp/escher.png\n\n\n# bitmap fonts\nxset +fp ~/.local/share/fonts &\nxset fp rehash &\nxset fp+ /usr/share/fonts/bitmap &\n\nbspc monitor -d I II III IV V VI VII VIII IX X\n\n#bspc monitor -d I \n#bspc monitor DP2-1 II III IV \n#bspc monitor DP2-2 V VI VII\n#bspc monitor DVI VIII IX X\n\n# appearance \nbspc config border_width 8\nbspc config window_gap 32 \n\n#bspc config window_gap $gap;\nbspc config top_padding $(($PANEL_HEIGHT-gap)) 30\n#bspc config left_padding -$gap\n#bspc config right_padding -$gap\n#bspc config bottom_padding -$gap\n\n# Set the border colors - without pywal\n# Dracula\n#bspc config normal_border_color \"#282a36\"\n#bspc config active_border_color \"#6272a4\"\n#bspc config focused_border_color \"#BFBFBF\"\n#bspc config presel_feedback_color \"#6272a4\"\n\n# ICEBERG\nbspc config normal_border_color \"#1c1c1c\"\nbspc config active_border_color \"#7CABA3\"\nbspc config focused_border_color \"#777777\"\nbspc config presel_feedback_color \"#3a3a3a\"\n\nbspc config single_monocle true\nbspc config borderless_monocle true\nbspc config gapless_monocle true\nbspc config focus_follows_pointer true\nbspc config pointer_follows_focus false\nbspc config center_pseudo_tiled true\nbspc config ignore_ewmh_focus true\n\nbspc config split_ratio 0.50\n\n# Automatic Splitting Settings\nbspc config automatic_scheme\tspiral\nbspc config initial_polarity\tsecond_child\n\n\n# Some personal rules\nbspc rule --add firefox desktop=I follow=off \nbspc rule --add qutebrowser desktop=I follow=off\nbspc rule --add Opera desktop=I follow=off\nbspc rule --add Google-chrome desktop=I follow=off\nbspc rule --add TelegramDesktop desktop=II follow=off\nbspc rule --add Thunar desktop=III follow=off \nbspc rule --add Zathura state=tiled\nbspc rule --add Transmission-gtk desktop=VIII focus=off follow=on\nbspc rule --add feh state=floating focus=on\nbspc rule --add mpv state=floating\n\n\nfunction reset_color_if_not_VIM {\n\t#autocmd events in ~/.vimrc will handle case where window is VIM\n\tnode_id=$(echo $1 | grep -oE '[^ ]+$')\n\tnode_name=$(xtitle $node_id)\n\tif [[ $node_name != *\"VIM\"* ]]; then\n\t\t$HOME/.vim/bspwm_border_color/reset\n\tfi\n}\n\nbspc subscribe node_focus | while read -r line; do reset_color_if_not_VIM \"$line\"; done\n\n\n\n# vim: ft=sh\n" }, { "alpha_fraction": 0.6747515201568604, "alphanum_fraction": 0.6930417418479919, "avg_line_length": 23.647058486938477, "blob_id": "1cc9efcfe62103054e0f7a78d584f349c5f1f598", "content_id": "349c7625945794e3fdc7f8d580bddd2d48969256", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2515, "license_type": "no_license", "max_line_length": 87, "num_lines": 102, "path": "/E480/bspwm/bspwmrc", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "#! /bin/sh\n#\n# # \n# ### ## ### # # ### ### ### \n# # # # # # ### ### # # \n# ### ## ### ### # # # ###\n# #\n#\n\n# Autostart Some Shit\npgrep -x sxhkd > /dev/null || sxhkd &\npicom &\ndunst &\n$HOME/.config/polybar/launch.sh\n\n\n# Wallpaper\n#hsetroot -solid '#282828' &\n#feh --bg-fill Bilder/wp/stones.png\nnitrogen --restore &\n#bwall &\n\n\n# bitmap fonts\nxset +fp ~/.local/share/fonts &\nxset fp rehash &\nxset fp+ /usr/share/fonts/bitmap &\n\nbspc monitor -d I II III IV V VI VII VIII IX X\n\n# appearance \nbspc config border_width 4\nbspc config window_gap 8\n\n#bspc config window_gap $gap;\nbspc config top_padding $(($PANEL_HEIGHT-gap)) 30\n#bspc config left_padding -$gap\n#bspc config right_padding -$gap\n#bspc config bottom_padding -$gap\n\n# Set the border colors - without pywal\n# Dracula\nbspc config normal_border_color \"#1c1b1d\"\nbspc config active_border_color \"#6272a4\"\nbspc config focused_border_color \"#DEAF9D\"\nbspc config presel_feedback_color \"#6272a4\"\n\n# ICEBERG\n#bspc config normal_border_color \"#161821\"\n#bspc config active_border_color \"#7CABA3\"\n#bspc config focused_border_color \"#84A0C6\"\n#bspc config presel_feedback_color \"#101113\"\n\nbspc config single_monocle true\nbspc config borderless_monocle true\nbspc config gapless_monocle true\nbspc config focus_follows_pointer true\nbspc config pointer_follows_focus false\nbspc config center_pseudo_tiled true\nbspc config ignore_ewmh_focus true\n\nbspc config split_ratio 0.50\n\n# Automatic Splitting Settings\nbspc config automatic_scheme\tspiral\nbspc config initial_polarity\tsecond_child\n\n\n\n\n# Some personal rules\nbspc rule --add firefox desktop=I follow=off \nbspc rule --add qutebrowser desktop=I follow=off\nbspc rule --add Opera desktop=I follow=off\nbspc rule --add brave desktop=I follow=off\nbspc rule --add TelegramDesktop desktop=II follow=off\nbspc rule --add Thunar desktop=III follow=off \nbspc rule --add Zathura state=tiled\nbspc rule --add Transmission-gtk desktop=VIII focus=off follow=off\nbspc rule --add feh state=floating focus=on\nbspc rule --add mpv state=floating\n\n\n\nbspc config external_rules_command \"$(which external_rules)\"\n\nfunction reset_color_if_not_VIM {\n\t#autocmd events in ~/.vimrc will handle case where window is VIM\n\tnode_id=$(echo $1 | grep -oE '[^ ]+$')\n\tnode_name=$(xtitle $node_id)\n\tif [[ $node_name != *\"VIM\"* ]]; then\n\t\t$HOME/.vim/bspwm_border_color/reset\n\tfi\n}\n\nbspc subscribe node_focus | while read -r line; do reset_color_if_not_VIM \"$line\"; done\n\n\n\n\n\n# vim: ft=sh\n\n" }, { "alpha_fraction": 0.6823529601097107, "alphanum_fraction": 0.6941176652908325, "avg_line_length": 27.33333396911621, "blob_id": "a6a19dbbef786d0fec6ec29fb95577a3599f6432", "content_id": "f1c2a9026fc9dbd4b12f9e6144b3d5afd5f2b1b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 170, "license_type": "no_license", "max_line_length": 49, "num_lines": 6, "path": "/W541/bspwm/scripts/borderless", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "#!/bin/sh\nwhile bspc subscribe -c 1 node_focus; do\nbw=\"$(bspc config border_width)\"\nbspc config border_width \"$bw\"\nbspc config -n focused border_width \"$((bw + 6))\"\ndone\n" }, { "alpha_fraction": 0.6551724076271057, "alphanum_fraction": 0.6620689630508423, "avg_line_length": 28, "blob_id": "cd3395ea94153919bfd10a90fd543a1aa73441f8", "content_id": "c2e339e70de127ee9705ec6bab2ed71dea5f0e15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 145, "license_type": "no_license", "max_line_length": 60, "num_lines": 5, "path": "/scripts-misc/floating", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "#! /bin/bash/env bash\n\nfor attr in $(herbstclient complete 1 attr tags.by-name); do\n herbstclient attr \"$attr.floating\" true\n done\n" }, { "alpha_fraction": 0.5893787145614624, "alphanum_fraction": 0.605692446231842, "avg_line_length": 27.397958755493164, "blob_id": "5b1f723703847e74cc0c61c42950269f7c15f50b", "content_id": "34594d20b05c5902fb9fc6dfe94e55cdd59af702", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2881, "license_type": "no_license", "max_line_length": 134, "num_lines": 98, "path": "/scripts-misc/preneo.sh", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "#!/bin/bash\r\n\r\nbold=$(tput bold)\r\n\r\n# Clears attributes\r\nclear=$(tput sgr0)\r\n\r\n# Default color\r\n# colors are now defined with a launch option \"-c\"\r\ncolor=$(tput setaf 1)\r\n\r\n## Custom Image\r\n\r\n# If usewall=1 then fetch will use a cropped version of your wallpaper as the img\r\nusewall=1\r\n\r\n# The default image to use if usewall=0\r\nimg=\"$HOME/Bilder/Arch.jpg\"\r\n\r\n# Image width/height/offset\r\nwidth=194\r\nheight=140\r\nyoffset=0\r\nxoffset=0\r\n\r\n# Padding to align text to the right\r\npad=\" \"\r\n\r\n## Other\r\n\r\n# Title\r\n# title can also be changed with -t\r\n# TO use the usual \"user@hostname\" change the line below to:\r\n# title=\"$(whoami)@$(hostname)\"\r\ntitle=\"Happy Tiling\"\r\n\r\n# Custom text to print at the bottom, configurable at launch with \"-e\"\r\ncustomtext=$(~/scripts/colorscripts/panes)\r\n\r\n# Set up args\r\nwhile getopts \":c:e:w:h:t:p:x:y:\" opt; do\r\n case $opt in\r\n c) color=$(tput setaf $OPTARG) ;;\r\n e) customtext=\"$OPTARG\" ;;\r\n w) width=\"$OPTARG\" ;;\r\n h) height=\"$OPTARG\" ;;\r\n t) title=\"$OPTARG\" ;;\r\n p) pad=\"$OPTARG\" ;;\r\n x) xoffset=\"$OPTARG\" ;;\r\n y) yoffset=\"$OPTARG\" ;;\r\n esac\r\ndone\r\n\r\n# Get image from wallpaper\r\n# Requires feh\r\nif [[ $usewall == 1 ]]; then\r\n wallpaper=$(cat .fehbg | awk '/feh/ {printf $3}' | sed -e \"s/'//g\")\r\n\r\n # Directory to store cropped wallpapers.\r\n walltempdir=\"$HOME/.wallpaper\"\r\n\r\n # Check if the directory exists\r\n if [ ! -d \"$walltempdir\" ]; then\r\n mkdir \"$walltempdir\" || echo \"Failed to create wallpaper dir\"; exit\r\n fi\r\n\r\n # Crop the wallpaper and save it to the wallpaperdir\r\n # By default it crops a 1080x1080 square in the center of the image.\r\n [[ -f \"$walltempdir/$(basename $wallpaper)\" ]] || convert -crop 1080x1080+480+0 \"$wallpaper\" \"$walltempdir/$(basename $wallpaper)\"\r\n\r\n # The final image\r\n img=\"$walltempdir/$(basename $wallpaper)\"\r\nfi\r\n\r\n# Underline title with length of title\r\nunderline=$(printf '%0.s-' $(seq 1 $(echo \"${title%?}\" | wc -m)))\r\n\r\n## Start printing info\r\n\r\n# Clear terminal before running\r\nclear\r\n\r\necho \"${pad}${bold}$title${clear}\"\r\necho \"${pad}$underline\"\r\necho \"${pad}${bold}${color}OS${clear}: $(cat /etc/*ease | awk '/^NAME=/' | cut -d '\"' -f2)\"\r\necho \"${pad}${bold}${color}Kernel${clear}: $(uname -r)\"\r\necho \"${pad}${bold}${color}Uptime${clear}: $(uptime -p)\"\r\necho \"${pad}${bold}${color}Packages${clear}: $(pacman -Q | wc -l)\"\r\necho \"${pad}${bold}${color}Shell${clear}: $SHELL\"\r\necho \"${pad}${bold}${color}Window Manager${clear}: bspwm\"\r\necho \"${pad}${bold}${color}Cpu${clear}: $(lscpu | grep name |awk '{print $5}')\"\r\necho \"${pad}${bold}${color}Ram${clear}: $(free -m | awk '/Mem:/ {printf $3 \"MB / \" $2 \"MB\"}')\"\r\necho \"${pad}${bold}${color}Song${clear}: $(mpc current)\"\r\necho \"\"\r\necho \"$customtext\"\r\necho \"\"\r\n\r\necho -e \"0;1;$xoffset;$yoffset;$width;$height;;;;;$img\\n4;\\n3;\" | /usr/lib/w3m/w3mimgdisplay\r\n" }, { "alpha_fraction": 0.596574068069458, "alphanum_fraction": 0.5983263850212097, "avg_line_length": 36.73684310913086, "blob_id": "10fb85a90ca915c59a82e1047aa9cab09e21dffd", "content_id": "9a48a339aa3e055248fb5100fd70d1357deb4398", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 27963, "license_type": "no_license", "max_line_length": 179, "num_lines": 741, "path": "/startpage/js/control.js", "repo_name": "pjhalsli/configs", "src_encoding": "UTF-8", "text": "var control = (function() {\n\n var toggle = function(override) {\n var options = {\n path: null,\n value: null\n };\n if (override) {\n options = helper.applyOptions(options, override);\n };\n if (options.path != null) {\n helper.setObject({\n path: options.path,\n object: state.get(),\n newValue: options.value\n });\n };\n };\n\n var render = function() {\n var html = helper.e(\"html\");\n var _edit = function() {\n if (state.get().edit.active) {\n helper.addClass(html, \"is-edit\");\n } else {\n helper.removeClass(html, \"is-edit\");\n };\n };\n var _date = function() {\n if (state.get().header.date.show.date || state.get().header.date.show.day || state.get().header.date.show.month || state.get().header.date.show.year) {\n helper.addClass(html, \"is-date\");\n } else {\n helper.removeClass(html, \"is-date\");\n };\n };\n var _clock = function() {\n if (state.get().header.clock.show.seconds || state.get().header.clock.show.minutes || state.get().header.clock.show.hours) {\n helper.addClass(html, \"is-clock\");\n } else {\n helper.removeClass(html, \"is-clock\");\n };\n };\n var _search = function() {\n if (state.get().header.search.active) {\n helper.addClass(html, \"is-search\");\n } else {\n helper.removeClass(html, \"is-search\");\n };\n if (state.get().header.search.grow) {\n helper.addClass(html, \"is-search-grow\");\n } else {\n helper.removeClass(html, \"is-search-grow\");\n };\n helper.e(\".control-header-search-engine-custom-url\").value = state.get().header.search.engine.custom.url;\n };\n var _alignment = function() {\n helper.removeClass(html, \"is-alignment-horizontal-left\");\n helper.removeClass(html, \"is-alignment-horizontal-center\");\n helper.removeClass(html, \"is-alignment-horizontal-right\");\n helper.removeClass(html, \"is-alignment-vertical-top\");\n helper.removeClass(html, \"is-alignment-vertical-center\");\n helper.removeClass(html, \"is-alignment-vertical-bottom\");\n helper.addClass(html, \"is-alignment-horizontal-\" + state.get().layout.alignment.horizontal);\n helper.addClass(html, \"is-alignment-vertical-\" + state.get().layout.alignment.vertical);\n };\n var _link = function() {\n var view = {\n block: function() {\n helper.addClass(html, \"is-link-block\");\n helper.removeClass(html, \"is-link-list\");\n },\n list: function() {\n helper.removeClass(html, \"is-link-block\");\n helper.addClass(html, \"is-link-list\");\n }\n };\n view[state.get().link.style]();\n if (state.get().link.show.active) {\n helper.addClass(html, \"is-link\");\n } else {\n helper.removeClass(html, \"is-link\");\n };\n if (state.get().link.show.name) {\n helper.addClass(html, \"is-link-name\");\n } else {\n helper.removeClass(html, \"is-link-name\");\n };\n if (state.get().link.show.url) {\n helper.addClass(html, \"is-link-url\");\n } else {\n helper.removeClass(html, \"is-link-url\");\n };\n };\n var _layout = function() {\n helper.removeClass(html, \"is-layout-fluid\");\n helper.removeClass(html, \"is-layout-wide\");\n helper.removeClass(html, \"is-layout-thin\");\n helper.addClass(html, \"is-layout-\" + state.get().layout.container);\n if (state.get().layout.scrollPastEnd) {\n helper.addClass(html, \"is-scroll-past-end\");\n } else {\n helper.removeClass(html, \"is-scroll-past-end\");\n };\n };\n var _editAdd = function() {\n if (state.get().header.editAdd.active) {\n helper.addClass(html, \"is-search-edit-add\");\n } else {\n helper.removeClass(html, \"is-search-edit-add\");\n };\n };\n var _accent = function() {\n if (state.get().header.accent.active) {\n helper.addClass(html, \"is-search-accent\");\n } else {\n helper.removeClass(html, \"is-search-accent\");\n };\n };\n _alignment();\n _edit();\n _date();\n _clock();\n _search();\n _editAdd();\n _accent();\n _link();\n _layout();\n };\n\n var dependents = function() {\n var _edit = function() {\n if (bookmarks.get().length > 0) {\n helper.e(\".control-edit\").disabled = false;\n } else {\n helper.e(\".control-edit\").disabled = true;\n helper.e(\".control-edit\").checked = false;\n state.change({\n path: \"edit.active\",\n value: false\n });\n };\n };\n var _date = function() {\n var activeCount = 0;\n var toCheck = [state.get().header.date.show.date, state.get().header.date.show.day, state.get().header.date.show.month, state.get().header.date.show.year];\n toCheck.forEach(function(arrayItem, index) {\n if (arrayItem == true) {\n activeCount++;\n };\n });\n if (activeCount >= 2 && (state.get().header.date.show.date || state.get().header.date.show.day || state.get().header.date.show.month || state.get().header.date.show.year)) {\n helper.e(\".control-header-date-show-separator\").disabled = false;\n } else {\n helper.e(\".control-header-date-show-separator\").disabled = true;\n };\n if (state.get().header.date.show.day || state.get().header.date.show.month) {\n helper.e(\".control-header-date-character-length-short\").disabled = false;\n helper.e(\".control-header-date-character-length-long\").disabled = false;\n } else {\n helper.e(\".control-header-date-character-length-short\").disabled = true;\n helper.e(\".control-header-date-character-length-long\").disabled = true;\n };\n };\n var _clock = function() {\n var activeCount = 0;\n var toCheck = [state.get().header.clock.show.seconds, state.get().header.clock.show.minutes, state.get().header.clock.show.hours];\n toCheck.forEach(function(arrayItem, index) {\n if (arrayItem == true) {\n activeCount++;\n };\n });\n if (activeCount >= 2 && (state.get().header.clock.show.seconds || state.get().header.clock.show.minutes || state.get().header.clock.show.hours)) {\n helper.e(\".control-header-clock-show-separator\").disabled = false;\n } else {\n helper.e(\".control-header-clock-show-separator\").disabled = true;\n };\n if (state.get().header.clock.show.seconds || state.get().header.clock.show.minutes || state.get().header.clock.show.hours) {\n helper.e(\".control-header-clock-24\").disabled = false;\n helper.e(\".control-header-clock-show-meridiem\").disabled = false;\n } else {\n helper.e(\".control-header-clock-24\").disabled = true;\n helper.e(\".control-header-clock-show-meridiem\").disabled = true;\n };\n if ((state.get().header.clock.show.seconds || state.get().header.clock.show.minutes || state.get().header.clock.show.hours) && !state.get().header.clock.hour24) {\n helper.e(\".control-header-clock-show-meridiem\").disabled = false;\n } else {\n helper.e(\".control-header-clock-show-meridiem\").disabled = true;\n };\n };\n var _search = function() {\n if (state.get().header.search.active) {\n helper.e(\".control-header-search-grow\").disabled = false;\n helper.e(\".control-header-search-focus\").disabled = false;\n helper.e(\".control-header-search-engine-google\").disabled = false;\n helper.e(\".control-header-search-engine-duckduckgo\").disabled = false;\n helper.e(\".control-header-search-engine-giphy\").disabled = false;\n helper.e(\".control-header-search-engine-custom\").disabled = false;\n helper.e(\".control-header-search-engine-label\").removeAttribute(\"disabled\");\n } else {\n helper.e(\".control-header-search-grow\").disabled = true;\n helper.e(\".control-header-search-focus\").disabled = true;\n helper.e(\".control-header-search-engine-google\").disabled = true;\n helper.e(\".control-header-search-engine-duckduckgo\").disabled = true;\n helper.e(\".control-header-search-engine-giphy\").disabled = true;\n helper.e(\".control-header-search-engine-custom\").disabled = true;\n helper.e(\".control-header-search-engine-label\").setAttribute(\"disabled\", \"\");\n };\n if (state.get().header.search.active && state.get().header.search.engine.selected === \"custom\") {\n helper.e(\"[for=control-header-search-engine-custom-url]\").removeAttribute(\"disabled\");\n helper.e(\".control-header-search-engine-custom-url\").disabled = false;\n } else {\n helper.e(\"[for=control-header-search-engine-custom-url]\").setAttribute(\"disabled\", \"\");\n helper.e(\".control-header-search-engine-custom-url\").disabled = true;\n };\n };\n var _theme = function() {\n if (state.get().layout.theme.random.active) {\n helper.eA(\"input[name='control-layout-theme-style']\").forEach(function(arrayItem, index) {\n arrayItem.disabled = false;\n });\n } else {\n helper.eA(\"input[name='control-layout-theme-style']\").forEach(function(arrayItem, index) {\n arrayItem.disabled = true;\n });\n };\n };\n var _link = function() {\n if (state.get().link.show.active) {\n helper.e(\".control-link-show-name\").disabled = false;\n helper.e(\".control-link-show-url\").disabled = false;\n helper.e(\".control-link-style-block\").disabled = false;\n helper.e(\".control-link-style-list\").disabled = false;\n helper.e(\".control-link-new-tab\").disabled = false;\n helper.e(\".control-link-sort-none\").disabled = false;\n helper.e(\".control-link-sort-name\").disabled = false;\n helper.e(\".control-link-sort-letter\").disabled = false;\n helper.e(\".control-layout-alignment-vertical-top\").disabled = true;\n helper.e(\".control-layout-alignment-vertical-center\").disabled = true;\n helper.e(\".control-layout-alignment-vertical-bottom\").disabled = true;\n } else {\n helper.e(\".control-link-show-name\").disabled = true;\n helper.e(\".control-link-show-url\").disabled = true;\n helper.e(\".control-link-style-block\").disabled = true;\n helper.e(\".control-link-style-list\").disabled = true;\n helper.e(\".control-link-new-tab\").disabled = true;\n helper.e(\".control-link-sort-none\").disabled = true;\n helper.e(\".control-link-sort-name\").disabled = true;\n helper.e(\".control-link-sort-letter\").disabled = true;\n helper.e(\".control-layout-alignment-vertical-top\").disabled = false;\n helper.e(\".control-layout-alignment-vertical-center\").disabled = false;\n helper.e(\".control-layout-alignment-vertical-bottom\").disabled = false;\n };\n };\n var _background = function() {\n if (state.get().background.image.active) {\n helper.e(\"[for=control-background-image-url]\").removeAttribute(\"disabled\");\n helper.e(\".control-background-image-url\").disabled = false;\n helper.e(\"[for=control-background-image-opacity]\").removeAttribute(\"disabled\");\n helper.e(\".control-background-image-opacity\").disabled = false;\n helper.e(\"[for=control-background-image-blur]\").removeAttribute(\"disabled\");\n helper.e(\".control-background-image-blur\").disabled = false;\n helper.e(\"[for=control-background-image-grayscale]\").removeAttribute(\"disabled\");\n helper.e(\".control-background-image-grayscale\").disabled = false;\n helper.e(\"[for=control-background-image-accent-opacity]\").removeAttribute(\"disabled\");\n helper.e(\".control-background-image-accent-opacity\").disabled = false;\n } else {\n helper.e(\"[for=control-background-image-url]\").setAttribute(\"disabled\", \"\");\n helper.e(\".control-background-image-url\").disabled = true;\n helper.e(\"[for=control-background-image-opacity]\").setAttribute(\"disabled\", \"\");\n helper.e(\".control-background-image-opacity\").disabled = true;\n helper.e(\"[for=control-background-image-blur]\").setAttribute(\"disabled\", \"\");\n helper.e(\".control-background-image-blur\").disabled = true;\n helper.e(\"[for=control-background-image-grayscale]\").setAttribute(\"disabled\", \"\");\n helper.e(\".control-background-image-grayscale\").disabled = true;\n helper.e(\"[for=control-background-image-accent-opacity]\").setAttribute(\"disabled\", \"\");\n helper.e(\".control-background-image-accent-opacity\").disabled = true;\n };\n };\n _edit();\n _date();\n _clock();\n _search();\n _theme();\n _link();\n _background();\n };\n\n var _bind = function() {\n helper.e(\".control-menu\").addEventListener(\"click\", function() {\n menu.toggle();\n }, false);\n helper.e(\".control-add\").addEventListener(\"click\", function() {\n link.add();\n }, false);\n helper.e(\".control-edit\").addEventListener(\"change\", function() {\n state.change({\n path: \"edit.active\",\n value: this.checked\n });\n render();\n dependents();\n data.save();\n }, false);\n helper.e(\".control-layout-theme\").addEventListener(\"change\", function() {\n state.change({\n path: \"layout.theme.current\",\n value: helper.hexToRgb(this.value)\n });\n theme.render();\n data.save();\n }, false);\n helper.e(\".control-layout-theme-random\").addEventListener(\"change\", function() {\n state.change({\n path: \"layout.theme.random.active\",\n value: this.checked\n });\n theme.render();\n dependents();\n data.save();\n }, false);\n helper.eA(\"input[name='control-layout-theme-style']\").forEach(function(arrayItem, index) {\n arrayItem.addEventListener(\"change\", function() {\n state.change({\n path: \"layout.theme.random.style\",\n value: this.value\n });\n render();\n data.save();\n }, false);\n });\n helper.e(\".control-link-new-tab\").addEventListener(\"change\", function() {\n state.change({\n path: \"link.newTab\",\n value: this.checked\n });\n link.clear();\n link.render();\n data.save();\n });\n helper.e(\".control-link-show-active\").addEventListener(\"change\", function() {\n state.change({\n path: \"link.show.active\",\n value: this.checked\n });\n render();\n dependents();\n header.render();\n data.save();\n });\n helper.e(\".control-link-show-name\").addEventListener(\"change\", function() {\n state.change({\n path: \"link.show.name\",\n value: this.checked\n });\n render();\n dependents();\n data.save();\n });\n helper.e(\".control-link-show-url\").addEventListener(\"change\", function() {\n state.change({\n path: \"link.show.url\",\n value: this.checked\n });\n render();\n dependents();\n data.save();\n });\n helper.eA(\"input[name='control-link-style']\").forEach(function(arrayItem, index) {\n arrayItem.addEventListener(\"change\", function() {\n state.change({\n path: \"link.style\",\n value: this.value\n });\n render();\n data.save();\n }, false);\n });\n helper.eA(\"input[name='control-link-sort']\").forEach(function(arrayItem, index) {\n arrayItem.addEventListener(\"change\", function() {\n state.change({\n path: \"link.sort\",\n value: this.value\n });\n link.clear();\n link.render();\n data.save();\n }, false);\n });\n helper.e(\".control-header-search-active\").addEventListener(\"change\", function() {\n state.change({\n path: \"header.search.active\",\n value: this.checked\n });\n render();\n dependents();\n header.render();\n data.save();\n }, false);\n helper.e(\".control-header-search-grow\").addEventListener(\"change\", function() {\n state.change({\n path: \"header.search.grow\",\n value: this.checked\n });\n render();\n header.render();\n data.save();\n }, false);\n helper.e(\".control-header-search-focus\").addEventListener(\"change\", function() {\n state.change({\n path: \"header.search.focus\",\n value: this.checked\n });\n data.save();\n }, false);\n helper.eA(\"input[name='control-header-search-engine']\").forEach(function(arrayItem, index) {\n arrayItem.addEventListener(\"change\", function() {\n state.change({\n path: \"header.search.engine.selected\",\n value: this.value\n });\n render();\n dependents();\n search.update();\n data.save();\n }, false);\n });\n helper.e(\".control-header-search-engine-custom-url\").addEventListener(\"input\", function() {\n state.change({\n path: \"header.search.engine.custom.url\",\n value: this.value\n });\n search.update();\n data.save();\n }, false);\n helper.e(\".control-header-date-show-date\").addEventListener(\"change\", function() {\n state.change({\n path: \"header.date.show.date\",\n value: this.checked\n });\n render();\n dependents();\n date.clear();\n date.render();\n header.render();\n data.save();\n }, false);\n helper.e(\".control-header-date-show-day\").addEventListener(\"change\", function() {\n state.change({\n path: \"header.date.show.day\",\n value: this.checked\n });\n render();\n dependents();\n date.clear();\n date.render();\n header.render();\n data.save();\n }, false);\n helper.e(\".control-header-date-show-month\").addEventListener(\"change\", function() {\n state.change({\n path: \"header.date.show.month\",\n value: this.checked\n });\n render();\n dependents();\n date.clear();\n date.render();\n header.render();\n data.save();\n }, false);\n helper.e(\".control-header-date-show-year\").addEventListener(\"change\", function() {\n state.change({\n path: \"header.date.show.year\",\n value: this.checked\n });\n render();\n dependents();\n date.clear();\n date.render();\n header.render();\n data.save();\n }, false);\n helper.e(\".control-header-date-show-separator\").addEventListener(\"change\", function() {\n state.change({\n path: \"header.date.show.separator\",\n value: this.checked\n });\n render();\n dependents();\n date.clear();\n date.render();\n header.render();\n data.save();\n }, false);\n helper.eA(\"input[name='control-header-date-character-length']\").forEach(function(arrayItem, index) {\n arrayItem.addEventListener(\"change\", function() {\n state.change({\n path: \"header.date.characterLength\",\n value: this.value\n });\n render();\n date.clear();\n date.render();\n header.render();\n data.save();\n }, false);\n });\n helper.e(\".control-header-clock-show-seconds\").addEventListener(\"change\", function() {\n state.change({\n path: \"header.clock.show.seconds\",\n value: this.checked\n });\n render();\n dependents();\n clock.clear();\n clock.render();\n header.render();\n data.save();\n }, false);\n helper.e(\".control-header-clock-show-minutes\").addEventListener(\"change\", function() {\n state.change({\n path: \"header.clock.show.minutes\",\n value: this.checked\n });\n render();\n dependents();\n clock.clear();\n clock.render();\n header.render();\n data.save();\n }, false);\n helper.e(\".control-header-clock-show-hours\").addEventListener(\"change\", function() {\n state.change({\n path: \"header.clock.show.hours\",\n value: this.checked\n });\n render();\n dependents();\n clock.clear();\n clock.render();\n header.render();\n data.save();\n }, false);\n helper.e(\".control-header-clock-show-separator\").addEventListener(\"change\", function() {\n state.change({\n path: \"header.clock.show.separator\",\n value: this.checked\n });\n clock.clear();\n clock.render();\n header.render();\n data.save();\n }, false);\n helper.e(\".control-header-clock-24\").addEventListener(\"change\", function() {\n state.change({\n path: \"header.clock.hour24\",\n value: this.checked\n });\n dependents();\n clock.clear();\n clock.render();\n header.render();\n data.save();\n }, false);\n helper.e(\".control-header-clock-show-meridiem\").addEventListener(\"change\", function() {\n state.change({\n path: \"header.clock.show.meridiem\",\n value: this.checked\n });\n clock.clear();\n clock.render();\n header.render();\n data.save();\n }, false);\n helper.e(\".control-header-edit-add-active\").addEventListener(\"change\", function() {\n state.change({\n path: \"header.editAdd.active\",\n value: this.checked\n });\n render();\n header.render();\n data.save();\n }, false);\n helper.e(\".control-header-accent-active\").addEventListener(\"change\", function() {\n state.change({\n path: \"header.accent.active\",\n value: this.checked\n });\n render();\n header.render();\n data.save();\n }, false);\n helper.eA(\"input[name='control-layout-alignment-horizontal']\").forEach(function(arrayItem, index) {\n arrayItem.addEventListener(\"change\", function() {\n state.change({\n path: \"layout.alignment.horizontal\",\n value: this.value\n });\n render();\n data.save();\n }, false);\n });\n helper.eA(\"input[name='control-layout-alignment-vertical']\").forEach(function(arrayItem, index) {\n arrayItem.addEventListener(\"change\", function() {\n state.change({\n path: \"layout.alignment.vertical\",\n value: this.value\n });\n render();\n data.save();\n }, false);\n });\n helper.eA(\"input[name='control-layout-container']\").forEach(function(arrayItem, index) {\n arrayItem.addEventListener(\"change\", function() {\n state.change({\n path: \"layout.container\",\n value: this.value\n });\n render();\n header.render();\n data.save();\n }, false);\n });\n helper.e(\".control-layout-scroll-past-end\").addEventListener(\"change\", function() {\n state.change({\n path: \"layout.scrollPastEnd\",\n value: this.checked\n });\n render();\n data.save();\n }, false);\n helper.e(\".control-background-image-active\").addEventListener(\"change\", function() {\n state.change({\n path: \"background.image.active\",\n value: this.checked\n });\n render();\n dependents();\n background.render();\n data.save();\n }, false);\n helper.e(\".control-background-image-url\").addEventListener(\"input\", function() {\n state.change({\n path: \"background.image.url\",\n value: this.value\n });\n background.render();\n data.save();\n }, false);\n helper.e(\".control-background-image-opacity\").addEventListener(\"input\", function() {\n state.change({\n path: \"background.image.opacity\",\n value: (100 - parseInt(this.value)) / 100\n });\n background.render();\n data.save();\n }, false);\n helper.e(\".control-background-image-blur\").addEventListener(\"input\", function() {\n state.change({\n path: \"background.image.blur\",\n value: parseInt(this.value, 10)\n });\n background.render();\n data.save();\n }, false);\n helper.e(\".control-background-image-grayscale\").addEventListener(\"input\", function() {\n state.change({\n path: \"background.image.grayscale\",\n value: parseInt(this.value, 10) / 100\n });\n background.render();\n data.save();\n }, false);\n helper.e(\".control-background-image-accent-opacity\").addEventListener(\"input\", function() {\n state.change({\n path: \"background.image.accentOpacity\",\n value: parseInt(this.value, 10) / 100\n });\n background.render();\n data.save();\n }, false);\n };\n\n var update = function() {\n helper.e(\".control-edit\").checked = state.get().edit.active;\n helper.e(\".control-layout-theme\").value = helper.rgbToHex(state.get().layout.theme.current);\n helper.e(\".control-layout-theme-random\").checked = state.get().layout.theme.random.active;\n helper.e(\".control-layout-theme-style-\" + state.get().layout.theme.random.style).checked = true;\n helper.e(\".control-link-new-tab\").value = state.get().link.style.newTab;\n helper.e(\".control-link-show-active\").checked = state.get().link.show.active;\n helper.e(\".control-link-show-name\").checked = state.get().link.show.name;\n helper.e(\".control-link-show-url\").checked = state.get().link.show.url;\n helper.e(\".control-link-style-\" + state.get().link.style).checked = true;\n helper.e(\".control-link-sort-\" + state.get().link.sort).checked = true;\n helper.e(\".control-header-search-active\").checked = state.get().header.search.active;\n helper.e(\".control-header-search-grow\").checked = state.get().header.search.grow;\n helper.e(\".control-header-search-focus\").checked = state.get().header.search.focus;\n helper.e(\".control-header-search-engine-\" + state.get().header.search.engine.selected).checked = true;\n helper.e(\".control-header-search-engine-custom-url\").value = state.get().header.search.engine.custom.url;\n helper.e(\".control-header-date-show-date\").checked = state.get().header.date.show.date;\n helper.e(\".control-header-date-show-day\").checked = state.get().header.date.show.day;\n helper.e(\".control-header-date-show-month\").checked = state.get().header.date.show.month;\n helper.e(\".control-header-date-show-year\").checked = state.get().header.date.show.year;\n helper.e(\".control-header-date-show-separator\").checked = state.get().header.date.show.separator;\n helper.e(\".control-header-clock-show-seconds\").checked = state.get().header.clock.show.seconds;\n helper.e(\".control-header-clock-show-minutes\").checked = state.get().header.clock.show.minutes;\n helper.e(\".control-header-clock-show-hours\").checked = state.get().header.clock.show.hours;\n helper.e(\".control-header-clock-show-separator\").checked = state.get().header.clock.show.separator;\n helper.e(\".control-header-clock-24\").checked = state.get().header.clock.hour24;\n helper.e(\".control-header-clock-show-meridiem\").checked = state.get().header.clock.show.meridiem;\n helper.e(\".control-header-edit-add-active\").checked = state.get().header.editAdd.active;\n helper.e(\".control-header-accent-active\").checked = state.get().header.accent.active;\n helper.e(\".control-header-date-character-length-\" + state.get().header.date.characterLength).checked = true;\n helper.e(\".control-layout-alignment-horizontal-\" + state.get().layout.alignment.horizontal).checked = true;\n helper.e(\".control-layout-alignment-vertical-\" + state.get().layout.alignment.vertical).checked = true;\n helper.e(\".control-layout-container-\" + state.get().layout.container).checked = true;\n helper.e(\".control-layout-scroll-past-end\").checked = state.get().layout.scrollPastEnd;\n helper.e(\".control-background-image-active\").checked = state.get().background.image.active;\n helper.e(\".control-background-image-url\").value = state.get().background.image.url;\n helper.e(\".control-background-image-opacity\").value = 100 - (state.get().background.image.opacity * 100);\n helper.e(\".control-background-image-blur\").value = state.get().background.image.blur;\n helper.e(\".control-background-image-grayscale\").value = state.get().background.image.grayscale * 100;\n helper.e(\".control-background-image-accent-opacity\").value = (state.get().background.image.accentOpacity * 100);\n };\n\n var init = function() {\n _bind();\n update();\n dependents();\n render();\n };\n\n // exposed methods\n return {\n init: init,\n render: render,\n dependents: dependents,\n update: update\n };\n\n})();\n" } ]
20
Lo-kin/agefans-all-name
https://github.com/Lo-kin/agefans-all-name
7a2e151d973920f5a2f99d8acc3c47f6ad6d0651
d3d573aff239a48f6f3297d6ef41a415e9eea5af
cab7bf7ed1beba492be1903ddb48b566dbf31baa
refs/heads/main
2023-06-21T23:08:03.414419
2021-07-23T13:59:52
2021-07-23T13:59:52
388,800,036
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8524590134620667, "alphanum_fraction": 0.8524590134620667, "avg_line_length": 19.33333396911621, "blob_id": "677d0477536543c7307255d0a4aa4ce1ff13273d", "content_id": "0b19eded18e0e17f1ef762066bd97233e1d6cf37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 101, "license_type": "no_license", "max_line_length": 20, "num_lines": 3, "path": "/README.md", "repo_name": "Lo-kin/agefans-all-name", "src_encoding": "UTF-8", "text": "# agefans-all-name\n用于索引agefans现有番剧,更加稳定\nanimelist.txt是已输出的文件\n" }, { "alpha_fraction": 0.5558558702468872, "alphanum_fraction": 0.5963963866233826, "avg_line_length": 26.04878044128418, "blob_id": "fb66854f7a5ee66437d729eea7bd0f4f870c0754", "content_id": "66aa0de95f7ff9d912a57b4862e2d8a497931f79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1144, "license_type": "no_license", "max_line_length": 64, "num_lines": 41, "path": "/main.py", "repo_name": "Lo-kin/agefans-all-name", "src_encoding": "UTF-8", "text": "import requests\nimport re\nimport os\nimport linecache\nfrom requests.models import Response\n\nstart_page =\"https://www.agefans.cc/detail/{}{}\"\nstart_year = 1999\nstart_num = 0\n\nfile1 = open(\"animelist.txt\" , \"a\" , encoding=\"utf-8\")#爬取内容\nfile2 = open(\"tmp.txt\" , \"w\" , encoding=\"utf-8\") #临时文件\n\ni = 0\n\nwhile i == 0:\n start_num = start_num + 1\n start_num4 = str(start_num)\n start_num5 = start_num4.zfill(4)#将数字转换为000?的格式\n comp_url = start_page.format(start_year,start_num5)\n start_years = str(start_year)\n start_num5s = str(start_num5)\n request = requests.get(comp_url)\n code = request.status_code\n\n if code == 404:\n start_year = start_year + 1\n start_num = 0\n else:\n print(comp_url)\n file2.write(request.text)\n file2.close\n rl15 = linecache.getline(\"tmp.txt\" , 15)\n title = re.findall(r'content=\\W(.*),' , rl15)\n file1.write(\"-\" + start_years + start_num5s + \"-\" + \"<\")\n file1.write(title[0])\n file1.write(\">\" + \"\\n\")\n file1.flush()\n file2.seek(0)\n file2.truncate(0)\n linecache.clearcache()\n\n" } ]
2
inn0kenty/RCARovio
https://github.com/inn0kenty/RCARovio
84a8f8839d3478151bac22aef20cdb9b6df2704b
824d916bfef7eb6b81b46ad8d8b504ced98a4fc2
ae9295af78c35a63d42daf0ec1f58618c82d88b6
refs/heads/master
2020-12-25T14:58:45.769103
2015-12-28T12:20:58
2015-12-28T12:20:58
66,375,237
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5149683356285095, "alphanum_fraction": 0.5230281949043274, "avg_line_length": 28.440677642822266, "blob_id": "00ee3ed951555b052177d16a017d287f756aed51", "content_id": "82a79ba7078a52112946dd349e5953be3ff19aaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3474, "license_type": "no_license", "max_line_length": 80, "num_lines": 118, "path": "/utils/http.py", "repo_name": "inn0kenty/RCARovio", "src_encoding": "UTF-8", "text": "import httplib\nimport urllib\n\n\nclass HTTPRequests (object):\n def __init__(self, ip):\n self.__ip = ip\n self.__image_handler = None\n\n def add_image_handler(self, image_handler):\n self.__image_handler = image_handler\n\n def move(self, command):\n params = urllib.urlencode([('Cmd', 'nav'), ('action', 18),\n ('drive', command.get_value()),\n ('speed', command.get_speed())])\n\n try:\n self.__connection.request('POST', '/rev.cgi', params)\n response = self.__connection.getresponse()\n except KeyboardInterrupt:\n print '\\nAborted by user'\n exit(0)\n except:\n print command.get_name() + '... connection failed'\n return False\n\n # parsing response\n response = response.read().strip('\\n')\n\n # response parameter\n response = response.split('\\n')[1].split('|')[0].split('=')[1]\n\n if int(response) != 0:\n print 'Bad response from Rovio\\nInternal error'\n return False\n\n return True\n\n def cap_image(self):\n try:\n self.__connection.request('GET', '/Jpeg/CamImg0001.jpg')\n response = self.__connection.getresponse()\n except KeyboardInterrupt:\n print '\\nAborted by user'\n exit(0)\n except:\n print 'capture_image... connection failed'\n return False\n\n if self.__image_handler:\n self.__image_handler(response.read())\n\n return True\n\n def reset_home(self):\n params = urllib.urlencode([('Cmd', 'nav'), ('action', 27)])\n try:\n self.__connection.request('POST', '/rev.cgi', params)\n except KeyboardInterrupt:\n print '\\nAborted by user'\n exit(0)\n except Exception as e:\n print 'Reset home... connection faild', e.message\n return False\n\n return True\n\n def ping(self):\n params = urllib.urlencode([('Cmd', 'nav'), ('action', 1)])\n try:\n self.__connection.request('POST', '/rev.cgi', params)\n response = self.__connection.getresponse()\n except KeyboardInterrupt:\n print '\\nAborted by user'\n exit(0)\n except:\n print 'Ping... connection failed'\n return False, None\n\n # parsing response\n response = response.read().strip('\\n')\n\n # response parameter\n ping = response.split('\\n')[1].split('|')[0].split('=')\n # battery parameter\n battery = response.split('\\n')[7].split('|')[1].split('=')\n\n if int(ping[1]) == 0: # if response parameter 0 then all ok\n return True, battery[1]\n else:\n return False, None\n\n def set_resolution(self, param):\n try:\n self.__connection.request('GET',\n '/ChangeResolution.cgi?ResType=' + param)\n except KeyboardInterrupt:\n print '\\nAborted by user'\n exit(0)\n except:\n print 'Set resolution... connection faild'\n return False\n\n return True\n\n def open(self):\n self.__connection = httplib.HTTPConnection(self.__ip, timeout=10)\n\n def close(self):\n self.__connection.close()\n\n def __enter__(self):\n self.open()\n return self\n\n def __exit__(self, type, value, traceback):\n self.close()\n" }, { "alpha_fraction": 0.619271457195282, "alphanum_fraction": 0.6216216087341309, "avg_line_length": 31.730770111083984, "blob_id": "550407b15a6c7ed543c63a7ce579e97f58a4a9f3", "content_id": "8c8e162d8dd4867902b8628bf462ba525c531436", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 851, "license_type": "no_license", "max_line_length": 76, "num_lines": 26, "path": "/main/__init__.py", "repo_name": "inn0kenty/RCARovio", "src_encoding": "UTF-8", "text": "import argparse\nimport shutil\nimport os\n\n\nclass CleanAction(argparse.Action):\n def __call__(self, parser, namespace, values, option_string=None):\n path = os.getenv('HOME') + '/.rovio/'\n if os.path.exists(path):\n shutil.rmtree(path)\n parser.exit()\n\n\nparser = argparse.ArgumentParser(description='Avaliable arguments')\n\nparser.add_argument('-t', '--test', action='store_true',\n help='Run syntactic test for input file')\n\nparser.add_argument('-p', '--ping', action='store_true',\n help='Ping rovio IP address')\n\nparser.add_argument('-c', '--clean', action=CleanAction, nargs=0,\n help='Cleans all stored images')\n\nparser.add_argument('file_path', metavar='FILE_NAME', type=str, nargs=1,\n help='A path to file that contains a commands to Rovio')\n" }, { "alpha_fraction": 0.5852417349815369, "alphanum_fraction": 0.5954198241233826, "avg_line_length": 27.071428298950195, "blob_id": "8d6ff6b7ebf7f26a35dda12fc6f275b4baa2f9a3", "content_id": "c9ff003dd902687c0dc5f6062681b0f4331ccc6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 393, "license_type": "no_license", "max_line_length": 49, "num_lines": 14, "path": "/setup.py", "repo_name": "inn0kenty/RCARovio", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n\nfrom distutils.core import setup\n\nsetup(name='Rovio',\n version='1.1.2',\n description='Remote Rovio control',\n author='Innokenty Lebedev (RobotsCityAmsterdam)',\n author_email='[email protected]',\n url='http://robotscityamsterdam.com',\n packages=['rovio_base', 'main', 'utils'],\n scripts=['rovio'],\n data_files=[('/etc/rovio/', ['rovio.cfg'])]\n )\n" }, { "alpha_fraction": 0.48720064759254456, "alphanum_fraction": 0.5057803392410278, "avg_line_length": 29.64556884765625, "blob_id": "0c4744d887cca113b8541b1e1c9e208d162bbb9e", "content_id": "910cc514788378c1e08aa52203839e5dae2aaeaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2422, "license_type": "no_license", "max_line_length": 64, "num_lines": 79, "path": "/utils/command.py", "repo_name": "inn0kenty/RCARovio", "src_encoding": "UTF-8", "text": "class Command(object):\n \"\"\"The Command class represent a one instruction to rovio\"\"\"\n def __init__(self, command_array):\n self.__name = command_array[0] # command name\n self.__value = self.__set_value(self.__name)\n\n del command_array[0]\n\n self.__parameters = command_array\n command_array = dict(enumerate(command_array))\n if self.__name == 'rotate_left_by_speed' or \\\n self.__name == 'rotate_right_by_speed':\n self.__speed = command_array.get(0, 1)\n self.__time = -1\n else:\n self.__speed = 1 #command_array.get(0, 10)\n self.__time = command_array.get(0, -1)\n\n def get_name(self):\n return self.__name\n\n def get_speed(self):\n return self.__speed\n\n def get_time(self):\n return int(self.__time)\n\n def get_value(self):\n return self.__value\n\n def get_params(self):\n return self.__parameters\n\n def __set_value(self, x):\n return {'forward': 1,\n 'backward': 2,\n 'straight_left': 3,\n 'straight_right': 4,\n 'rotate_left_by_speed': 5,\n 'rotate_right_by_speed': 6,\n 'diagonal_forward_left': 7,\n 'diagonal_forward_right': 8,\n 'diagonal_backward_left': 9,\n 'diagonal_backward_right': 10,\n 'head_up': 11,\n 'head_down': 12,\n 'head_middle': 13,\n 'rotate_left_by_20_degree': 17,\n 'rotate_right_by_20_degree': 18,\n 'capture_image': 19,\n 'wait': 20,\n }.get(x, -1)\n\nclass CommandQueue(object):\n \"\"\"The CommandQueue class represent a queue of\n commands that rovio should do\"\"\"\n def __init__(self):\n self.__commands = []\n\n def add_command(self, command):\n \"\"\" command should be as list \"\"\"\n self.__commands.append(Command(command))\n\n def get(self, index):\n if (0 <= index) and (index < len(self.__commands)):\n return self.__commands[index]\n else:\n return None\n\n def __iter__(self):\n self.__position = -1\n return self\n\n def next(self):\n if self.__position < len(self.__commands) - 1:\n self.__position += 1\n return self.__commands[self.__position]\n else:\n raise StopIteration()\n\n" }, { "alpha_fraction": 0.5209471583366394, "alphanum_fraction": 0.5250455141067505, "avg_line_length": 30.371429443359375, "blob_id": "4d3a4fab52b83ff9c4205024bec8e8ff47e1a922", "content_id": "713f8bac785391c3bed661330e2606822a4ba268", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2196, "license_type": "no_license", "max_line_length": 75, "num_lines": 70, "path": "/rovio_base/rovio.py", "repo_name": "inn0kenty/RCARovio", "src_encoding": "UTF-8", "text": "from utils.http import HTTPRequests\nimport time\nfrom datetime import datetime\nimport os\nfrom utils.utils import Config\nimport subprocess\nimport threading\n\n\nclass Rovio(object):\n def __init__(self, address, commands):\n self.__address = address\n self.__commands = commands\n self.__remote_rovio = HTTPRequests(address)\n self.__remote_rovio.add_image_handler(self.__impage_handler)\n self.__config = Config()\n self.__remote_rovio.open()\n self.__remote_rovio.set_resolution(self.__config.get('resolution'))\n self.__remote_rovio.close()\n self.__remote_rovio.open()\n self.__remote_rovio.reset_home()\n self.__remote_rovio.close()\n\n def do(self):\n with self.__remote_rovio as r:\n for command in self.__commands:\n if command.get_name() == 'capture_image':\n done = r.cap_image()\n\n if command.get_name() == 'wait':\n time.sleep(command.get_time())\n done =True\n\n if command.get_time() < 0:\n done = r.move(command)\n time.sleep(0.5)\n\n for t in xrange(command.get_time()*4):\n done = r.move(command)\n if not done:\n break\n time.sleep(0.15)\n\n if done:\n print command.get_name() + '... done'\n\n def __impage_handler(self, data):\n handler = ImageHandler(data)\n handler.start()\n\n\nclass ImageHandler(threading.Thread):\n def __init__(self, image_data):\n threading.Thread.__init__(self)\n self.__image_data = image_data\n\n def run(self):\n image_path = os.getenv(\"HOME\") + '/.rovio/'\n if not os.path.exists(image_path):\n os.makedirs(image_path)\n image_name = image_path + \\\n datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S.jpg\")\n\n image = open(image_name, 'wb')\n image.write(self.__image_data)\n image.close()\n\n config = Config()\n subprocess.call(config.get('open') + ' ' +\n image_name + ' > /dev/null 2>&1', shell=True)\n" }, { "alpha_fraction": 0.6061946749687195, "alphanum_fraction": 0.6120944023132324, "avg_line_length": 23.214284896850586, "blob_id": "2fc08bebd153218101df4da2d16f3357d2273b25", "content_id": "f9611743db7fe1e574b2bf7e6b38a0779ec9805d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 678, "license_type": "no_license", "max_line_length": 50, "num_lines": 28, "path": "/main/main.py", "repo_name": "inn0kenty/RCARovio", "src_encoding": "UTF-8", "text": "from utils.tests import Test\nfrom . import parser\nimport sys\nimport os.path\nfrom utils.utils import FileParser, Config\nfrom rovio_base.rovio import Rovio\n\ndef main() :\n args = parser.parse_args()\n file_path = args.file_path[0]\n\n if not os.path.isfile(file_path):\n print 'File not found'\n exit(-1);\n\n file_parser = FileParser(file_path)\n address, commands = file_parser.get_data()\n config = Config()\n\n if len(sys.argv) > 2:\n test = Test(address, commands)\n if args.ping:\n test.ping()\n if args.test:\n test.syntax()\n else:\n remote_rovio = Rovio(address[1], commands)\n remote_rovio.do()\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7638108730316162, "avg_line_length": 30.64444351196289, "blob_id": "50839d0ea74e281f287d20b74e0fa4d97bfcc3af", "content_id": "3f3f82b8aaf1d1f19aac0ee9fe4e50ce21fae9e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6876, "license_type": "no_license", "max_line_length": 105, "num_lines": 135, "path": "/README.md", "repo_name": "inn0kenty/RCARovio", "src_encoding": "UTF-8", "text": "# Информация\n\nДанная программа позволяет автоматизировать работу Rovio, описав его\nдействия с помощью простого языка, интерпретируя который, Rovio будет играть \nсвою роль в спектакле.\n\n# Установка\n\nВ терминале необходимо выполнить команду:\n\n```bash\n$ sudo pip2 install git+http://git.robotscityamsterdam.com/git/inn0kenty/rovio.git\n```\n\nСистема может попросить логин и пароль. Тогда необходимо ввести логин `rca`, \nпароль `SxyVcIZfbklBi5jiUtZO`\n\n# Операторам\n\nПосле установки, в системе появится программа - rovio, работающая из командной\nстроки.\n\nПрограмме при запуске необходимо подсунуть файл с командами, которые\nдолжен выполнить Rovio.\n\nЗапустить программу можно следующим образом:\n\n```bash\n$ rovio <file_name>\n```\n\nгде `<file_name>` путь к файлу с командами\n\n## Структура файла с командами\n\n- Каждая команда в файле должна быть на отдельной строке \n- В файле не может быть пустых строк \n- Самая первая команда в файле имеет вид:\n\n ```\n address xxx.xxx.xxx.xxx\n ```\n\n где `xxx.xxx.xxx.xxx` - ip адрес Rovio. После этой команды могут быть любые \n команды, из раздела [Доступные команды](#Доступные команды), \n в любой последовательности.\n- У некоторых команд может быть параметр - время или скорость. Этот параметр \n отделяется от команды пробелом\n\n## Доступные команды\n\n|Команда|Параметр|Описание|\n|:-----:|:------:|:------:|\n|forward|время в секундах|движение вперед|\n|backward|время в секундах|движение назад|\n|straight_left|время в секундах|движение налево|\n|straight_right|время в секундах|движение направо|\n|rotate_left_by_speed|скорость (от 1 до 10), где 1 - самая быстрая|поворот налево с заданной скоростью|\n|rotate_right_by_speed|скорость (от 1 до 10), где 1 - самая быстрая|поворот направо с заданной скоростью|\n|diagonal_forward_left|время в секундах|движение по диагонале вперед и налево|\n|diagonal_forward_right|время в секундах|движение по диагонале вперед и направо|\n|diagonal_backward_left|время в секундах|движение по диагонале назад и налево|\n|diagonal_backward_right|время в секундах|движение по диагонале назад и направо|\n|head_up|-|поднять голову на максимум|\n|head_down|-|опустить голову|\n|head_middle|-|переместить голову на центр|\n|rotate_left_by_20_degree|-|поворот налево на 20 градусов|\n|rotate_right_by_20_degree|-|поворот направо на 20 градусов|\n|capture_image|-|снять и показать изображение с камеры|\n|wait|время в секундах|подождать заданное колличество секунд|\n\n## Проверка синтаксиса файла с командами\n\nПосле создания файла с командами, необхдимо его проверить на наличие ошибок. Это\nважно, иначе, при работе, Rovio не получит сломанную команду и начнет вести себя\nне так, как от него ожидается.\n\nПроверка делается следующим образом:\n\n```bash\n$ rovio -t <file_name>\n```\n\nЕсли программа выдаст сообщение `Syntax test OK`, значит с файлом все впорядке и\nего можно использовать, иначе программа выдаст сообщене об ошибке и укажет на\nкакой строке файла она находится.\n\n## Проверка доступности Rovio\n\nИногда может понадобиться удаленно проверить включен ли Rovio. Для этого можно\nвоспользоваться командой:\n\n```bash\n$ rovio -p <file_name>\n```\n\nЕсли Rovio включен, то вы увидете сообщение `Ping test OK`, а также уровень \nзаряда батареи, иначе вы увидите сообщение об ошибке.\n\nNB: В данном случае, в файле с командами может быть только первая строка с\nадресом, т.к. остальные команды не выполняются.\n\n## Настройки программы\n\nФайл с настройками программы иеет путь `/etc/rovio/rovio.cfg`. \n\nФайл содержит следующие параметры:\n\n- open - имя программы через которую будут открываться полученные от Rovio\n изображения (если параметр не указан, то изображения будут открываться \n через программу open, если она стоит в системе, иначе изображения вообще\n не будут открываться)\n- resolution - размер получаемых от Rovio изображений, указывается с помощью\n цифры:\n \n - 0 - размер 176 на 144\n - 1 - размер 352 на 288\n - 2 - размер 320 на 240\n - 3 - размер 640 на 480 (Используется по умолчанию)\n\n## Пример файла с командами\n\n```\naddress 192.168.1.25 \nforward 5\nstraight_right 5\nrotate_right_by_speed 1\ncapture_image\n```\n\n# Проблемы?\n\nОбо всех ошибках и неадекватном поведении, просьба сообщать мне на почту \n`[email protected]`. В теме письма укажите `RCA Rovio`, опишите проблему и\nпрекрепите файл с командами.\n" }, { "alpha_fraction": 0.44069430232048035, "alphanum_fraction": 0.445515900850296, "avg_line_length": 34.4529914855957, "blob_id": "06f6459d8f894923b205dd26b65765d31b4e0bfd", "content_id": "846902d258b3d1676bf293e77d22fbe835cf113f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4148, "license_type": "no_license", "max_line_length": 81, "num_lines": 117, "path": "/utils/tests.py", "repo_name": "inn0kenty/RCARovio", "src_encoding": "UTF-8", "text": "from http import HTTPRequests\n\n\nclass Test(object):\n def __init__(self, address, commands):\n self.__address = address\n self.__commands = commands # commands from file\n # all available commands\n self.__available_commands = {'forward': (self.__is_time_correct,),\n 'backward': (self.__is_time_correct,),\n 'straight_left': (self.__is_time_correct,),\n 'straight_right': (self.__is_time_correct,),\n 'rotate_left_by_speed':\n (self.__is_speed_correct,),\n 'rotate_right_by_speed':\n (self.__is_speed_correct,),\n 'diagonal_forward_left':\n (self.__is_time_correct,),\n 'diagonal_forward_right':\n (self.__is_time_correct,),\n 'diagonal_backward_left':\n (self.__is_time_correct,),\n 'diagonal_backward_right':\n (self.__is_time_correct,),\n 'head_up': (),\n 'head_down': (),\n 'head_middle':(),\n 'rotate_left_by_20_degree': (),\n 'rotate_right_by_20_degree': (),\n 'capture_image': (),\n 'wait': (self.__is_time_correct,),}\n\n def syntax(self):\n line_number = 0 # line counter\n\n if self.__address[0] != 'address' or not self.__is_ip_correct(\n self.__address[1]):\n print 'Syntax error\\naddress should be first'\n return False\n\n for command in self.__commands: # for all commands check parameters\n line_number += 1\n\n # checking if command is available\n try:\n test_func = self.__available_commands[command.get_name()]\n except:\n print 'Syntax error\\nline ' + str(line_number)\n return False\n\n params_count = len(command.get_params())\n\n # if count of test functions not equal count of parameters then\n # it is error\n if len(test_func) != params_count:\n print 'Syntax error\\nline ' + str(line_number)\n return False\n\n # checking all parameters the correctness\n for test, command in zip(test_func, command.get_params()):\n if not test(command):\n print 'Syntax error\\nline ' + str(line_number)\n return False\n\n print 'Syntax test OK'\n return True\n\n def __is_speed_correct(self, speed):\n speed = int(speed)\n\n if (speed <= 0) or (speed > 10):\n return False\n\n return True\n\n def __is_time_correct(self, time):\n time = int(time)\n\n if time <= 0:\n return False\n\n return True\n\n def ping(self):\n # command = self.__commands.get(0)\n # checking if first command is a address\n if self.__address[0] != 'address':\n print 'Ping error\\nFile syntax error\\naddress keyword not found'\n return False\n\n # checking ip address the correctness\n ip = self.__address[1]\n if not self.__is_ip_correct(ip):\n print 'Ping error\\nBad address'\n return False\n\n # send request to rovio\n with HTTPRequests(ip) as con:\n ping, battery = con.ping()\n\n if not ping:\n return False\n\n print 'Ping test OK\\nBattery level: ' + battery\n return True\n\n def __is_ip_correct(self, ip):\n ip = ip.split('.')\n\n if len(ip) != 4:\n return False\n\n for i in ip:\n if int(i) < 0 or int(i) > 255:\n return False\n\n return True\n" }, { "alpha_fraction": 0.5304846167564392, "alphanum_fraction": 0.5330901741981506, "avg_line_length": 28.953125, "blob_id": "454aafbb2562455ddeffa507ce23279143d999fd", "content_id": "0dea647f5261e65cf8450e5ac3baa2d01bc104da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1919, "license_type": "no_license", "max_line_length": 74, "num_lines": 64, "path": "/utils/utils.py", "repo_name": "inn0kenty/RCARovio", "src_encoding": "UTF-8", "text": "from command import CommandQueue\nimport os\n\n\nclass FileParser(object):\n \"\"\"Parse commands from file to a CommandQueue object\"\"\"\n def __init__(self, file_path):\n self.__file_path = file_path\n self.__commands = CommandQueue()\n\n command_file = open(file_path, 'r')\n self.__address = self.__parse_command(command_file.readline())\n\n for command in command_file:\n if command != '\\n':\n self.__commands.add_command(self.__parse_command(command))\n\n def get_data(self):\n return self.__address, self.__commands\n\n def __parse_command(self, command):\n command = command.strip('\\n')\n command = (' '.join(command.split())).split(' ')\n return command\n\n\nclass Singleton(type):\n _instances = {}\n\n def __call__(cls, *args, **kwargs):\n if cls not in cls._instances:\n cls._instances[cls] = super(Singleton, cls).__call__(\n *args, **kwargs)\n\n return cls._instances[cls]\n\n\nclass Config(object):\n __metaclass__ = Singleton\n\n def __init__(self):\n self.__parameters = {}\n for loc in os.path.abspath(os.curdir), '/etc/rovio':\n try:\n with open(os.path.join(loc, 'rovio.cfg')) as source:\n for param in source:\n key, value = self.__parse_param(param)\n self.__parameters[key] = value\n except IOError:\n pass\n\n def get(self, name):\n if name == 'open':\n return self.__parameters.get(name, 'open')\n elif name == 'resolution':\n return self.__parameters.get(name, '3')\n\n def __parse_param(self, param):\n param = param.strip('\\n')\n param = param.split(':')\n param[0] = ''.join(param[0].split())\n param[1] = param[1].strip(' ')\n #param = (''.join(param.split())).split(':')\n return param\n\n\n" } ]
9
leoribeiro/s2v
https://github.com/leoribeiro/s2v
66d36d4f4471f353118bf2c0eb791f18c5e5a6a4
6e2b49f74a571044fc8d75c2886a8b666f03dc68
32f90bee59f04d6c038e79e668468ec2754c7b56
refs/heads/master
2020-03-21T15:50:34.017817
2018-06-26T12:33:15
2018-06-26T12:33:15
138,736,149
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6853073239326477, "alphanum_fraction": 0.6892640590667725, "avg_line_length": 26.489051818847656, "blob_id": "bafe7c6339a942b3cc7c6b4fb66da48851cf3f4a", "content_id": "d38bd08ef89794f99045a10bfa8c7400601b6a18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3791, "license_type": "no_license", "max_line_length": 112, "num_lines": 137, "path": "/src/struc2vec.py", "repo_name": "leoribeiro/s2v", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport random,sys,logging\nfrom concurrent.futures import ProcessPoolExecutor, as_completed\nfrom multiprocessing import Manager\nfrom time import time\nfrom collections import deque\n\nfrom utils import *\nfrom algorithms import *\nfrom algorithms_distances import *\nimport graph\n\n\nclass Graph():\n\tdef __init__(self, g, is_directed, workers, K, S):\n\n\t\tlogging.info(\" - Converting graph to dict...\")\n\t\tself.G = g.gToDict()\n\t\tlogging.info(\"Graph converted.\")\n\n\t\tself.num_vertices = g.number_of_nodes()\n\t\tself.num_edges = g.number_of_edges()\n\t\tself.is_directed = is_directed\n\t\tself.workers = workers\n\t\tself.K = K\n\t\tself.S = S\n\t\tlogging.info('Graph - Number of vertices: {}'.format(self.num_vertices))\n\t\tlogging.info('Graph - Number of edges: {}'.format(self.num_edges))\n\n\n\tdef preprocess_neighbors_with_rw(self):\n\n\t\t# with ProcessPoolExecutor(max_workers=self.workers) as executor:\n\t\t# \tjob = executor.submit(exec_rw,self.G,self.workers,self.K,self.S)\n\t\t\t\n\t\t# \tself.degree_list = job.result()\n\n\t\tself.degree_list = exec_rw(self.G,self.workers,self.K,self.S)\n\n\t\treturn\n\n\tdef create_vectors(self):\n\t\tlogging.info(\"Creating degree vectors...\")\n\t\tdegrees = {}\n\t\tdegrees_sorted = set()\n\t\tG = self.G\n\t\tfor v in G.keys():\n\t\t\tdegree = len(G[v])\n\t\t\tdegrees_sorted.add(degree)\n\t\t\tif(degree not in degrees):\n\t\t\t\tdegrees[degree] = {}\n\t\t\t\tdegrees[degree]['vertices'] = deque() \n\t\t\tdegrees[degree]['vertices'].append(v)\n\t\tdegrees_sorted = np.array(list(degrees_sorted),dtype='int')\n\t\tdegrees_sorted = np.sort(degrees_sorted)\n\n\t\tl = len(degrees_sorted)\n\t\tfor index, degree in enumerate(degrees_sorted):\n\t\t\tif(index > 0):\n\t\t\t\tdegrees[degree]['before'] = degrees_sorted[index - 1]\n\t\t\tif(index < (l - 1)):\n\t\t\t\tdegrees[degree]['after'] = degrees_sorted[index + 1]\n\t\tlogging.info(\"Degree vectors created.\")\n\n\t\tself.degrees_vector = degrees\n\n\tdef calc_distances(self):\n\n\t\tfutures = {}\n\t\tresults = {}\n\n\t\tG = self.G\n\t\tnumber_vertices = len(G)\n\n\t\tvertices_ = G.keys()\n\t\tvertices_nbrs = get_neighbors(vertices_,G,self.degrees_vector,number_vertices)\n\t\tchunks_vertices = partition(vertices_,self.workers)\n\n\t\tdistances = {}\n\n\t\twith ProcessPoolExecutor(max_workers = self.workers) as executor:\n\n\t\t\tpart = 0\n\t\t\tfor c in chunks_vertices:\n\t\t\t\t#print c,part\n\t\t\t\t#print \"part\",part\n\t\t\t\t#calc_distances(c, self.degree_list, vertices_nbrs)\n\t\t\t\t\n\t\t\t\tlogging.info(\"Executing part {}...\".format(part))\n\t\t\t\tjob = executor.submit(calc_distances, c, self.degree_list, vertices_nbrs)\n\t\t\t\tfutures[job] = part\n\t\t\t\tpart += 1\n\n\t\t\tlogging.info(\"Receiving results...\")\n\t\t\tfor job in as_completed(futures):\n\t\t\t\tpart = futures[job]\n\t\t\t\tdistances[part] = job.result()\n\t\t\t\tlogging.info(\"Part {} completed.\".format(part))\n\n\n\n\t\tself.distances = distances\n\t\tself.vertices_nbrs = vertices_nbrs\n\t\treturn\n\n\n\tdef create_distances_network(self):\n\t\tchunks_vertices = partition(self.G.keys(),self.workers)\n\n\t\tself.multi_graph,self.alias_method_j,self.alias_method_q,self.amount_neighbours = \\\n\t\tgenerate_distances_network(self.distances,chunks_vertices,self.vertices_nbrs,self.S)\n\n\t\treturn\n\n\n\tdef simulate_walks(self,num_walks,walk_length):\n\n\t\treturn generate_random_walks(num_walks,walk_length,self.workers,\n\t\t\tself.G.keys(),self.multi_graph,\n\t\t\tself.alias_method_j,self.alias_method_q,self.amount_neighbours)\n\n\t\t# for large graphs, it is serially executed, because of memory use.\n\t\t# if(len(self.G) > 500000):\n\n\t\t# \twith ProcessPoolExecutor(max_workers=1) as executor:\n\t\t# \t\tjob = executor.submit(generate_random_walks_large_graphs,num_walks,walk_length,self.workers,self.G.keys())\n\n\t\t# \t\tjob.result()\n\n\t\t# else:\n\n\t\t# \twith ProcessPoolExecutor(max_workers=1) as executor:\n\t\t# \t\tjob = executor.submit(generate_random_walks,num_walks,walk_length,self.workers,self.G.keys())\n\n\t\t# \t\tjob.result()\n\n\n\t\t\t\n\n\n\n\n\n\t\t\n\n \t\n\n\n" }, { "alpha_fraction": 0.5182732343673706, "alphanum_fraction": 0.5333987474441528, "avg_line_length": 25.246780395507812, "blob_id": "a2d36836d940edd115e8bc430f568dc1e790a83b", "content_id": "5e3ea29a660f6f6b618f813d5542042a30fd65f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12237, "license_type": "no_license", "max_line_length": 123, "num_lines": 466, "path": "/src/algorithms_distances.py", "repo_name": "leoribeiro/s2v", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom time import time\nfrom collections import deque\nimport numpy as np\nimport math,logging\nfrom fastdtw import fastdtw\nfrom concurrent.futures import ProcessPoolExecutor, as_completed\nfrom collections import defaultdict\nfrom utils import *\nimport os\n\ndef getRWDegreeListsVertices(g,vertices,K,S):\n degreeList = {}\n\n for v in vertices:\n degreeList[v] = getRWDegreeLists(g,v,K,S)\n #degreeList[v] = getDegreeLists(g,v,S)\n\n return degreeList\n\ndef getDegreeLists(g, root, calcUntilLayer):\n t0 = time()\n\n listas = {}\n vetor_marcacao = [0] * (max(g) + 1)\n\n # Marcar s e inserir s na fila Q\n queue = deque()\n queue.append(root)\n vetor_marcacao[root] = 1\n \n\n l = deque()\n \n ## Variáveis de controle de distância\n depth = 0\n pendingDepthIncrease = 0\n timeToDepthIncrease = 1\n\n while queue:\n vertex = queue.popleft()\n timeToDepthIncrease -= 1\n\n l.append(len(g[vertex]))\n\n for v in g[vertex]:\n if(vetor_marcacao[v] == 0):\n vetor_marcacao[v] = 1\n queue.append(v)\n pendingDepthIncrease += 1 \n\n if(timeToDepthIncrease == 0):\n\n lp = np.array(l,dtype='float')\n lp = np.sort(lp)\n listas[depth] = lp\n l = deque()\n\n if(calcUntilLayer - 1 == depth):\n break\n\n depth += 1\n timeToDepthIncrease = pendingDepthIncrease\n pendingDepthIncrease = 0\n\n\n t1 = time()\n logging.info('BFS vertex {}. Time: {}s'.format(root,(t1-t0)))\n\n\n return listas\n\ndef getRWDegreeLists(g,root,K,S):\n t0 = time()\n\n listas = {}\n paths = {}\n #print K,S\n \n for k in range(0,K):\n v = root\n path = deque()\n d = len(g[v])\n path.append(d)\n while len(path) < S:\n idx = np.random.randint(d)\n v = g[v][idx]\n d = len(g[v])\n path.append(d)\n paths[k] = path\n \n for s in range(0,S):\n l = []\n for k in range(0,K):\n l.append(paths[k][s])\n l = np.array(l,dtype='float')\n l = np.sort(l)\n listas[s] = np.array(l,dtype=np.int32)\n\n t1 = time()\n logging.info('RW vertex {}. Time: {}s'.format(root,(t1-t0)))\n\n return listas\n\ndef cost(a,b):\n ep = 0.5\n m = max(a,b) + ep\n mi = min(a,b) + ep\n return ((m/mi) - 1)\n\ndef cost_min(a,b):\n ep = 0.5\n m = max(a[0],b[0]) + ep\n mi = min(a[0],b[0]) + ep\n return ((m/mi) - 1) * min(a[1],b[1])\n\n\ndef cost_max(a,b):\n ep = 0.5\n m = max(a[0],b[0]) + ep\n mi = min(a[0],b[0]) + ep\n return ((m/mi) - 1) * max(a[1],b[1])\n\ndef verifyDegrees(degrees,degree_v_root,degree_a,degree_b):\n\n if(degree_b == -1):\n degree_now = degree_a\n elif(degree_a == -1):\n degree_now = degree_b\n elif(abs(degree_b - degree_v_root) < abs(degree_a - degree_v_root)):\n degree_now = degree_b\n else:\n degree_now = degree_a\n\n return degree_now \n\ndef get_vertices(v,degree_v,degrees,a_vertices):\n a_vertices_selected = 2 * math.log(a_vertices,2)\n #logging.info(\"Selecionando {} próximos ao vértice {} ...\".format(int(a_vertices_selected),v))\n vertices = deque()\n\n try:\n c_v = 0 \n\n for v2 in degrees[degree_v]['vertices']:\n if(v != v2):\n vertices.append(v2)\n c_v += 1\n if(c_v > a_vertices_selected):\n raise StopIteration\n\n if('before' not in degrees[degree_v]):\n degree_b = -1\n else:\n degree_b = degrees[degree_v]['before']\n if('after' not in degrees[degree_v]):\n degree_a = -1\n else:\n degree_a = degrees[degree_v]['after']\n if(degree_b == -1 and degree_a == -1):\n raise StopIteration\n degree_now = verifyDegrees(degrees,degree_v,degree_a,degree_b)\n\n while True:\n for v2 in degrees[degree_now]['vertices']:\n if(v != v2):\n vertices.append(v2)\n c_v += 1\n if(c_v > a_vertices_selected):\n raise StopIteration\n\n if(degree_now == degree_b):\n if('before' not in degrees[degree_b]):\n degree_b = -1\n else:\n degree_b = degrees[degree_b]['before']\n else:\n if('after' not in degrees[degree_a]):\n degree_a = -1\n else:\n degree_a = degrees[degree_a]['after']\n \n if(degree_b == -1 and degree_a == -1):\n raise StopIteration\n\n degree_now = verifyDegrees(degrees,degree_v,degree_a,degree_b)\n\n except StopIteration:\n #logging.info(\"Vértice {} - próximos selecionados.\".format(v))\n return list(vertices)\n\n return list(vertices)\n\n\ndef get_neighbors(list_vertices,G,degrees,number_vertices):\n\n vertices = {}\n \n for v in list_vertices:\n nbs = get_vertices(v,len(G[v]),degrees,number_vertices)\n vertices[v] = nbs\n\n return vertices\n\n\ndef calc_distances(vertices,degree_list,vertices_nbrs):\n\n distances = []\n\n dist_func = cost\n\n for v1 in vertices:\n #print v1,\"->\",\n lists_v1 = degree_list[v1]\n nbs = vertices_nbrs[v1]\n\n max_layer = len(degree_list[v1])\n\n for v2 in nbs:\n t00 = time()\n #print v2,\n #if(v1 == 11):\n # print \"v1\",v1,\"v2\",v2,\" -> \",\n for layer in range(max_layer):\n #t00 = time()\n lists_v2 = degree_list[v2]\n \n dist, path = fastdtw(lists_v1[layer],lists_v2[layer],radius=1,dist=dist_func)\n\n if(layer > 0):\n f_dist = distances[-1]\n dist = np.float32(dist + f_dist)\n #if(v1 == 11):\n # print layer,dist,\n distances.append(dist)\n\n t11 = time()\n logging.info('fastDTW between vertices ({}, {}). Time: {}s'.format(v1,v2,(t11-t00)))\n #if(v1 == 11):\n # print \"#\"\n return distances\n\n\ndef selectVertices(layer,fractionCalcDists):\n previousLayer = layer - 1\n\n logging.info(\"Recovering distances from disk...\")\n distances = restoreVariableFromDisk('distances')\n\n threshold = calcThresholdDistance(previousLayer,distances,fractionCalcDists)\n\n logging.info('Selecting vertices...')\n\n vertices_selected = deque()\n\n for vertices,layers in distances.iteritems():\n if(previousLayer not in layers):\n continue\n if(layers[previousLayer] <= threshold):\n vertices_selected.append(vertices)\n\n distances = {}\n\n logging.info('Vertices selected.')\n\n return vertices_selected\n\n\ndef exec_rw(G,workers,K,S):\n\n futures = {}\n degreeList = {}\n\n t0 = time()\n vertices = G.keys()\n parts = workers\n chunks = partition(vertices,parts)\n\n with ProcessPoolExecutor(max_workers=workers) as executor:\n\n part = 1\n for c in chunks:\n #dl = getRWDegreeListsVertices(G,c,K,S)\n #degreeList.update(dl)\n job = executor.submit(getRWDegreeListsVertices,G,c,K,S)\n futures[job] = part\n part += 1\n\n for job in as_completed(futures):\n dl = job.result()\n v = futures[job]\n degreeList.update(dl)\n\n #logging.info(\"Saving degreeList on disk...\")\n #saveVariableOnDisk(degreeList,'degreeList')\n t1 = time()\n logging.info('Execution time - RW BFS: {}m'.format((t1-t0)/60))\n\n\n return degreeList\n\n\ndef generate_parameters_random_walk(multi_graph):\n\n sum_weights = {}\n amount_edges = {}\n\n for v in multi_graph.keys():\n\n max_layer = multi_graph[v].shape[0] - 1\n for layer,weights in enumerate(multi_graph[v]):\n\n if(layer >= max_layer):\n break\n\n if(layer not in sum_weights):\n sum_weights[layer] = 0\n amount_edges[layer] = 0\n \n sum_weights[layer] += np.sum(weights)\n amount_edges[layer] += len(weights)\n\n average_weight = {}\n for layer in sum_weights.keys():\n average_weight[layer] = sum_weights[layer] / amount_edges[layer]\n\n\n amount_neighbours = {}\n for v in multi_graph.keys():\n\n max_layer = multi_graph[v].shape[0] - 1\n for layer,weights in enumerate(multi_graph[v]):\n\n if(layer >= max_layer):\n break\n\n if(layer not in amount_neighbours):\n amount_neighbours[layer] = {}\n\n amount_neighbours[layer][v] = 0\n\n for w in weights:\n if(w > average_weight[layer]):\n amount_neighbours[layer][v] += 1\n\n return amount_neighbours\n\ndef generate_multi_graph(all_distances,chunks_vertices,vertices_nbrs,max_layer):\n\n multi_graph = {}\n\n for index,vertices in enumerate(chunks_vertices): \n distances = all_distances[index]\n cont_distance = 0\n #print vertices,index\n\n for v1 in vertices:\n \n #print v1,\"->\",\n nbs = vertices_nbrs[v1]\n multi_graph[v1] = np.full((max_layer+1,len(nbs)), np.inf)\n\n multi_graph[v1][max_layer] = np.array(nbs)\n\n for idx,v2 in enumerate(nbs):\n #if(v1 == 13 or v1 == 14):\n # print \"v1\",v1,\"v2\",v2,\" ->\",\n for layer in range(max_layer):\n dist = distances[cont_distance]\n #if(v1 == 14 or v1 == 13):\n # print layer,dist,\" \",\n w = np.exp(-float(dist))\n multi_graph[v1][layer][idx] = w\n cont_distance += 1\n #if(v1 == 13 or v1 == 14):\n # print \" #\"\n \n\n\n #print \"#\"\n\n\n return multi_graph\n\n\ndef generate_multigraph_probabilities(multi_graph):\n\n alias_method_j = {}\n alias_method_q = {} \n\n\n for v in multi_graph.keys():\n\n max_layer = multi_graph[v].shape[0] - 1\n len_nbs = multi_graph[v].shape[1]\n\n alias_method_j[v] = np.full((max_layer,len_nbs), np.inf)\n alias_method_q[v] = np.full((max_layer,len_nbs), np.inf)\n\n for layer,weights in enumerate(multi_graph[v]):\n\n if(layer >= max_layer):\n break\n\n unnormalized_probs = multi_graph[v][layer]\n norm_const = sum(unnormalized_probs)\n\n multi_graph[v][layer] = \\\n np.array([float(u_prob)/norm_const for u_prob in unnormalized_probs])\n\n J, q = alias_setup(multi_graph[v][layer])\n alias_method_j[v][layer] = J\n alias_method_q[v][layer] = q\n\n return multi_graph,alias_method_j,alias_method_q\n\n\ndef generate_distances_network(all_distances,vertices,vertices_nbrs,max_layer):\n t0 = time()\n logging.info('Creating distance network...')\n\n multi_graph = generate_multi_graph(all_distances,vertices,vertices_nbrs,max_layer)\n\n t1 = time()\n t = t1-t0\n logging.info('- Time - part 1: {}s'.format(t))\n\n\n amount_neighbours = generate_parameters_random_walk(multi_graph)\n\n multi_graph,alias_method_j,alias_method_q = generate_multigraph_probabilities(multi_graph)\n \n return multi_graph,alias_method_j,alias_method_q,amount_neighbours\n\n\ndef alias_setup(probs):\n '''\n Compute utility lists for non-uniform sampling from discrete distributions.\n Refer to https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/\n for details\n '''\n K = len(probs)\n q = np.zeros(K)\n J = np.zeros(K, dtype=np.int)\n\n smaller = []\n larger = []\n for kk, prob in enumerate(probs):\n q[kk] = K*prob\n if q[kk] < 1.0:\n smaller.append(kk)\n else:\n larger.append(kk)\n\n while len(smaller) > 0 and len(larger) > 0:\n small = smaller.pop()\n large = larger.pop()\n\n J[small] = large\n q[large] = q[large] + q[small] - 1.0\n if q[large] < 1.0:\n smaller.append(large)\n else:\n larger.append(large)\n\n return J, q\n" }, { "alpha_fraction": 0.6383333206176758, "alphanum_fraction": 0.653333306312561, "avg_line_length": 26.045454025268555, "blob_id": "a1a1281720cc298d2df03cd811333dfd7c3eb8a2", "content_id": "24d3672e0c07980c3c0875ca2a2bb94bce0afacc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 600, "license_type": "no_license", "max_line_length": 95, "num_lines": 22, "path": "/src/utils.py", "repo_name": "leoribeiro/s2v", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom time import time\nimport logging,inspect\nimport cPickle as pickle\nfrom itertools import islice\nimport os.path\n\ndir_f = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n\ndef returnPathStruc2vec():\n return dir_f.replace(\" \",\"\\ \")\n\ndef chunks(data, SIZE=10000):\n it = iter(data)\n for i in xrange(0, len(data), SIZE):\n yield {k:data[k] for k in islice(it, SIZE)}\n\ndef partition(lst, n):\n division = len(lst) / float(n)\n return [ lst[int(round(division * i)): int(round(division * (i + 1)))] for i in xrange(n) ]\n\n return\n\n\n\n\n\n" }, { "alpha_fraction": 0.523196816444397, "alphanum_fraction": 0.5747866034507751, "avg_line_length": 29.812976837158203, "blob_id": "b504fcb84ab9e9f99ca40178048d5f81e0a00ccf", "content_id": "c72904032dd635eb2bcc3dd6427e386b008d38f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8083, "license_type": "no_license", "max_line_length": 757, "num_lines": 262, "path": "/plot_graph.py", "repo_name": "leoribeiro/s2v", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\"\"\"\nSimple demo of a scatter plot.\n\"\"\"\nimport numpy as np\nimport sys\n\nimport pickle\nimport random\nimport argparse\nfrom graph_tool.all import Graph,sfdp_layout,graph_draw\nimport gensim\n#import matplotlib.pyplot as plt\n#import matplotlib.cm as cm\n\nfrom plotly.plotly import image\nfrom plotly.graph_objs import Layout, Font, XAxis, YAxis, Margin, Scatter, Marker, Data, Figure, Annotation, Annotations\n\nimport plotly.plotly as py\npy.sign_in('leonardofribeiro', 'TSFHBCu3kofmY8kOnlT0')\n\n\ndef getColorText(c):\n c = list(c)\n r = c[1] + c[2]\n r = float.fromhex(r)\n g = c[3] + c[4]\n g = float.fromhex(g)\n b = c[5] + c[6]\n b = float.fromhex(b)\n\n if(r*0.299 + g*0.587 + b*0.144) > 186:\n return \"#000000\"\n else:\n return \"#ffffff\"\n\ndef scatter_nodes(pos, labels=None, color=None, opacity=1):\n # pos is the dict of node positions\n # labels is a list of labels of len(pos), to be displayed when hovering the mouse over the nodes\n # color is the color for nodes. When it is set as None the Plotly default color is used\n # size is the size of the dots representing the nodes\n #opacity is a value between [0,1] defining the node color opacity\n L=len(pos[0])\n trace = Scatter(x=[], y=[], mode='markers', marker = dict(\n size = 22,\n #size = 15,\n line = dict(\n width = 0.5,\n color = 'rgb(0, 0, 0)'\n )\n ))\n for k in range(L):\n trace['x'].append(pos[0][k])\n trace['y'].append(pos[1][k])\n attrib=dict(name='', text=labels , hoverinfo='text', opacity=opacity) # a dict of Plotly node attributes\n trace=dict(trace, **attrib)# concatenate the dict trace and attrib\n if color is not None:\n trace['marker']['color']=color\n return trace \n\ndef make_annotations(pos, text, colorVertex, font_size=14, font_color='rgb(25,25,25)'):\n L=len(pos[0])\n if len(text)!=L:\n raise ValueError('The lists pos and text must have the same len')\n annotations = Annotations()\n for k in range(L):\n f = getColorText(colorVertex[k])\n annotations.append(\n Annotation(\n #text=text[k], \n x=pos[0][k], y=pos[1][k],\n xref='x1', yref='y1',\n font=dict(color= f, size=font_size),\n showarrow=False)\n )\n return annotations \n\n\ndef trataCores(dictMap):\n\n colorsVertex = {}\n\n c = ['#9ac974','#b9371d','#66a6f2','#dcc156','#815faa','#dddfe0']\n #c = ['#7CEA61', '#2D6D78', '#CA83E6', '#707EE7', '#12CF6D', '#FF2CF4', '#E4F401', '#8DB1B0', '#28D7A5', '#4A0A40', '#7DC884', '#B3C3EF', '#115FBB', '#A4719F', '#7F7DE1', '#BC6512', '#4822FA', '#E9062D', '#CA96E4', '#BC61B3', '#6B5BE6', '#EF31D1', '#D46033', '#09F25E', '#70490F', '#56F6B4', '#2D7155', '#62BEC7', '#F627CE', '#08888B', '#F8400C', '#4F75C6', '#9505C6', '#418482', '#C071DE', '#A6D606', '#DD7F43', '#667902', '#693192', '#FF1F95', '#833568', '#0142F3', '#C1C401', '#F6FDE7', '#BAE2E8', '#D87B36', '#CCD13B', '#3455CC', '#663A63', '#D56A43', '#A0B3C4', '#DDBBCD', '#574769', '#9C26F9', '#EAF6E4', '#9CC232', '#287602', '#33A0F8', '#21D5A0', '#3430B1', '#482358', '#2CF532', '#A3FFEA', '#B0A3E4', '#20980B', '#2C9744', '#9DA8A5', '#2101C9']\n cont = 0\n for k,v in dictMap.items():\n #r = lambda: random.randint(0,255)\n #t = ('#%02X%02X%02X' % (r(),r(),r()))\n colorsVertex[k] = c[cont]\n colorsVertex[v] = c[cont]\n cont += 1\n\n return colorsVertex\n\ndef trataPosicoes(g,pos,dict_map,labels_vertices_inv):\n\n new_pos = g.new_vertex_property(\"vector<double>\")\n\n for k,v in dict_map.items():\n index = labels_vertices_inv[k]\n vertex_p = g.vertex(index)\n new_pos[vertex_p] = pos[vertex_p]\n\n #index = labels_vertices_inv[v]\n #vertex_s = g.vertex(index)\n \n #n_pos = [pos[vertex_p][0]+20, pos[vertex_p][1]]\n #new_pos[vertex_s] = n_pos \n\n return new_pos\n\ndef mapeiaLabels(g,labels_vertices):\n dict_map_inv = {}\n for v in g.vertices():\n index = g.vertex_index[v]\n label = labels_vertices[v]\n dict_map_inv[label] = index\n return dict_map_inv \n\n\nwhile True:\n\n parser = argparse.ArgumentParser(description='Espelhar grafo.')\n parser.add_argument('--edge-list', nargs='?', required=True,\n help='EdgeList a ser espelhada.')\n parser.add_argument('--dict-map', nargs='?', required=True,\n help='Arquivo para mapeamento dos pares.')\n parser.add_argument('--emb-file', nargs='?', required=True,\n help='Arquivo de embeddings.')\n args = parser.parse_args()\n with open(args.dict_map, 'rb') as handle:\n dict_map = pickle.load(handle)\n\n print (dict_map)\n\n print (\"Carregando arquivo...\")\n\n g = Graph(directed=False)\n\n edgelist = []\n\n with open(args.edge_list) as f:\n for line in f:\n if(line):\n edgelist.append(map(int,line.split()))\n\n labels_vertices = g.add_edge_list(edgelist,hashed=True)\n\n labels_vertices_str = g.new_vertex_property(\"string\")\n for v in g.vertices():\n labels_vertices_str[v] = str(labels_vertices[v])\n\n labels_vertices_inv = mapeiaLabels(g,labels_vertices)\n\n pos = sfdp_layout(g)\n colors = trataCores(dict_map)\n pos_new = trataPosicoes(g,pos,dict_map,labels_vertices_inv)\n\n color = g.new_vertex_property(\"string\")\n\n for v in g.vertices():\n index = g.vertex_index[v]\n label = labels_vertices[v]\n if label not in colors:\n colors[label] = '#0c0cff'\n pos_new[v] = pos[v]\n color[v] = colors[label]\n\n\n vprops = {}\n vprops[\"font_size\"] = 24\n vprops[\"text\"] = labels_vertices_str\n vprops[\"fill_color\"] = color\n\n # #vcmap=cm.nipy_spectral,\n #graph_draw(g,vprops=vprops,pos=pos_new,output=args.emb_file+\"-grafo.png\",output_size=(2048,1024))\n\n # graph_draw(g,vertex_fill_color=color,vertex_text=labels_vertices_str,vertex_font_size=20,\n # pos=pos_new,output=\"grafo.png\",output_size=(2048,1024))\n\n\n #graphviz_draw(g,vcolor=color,vcmap=cm.viridis,vsize=0.3,vprops=vprops, pos=pos_new,output=\"grafo.png\")\n\n #########################\n\n embeddings = gensim.models.KeyedVectors.load_word2vec_format(args.emb_file, binary=False)\n\n x = []\n y = []\n n = []\n colors_graph = []\n for v in g.vertices():\n l = str(labels_vertices[v])\n coords = embeddings[l]\n x.append(coords[0])\n y.append(coords[1])\n n.append(l)\n colors_graph.append(colors[labels_vertices[v]])\n\n # fig, ax = plt.subplots()\n # ax.scatter(x, y,c=colors_graph, s=320,cmap='nipy_spectral')\n\n # for i, txt in enumerate(n):\n\n # xx = str(float(x[i]) - 0.05)\n # yy = str(float(y[i]) - 0.04)\n\n # ax.annotate(txt.zfill(2), (xx,yy),color=\"white\")\n\n #plt.savefig('grafico.png', format='png', dpi=300)\n #plt.show()\n\n width=2048\n height=1024\n axis=dict(showline=True, # hide axis line, grid, ticklabels and title\n zeroline=False,\n showgrid=True,\n showticklabels=True\n )\n layout=Layout(title= '', #\n font= Font(size=20),\n #showlegend=False,\n autosize=True,\n width=width,\n height=height,\n xaxis=XAxis(axis),\n yaxis=YAxis(axis),\n margin=Margin(\n l=55,\n r=20,\n b=40,\n t=10,\n pad=0,\n \n ),\n hovermode='closest',\n #plot_bgcolor='#EFECEA', #set background color \n )\n\n trace2= scatter_nodes([x,y],n,colors_graph)\n\n data=Data([trace2])\n\n fig = Figure(data=data, layout=layout)\n\n #fig['layout'].update(annotations=make_annotations([x,y], n, colors_graph))\n #offline.iplot(fig, filename='tst')\n\n image.save_as(fig,args.emb_file+\"-grafico.png\",scale=3)\n\n a = input('Pressione uma tecla para continuar: ')\n if(a and int(a) == 0):\n break\n\n\n\n'''\ng.vp.vertex_name[v]\ng.vertex_index[v]\ng.vertex(index)\n'''\n\n\n\n\n\n\n " }, { "alpha_fraction": 0.5991689562797546, "alphanum_fraction": 0.6069251894950867, "avg_line_length": 28.590164184570312, "blob_id": "d70c83130c08068ca417d15c97b8b79c7bd05836", "content_id": "9134fd7fb3f67fa47b37d706276ae1a3d3bd260a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3610, "license_type": "no_license", "max_line_length": 145, "num_lines": 122, "path": "/src/algorithms.py", "repo_name": "leoribeiro/s2v", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom time import time\nfrom collections import deque\nimport numpy as np\nimport math,random,logging\nfrom concurrent.futures import ProcessPoolExecutor, as_completed\nimport multiprocessing as mp\nfrom collections import defaultdict\n\nfrom utils import *\n\n\ndef chooseNeighbor(v,graphs,alias_method_j,alias_method_q,layer):\n v_list = graphs[v][-1].astype(int)\n\n idx = alias_draw(alias_method_j[v][layer].astype(int),alias_method_q[v][layer])\n v = v_list[idx]\n\n return v\n\n\ndef exec_random_walk(multi_graph,alias_method_j,alias_method_q,v,walk_length,amount_neighbours):\n root = v\n t0 = time()\n layer = 0\n\n path = []\n path.append(v)\n\n while len(path) < walk_length:\n r = random.random()\n\n if(r < 0.3):\n v = chooseNeighbor(v,multi_graph,alias_method_j,alias_method_q,layer)\n path.append(v)\n\n else:\n r = random.random()\n limiar_moveup = prob_moveup(amount_neighbours[layer][v])\n if(r > limiar_moveup):\n if(layer > 0):\n layer = layer - 1 \n else:\n if((layer + 1) < len(multi_graph[v]) - 1):\n layer = layer + 1\n\n t1 = time()\n logging.info('RW - vertex {}. Time : {}s'.format(root,(t1-t0)))\n\n return path\n\n\ndef exec_ramdom_walks_for_chunck(vertices,multi_graph,alias_method_j,alias_method_q,walk_length,amount_neighbours):\n walks = deque()\n for v in vertices:\n walks.append(exec_random_walk(multi_graph,alias_method_j,alias_method_q,v,walk_length,amount_neighbours))\n return walks\n\ndef generate_random_walks(num_walks,walk_length,workers,vertices,multi_graph,alias_method_j,alias_method_q,amount_neighbours):\n\n logging.info('Loading distances_nets from disk...')\n\n logging.info('Creating RWs...')\n t0 = time()\n \n walks = []\n\n# if(workers > num_walks):\n# workers = num_walks\n#\n# with ProcessPoolExecutor(max_workers=2) as executor:\n# futures = {}\n# for walk_iter in range(num_walks):\n# random.shuffle(vertices)\n# job = executor.submit(exec_ramdom_walks_for_chunck,vertices,multi_graph,alias_method_j,alias_method_q,walk_length,amount_neighbours)\n# futures[job] = walk_iter\n# #part += 1\n# logging.info(\"Receiving results...\")\n# for job in as_completed(futures):\n# walk = job.result()\n# r = futures[job]\n# logging.info(\"Iteration {} executed.\".format(r))\n# walks.extend(walk)\n# del futures[job]\n\n\n# t1 = time()\n# logging.info('RWs created. Time: {}m'.format((t1-t0)/60))\n logging.info(\"Saving Random Walks on disk...\")\n\n for walk_iter in range(num_walks):\n random.shuffle(vertices)\n logging.info(\"Execution iteration {} ...\".format(walk_iter))\n walk = exec_ramdom_walks_for_chunck(vertices,multi_graph,alias_method_j,alias_method_q,walk_length,amount_neighbours)\n walks.extend(walk)\n logging.info(\"Iteration {} executed.\".format(walk_iter))\n\n t1 = time()\n logging.info('RWs created. Time : {}m'.format((t1-t0)/60))\n logging.info(\"Saving Random Walks on disk...\")\n \n return walks\n\n\n\ndef prob_moveup(amount_neighbours):\n x = math.log(amount_neighbours + math.e)\n p = (x / ( x + 1))\n return p\n\n\ndef alias_draw(J, q):\n '''\n Draw sample from a non-uniform discrete distribution using alias sampling.\n '''\n K = len(J)\n\n kk = int(np.floor(np.random.rand()*K))\n if np.random.rand() < q[kk]:\n return kk\n else:\n return J[kk]\n" }, { "alpha_fraction": 0.5448088049888611, "alphanum_fraction": 0.5562897324562073, "avg_line_length": 25.84700584411621, "blob_id": "7611813ebc1be6db45b2e453239a054783921205", "content_id": "9dc2a2e2335a1270f025bcf682fa5238ed155a1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12111, "license_type": "no_license", "max_line_length": 123, "num_lines": 451, "path": "/src/algorithms_distances_old.py", "repo_name": "leoribeiro/s2v", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom time import time\nfrom collections import deque\nimport numpy as np\nimport math,logging\nfrom fastdtw import fastdtw\nfrom concurrent.futures import ProcessPoolExecutor, as_completed\nfrom collections import defaultdict\nfrom utils import *\nimport os\n\ndef getRWDegreeListsVertices(g,vertices,K,S):\n degreeList = {}\n\n for v in vertices:\n degreeList[v] = getRWDegreeLists(g,v,K,S)\n\n return degreeList\n\n\ndef getRWDegreeLists(g,root,K,S):\n t0 = time()\n\n listas = {}\n paths = {}\n #print K,S\n \n for k in range(0,K):\n v = root\n path = deque()\n d = len(g[v])\n path.append(d)\n while len(path) < S:\n idx = np.random.randint(d)\n v = g[v][idx]\n d = len(g[v])\n path.append(d)\n paths[k] = path\n \n for s in range(0,S):\n l = []\n for k in range(0,K):\n l.append(paths[k][s])\n l = np.array(l,dtype='float')\n l = np.sort(l)\n listas[s] = np.array(l,dtype=np.int32)\n\n t1 = time()\n logging.info('RW vertex {}. Time: {}s'.format(root,(t1-t0)))\n\n return listas\n\ndef cost(a,b):\n ep = 0.5\n m = max(a,b) + ep\n mi = min(a,b) + ep\n return ((m/mi) - 1)\n\ndef cost_min(a,b):\n ep = 0.5\n m = max(a[0],b[0]) + ep\n mi = min(a[0],b[0]) + ep\n return ((m/mi) - 1) * min(a[1],b[1])\n\n\ndef cost_max(a,b):\n ep = 0.5\n m = max(a[0],b[0]) + ep\n mi = min(a[0],b[0]) + ep\n return ((m/mi) - 1) * max(a[1],b[1])\n\ndef preprocess_degreeLists():\n\n logging.info(\"Recovering degreeList from disk...\")\n degreeList = restoreVariableFromDisk('degreeList')\n\n logging.info(\"Creating compactDegreeList...\")\n\n dList = {}\n dFrequency = {}\n for v,layers in degreeList.iteritems():\n dFrequency[v] = {}\n for layer,degreeListLayer in layers.iteritems():\n dFrequency[v][layer] = {}\n for degree in degreeListLayer:\n if(degree not in dFrequency[v][layer]):\n dFrequency[v][layer][degree] = 0\n dFrequency[v][layer][degree] += 1\n for v,layers in dFrequency.iteritems():\n dList[v] = {}\n for layer,frequencyList in layers.iteritems():\n list_d = []\n for degree,freq in frequencyList.iteritems():\n list_d.append((degree,freq))\n list_d.sort(key=lambda x: x[0])\n dList[v][layer] = np.array(list_d,dtype='float')\n\n logging.info(\"compactDegreeList created!\")\n\n saveVariableOnDisk(dList,'compactDegreeList')\n\ndef verifyDegrees(degrees,degree_v_root,degree_a,degree_b):\n\n if(degree_b == -1):\n degree_now = degree_a\n elif(degree_a == -1):\n degree_now = degree_b\n elif(abs(degree_b - degree_v_root) < abs(degree_a - degree_v_root)):\n degree_now = degree_b\n else:\n degree_now = degree_a\n\n return degree_now \n\ndef get_vertices(v,degree_v,degrees,a_vertices):\n a_vertices_selected = 2 * math.log(a_vertices,2)\n #logging.info(\"Selecionando {} próximos ao vértice {} ...\".format(int(a_vertices_selected),v))\n vertices = deque()\n\n try:\n c_v = 0 \n\n for v2 in degrees[degree_v]['vertices']:\n if(v != v2):\n vertices.append(v2)\n c_v += 1\n if(c_v > a_vertices_selected):\n raise StopIteration\n\n if('before' not in degrees[degree_v]):\n degree_b = -1\n else:\n degree_b = degrees[degree_v]['before']\n if('after' not in degrees[degree_v]):\n degree_a = -1\n else:\n degree_a = degrees[degree_v]['after']\n if(degree_b == -1 and degree_a == -1):\n raise StopIteration\n degree_now = verifyDegrees(degrees,degree_v,degree_a,degree_b)\n\n while True:\n for v2 in degrees[degree_now]['vertices']:\n if(v != v2):\n vertices.append(v2)\n c_v += 1\n if(c_v > a_vertices_selected):\n raise StopIteration\n\n if(degree_now == degree_b):\n if('before' not in degrees[degree_b]):\n degree_b = -1\n else:\n degree_b = degrees[degree_b]['before']\n else:\n if('after' not in degrees[degree_a]):\n degree_a = -1\n else:\n degree_a = degrees[degree_a]['after']\n \n if(degree_b == -1 and degree_a == -1):\n raise StopIteration\n\n degree_now = verifyDegrees(degrees,degree_v,degree_a,degree_b)\n\n except StopIteration:\n #logging.info(\"Vértice {} - próximos selecionados.\".format(v))\n return list(vertices)\n\n return list(vertices)\n\n\ndef splitDegreeList(part,c,G,degreeList,degrees):\n\n degreeListsSelected = {}\n vertices = {}\n a_vertices = len(G)\n\n for v in c:\n nbs = get_vertices(v,len(G[v]),degrees,a_vertices)\n vertices[v] = nbs\n degreeListsSelected[v] = degreeList[v]\n for n in nbs:\n degreeListsSelected[n] = degreeList[n]\n\n return vertices,degreeListsSelected\n\n\ndef calc_distances(results):\n\n vertices = results[0]\n degreeList = results[1]\n\n distances = {}\n\n dist_func = cost\n\n for v1,nbs in vertices.iteritems():\n lists_v1 = degreeList[v1]\n\n for v2 in nbs:\n t00 = time()\n lists_v2 = degreeList[v2]\n\n max_layer = min(len(lists_v1),len(lists_v2))\n distances[v1,v2] = {}\n\n for layer in range(0,max_layer):\n dist, path = fastdtw(lists_v1[layer],lists_v2[layer],radius=1,dist=dist_func)\n\n distances[v1,v2][layer] = dist\n\n t11 = time()\n logging.info('fastDTW between vertices ({}, {}). Time: {}s'.format(v1,v2,(t11-t00)))\n\n\n preprocess_consolides_distances(distances)\n\n return distances\n\n\ndef selectVertices(layer,fractionCalcDists):\n previousLayer = layer - 1\n\n logging.info(\"Recovering distances from disk...\")\n distances = restoreVariableFromDisk('distances')\n\n threshold = calcThresholdDistance(previousLayer,distances,fractionCalcDists)\n\n logging.info('Selecting vertices...')\n\n vertices_selected = deque()\n\n for vertices,layers in distances.iteritems():\n if(previousLayer not in layers):\n continue\n if(layers[previousLayer] <= threshold):\n vertices_selected.append(vertices)\n\n distances = {}\n\n logging.info('Vertices selected.')\n\n return vertices_selected\n\n\ndef preprocess_consolides_distances(distances, startLayer = 1):\n\n logging.info('Consolidating distances...')\n\n for vertices,layers in distances.iteritems():\n keys_layers = sorted(layers.keys())\n startLayer = min(len(keys_layers),startLayer)\n for layer in range(0,startLayer):\n keys_layers.pop(0)\n\n\n for layer in keys_layers:\n layers[layer] += layers[layer - 1]\n\n logging.info('Distances consolidated.')\n\n\ndef exec_rw(G,workers,K,S):\n\n futures = {}\n degreeList = {}\n\n t0 = time()\n vertices = G.keys()\n parts = workers\n chunks = partition(vertices,parts)\n\n with ProcessPoolExecutor(max_workers=workers) as executor:\n\n part = 1\n for c in chunks:\n #dl = getRWDegreeListsVertices(G,c,K,S)\n #degreeList.update(dl)\n job = executor.submit(getRWDegreeListsVertices,G,c,K,S)\n futures[job] = part\n part += 1\n\n for job in as_completed(futures):\n dl = job.result()\n v = futures[job]\n degreeList.update(dl)\n\n #logging.info(\"Saving degreeList on disk...\")\n #saveVariableOnDisk(degreeList,'degreeList')\n t1 = time()\n logging.info('Execution time - RW BFS: {}m'.format((t1-t0)/60))\n\n\n return degreeList\n\n\n\ndef generate_distances_network_part1(all_distances):\n weights_distances = {}\n for d in all_distances: \n distances = d\n \n for vertices,layers in distances.iteritems():\n for layer,distance in layers.iteritems():\n vx = vertices[0]\n vy = vertices[1]\n if(layer not in weights_distances):\n weights_distances[layer] = {}\n weights_distances[layer][vx,vy] = distance\n graph_weights = {}\n for layer,values in weights_distances.iteritems():\n graph_weights[layer] = values\n\n return graph_weights\n\ndef generate_distances_network_part2(all_distances):\n graphs = {}\n for d in all_distances: \n distances = d\n\n for vertices,layers in distances.iteritems():\n for layer,distance in layers.iteritems():\n vx = vertices[0]\n vy = vertices[1]\n if(layer not in graphs):\n graphs[layer] = {}\n if(vx not in graphs[layer]):\n graphs[layer][vx] = [] \n if(vy not in graphs[layer]):\n graphs[layer][vy] = [] \n graphs[layer][vx].append(vy)\n graphs[layer][vy].append(vx)\n\n graph_layers = {}\n for layer,values in graphs.iteritems():\n graph_layers[layer] = values\n\n return graph_layers\n\ndef generate_distances_network_part3(graph_weights,graph_layers):\n\n alias_method_j = {}\n alias_method_q = {}\n weights = {}\n\n for layer,value in graph_weights.iteritems():\n graphs = graph_layers[layer]\n weights_distances = graph_weights[layer]\n\n logging.info('Executing layer {}...'.format(layer))\n\n alias_method_j[layer] = {}\n alias_method_q[layer] = {} \n weights[layer] = {} \n \n for v,neighbors in graphs.iteritems():\n e_list = deque()\n sum_w = 0.0\n\n\n for n in neighbors:\n if (v,n) in weights_distances:\n wd = weights_distances[v,n]\n else:\n wd = weights_distances[n,v]\n w = np.exp(-float(wd))\n e_list.append(w)\n sum_w += w\n\n e_list = [x / sum_w for x in e_list]\n weights[layer][v] = e_list\n J, q = alias_setup(e_list)\n alias_method_j[layer][v] = J\n alias_method_q[layer][v] = q\n\n\n logging.info('Layer {} executed.'.format(layer))\n\n logging.info('Weights created.')\n\n return weights,alias_method_j,alias_method_q\n\n\n\ndef generate_distances_network(all_distances):\n t0 = time()\n logging.info('Creating distance network...')\n\n graph_weights = generate_distances_network_part1(all_distances)\n\n t1 = time()\n t = t1-t0\n logging.info('- Time - part 1: {}s'.format(t))\n\n t0 = time()\n\n graph_layers = generate_distances_network_part2(all_distances)\n\n t1 = time()\n t = t1-t0\n logging.info('- Time - part 2: {}s'.format(t))\n logging.info('distance network created.')\n\n logging.info('Transforming distances into weights...')\n\n \n\n t0 = time()\n\n weights,alias_method_j,alias_method_q = generate_distances_network_part3(graph_weights,graph_layers)\n\n\n t1 = time()\n t = t1-t0\n logging.info('- Time - part 3: {}s'.format(t))\n \n return graph_layers,weights,alias_method_j,alias_method_q\n\n\ndef alias_setup(probs):\n '''\n Compute utility lists for non-uniform sampling from discrete distributions.\n Refer to https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/\n for details\n '''\n K = len(probs)\n q = np.zeros(K)\n J = np.zeros(K, dtype=np.int)\n\n smaller = []\n larger = []\n for kk, prob in enumerate(probs):\n q[kk] = K*prob\n if q[kk] < 1.0:\n smaller.append(kk)\n else:\n larger.append(kk)\n\n while len(smaller) > 0 and len(larger) > 0:\n small = smaller.pop()\n large = larger.pop()\n\n J[small] = large\n q[large] = q[large] + q[small] - 1.0\n if q[large] < 1.0:\n smaller.append(large)\n else:\n larger.append(large)\n\n return J, q" } ]
6
a-machine-magic/Genre-Classification
https://github.com/a-machine-magic/Genre-Classification
c6661bdd1eb29676a8239d1814ce048fb0e3c780
47e02428e62f1c86b8e75e2dfb8fa84bb3765870
418f9176ece6b97d0cf20b9df50ef466b1c1303c
refs/heads/master
2021-01-24T03:19:48.167731
2018-03-25T14:59:32
2018-03-25T14:59:32
122,884,983
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8260869383811951, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 22, "blob_id": "d8d057ee706f60b1ec652afda45e2e98761817c0", "content_id": "4cb0767127c1b7b0504d2e65dcad3e063601fd56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 23, "license_type": "no_license", "max_line_length": 22, "num_lines": 1, "path": "/README.md", "repo_name": "a-machine-magic/Genre-Classification", "src_encoding": "UTF-8", "text": "# Genre-Classification\n" }, { "alpha_fraction": 0.6152967810630798, "alphanum_fraction": 0.6237950325012207, "avg_line_length": 32.35593032836914, "blob_id": "d6422e6fc2744cc56c749c58816155bf840c2a3b", "content_id": "0a798ba9b8730318b750554dbccf95b6a727cee8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7884, "license_type": "no_license", "max_line_length": 136, "num_lines": 236, "path": "/datawrangler.py", "repo_name": "a-machine-magic/Genre-Classification", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport string\nimport nltk\nimport nltk.corpus\nfrom nltk.corpus import stopwords\nimport gensim\nfrom gensim import corpora, models\nfrom time import gmtime, strftime\nfrom collections import Counter\nimport itertools\nimport pyLDAvis\nimport pyLDAvis.gensim\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud\nimport pickle\n\n\n\n\ndef data_wrangler(texts,tsv):\n \n #access data files \n with open(texts, encoding='utf-8') as text_file:\n lines = text_file.readlines()\n text = [i.split('\\t') for i in lines]\n\n # resolve refrences \n text_dict = {int(iD):texts for iD, texts in text }\n\n # initiate dataframe\n column_names = ['Wiki movie ID', 'Freebase movie ID', 'Movie Name', 'Movie release data', 'Movie box office', 'Movie runtime',\n 'Movie languages', 'Movie Countries', 'Movie Genres']\n \n #populate database\n movie_data_matrix = pd.read_csv(tsv, sep='\\t', names=column_names)\n movie_data_matrix['Text'] = movie_data_matrix['Wiki movie ID'].map(text_dict)\n movie_data_matrix['genre_data'] =[set(eval(i.lower()).values()) for i in movie_data_matrix['Movie Genres']]\n \n print('Intial shape of data %s' %str(movie_data_matrix.shape))\n \n #filter by language and available texts\n movie_data_matrix_english=movie_data_matrix.loc[movie_data_matrix['Movie languages'].str.contains(\"english\", case=False)]\n print('Shape of data for english films %s' %str(movie_data_matrix_english.shape))\n matrix = movie_data_matrix_english.dropna(subset=['Text'])\n print('Shape of data for english films with source text %s' %str(matrix.shape))\n \n corpus = matrix.Text.tolist()\n print('Final size of corpus %s' %str(len(corpus)))\n \n #create genre_labels \n genre_distribution = Counter(itertools.chain(*matrix['genre_data']))\n del genre_distribution['drama']\n del genre_distribution['comedy'] \n \n matrix = matrix.dropna(subset=['genre_data'])\n \n \n matrix['labels'] = [sorted(list((genre_distribution[x],x) for x in genre), reverse=True)[:1]\n for genre in matrix['genre_data']]\n print('Shape of data for english films with source text and genre labels %s' %str(matrix.shape))\n \n return movie_data_matrix,matrix,corpus\n\n\ndef preprocessed_data(corpus):\n \n stop_words1 = stopwords.words('english')\n \n with open('name_stopwords.tsv') as text_file:\n stop_words2 = text_file.read().lower().replace(',', \" \").split()\n \n stop_words3 = [i.lower() for i in nltk.corpus.names.words()]\n \n stopwords_theta= set(stop_words1+stop_words2+stop_words3)\n ########################################################################\n punctuation = list(string.punctuation)\n keep_punctuation = [\"'\", \"-\"]\n \n global punctuation_beta\n punctuation_beta=set(punctuation) - set(keep_punctuation)\n ########################################################################\n \n tokenize = lambda x:x.lower().replace('.', \" \").replace(',', \" \").replace('\"', \" \").split()\n tokenized_corpus = [list(tokenize(i)) for i in corpus]\n \n cleaned_documents=[list(token for token in document \n if not any(p in token for p in punctuation_beta) and\n token not in (stopwords_theta or punctuation_beta)) \n for document in tokenized_corpus]\n\n\n pickle.dump(cleaned_documents, open( \"cleaned_documents.p\", \"wb\" ) )\n \n return cleaned_documents\n\ndef LDA_Model(tokenized_documents, topics, passes_value):\n dictionary=corpora.Dictionary(tokenized_documents)\n corpus = [dictionary.doc2bow(text) for text in tokenized_documents]\n ldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics=topics, id2word = dictionary, passes=passes_value)\n return ldamodel, corpus, dictionary\n\ndef topic_items(LDA_model, num_words):\n legend ={}\n for i in LDA_model.show_topics(num_topics=LDA_model.num_topics,num_words=num_words, formatted=False):\n key = [j for j,_ in i[1]]\n# print (i[0], [j for j,_ in i[1]])\n legend[i[0]] = key\n return legend\n\n\ndef visuzalization (ldamodel, corpus, dictionary, num_words):\n viz=pyLDAvis.gensim.prepare(ldamodel, corpus, dictionary)\n legend=topic_items(ldamodel, 15)\n \n for i, (k,v) in enumerate(legend.items()):\n plt.figure()\n plt.imshow(WordCloud(background_color=\"white\").fit_words(ldamodel.show_topic(k, num_words)))\n plt.axis(\"off\")\n plt.title(\"Topic #\" + str(k+1))\n plt.show()\n \n display=pyLDAvis.display(viz)\n \n return display\n\ndef original_modeled_documents(data, dataframe, ldamodel, dictionary, num_topics):\n save = False\n \n topics = []\n exclude = set()\n \n legend=topic_items(ldamodel,15)\n \n for i,d in enumerate(data):\n document_topics=ldamodel[dictionary.doc2bow(d)]\n sorted_topics=sorted(document_topics, reverse=True, key = lambda x :x[1])[:num_topics]\n top_topics=[j for j,_ in sorted_topics]\n theme = [legend[t] for t in top_topics if t not in exclude]\n topics.append(theme)\n \n dataframe['Topics'] = topics\n \n if save:\n LL = dataframe.sort_values('Movie Name', ascending=True)\n LL.to_csv('[email protected]') \n return dataframe\n\n\ndef data_wrangler_film2():\n import os\n path = \"/Users/ViVeri/Desktop/Wave/imsdb_raw_nov_2015\"\n name = []\n \n filenames = []\n text = []\n for root, dirs, files in os.walk(path):\n for file in files:\n if file.endswith(\".txt\"):\n \n\n name.append(file)\n filenames.append(os.path.join(root, file))\n\n for i in filenames:\n with open(i) as inputfile:\n text.append(inputfile.read())\n \n# tk_corpus = [i.lower().split() for i in corpus] \n\n labels =[os.path.dirname(i).split('/')[-1] for i in filenames]\n \n corpus=preprocessed_data(text)\n\n M2=pd.DataFrame()\n M2['name']= name\n M2['genre'] = labels\n M2['text'] = text\n M2['corpus'] = corpus\n\n\n pickle.dump(M2, open( \"M2.p\", \"wb\" ) )\n\n\n return M2\n\ndef new_modeled_documents(new_data,names, labels, ldamodel, dictionary, ):\n \n save = False\n \n topics =[]\n themes = []\n\n exclude = set([24,21, 29,12])\n\n legend=topic_items(ldamodel,15)\n \n for i,d in enumerate(new_data):\n document_topics=ldamodel[dictionary.doc2bow(d)]\n sorted_documents=sorted(document_topics, reverse=True, key = lambda x :x[1])[:7]\n top_topics=[j for j,_ in sorted_documents]\n theme_id = [t for t in top_topics if t not in exclude]\n theme= [legend[t] for t in top_topics if t not in exclude]\n topics.append(theme_id)\n themes.append(theme)\n \n M=pd.DataFrame()\n M['Names'] = names\n M['Genre'] = labels\n M['Topics'] = topics\n M['Themes'] = themes\n\n # for i, j in enumerate(topics):\n # M['topic' + '{:02d}'.format(i+1)] = j \n \n \n if save:\n M.to_csv('[email protected]')\n \n return M\n\ndef load_model(model_file):\n model_=models.ldamodel.LdaModel.load(model_file)\n id2word = gensim.corpora.Dictionary()\n _ = id2word.merge_with(model_.id2word)\n \n return model_ , id2word\n\n \n# U, M, C = datawrangler.data_wrangler('plot_summaries.txt', 'movie.metadata.tsv')\n# data = datawrangler.preprocessed_data(C)\n# model_, train_corpus, dictionary =datawrangler.LDA_Model(data, 5, 10)\n# legend=topic_items(model_,15)\n# viz = visuzalization(model_, train_corpus, dictionary, 15)\n# M=original_modeled_documents(data,M,modelo, dictionary, 5) #Matrix contains information on original documents and corresponding topics\n# name, labels, corpus=data_wrangler_film2()\n# R=new_modeled_documents(corpus,name,labels,modelo,id2word)# Matrix contains information on Film2.0 corpus and corresponding topics\n\n\n\n\n\n\n\n\n\n\n\n\n" } ]
2
RichardMinsooGo/Machine_Learning_01_Introduction
https://github.com/RichardMinsooGo/Machine_Learning_01_Introduction
c972a079d5272e674163c9f40cc5a73ddfe3e0f2
43dc90cf3595e00a828c48bb0197f1186ad14a68
b3f3c6710f9f8b52eff6e97808a26fa9352b4863
refs/heads/master
2021-01-07T19:27:40.576385
2020-11-24T02:26:20
2020-11-24T02:26:20
241,797,108
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5263774991035461, "alphanum_fraction": 0.6500586271286011, "avg_line_length": 25.671875, "blob_id": "1718b8a3a9edd6081c89f572d32301d32baa205f", "content_id": "53033a7a20b0982af42edf9467d38d454bbb9917", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1706, "license_type": "no_license", "max_line_length": 86, "num_lines": 64, "path": "/31_TF2_cifar10_beginner_sparse.py", "repo_name": "RichardMinsooGo/Machine_Learning_01_Introduction", "src_encoding": "UTF-8", "text": "import tensorflow as tf\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\ncifar10 = tf.keras.datasets.cifar10\nIMG_SIZE = 32\n\n(X_train, Y_train), (X_test, Y_test) = cifar10.load_data()\n\nprint(X_train.shape[0])\nprint(X_test.shape[0])\n# sys.exit()\n\n# cv2.resize(X_train[i], (IMG_SIZE, IMG_SIZE), interpolation=cv2.INTER_CUBIC)\n\n\nX_train, X_test = X_train / 255.0, X_test / 255.0\n\nprint(Y_train[0:10])\n\n# in the case of Keras or TF2, type shall be [image_size, image_size, 1]\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(IMG_SIZE, IMG_SIZE, 3)),\n tf.keras.layers.Dense(256, activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(10, activation='softmax')\n])\n\nmodel.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\nmodel.fit(X_train, Y_train, epochs=5, verbose=1)\n\nmodel.evaluate(X_test, Y_test, verbose=2) \n\n\"\"\"\nverbose default is 1\n\nverbose=0 (silent)\n\nverbose=1 (progress bar)\n\nTrain on 186219 samples, validate on 20691 samples\nEpoch 1/2\n186219/186219 [==============================] - 85s 455us/step - loss: 0.5815 - acc: \n0.7728 - val_loss: 0.4917 - val_acc: 0.8029\nTrain on 186219 samples, validate on 20691 samples\nEpoch 2/2\n186219/186219 [==============================] - 84s 451us/step - loss: 0.4921 - acc: \n0.8071 - val_loss: 0.4617 - val_acc: 0.8168\n\n\nverbose=2 (one line per epoch)\n\nTrain on 186219 samples, validate on 20691 samples\nEpoch 1/1\n - 88s - loss: 0.5746 - acc: 0.7753 - val_loss: 0.4816 - val_acc: 0.8075\nTrain on 186219 samples, validate on 20691 samples\nEpoch 1/1\n - 88s - loss: 0.4880 - acc: 0.8076 - val_loss: 0.5199 - val_acc: 0.8046\n \n \"\"\"" }, { "alpha_fraction": 0.5577689409255981, "alphanum_fraction": 0.6595838665962219, "avg_line_length": 28.350648880004883, "blob_id": "22769e1ec63cfd01649ab0b8cfb79a33f9c45ebf", "content_id": "59f4a0f06c93ef1714c81a65667b30a7f9d52fcd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2259, "license_type": "no_license", "max_line_length": 101, "num_lines": 77, "path": "/12_TF2_MNIST_categorical_network_modify.py", "repo_name": "RichardMinsooGo/Machine_Learning_01_Introduction", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPool2D, Dropout\nfrom tensorflow.keras import Model, Sequential\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nfrom tensorflow.keras.utils import to_categorical\n\nmnist = tf.keras.datasets.mnist\n\n(X_train, Y_train), (X_test, Y_test) = mnist.load_data()\nX_train, X_test = X_train / 255.0, X_test / 255.0\n\nprint(Y_train[0:10])\n\n# in the case of Keras or TF2, type shall be [image_size, image_size, 1]\n# if it is RGB type, type shall be [image_size, image_size, 3]\n# For MNIST or Fashion MNIST, it need to reshape\nX_train = X_train[..., tf.newaxis]\nX_test = X_test[..., tf.newaxis]\n\nY_train = to_categorical(Y_train, 10)\nY_test = to_categorical(Y_test, 10) \n\nprint(Y_train[0:10])\n\nmodel = Sequential([\n Conv2D(filters=64, kernel_size=3, activation=tf.nn.relu, padding='SAME',input_shape=(28, 28, 1)),\n MaxPool2D(padding='SAME'),\n Conv2D(filters=128, kernel_size=3, activation=tf.nn.relu, padding='SAME'),\n MaxPool2D(padding='SAME'),\n Conv2D(filters=256, kernel_size=3, activation=tf.nn.relu, padding='SAME'),\n MaxPool2D(padding='SAME'),\n Flatten(),\n Dense(256, activation='relu'),\n Dropout(0.2),\n Dense(10, activation='softmax')\n])\nmodel.summary()\n\nmodel.compile(optimizer='adam',\n\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\nmodel.fit(X_train, Y_train, epochs=5, verbose=1)\n\nmodel.evaluate(X_test, Y_test, verbose=2) \n\n\"\"\"\nverbose default is 1\n\nverbose=0 (silent)\n\nverbose=1 (progress bar)\n\nTrain on 186219 samples, validate on 20691 samples\nEpoch 1/2\n186219/186219 [==============================] - 85s 455us/step - loss: 0.5815 - acc: \n0.7728 - val_loss: 0.4917 - val_acc: 0.8029\nTrain on 186219 samples, validate on 20691 samples\nEpoch 2/2\n186219/186219 [==============================] - 84s 451us/step - loss: 0.4921 - acc: \n0.8071 - val_loss: 0.4617 - val_acc: 0.8168\n\n\nverbose=2 (one line per epoch)\n\nTrain on 186219 samples, validate on 20691 samples\nEpoch 1/1\n - 88s - loss: 0.5746 - acc: 0.7753 - val_loss: 0.4816 - val_acc: 0.8075\nTrain on 186219 samples, validate on 20691 samples\nEpoch 1/1\n - 88s - loss: 0.4880 - acc: 0.8076 - val_loss: 0.5199 - val_acc: 0.8046\n \n \"\"\"" }, { "alpha_fraction": 0.6015645861625671, "alphanum_fraction": 0.6239546537399292, "avg_line_length": 34.644229888916016, "blob_id": "cea07b0331b9773f133a3136ad497257b2976033", "content_id": "3ca979f3f6183c3d6ba565678edaffb137a338a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3913, "license_type": "no_license", "max_line_length": 122, "num_lines": 104, "path": "/21_TF2_MNIST_expert_sequential_sparse.py", "repo_name": "RichardMinsooGo/Machine_Learning_01_Introduction", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPool2D, Dropout\nfrom tensorflow.keras import Model, Sequential\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n# print(tf.__version__)\n## MNIST Dataset #########################################################\nmnist = tf.keras.datasets.mnist\n# class_names = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n##########################################################################\n\n## Fashion MNIST Dataset #################################################\n# mnist = tf.keras.datasets.fashion_mnist\n# class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\n##########################################################################\n(X_train, Y_train), (X_test, Y_test) = mnist.load_data() \n\n# Change data type as float. If it is unt type, it might cause error \nX_train, X_test = X_train / 255.0, X_test / 255.0\n\nprint(Y_train[0:10])\n\nprint(X_train.shape)\n\n# in the case of Keras or TF2, type shall be [image_size, image_size, 1]\n# if it is RGB type, type shall be [image_size, image_size, 3]\n# For MNIST or Fashion MNIST, it need to reshape\nX_train = X_train[..., tf.newaxis]\nX_test = X_test[..., tf.newaxis]\n\nprint(X_train.shape)\n\nbatch_size = 1000\n# 입력된 buffer_size만큼 data를 채우고 무작위로 sampling하여 새로운 data로 바꿉니다.\n# 완벽한 셔플링을 위해서는 데이터 세트의 전체 크기보다 크거나 같은 버퍼 크기가 필요합니다.\n# 만약 작은 데이터수보다 작은 buffer_size를 사용할경우,\n# 처음에 설정된 buffer_size만큼의 data안에서 임의의 셔플링이 발생합니다.\nshuffle_size = 100000\n\ntrain_ds = tf.data.Dataset.from_tensor_slices(\n (X_train, Y_train)).shuffle(shuffle_size).batch(batch_size)\ntest_ds = tf.data.Dataset.from_tensor_slices((X_test, Y_test)).batch(batch_size)\n\nmodel = Sequential([\n Conv2D(filters=64, kernel_size=3, activation=tf.nn.relu, padding='SAME',input_shape=(28, 28, 1)),\n MaxPool2D(padding='SAME'),\n Conv2D(filters=128, kernel_size=3, activation=tf.nn.relu, padding='SAME'),\n MaxPool2D(padding='SAME'),\n Conv2D(filters=256, kernel_size=3, activation=tf.nn.relu, padding='SAME'),\n MaxPool2D(padding='SAME'),\n Flatten(),\n Dense(256, activation='relu'),\n Dropout(0.2),\n Dense(10, activation='softmax')\n])\n\nmodel.summary()\n\nloss_object = tf.keras.losses.SparseCategoricalCrossentropy()\n\noptimizer = tf.keras.optimizers.Adam()\n\ntrain_loss = tf.keras.metrics.Mean(name='train_loss')\ntrain_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')\n\ntest_loss = tf.keras.metrics.Mean(name='test_loss')\ntest_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')\n\[email protected]\ndef train_step(images, labels):\n with tf.GradientTape() as tape:\n predictions = model(images)\n loss = loss_object(labels, predictions)\n gradients = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\n train_loss(loss)\n train_accuracy(labels, predictions)\n\[email protected]\ndef test_step(images, labels):\n predictions = model(images)\n t_loss = loss_object(labels, predictions)\n\n test_loss(t_loss)\n test_accuracy(labels, predictions)\n\nEPOCHS = 5\n\nfor epoch in range(EPOCHS):\n for images, labels in train_ds:\n train_step(images, labels)\n\n for test_images, test_labels in test_ds:\n test_step(test_images, test_labels)\n\n template = 'epoch: {:>5,d}, loss: {:>2.4f}, accuracy: {:>2.3f}%, test loss: {:>2.4f}, test accuracy: {:>2.3f}%'\n print (template.format(epoch+1,\n train_loss.result(),\n train_accuracy.result()*100,\n test_loss.result(),\n test_accuracy.result()*100))\n" } ]
3
richardpanda/todo-api
https://github.com/richardpanda/todo-api
351ce91feea2124a2e2646ddd554c7ab582adec7
40ee3cc3fa96fc58fa6721e92a057c01ac938273
1a4d5827bb6a4139874b0fca84ec3b59a98bf826
refs/heads/master
2020-03-16T17:54:32.617815
2018-05-17T01:42:13
2018-05-17T01:42:13
132,851,715
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6179534196853638, "alphanum_fraction": 0.6234681606292725, "avg_line_length": 37.400001525878906, "blob_id": "4444ae36f10d0ccaa03467c8d25bb4d9c56b6f72", "content_id": "603933d44c5dc391c3db1d85205936b747834892", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3264, "license_type": "permissive", "max_line_length": 84, "num_lines": 85, "path": "/tests/test_signup.py", "repo_name": "richardpanda/todo-api", "src_encoding": "UTF-8", "text": "import unittest\n\nfrom app import create_app, db\nfrom app.models import User\nfrom config import TestingConfig\n\n\nclass SignUpTests(unittest.TestCase):\n def setUp(self):\n self.app = create_app(TestingConfig)\n self.client = self.app.test_client()\n self.app_context = self.app.app_context()\n self.app_context.push()\n db.create_all()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n self.app_context.pop()\n\n def test_signup(self):\n password = 'password'\n request_body = {'username': 'johndoe',\n 'password': password, 'password_confirm': password}\n response = self.client.post('/api/signup', json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 201)\n self.assertIsNotNone(response_body['token'])\n\n user = db.session.query(User).first()\n self.assertNotEqual(user.hash, password)\n\n def test_signup_without_username(self):\n password = 'password'\n request_body = {'password': password, 'password_confirm': password}\n response = self.client.post('/api/signup', json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response_body['message'], 'Username is missing.')\n\n def test_signup_without_password(self):\n request_body = {'username': 'johndoe', 'password_confirm': 'password'}\n response = self.client.post('/api/signup', json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response_body['message'], 'Password is missing.')\n\n def test_signup_without_password_confirm(self):\n request_body = {'username': 'johndoe', 'password': 'password'}\n response = self.client.post('/api/signup', json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response_body['message'],\n 'Password confirm is missing.')\n\n def test_signup_with_mismatch_password_and_password_confirm(self):\n request_body = {'username': 'johndoe',\n 'password': 'password', 'password_confirm': 'mismatch password'}\n response = self.client.post('/api/signup', json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 400)\n self.assertEqual(\n response_body['message'], 'Password and password confirm do not match.')\n\n def test_signup_with_username_already_registered(self):\n username = 'johndoe'\n password = 'password'\n\n user = User(username=username, password=password)\n db.session.add(user)\n db.session.commit()\n\n request_body = {'username': username,\n 'password': password, 'password_confirm': password}\n response = self.client.post('/api/signup', json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response_body['message'],\n 'Username is already taken.')\n" }, { "alpha_fraction": 0.6235154271125793, "alphanum_fraction": 0.6359857320785522, "avg_line_length": 34.82978820800781, "blob_id": "b7db10ca4e8836b7943fbca29ff42e57be22a39f", "content_id": "01d9728eb45f127496292c19f016a8e62c8e5021", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1684, "license_type": "permissive", "max_line_length": 78, "num_lines": 47, "path": "/tests/test_get_todos.py", "repo_name": "richardpanda/todo-api", "src_encoding": "UTF-8", "text": "import unittest\n\nfrom app import create_app, db\nfrom app.models import Todo, User\nfrom config import TestingConfig\n\n\nclass GetTodosTest(unittest.TestCase):\n def setUp(self):\n self.app = create_app(TestingConfig)\n self.client = self.app.test_client()\n self.app_context = self.app.app_context()\n self.app_context.push()\n db.create_all()\n self.user1 = User(username='johndoe', password='password')\n self.user2 = User(username='janedoe', password='password')\n self.todo1 = Todo(text='Finish homework')\n self.todo2 = Todo(text='Exercise')\n self.user1.todos.extend([self.todo1, self.todo2])\n self.user2.todos.append((Todo(text='Mow lawn')))\n db.session.add_all([self.user1, self.user2])\n db.session.commit()\n self.token = self.user1.generate_jwt()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n self.app_context.pop()\n\n def test_get_todos(self):\n headers = {'Authorization': f'Bearer {self.token}'}\n response = self.client.get('/api/todos', headers=headers)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(response_body['todos']), 2)\n\n todo = response_body['todos'][0]\n self.assertEqual(todo['id'], self.todo1.id)\n self.assertEqual(todo['text'], self.todo1.text)\n\n def test_get_todos_without_token(self):\n response = self.client.get('/api/todos')\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 401)\n self.assertEqual(response_body['message'], 'Authentication required.')\n" }, { "alpha_fraction": 0.7463768124580383, "alphanum_fraction": 0.7463768124580383, "avg_line_length": 45, "blob_id": "46a6361ea89ee5faea30027ce648e81ffcead97e", "content_id": "ce136ee2122260fc3d929ec6d002577efe4ade47", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 138, "license_type": "permissive", "max_line_length": 125, "num_lines": 3, "path": "/README.md", "repo_name": "richardpanda/todo-api", "src_encoding": "UTF-8", "text": "# Todo API\n\n[![Build Status](https://travis-ci.org/richardpanda/todo-api.svg?branch=master)](https://travis-ci.org/richardpanda/todo-api)\n" }, { "alpha_fraction": 0.6383273601531982, "alphanum_fraction": 0.6566048264503479, "avg_line_length": 26.150375366210938, "blob_id": "ca13615c66ee2c19b7806a39eb21e5c8aba7728a", "content_id": "33056799f2eed0c0beaa2fc1452cb66a054a9f3b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3611, "license_type": "permissive", "max_line_length": 82, "num_lines": 133, "path": "/app/api.py", "repo_name": "richardpanda/todo-api", "src_encoding": "UTF-8", "text": "from app import db\nfrom flask import Blueprint, current_app, g, jsonify, request\nfrom sqlalchemy import exists\n\nfrom .middleware import token_auth\nfrom .models import Todo, User\n\napi = Blueprint('api', __name__)\n\n\[email protected]('/signin', methods=['POST'])\ndef signin():\n request_body = request.get_json()\n username = request_body.get('username')\n password = request_body.get('password')\n\n if not username:\n return jsonify(message='Username is missing.'), 400\n\n if not password:\n return jsonify(message='Password is missing.'), 400\n\n user = User.query.filter_by(username=username).first()\n\n if not user:\n return jsonify(message='Username does not exist.'), 404\n\n if not user.check_password(password):\n return jsonify(message='Incorrect password.'), 401\n\n return jsonify(token=user.generate_jwt()), 200\n\n\[email protected]('/signup', methods=['POST'])\ndef signup():\n request_body = request.get_json()\n username = request_body.get('username')\n password = request_body.get('password')\n password_confirm = request_body.get('password_confirm')\n\n if not username:\n return jsonify(message='Username is missing.'), 400\n\n if not password:\n return jsonify(message='Password is missing.'), 400\n\n if not password_confirm:\n return jsonify(message='Password confirm is missing.'), 400\n\n if password != password_confirm:\n return jsonify(message='Password and password confirm do not match.'), 400\n\n user_exists = db.session.query(\n exists().where(User.username == username)).scalar()\n\n if user_exists:\n return jsonify(message='Username is already taken.'), 400\n\n user = User(username=username,\n password=password)\n db.session.add(user)\n db.session.commit()\n\n return jsonify(token=user.generate_jwt()), 201\n\n\[email protected]('/todo/<int:todo_id>', methods=['DELETE'])\n@token_auth.login_required\ndef delete_todo(todo_id):\n todo = Todo.query.filter_by(id=todo_id).first()\n\n if not todo:\n return jsonify(message='Todo not found.'), 404\n\n if todo.user_id != g.user_id:\n return jsonify(message='Unauthorized.'), 401\n\n db.session.delete(todo)\n db.session.commit()\n\n return jsonify(), 200\n\n\[email protected]('/todo/<int:todo_id>', methods=['PUT'])\n@token_auth.login_required\ndef update_todo(todo_id):\n request_body = request.get_json()\n text = request_body.get('text')\n is_completed = request_body.get('is_completed')\n\n if is_completed is None:\n return jsonify(message='Completed is missing.'), 400\n\n if not text:\n return jsonify(message='Text is missing.'), 400\n\n todo = Todo.query.filter_by(id=todo_id).first()\n\n if not todo:\n return jsonify(message='Todo not found.'), 404\n\n if todo.user_id != g.user_id:\n return jsonify(message='Unauthorized.'), 401\n\n todo.text = text\n todo.is_completed = is_completed\n db.session.commit()\n\n return jsonify(id=todo_id, text=text, is_completed=is_completed), 200\n\n\[email protected]('/todos', methods=['GET'])\n@token_auth.login_required\ndef get_todos():\n todos = [todo.as_dict()\n for todo in Todo.query.filter_by(user_id=g.user_id)]\n return jsonify(todos=todos), 200\n\n\[email protected]('/todos', methods=['POST'])\n@token_auth.login_required\ndef create_todo():\n request_body = request.get_json()\n text = request_body.get('text')\n\n if not text:\n return jsonify(message='Text is missing.'), 400\n\n todo = Todo(text=text, user_id=g.user_id)\n db.session.add(todo)\n db.session.commit()\n\n return jsonify(id=todo.id, text=todo.text), 201\n" }, { "alpha_fraction": 0.7207792401313782, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 50.33333206176758, "blob_id": "0c5e7ae23d95e7d07400cce230e47ad1ad39f7c6", "content_id": "3f43710fd1f07cb7f2cea4a3fcc4e7a031a297ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 154, "license_type": "permissive", "max_line_length": 73, "num_lines": 3, "path": "/.env.example", "repo_name": "richardpanda/todo-api", "src_encoding": "UTF-8", "text": "JWT_SECRET=\"\"\nDEV_DB_URI=\"postgres://user:password@localhost:5432/todo_api_dev\"\nTESTING_DB_URI=\"postgres://user:password@localhost:5432/todo_api_testing\"\n" }, { "alpha_fraction": 0.6280777454376221, "alphanum_fraction": 0.633693277835846, "avg_line_length": 34.61538314819336, "blob_id": "e3179a2838e1a2f55a247aac8197b2119bb830ad", "content_id": "ec69b9bfc4792a80e40bb47f414c16cdf324d12e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2315, "license_type": "permissive", "max_line_length": 78, "num_lines": 65, "path": "/tests/test_delete_todo.py", "repo_name": "richardpanda/todo-api", "src_encoding": "UTF-8", "text": "import unittest\n\nfrom app import create_app, db\nfrom app.models import Todo, User\nfrom config import TestingConfig\n\n\nclass DeleteTodoTest(unittest.TestCase):\n def setUp(self):\n self.app = create_app(TestingConfig)\n self.client = self.app.test_client()\n self.app_context = self.app.app_context()\n self.app_context.push()\n db.create_all()\n self.user = User(username='johndoe', password='password')\n self.todo = Todo(text='Finish homework')\n self.user.todos.append(self.todo)\n db.session.add(self.user)\n db.session.commit()\n self.token = self.user.generate_jwt()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n self.app_context.pop()\n\n def test_delete_todo(self):\n headers = {'Authorization': f'Bearer {self.token}'}\n response = self.client.delete(\n f'/api/todo/{self.todo.id}', headers=headers)\n\n self.assertEqual(response.status_code, 200)\n\n todo = Todo.query.filter_by(id=self.todo.id).first()\n self.assertIsNone(todo)\n\n def test_delete_todo_without_token(self):\n response = self.client.delete(f'/api/todo/{self.todo.id}')\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 401)\n self.assertEqual(response_body['message'], 'Authentication required.')\n\n def test_delete_todo_with_nonexistent_todo(self):\n headers = {'Authorization': f'Bearer {self.token}'}\n invalid_todo_id = self.todo.id + 1\n response = self.client.delete(\n f'/api/todo/{invalid_todo_id}', headers=headers)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 404)\n self.assertEqual(response_body['message'], 'Todo not found.')\n\n def test_delete_todo_with_diff_user(self):\n diff_user = User(username='janedoe', password='password')\n db.session.add(diff_user)\n db.session.commit()\n\n headers = {'Authorization': f'Bearer {diff_user.generate_jwt()}'}\n response = self.client.delete(\n f'/api/todo/{self.todo.id}', headers=headers)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 401)\n self.assertEqual(response_body['message'], 'Unauthorized.')\n" }, { "alpha_fraction": 0.7419354915618896, "alphanum_fraction": 0.7419354915618896, "avg_line_length": 21.545454025268555, "blob_id": "dc71fa634ba409261693a35ce33a24cedbfbe0eb", "content_id": "933a255d255e3b3e437d4a63f01d1aff20f43979", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 248, "license_type": "permissive", "max_line_length": 44, "num_lines": 11, "path": "/todo_api.py", "repo_name": "richardpanda/todo-api", "src_encoding": "UTF-8", "text": "from app import create_app, db\nfrom app.models import Todo, User\nfrom flask_migrate import Migrate\n\napp = create_app()\nmigrate = Migrate(app, db)\n\n\[email protected]_context_processor\ndef make_shell_context():\n return dict(db=db, Todo=Todo, User=User)\n" }, { "alpha_fraction": 0.6225740313529968, "alphanum_fraction": 0.6271705627441406, "avg_line_length": 33.96428680419922, "blob_id": "f3eef44b3706c91890575bfc9c106bb14c3f37b1", "content_id": "2ebc40392b7852040d49cf4fdf1a27347f8f3afe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1958, "license_type": "permissive", "max_line_length": 78, "num_lines": 56, "path": "/tests/test_create_todo.py", "repo_name": "richardpanda/todo-api", "src_encoding": "UTF-8", "text": "import unittest\n\nfrom app import create_app, db\nfrom app.models import Todo, User\nfrom config import TestingConfig\n\n\nclass CreateTodoTests(unittest.TestCase):\n def setUp(self):\n self.app = create_app(TestingConfig)\n self.client = self.app.test_client()\n self.app_context = self.app.app_context()\n self.app_context.push()\n db.create_all()\n self.user = User(username='johndoe', password='password')\n db.session.add(self.user)\n db.session.commit()\n self.token = self.user.generate_jwt()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n self.app_context.pop()\n\n def test_create_todo(self):\n headers = {'Authorization': f'Bearer {self.token}'}\n text = 'Make bed'\n request_body = {'text': text}\n response = self.client.post(\n '/api/todos', headers=headers, json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 201)\n\n todo = Todo.query.filter_by(user_id=self.user.id, text=text).first()\n self.assertEqual(response_body['id'], todo.id)\n self.assertEqual(response_body['text'], todo.text)\n\n def test_create_todo_without_token(self):\n text = 'Make bed'\n request_body = {'text': text}\n response = self.client.post('/api/todos', json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 401)\n self.assertEqual(response_body['message'], 'Authentication required.')\n\n def test_create_todo_without_text(self):\n headers = {'Authorization': f'Bearer {self.token}'}\n request_body = {}\n response = self.client.post(\n '/api/todos', headers=headers, json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response_body['message'], 'Text is missing.')\n" }, { "alpha_fraction": 0.648888885974884, "alphanum_fraction": 0.6562963128089905, "avg_line_length": 32.75, "blob_id": "cbe6eda517c994abd58afdde671875514b88cd20", "content_id": "54dded92299876fee0b0658a1c991007463710de", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1350, "license_type": "permissive", "max_line_length": 110, "num_lines": 40, "path": "/app/models.py", "repo_name": "richardpanda/todo-api", "src_encoding": "UTF-8", "text": "import jwt\n\nfrom app import db\nfrom bcrypt import checkpw, gensalt, hashpw\nfrom flask import current_app\nfrom sqlalchemy.orm import relationship\n\n\nclass Todo(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n text = db.Column(db.String(100))\n is_completed = db.Column(db.Boolean, default=False)\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'))\n\n def __repr__(self):\n return f'<Todo id={self.id} text={self.text} is_completed={self.is_completed} user_id={self.user_id}>'\n\n def as_dict(self):\n return {'id': self.id, 'text': self.text, 'is_completed': self.is_completed}\n\n\nclass User(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(25), unique=True)\n hash = db.Column(db.String(60))\n todos = relationship('Todo', backref='user')\n\n def __init__(self, username, password):\n self.username = username\n self.password = password\n self.hash = hashpw(password.encode(), gensalt()).decode()\n\n def __repr__(self):\n return f'<User id={self.id} username={self.username} hash={self.hash}>'\n\n def check_password(self, password):\n return checkpw(password.encode(), self.hash.encode())\n\n def generate_jwt(self):\n return jwt.encode({'id': self.id}, current_app.config['JWT_SECRET'], algorithm='HS256').decode()\n" }, { "alpha_fraction": 0.6337910890579224, "alphanum_fraction": 0.6400333046913147, "avg_line_length": 36.546875, "blob_id": "fb6cca972710c6cba4e645b3c56984e40b6b9823", "content_id": "e715a334604a01fca90a3d09323443b39e5c59a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2403, "license_type": "permissive", "max_line_length": 78, "num_lines": 64, "path": "/tests/test_signin.py", "repo_name": "richardpanda/todo-api", "src_encoding": "UTF-8", "text": "import unittest\n\nfrom app import create_app, db\nfrom app.models import User\nfrom config import TestingConfig\n\n\nclass SignInTests(unittest.TestCase):\n def setUp(self):\n self.app = create_app(TestingConfig)\n self.client = self.app.test_client()\n self.app_context = self.app.app_context()\n self.app_context.push()\n db.create_all()\n self.user = User(username='johndoe', password='password')\n db.session.add(self.user)\n db.session.commit()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n self.app_context.pop()\n\n def test_signin(self):\n request_body = {'username': self.user.username,\n 'password': self.user.password}\n response = self.client.post('/api/signin', json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 200)\n self.assertIsNotNone(response_body['token'])\n\n def test_signin_without_username(self):\n request_body = {'password': self.user.password}\n response = self.client.post('/api/signin', json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response_body['message'], 'Username is missing.')\n\n def test_signin_without_password(self):\n request_body = {'username': self.user.username}\n response = self.client.post('/api/signin', json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response_body['message'], 'Password is missing.')\n\n def test_signin_with_unregistered_username(self):\n request_body = {'username': 'janedoe', 'password': self.user.password}\n response = self.client.post('/api/signin', json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 404)\n self.assertEqual(response_body['message'], 'Username does not exist.')\n\n def test_signin_with_incorrect_password(self):\n request_body = {'username': self.user.username,\n 'password': 'incorrect password'}\n response = self.client.post('/api/signin', json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 401)\n self.assertEqual(response_body['message'], 'Incorrect password.')\n" }, { "alpha_fraction": 0.6425902843475342, "alphanum_fraction": 0.672478199005127, "avg_line_length": 25.766666412353516, "blob_id": "242db1089034c2bc0d662011d2f45571636002b2", "content_id": "26a8bd34dd75f0ef459a0b46af6fa69548b7e2cb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 803, "license_type": "permissive", "max_line_length": 107, "num_lines": 30, "path": "/migrations/versions/49cd7a5a1015_change_password_to_hash.py", "repo_name": "richardpanda/todo-api", "src_encoding": "UTF-8", "text": "\"\"\"Change password to hash\n\nRevision ID: 49cd7a5a1015\nRevises: b0ac1a366391\nCreate Date: 2018-05-10 19:02:02.138912\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '49cd7a5a1015'\ndown_revision = 'b0ac1a366391'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user', sa.Column('hash', sa.String(length=60), nullable=True))\n op.drop_column('user', 'password')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user', sa.Column('password', sa.VARCHAR(length=60), autoincrement=False, nullable=True))\n op.drop_column('user', 'hash')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6252952218055725, "alphanum_fraction": 0.6302807927131653, "avg_line_length": 39.11579132080078, "blob_id": "cdca303d2a11f2f561c623c057e84c3d1a7b58d7", "content_id": "c097f21fa92cff570f1f0156c96e43672bf53226", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3811, "license_type": "permissive", "max_line_length": 79, "num_lines": 95, "path": "/tests/test_update_todo.py", "repo_name": "richardpanda/todo-api", "src_encoding": "UTF-8", "text": "import unittest\n\nfrom app import create_app, db\nfrom app.models import Todo, User\nfrom config import TestingConfig\n\n\nclass UpdateTodoTest(unittest.TestCase):\n def setUp(self):\n self.app = create_app(TestingConfig)\n self.client = self.app.test_client()\n self.app_context = self.app.app_context()\n self.app_context.push()\n db.create_all()\n self.user = User(username='johndoe', password='password')\n self.todo = Todo(text='Finish homework')\n self.user.todos.append(self.todo)\n db.session.add(self.user)\n db.session.commit()\n self.token = self.user.generate_jwt()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n self.app_context.pop()\n\n def test_update_todo(self):\n headers = {'Authorization': f'Bearer {self.token}'}\n request_body = {'text': 'Exercise', 'is_completed': True}\n response = self.client.put(\n f'/api/todo/{self.todo.id}', headers=headers, json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response_body['id'], self.todo.id)\n self.assertEqual(response_body['text'], 'Exercise')\n self.assertTrue(response_body['is_completed'])\n\n todo = Todo.query.filter_by(id=self.todo.id).first()\n self.assertEqual(todo.text, 'Exercise')\n self.assertTrue(todo.is_completed)\n\n def test_update_todo_without_token(self):\n request_body = {'text': 'Exercise', 'is_completed': True}\n response = self.client.put(\n f'/api/todo/{self.todo.id}', json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 401)\n self.assertEqual(response_body['message'], 'Authentication required.')\n\n def test_update_todo_without_text(self):\n headers = {'Authorization': f'Bearer {self.token}'}\n request_body = {'is_completed': True}\n response = self.client.put(\n f'/api/todo/{self.todo.id}', headers=headers, json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response_body['message'], 'Text is missing.')\n\n def test_update_todo_without_is_completed(self):\n headers = {'Authorization': f'Bearer {self.token}'}\n request_body = {'text': 'Exercise'}\n response = self.client.put(\n f'/api/todo/{self.todo.id}', headers=headers, json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response_body['message'], 'Completed is missing.')\n\n def test_update_todo_with_nonexistent_todo(self):\n headers = {'Authorization': f'Bearer {self.token}'}\n request_body = {'text': 'Exercise', 'is_completed': True}\n invalid_todo_id = self.todo.id + 1\n response = self.client.put(\n f'/api/todo/{invalid_todo_id}', headers=headers, json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 404)\n self.assertEqual(response_body['message'], 'Todo not found.')\n\n def test_update_todo_with_diff_user(self):\n diff_user = User(username='janedoe', password='password')\n db.session.add(diff_user)\n db.session.commit()\n\n headers = {'Authorization': f'Bearer {diff_user.generate_jwt()}'}\n request_body = {'text': 'Exercise', 'is_completed': True}\n response = self.client.put(\n f'/api/todo/{self.todo.id}', headers=headers, json=request_body)\n response_body = response.get_json()\n\n self.assertEqual(response.status_code, 401)\n self.assertEqual(response_body['message'], 'Unauthorized.')\n" }, { "alpha_fraction": 0.6206896305084229, "alphanum_fraction": 0.6746626496315002, "avg_line_length": 22.821428298950195, "blob_id": "897ae06c056cec00daf803f702fe62a4072a8bde", "content_id": "7edd3780bbb1d613f24ad3b230015aff95e5d1a1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 667, "license_type": "permissive", "max_line_length": 81, "num_lines": 28, "path": "/migrations/versions/caf8cbb2bf01_add_is_completed_attribute_to_todo.py", "repo_name": "richardpanda/todo-api", "src_encoding": "UTF-8", "text": "\"\"\"Add is_completed attribute to Todo\n\nRevision ID: caf8cbb2bf01\nRevises: 4c9cb436e212\nCreate Date: 2018-05-12 17:14:14.319321\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'caf8cbb2bf01'\ndown_revision = '4c9cb436e212'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('todo', sa.Column('is_completed', sa.Boolean(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('todo', 'is_completed')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6697761416435242, "alphanum_fraction": 0.6809701323509216, "avg_line_length": 22.30434799194336, "blob_id": "9d7c2ceb2a08bc886b549600d4a2a671ac2e4c4f", "content_id": "b62935a1c9e94a2002ab75d25865621e6b94d35c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 536, "license_type": "permissive", "max_line_length": 74, "num_lines": 23, "path": "/app/middleware.py", "repo_name": "richardpanda/todo-api", "src_encoding": "UTF-8", "text": "import jwt\n\nfrom flask import current_app, g, jsonify\nfrom flask_httpauth import HTTPTokenAuth\n\ntoken_auth = HTTPTokenAuth('Bearer')\n\n\n@token_auth.verify_token\ndef verify_token(token):\n jwt_secret = current_app.config['JWT_SECRET']\n g.jwt_claims = {}\n try:\n g.jwt_claims = jwt.decode(token, jwt_secret, algorithms=['HS256'])\n g.user_id = g.jwt_claims['id']\n except:\n return False\n return True\n\n\n@token_auth.error_handler\ndef token_error():\n return jsonify(message='Authentication required.'), 401\n" }, { "alpha_fraction": 0.5120643377304077, "alphanum_fraction": 0.6997318863868713, "avg_line_length": 15.954545021057129, "blob_id": "dbe6b97c86e0cec5212aac40f12dd1566f5afdee", "content_id": "59e90ac2ed57d1c9b110ca1a230a51eff9731a8c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 373, "license_type": "permissive", "max_line_length": 23, "num_lines": 22, "path": "/requirements.txt", "repo_name": "richardpanda/todo-api", "src_encoding": "UTF-8", "text": "alembic==0.9.9\nbcrypt==3.1.4\ncffi==1.11.5\nclick==6.7\nFlask==1.0.2\nFlask-HTTPAuth==3.2.3\nFlask-Migrate==2.1.1\nFlask-SQLAlchemy==2.3.2\nitsdangerous==0.24\nJinja2==2.10\nMako==1.0.7\nMarkupSafe==1.0\npsycopg2==2.7.4\npsycopg2-binary==2.7.4\npycparser==2.18\nPyJWT==1.6.1\npython-dateutil==2.7.3\npython-dotenv==0.8.2\npython-editor==1.0.3\nsix==1.11.0\nSQLAlchemy==1.2.7\nWerkzeug==0.14.1\n" }, { "alpha_fraction": 0.6517857313156128, "alphanum_fraction": 0.6517857313156128, "avg_line_length": 20.33333396911621, "blob_id": "1ad064a03980dd7a7af6fe679beac80a0f447869", "content_id": "ae9051d6cbac2dfdb6778875e7c06650eadb0b18", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 448, "license_type": "permissive", "max_line_length": 70, "num_lines": 21, "path": "/config.py", "repo_name": "richardpanda/todo-api", "src_encoding": "UTF-8", "text": "import os\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n\nclass Config():\n DEBUG = True\n ENV = 'dev'\n JWT_SECRET = os.getenv('JWT_SECRET', 'secret')\n SQLALCHEMY_DATABASE_URI = os.getenv('DEV_DB_URI', 'sqlite://')\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n TESTING = False\n\n\nclass TestingConfig(Config):\n DEBUG = False\n ENV = 'testing'\n SQLALCHEMY_DATABASE_URI = os.getenv('TESTING_DB_URI', 'sqlite://')\n TESTING = True\n" } ]
16
cmichal/python-social-auth
https://github.com/cmichal/python-social-auth
ecec0d3ed18e47368f24f314b90aabf449997177
42fa2b0e32a3b94ba59ec006435ea9e6644e1ca1
846f4f22c1d07c646d9ec9f9c5b6a454a34bb8d4
refs/heads/master
2021-01-15T11:07:11.559869
2015-12-09T23:35:02
2015-12-09T23:35:02
47,723,633
0
0
null
2015-12-09T22:42:03
2015-12-09T22:42:04
2015-12-09T23:15:09
Python
[ { "alpha_fraction": 0.6074429750442505, "alphanum_fraction": 0.6122449040412903, "avg_line_length": 28.75, "blob_id": "8903522c24df1556d4bc4c59a87b527083cf7831", "content_id": "c90d6fa1f2b4ab69993920fe6ef1ab1ded1b592c", "detected_licenses": [ "BSD-2-Clause", "Python-2.0", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 833, "license_type": "permissive", "max_line_length": 77, "num_lines": 28, "path": "/social/apps/django_app/urls.py", "repo_name": "cmichal/python-social-auth", "src_encoding": "UTF-8", "text": "\"\"\"URLs module\"\"\"\nfrom django import VERSION\nfrom django.conf import settings\nfrom django.conf.urls import url\nfrom social.apps.django_app import views\n\nfrom social.utils import setting_name\n\n\nextra = getattr(settings, setting_name('TRAILING_SLASH'), True) and '/' or ''\n\nurlpatterns = (\n # authentication / association\n url(r'^login/(?P<backend>[^/]+){0}$'.format(extra),\n views.auth,\n name='begin'),\n url(r'^complete/(?P<backend>[^/]+){0}$'.format(extra),\n views.complete,\n name='complete'),\n # disconnection\n url(r'^disconnect/(?P<backend>[^/]+){0}$'.format(extra),\n views.disconnect,\n name='disconnect'),\n url(r'^disconnect/(?P<backend>[^/]+)/(?P<association_id>[^/]+){0}$'\n .format(extra),\n views.disconnect,\n name='disconnect_individual'),\n)\n" }, { "alpha_fraction": 0.6309148073196411, "alphanum_fraction": 0.6340693831443787, "avg_line_length": 36.29411697387695, "blob_id": "8609211d91fb63ffd223ba453d770fb51c4a3e9d", "content_id": "4051d28dd1e35ca7c4c354656f6e96b60dd55b7e", "detected_licenses": [ "BSD-2-Clause", "Python-2.0", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 634, "license_type": "permissive", "max_line_length": 87, "num_lines": 17, "path": "/social/apps/django_app/default/compat.py", "repo_name": "cmichal/python-social-auth", "src_encoding": "UTF-8", "text": "from django import VERSION\n\nif VERSION >= (1, 8):\n from itertools import chain\n\n def get_all_field_names_from_options(opts):\n names = list(set(chain.from_iterable(\n (field.name, field.attname) if hasattr(field, 'attname') else (field.name,)\n for field in opts.get_fields()\n # For complete backwards compatibility, you may want to exclude\n # GenericForeignKey from the results.\n if not (field.many_to_one and field.related_model is None)\n )))\n return names\nelse:\n def get_all_field_names_from_options(opts):\n return opts.get_all_field_names()\n" } ]
2
MijailMain/Kiosk-Mongo
https://github.com/MijailMain/Kiosk-Mongo
d8d1093d9f44e0d15181016e23cbf696b2d3b063
8cfb5f0104d429396a90932bdcdb31bb0a7e5d63
909894cb4adb377d407628742afc8b84c3fc1a77
refs/heads/master
2022-12-08T23:23:26.047820
2020-08-31T06:12:55
2020-08-31T06:12:55
291,611,892
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6414141654968262, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 15.583333015441895, "blob_id": "ecc01ee0c2ff9e8ff17db8500a93bf55b5216b91", "content_id": "c933f050191a45dd84ed1615ead87ab06d6d94e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 198, "license_type": "no_license", "max_line_length": 51, "num_lines": 12, "path": "/Dockerfile", "repo_name": "MijailMain/Kiosk-Mongo", "src_encoding": "UTF-8", "text": "FROM alpine:3.10\n\nRUN apk add --no-cache python3-dev \\\n && pip3 install --upgrate pip3\n\nWORKDIR /code\n\nCOPY . /code\n\nRUN pip3 --no-cache-dir install -r requirements.txt\n\nCMD [\"python3\", \"App.py\"]" }, { "alpha_fraction": 0.7967479825019836, "alphanum_fraction": 0.7967479825019836, "avg_line_length": 60.5, "blob_id": "15ea505c3b45ac3bbe8f1b81f1eeafaccc42737b", "content_id": "6598ae8cb2ae8385a03bf516b59685c20e45ceff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 123, "license_type": "no_license", "max_line_length": 108, "num_lines": 2, "path": "/README.md", "repo_name": "MijailMain/Kiosk-Mongo", "src_encoding": "UTF-8", "text": "# Kiosk-Mongo\nEste Proyecto Permite conectarse a un DB Mongo y mostar la los datos de registro en un servidor web de Flask\n" }, { "alpha_fraction": 0.3709394335746765, "alphanum_fraction": 0.38323089480400085, "avg_line_length": 26.095237731933594, "blob_id": "73d43eb1dd6b071b8f3939979e98b7052171ca91", "content_id": "7bf2720e14cc9a20a9aba760d445cc9bd5773e85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2278, "license_type": "no_license", "max_line_length": 76, "num_lines": 84, "path": "/App.py", "repo_name": "MijailMain/Kiosk-Mongo", "src_encoding": "UTF-8", "text": "# Mongo\nfrom pymongo import MongoClient\n# Flask\nfrom flask import Flask, request\nfrom flask import render_template\nfrom flask import jsonify\n\n# Cors\nfrom flask_cors import CORS\n\n# FecHa\nfrom datetime import date\nfrom datetime import datetime\n\n# Cors access\napp=Flask(__name__)\ncors = CORS(app)\n\nServer = '192.168.100.3'\nServerMongo = '192.168.100.14'\n\n# Setting Mongo\nclient = MongoClient(ServerMongo, username='Admin', password='Admin')\ndb = client['Kiosk']\ncollections = db['Kiosk']\n\nprint (\"/aggregator/length/\")\nprint (\"/aggregator/data/<Id>\")\n\n#//////////////////////////////////////////////////////////////////////////\n# Index\n#//////////////////////////////////////////////////////////////////////////\[email protected]('/')\ndef hello_world():\n\n return render_template('index.html')\n \n\n#***************************************************************************\n#//////////////////////////////////////////////////////////////////////////\n# LOGIN\n#//////////////////////////////////////////////////////////////////////////\n#***************************************************************************\n#######################################\n# Login User\n#######################################\[email protected]('/aggregator/data/<Id>', methods=[ 'Get'])\ndef CustomRule(Id):\n\n print (\" - New Request Aggregator data: \",Id)\n \n # resulT\n Data = []\n value = db.KioskData.count(); \n value2 = db.KioskData.find({}, {\"_id\":0})\n\n print (db)\n print (value)\n\n for registro in value2:\n Data.append(registro)\n\n return jsonify(Data[int(Id)])\n \n#######################################\n# length User\n#######################################\[email protected]('/aggregator/length/', methods=[ 'Get'])\ndef length():\n \n value = db.KioskData.count(); \n print (\" - New Request Aggregator length: \",value)\n\n return jsonify({\"length\": value})\n \n\n\n#***************************************************************************\n#//////////////////////////////////////////////////////////////////////////\n# Host Api\n#//////////////////////////////////////////////////////////////////////////\n#***************************************************************************\nif __name__ == '__main__':\n app.run(host=Server, port=5080, debug=True)\n\n\n" } ]
3
noobul/PythonTraining
https://github.com/noobul/PythonTraining
247126d175a5217b64b5cf8b76aece30c746f13f
d97223c2c31f5db1b3b04bbcc4e607d5a4614db0
75ff68e49d6f360754d5b4d8ae4bceb1856e84c2
refs/heads/main
2023-04-10T23:52:29.037887
2021-04-15T08:04:59
2021-04-15T08:04:59
317,573,511
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6103183031082153, "alphanum_fraction": 0.634467601776123, "avg_line_length": 31.571428298950195, "blob_id": "23b0343c3016bef009e41f4e96f7b516d3083eee", "content_id": "f19aa8b63f134b1289d4a0d04645b96b640a3479", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 911, "license_type": "no_license", "max_line_length": 96, "num_lines": 28, "path": "/Ch11/11-3/employee_test.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "import unittest\nfrom employee import Employee as em\n\nclass TestEmployeeClass(unittest.TestCase):\n \"\"\"Tests for the employee class\"\"\"\n\n def setUp(self):\n \"\"\" Create employees with different raises \"\"\"\n first_name = \"Doe\"\n last_name = \"John\"\n anual_salary = 100000\n self.custom_raise_ammount = 7000\n self.john_doe = em(first_name, last_name, anual_salary)\n self.default_raise = 105000\n self.custom_raise = 107000\n\n def test_default_raise(self):\n \"\"\"Test defau;t raise\"\"\"\n self.john_doe.give_raise()\n self.assertEqual(self.john_doe.give_raise(), self.default_raise)\n\n def test_custom_raise(self):\n \"\"\"Test custom raise\"\"\"\n self.john_doe.give_raise(self.custom_raise)\n self.assertEqual(self.john_doe.give_raise(self.custom_raise_ammount), self.custom_raise)\n\nif __name__ == '__main__':\n unittest.main()" }, { "alpha_fraction": 0.6075388193130493, "alphanum_fraction": 0.6075388193130493, "avg_line_length": 27.25, "blob_id": "0ce081d91eaf05aec9004c79f72b76e540d5d47d", "content_id": "2f2127c37d88da2d21db4bcb44feb90d82a0d7d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 451, "license_type": "no_license", "max_line_length": 59, "num_lines": 16, "path": "/Ch10/10-1/10-6-7/addition.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "def add_method(fst_number, snd_number):\n try:\n result = int(fst_number) + int(snd_number)\n except ValueError:\n print(\"You didn't enter a number\")\n else:\n print(result)\n\nwhile True:\n first_number = input(\"Please enter a number: \")\n if first_number == 'q':\n break\n second_number = input(\"Please enter a second number: \")\n if second_number == 'q':\n break\n add_method(first_number, second_number)" }, { "alpha_fraction": 0.6100558638572693, "alphanum_fraction": 0.6268156170845032, "avg_line_length": 26.15151596069336, "blob_id": "f63f488d781d95d9e9cb856154ae084cbb14bb8f", "content_id": "ec1376df476e8621d115dd880fc238b406b27a29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 895, "license_type": "no_license", "max_line_length": 94, "num_lines": 33, "path": "/Ch6/dictionaries.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "#6-1 Person\nperson_0 = {\n \"first_name\": \"Doe\",\n \"last_name\": \"John\",\n \"age\": \"25\",\n \"city\": \"New York\",\n}\nprint(person_0)\n\n#6-2 Favourite numbers\nfavourite_numbers = {\n \"John\" : \"5\",\n \"Maria\": \"1\",\n \"Leonard\": \"7\",\n \"Jimmy\": \"9\",\n \"Anna\": \"3\",\n}\nfor favourite_number in favourite_numbers:\n name = favourite_numbers[f'{favourite_number}']\n print(f\"{favourite_number}: {name}\")\n\n#6-3 Glossary\nprogramming_words = {\n \"variable\" : \"keyword that can store data\",\n \"string\" : \"text data type\",\n \"boolean\" : \"data type that can have the value 'true' and 'false'\",\n \"if-else condition\" : \"method for checking conditions and executing code based on result\",\n \"integer\" : \"whole-number data type\",\n}\n\nfor programming_word in programming_words:\n definition = programming_words[f'{programming_word}']\n print(f\"The {programming_word} is a {definition}.\")" }, { "alpha_fraction": 0.5879194736480713, "alphanum_fraction": 0.6060402393341064, "avg_line_length": 20.91176414489746, "blob_id": "3cd697c347da6fedf5d3e322d05820c2c5eb5370", "content_id": "0e85a64659c1a669e884d548833b4f7ef323a523", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1490, "license_type": "no_license", "max_line_length": 63, "num_lines": 68, "path": "/Ch5/IfConditions.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "#AlienColours1\nalien_color = 'green' \nalien_color1 = \"blue\"\nif alien_color == 'green':\n print('You get 5 points')\nif alien_color == 'red':\n print()\n\n#AlienColours2\nif alien_color == 'green':\n points = 5\nelse:\n points = 10\nprint(f\"you got {points} points\")\n\nif alien_color1 == 'green':\n points = 5\nelse:\n points = 10\nprint(f\"you got {points} points\")\n\n#AlienColor3\naliens = (\"green\", \"yellow\", \"red\")\nfor alien in aliens:\n if alien == \"green\":\n points = 5\n if alien == \"yellow\":\n points = 10\n if alien == \"red\":\n points = 15\n print(f\"You got {points} points for killing {alien} alien\")\n\n#Stages of life\nage = 18\n\nif age < 2:\n stage = 'a baby'\nelif age < 4:\n stage = 'a toddler';\nelif age < 13:\n stage = 'a kid'\nelif age < 20:\n stage = 'a teenager'\nelif age < 65:\n stage = 'an adult'\nelse:\n stage = 'an elder'\n\nprint(f\"That person is {stage}\")\n\n#favorite fruit\nfavorite_fruits = ('apple', 'bannana', 'avocado')\n\nfor fruit in favorite_fruits:\n if fruit == 'bannana':\n print(f\"He must really like {fruit}\")\nfor fruit in favorite_fruits:\n if fruit == 'apple':\n print(f\"He must really like {fruit}\")\nfor fruit in favorite_fruits:\n if fruit == 'avocado':\n print(f\"He must really like {fruit}\")\nfor fruit in favorite_fruits:\n if fruit == 'orange':\n print(f\"He must really like {fruit}\")\nfor fruit in favorite_fruits:\n if fruit == 'tomato':\n print(f\"He must really like {fruit}\")\n" }, { "alpha_fraction": 0.6747967600822449, "alphanum_fraction": 0.6747967600822449, "avg_line_length": 29.875, "blob_id": "766f1db03ae66aac203a28c2beb9a202312230cf", "content_id": "b90707ecad9d266802ec0ccd2ec5e1a8b4358f88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 246, "license_type": "no_license", "max_line_length": 70, "num_lines": 8, "path": "/Ch9/9-3 User/admin.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "import user\nimport privileges\n\nclass Admin(user.User):\n\n def __init__(self, first_name, last_name, user_name, user_email):\n super().__init__(first_name, last_name, user_name, user_email)\n self.privileges = privileges.Privileges()" }, { "alpha_fraction": 0.6161879897117615, "alphanum_fraction": 0.6214098930358887, "avg_line_length": 30.91666603088379, "blob_id": "d1c63ee0eb9ede054b117806b5cb3b2fbb0f3e0c", "content_id": "7e787d56d9c1b34b762bad5aaa9909be29be5b2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 383, "license_type": "no_license", "max_line_length": 61, "num_lines": 12, "path": "/Ch8/8-7 Album.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "def make_album(artis_name, album_name, number_of_songs=None):\n album_dictionary = {\n 'name' : artis_name,\n 'album' : album_name,\n }\n if number_of_songs:\n album_dictionary['nr_songs'] = number_of_songs\n print(album_dictionary)\n\nmake_album('Pink Floyd', \"Dark side of the Moon\")\nmake_album(\"Led Zeppelin\", \"IV\")\nmake_album(\"Come\", \"Orizont\", \"10\")\n" }, { "alpha_fraction": 0.6829268336296082, "alphanum_fraction": 0.6829268336296082, "avg_line_length": 30.88888931274414, "blob_id": "dddb841136cda0b0d8dbfa138e1f4aca53be8a5d", "content_id": "fa93b838418395c0346f9c6deefc3413372ae649", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 287, "license_type": "no_license", "max_line_length": 54, "num_lines": 9, "path": "/Ch8/8-6 City names.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "def city_country(city_name_input, country_name_input):\n city_name = city_name_input.title()\n country_name = city_name_input.title()\n\n print(f\"{city_name}, {country_name}\")\n\ncity_country('Santiago', 'Chile')\ncity_country('Cluj-Napoca', 'Romania')\ncity_country('New York', 'USA')\n" }, { "alpha_fraction": 0.4961997866630554, "alphanum_fraction": 0.5249728560447693, "avg_line_length": 22.037500381469727, "blob_id": "b9ff7928972d1cdd27a64a65274e819691760010", "content_id": "4025bbf1c93c5013997bf2fd7809e249fb3fc44e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1842, "license_type": "no_license", "max_line_length": 56, "num_lines": 80, "path": "/Ch6/nested.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "#6-7 People\nperson_0 = {\n \"first_name\": \"Doe\",\n \"last_name\": \"John\",\n \"age\": \"25\",\n \"city\": \"New York\",\n}\nperson_1 = {\n \"first_name\": \"Forman\",\n \"last_name\": \"Red\",\n \"age\": \"55\",\n \"city\": \"Point Place\",\n}\nperson_2 = {\n \"first_name\": \"Dorian\",\n \"last_name\": \"John\",\n \"age\": \"30\",\n \"city\": \"Los Angeles\",\n}\n\npeople = (person_0, person_1, person_2)\n\nfor person in people:\n print(person)\n\n#6-9 favorite places\nfavorite_places = {\n \"John\" : [\"CoffeBucks\"],\n \"Red\" : [\"The Lake\", \"The Couch\"],\n \"Maria\" : [\"The Mall\", \"Paris\", \"CoffeBucks\"],\n}\n\nfor person, places in favorite_places.items():\n if len(places) > 1:\n print(f\"{person}, your favorite places are:\")\n else:\n print(f\"{person}, your favourite place is:\")\n for place in places:\n print(f\"\\t{place.title()}\")\n\n#6-10 favorite numbers\nfavourite_numbers = {\n \"John\" : [\"5\", \"12\"],\n \"Maria\": [\"1\", \"2\", \"3\"],\n \"Leonard\": [\"7\"],\n \"Jimmy\": [\"9\", \"5\"],\n \"Anna\": [\"3\"],\n}\n\nfor person, numbers in favourite_numbers.items():\n if len(numbers) > 1:\n print(f\"{person}, your favourite numbers are: \")\n else:\n print(f\"{person}, your favourite number is: \")\n for number in numbers:\n print(f\"{number}\")\n\n#6-11 Cities\ncities = {\n 'Cluj-Napoca':{\n 'county' : 'Cluj',\n 'population' : '321687',\n 'fact' : \"In German it's called 'Klausenburg'\",\n },\n 'Bucuresti' : {\n 'county' : 'n/a',\n 'population' : '2151655',\n 'fact' : \"It's the capital of Romania\",\n },\n 'Brasov' : {\n 'county' : 'Brasov',\n 'population' : '290743',\n 'fact' : \"The 'Black Church' is situated here.\",\n }\n}\n\nfor city, details in cities.items():\n print(f\"{city}:\")\n for detail, info in details.items():\n print(f\"\\t{detail} : {info}\")" }, { "alpha_fraction": 0.6882529854774475, "alphanum_fraction": 0.7108433842658997, "avg_line_length": 23.629629135131836, "blob_id": "e4d6a18baaefc0814cf3254a6691577d9c4eff07", "content_id": "65c02d904f7996c7b953ae6b63ef860489266792", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 664, "license_type": "no_license", "max_line_length": 63, "num_lines": 27, "path": "/Ch9/9-3 User/user_create.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "import user\nimport admin\n\nuser1 = user.User('Trent', 'Reznor', 'TReznor', '[email protected]')\nuser2 = user.User('Jiimy', 'Page', 'jPage', '[email protected]')\nuser3 = user.User('tonny', 'stark', 'IronMan', '[email protected]')\n\nadmin = admin.Admin('admin', 'adminson', 'TheAdmin', '[email protected]')\n\nuser_objects = (user1, user2, user3)\n\nfor user_object in user_objects:\n user_object.describe_user()\n\nuser1.greet_user('name')\nuser2.greet_user('name')\nuser3.greet_user('user')\n\nuser1.increment_login_attempts()\nuser1.increment_login_attempts()\nuser1.increment_login_attempts()\nprint(user1.login_attempts)\n\nuser1.reset_login_attempts()\nprint(user1.login_attempts)\n\nadmin.privileges.show_privileges()" }, { "alpha_fraction": 0.5625, "alphanum_fraction": 0.5625, "avg_line_length": 25.125, "blob_id": "a31417359c61806a03a57ac2444fda24eee8f878", "content_id": "1293eb2b74b0b9ca8665c97f8cf6b8c30b0300ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "no_license", "max_line_length": 49, "num_lines": 8, "path": "/Ch10/10-1/10-3-4-5/book.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "class Book:\n\n def __init__(self, data):\n self.data = data\n\n def append_in_book(self, book_name, data):\n with open(book_name, 'a') as file_object:\n file_object.write(f\"{data}\\n\")" }, { "alpha_fraction": 0.616847813129425, "alphanum_fraction": 0.6277173757553101, "avg_line_length": 32.54545593261719, "blob_id": "384fd80c1bb5b9d0c33f9c3aa94bb9538b1880b8", "content_id": "136f596a54023aec1da7cd0cbe092bf5eddf48b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 368, "license_type": "no_license", "max_line_length": 60, "num_lines": 11, "path": "/Ch11/11-3/employee.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "class Employee:\n \n def __init__(self, first_name, last_name, anual_salary):\n self.first_name = first_name\n self.last_name = last_name\n self.anual_salary = anual_salary\n\n def give_raise(self, raise_ammount = 5000):\n #self.raise_ammount = raise_ammount\n new_salary = self.anual_salary + raise_ammount\n return new_salary" }, { "alpha_fraction": 0.8421052694320679, "alphanum_fraction": 0.8421052694320679, "avg_line_length": 18, "blob_id": "61e267dc8998472de9ce239a07c2007235073a94", "content_id": "da8d180118d4f5c941570830766328e435bfde4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 38, "license_type": "no_license", "max_line_length": 20, "num_lines": 2, "path": "/README.md", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "# PythonTraining\npython code snippets\n" }, { "alpha_fraction": 0.5226730108261108, "alphanum_fraction": 0.5226730108261108, "avg_line_length": 34, "blob_id": "56f25ea3acfa4c183897af2ca74c6c300bf2b298", "content_id": "dcb2dd7d5ff8ebef11b7279a3ac398f0a4bd3dd2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 419, "license_type": "no_license", "max_line_length": 72, "num_lines": 12, "path": "/Ch8/8-13 User profile.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "def build_profile(first, last, **user_info):\n \"\"\"Build a dictionary containing everything we know about a user.\"\"\"\n user_info['first_name'] = first\n user_info['last_name'] = last\n return user_info\n\nuser_profile = build_profile('john', 'doe' , \n location = 'Romania' ,\n field = 'IT' ,\n hobby = 'gaming')\n\nprint(user_profile)" }, { "alpha_fraction": 0.6050955653190613, "alphanum_fraction": 0.6242038011550903, "avg_line_length": 30.600000381469727, "blob_id": "a8e425d48f230c2b98b8f01c52557aa7a7f97b04", "content_id": "92c706b87f4a84c90c40d36835d03d7d06c0a856", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 157, "license_type": "no_license", "max_line_length": 32, "num_lines": 5, "path": "/Ch3/Names.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "names = [\"Ion\", \"Maria\", \"Bula\"]\ngrettings = \"Hello pleb:\"\nprint(f\"{grettings} {names[0]}\")\nprint(f\"{grettings} {names[1]}\")\nprint(f\"{grettings} {names[2]}\")" }, { "alpha_fraction": 0.5333333611488342, "alphanum_fraction": 0.5754386186599731, "avg_line_length": 19.428571701049805, "blob_id": "73a6c4b1ff520c5d3926c22375a0085c479fc24d", "content_id": "2b90877bc86b3c8c8436e928e5d41e8bd52bac41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 285, "license_type": "no_license", "max_line_length": 36, "num_lines": 14, "path": "/Ch10/10-8-9/cats_and_dogs.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "cats = 'Ch10/10-8-9/cats.txt'\ndogs = 'Ch10/10-8-9/dogs.txt'\n\ndef read_file(file_object):\n try:\n with open(file_object) as f:\n for line in f:\n print(line.rstrip())\n except FileNotFoundError:\n pass\n\nread_file(cats)\nprint(\" \")\nread_file(dogs)" }, { "alpha_fraction": 0.59375, "alphanum_fraction": 0.625, "avg_line_length": 47.16666793823242, "blob_id": "277f00e0d78a7adbd306bdad25ba0362ae74686b", "content_id": "ba2802bf31e9994a773301bdc83b52a49735f759", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 288, "license_type": "no_license", "max_line_length": 117, "num_lines": 6, "path": "/Ch3/myOwnList.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "cars = [\"audi\", \"mercedes\", \"bmw\"]\nmessages = [\"is driven by assholes\", \"is also driven by assholes\", \"is a great car\"]\nprints = [f\"{cars[0].title()} {messages[0]}\", f\"{cars[1].title()} {messages[2]}\", f\"{cars[2].title()} {messages[1]}\"]\nprint(prints[0])\nprint(prints[1])\nprint(prints[2])" }, { "alpha_fraction": 0.707317054271698, "alphanum_fraction": 0.707317054271698, "avg_line_length": 19.75, "blob_id": "2486866ee2067c227ca1d6e0c2295a91dde311cb", "content_id": "b13dcde4fcf89ce11570ac8187aaf16844e10212", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 82, "license_type": "no_license", "max_line_length": 42, "num_lines": 4, "path": "/Ch8/8-1 Messages.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "def dislay_message():\n print(\"I'm learning about functions.\")\n\ndislay_message()" }, { "alpha_fraction": 0.6969696879386902, "alphanum_fraction": 0.6969696879386902, "avg_line_length": 40.5, "blob_id": "87ad9165c3741eaf82d19a582da28f4c163b31c3", "content_id": "8622b62678912101531816f403af76bf1418a11d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 165, "license_type": "no_license", "max_line_length": 94, "num_lines": 4, "path": "/Ch8/8-3 T-shirt.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "def make_shirt(shirt_size, shirt_message):\n print(f\"The size of the shirt is {shirt_size}, and it has {shirt_message} printed on it.\")\n\nmake_shirt('XL', 'Wazzap')" }, { "alpha_fraction": 0.5252293348312378, "alphanum_fraction": 0.6192660331726074, "avg_line_length": 13.096774101257324, "blob_id": "cd81371d91325d6bac4fe5cebcd3f9465689111e", "content_id": "4ff27e4cf469ae8a58787187cebbea76b2eed4cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "no_license", "max_line_length": 43, "num_lines": 31, "path": "/CH4/range.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "#4-3\nfor value in range(1, 21):\n print(value)\n\n#4-4\nmilion = [range(1, 1000001)]\n#4-5\nprint(min(milion))\nprint(max(milion))\n\n#for value in milion:\n #print(value)\n\n#4-6\nfor value in range(1, 21, 2):\n print(value)\n\n#4-7\nfor value in range(3, 31, 3):\n print(value)\n\n#4-8\ncubes = []\nfor value in range(1, 11):\n cube = value**3\n cubes.append(cube)\nprint(cubes)\n\n#4-9\ncubes = [value**3 for value in range(1,11)]\nprint(cubes)" }, { "alpha_fraction": 0.7123745679855347, "alphanum_fraction": 0.7190635204315186, "avg_line_length": 14, "blob_id": "988d122b2bc61ea62ae116474d4150d36fc9d025", "content_id": "b7325d538feddd934658f0bc4cdcc1c773e33d45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 299, "license_type": "no_license", "max_line_length": 63, "num_lines": 20, "path": "/Ch3/Seeing The World.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "#3-8 Seeing the world\nplaces = [\"Moscova\", \"New york\", \"Amsterdam\", \"Tokyo\", \"Egipt\"]\nprint(places)\n\nsort_places = sorted(places)\nprint(sort_places)\n\nprint(places)\n\nplaces.reverse()\nprint(places)\n\nplaces.reverse()\nprint(places)\n\nplaces.sort()\nprint(places)\n\nplaces.sort(reverse = True)\nprint(places)" }, { "alpha_fraction": 0.5771276354789734, "alphanum_fraction": 0.6072695255279541, "avg_line_length": 28.710525512695312, "blob_id": "3ed92f1e35a669e948b7d29e4593f60f3ed9cfa6", "content_id": "4f5c7d8792600d1c94ca921f58a35226f72942ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1128, "license_type": "no_license", "max_line_length": 74, "num_lines": 38, "path": "/Ch5/ifLists.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "#5-8 and 5-9\nusernames = ('admin', 'johm', 'kitty55', 'vasile69', 'belzebub')\nif usernames:\n for user in usernames:\n if user == 'admin':\n print(f\"Hello {user}. Would you like to see a status report?\")\n else:\n print(f\"Jello {user}, thank you for logging in again.\")\nelse:\n print(\"We need to add some users.\")\n\n#5-10 Checking usernames\ncurrent_users = ('johm', 'kitty55', 'vasile69', 'Belzebub', 'Bro')\nnew_users = ('ale73', 'panda', 'Bro', 'VASILE69', 'GutzaRULLZ')\ncurrent_users_lower = []\n\nfor current_user in current_users:\n current_user_lower = current_user.lower()\n current_users_lower.append(current_user_lower)\n\nfor new_user in new_users:\n if new_user.lower() in current_users_lower:\n print(f\"The {new_user} username is invalid\")\n else:\n print(f\"The {new_user} usename is valid\")\n\n#5-11 Ordinal numbers\nnumbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)\n\nfor number in numbers:\n if number == 1:\n print(f\"{number}st\")\n elif number == 2:\n print(f\"{number}nd\")\n elif number == 3:\n print(f\"{number}rd\")\n else:\n print(f\"{number}th\")" }, { "alpha_fraction": 0.6815789341926575, "alphanum_fraction": 0.6815789341926575, "avg_line_length": 24.399999618530273, "blob_id": "82f3fce078a9c78f02f36a8b899c9eceb1977c5a", "content_id": "ac189a4966360cf40248f58184f8f4452542a503", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 380, "license_type": "no_license", "max_line_length": 47, "num_lines": 15, "path": "/Ch8/8-10 Sending messages.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "messages_list = [\"Hello\", \"How are you?\", \":)\"]\nsent_messages = []\n\ndef print_messages(messages):\n for message in messages:\n print(message)\n\ndef send_messages(send_messages):\n while send_messages:\n send_message = send_messages.pop()\n sent_messages.append(send_message)\n print(sent_messages)\n\nsend_messages(messages_list)\nprint_messages(messages_list)" }, { "alpha_fraction": 0.6822429895401001, "alphanum_fraction": 0.6822429895401001, "avg_line_length": 34.83333206176758, "blob_id": "1f731f7b18b2bea3efd62410fbc5a421319faebe", "content_id": "cf1545f0f89841803e889242a0b0bc0e5a64e613", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 214, "license_type": "no_license", "max_line_length": 94, "num_lines": 6, "path": "/Ch8/8-4 Large shirts.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "def make_shirt(shirt_size='L', shirt_message='I Love Python'):\n print(f\"The size of the shirt is {shirt_size}, and it has {shirt_message} printed on it.\")\n\nmake_shirt()\nmake_shirt('M')\nmake_shirt('XL', 'Wazzap')" }, { "alpha_fraction": 0.6275861859321594, "alphanum_fraction": 0.6413792967796326, "avg_line_length": 26.619047164916992, "blob_id": "2e4c7c6aceab00b40c2977db89850bef7884ed19", "content_id": "d6f3bb48ffe65ace8e4533600fd7920f2038e12f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 580, "license_type": "no_license", "max_line_length": 64, "num_lines": 21, "path": "/Ch10/10-11-12/verify_user.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "import json_handler_class\n\nuser_add = \"You have been added successfully:\"\nuser_display = \"You're: \"\nask_prompt = \"Is the curren username correct? (type 'y' or 'n')\"\nprompt = \"Enter username: \"\nfile_name = \"Ch10/10-11-12/user.json\"\n\nuser = json_handler_class.JasonHandler(file_name)\ntry:\n user.read_from_json(user_display)\n ask = input(ask_prompt)\n if ask == 'n':\n user.add_to_json(prompt, user_add)\n elif ask == 'y':\n print(\"Awesome!\")\n else:\n print('Wrong input')\n pass\nexcept FileNotFoundError:\n user.add_to_json(prompt, user_add)\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 20.615385055541992, "blob_id": "c7bb523b7fe1fa95e9757f31f601b1210e6dab37", "content_id": "888aed076a7d3b79ff7cd6e7628a387c68b5983a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 280, "license_type": "no_license", "max_line_length": 65, "num_lines": 13, "path": "/Ch10/10-1/10-3-4-5/programming_pool.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "import book\n\nrunner = True\n\nwhile runner:\n prompt = (\"Why do you like programming?(type 'q' to quit): \")\n answer = input(prompt)\n\n if answer == 'q':\n runner = False\n else:\n answers = book.Book(answer)\n answers.append_in_book('answers.txt', answer)" }, { "alpha_fraction": 0.5321637392044067, "alphanum_fraction": 0.5964912176132202, "avg_line_length": 16.200000762939453, "blob_id": "d265aa8fb3383c82b987a8934ccdc54c7ef7746a", "content_id": "30e052609c5a48256b7db610b5e1f4270e8417ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 171, "license_type": "no_license", "max_line_length": 68, "num_lines": 10, "path": "/Ch2/numbers.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "#you can declre multipla variables and their values in pythonimport \na, b, c, d = 5, 3, 2, 4\nz = a + b\ny = c * d\nprint(z)\nprint(y)\ns = 1_000\nf = 492\np = s / c - f\nprint(p)" }, { "alpha_fraction": 0.7479748129844666, "alphanum_fraction": 0.7551755309104919, "avg_line_length": 26.799999237060547, "blob_id": "b2a1ba20c4d8c2c6cd2a253394eaac8426f9041b", "content_id": "1ebd2e549c2f41ed3ed9b83b0498562c182b9b63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1111, "license_type": "no_license", "max_line_length": 80, "num_lines": 40, "path": "/Ch9/9-1/9-2 restaurant/new restaurant.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "import Restaurant\n\npizza_restaurant = Restaurant.Restaurant('La pomodori', 'Pizza')\nshaworma_restaurant = Restaurant.Restaurant('Mama Manu', 'Shaworma')\nsoup_restaurant = Restaurant.Restaurant('Souper', 'Soup')\n\nic_stand = Restaurant.IceCreamStand('Gelato', 'Ice Cream')\n\nrestaurants = [pizza_restaurant, shaworma_restaurant, soup_restaurant, ic_stand]\n\ndef restaurant_status():\n for restaurant in restaurants:\n\n print(restaurant.restaurant_name)\n print(restaurant.cuisine_type)\n print(restaurant.number_served)\n\n restaurant.describe_restaurant()\n\n message = f\"The {restaurant.restaurant_name} restauranat is now open.\"\n restaurant.open_restaurant(message)\n\nrestaurant_status()\n\npizza_restaurant.set_number_served(20)\nshaworma_restaurant.set_number_served(35)\nsoup_restaurant.set_number_served(1)\n\nrestaurant_status()\n\npizza_restaurant.increment_number_served(5)\nshaworma_restaurant.increment_number_served(7)\nsoup_restaurant.increment_number_served(5)\n\nrestaurant_status()\n\nflavors = ['vanila', 'chocolate']\n\nic_stand.add_flavors(flavors)\nic_stand.display_flavors()" }, { "alpha_fraction": 0.541304349899292, "alphanum_fraction": 0.5695652365684509, "avg_line_length": 24.61111068725586, "blob_id": "cb497a0a18ec9eaf88bdb4e17eef479cdf72919f", "content_id": "e6d72207d3913c88dcbea9b49192e3f078ff4e3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 460, "license_type": "no_license", "max_line_length": 50, "num_lines": 18, "path": "/Ch10/10-10/common_words.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "franken = \"Ch10/10-10/Frankenstein.txt\"\npnp = \"Ch10/10-10/Pride and Prejudice.txt\"\n\ndef word_counter(word, book_name):\n try:\n result = 0 \n with open(book_name) as f:\n for line in f:\n counter = line.lower().count(word)\n result += counter\n print(result)\n except FileNotFoundError:\n print('File not found')\n\nbooks = [franken, pnp]\n\nfor book in books:\n word_counter('the ', book)" }, { "alpha_fraction": 0.7163461446762085, "alphanum_fraction": 0.7163461446762085, "avg_line_length": 33.83333206176758, "blob_id": "798b68915b88b9ad1dc1a0842744a81381910e34", "content_id": "8eb457190918d40e5a7aff96f8807955a20e9cc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "no_license", "max_line_length": 59, "num_lines": 6, "path": "/Ch8/8-12 Sandwiches.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "def sandwich_items(*items):\n print(f\"Your sandwich will contains {items}\")\n\nsandwich_items(\"tomatoes\", \"salad\", \"bacon\")\nsandwich_items(\"salami\")\nsandwich_items(\"cheese\", \"more cheese\", \"even more cheese\")" }, { "alpha_fraction": 0.65625, "alphanum_fraction": 0.671875, "avg_line_length": 24.799999237060547, "blob_id": "16e821d360b7f29d6f778dc081ef25a3af7b1981", "content_id": "d4fcb5b5b9242f1e7f4e967562a0549a61663e1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 128, "license_type": "no_license", "max_line_length": 48, "num_lines": 5, "path": "/CH4/Pizza.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "#4-1\npizzas = [\"Picante\", \"Vegetarian\", \"Margherita\"]\nfor pizza in pizzas:\n print(f\"{pizza} is amazing\")\nprint(\"Pizza rullz\")" }, { "alpha_fraction": 0.7106227278709412, "alphanum_fraction": 0.7106227278709412, "avg_line_length": 33.25, "blob_id": "2207883d7d1ec3def44a6aa812762a345503e130", "content_id": "30878b3d2fe2da8dea8b1da911d542037b7efb94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 273, "license_type": "no_license", "max_line_length": 75, "num_lines": 8, "path": "/Ch7/7-8 Deli.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "sandwich_orders = ['BLT', 'Tuna', 'Veggie', 'chicken salad', 'Italian BMT']\nfinished_sandwiches = []\n\nwhile sandwich_orders:\n sandwich_order = sandwich_orders.pop()\n\n print(f\"Your {sandwich_order} sandwich is finished.\")\n finished_sandwiches.append(sandwich_order)" }, { "alpha_fraction": 0.6474907994270325, "alphanum_fraction": 0.6474907994270325, "avg_line_length": 30.384614944458008, "blob_id": "ad89be01bfb9fa4a008ca220d7fd04f23ebace1e", "content_id": "2c09879e3c7ed7df375c129770681ce83c7691f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 817, "license_type": "no_license", "max_line_length": 85, "num_lines": 26, "path": "/Ch8/8-8 User album.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "def make_album(artis_name, album_name, number_of_songs=None):\n album_dictionary = {\n 'name' : artis_name,\n 'album' : album_name,\n }\n if number_of_songs:\n album_dictionary['nr_songs'] = number_of_songs\n print(album_dictionary)\n\nloop = True\nquit_message = \"Type 'q' to quit or press 'Enter' to continue \"\nalbum_message = \"What is your favourite album? \"\nartist_message = \"By whom? \"\nsong_nr_meesage = \"Do you know how many songs does it have? (press 'Enter' to skip) \"\n\n\nwhile loop:\n album_name_prompt = input(album_message)\n artist_name_prompt = input(artist_message)\n song_nr_prompt = input(song_nr_meesage)\n quit_promt = input(quit_message)\n\n if quit_promt == 'q':\n break\n else:\n make_album(artist_name_prompt, album_name_prompt, song_nr_prompt)\n\n" }, { "alpha_fraction": 0.6354343891143799, "alphanum_fraction": 0.6626916527748108, "avg_line_length": 24.565217971801758, "blob_id": "3142791ae72232a275ac5b265b78859a0a41399e", "content_id": "e6781de5dd401f7e13f33ae39a39e00689556971", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 587, "license_type": "no_license", "max_line_length": 54, "num_lines": 23, "path": "/Ch7/input.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "#7-1 Rental car\ncar = input(\"What kind of car would you like: \")\nprint(f\"Let me see if I can find a {car.title()}\")\n\n#7-2 REstaurant sitting\nparty = input(\"How many people are in your party?: \")\nparty = int(party)\n\nif party > 8:\n print(\"Please wait untill a table is free.\")\nelse:\n print(\"Please follow me to your table.\")\n\n#7-3 multiple of ten\nprompt = \"Is this a multiple of 10?\"\nprompt += \"\\nEnter number: \"\nnumber = input(prompt)\nnumber = int(number)\n\nif number % 10 == 0:\n print(f\"{number} is a multiple of 10.\")\nelse:\n print(f\"{number} number is not a multiple of 10.\")" }, { "alpha_fraction": 0.6242603659629822, "alphanum_fraction": 0.6242603659629822, "avg_line_length": 27.20833396911621, "blob_id": "825ab46e8056647e1142a99bc9d91f90b748d57d", "content_id": "e69c18fd3e3de29699eab25ee0628a62cb0cac9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 676, "license_type": "no_license", "max_line_length": 99, "num_lines": 24, "path": "/Ch7/7-19 Dream Vacation.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "dream_vacation = {}\n\ndreams = True\n\nwhile dreams:\n who_are_you = 'Please enter your name: '\n name = input(who_are_you)\n destination_promot = f'{name.title()}, if you could visit only one place, where would you go? '\n destination = input(destination_promot)\n\n dream_vacation[name] = destination\n\n repeat = input(\"Would someone else like to respond? (yes/no)\")\n if repeat == 'no':\n dreams = False\n elif repeat == 'yes':\n dreams = True\n else:\n print(\"Invalid input\")\n dreams = False\n \nprint('---poll results!---')\nfor name, destination in dream_vacation.items():\n print(f'{name} would like to visit {destination}')" }, { "alpha_fraction": 0.6645962595939636, "alphanum_fraction": 0.6645962595939636, "avg_line_length": 22.14285659790039, "blob_id": "697d5725a854f320f67437f900bd60f35b58af58", "content_id": "60dd6f93f63d99bc049e599deadbcfb7e9a23185", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 161, "license_type": "no_license", "max_line_length": 47, "num_lines": 7, "path": "/Ch8/8-9 Mesages.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "messages_list = [\"Hello\", \"How are you?\", \":)\"]\n\ndef print_messages(messages):\n for message in messages:\n print(message)\n\nprint_messages(messages_list)" }, { "alpha_fraction": 0.7397260069847107, "alphanum_fraction": 0.7397260069847107, "avg_line_length": 13.800000190734863, "blob_id": "7b1106d7bbfb8d9a588005a192f602ecefef9e8f", "content_id": "d67343ede393bd40bf2d9082d1016a0585209803", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 73, "license_type": "no_license", "max_line_length": 23, "num_lines": 5, "path": "/Ch1/hello_world.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "message = \"Hello World\"\nprint(message)\n\nmessage = \"Wazzap\"\nprint(message)" }, { "alpha_fraction": 0.7027027010917664, "alphanum_fraction": 0.7027027010917664, "avg_line_length": 27, "blob_id": "39bd93b5ad3bc2ae0b41501f8597a6e831fffcfa", "content_id": "c4f9331283b3dd0b9ff97ca927e01ee3ee81f785", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 111, "license_type": "no_license", "max_line_length": 54, "num_lines": 4, "path": "/Ch8/8-2 Favorite books.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "def favorite_book(book_title):\n print(f'My favorite book is {book_title.title()}')\n\nfavorite_book('bla bla')" }, { "alpha_fraction": 0.5466805100440979, "alphanum_fraction": 0.5518672466278076, "avg_line_length": 30.129032135009766, "blob_id": "ffd34d6ef58eed57dd901aa4b59d96c2a24f407e", "content_id": "2d0f2b34ede8a1a9766181de56f10dad64df7a63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 964, "license_type": "no_license", "max_line_length": 69, "num_lines": 31, "path": "/Ch9/9-3 User/user.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "class User:\n def __init__(self, first_name, last_name, user_name, user_email):\n self.first_name = first_name\n self.last_name = last_name\n self.user_name = user_name\n self.user_email = user_email\n self.login_attempts = 0 #9-4\n\n def describe_user(self):\n user_summary = {\n 'first name' : self.first_name.title(),\n 'last name' : self.last_name.title(),\n 'user name' : self.user_name,\n 'email' : self.user_email,\n }\n\n print(user_summary)\n\n def greet_user(self, greet_request):\n if greet_request == 'name':\n print(f\"Hello {self.first_name} {self.last_name}!\")\n elif greet_request == 'user':\n print(f\"Wazzup {self.user_name}!\")\n else:\n print(f'{greet_request}')\n\n def increment_login_attempts(self):\n self.login_attempts +=1\n \n def reset_login_attempts(self):\n self.login_attempts = 0" }, { "alpha_fraction": 0.5040485858917236, "alphanum_fraction": 0.5485829710960388, "avg_line_length": 19.625, "blob_id": "7c10053026aabb46a660b1d95e13218250cdd56c", "content_id": "42ec82ede938019355d2d7ca3b38f2a2aa95a57c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 494, "license_type": "no_license", "max_line_length": 56, "num_lines": 24, "path": "/Ch7/7-5 moovie tickets.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "price_3 = '$0'\nprice_3_12 = '$10'\nprice_12 = '$15'\n\nprompt = 'Would you like to see a movie?'\nprompt += '\\nPlease submit the age to check the price: '\n\nloop = True\n\nwhile loop:\n age_input = input(prompt)\n age = int(age_input)\n\n if age <= 3:\n print(f'The price is {price_3}')\n continue\n if age <= 12:\n print(f'The price is {price_3_12}')\n continue\n if age > 12:\n print(f'The price is {price_12}') \n continue\n else:\n loop = False" }, { "alpha_fraction": 0.6098654866218567, "alphanum_fraction": 0.6307922005653381, "avg_line_length": 32.5, "blob_id": "ce9d4f96649a79f658427822f02eed3b6bf4cc5e", "content_id": "c04d6d72688c0a0e5e98c5ebd6373f6af1f03435", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 669, "license_type": "no_license", "max_line_length": 84, "num_lines": 20, "path": "/Ch11/11 1-2/city_test.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "import unittest\nimport city_class as cc\n\nclass CitiesTestCase(unittest.TestCase):\n \"\"\"Tests for ciity_class.py function.\"\"\"\n\n def test_city_formatert(self):\n \"\"\"Do countries like Satiago, Chile work?\"\"\"\n sc = cc.City('santiago', 'chile')\n sc_formated = sc.city_formater()\n self.assertEqual(sc_formated, \"Santiago, Chile\")\n\n def test_city_formatert_pop(self):\n \"\"\"can I add population for cities?\"\"\"\n sc = cc.City('santiago', 'chile', 6_269_384)\n sc_formated = sc.city_formater()\n self.assertEqual(sc_formated, \"Santiago, Chile has a population of 6269384\")\n\nif __name__ == '__main__':\n unittest.main()" }, { "alpha_fraction": 0.6071428656578064, "alphanum_fraction": 0.6071428656578064, "avg_line_length": 23.5625, "blob_id": "ad70ad261879278d6f730347ed67c3b0901a922a", "content_id": "4b2448ccb749b5478b963e34bd2f220d28148996", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 392, "license_type": "no_license", "max_line_length": 65, "num_lines": 16, "path": "/Ch10/10-1/10-3-4-5/guest_book_runner.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "import book\n\nbook_name = input(\"Enter book name: \")\nguest_book_file = f\"{book_name}.txt\"\n\nrunner = True\n\nwhile runner:\n prompt = \"Write your name or 'q' to quit: \"\n guest = input(prompt)\n if guest == 'q':\n runner = False\n else:\n guest_book = book.Book(guest)\n print(f'Welcome {guest.title()}')\n guest_book.append_in_book(guest_book_file, guest.title())" }, { "alpha_fraction": 0.6814988255500793, "alphanum_fraction": 0.6814988255500793, "avg_line_length": 37.90909194946289, "blob_id": "1272e3316438ffca95f7550bb7b0e40bed20a1da", "content_id": "8496cd06defc5bce9cb9c244491e74cabdb271dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 427, "license_type": "no_license", "max_line_length": 63, "num_lines": 11, "path": "/Ch1/name2.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "input_first_name = \" Blake\"\ninput_middle_name = \" hellbalzer \"\ninput_last_name = \"john \"\nsalutations = \"Hello!\"\nmessage = \"How are you today?\"\nfirst_name = f\"{input_first_name.lstrip()}\"\nmiddle_name = f\"{input_middle_name.strip().title()}\"\nlast_name = f\"{input_last_name.rstrip().title()}\"\nname = f'{first_name} \"{middle_name}\" {last_name}'\ndisplay_message = f\"\\t\\t{salutations} \\n\\t{name} \\n\\t{message}\"\nprint(display_message)" }, { "alpha_fraction": 0.5748792290687561, "alphanum_fraction": 0.5845410823822021, "avg_line_length": 22.11111068725586, "blob_id": "32adf220284f50650cbccf9b9d6135dacbe3eb09", "content_id": "96454f04327a98c6173a24daf8ac64742523e2c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 207, "license_type": "no_license", "max_line_length": 41, "num_lines": 9, "path": "/Ch9/9-13 Dice/dice.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "from random import randint\n\nclass Dice:\n def __init__(self, sides = 6):\n self.sides = sides\n\n def roll_dice(self, rolls):\n for x in range(rolls):\n print(randint(1, self.sides))" }, { "alpha_fraction": 0.6629629731178284, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 32.875, "blob_id": "5311309c5ded4c7320a77f7ced749c7cc4ebe6fa", "content_id": "14e4306c4e8beeb9db3d84ebe976f7ae3eadf2f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 270, "license_type": "no_license", "max_line_length": 65, "num_lines": 8, "path": "/CH4/tuple.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "simple_foods = (\"omlette\", \"soupe\", \"pasta\", \"pancakes\", \"toast\")\nfor simple_food in simple_foods:\n print(simple_food)\n#simple_foods[0] = \"pizza\"\n\nsimple_foods = (\"omlette\", \"soupe\", \"pasta\", \"waffles\", \"pizza\")\nfor simple_food in simple_foods:\n print(simple_food)" }, { "alpha_fraction": 0.6202749013900757, "alphanum_fraction": 0.623711347579956, "avg_line_length": 28.871795654296875, "blob_id": "63c61b230af9b2a80b7773f285e1764d6db04185", "content_id": "28c30c208be3530f24e887d01b5fe04e48de4af9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1164, "license_type": "no_license", "max_line_length": 65, "num_lines": 39, "path": "/Ch9/9-1/9-2 restaurant/Restaurant.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "class Restaurant:\n\n def __init__(self, restaurant_name, cuisine_type):\n self.restaurant_name = restaurant_name\n self.cuisine_type = cuisine_type\n self.number_served = 0\n\n def describe_restaurant(self):\n print(f\"The restaurant is called {self.restaurant_name}\")\n print(f\"The restaurant servs {self.cuisine_type}\")\n\n def open_restaurant(self, open_mesage):\n print(open_mesage)\n\n def set_number_served(self, served):\n if served >= self.number_served:\n self.number_served = served\n else:\n print(\"You can't decrease the number served.\")\n\n def increment_number_served(self, served):\n if served >= 0:\n self.number_served += served\n else:\n print(\"You can't decrease the number served.\")\n\n#9-6 Ice Cream Stand\nclass IceCreamStand(Restaurant):\n\n def __init__(self, restaurant_name, cuisine_type):\n\n super().__init__(restaurant_name, cuisine_type)\n self.ice_cream_flavors = []\n\n def add_flavors(self, flavors):\n self.ice_cream_flavors = flavors\n\n def display_flavors(self):\n print(f\"{self.ice_cream_flavors}\")" }, { "alpha_fraction": 0.5183486342430115, "alphanum_fraction": 0.5229358077049255, "avg_line_length": 28.133333206176758, "blob_id": "bf809e0082802765eea1ea1bf9e39523e5ffb60d", "content_id": "a65d251da3978d4bed7be732e7c0afd59e3112e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "no_license", "max_line_length": 60, "num_lines": 15, "path": "/Ch11/11 1-2/city_class.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "class City:\n def __init__(self, country, city, population = 0):\n self.country = country\n self.city = city\n self.population = population\n\n def city_formater(self):\n co = self.country.title()\n ci = self.city.title()\n pop = self.population\n if pop > 0:\n result = f\"{co}, {ci} has a population of {pop}\"\n else:\n result = f\"{co}, {ci}\"\n return result" }, { "alpha_fraction": 0.6801541447639465, "alphanum_fraction": 0.7032755017280579, "avg_line_length": 23.761905670166016, "blob_id": "36adad154ae811044a7049e4a162d13dfb26ce8f", "content_id": "e73dc016aeb61c7e3384743c4c9819ac0c3c5ff4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 519, "license_type": "no_license", "max_line_length": 78, "num_lines": 21, "path": "/CH4/slices.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "#4-10\nfoods = [\"pizza\", \"falafel\",\"shaworma\", \"carrot cake\", \"cannoli\", \"ice cream\"]\nfirst_slice = foods[:3] #prints first 3\nsecond_slice = foods[1:4] #definde slice\nlast_slice = foods[-3:] #prints last 3\nprint(first_slice)\nprint(second_slice)\nprint(last_slice)\nfor food in foods:\n print(food)\n\n#4-11\n\npizzas = [\"Picante\", \"Vegetarian\", \"Margherita\"]\nfried_pizzas = pizzas[:]\npizzas.append(\"Quatro stagioni\")\nfried_pizzas.append(\"Quatro carne\")\nprint(pizzas)\nfor pizza in pizzas:\n print(pizza)\nprint(fried_pizzas)" }, { "alpha_fraction": 0.6705539226531982, "alphanum_fraction": 0.6778425574302673, "avg_line_length": 25.423076629638672, "blob_id": "4dc07564284e91eec488c4429aff331b5b25e08f", "content_id": "4c8900924844ad5ed56984951651ba736d007c5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 686, "license_type": "no_license", "max_line_length": 67, "num_lines": 26, "path": "/Ch10/10-1/text_program_thing.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "filename = \"Ch10/10-1/test.txt\"\n\nfile_lines = []\n\nwith open(filename) as file_object:\n #prints entire file\n content = file_object.read()\n print(content.rstrip())\n\nwith open(filename) as file_object:\n #prints file content line by line\n for line in file_object:\n print(line.rstrip())\n \nwith open(filename) as file_object:\n #store data from file in file_lines lsit\n for line in file_object:\n file_lines.append(line)\n\n#prints each line in list\nfor file_line in file_lines:\n print(file_line.strip())\n\n#replace 'Pyhton' with 'C#' for each line in the list durring print\nfor file_line in file_lines:\n print(file_line.replace('Python', 'C#').strip())" }, { "alpha_fraction": 0.6296296119689941, "alphanum_fraction": 0.6296296119689941, "avg_line_length": 31.736841201782227, "blob_id": "234d135c2514ae4d9a1f115cded5fb1cdd140b77", "content_id": "758d866fa2bf645b9db3110e1b64235cce4087bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 621, "license_type": "no_license", "max_line_length": 99, "num_lines": 19, "path": "/Ch7/7-4 pizza order.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "loop = True\ntoppings = []\n\nwhile loop:\n prompt = 'What would you like on your pizza?'\n prompt += '\\nType quit to exit, type selection to see current toppings, type order to submit: '\n topping = input(prompt) \n toppings_prompt = f\"The {topping} has been added to the list.\"\n selection = f\"This is your current selection{toppings}\"\n if topping == 'quit':\n loop = False\n elif topping == 'selection':\n print(selection)\n elif topping == 'order':\n print('Your order has been submited.')\n loop = False\n else:\n toppings.append(topping)\n print(toppings_prompt)" }, { "alpha_fraction": 0.50390625, "alphanum_fraction": 0.54296875, "avg_line_length": 20.41666603088379, "blob_id": "8645b2ab71353a8c646900dde28ece8cdc9ac12b", "content_id": "81ccf6f591944a878750ab4c52c058725319d92a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "no_license", "max_line_length": 28, "num_lines": 12, "path": "/Ch9/9-13 Dice/roll_dice.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "import dice\n\ndefault_dice = dice.Dice()\nten_dice = dice.Dice(10)\ntwenty_dice = dice.Dice(20)\n\ndefault_dice.roll_dice(10)\nprint('-------------------')\nten_dice.roll_dice(10)\nprint('-------------------')\ntwenty_dice.roll_dice(10)\nprint('-------------------')" }, { "alpha_fraction": 0.6794425249099731, "alphanum_fraction": 0.6794425249099731, "avg_line_length": 35, "blob_id": "dfb291181beb048660b8f693e4641ff4c6511d27", "content_id": "930b480e162111dd1ee7bb0c2b12412165b22c7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 287, "license_type": "no_license", "max_line_length": 67, "num_lines": 8, "path": "/Ch8/8-14 Cars.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "def make_car(manufacturer, model, **car_details):\n \"\"\"Create car details\"\"\"\n car_details[\"manufacturer_name\"] = manufacturer.title()\n car_details[\"model_name\"] = model.title()\n return car_details\n\ncar = make_car('subaru', 'outback', color='blue', tow_package=True)\nprint(car)" }, { "alpha_fraction": 0.6982758641242981, "alphanum_fraction": 0.7586206793785095, "avg_line_length": 28.25, "blob_id": "5b6c86599e37808e177fa30388965b5c35477480", "content_id": "c7f48e35d3762bdb64771603a2cc1838a45ceba0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 116, "license_type": "no_license", "max_line_length": 65, "num_lines": 4, "path": "/Ch11/11 1-2/city_main.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "import city_class\n\nsantiago_chille = city_class.City('chile', 'santiago', 6_269_384)\nsantiago_chille.city_formater()" }, { "alpha_fraction": 0.7191011309623718, "alphanum_fraction": 0.7191011309623718, "avg_line_length": 28.83333396911621, "blob_id": "0b9b002de83457343850b96cb7e49f8b88ecc82d", "content_id": "7aee89ebfb41bcdeb0552438a487c81adb08fd60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 178, "license_type": "no_license", "max_line_length": 53, "num_lines": 6, "path": "/Ch8/8-5 cities.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "def describe_city(city_name, city_country='Romania'):\n print(f\"{city_name} is in {city_country}\")\n\ndescribe_city('Cluj-Napoca')\ndescribe_city('Brasov')\ndescribe_city('Moscow')" }, { "alpha_fraction": 0.7260981798171997, "alphanum_fraction": 0.7467700242996216, "avg_line_length": 31.25, "blob_id": "fdfc23122ddb30cffe4543966af5756f92ddc5ae", "content_id": "6d706f36d664cba397eafb0d7d5f0d10c9027f24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 387, "license_type": "no_license", "max_line_length": 60, "num_lines": 12, "path": "/Ch10/10-11-12/fav_numbers.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "import json_handler_class\n\nnumber_add = \"We'll remmeber that your favorinte number is:\"\nnumber_display = \"Your favorinte number is:\"\nprompt = \"What is your favorite number? \"\nfile_name = \"Ch10/10-11-12/fav_number.json\"\n\nfav_nr = json_handler_class.JasonHandler(file_name)\ntry:\n fav_nr.read_from_json(number_display)\nexcept FileNotFoundError:\n fav_nr.add_to_json(prompt,number_add)\n" }, { "alpha_fraction": 0.6898148059844971, "alphanum_fraction": 0.6898148059844971, "avg_line_length": 32.30769348144531, "blob_id": "832fffcba60be06353c3e2ecfafe831f1eb11b0c", "content_id": "617c1873792563f1493ae618c1b1c42c0261ac2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 432, "license_type": "no_license", "max_line_length": 111, "num_lines": 13, "path": "/Ch7/7-9 No Pastramy.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "sandwich_orders = ['BLT', 'Pastrami', 'Tuna', 'Veggie', 'Pastrami', 'chicken salad', 'Pastrami', 'Italian BMT']\nfinished_sandwiches = []\n\nprint('We are out of Pastrami!')\n\nwhile sandwich_orders: \n while 'Pastrami' in sandwich_orders:\n sandwich_orders.remove('Pastrami')\n\n sandwich_order = sandwich_orders.pop()\n\n print(f\"Your {sandwich_order} sandwich is finished.\")\n finished_sandwiches.append(sandwich_order)" }, { "alpha_fraction": 0.6785396337509155, "alphanum_fraction": 0.700801432132721, "avg_line_length": 24.545454025268555, "blob_id": "603540d3195769a1764f8e78c42ad9cf9d16f073", "content_id": "7c301e6253930bc15ee7c56f94d0c152c7f2a37b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1123, "license_type": "no_license", "max_line_length": 52, "num_lines": 44, "path": "/Ch3/GuestList.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "#Exercisse 3-4\npeople = [\"Hendrix\", \"Page\", \"Freddy\"]\nprint(f\"{people} are invited to dinner\")\n\n#Exercise 3-5\ncant_makeit = people.pop(2)\nprint (f\"{cant_makeit} can't make it\")\npeople.append(\"Cobain\")\nprint(f\"{people} are invited to dinner\")\n\n#Exercise 3-6\nprint(\"I found a bigger table\")\npeople.insert(0, \"Einstein\")\npeople.insert(2, \"Hitler\")\npeople.append(\"Stalin\")\nprint(f\"{people[0]} you're invited to dinner\")\nprint(f\"{people[1]} you're invited to dinner\")\nprint(f\"{people[2]} you're invited to dinner\")\nprint(f\"{people[3]} you're invited to dinner\")\nprint(f\"{people[4]} you're invited to dinner\")\nprint(f\"{people[5]} you're invited to dinner\")\n\n#Exercise 3-7\nprint(\"I can only invite two people for dinner\")\nprint(f\"{people.pop()} you're uninvited\")\nprint(f\"{people.pop()} you're uninvited\")\nprint(f\"{people.pop()} you're uninvited\")\nprint(f\"{people.pop()} you're uninvited\")\n\nprint(f\"{people[0]} you're still invited to dinner\")\nprint(f\"{people[1]} you're still invited to dinner\")\n\n#3-9\nlist_len = len(people)\nprint(list_len)\n\ndel people[1]\ndel people[0]\n\nprint(people)\n\n#3-9\nlist_len = len(people)\nprint(list_len)" }, { "alpha_fraction": 0.7631579041481018, "alphanum_fraction": 0.7631579041481018, "avg_line_length": 14.399999618530273, "blob_id": "4ef5e2ac777351b0c99017a2946b05c97747429c", "content_id": "43015dd9ebdc068fc795605a9996714048dbb0ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 76, "license_type": "no_license", "max_line_length": 32, "num_lines": 5, "path": "/Ch9/9-14 lottery/play_lottery.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "import lottery\n\nplay_lottery = lottery.Lottery()\n\nprint(play_lottery.play())" }, { "alpha_fraction": 0.7093595862388611, "alphanum_fraction": 0.7093595862388611, "avg_line_length": 36, "blob_id": "67820ecc3a61172d969cc9c050e8bb91086f91fb", "content_id": "ea7f7559af82468503bd6df102747a2d87b41e5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 406, "license_type": "no_license", "max_line_length": 57, "num_lines": 11, "path": "/Ch1/name.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "first_name = \"ada \"\nlast_name = \" lovelace\"\n#rstrip() - removes white space from right side of string\n#lstrip() - removes white space from left side of string\n#strip() - removes white space from both sides of string\nfull_name = f\"{first_name.rstrip()} {last_name.lstrip()}\"\nprint(full_name.title())\nprint(full_name.upper())\nprint(full_name.lower())\nmessage = (f\"Hello, {full_name.title()}!\")\nprint(message)" }, { "alpha_fraction": 0.5742574334144592, "alphanum_fraction": 0.5742574334144592, "avg_line_length": 29.350000381469727, "blob_id": "427cace33ddd4c277be1616abf3577ac7e851636", "content_id": "d51e21a5f78fb1861703100c118e5ab60c4239eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 606, "license_type": "no_license", "max_line_length": 66, "num_lines": 20, "path": "/Ch10/10-11-12/json_handler_class.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "import json\n\nclass JasonHandler:\n def __init__(self, file_name):\n self.file_name = file_name\n\n def add_to_json(self, prompt, message):\n \"\"\"ads info to specifie json file and prints message\"\"\"\n info = input(prompt)\n with open(self.file_name, 'w') as f:\n json.dump(info, f)\n print(f\"{message} {info}\")\n return info\n\n def read_from_json(self, message):\n \"\"\"Reads info from specifi json file and prints message\"\"\"\n with open(self.file_name) as f:\n info = json.load(f)\n print(f\"{message} {info}\")\n return info" }, { "alpha_fraction": 0.6300715804100037, "alphanum_fraction": 0.6396181583404541, "avg_line_length": 20, "blob_id": "75e7d026089e9e452c8fd242b1c2aee5227b88a7", "content_id": "58ad35e1d03572c0a70f934676b4a900adfc7de5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 419, "license_type": "no_license", "max_line_length": 70, "num_lines": 20, "path": "/Ch9/9-14 lottery/lottery_statistics.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "import lottery\n\nmy_ticket = [1, 8, 'a', 'c']\nnr_runs = 0\n\nplay_lottery = lottery.Lottery()\n\ntest = True\nwhile test:\n #runs the lottery method until the results matches the 'my_ticket'\n #also counts the number of runs\n result = set(play_lottery.play())\n my_ticket = set(my_ticket)\n print(result)\n nr_runs += 1\n if result == my_ticket:\n break\n\nprint(nr_runs)\nprint(f\"{result} and {my_ticket}\")" }, { "alpha_fraction": 0.47663551568984985, "alphanum_fraction": 0.5046728849411011, "avg_line_length": 25.8125, "blob_id": "7895da984a6bb5c62c4066a0d7a3b66701e459e4", "content_id": "9c6257eb53c8c36b5b4a7aaa0ed2ab9a132d5d34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 428, "license_type": "no_license", "max_line_length": 76, "num_lines": 16, "path": "/Ch9/9-14 lottery/lottery.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "from random import choice\n\n\"\"\"Lotery class\"\"\"\nclass Lottery:\n def __init__(self):\n self.pool = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd', 'e')\n\n def play(self):\n \"\"\" \n Play method used to create a list with the results of a lottery run\n \"\"\"\n results = []\n for x in range(4):\n result = choice(self.pool)\n results.append(result)\n return results" }, { "alpha_fraction": 0.6242476105690002, "alphanum_fraction": 0.6337059140205383, "avg_line_length": 27.390243530273438, "blob_id": "668802b57ddb9d2d1b1188ff2dbb0c04c702a235", "content_id": "e0c589786a77f9b8f1d893c0702724ae501d192c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1163, "license_type": "no_license", "max_line_length": 94, "num_lines": 41, "path": "/Ch6/dictionarielooping.py", "repo_name": "noobul/PythonTraining", "src_encoding": "UTF-8", "text": "#6-4 Glossary 2\nprogramming_words = {\n \"variable\" : \"keyword that can store data\",\n \"string\" : \"text data type\",\n \"boolean\" : \"data type that can have the value 'true' and 'false'\",\n \"if-else condition\" : \"method for checking conditions and executing code based on result\",\n \"integer\" : \"whole-number data type\",\n}\n\nfor variable, definition in programming_words.items():\n print(f\"The {variable} is a {definition}\")\n\n#6-5 Rivers\nmajor_rivers = {\n 'nile' : 'egypt',\n 'danube' : 'romania',\n 'amazon' : 'brazil',\n}\n\nfor river, country in major_rivers.items():\n print(f\"The {river.title()} runs through {country.title()}\")\nfor river1 in major_rivers.keys():\n print(river1)\nfor country1 in major_rivers.values():\n print(country1)\n\n#6-6 Polling\nfavourite_languages = {\n 'jen' : 'python',\n 'sarah' : 'C',\n 'edward' : 'ruby',\n 'phil' : 'python',\n}\n\npeople_to_thake_the_poll = ('jen', 'phil', 'matt', 'maria')\n\nfor person in favourite_languages:\n if person in people_to_thake_the_poll:\n print(f\"Thank you, {person.title()}, for taking the poll.\")\n else:\n print(f\"{person.title()}! Please take the poll.\")" } ]
62
Elkarnet/scripts
https://github.com/Elkarnet/scripts
0e8f36280ecde797f7e80d7b96b80d42d32c41d7
a3598abbf692d60dcf516a14bd37ce8c17650f13
085b9205b13fac2392399f9125aa7adcb96407bb
refs/heads/master
2016-09-05T17:13:33.363668
2014-04-10T11:43:13
2014-04-10T11:43:13
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4688405692577362, "alphanum_fraction": 0.4789855182170868, "avg_line_length": 25.538461685180664, "blob_id": "4c3981bd7eb133b296bb899471493bf585e5967d", "content_id": "39b380de5302acf848386ceca617521f93fe6965", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1380, "license_type": "no_license", "max_line_length": 74, "num_lines": 52, "path": "/dhcp/LeaseInfo.py", "repo_name": "Elkarnet/scripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\ndef split_ip(ip):\n return tuple(int(part) for part in ip.split('.'))\n\ndef ip_key(item):\n return split_ip(item[0])\n\ndef parse(fileName):\n\n f = open( fileName, \"r\" )\n output = {}\n thisIp = \"\"\n thisMAC = \"\"\n thisName = \"\"\n \n for line in f:\n \n # ip\n if (line.find(\"lease\") == 0):\n if (thisIp != \"\"):\n output[thisIp] = thisIp + \" \" + thisMAC + \" \" + thisName\n thisMAC = \"\"\n thisName = \"\"\n \n thisIp = line[line.find(\" \") +1 : line.find(\"{\") -1]\n\n # mac\n if(line.find(\"hardware ethernet\") > -1):\n thisMAC = line[line.find(\"ethernet\") +9 : line.find(\";\")]\n \n # uid - will be replaced with name if it exists\n if(line.find(\"uid\") > -1):\n thisName = line[line.find(\"uid\") +5 : line.find(\";\") -1]\n \n # hostname\n if(line.find(\"client-hostname\") > -1):\n thisName = line[line.find(\"hostname\") +10 : line.find(\";\") -1]\n \n #final line\n if (thisIp != \"\"):\n output[thisIp] = thisIp + \" \" + thisMAC + \" \" + thisName\n\n #print output\n for k, v in sorted(output.items(), key=ip_key):\n print(v)\n\n # Close the file\n f.close()\n \n#parse(\"/home/james/Source/LeaseInfo/dhcpd.leases\")\nparse(\"/var/lib/dhcp/dhcpd.leases\")\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 29, "blob_id": "9f8f43abd86bc714fa2023838d92b487a3a05110", "content_id": "c921e90ef9b754404d67e24950db7447bcb75b0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 120, "license_type": "no_license", "max_line_length": 99, "num_lines": 4, "path": "/README.md", "repo_name": "Elkarnet/scripts", "src_encoding": "UTF-8", "text": "# Scripts\n\n### DHCP\n* __LeaseInfo.py__: DHCP zerbitzarian script hau exekutatuz, IP esleipenen zerrenda bat jasoko dugu\n" } ]
2
Nikhil-oruganti/automated_email-python-
https://github.com/Nikhil-oruganti/automated_email-python-
41672d6e90343c0f721b84a617473d0f27ef9ab3
6e98f700885e170c6030a000aa8e7a1628e5f845
ec0340bb868ec46d141677aed1e5d94624a9dada
refs/heads/main
2023-06-18T11:05:53.421536
2021-07-15T18:32:55
2021-07-15T18:32:55
386,384,734
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5920398235321045, "alphanum_fraction": 0.5995025038719177, "avg_line_length": 24.66666603088379, "blob_id": "9593a1bd6dbba0c16265eba7ef1bfe36248c901b", "content_id": "ed10d02e9c77770e513a0495873d22d9f95e9c7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 402, "license_type": "no_license", "max_line_length": 46, "num_lines": 15, "path": "/automatic email.py", "repo_name": "Nikhil-oruganti/automated_email-python-", "src_encoding": "UTF-8", "text": "import os\r\nimport random\r\nimport smtplib\r\n\r\ndef automated_mail():\r\n email = input(\" enter your email:\")\r\n name = input(\" enter yoyr full name:\")\r\n message= (f\"{name}, welcome to myntra\")\r\n s= smtplib.SMTP('smtp.gmail.com', 587)\r\n s.starttls()\r\n s.login(\"your mail\",\"google app password\")\r\n s.sendmail(\"&&&&&&&&&&&\",email, message)\r\n print(\" email sent!\")\r\n\r\nautomated_mail()\r\n\r\n" }, { "alpha_fraction": 0.8036649227142334, "alphanum_fraction": 0.8036649227142334, "avg_line_length": 62.5, "blob_id": "7459a93c7a6450c14d5b1c7c39698e93b9c0e9d1", "content_id": "a5bcd7b512ba50e064376e8260b74dd2d0fcb816", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 382, "license_type": "no_license", "max_line_length": 124, "num_lines": 6, "path": "/README.md", "repo_name": "Nikhil-oruganti/automated_email-python-", "src_encoding": "UTF-8", "text": "# automated_email in python\n\nIn this repository we will use a smtp library\nsimple mail transfer protocol is used for the trasfer of electronic mail.\nimportant thing is to enter your mail and the google app password in place where mentioned your mail and google app password\nif you are confused on how to find the google app password then just google it. you will find that easily.\n\n" } ]
2
SusheendharVijay/AutoML-Benchmarking
https://github.com/SusheendharVijay/AutoML-Benchmarking
2857e0f5b750bb6cbeb06c36b7a27fee01153767
f2edda14d3e8c2a138b3863384a0ff9cf4bb6a02
c2f8c442c47e85d5d2a19cbd83a25d9947433c46
refs/heads/master
2020-12-13T00:00:50.002040
2020-03-08T06:55:00
2020-03-08T06:55:00
234,263,232
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7947093844413757, "alphanum_fraction": 0.8043964505195618, "avg_line_length": 82.8125, "blob_id": "bc773b4f57b6fcddf9ccf2413a1690c3274ba052", "content_id": "77f07698ffb1cd63fbae1e1c7044ed00e174b630", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2686, "license_type": "no_license", "max_line_length": 446, "num_lines": 32, "path": "/README.md", "repo_name": "SusheendharVijay/AutoML-Benchmarking", "src_encoding": "UTF-8", "text": "# AutoML-Benchmarking\nBenchmarking popular open source Automatic Machine Learning Frameworks. Datasets from OpenML API. \n\nFull Report Link [here](https://docs.google.com/document/d/1ZkKL4Zm8IeD7W6tN6Xpwb8HaY_1cOhAh99EUFs4tgfE/edit?usp=sharing)\n\n### [OpenML](https://www.openml.org/)\nOpenML is an online machine learning platform for sharing and organizing data, machine learning algorithms and experiments. It is designed to create a frictionless, networked ecosystem, that you can readily integrate into your existing processes/code/environments, allowing people all over the world to collaborate and build directly on each other’s latest ideas, data and results, irrespective of the tools and infrastructure they happen to use.\n\n## Frameworks:\n### [H2O AutoML](https://www.h2o.ai/products/h2o/)\nH2O is a fully open-source, distributed in-memory machine learning platform with linear scalability. H2O supports the most widely used statistical & machine learning algorithms, including gradient boosted machines, generalized linear models, deep learning, and many more. H2OAutoML is H2O's automatic machine learning framework. \n\n### [Auto-Sklearn](https://automl.github.io/auto-sklearn/master/)\nAuto-sklearn provides out-of-the-box supervised machine learning. Built around the scikit-learn machine learning library, auto-sklearn automatically searches for the right learning algorithm for a new machine learning dataset and optimizes its hyperparameters. Thus, it frees the machine learning practitioner from these tedious tasks and allows them to focus on the real problem.\n\n### [TPOT](https://epistasislab.github.io/tpot/)\nTPOT (tree-based pipeline optimisation tool) is a Python Automated Machine Learning tool that optimizes machine learning pipelines using genetic programming.TPOT will automate the most tedious part of machine learning by intelligently exploring thousands of possible pipelines to find the best one for your data.\n\nOnce TPOT is finished searching (or you get tired of waiting), it provides you with the Python code for the best pipeline it found so you can tinker with the pipeline from there.TPOT is built on top of scikit-learn, so all of the code it generates should look familiar if you're familiar with scikit-learn.\n\n## Benchmarking process:\n- Time to train 2 mins for each framework.\n- F1 score for classification and R2 score for regression tasks\n- 8 datasets used for recording results. (4-regression,4-classification)\n- Default parameters wherever applicable.\n- Average over two random seeds.\n- Can be run on any number of datasets from OpenML, when provided with the OpenML data_id\n\n## Recorded data\n- f1 scores\n- r2 scores\n- time for prediction \n\n" }, { "alpha_fraction": 0.5756630301475525, "alphanum_fraction": 0.5919570326805115, "avg_line_length": 36.94736862182617, "blob_id": "4ef00b139ae34b19d2820259599269922b5112bc", "content_id": "c6aac2c8bd0dadc2a32b6cc1eea52c14f47ecab8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5769, "license_type": "no_license", "max_line_length": 133, "num_lines": 152, "path": "/autoskl_bench.py", "repo_name": "SusheendharVijay/AutoML-Benchmarking", "src_encoding": "UTF-8", "text": "import openml as oml \nimport pandas as pd \nimport numpy as np\nimport warnings\nfrom sklearn.model_selection import train_test_split\nimport warnings\nfrom sklearn.preprocessing import LabelEncoder \nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.metrics import f1_score,r2_score,roc_auc_score,accuracy_score \nwarnings.simplefilter(action=\"ignore\", category=DeprecationWarning)\nimport autosklearn.classification\nimport autosklearn.regression\nimport time\nimport random\n\n\ncolumns = ['did','name','NumberOfInstances', 'NumberOfFeatures','NumberOfClasses']\noml.config.apikey = 'f7b559f93de31b58e136a7a6ca02c3e9'\noml.config.server = 'https://www.openml.org/api/v1/xml' \ndata_dict = oml.datasets.list_datasets()\ndata_list = pd.DataFrame.from_dict(data_dict,orient='index')\n\ndata_ids = {\n 'classification':[1464,40701,1046], #1461 showing error while evaluating together,until then training it separately. \n 'regression':[196,308,537,344]\n }\n\n\n\n\ndef autoskl_benchmarking(data_id,problem_type):\n\n data = oml.datasets.get_dataset(data_id)\n\n if problem_type == 'classification':\n \n X,y,categorical_indicator,attribute_names = data.get_data(target=data.default_target_attribute)\n df1 = pd.DataFrame(X,columns=attribute_names)\n \n feat_type = ['Categorical' if ci else 'Numerical' for ci in categorical_indicator]\n\n \n f1_scores = []\n time_to_predict=[]\n for feature in X.columns:\n if str(X.dtypes[feature])=='category':\n le = LabelEncoder()\n X[feature] = le.fit_transform(X[feature])\n \n\n\n for seed in random.sample(range(1,100),2):\n\n X_train, X_test, y_train, y_test =train_test_split(X, y, random_state=1)\n\n automl = autosklearn.classification.AutoSklearnClassifier(\n time_left_for_this_task=120, # sec., how long should this seed fit process run\n per_run_time_limit=30, # sec., each model may only take this long before it's killed\n ml_memory_limit=1024, # MB, memory limit imposed on each call to a ML algorithm\n \n )\n with warnings.catch_warnings():\n warnings.simplefilter('ignore',category=RuntimeWarning)\n automl.fit(X_train, y_train,feat_type=feat_type,metric=autosklearn.metrics.f1)\n start_time = time.time()\n y_hat = automl.predict(X_test)\n time_to_predict.append(time.time() - start_time)\n y_hat1 = [str(int(i)) for i in y_hat]\n y_test = np.array(y_test)\n le = LabelEncoder()\n y_hat = le.fit_transform(y_hat1)\n y_test= le.transform(y_test)\n f1_scores.append(f1_score(y_hat,y_test))\n \n\n \n return np.mean(f1_scores),np.mean(time_to_predict)\n\n if problem_type == 'regression':\n X,y,categorical_indicator,attribute_names = data.get_data(target=data.default_target_attribute)\n \n feat_type = ['Categorical' if ci else 'Numerical' for ci in categorical_indicator]\n for feature in X.columns:\n if str(X.dtypes[feature])=='category':\n le = LabelEncoder()\n X[feature] = le.fit_transform(X[feature])\n\n \n r2_scores = []\n time_to_predict=[]\n\n for seed in random.sample(range(1,100),2):\n\n X_train, X_test, y_train, y_test =train_test_split(X, y, random_state=1)\n\n automl = autosklearn.regression.AutoSklearnRegressor(\n time_left_for_this_task=120, # sec., how long should this seed fit process run\n per_run_time_limit=30, # sec., each model may only take this long before it's killed\n ml_memory_limit=1024, # MB, memory limit imposed on each call to a ML algorithm\n \n )\n \n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n automl.fit(X_train, y_train,dataset_name=str(data_id),feat_type=feat_type,metric=autosklearn.metrics.r2)\n start_time = time.time()\n y_hat = automl.predict(X_test)\n time_to_predict.append(time.time() - start_time)\n r2_scores.append(r2_score(y_hat,y_test))\n return np.mean(r2_scores),np.mean(time_to_predict)\n\n\n\n \n \n\ndef bench_scoring(data_ids):\n clf_scores_dict ={}\n reg_scores_dict = {}\n prediction_time={}\n\n for ID in data_ids['classification']:\n score,time_to_predict = autoskl_benchmarking(ID,'classification')\n print('score for {} is :{}'.format(ID,score))\n clf_scores_dict[ID] = score\n prediction_time[ID] = time_to_predict\n\n for ID in data_ids['regression']:\n score = autoskl_benchmarking(ID,'regression')\n print('score for {} is :{}'.format(ID,score))\n reg_scores_dict[ID] = score\n prediction_time[ID] = time_to_predict\n\n return clf_scores_dict,reg_scores_dict,prediction_time\n\n \n \n \n \n \n \n\n\n\nclf_dict,reg_dict,time_dict = bench_scoring(data_ids)\nreg = pd.Series(reg_dict,index=reg_dict.keys())\nclf = pd.Series(clf_dict,index=clf_dict.keys())\ntimings = pd.Series(time_dict,index=time_dict.keys())\n\nreg.to_csv('autoskl_benchmarking/reg_autoskl.csv')\nclf.to_csv('autoskl_benchmarking/clf_autoskl.csv')\ntimings.to_csv('autoskl_benchmarking/time_to_predict_autoskl.csv')\n\n" }, { "alpha_fraction": 0.6794956922531128, "alphanum_fraction": 0.7090245485305786, "avg_line_length": 29.110000610351562, "blob_id": "ab46457d91e97b1b5daa8123f78c7245a4b2416f", "content_id": "aecd52123e1809539f2c4252bffc985224ae6225", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3014, "license_type": "no_license", "max_line_length": 96, "num_lines": 100, "path": "/H2O_bench.py", "repo_name": "SusheendharVijay/AutoML-Benchmarking", "src_encoding": "UTF-8", "text": "import openml as oml \nimport pandas as pd \nimport numpy as np\nimport warnings\nfrom sklearn.model_selection import train_test_split\nimport warnings\nfrom sklearn.preprocessing import LabelEncoder \nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.metrics import f1_score,r2_score,roc_auc_score,accuracy_score \nwarnings.simplefilter(action=\"ignore\", category=DeprecationWarning)\nimport h2o\nfrom h2o.automl import H2OAutoML\nimport time\nimport random\nh2o.init()\n\ncolumns = ['did','name','NumberOfInstances', 'NumberOfFeatures','NumberOfClasses']\noml.config.apikey = 'f7b559f93de31b58e136a7a6ca02c3e9'\noml.config.server = 'https://www.openml.org/api/v1/xml' \ndata_dict = oml.datasets.list_datasets()\ndata_list = pd.DataFrame.from_dict(data_dict,orient='index')\n\ndata_ids = {\n 'classification': [1464,40701,1046,1461], \n 'regression':[196,308,537,344]\n }\n\n\n\ndef H2O_benchmarking(data_id,problem_type):\n\tdata = oml.datasets.get_dataset(data_id)\n\tX,y,categorical_indicator,attribute_names = data.get_data(target=data.default_target_attribute)\n\tX['target'] = y\n\thf = h2o.H2OFrame(X)\n\n\n\ttrain,test = hf.split_frame(ratios=[0.8],seed=1)\n\tx = hf.columns\n\tx.remove('target')\n\ty='target'\n\n\tfor seed in random.sample(range(0,100),2):\n\n\t\taml = H2OAutoML(max_runtime_secs=120,seed=seed)\n\t\taml.train(x=x,y=y,training_frame=train)\n\t\tlb = aml.leaderboard\n\n\t\tf1_scores=[]\n\t\ttime_to_predict=[]\n\t\tr2_scores=[]\n\n\t\tstart_time = time.time()\n\t\tpred = aml.leader.predict(test)\n\t\ttime_to_predict.append(time.time() - start_time)\n\t\t\n\t\tpred = pred.as_data_frame()\n\t\ttest1 = test.as_data_frame()\n\n\t\tif problem_type =='classification':\n\t\t\tpredr = np.round(pred)\n\t\t\tf1_scores.append(f1_score(predr,test1['target']))\n\n\t\tif problem_type == 'regression':\n\t\t\tr2_scores.append(r2_score(pred,test1['target']))\n\n\tif problem_type=='classification':\n\t\treturn np.mean(f1_scores),np.mean(time_to_predict)\n\telse:\n\t\treturn np.mean(r2_scores),np.mean(time_to_predict)\n\n\n\ndef bench_scoring(data_ids):\n\tclf_scores_dict ={}\n\treg_scores_dict = {}\n\tprediction_time ={}\n\n\tfor ID in data_ids['classification']:\n\t score,time_to_predict = H2O_benchmarking(ID,'classification')\n\t print('score for {} is :{}'.format(ID,score))\n\t clf_scores_dict[ID] = score\n\t prediction_time[ID] = time_to_predict\n\n\tfor ID in data_ids['regression']:\n\t score,time_to_predict = H2O_benchmarking(ID,'regression')\n\t print('score for {} is :{}'.format(ID,score))\n\t reg_scores_dict[ID] = score\n\t prediction_time[ID] = time_to_predict\n\n\treturn clf_scores_dict,reg_scores_dict,prediction_time\n\nclf_dict,reg_dict,time_dict = bench_scoring(data_ids)\nprint('classification:{} , regression:{}'.format(clf_dict,reg_dict))\nreg = pd.Series(reg_dict,index=reg_dict.keys())\nclf = pd.Series(clf_dict,index=clf_dict.keys())\ntimings = pd.Series(time_dict,index=time_dict.keys())\n\nreg.to_csv('H2O_benchmarking/reg_h2o.csv')\nclf.to_csv('H2O_benchmarking/clf_h2o.csv')\ntimings.to_csv('H2O_benchmarking/time_to_predict_h2o.csv')\n\n\n\n" }, { "alpha_fraction": 0.7028942704200745, "alphanum_fraction": 0.7448316812515259, "avg_line_length": 30.370370864868164, "blob_id": "fef17e02cade9dc0ea015b3ff132ea2e4884634a", "content_id": "c8c2774c58d1dcc50b1b9a7720493ad3e975b547", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1693, "license_type": "no_license", "max_line_length": 100, "num_lines": 54, "path": "/auto_ml_bench.py", "repo_name": "SusheendharVijay/AutoML-Benchmarking", "src_encoding": "UTF-8", "text": "import openml as oml \nimport pandas as pd \nimport numpy as np\nimport warnings\nfrom sklearn.model_selection import train_test_split\nimport warnings\nfrom sklearn.preprocessing import LabelEncoder \nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.metrics import f1_score,r2_score,roc_auc_score,accuracy_score \nwarnings.simplefilter(action=\"ignore\", category=DeprecationWarning)\nimport time\nimport random\nimport auto_ml\nfrom auto_ml import Predictor\n\ncolumns = ['did','name','NumberOfInstances', 'NumberOfFeatures','NumberOfClasses']\noml.config.apikey = 'f7b559f93de31b58e136a7a6ca02c3e9'\noml.config.server = 'https://www.openml.org/api/v1/xml' \ndata_dict = oml.datasets.list_datasets()\ndata_list = pd.DataFrame.from_dict(data_dict,orient='index')\n\ndata_ids = {\n 'classification':[1464],#[1464,40701,1046]\n 'regression':[196]#[196,308,537,344]\n }\n\n\ndata = oml.datasets.get_dataset(1464)\nX,y,categorical_indicator,attribute_names = data.get_data(target=data.default_target_attribute)\n\t\t\ndf1 = pd.DataFrame(X,columns=attribute_names)\nvectorizer = DictVectorizer(sparse=False)\n\ndf2= vectorizer.fit_transform(df1[df1.columns[0:]].to_dict('records'))\ndf = pd.DataFrame(df2)\n#df['target'] = y\nle = LabelEncoder()\ny = le.fit_transform(y)\n\n\ncolumn_descriptions = {\n\t'target':'output'\n}\n\nX_train,X_test,y_train,y_test = train_test_split(df,y,train_size=0.75,test_size=0.25,random_state=1)\nX_train['target'] = y_train\nX_test['target'] = y_test\n\n\nml_predictor = Predictor(type_of_estimator='classifier',column_descriptions=column_descriptions)\nml_predictor.train(X_train)\n\n#test_score = ml_predictor.score(X_test,X_test.target)\n#print(test_score)" }, { "alpha_fraction": 0.6620262861251831, "alphanum_fraction": 0.7088167071342468, "avg_line_length": 40.629032135009766, "blob_id": "64702057394186827ae9c171238277ffb1f8890f", "content_id": "4697910a544bb5e87873d2458ecce2fc3301227c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2586, "license_type": "no_license", "max_line_length": 130, "num_lines": 62, "path": "/MLBox_bench.py", "repo_name": "SusheendharVijay/AutoML-Benchmarking", "src_encoding": "UTF-8", "text": "import openml as oml \nimport pandas as pd \nimport numpy as np\nimport warnings\nfrom sklearn.model_selection import train_test_split\nimport warnings\nfrom sklearn.preprocessing import LabelEncoder \nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.metrics import f1_score,r2_score,roc_auc_score,accuracy_score \nimport mlbox as mlb\nimport time\nimport random\nwarnings.simplefilter(action=\"ignore\", category=DeprecationWarning)\nwarnings.simplefilter(action=\"ignore\", category=FutureWarning)\n\n\ncolumns = ['did','name','NumberOfInstances', 'NumberOfFeatures','NumberOfClasses']\noml.config.apikey = 'f7b559f93de31b58e136a7a6ca02c3e9'\noml.config.server = 'https://www.openml.org/api/v1/xml' \ndata_dict = oml.datasets.list_datasets()\ndata_list = pd.DataFrame.from_dict(data_dict,orient='index')\n\ndata_ids = {\n 'classification':[1464],#[1464,40701,1046,1461], \n 'regression':[196]#[196,308,537,344]\n }\n\ns=\",\"\nr=mlb.preprocessing.Reader(s)\ndata = oml.datasets.get_dataset(1464)\nX,y,categorical_indicator,attribute_names = data.get_data(target=data.default_target_attribute)\n#X['target'] = y\nX_train, X_test, y_train, y_test =train_test_split(X, y, random_state=1,train_size=0.75,test_size=0.25)\nX_train['target'] = y_train\n#X_test['target'] = y_test\nX_train.to_csv('mlb_data/train_'+str(1416)+'.csv')\nX_test.to_csv('mlb_data/test_'+str(1416)+'.csv')\n\n#with warnings.catch_warnings():\n\t#warnings.simplefilter(\"ignore\", category=FutureWarning)\ndata = r.train_test_split(['mlb_data/train_'+str(1416)+'.csv','mlb_data/test_'+str(1416)+'.csv'],target_name='target')\n\nbest = mlb.preprocessing.Drift_thresholder().fit_transform(data)\n\n\nspace = {'est__strategy':{'search':'choice','space':['RandomForest','ExtraTrees','LightGBM','Bagging','Tree','AdaBoost']},#linear \n'ne__numerical_strategy':{'search':'choice','space':['mean','median']},\n'ne__categorical_strategy':{'search':'choice','space':['mode']},\n'ce__strategy':{'search':'choice','space':['label_encoding','entity_embedding','random_projection']},\n'fs__strategy':{'search':'choice','space':['l1','variance','rf_feature_importance']},\n'fs__threshold':{'search':'uniform','space':[0.01,0.3]},}\n#'est__max_depth':{'search':'choice','space':[3,5,7,9]},}\n#'est__n_estimators':{'search':'choice','space':[250,500,700,1000]}\n#'est__num_leaves':{'search':'choice','space':[7,30,120,500]}}\n\n\nopt = mlb.optimisation.Optimiser(scoring='f1',n_folds=5)\nbest = opt.optimise(space,data,40)\n\n\n#best = mlb.optimisation.Optimiser().evaluate(None,data)\nmlb.prediction.Predictor().fit_predict(best,data)\n\n\n\n\n\n" }, { "alpha_fraction": 0.6250821948051453, "alphanum_fraction": 0.6476649641990662, "avg_line_length": 32.0217399597168, "blob_id": "6a1b8affd0e915bc1be07cdc0eb8f455f20a4c79", "content_id": "870829dd94e92ccb9392f253dc2839ca34bb747a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4561, "license_type": "no_license", "max_line_length": 172, "num_lines": 138, "path": "/tpot_bench.py", "repo_name": "SusheendharVijay/AutoML-Benchmarking", "src_encoding": "UTF-8", "text": "import openml as oml \nimport pandas as pd \nimport numpy as np\nimport warnings\nfrom sklearn.model_selection import train_test_split\nimport warnings\nfrom tpot import TPOTClassifier\nfrom tpot import TPOTRegressor\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder \nfrom sklearn.feature_extraction import DictVectorizer\nwarnings.simplefilter(action=\"ignore\", category=DeprecationWarning)\nimport random\nimport time\n\n\n\ncolumns = ['did','name','NumberOfInstances', 'NumberOfFeatures','NumberOfClasses']\noml.config.apikey = 'f7b559f93de31b58e136a7a6ca02c3e9'\noml.config.server = 'https://www.openml.org/api/v1/xml' \ndata_dict = oml.datasets.list_datasets()\ndata_list = pd.DataFrame.from_dict(data_dict,orient='index')\n\n\n\n\ndef tpot_benchmarking(data_id,problem_type):\n\n data = oml.datasets.get_dataset(data_id)\n\n\n\n if problem_type =='classification':\n X,y,categorical_indicator,attribute_names = data.get_data(target=data.default_target_attribute)\n \n X = pd.get_dummies(X)\n le = LabelEncoder()\n y = le.fit_transform(y)\n X['target'] =y\n df = X.copy()\n\n # for feature in X.columns:\n # if str(X.dtypes[feature])=='category':\n # le = LabelEncoder()\n # X[feature] = le.fit_transform(X[feature])\n\n \n\n training_indices,testing_indices = training_indices,validation_indices = train_test_split(df.index.values,stratify=y,train_size=0.75,test_size=0.25,random_state=42)\n f1_score = []\n time_to_predict =[]\n\n\n\n for seed in random.sample(range(1,100),2):\n\n tpot = TPOTClassifier(verbosity=2,max_eval_time_mins=0.04,max_time_mins=2,population_size=15,cv=5,random_state=seed,scoring='f1')\n tpot.fit(df.drop('target',axis=1).loc[training_indices].values,df.loc[training_indices,'target'].values)\n start_time = time.time()\n preds = tpot.score(df.drop('target',axis=1).loc[validation_indices].values,df.loc[validation_indices, 'target'].values)\n time_to_predict.append(time.time() - start_time)\n f1_score.append(preds)\n\n\n return np.mean(f1_score),np.mean(time_to_predict)\n\n if problem_type == 'regression':\n X,y,categorical_indicator,attribute_names = data.get_data(target=data.default_target_attribute)\n X = pd.get_dummies(X)\n \n \n X['target'] =y\n \n\n #for feature in X.columns:\n # if str(X.dtypes[feature])=='category':\n # le = LabelEncoder()\n # X[feature] = le.fit_transform(X[feature])\n\n df = X.copy()\n training_indices,testing_indices = training_indices,validation_indices = train_test_split(df.index.values,train_size=0.75,test_size=0.25,random_state=42)\n r2 = []\n time_to_predict=[]\n\n for seed in random.sample(range(1,100),2):\n tpot = TPOTRegressor(verbosity=2,max_eval_time_mins=0.04,max_time_mins=2,population_size=15,cv=5,random_state=seed,scoring='r2')\n tpot.fit(df.drop('target',axis=1).loc[training_indices].values,df.loc[training_indices,'target'].values)\n start_time = time.time()\n preds = tpot.score(df.drop('target',axis=1).loc[validation_indices].values,df.loc[validation_indices, 'target'].values)\n time_to_predict.append(time.time() - start_time)\n r2.append(preds)\n\n return np.mean(r2),np.mean(time_to_predict)\n\n\n\n\n\ndata_ids = {\n 'classification':[1464,40701,1046,1461],\n 'regression':[196,308,537,344]\n }\n\n\n\n\ndef bench_scoring(data_ids):\n clf_scores_dict ={}\n reg_scores_dict = {}\n timing_dict={}\n\n for ID in data_ids['classification']:\n score,time_to_predict = tpot_benchmarking(ID,'classification')\n print('score for {} is :{}'.format(ID,score))\n clf_scores_dict[ID] = score\n timing_dict[ID]=time_to_predict\n\n for ID in data_ids['regression']:\n score,time_to_predict = tpot_benchmarking(ID,'regression')\n print('score for {} is :{}'.format(ID,score))\n reg_scores_dict[ID] = score\n timing_dict[ID] = time_to_predict\n\n\n\n\n return clf_scores_dict,reg_scores_dict,timing_dict\n\n\n\nclf_dict,reg_dict,time_dict = bench_scoring(data_ids)\n\nreg = pd.Series(reg_dict,index=reg_dict.keys())\nclf = pd.Series(clf_dict,index=clf_dict.keys())\ntimings = pd.Series(time_dict,index=time_dict.keys())\n\nreg.to_csv('TPOT_benchmarking/reg_tpot.csv')\nclf.to_csv('TPOT_benchmarking/clf_tpot.csv')\ntimings.to_csv('TPOT_benchmarking/time_to_predict_tpot.csv')\n\n\n\n\n" } ]
6
dp-wu/Leet_Code_Python
https://github.com/dp-wu/Leet_Code_Python
ed0efd78dc9b0f696563066add31133403f7abef
0744e9efed0a9c99213ac9d66a6f2d8aeb38579b
7abae1502b8f38419302f244ae328b1f8de37bcd
refs/heads/master
2023-01-10T21:51:56.586238
2023-01-03T20:53:53
2023-01-03T20:53:53
179,170,288
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5634573101997375, "alphanum_fraction": 0.5951859951019287, "avg_line_length": 28.483871459960938, "blob_id": "ff9a3794e562503413cf65cfc1c08a32c1c4eff3", "content_id": "b7535db3839d821f46b6ef04a2bba5e7a25712c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 914, "license_type": "no_license", "max_line_length": 97, "num_lines": 31, "path": "/Palindrome_Number.py", "repo_name": "dp-wu/Leet_Code_Python", "src_encoding": "UTF-8", "text": "\"\"\"\nDetermine whether an integer is a palindrome.\nAn integer is a palindrome when it reads the same backward as forward.\n\nExample:\nInput: -121\nOutput: false\nExplanation: From left to right, it reads -121. From right to left, it becomes 121-.\n\"\"\"\n\n\nclass Solution:\n # Runtime: 100 ms, faster than 94.70% of Python3 online submissions for Palindrome Number.\n # Memory Usage: 13.1 MB, less than 5.03% of Python3 online submissions for Palindrome Number.\n def isPalindrome(self, x: int) -> bool:\n # convert int to list of digits (each digit is a string)\n s = list(str(x))\n\n # go through the list\n while len(s) > 1:\n first = s[0]\n last = s[-1]\n\n # check if the first and the last digits are the same\n if first == last:\n s.pop(0)\n s.pop(-1)\n else:\n return False\n\n return True\n" }, { "alpha_fraction": 0.6471226811408997, "alphanum_fraction": 0.6688382029533386, "avg_line_length": 29.733333587646484, "blob_id": "6755ce6548de0810ef9cce9ee1938d6888e97fb0", "content_id": "19e1ff4de44761080c0b24facd353de6d0f492ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 921, "license_type": "no_license", "max_line_length": 98, "num_lines": 30, "path": "/Implement_strStr.py", "repo_name": "dp-wu/Leet_Code_Python", "src_encoding": "UTF-8", "text": "\"\"\"\nImplement strStr().\nReturn the index of the first occurrence of needle in haystack,\nor -1 if needle is not part of haystack.\n\nExample:\nInput: haystack = \"hello\", needle = \"ll\"\nOutput: 2\n\nWhat should we return when needle is an empty string?\nThis is a great question to ask during an interview.\nFor the purpose of this problem, we will return 0 when needle is an empty string.\nThis is consistent to C's strstr() and Java's indexOf().\n\"\"\"\n\n\nclass Solution:\n # Runtime: 36 ms, faster than 87.27% of Python3 online submissions for Implement strStr().\n # Memory Usage: 13.3 MB, less than 5.13% of Python3 online submissions for Implement strStr().\n def strStr(self, haystack: str, needle: str) -> int:\n if needle is None:\n return 0\n\n elif haystack is None:\n return -1\n\n if needle in haystack:\n return haystack.index(needle)\n else:\n return -1" }, { "alpha_fraction": 0.5559883117675781, "alphanum_fraction": 0.5813047885894775, "avg_line_length": 27.52777862548828, "blob_id": "4daacb3fc3e391fea3195557634bc84d84dd771f", "content_id": "2a85e9f6c4469cb6dedca0a096b2045d2c04f736", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1027, "license_type": "no_license", "max_line_length": 102, "num_lines": 36, "path": "/Search_Insert_Position.py", "repo_name": "dp-wu/Leet_Code_Python", "src_encoding": "UTF-8", "text": "\"\"\"\nGiven a sorted array and a target value,\nreturn the index if the target is found.\nIf not, return the index where it would be if it were inserted in order.\nYou may assume no duplicates in the array.\n\nExample:\nInput: [1,3,5,6], 7\nOutput: 4\n\"\"\"\n\n\nclass Solution:\n # Runtime: 36 ms. faster than 92.83% of Python3 online submissions for Search Insert Position.\n # Memory Usage: 13.7 MB, less than 5.11% of Python3 online submissions for Search Insert Position.\n def searchInsert(self, nums: List[int], target: int) -> int:\n # special cases\n if target in nums:\n return nums.index(target)\n elif target > nums[-1]:\n return len(nums)\n elif target < nums[0]:\n return 0\n\n # general case - binary search\n low = 0\n high = len(nums)\n\n while high - low > 1:\n mid = (high + low) // 2\n if target > nums[mid]:\n low = mid\n elif target < nums[mid]:\n high = mid\n\n return high\n" }, { "alpha_fraction": 0.5973111391067505, "alphanum_fraction": 0.6344430446624756, "avg_line_length": 31.5625, "blob_id": "01abab69754157879d78e26f80a05b662b151c9d", "content_id": "f7c7ebafae6e6fb8e6df1a29770578986068ec5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1562, "license_type": "no_license", "max_line_length": 94, "num_lines": 48, "path": "/Remove_Element.py", "repo_name": "dp-wu/Leet_Code_Python", "src_encoding": "UTF-8", "text": "\"\"\"\nGiven an array nums and a value val,\nremove all instances of that value in-place and return the new length.\nDo not allocate extra space for another array,\nyou must do this by modifying the input array in-place with O(1) extra memory.\nThe order of elements can be changed. It doesn't matter what you leave beyond the new length.\n\nExample:\nGiven nums = [0,1,2,2,3,0,4,2], val = 2,\nYour function should return length = 5,\nwith the first five elements of nums containing 0, 1, 3, 0, and 4.\nNote that the order of those five elements can be arbitrary.\nIt doesn't matter what values are set beyond the returned length.\n\"\"\"\n\n\nclass Solution:\n # Runtime: 52 ms, faster than 15.34% of Python3 online submissions for Remove Element.\n # Memory Usage: 13 MB, less than 5.09% of Python3 online submissions for Remove Element.\n def removeElement(self, nums, val):\n if nums is None:\n return 0\n ind = 0\n while ind < len(nums):\n\n if nums[ind] == val:\n del nums[ind]\n else:\n ind += 1\n print(nums)\n\n # Runtime: 36 ms, faster than 99.26% of Python3 online submissions for Remove Element.\n # Memory Usage: 13.2 MB, less than 5.09% of Python3 online submissions for Remove Element.\n def removeElement2(self, nums, val):\n if nums is None:\n return 0\n\n while True:\n if val in nums:\n nums.remove(val)\n else:\n break\n print(nums)\n\n\n\na = Solution()\nprint(a.removeElement2([0,1,2,2,3,0,4,2], 2))" }, { "alpha_fraction": 0.4878397583961487, "alphanum_fraction": 0.4964234530925751, "avg_line_length": 24.88888931274414, "blob_id": "a6e7204cbfe523269869c1b91646cae698fda741", "content_id": "7bbcd96aeb24b2891998197ab0a2a1dc528f6202", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 699, "license_type": "no_license", "max_line_length": 82, "num_lines": 27, "path": "/Rotate_List.py", "repo_name": "dp-wu/Leet_Code_Python", "src_encoding": "UTF-8", "text": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n if k == 0:\n return head\n if head is None:\n return None\n \n length = 1\n last = head\n while last.next:\n length += 1\n last = last.next\n last.next = head\n\n rotation = length - k % length\n while rotation > 0:\n last = last.next\n rotation -= 1\n \n result = last.next\n last.next = None\n return result\n" }, { "alpha_fraction": 0.5957275032997131, "alphanum_fraction": 0.6243450045585632, "avg_line_length": 44.925926208496094, "blob_id": "6816720b2556df59ab4f7bdb822e8529745f4725", "content_id": "830c95a0c9cc1492ccb156c2e76d466ab3ec4e68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2481, "license_type": "no_license", "max_line_length": 115, "num_lines": 54, "path": "/Remove_Dup_from_Sorted_Array.py", "repo_name": "dp-wu/Leet_Code_Python", "src_encoding": "UTF-8", "text": "\"\"\"\nGiven a sorted array nums, remove the duplicates in-place such that\neach element appear only once and return the new length.\nDo not allocate extra space for another array,\nyou must do this by modifying the input array in-place with O(1) extra memory.\n\nExample:\nGiven nums = [0,0,1,1,1,2,2,3,3,4],\nYour function should return length = 5,\nwith the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.\nIt doesn't matter what values are set beyond the returned length.\n\"\"\"\n\n\nclass Solution:\n # Runtime: 2568 ms, faster than 5.01% of Python3 online submissions for Remove Duplicates from Sorted Array.\n # Memory Usage: 15 MB, less than 5.43% of Python3 online submissions for Remove Duplicates from Sorted Array.\n def removeDuplicates(self, nums: List[int]) -> int:\n if len(nums) <= 1:\n print(nums)\n\n ind = 0\n while ind < len(nums):\n # the time complexity of this 'in' method is depending on the list 'nums'\n # so this function is actually a nested 'while-loop' and make the time complexity roughly O(n^2)\n if nums[ind] in nums[ind + 1:]:\n # this line if use 'del nums[ind]'\n # to replace 'remove()',\n # Runtime: 1996 ms, faster than 5.01% of Python3 online submissions\n # for Remove Duplicates from Sorted Array.\n # Memory Usage: 14.9 MB, less than 5.43% of Python3 online\n # submissions for Remove Duplicates from Sorted Array.\n nums.remove(nums[ind])\n else:\n ind += 1\n print(nums)\n\n # Runtime: 76 ms, faster than 37.97% of Python3 online submissions for Remove Duplicates from Sorted Array.\n # Memory Usage: 14.7 MB, less than 5.43% of Python3 online submissions for Remove Duplicates from Sorted Array.\n def removeDuplicates2(self, nums: List[int]) -> int:\n # inspired from other people's solution.\n if len(nums) <= 1:\n print(nums)\n ind = 1\n # since the given list 'nums' is a sorted list,\n # so all the same digits are showing in a consecutive way.\n # Hence although it's still a nested while-loop, the inner loop only contains 1 element.\n # which makes the whole function's time complexity become O(n)\n while ind < len(nums):\n if nums[ind] == nums[ind - 1]:\n del nums[ind]\n else:\n ind += 1\n print(nums)\n\n" }, { "alpha_fraction": 0.5532491207122803, "alphanum_fraction": 0.5920577645301819, "avg_line_length": 29.77777862548828, "blob_id": "887f9bff812b0273b62f933942a6e6e9cb57e761", "content_id": "25ee37970422c6a5a806b48d864db7c279ca10ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1112, "license_type": "no_license", "max_line_length": 95, "num_lines": 36, "path": "/Reverse_Integer.py", "repo_name": "dp-wu/Leet_Code_Python", "src_encoding": "UTF-8", "text": "\"\"\"\nGiven a 32-bit signed integer, reverse digits of an integer.\nAssume we are dealing with an environment which could only store\nintegers within the 32-bit signed integer range: [−231, 231 − 1].\nFor the purpose of this problem, assume that your function\nreturns 0 when the reversed integer overflows.\n\nExample:\nInput: -123\nOutput: -321\n\"\"\"\n\n\nclass Solution:\n # Runtime: 40 ms, faster than 99.96% of Python3 online submissions for Reverse Integer.\n # Memory Usage: 13.3 MB, less than 5.71% of Python3 online submissions for Reverse Integer.\n def reverse(self, x: int) -> int:\n # convert int into list of digits (each digit is a string)\n s = list(str(abs(x)))\n a = []\n\n # go through the list\n while len(s) != 0:\n # add last item of the list s to list a,\n # the remove the item from list s\n a.append(s.pop(-1))\n\n # check if the answer is valid\n if x >= 0:\n a = int(''.join(a))\n else:\n a = -int(''.join(a))\n if a < -2 ** 31 or a > 2 ** 31 - 1:\n return 0\n\n return a\n" }, { "alpha_fraction": 0.5650887489318848, "alphanum_fraction": 0.6042899489402771, "avg_line_length": 39.969696044921875, "blob_id": "e4706cd39bf3dc018259b2d82c1ee136f9bb9040", "content_id": "2b2682f1100483936aa99a864d118d82504d932b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1352, "license_type": "no_license", "max_line_length": 107, "num_lines": 33, "path": "/Two_Sum.py", "repo_name": "dp-wu/Leet_Code_Python", "src_encoding": "UTF-8", "text": "\"\"\"\nGiven an array of integers, return indices of the two numbers such that they add up to a specific target.\nYou may assume that each input would have exactly one solution, and you may not use the same element twice.\n\nExample:\nGiven nums = [2, 7, 11, 15], target = 9,\nBecause nums[0] + nums[1] = 2 + 7 = 9,\nreturn [0, 1]\n\"\"\"\n\n\nclass Solution:\n # my solution v1\n # Runtime: 1092 ms, faster than 32.87 % of Python3 online submissions for Two Sum.\n # Memory Usage: 13.5 MB, less than 49.67 % of Python3 online submissions for Two Sum.\n def two_sum_v1(self, nums: list[int], target: int) -> list[int]:\n for i in nums:\n ind_i = nums.index(i)\n if (target - i) in nums[ind_i+1:]:\n return [ind_i, nums[ind_i+1:].index(target - i)+ind_i+1]\n\n # solution v2 (learned from other ppl)\n # Runtime: 40 ms, faster than 82.81% of Python3 online submissions for Two Sum.\n # Memory Usage: 14.5 MB, less than 5.08 % of Python3 online submissions for Two Sum.\n def two_sum_v2(self, nums: list[int], target: int) -> list[int]:\n if len(nums) <= 2:\n return [ind for ind, v in enumerate(nums)]\n d = {}\n for ind, v in enumerate(nums):\n complement = target - v\n if complement in d.keys():\n return [d[complement], ind]\n d[v] = ind\n" }, { "alpha_fraction": 0.5353663563728333, "alphanum_fraction": 0.5866158604621887, "avg_line_length": 36.47618865966797, "blob_id": "c1a3efec270599cb2cb1963097c7154f75857c6a", "content_id": "1573f6f14f329b37d0cc56d4c2b9b2f99bca153b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2361, "license_type": "no_license", "max_line_length": 107, "num_lines": 63, "path": "/Roman_to_Integer.py", "repo_name": "dp-wu/Leet_Code_Python", "src_encoding": "UTF-8", "text": "\"\"\"\nRoman numerals are represented by seven different symbols: I, V, X, L, C, D and M.\n'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,\nFor example, two is written as II in Roman numeral, just two one's added together.\nTwelve is written as, XII, which is simply X + II.\nThe number twenty seven is written as XXVII, which is XX + V + II.\n\nRoman numerals are usually written largest to smallest from left to right.\nHowever, the numeral for four is not IIII.\nInstead, the number four is written as IV.\nBecause the one is before the five we subtract it making four. T\nhe same principle applies to the number nine, which is written as IX.\n\nThere are six instances where subtraction is used:\nI can be placed before V (5) and X (10) to make 4 and 9.\nX can be placed before L (50) and C (100) to make 40 and 90.\nC can be placed before D (500) and M (1000) to make 400 and 900.\nGiven a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.\n\nExample:\nInput: \"MCMXCIV\"\nOutput: 1994\nExplanation: M = 1000, CM = 900, XC = 90 and IV = 4.\n\"\"\"\n\n\nclass Solution:\n # Runtime: 68 ms, faster than 96.31% of Python3 online submissions for Roman to Integer.\n # Memory Usage: 13.2 MB, less than 5.05% of Python3 online submissions for Roman to Integer.\n def romanToInt(self, s: str) -> int:\n # create symbol-value dictionary\n d = {\n 'I': 1,\n 'V': 5,\n 'X': 10,\n 'L': 50,\n 'C': 100,\n 'D': 500,\n 'M': 1000,\n }\n # convert string to list of letters\n s = list(s)\n num = 0\n\n # go through the list of letters\n while len(s) > 1:\n # if the first letter represents greater value than the second\n # meaning they aren't forming 4(0, 00) or 9(0, 00)\n if d[s[0]] >= d[s[1]]:\n num += d[s[0]]\n # if the first letter represents smaller value than the second\n # meaning these two letters are forming 4(0, 00) or 9(0, 00) together\n elif d[s[0]] < d[s[1]]:\n num = num + d[s[1]] - d[s[0]]\n s.pop(1)\n # remove the checked item(s) and move the pointer to the next slot\n s.pop(0)\n\n # base case\n if len(s) == 1:\n num += d[s[0]]\n\n return num\n" }, { "alpha_fraction": 0.5800604224205017, "alphanum_fraction": 0.599194347858429, "avg_line_length": 30, "blob_id": "186b7a43c281f57ca6d23d9e27b1c39b7e9b109d", "content_id": "38f06a1a6b6f03261f8c8fbf31b6d1c2f77d0db1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 993, "license_type": "no_license", "max_line_length": 101, "num_lines": 32, "path": "/Logest_Common_Prefix.py", "repo_name": "dp-wu/Leet_Code_Python", "src_encoding": "UTF-8", "text": "\"\"\"\nWrite a function to find the longest common prefix string amongst an array of strings.\nIf there is no common prefix, return an empty string \"\".\nAll given inputs are in lowercase letters a-z.\n\nExample:\nInput: [\"flower\",\"flow\",\"flight\"]\nOutput: \"fl\"\n\"\"\"\n\n\nclass Solution:\n # Runtime: 36 ms, faster than 97.45% of Python3 online submissions for Longest Common Prefix.\n # Memory Usage: 13.2 MB, less than 5.10% of Python3 online submissions for Longest Common Prefix.\n def longestCommonPrefix(self, strs: List[str]) -> str:\n if len(strs) == 1:\n return strs[0]\n elif len(strs) == 0:\n return \"\"\n\n benchmark = min(strs, key=len)\n strs.remove(benchmark)\n prefix = \"\"\n\n counter = 0\n while counter < len(benchmark):\n for i in strs:\n if i[counter] != benchmark[counter]:\n return prefix\n prefix += benchmark[counter]\n counter += 1\n return prefix\n\n" }, { "alpha_fraction": 0.49132949113845825, "alphanum_fraction": 0.5196532011032104, "avg_line_length": 28.3389835357666, "blob_id": "99220aae16a513da38cfbac676ee591b42009773", "content_id": "aab48cf96b32cbd9137e6213229b3b5d97ba99d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1734, "license_type": "no_license", "max_line_length": 101, "num_lines": 59, "path": "/Unsolved_Count_n_Say.py", "repo_name": "dp-wu/Leet_Code_Python", "src_encoding": "UTF-8", "text": "\"\"\"\nCount and Say\n\nThe count-and-say sequence is the sequence of integers with the first five terms as following:\n1. 1\n2. 11\n3. 21\n4. 1211\n5. 111221\n\n1 is read off as \"one 1\" or 11.\n11 is read off as \"two 1s\" or 21.\n21 is read off as \"one 2, then one 1\" or 1211.\n\nGiven an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.\nNote: Each term of the sequence of integers will be represented as a string.\n\"\"\"\n\nimport re\n\n\nclass Solution:\n\n # this solution is modified from the answer posted by StefanPochmann on leetCode discussion board\n # the explanation is posted by FanchenBao, when answering neilteng's question\n def countAndSay(self, n):\n s = '1'\n for _ in range(n - 1):\n # print('------', _, '-----------')\n a = []\n for group, digit in re.findall(r'((.)\\2*)', s):\n a.append(''.join(str(len(group)) + digit))\n # print('group', group, 'digit', digit)\n # print('inner a', a)\n s = ''.join(a)\n # print('***')\n # print('outter s', s)\n return s\n\n\nclass Solution:\n\n # Another solution learned from softray's post on discussion board\n def countAndSay(self, n: int) -> str:\n say = '1'\n for ind in range(n - 1):\n new_say = ''\n pointer = say[0]\n counter = 0\n for letter in say:\n if letter == pointer:\n counter += 1\n else:\n new_say += str(counter) + pointer\n pointer = letter\n counter = 1\n new_say += str(counter) + pointer\n say = new_say\n return say" }, { "alpha_fraction": 0.5120405554771423, "alphanum_fraction": 0.5348542332649231, "avg_line_length": 28.22222137451172, "blob_id": "217798f57906aeb6ec91a5ef1eb739a69c8e6edd", "content_id": "5e881ac4c8b2a35f979312a6ab05e4de9403eae1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1578, "license_type": "no_license", "max_line_length": 97, "num_lines": 54, "path": "/Valid_Parentheses.py", "repo_name": "dp-wu/Leet_Code_Python", "src_encoding": "UTF-8", "text": "\"\"\"\nGiven a string containing just the characters '(', ')', '{', '}', '[' and ']',\ndetermine if the input string is valid.\n\nAn input string is valid if:\nOpen brackets must be closed by the same type of brackets.\nOpen brackets must be closed in the correct order.\nNote that an empty string is also considered valid.\n\nExample:\nInput: \"([)]\"\nOutput: false\n\"\"\"\n\nclass Solution:\n # my solution 1\n # Runtime: 68 ms, faster than 5.88% of Python3 online submissions for Valid Parentheses.\n # Memory Usage: 29.2 MB, less than 5.22% of Python3 online submissions for Valid Parentheses.\n def isValid_v1(self, s: str) -> bool:\n # create pattern\n li = [\"()\", \"[]\", \"{}\"]\n\n # base case\n if len(s) == 0:\n return True\n # recursion\n for i in li:\n if i in s:\n return self.isValid_v1(s.replace(i, ''))\n\n return False\n\n\n # my solution 2\n # Runtime: 36 ms, faster than 84.52% of Python3 online submissions for Valid Parentheses.\n # Memory Usage: 13.2 MB, less than 5.22% of Python3 online submissions for Valid Parentheses.\n def isValid_v2(self, s: str) -> bool:\n d = {')': '(',\n ']': '[',\n '}': '{', }\n stack = []\n\n for i in s:\n if i in d.values():\n stack.append(i)\n elif i in d.keys():\n if d[i] in stack and d[i] == stack[-1]:\n stack.pop(-1)\n else:\n return False\n\n if len(stack) == 0:\n return True\n return False\n" } ]
12
degurii/practice
https://github.com/degurii/practice
b5df95b17596fba85461061f738cf5bac790f6b4
55eb0c0364d35e764be3c669ac704525ba2e12d5
6e21fb93236d39eebd43372fde961f91bc985c2c
refs/heads/master
2018-10-20T16:27:25.533187
2018-07-20T18:12:23
2018-07-20T18:12:23
135,750,542
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.782608687877655, "alphanum_fraction": 0.782608687877655, "avg_line_length": 23, "blob_id": "a8f50c0e9765414da1da4076677f65c4c44798e2", "content_id": "638cf451ebae5514f03002393e16a2f806102524", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 61, "license_type": "no_license", "max_line_length": 23, "num_lines": 1, "path": "/crawling/readme.md", "repo_name": "degurii/practice", "src_encoding": "UTF-8", "text": "프로젝트 데이터를 위해 크롤링을 연습하자" }, { "alpha_fraction": 0.698630154132843, "alphanum_fraction": 0.698630154132843, "avg_line_length": 13.800000190734863, "blob_id": "188c490fd259d6aa4669cd713b5b818fa79d2749", "content_id": "81cc470d5c6ebdf57541248dca6cefa07e9ab1a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 161, "license_type": "no_license", "max_line_length": 31, "num_lines": 5, "path": "/readme.md", "repo_name": "degurii/practice", "src_encoding": "UTF-8", "text": "# Practice\n* 튜토리얼이나 기초적인 예제들을 따라 작성해보자\n\n\n* 하다가 이쯤이면 됐다 싶을때 포기하는 간만 본 코드들" }, { "alpha_fraction": 0.36158648133277893, "alphanum_fraction": 0.3719935119152069, "avg_line_length": 49.183433532714844, "blob_id": "c0c7e93ae803d00497379092691e4e54fb0f73ba", "content_id": "dcc27f82fd69fad57a09650946a5bcddf30f017e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14046, "license_type": "no_license", "max_line_length": 526, "num_lines": 169, "path": "/crawling/chap2/chap2_exam1.py", "repo_name": "degurii/practice", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n'''\r\n연습문제1\r\n1. 다음 사이트에서 링크가 되어 있는 모든 제목을 가져와서 출력합니다.\r\nhttp://media.daum.net/digital/\r\n'''\r\nimport requests\r\nimport re\r\nfrom bs4 import BeautifulSoup as bs\r\n\r\nres = requests.get('http://media.daum.net/digital/')\r\n\r\nsoup = bs(res.content, 'html.parser')\r\n\r\nhyperlink_data = soup.find_all('a', 'link_txt')\r\n# print(hyperlink_data)\r\n\r\n#print(str(hyperlink_data))\r\n#regex = ' ?[가-힣]+ ?[0-9]* ?| ?[0-9]* ?[가-힣]+ ?'\r\nregex = '[가-힣]+ ?[0-9]* ?|[0-9]* ?[가-힣]+ ?'\r\n#print(hyperlink_data)\r\nt1 = str(hyperlink_data).split('@')\r\n#print(t1)\r\ntitle = []\r\nfor i in t1:\r\n print(re.findall(regex, i))\r\n'''\r\nfor i in t1:\r\n s = ''\r\n for j in re.findall(regex, i):\r\n s += j\r\n title.append(s)\r\n\r\nfor i in title:\r\n print(i)\r\n '''\r\n#print(p)\r\n#m = p.match(str(hyperlink_data))\r\n#m = re.sub('[^ ㄱ-ㅣ가-힣]+', str(hyperlink_data))\r\n#print(m)\r\n\r\n'''\r\nOutput\r\n['마크롱 ', '대통령', ' 저커버그에 ', '세금 ', '더 ', '내라', ' 요구할 ', '듯']\r\n['미', '유럽선 ', '구글', '페이스북 ', '등 ', '공룡 ', '규제', ' 목청 ', '기업 ', '분할', ' 주장도']\r\n[' 전쟁 ', '2라운드', ' 구글', '해상도', ' 페이스북 ', '오디오', '더 ', '다양하게', ' 더 ', '스마트하게 ', '온', '오프 ', '간편결제', '애플 ', '겉으론 10', '억', ' 속내는 ', '3억', '7천만', ' 게임 ', '법정 ', '배틀', '애플 ', '배터리게이트', ' 뒤늦은 ', '환불', '배상액 ', '낮추려는 ', '꼼수', '윤곽 ', '드러난 ', '미래쇼핑', '쇼핑도 ', '시대', '사춘기 ', '영양 ', '상태에 ', '따른 ', '신체성장 ', '조절 ', '원리 ', '규명', '식물 ', '노화 ', '속도 ', '조절하는 ', ' 네트워크', ' 찾았다', '장애인 ', '주차구역에 ', '양심불량', ' 주차 ', ' 줄인 ', '비결', '애플', ' 폴크스바겐과 ', '손잡고 ', '자율주행차 ', '개발', '직원용 ', '셔틀']\r\n['도 8', '만원대 ', '무제한요금제', '약관심사중']\r\n['통신요금 ', '인가제 ', '없앤다고', ' 더 ', '큰 ', '대못 ', '박으면서']\r\n['보편요금제', ' 직격탄 ', '맞은 ', '알뜰폰', ' 망 ', '도매대가 ', '협상에 ', '촉각']\r\n['디스플레이 ', '논란 ', '휩싸인 ', '7씽큐', '오해서 ', '비롯된 ', '것']\r\n['7 씽큐', ' 디스플레이 ', '허위광고 ', '논란', '전자 ', '사실 ', '아니다']\r\n['전자', '30 업그레이드한 ', '35 내놓는다', '플랫폼화 ', '전략']\r\n['머스크도 ', '언론과 ', '전쟁', '기자', '매체 ', '신뢰도 ', '평가사이트 ', '열기로']\r\n['언론에 ', '불만', ' 폭발한 ', '일론 ', '머스크', '언론 ', '신뢰도 ', '평가 ', '사이트 ', '만들 ', '것']\r\n['머스크 ', '모델3 ', '브레이크 ', '결함 ', '인정', '빨리 ', '고치겠다']\r\n['사이언스 ', '프리즘']\r\n['이제는 ', '우주 ', '반도체', '다']\r\n['꿀딴지곰의 ', '겜덕연구소']\r\n['코흘리개 ', '시절', ' 게임에 ', '원시인과 ', '공룡만 ', '나오면 ', '즐거웠지']\r\n['디지털산책']\r\n['중국 ', '유니콘 ', '스타트업이 ', '강한 ', '이유']\r\n['이현덕이 ', '만난 ', '생각의 ', '리더']\r\n['김도훈 ', '경희대 ', '교수']\r\n['우주를 ', '보다']\r\n['큐리오시티', ' 화성 ', '표면에 ', '다시 ', '구멍을 ', '뚫다']\r\n['액체가 ', '고체 ', '되는 ', '순간 ', '온도를 ', '처음 ', '측정하다']\r\n['카카오톡', ' 답장 ', '기능 ', '추가']\r\n['사춘기 ', '영양 ', '상태에 ', '따른 ', '신체성장 ', '조절 ', '원리 ', '규명']\r\n[' 미세먼지 ', '측정해 ', '앱으로 ', '알려준다']\r\n['갤럭시노트9 ', '사전예약 ', '시 30', ' 가격 ', '할인 ', '및 ', '갤럭시', '9 플러스 ', '혜택']\r\n['애플 ', '겉으론 10', '억', ' 속내는 ', '3억', '7천만']\r\n['애플 ', '배터리게이트', ' 뒤늦은 ', '환불', '배상액 ', '낮추려는 ', '꼼수']\r\n['더 ', '다양하게', ' 더 ', '스마트하게 ', '온', '오프 ', '간편결제']\r\n['카카오톡', ' 답장 ', '기능 ', '추가', '상단 ', '고정 ', '방 5', '개로 ', '확대']\r\n['장애인 ', '주차구역에 ', '양심불량', ' 주차 ', ' 줄인 ', '비결']\r\n['스마트워치가 ', '몰려온다', '삼성', '애플 ', '삼파전']\r\n['카카오톡', ' 답장 ', '기능 ', '추가']\r\n[' 트럼프', '12 싱가포르 ', '북미회담 ', '전격 ', '취소', '김정은에 ', '공개서한']\r\n['핵실험장 ', '폐기일', ' 허찔린 ', ' 어떻게 ', '반응할까']\r\n['대통령', ' 북미회담 ', '취소에 ', '매우 ', '유감', '직접 ', '대화 ', '촉구']\r\n[' 폼페이오 ', '회담성공 ', '가능성 ', '작게 ', '봤다', '접촉했으나 ', '응답없어']\r\n['회담 ', '성공', ' 확신하던 ', '트럼프', ' 왜 ', '판', ' 깼나']\r\n[' 트럼프', '12 북미회담 ', '취소', '지금은 ', '부적절']\r\n[' 트럼프', ' 취소 ', '30분만에 ', '트윗 ', '메시지 ', '김정은과의 ', '회담을 ', '취소해야만 ', '했다']\r\n[' 핵실험장 ', '폐기하자 ', ' 회담 ', '취소', '한반도 ', '정세 ', '시계제로']\r\n[' 대낮 ', '초등학교 ', '옆에서 ', '살인사건', '흉기 ', '든 ', '채 ', '주변 ', '배회']\r\n[' 미 ', '언론 ', '진전된 ', '외교의 ', '종말', '데탕트 ', '위기']\r\n[' 쥐똥 ', '행주', ' 쓰레기통서 ', '해동', '입맛 ', '가시는 ', '유명 ', '맛집']\r\n[' 케이블카 ', '멈춰 10', '분간 ', '공중에', '한번 ', '탔으니 ', '반액만 ', '환불']\r\n[' 러 ', '의회 ', '핵실험장 ', '폐기 ', '뒤 ', '나온 ', '비건설적 ', '행보']\r\n['전문가들 ', '북미관계', ' 다시 ', '지난해로', '도발 ', '재개할 ', '듯']\r\n[' 불길 ', '뚫고 ', '이웃 ', '구한 ', '시민', '알고보니 ', '배우 ', '박재홍']\r\n[' 트럼프', ' 뒷통수 ', '우려에 ', '불신 ', '증폭', '핵능력 ', '사용않길', ' 경고장']\r\n['대통령 ', '북미정상회담 ', '취소 ', '매우 ', '유감', '해결 ', '기대']\r\n[' 친문 ', '인사들', '지도부에 ', '이재명 ', '비토', ' 서명', '자료집 ', '보내']\r\n[' 풍계리 ', '핵실험장 ', '갱도 ', '폭파', '폐기 ', '공언 34', '일 ', '만']\r\n[' 아파트서 ', '홀로 ', '살던 70', '대 ', '할머니 ', '숨진 ', '지 ', '수일 ', '만에 ', '발견']\r\n[' 출연 ', '미끼로 ', '무명배우에 ', '성폭력 ', '의혹', '유명 ', ' 등 ', '조사']\r\n[' 트럼프 ', '공식 ', '기자회견 ', '북한이 ', '마음 ', '돌릴 ', '때 ', '까지 ', '최대 ', '압박']\r\n[' 손학규', ' 송파을 ', '출마 ', '결심', '하루만에 ', '입장 ', '바꿔']\r\n[' 폼페이오 ', '북미회담 ', ' 반응 ', '없어', '2차 ', '방북후 ', '김정은 ', '태도 ', '변해']\r\n['가슴에 ', '손 ', '올리기도', '촬영 ', '중 ', '성추행', ' 줄 ', '이은 ', '폭로']\r\n[' 성사', ' 자신했는데', ' 한미회담 ', '이틀만에 ', '날벼락']\r\n[' 러 ', '언론 ', '당국 ', '풍계리 ', '외에 ', '다른 ', '핵실험장 ', '없다', '고 ', '밝혀']\r\n['회담 ', '개최지', ' 싱가포르', '회담 ', '취소 ', '유감']\r\n[' 고위급 ', '추정 ', '인물 ', '베이징 ', '도착', '영빈관 ', '이동']\r\n[' 미 ', '언론 ', '진전된 ', '외교의 ', '종말', '데탕트 ', '위기']\r\n['김어준의 ', '블랙하우스', ' 북미정상회담 ', '취소 ', '속보에 ', '방송 ', '중단']\r\n[' 유시민', '썰전', '서 ', '박형준 ', '발언 ', '제지 ', '태영호', ' 얘기할 ', '가치도 ', '없어']\r\n['마이웨이', ' 김애경 ', '남편 ', '김애경과 ', '두 ', '집 ', '살림', '24시간 ', '문자 ', '한다']\r\n[' 정은숙 ', '나한일', ' 내 ', '첫사랑이자 ', '운명같은 ', '사람']\r\n['썰전', ' 이종석 ', '북한 ', '통보하는 ', '버릇 ', '고쳐야']\r\n['처제가 ', '핑클', ' 이상순', ' 요정들에 ', '둘러싸여 ', '흐뭇한 ', '미소']\r\n[' 유이 ', '정해인 ', '잘 ', '되니 ', '잘생겨보여', ' 연락처 ', '그대로인지 ', '궁금']\r\n['동료 ', '성추행', '협박', ' 배우 ', '이서원 ', '검찰조사', '사과하고 ', '싶다']\r\n['도시어부', ' 최현석 ', '이 ', '프로 ', '복지 ', '최악', ' 호통']\r\n['꽃보다 ', '할배 ', '리턴즈', '6월', '4일 ', '출국', '새 ', '시즌 ', '촬영 ', '돌입']\r\n[' 우디 ', '앨런 ', ' 입양 ', '아들', '충격 ', '폭로 ', '가 ', '자식들 ', '학대했다']\r\n['해투3', ' 안영미', ' 남친과의 ', '열애스토리 ', '공개', '셀럽파이브 1', '위 ', '퇴근 ']\r\n['이리와 ', '안아줘', ' 허준호 ', '자서전 ', '출판에 ', '장기용', '진기주 ', '인생 ', '흔들']\r\n['마이웨이', ' 김애경 ', '고3 ', '시절 ', '의 ', '외도', ' 충격적 ', '기억']\r\n['향한 ', '그리움', '어서와', ' 장민', ' 스페인 ', '친구들과 ', '추억 ', '한쌈']\r\n[' 재혼 ', '앞둔 ', '기네스 ', '팰트로 ', '더 ', '이상 ', '아이 ', '원치 ', '않아']\r\n[' 이창동 ', '감독이 ', '한국에 ', '없던 ', '배우', '라 ', '반한 24', '살 ', '신인']\r\n[' 배우 ', '나한일', ' 동료 ', '정은숙과 27', '일 ', '결혼']\r\n['오늘내일', ' 김용만', ' 고지혈에 ', '지방간까지', '휴식 ', '필요한 ', '골골이', ' 당첨']\r\n['오작두', ' 유이 ', '말랐다는 ', '걱정 ', '알아', '체력 ', '관리 ', '중']\r\n['썰전', ' 유시민 ', '남북고위급회담 ', '취소', '의 ', '과잉반응']\r\n['슈츠', ' 장동건', '박형식', ' 재심 ', '승소', '12년 ', '전 ', '진실 ', '밝혔다']\r\n[' 나한일', ' 유혜영과 ', '2번의 ', '결혼', '이혼', '전 ', '연인 ', '정은숙과 ', '옥중결혼']\r\n['해투3', ' 안영미 ', '남친', ' 라디오 ', '청취자 ', '출신', '3년째 ', '연애중']\r\n['인형의 ', '집', ' 박하나', ' 왕빛나 ', '선처', ' 친모와 ', '극적상봉']\r\n[' 이서원', ' 사과해도 ', '복귀 ', '어려운 ', '배우 ', '인생']\r\n['인생술집', ' 박정현', ' 주당이라는 ', '소문 ', '해명 ', '실제 ', '주량 ', '와인 ', '한 ', '병']\r\n['버닝', ' 유아인의 ', '흐리멍덩한 ', '눈', ' 이창동의 ', '불편한 ', '질문']\r\n[' 기네스 ', '팰트로 ', ' 연인 ', '브래드 ', '피트', ' 성추행 ', '위협에서 ', '날 ', '보호']\r\n['우만기', ' 마지막회 ', '대본 ', '나왔다', '김명민 ', '선택이냐 ', '죽음이냐']\r\n[' 호나우지뉴', ' 두 ', '여성과 ', '동시 ', '결혼식 ', '준비', '조화롭게 ', '사는 ', '중']\r\n[' 축구전문가', '라멜라', '알리', '에릭센 ', '수준 ', '못 ', '미쳐']\r\n['전', ' 경기중 ', '대기심이 ', '이례적 ', '오심 ', '인정']\r\n[' 토트넘', ' 포체티노 ', '감독과 2023', '년까지 ', '재계약']\r\n['어디서든 1', '승만 ', '더', ' 한화', ' 성공적인 ', '두산 3', '연전']\r\n[' 왕웨이중 ', '기다린 ', '대만', ' 소사에 ', '놀랐다']\r\n[' 이 ', '정도로 ', '흔들린 ', '김주찬을 ', '본 ', '적이 ', '있나']\r\n[' 충격 ', '증언 ', '외국인 ', '감독 ', '죽이기', ' 전명규 ', '지시였다']\r\n[' 논란의 ', '빙상 ', '경기복 ', '교체', '사전 ', '정보 ', '유출 ', '정황 ', '확인']\r\n['류현진 ', '아내', ' 배지현', ' 왁스 ', '군단 ', '합류 ', '여전한 ', '미모']\r\n['김연경 17', '점', ' 한국', ' 이탈리아에 ', '완패', '5연승 ', '좌절']\r\n[' 문체부 ', '심석희 ', '수십 ', '차례 ', '폭행 ', '코치', ' 수사 ', '의뢰']\r\n[' 이탈리아 ', '감독 ', '김연경에게 ', '공 ', '안 ', '주는 ', '작전 ', '주효']\r\n[' 이영표의 ', '한숨 ', '한국은 ', '축구를 ', '좋아하는 ', '게 ', '아니다']\r\n[' 삼성', '한화', ' 탈보트', ' 클리블랜드와 ', '계약', ' 복귀 ', '조준']\r\n[' 언론', '커쇼', '류현진 ', '없이 ', '선발 ', '06 인상적']\r\n[' 진출', ' 이니에스타', ' 야구장 ', '방문으로 ', '일정 ', '시작']\r\n[' 불펜 ', '역전패 ', '악몽', ' 선수단 ', '전체에 ', '물들다']\r\n[' 월드컵 ', ' 구호', '아시아의 ', '호랑이', ' 세계를 ', '삼켜라', ' 확정']\r\n['6실책 ', '자멸', '13 완패', '고영표 11', ' 완투승']\r\n[' 박지수 ', '방출 ', '위기', ' 넘겨', ' 라스베이거스 ', '로스터 ', '잔류']\r\n[' 심판진', ' 경기도중 ', '오심인정', '대체 ', '무슨일이']\r\n['최대 1', '년', ' 권창훈 ', '부상', ' 아시안게임도 ', '불가능하다']\r\n['박지성 ', '절친', ' 에브라', ' 웨스트햄 ', '떠난다', '계약 ', '만료']\r\n[' 이의신청 ', ' 징계 ', '수용', '이승훈의 ', '선택은']\r\n[' 호날두 ', '생물학적 ', '나이 23', '살', '41살까지 ', '뛸 ', '수 ', '있다']\r\n[' 차비', ' 알 ', '사드와 2', '년 ', '더 ', '함께 ', '한다', '재계약 ', '발표']\r\n['징계 ', '없이 ', '중국', ' 심석희 ', '폭행한 ', '조재범 ', '코치', ' 수사기관 ', '수사 ', '나선다']\r\n['3주차에서 ', '빠지는 ', '김연경 ', '네덜란드서 ', '좋은 ', '공부하고 ', '오길']\r\n[' 뜨거웠던 ', '한화와 ', '대전구장', ' 화룡점정까지는 ', '역부족', '자유한국당', '최선희', '최저임금', '북미 ', '정상회담', '김애경', '박지원', '김정은', '손학규', '변희재', '조현아', '한국당', '폼페이오 ', '편지', '트럼프 ', '기자회견', '펜스', '풍계리 ', '핵실험장 ', '폐기', '박재홍', '정국', '이선빈', '오늘내일', '어서와 ', '한국은 ', '처음이지', '장민 ', '아버지', '꽃보다 ', '할배', '류준열', '신태용', '파레디스', '이니에스타', '신태용호', '추신수', '강정호', '정은원', '안지만', '던전형 ', '치열한 ', '전투를 ', '즐겨라', '극강의 ', '군단', ' 용의군단', ' 완성형 ', '뉴스홈', '사회', '정치', '경제', '국제', '문화', '포토', '이슈', '미디어랩', '키워드', '쿼트', '언론사별 ', '뉴스', '배열이력', '전체뉴스', '랭킹', '연재', '스토리펀딩']\r\n\r\n'''" }, { "alpha_fraction": 0.703125, "alphanum_fraction": 0.71875, "avg_line_length": 20.33333396911621, "blob_id": "6cbaac7474ff3448ec34548923dc28b45a552429", "content_id": "d9aba50191c9e5c9904834508297b1a66937e3c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 100, "license_type": "no_license", "max_line_length": 38, "num_lines": 3, "path": "/web/readme.md", "repo_name": "degurii/practice", "src_encoding": "UTF-8", "text": "생활코딩 강의를 듣고 예제를 작성해봅니다.\n\n< https://opentutorials.org/course/1 >\n" } ]
4
jaburges/tuyagateway
https://github.com/jaburges/tuyagateway
35389cfae26d18ad96ccd65e55910a6a76162ec0
653c368aa19cd1bd6b72ca515eb3a4d66cbe2c2a
eb4605f23be0ffe941a6680e65241ee68997abff
refs/heads/master
2023-02-13T23:08:34.675400
2020-08-27T21:34:48
2020-08-27T21:34:48
294,479,878
0
0
null
2020-09-10T17:39:57
2020-09-10T13:56:33
2020-08-27T21:37:30
null
[ { "alpha_fraction": 0.5, "alphanum_fraction": 0.5600000023841858, "avg_line_length": 15.666666984558105, "blob_id": "0576dd90d154f19b53eaab50a1821e399be06655", "content_id": "a0795bb8b2d32a803d0336bfc47dfc46d3651af0", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 50, "license_type": "permissive", "max_line_length": 26, "num_lines": 3, "path": "/version.py", "repo_name": "jaburges/tuyagateway", "src_encoding": "UTF-8", "text": "\"\"\"Version information.\"\"\"\n\n__version__ = \"2.0.1\"\n" } ]
1
JoeKeating/PythonCrashCourse
https://github.com/JoeKeating/PythonCrashCourse
12ac46b2653c47252b7e95a0a81f14c164395f6f
894b75160e96f9e47e1d0cb595747beb2161edfa
4d70d583974dec6126afd058207fc092ef70cb28
refs/heads/master
2020-05-22T09:54:52.705972
2019-05-23T18:11:57
2019-05-23T18:11:57
186,299,647
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6881557106971741, "alphanum_fraction": 0.707769513130188, "avg_line_length": 36.369319915771484, "blob_id": "f8a49c8c79be319694ab4259108d9f9a608335b6", "content_id": "4184623ac9ef726a589492c498c0b9187e3e8b6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6607, "license_type": "no_license", "max_line_length": 120, "num_lines": 176, "path": "/Chapter Four.py", "repo_name": "JoeKeating/PythonCrashCourse", "src_encoding": "UTF-8", "text": "from time import sleep\n\n# 4-1. Pizzas: Think of at least three kinds of your favorite pizza . Store these pizza names in a list,\n# and then use a for loop to print the name of each pizza .\n# • Modify your for loop to print a sentence using the name of the pizza instead of printing just the name of the pizza.\n# For each pizza you should have one line of output containing a simple statement like I like pepperoni pizza.\n#\n# • Add a line at the end of your program, outside the for loop, that states how much you like pizza.\n# The output should consist of three or more lines about the kinds of pizza you like and then an additional sentence,\n# such as I really love pizza!\n\nprint(\"Exercise 4-1\")\npizzas = [\"Cheese\", \"Pepperoni\", \"The Works\", \"Sausage\"]\n\nfor pizza in pizzas:\n print(\"Gimme some \" + pizza + \" pizza!\")\n\nprint(\"I do love me some pizza!\")\n\n# 4-2. Animals: Think of at least three different animals that have a common characteristic .\n# Store the names of these animals in a list, and then use a for loop to print out the name of each animal .\n# • Modify your program to print a statement about each animal, such as\n# A dog would make a great pet.\n# • Add a line at the end of your program stating what these animals have in common .\n# You could print a sentence such as Any of these animals would make a great pet!\n\nprint(\"Exercise 4-2\")\n\nanimals = [\"Dog\", \"Cat\", \"Fish\"]\n\nfor animal in animals:\n print(\"A \" + animal + \" would make a great pet!\")\n\nprint(\"All these animals would make great pets!\")\n\n# 4-3. Counting to Twenty: Use a for loop to print the numbers from 1 to 20, inclusive .\nprint(\"\\nExercise 4-3\")\n\nfor i in range(1, 21):\n print(i)\n\n\n\n# 4-4. One Million: Make a list of the numbers from one to one million, and then use a for loop to print the numbers.\n# (If the output is taking too long, stop it by pressing ctrl-C or by closing the output window .)\n\nsleep(3)\nprint(\"\\nExercise 4-4\")\nprint(\"Begin to populate millions\")\nmillions = []\nfor i in range(1, 1000001):\n millions.append(i)\nprint(\"Finished populating millions\")\n\n#for million in millions:\n #print(million)\n \n# 4-5. Summing a Million: Make a list of the numbers from one to one million, and then use min() and max()\n# to make sure your list actually starts at one and ends at one million . Also, use the sum() function to see how\n# quickly Python can add a million numbers .\n\nprint(\"Exercise 4-5\")\ndollars = [ i for i in range(1, 1000001)]\nprint(\"The length of dollars is: \" + str(len(dollars)))\nprint(\"The min value in dollars is: \" + str(min(dollars)))\nprint(\"The max value in dollars is: \" + str(max(dollars)))\nprint(\"The sum of all the values in dollars is: \" + str(sum(dollars)))\n\n\n# 4-6. Odd Numbers: Use the third argument of the range() function to make a list of the odd numbers from 1 to 20 .\n# Use a for loop to print each number .\n\nprint(\"Exercise 4-6\")\n\nnumbers = [i for i in range(1, 21, 2)]\nprint(\"Odd numbers: \" + str(numbers))\nnumbers = [i for i in range(2, 21, 2)]\nprint(\"Even numbers: \" + str(numbers))\n# 4-7. Threes: Make a list of the multiples of 3 from 3 to 30 . Use a for loop to print the numbers in your list.\nprint(\"Exercise 4-7\")\n\nnumbers = [i for i in range(3, 30, 3)]\nfor number in numbers:\n print(number)\n# 4-8. Cubes: A number raised to the third power is called a cube . For example, the cube of 2 is written as 2**3\n# in Python . Make a list of the first 10 cubes (that is, the cube of each integer from 1 through 10), and\n# use a for loop to print out the value of each cube .\nprint(\"Exercise 4-8\")\n\ncubes = [i**3 for i in range(1, 11)]\n\nfor cube in cubes:\n print(cube)\n\n# 4-9. Cube Comprehension: Use a list comprehension to generate a list of the first 10 cubes .\n\nprint(\"Exercise 4-9\")\n\ncubes = [i**3 for i in range(1, 11)]\n\nfor cube in cubes:\n print(cube)\n\n# 4-10. Slices: Using one of the programs you wrote in this chapter, add several\n# lines to the end of the program that do the following:\n# • Print the message, The first three items in the list are:. Then use a slice to\n# print the first three items from that program’s list.\n# • Print the message, Three items from the middle of the list are:. Use a slice\n# to print three items from the middle of the list.\n# • Print the message, The last three items in the list are:. Use a slice to print\n# the last three items in the list.\n\nprint(\"Exercise 4-10\")\n\nprint(\"The first three items of the list are: \" + str(cubes[:3]))\nprint(\"The middle three items of the list are: \" + str(cubes[4:7]))\nprint(\"The last three items of the list are: \" + str(cubes[7:]))\n\n\n# 4-11. My Pizzas, Your Pizzas: Start with your program from Exercise 4-1\n# (page 60). Make a copy of the list of pizzas, and call it friend_pizzas.\n# Then, do the following:\n# • Add a new pizza to the original list.\n# • Add a different pizza to the list friend_pizzas.\n# • Prove that you have two separate lists. Print the message, My favorite\n# pizzas are:, and then use a for loop to print the first list. Print the message,\n#\n# My friend’s favorite pizzas are:, and then use a for loop to print the sec-\n# ond list. Make sure each new pizza is stored in the appropriate list.\n\nsleep(3)\nprint(\"Exercise 4-11\")\nprint(pizzas)\nfriends_pizzas = pizzas[:]\npizzas.append(\"Veggie\")\nfriends_pizzas.append(\"BBQ Chicken\")\nprint(\"My favorite pizzas are: \")\nfor pizza in pizzas:\n print(pizza)\n\nprint(\"My friend's favorite pizzas are: \")\nfor pizza in friends_pizzas:\n print(pizza)\n\n#\n# 4-12. More Loops: All versions of foods.py in this section have avoided using\n# for loops when printing to save space. Choose a version of foods.py, and\n# write two for loops to print each list of foods.\nprint(\"Exercise 4-12\")\n\nmy_foods = ['pizza', 'falafel', 'carrot cake']\nfriend_foods = my_foods[:]\n\nprint(\"My favorite foods are:\")\nfor food in my_foods:\n print(food)\n\nprint(\"\\nMy friend's favorite foods are:\")\nfor food in friend_foods:\n print(food)\n\n# 4-13. Buffet: A buffet-style restaurant offers only five basic foods .\n# Think of five simple foods, and store them in a tuple .\n# • Use a for loop to print each food the restaurant offers .\n# • Try to modify one of the items, and make sure that Python rejects the\n# change .\n# • The restaurant changes its menu, replacing two of the items with different foods .\n# Add a block of code that rewrites the tuple, and then use a for loop\n# to print each of the items on the revised menu .\n\nprint(\"Exercise 4-13\")\nmenu = (\"Eggs\", \"Waffles\", \"Pancakes\", \"Bacon\", \"Sausage\")\nmenu = (\"Eggs\", \"Waffles\", \"Pancakes\", \"Grits\", \"Homefries\")\n\nfor item in menu:\n print(item)\n" }, { "alpha_fraction": 0.6491257548332214, "alphanum_fraction": 0.6590341329574585, "avg_line_length": 32.0578498840332, "blob_id": "a28209835252b97a369f5e403c92fa2ca8b0c1ea", "content_id": "723ab8fea609addc88f99d9e3209bd173fbd5613", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12020, "license_type": "no_license", "max_line_length": 120, "num_lines": 363, "path": "/Chapter Nine.py", "repo_name": "JoeKeating/PythonCrashCourse", "src_encoding": "UTF-8", "text": "from time import sleep\n\n# 9-1. Restaurant: Make a class called Restaurant . The __init__() method for\n# Restaurant should store two attributes: a restaurant_name and a cuisine_type .\n# Make a method called describe_restaurant() that prints these two pieces of information,\n# and a method called open_restaurant() that prints a message indi- cating that the restaurant is open .\n# Make an instance called restaurant from your class . Print the two attri- butes individually,\n# and then call both methods .\n\nprint(\"\\nExercise 9-1\")\n\n# Define classes\nclass Restaurant():\n\n def __init__(self, name, cuisine):\n self.name = name\n self.cuisine = cuisine\n\n def describe_restaurant(self):\n print(\"The restaurant \" + self.name + \" serves \" + self.cuisine + \" food.\")\n\n\nmcdonalds = Restaurant(\"McDonalds\", \"Modern American\")\nvolt = Restaurant(\"Volt\", \"Great American\")\n\n\nmy_restaurants = []\n\n\nmy_restaurants.append(mcdonalds.name)\nmy_restaurants.append(volt.name)\n\nfor restaurant in my_restaurants:\n print(restaurant)\n\n\n\n\n# 9-2. Three Restaurants: Start with your class from Exercise 9-1 .\n# Create three different instances from the class, and call describe_restaurant() for each instance .\nprint(\"\\nExercise 9-2\")\n\nmcdonalds = Restaurant(\"McDonalds\", \"Modern American\")\nvolt = Restaurant(\"Volt\", \"Great American\")\nthree_brothers = Restaurant(\"Three Brothers\", \"Pizza\")\n\nmcdonalds.describe_restaurant()\nvolt.describe_restaurant()\nthree_brothers.describe_restaurant()\n\n\n# 9-3. Users: Make a class called User . Create two attributes called first_name and\n# last_name, and then create several other attributes that are typically stored in a user profile .\n# Make a method called describe_user() that prints a summary of the user’s information . Make another method\n# called greet_user() that prints a personalized greeting to the user .\n# Create several instances representing different users, and call both methods for each user .\nprint(\"\\nExercise 9-3\")\n\nclass User():\n\n def __init__(self, first_name, last_name, **traits):\n self.first_name = first_name\n self.last_name = last_name\n self.traits = traits\n\n def describe_user(self):\n print(\"Here are \" + self.first_name + \" \" + self.last_name + \"'s traits:\")\n for key, value in self.traits.items():\n print(\"\\t\" + key + \" : \" + str(value))\n\n def greet_user(self):\n print(\"Greetings, \" + self.first_name + \" \" + self.last_name + \".\")\n\n\ntraci = User(\"Traci\", \"Klotz\", age = 45, occupation = \"release manager\")\n\njoe = User(\"Joe\", \"Keating\", age = 55, height_in_inches = 72, home_town = \"Philly\")\n\nleslie = User(\"Leslie\", \"Keating\", home_town = \"Luke\", favorite_movie = \"Thor:Ragnorok\")\n\nleslie.greet_user()\nleslie.describe_user()\n\ntraci.greet_user()\ntraci.describe_user()\n\njoe.greet_user()\njoe.describe_user()\n\n# 9-4. Number Served: Start with your program from Exercise 9-1 (page 166) . Add an attribute called\n# number_served with a default value of 0 . Create an instance called restaurant from this class .\n# Print the number of customers the restaurant has served, and then change this value and print it again .\n# Add a method called set_number_served() that lets you set the number of customers that have been served .\n# Call this method with a new number and print the value again .\n# Add a method called increment_number_served() that lets you increment the number of customers who’ve been served .\n# Call this method with any num- ber you like that could represent how many customers were served in,\n# say, a day of business .\nprint(\"\\nExercise 9-4\")\n\n# Define classes\nclass Restaurant():\n\n def __init__(self, name, cuisine):\n self.name = name\n self.cuisine = cuisine\n self.number_served = 0\n\n def describe_restaurant(self):\n print(\"The restaurant \" + self.name + \" serves \" + self.cuisine + \" food.\")\n\n\nvolt = Restaurant(\"volt\", \"Modern American\")\n\nprint(\"Yesterday, \" + volt.name.title() + \" served \" + str(volt.number_served) + \" diners.\")\n\nvolt.number_served = 23\n\nprint(\"Yesterday, \" + volt.name.title() + \" served \" + str(volt.number_served) + \" diners.\")\n\n\n# 9-5. Login Attempts: Add an attribute called login_attempts to your User class from Exercise 9-3 (page 166) .\n# Write a method called increment_ login_attempts() that increments the value of login_attempts by 1 . Write another\n# method called reset_login_attempts() that resets the value of login_ attempts to 0 .\n# Make an instance of the User class and call increment_login_attempts() several times .\n# Print the value of login_attempts to make sure it was incremented properly, and then call reset_login_attempts() .\n# Print login_attempts again to make sure it was reset to 0\nprint(\"\\nExercise 9-5\")\n\n\nclass User():\n\n def __init__(self, first_name, last_name, **traits):\n self.first_name = first_name\n self.last_name = last_name\n self.traits = traits\n self.login_attempts = 0\n\n def describe_user(self):\n print(\"Here are \" + self.first_name + \" \" + self.last_name + \"'s traits:\")\n for key, value in self.traits.items():\n print(\"\\t\" + key + \" : \" + str(value))\n\n def greet_user(self):\n print(\"Greetings, \" + self.first_name + \" \" + self.last_name + \".\")\n\n def increment_login_attempts(self):\n self.login_attempts += 1\n\n def reset_login_attempts(self):\n self.login_attempts = 0\n\n\njoe = User(\"Joe\", \"Keating\")\n\nfor i in range(5):\n joe.increment_login_attempts()\n print(\"Login attempts: \" + str(joe.login_attempts) + \"\\n\")\n\n\njoe.reset_login_attempts()\n\nprint(\"Login attempts: \" + str(joe.login_attempts))\n\n\n# 9-6. Ice Cream Stand: An ice cream stand is a specific kind of restaurant .\n# Write a class called IceCreamStand that inherits from the Restaurant class you wrote in Exercise 9-1 (page 166)\n# or Exercise 9-4 (page 171) . Either version of\n# the class will work; just pick the one you like better . Add an attribute called flavors that\n# stores a list of ice cream flavors . Write a method that displays these flavors . Create an instance of IceCreamStand,\n# and call this method .\nsleep(3)\nprint(\"\\nExercise 9-6\")\n\nclass Restaurant():\n\n def __init__(self, name, cuisine):\n self.name = name\n self.cuisine = cuisine\n self.number_served = 0\n\n def describe_restaurant(self):\n print(\"The restaurant \" + self.name + \" serves \" + self.cuisine + \" food.\")\n\n\nclass IceCreamStand(Restaurant):\n\n def __init__(self, name, cuisine, *ice_cream_flavors):\n super().__init__(name, cuisine)\n self.ice_cream_flavors = ice_cream_flavors\n\n def display_flavors(self):\n if self.ice_cream_flavors:\n for flavor in self.ice_cream_flavors:\n print(flavor)\n\n\nmy_stand = IceCreamStand(\"Joe's Ice Cream Stand\", \"Ice Cream\", \"Vanilla\", \"Chocolate\", \"Strawberry\", \"Pistachio\")\n\nmy_stand.display_flavors()\n\n\n# 9-7. Admin: An administrator is a special kind of user . Write a class called Admin that inherits from\n# the User class you wrote in Exercise 9-3 (page 166)\n# or Exercise 9-5 (page 171) . Add an attribute, privileges, that stores a list\n# of strings like \"can add post\", \"can delete post\", \"can ban user\", and so on .\n# Write a method called show_privileges() that lists the administrator’s set of privileges .\n# Create an instance of Admin, and call your method .\nsleep(3)\n\nprint(\"\\nExercise 9-7\")\n\nclass User():\n\n def __init__(self, first_name, last_name, **traits):\n self.first_name = first_name\n self.last_name = last_name\n self.traits = traits\n self.login_attempts = 0\n\n def describe_user(self):\n print(\"Here are \" + self.first_name + \" \" + self.last_name + \"'s traits:\")\n for key, value in self.traits.items():\n print(\"\\t\" + key + \" : \" + str(value))\n\n def greet_user(self):\n print(\"Greetings, \" + self.first_name + \" \" + self.last_name + \".\")\n\n def increment_login_attempts(self):\n self.login_attempts += 1\n\n def reset_login_attempts(self):\n self.login_attempts = 0\n\nclass Admin(User):\n\n def __init__(self, first_name, last_name, *perms, **traits):\n super().__init__(first_name, last_name, **traits)\n self.perms = perms\n\n def show_perms(self):\n print(\"Here are \" + self.first_name + \" \" + self.last_name + \"'s permissions are:\")\n if self.perms:\n for perm in self.perms:\n print(\"\\t\" + perm)\n\n def show_traits(self):\n print(\"Here are \" + self.first_name + \" \" + self.last_name + \"'s traits are:\")\n if self.traits:\n for key, value in self.traits.items():\n print(\"\\t\" + key + \" : \" + str(value))\n\n\nmy_admin = Admin(\"Joe\", \"Keating\", \"Destroy user\", \"Delete System\", \"Destroy the entire net worth of the company\",\n age = 55, hometown = \"philly\")\n\nmy_admin.show_perms()\nmy_admin.show_traits()\n\n\n\n# 9-8. Privileges: Write a separate Privileges class . The class should have one attribute,\n# privileges, that stores a list of strings as described in Exercise 9-7 .\n# Move the show_privileges() method to this class . Make a Privileges instance as\n# an attribute in the Admin class . Create a new instance of Admin and use your method to show its privileges .\n\nsleep(3)\nprint(\"\\n Exercise 9-8\")\n\nclass Permissions():\n\n def __init__(self, perms = [\"Create User\", \"Annihilate entire net worth of company.\"]):\n self.perms = perms\n\n def show_perms(self):\n if self.perms:\n for perm in self.perms:\n print(\"\\n\" + perm)\n\n\nclass Admin(User):\n\n def __init__(self, first_name, last_name, **traits):\n super().__init__(first_name, last_name, **traits)\n self.permissions = Permissions()\n self.traits = traits\n\n\nadmin_1 = Admin(\"Joe\", \"Keating\")\nadmin_1.permissions.show_perms()\n\n\n# 9-9. Battery Upgrade: Use the final version of electric_car.py from this section .\n# Add a method to the Battery class called upgrade_battery() . This method should check the battery size\n# and set the capacity to 85 if it isn’t already . Make an electric car with a default battery size,\n# call get_range() once, and then call get_range() a second time after upgrading the battery .\n# You should see an increase in the car’s ran\nprint(\"\\nExercise 9-9\")\n\n\nclass Car():\n\n def __init__(self, make, model):\n self.make = make\n self.model = model\n self.gas_tank_capacity = 0\n\n def set_gas_tank_capacity(self, capacity):\n self.gas_tank_capacity = capacity\n\n def display_car(self):\n print(\"Make: \" + self.make)\n print(\"Model: \" + self.model)\n print(\"Gas tank capacity: \" + str(self.gas_tank_capacity))\n\n\nclass Battery():\n\n def __init__(self):\n self.capacity = 0\n self.brand = \"\"\n\n def describe_battery(self):\n print(\"Battery brand: \" + self.brand)\n print(\"Battery capacity: \" + str(self.capacity))\n\n def upgrade_battery(self, capacity, brand):\n if self.capacity == 0 or self.brand == \"\":\n self.capacity = capacity\n self.brand = brand\n\n\nclass ElectricCar(Car):\n\n def __init__(self, name, model):\n super().__init__(name, model)\n self.range = 0\n self.battery = Battery()\n\n def set_range(self, range):\n self.range = range\n\n def set_gas_tank_capacity(self, capacity):\n print(\"This is an electric car, you cannot set the gas tank capacity!\")\n\n def display_car(self):\n print(\"Make: \" + self.make)\n print(\"Model: \" + self.model)\n print(\"Range: \" + str(self.range))\n\n\nregular_car = Car(\"Hyundai\", \"Santa Fe\")\n\nregular_car.set_gas_tank_capacity(17)\n\nregular_car.display_car()\n\nelectric_car = ElectricCar(\"Hyundai\", \"Tree Hugger\")\nelectric_car.set_gas_tank_capacity(13)\nelectric_car.set_range(320)\nelectric_car.display_car()\nelectric_car.battery.describe_battery()\nelectric_car.battery.upgrade_battery(\"15,000,000 petajules\", \"Duracell\")\nelectric_car.battery.describe_battery()\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7625698447227478, "alphanum_fraction": 0.7821229100227356, "avg_line_length": 88.5, "blob_id": "85ec175d66e01db54867977656dffde2cfb35ce4", "content_id": "dda68cd04095948eecc9a3f2b083e61f67c8a15a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 358, "license_type": "no_license", "max_line_length": 140, "num_lines": 4, "path": "/README.md", "repo_name": "JoeKeating/PythonCrashCourse", "src_encoding": "UTF-8", "text": "# PythonCrashCourse\n5/18/2019 - I created this repo for a couple different reasons. First, I wanted to save the programs I wrote while making my way through No \nStarch Press' Python Crash Course. Second, I needed a way to be able to work on updated versions of the product on three different \nmachines. Added bonus is that I'm also learning a bit about Git.\n" }, { "alpha_fraction": 0.6660685539245605, "alphanum_fraction": 0.6780621409416199, "avg_line_length": 39.25475311279297, "blob_id": "1927db1081a4cba353f67fc434e57ecfe340a443", "content_id": "aeb281d34dada55bb963298c822d460d0ca0088a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10673, "license_type": "no_license", "max_line_length": 117, "num_lines": 263, "path": "/Chapter Five.py", "repo_name": "JoeKeating/PythonCrashCourse", "src_encoding": "UTF-8", "text": "# 5-1. Conditional Tests: Write a series of conditional tests . Print a statement describing each test and your\n# prediction for the results of each test . Your code should look something like this:\n# car = 'subaru'\n# print(\"Is car == 'subaru'? I predict True.\")\n# print(car == 'subaru')\n# print(\"\\nIs car == 'audi'? I predict False.\")\n# print(car == 'audi')\n# • Look closely at your results, and make sure you understand why each line evaluates to True or False .\n# • Create at least 10 tests . Have at least 5 tests evaluate to True and another 5 tests evaluate to False .\n# 5-2. More Conditional Tests: You don’t have to limit the number of tests you create to 10 . If you want to try\n# more comparisons, write more tests and add them to conditional_tests.py . Have at least one True and one\n# False result for each of the following:\n# • Tests for equality and inequality with strings\n# • Tests using the lower() function\n# • Numerical tests involving equality and inequality, greater than and less than, greater than or\n# equal to, and less than or equal to\n# • Tests using the and keyword and the or keyword\n# • Test whether an item is in a list\n# • Test whether an item is not in a list\n\nprint(\"Exercise 5-1 and Exercise 5-2\")\nquarterback = \"Wentz\"\nprint(\"Does quarterback = 'Wentz'\")\nprint(quarterback == \"Wentz\")\nprint(\"Is quarterback not equal to Wentz?\")\nprint(quarterback != \"Wentz\")\nprint(\"Is quarterback not equal to 'Foles' and equal to 'Wentz'?\")\nprint(quarterback != \"Foles\" and quarterback == \"Wentz\")\n\nquarterbacks = [\"Wentz\", \"Sudfield\"]\nprint(\"Is 'Wentz' in quarterbacks?\")\nprint(\"Wentz\" in quarterbacks)\nprint(\"Is 'Wentz not in quarterbacks?\")\nprint(\"Wentz\" not in quarterbacks)\nprint(\"Is 'Wentz' in quarterbacks and 'Foles' in quarterbacks?\")\nprint(\"Wentz\" in quarterbacks and \"Foles\" in quarterbacks)\nprint(\"Is 'Wentz' in quarterbacks or 'Foles' in quarterbacks?\")\nprint(\"Wentz\" in quarterbacks or \"Foles\" in quarterbacks)\nprint(\"Is quarterback equal to 'Wentz' and 'Foles' not in quarterbacks?\")\nprint(quarterback == \"Wentz\" and \"Foles\" not in quarterbacks)\nprint(\"Is quarterback not equal to 'Foles?\")\nprint(quarterback != \"Foles\")\nprint(\"Is quarterback not equal to 'Wentz'?\")\nprint(quarterback != \"Wentz\")\nprint(\"Is 'Wentz' in quarterbacks and 'Foles' in quarterbacks or is 'Sudfield' in quarterbacks?\")\nprint(\"Wentz\" in quarterbacks and \"Foles\" in quarterbacks or \"Sudfield\" in quarterbacks)\nprint(\"Is 'Wentz' equal to 'wentz?\")\nprint(quarterback.lower() == \"wentz\")\n\n# 5-3. Alien Colors #1: Imagine an alien was just shot down in a game . Create a variable called alien_color\n# # and assign it a value of 'green', 'yellow', or 'red' .\n# • Write an if statement to test whether the alien’s color is green . If it is,\n# print a message that the player just earned 5 points .\n# • Write one version of this program that passes the if test and another that fails .\n# (The version that fails will have no output .)\nprint(\"Exercise 5-3\")\n\nalien_color = \"red\"\n\nif alien_color == \"green\":\n print(\"You earned five points!\")\n\nif alien_color == \"red\":\n print(\"Passed\")\n\n\n\n\n\n\n\n#\n# 5-4. Alien Colors #2: Choose a color for an alien as you did in Exercise 5-3, and write an if-else chain .\n# • If the alien’s color is green, print a statement that the player just earned 5 points for shooting the alien .\n# • If the alien’s color isn’t green, print a statement that the player just earned 10 points .\n# • Write one version of this program that runs the if block and another that runs the else block .\nprint(\"\\nExercise 5-4\")\nalien_color = \"red\"\nprint(\"The alien_color is: \" + alien_color)\nif alien_color == \"green\":\n print(\"You just earned five points.\")\nelse:\n print(\"You just earned ten points.\")\n\nalien_color = \"green\"\nprint(\"The alien_color is: \" + alien_color)\nif alien_color == \"green\":\n print(\"You just earned five points.\")\nelse:\n print(\"You just earned ten points.\")\n\n\n\n\n# 5-5. Alien Colors #3: Turn your if-else chain from Exercise 5-4 into an if-elif- else chain .\n# • If the alien is green, print a message that the player earned 5 points .\n# • If the alien is yellow, print a message that the player earned 10 points .\n# • If the alien is red, print a message that the player earned 15 points .\n# • Write three versions of this program, making sure each message is printed for the appropriate color alien .\nprint(\"\\nExercise 5-5\")\n\nalien_color = \"green\"\n\nprint(\"The alien_color is: \" + alien_color)\nif alien_color == \"green\":\n print(\"You just earned five points.\")\nelif alien_color == \"yellow\":\n print(\"You just earned ten points.\")\nelif alien_color == \"red\":\n print(\"You just earned fifteen points.\")\n\nalien_color = \"yellow\"\n\nprint(\"The alien_color is: \" + alien_color)\nif alien_color == \"green\":\n print(\"You just earned five points.\")\nelif alien_color == \"yellow\":\n print(\"You just earned ten points.\")\nelif alien_color == \"red\":\n print(\"You just earned fifteen points.\")\n\n\nalien_color = \"red\"\n\nprint(\"The alien_color is: \" + alien_color)\nif alien_color == \"green\":\n print(\"You just earned five points.\")\nelif alien_color == \"yellow\":\n print(\"You just earned ten points.\")\nelif alien_color == \"red\":\n print(\"You just earned fifteen points.\")\n\n# 5-6. Stages of Life: Write an if-elif-else chain that determines a person’s stage of life . Set a value for\n# the variable age, and then:\n# • If the person is less than 2 years old, print a message that the person is a baby .\n# • If the person is at least 2 years old but less than 4, print a message that the person is a toddler .\n# • If the person is at least 4 years old but less than 13, print a message that the person is a kid .\n# • If the person is at least 13 years old but less than 20, print a message that the person is a teenager .\n# • If the person is at least 20 years old but less than 65, print a message that the person is an adult .\n# • If the person is age 65 or older, print a message that the person is an elder .\nprint(\"\\nExercise 5-7\")\nfor age in range(1, 100, 5):\n\n print(\"At the age of \" + str(age) + \" you are a: \")\n\n if age < 2:\n print(\"Baby\")\n elif age >= 2 and age < 4:\n print(\"Toddler\")\n elif age >= 4 and age < 13:\n print(\"Kid\")\n elif age >= 13 and age < 20:\n print(\"Teenager\")\n elif age >= 20 and age < 65:\n print(\"Adult\")\n else:\n print(\"Elder\")\n\n\n# 5-7. Favorite Fruit: Make a list of your favorite fruits, and then write a series of independent\n# if statements that check for certain fruits in your list .\n# • Make a list of your three favorite fruits and call it favorite_fruits .\n# • Write five if statements . Each should check whether a certain kind of fruit is in your\n# list . If the fruit is in your list, the if block should print a statement, such as You really like bananas!\nprint(\"\\nExercise 5-7\")\nfruits = [\"apples\", \"mangos\", \"bananas\", \"guavas\", \"blueberries\"]\n\nif \"apples\" in fruits:\n print(\"You must love apples!\")\nif \"mangos\" in fruits:\n print(\"You must love mangos!\")\nif \"bananas\" in fruits:\n print(\"You must love bananas!\")\nif \"guavas\" in fruits:\n print(\"You must love guavas!\")\nif \"blueberries\" in fruits:\n print(\"You must love blueberries!\")\n\n# 5-8. Hello Admin: Make a list of five or more usernames, including the name 'admin' . Imagine you are writing\n# code that will print a greeting to each user after they log in to a website . Loop through the list,\n# and print a greeting to each user:\n# • If the username is 'admin', print a special greeting, such as Hello admin, would you like to see a status report?\n# • Otherwise, print a generic greeting, such as Hello Eric, thank you for log- ging in again.\nprint(\"\\nExercise 5-8\")\nusers = [\"Joe\", \"Paul\", \"John\", \"admin\", \"Traci\"]\n\nfor user in users:\n if user == \"admin\":\n print(\"Hello Master\")\n else:\n print(\"Welcome \" + user + \"!\")\n\n\n# 5-9. No Users: Add an if test to hello_admin.py to make sure the list of users is not empty .\n# • If the list is empty, print the message We need to find some users!\n# • Remove all of the usernames from your list, and make sure the correct\n# message is printed .\n\nprint(\"\\nExercise 5-9\")\nusers = [\"Joe\", \"Paul\", \"John\", \"admin\", \"Traci\"]\n\nif users:\n for user in users:\n if user == \"admin\":\n print(\"Hello Master\")\n else:\n print(\"Welcome \" + user + \"!\")\nelse:\n print(\"This website needs some users!\")\n\nusers = []\n\nif users:\n for user in users:\n if user == \"admin\":\n print(\"Hello Master\")\n else:\n print(\"Welcome \" + user + \"!\")\nelse:\n print(\"This website needs some users!\")\n\n# 5-10. Checking Usernames: Do the following to create a program that simulates\n# how websites ensure that everyone has a unique username .\n# • Make a list of five or more usernames called current_users .\n# • Make another list of five usernames called new_users . Make sure one or\n# two of the new usernames are also in the current_users list .\n# • Loop through the new_users list to see if each new username has already been used . If it has,\n# print a message that the person will need to enter a new username . If a username has not been used,\n# print a message saying that the username is available .\n# • Make sure your comparison is case insensitive . If 'John' has been used, 'JOHN' should not be accepted .\nprint(\"\\nExercise 5-10\")\n\ncurrent_users = [\"Traci\", \"Sarah\", \"Lindsey\", \"Lauren\", \"Tiffany\"]\nnew_users = [\"traci\", \"Melba\", \"Mulva\", \"Lauren\", \"Cindy\"]\n\nfor new_user in new_users:\n if new_user.lower() or new_user in current_users:\n print(new_user.title() + \" you need to pick a new name.\")\n else:\n print(\"Welcome aboard, \" + new_user.title())\n current_users.append(new_user.title())\n\n\n\n\n# 5-11. Ordinal Numbers: Ordinal numbers indicate their position in a list, such as 1st or 2nd .\n# Most ordinal numbers end in th, except 1, 2, and 3 .\n# • Store the numbers 1 through 9 in a list .\n# • Loop through the list .\n# • Use an if-elif-else chain inside the loop to print the proper ordinal end- ing for each number .\n# Your output should read \"1st 2nd 3rd 4th 5th 6th 7th 8th 9th\", and each result should be on a separate line .\nprint(\"\\nExercise 5-11\")\n\nnumbers = [i for i in range(1, 10)]\nfor number in numbers:\n if number == 1:\n print(str(number) + \"st\")\n elif number == 2:\n print(str(number) + \"nd\")\n elif number == 3:\n print(str(number) + \"rd\")\n else:\n print(str(number) + \"th\")\n\n\n" }, { "alpha_fraction": 0.703553318977356, "alphanum_fraction": 0.7246192693710327, "avg_line_length": 38.380001068115234, "blob_id": "0384b074f0e0965c066a2425471d621360405e99", "content_id": "b7bc5455023ca081f5e492e81af2144e13e148ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3962, "license_type": "no_license", "max_line_length": 120, "num_lines": 100, "path": "/Chapter Two.py", "repo_name": "JoeKeating/PythonCrashCourse", "src_encoding": "UTF-8", "text": "\n# 2.1 Simple Message: Store a message in a variable, and then print that message .\nprint(\"Exercise 2.1\")\nmessage = \"This is my message!\"\nprint(message)\n\n# 2-2. Simple Messages: Store a message in a variable, and print that message .\n# Then change the value of your variable to a new message, and print the new message .\n\nprint(\"Exercise 2.2\")\nmessage = \"This is the first message.\"\nprint(message)\nmessage = \"But this is a new message.\"\nprint(message)\n\n# 2-3. Personal Message: Store a person’s name in a variable, and print a message to that person .\n# Your message should be simple, such as,\n# “Hello Eric, would you like to learn some Python today?”\n\nprint(\"Exercise 2.3\")\nfriend_name = \"Eric\"\nprint(\"Hey \" + friend_name + \", I had a great time with you at the Lennon Claypool Delirium. \")\n\n# 2-4. Name Cases: Store a person’s name in a variable, and then print that per- son’s\n# name in lowercase, uppercase, and titlecase .\n\nprint(\"Exercise 2.4\")\nfriend_name = \"tyrion Lannister\"\nprint(\"My friend's name in uppercase: \" + friend_name.upper())\nprint(\"My friend's name in lowercase: \" + friend_name.lower())\nprint(\"My friend's name in titlecase: \" + friend_name.title())\n\n\n# 2-5. Famous Quote: Find a quote from a famous person you admire . Print the quote and the name of its author .\n# Your output should look something like the following, including the quotation marks:\n# Albert Einstein once said, “A person who never made a mistake never tried anything new.”\nprint(\"Exercise 2-5\")\nprint(\"Marcus Aurelius said 'Everything we here is an opinion, not a fact. Everything we see is perspective, \" \n \"not the truth.' \")\n\n# 2-6. Famous Quote 2: Repeat Exercise 2-5, but this time store the famous per- son’s\n# name in a variable called famous_person .\n# Then compose your message and store it in a new variable called message . Print your message .\n\nprint(\"Exercise 2-6\")\nfamous_person = \"Marcus Aurelius\"\nmessage = \"'Everything we here is an opinion, not a fact. Everything we see is perspective, not the truth.'\"\n\nprint(famous_person + \" sayeth, \" + message)\n\n# 2-7. Stripping Names: Store a person’s name, and include some whitespace characters at the\n# beginning and end of the name .\n# Make sure you use each character combination, \"\\t\" and \"\\n\", at least once .\n# Print the name once, so the whitespace around the name is displayed .\n\nprint(\"Exercise 2-7\")\n# Then print the name using each of the three stripping functions, lstrip(), rstrip(), and strip() .\n\nprint(\"Exercise 2-7\")\nprint(\"The famous person's name is \" + famous_person.rstrip())\nprint(\"The famous person's name is \" + famous_person.lstrip())\nprint(\"The famous person's name is \" + famous_person.strip())\n\n\n# 2-8. Number Eight: Write addition, subtraction, multiplication, and division operations that each result in\n# the number 8 . Be sure to enclose your operations in print statements to see the results.\n\nprint(\"Exercise 2-8\")\nprint(7 + 1)\nprint(16 - 8)\nprint(4 * 2)\nprint(int(64/8))\n\n\n# 2-9. Favorite Number: Store your favorite number in a variable . Then, using that variable, create a message that\n# reveals your favorite number . Print that message .\n\nprint(\"Exercise 2-9\")\nfavorite_number = 13\nprint(\"My favorite number is: \" + str(favorite_number))\n\n# 2-10. Adding Comments: Choose two of the programs you’ve written, and add at least one comment to each . If you don’t\n# have anything specific to write because your programs are too simple at this point, just add your name and the current\n# date at the top of each program file . Then write one sentence describing what the program does .\n\nprint(\"This is exercise 2-10\")\n# This is Exercise 2-9\nprint(\"Exercise 2-9\")\nfavorite_number = 13\nprint(\"My favorite number is: \" + str(favorite_number))\n\n# This is Exercise 2-8\nprint(\"Exercise 2-8\")\nprint(7 + 1)\nprint(16 - 8)\nprint(int(64/8))\n\n# 2-11. Zen of Python: Enter import this into a Python terminal session and skim through the additional principles .\n\nprint(\"Exercise 2-9\")\nimport this\n\n" }, { "alpha_fraction": 0.6811451315879822, "alphanum_fraction": 0.691565215587616, "avg_line_length": 36.04878234863281, "blob_id": "cc46443b4de5c1bb6882b5c195b979a07bd9c3dd", "content_id": "711fe30671bb92d5ce35bc4cd27d3d953a03a853", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9203, "license_type": "no_license", "max_line_length": 120, "num_lines": 246, "path": "/Chapter Three.py", "repo_name": "JoeKeating/PythonCrashCourse", "src_encoding": "UTF-8", "text": "from time import sleep\n\n# 3-1. Names: Store the names of a few of your friends in a list called names . Print each person’s name by accessing\n# each element in the list, one at a time .\n\nprint(\"Exercise 3-1\")\nmy_friends = [\"Eric\", \"Patrick\", \"Justin\"]\n\nprint(\"One of my friends is: \" + my_friends[0])\nprint(\"One of my friends is: \" + my_friends[1])\nprint(\"One of my friends is: \" + my_friends[2])\n\n# 3-2. Greetings: Start with the list you used in Exercise 3-1, but instead of just printing each person’s name, print a\n# message to them . The text of each mes- sage should be the same, but each message should be personalized with the\n# person’s name .\n\nprint(\"Exercise 3-2\")\nprint(\"Hey \" + my_friends[0] + \", lets go grab a beer.\")\nprint(\"Hey \" + my_friends[1] + \", lets go grab a beer.\")\nprint(\"Hey \" + my_friends[2] + \", lets go grab a beer.\")\n\n# 3-3. Your Own List: Think of your favorite mode of transportation, such as a motorcycle or a car, and make a list that\n# stores several examples . Use your list to print a series of statements about these items, such\n# as “I would like to own a Honda motorcycle .”\n\nprint(\"Exercise 3-3\")\nfavorite_transport = [\"plane\", \"train\", \"automobile\"]\n\nprint(\"I would love to catch a \" + favorite_transport[0] + \" right now.\")\nprint(\"Let's ride on the choo choo \" + favorite_transport[1] + \".\")\nprint(\"Let's jump in the \" + favorite_transport[2] + \" and go for a ride.\")\n\n# 3-4. Guest List: If you could invite anyone, living or deceased, to dinner, who would you invite? Make a list that\n# includes at least three people you’d like to invite to dinner . Then use your list to print a message to each person,\n# inviting them to dinner .\n\nprint(\"Exercise 3-4\")\nguests = [\"Jim Morrison\", \"Buddha\", \"Adolf Hitler\", \"Nick Foles\"]\nfor guest in guests:\n print(\"Hello, \" + guest + \" would you like to come to dinner?\")\n\n\n\n\n# 3-5. Changing Guest List: You just heard that one of your guests can’t make the dinner, so you need to send out a\n# new set of invitations . You’ll have to think of someone else to invite .\n# • Start with your program from Exercise 3-4 . Add a print statement at the end of your program stating the name of\n# the guest who can’t make it .\n# • Modify your list, replacing the name of the guest who can’t make it with the name of the new person\n# you are inviting . • Print a second set of invitation messages, one for each person who is still in your list .\n\n\nprint(\"Exercise 3-5\")\n\nguests = [\"Jim Morrison\", \"Buddha\", \"Adolf Hitler\", \"Nick Foles\"]\nfor guest in guests:\n print(\"Hello, \" + guest + \" would, you like to come to dinner?\")\n\nprint(guests[0] + \" can't make it.\")\n\nguests.remove(\"Jim Morrison\")\n\nguests.insert(0, \"Jimmy Page\")\n\nfor guest in guests:\n print(\"Hello, \" + guest + \" would, you like to come to dinner?\")\n\n\n\n\n# 3-6. More Guests: You just found a bigger dinner table, so now more space is available .\n# Think of three more guests to invite to dinner .\n# • Start with your program from Exercise 3-4 or Exercise 3-5 . Add a print statement to the end of your program\n# informing people that you found a bigger dinner table .\n# • Use insert() to add one new guest to the beginning of your list .\n# • Use insert() to add one new guest to the middle of your list .\n# • Use append() to add one new guest to the end of your list .\n# • Print a new set of invitation messages, one for each person in your list .\n\n\nprint(\"Exercise 3-6\")\n\nguests = [\"Jim Morrison\", \"Buddha\", \"Adolf Hitler\", \"Nick Foles\"]\nfor guest in guests:\n print(\"Hello, \" + guest + \" would, you like to come to dinner?\")\n\nprint(guests[0] + \" can't make it.\")\n\nguests.remove(\"Jim Morrison\")\n\nguests.insert(0, \"Jimmy Page\")\n\nfor guest in guests:\n print(\"Hello, \" + guest + \" would, you like to come to dinner?\")\n\nprint(\"We just found a bigger table!\")\nguests.insert(0, \"Gary Oldman\")\nguests.insert(3, \"Julius Caesar\")\nguests.append(\"Imhotep\")\n\nfor guest in guests:\n print(\"Hello, \" + guest + \" would, you like to come to dinner?\")\n\n# 3-7. Shrinking Guest List: You just found out that your new dinner table won’t arrive in time for the dinner,\n# # and you have space for only two guests .\n# # • Start with your program from Exercise 3-6 . Add a new line that prints a message saying that you can invite\n# # only two people for dinner .\n# # • Use pop() to remove guests from your list one at a time until only two names remain in your list .\n# # Each time you pop a name from your list, print a message to that person letting them know\n# # you’re sorry you can’t invite them to dinner .\n# # • Print a message to each of the two people still on your list,\n# # letting them know they’re still invited .\n# # • Use del to remove the last two names from your list, so you have an empty list .\n# # Print your list to make sure you actually have an empty list at the end of your program .\n\nprint(\"Exercise 3-7\")\n\nguests = [\"Jim Morrison\", \"Buddha\", \"Adolf Hitler\", \"Nick Foles\"]\nfor guest in guests:\n print(\"Hello, \" + guest + \" would, you like to come to dinner?\")\n\nprint(guests[0] + \" can't make it.\")\n\nguests.remove(\"Jim Morrison\")\n\nguests.insert(0, \"Jimmy Page\")\n\nfor guest in guests:\n print(\"Hello, \" + guest + \" would, you like to come to dinner?\")\n\nprint(\"We just found a bigger table!\")\nguests.insert(0, \"Gary Oldman\")\nguests.insert(3, \"Julius Caesar\")\nguests.append(\"Imhotep\")\n\nfor guest in guests:\n print(\"Hello, \" + guest + \" would, you like to come to dinner?\")\n\nprint(\"Eeeesh, we only have room for two people at dinner.\")\n\nwhile len(guests) > 2:\n print(\"Sorry \" + guests.pop() + \" you're disinvited.\")\n\nwhile len(guests) > 0:\n del(guests[0])\n \nprint(len(guests))\n\n# 3-8. Seeing the World: Think of at least five places in the world you’d like to visit .\n# • Store the locations in a list . Make sure the list is not in alphabetical order .\n# • Print your list in its original order . Don’t worry about printing the list neatly, just print it\n# as a raw Python list .\n# • Use sorted() to print your list in alphabetical order without modifying the actual list .\n# • Show that your list is still in its original order by printing it .\n# • Use sorted() to print your list in reverse alphabetical order without chang- ing the order of the original list .\n# • Show that your list is still in its original order by printing it again .\n# • Use reverse() to change the order of your list . Print the list to show that its order has changed .\n# • Use reverse() to change the order of your list again . Print the list to show it’s back to its original order .\n# • Use sort() to change your list so it’s stored in alphabetical order . Print the list to show that its\n# order has been changed .\n# • Use sort() to change your list so it’s stored in reverse alphabetical order . Print the list to show that\n# its order has changed .\n#\n\nprint(\"Exercise 3-8\")\nplaces = [\"Turkey\", \"Egypt\", \"Thailand\", \"France\", \"Norway\"]\nprint(places)\nprint(sorted(places))\nprint(places)\nprint(sorted(places, reverse = True))\nprint(places)\nplaces.reverse()\nprint(places)\nplaces.reverse()\nprint(places)\nplaces.sort()\nprint(places)\nplaces.sort(reverse=True)\nprint(places)\n\n\n\n\n\n# 3-9. Dinner Guests: Working with one of the programs from Exercises 3-4 through 3-7 (page 46), use len() to\n# print a message indicating the number of people you are inviting to dinner .\nprint(\"Exercise 3-9\")\n\nguests = [\"Jim Morrison\", \"Buddha\", \"Adolf Hitler\", \"Nick Foles\"]\nfor guest in guests:\n print(\"Hello, \" + guest + \" would, you like to come to dinner?\")\n\nprint(guests[0] + \" can't make it.\")\n\nguests.remove(\"Jim Morrison\")\n\nguests.insert(0, \"Jimmy Page\")\n\nfor guest in guests:\n print(\"Hello, \" + guest + \" would, you like to come to dinner?\")\n\nprint(\"We just found a bigger table!\")\nguests.insert(0, \"Gary Oldman\")\nguests.insert(3, \"Julius Caesar\")\nguests.append(\"Imhotep\")\n\nfor guest in guests:\n print(\"Hello, \" + guest + \" would, you like to come to dinner?\")\n\nprint(\"Eeeesh, we only have room for two people at dinner.\")\n\nwhile len(guests) > 2:\n print(\"Sorry \" + guests.pop() + \" you're disinvited.\")\nprint(len(guests))\nwhile len(guests) > 0:\n del (guests[0])\n\nprint(len(guests))\n\n\n# 3-10. Every Function: Think of something you could store in a list . For example, you could make a list of\n# mountains, rivers, countries, cities, languages, or any- thing else you’d like . Write a program that creates a\n# list containing these items and then uses each function introduced in this chapter at least once .\n\nprint(\"Exercise 3-10\")\n\ncities = [\"Paris\", \"Santa Fe\", \"Los Angeles\", \"Istanbul\"]\nprint(cities)\nprint(\"Temporary sorted: \" + str(sorted(cities)))\nprint(\"Temporary reverse sort:\" + str(sorted(cities, reverse = True)))\ncities.reverse()\nprint(\"Permanently reversed:\" + str(cities))\ncities.sort()\nprint(\"Permanently sorted: \" + str(cities))\ncities.sort(reverse = True)\nprint(\"Permanently sorted in reverse order: \" + str(cities))\nprint(\"The length of cities is: \" + str(len(cities)))\n\n# 3-11. Intentional Error: If you haven’t received an index error in one of your programs yet, try to make one happen .\n# Change an index in one of your pro- grams to produce an index error . Make sure you correct the error before clos-\n# ing the program .\nsleep(5)\nprint(\"Exercise 3-11\")\n\nmotorcycles = []\nprint(motorcycles[-1])\n\n\n\n" }, { "alpha_fraction": 0.5642317533493042, "alphanum_fraction": 0.5680100917816162, "avg_line_length": 26.379310607910156, "blob_id": "d63576f434f7e31cee0a0e495086596fd3677b74", "content_id": "8d8fe2c3f844d9c6f80e5a478a753b43be0098db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 794, "license_type": "no_license", "max_line_length": 66, "num_lines": 29, "path": "/my_modules.py", "repo_name": "JoeKeating/PythonCrashCourse", "src_encoding": "UTF-8", "text": "class Car():\n\n def __init__(self, make, model):\n self.make = make\n self.model = model\n self.gas_tank_capacity = 0\n\n def set_gas_tank_capacity(self, capacity):\n self.gas_tank_capacity = capacity\n\n def display_car(self):\n print(\"Make: \" + self.make)\n print(\"Model: \" + self.model)\n print(\"Gas tank capacity: \" + str(self.gas_tank_capacity))\n\nclass Battery():\n\n def __init__(self):\n self.capacity = 0\n self.brand = \"\"\n\n def describe_battery(self):\n print(\"Battery brand: \" + self.brand)\n print(\"Battery capacity: \" + str(self.capacity))\n\n def upgrade_battery(self, capacity, brand):\n if self.capacity == 0 or self.brand == \"\":\n self.capacity = capacity\n self.brand = brand\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.625, "avg_line_length": 28.33333396911621, "blob_id": "f4b2e920bdf1e77808b7357470a167785854521a", "content_id": "7cf8b11b715ce00ad4160b8a29dc25286717025b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 264, "license_type": "no_license", "max_line_length": 61, "num_lines": 9, "path": "/cars.py", "repo_name": "JoeKeating/PythonCrashCourse", "src_encoding": "UTF-8", "text": "def build_car(manufacturer, model, **features):\n\n # This function build a car\n\n car_dict = {\"manufacturer\": manufacturer, \"model\": model}\n if features:\n for key, value in features.items():\n car_dict[key] = str(value)\n return car_dict\n" }, { "alpha_fraction": 0.6655452251434326, "alphanum_fraction": 0.6801899671554565, "avg_line_length": 36.43703842163086, "blob_id": "d4461dc57b203bc112ff030627156ba32075baeb", "content_id": "17a511988f9f6bcaa0faf035f071cec44b7524ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5069, "license_type": "no_license", "max_line_length": 121, "num_lines": 135, "path": "/Chapter Seven.py", "repo_name": "JoeKeating/PythonCrashCourse", "src_encoding": "UTF-8", "text": "# 7-1. Rental Car: Write a program that asks the user what kind of rental car they would like .\n# Print a message about that car, such as “Let me see if I can find you a Subaru .”\n\n# print(\"\\nExercise 7-1\")\n#\n# query = input(\"What kind of car would you like to rent? \")\n#\n# print(\"Let's see if we can find a \" + query + \" for you.\")\n\n\n\n# 7-2. Restaurant Seating: Write a program that asks the user how many people are in their dinner group .\n# If the answer is more than eight, print a message say- ing they’ll have to wait for a table .\n# Otherwise, report that their table is ready .\n\n# print(\"\\nExercise 7-2\")\n#\n# answer = input(\"How many people for dinner? \")\n# if int(answer) > 8:\n# print(\"You'll have to wait for a table.\")\n# else:\n# print(\"Your table is ready.\")\n\n\n# 7-3. Multiples of Ten: Ask the user for a number, and then report whether the number is a multiple of 10 or not .\n\n# print(\"\\nExercise 7-3\")\n#\n# answer = input(\"Enter a number: \")\n#\n# if int(answer)%10 == 0:\n# print(\"This is a multiple of 10.\")\n# else:\n# print(\"This is not a multiple of 10.\")\n\n# 7-4. Pizza Toppings: Write a loop that prompts the user to enter a series of pizza toppings until\n# they enter a 'quit' value . As they enter each topping, print a message saying you’ll add that topping to their pizza .\n\n# print(\"\\nExercise 7-4\")\n#\n# while answer != \"quit\":\n# answer = input(\"Enter a topping please: \")\n# print(answer)\n\n\n\n\n#\n# 7-5. Movie Tickets: A movie theater charges different ticket prices depending on a person’s age .\n# If a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is $10; and\n# if they are over age 12, the ticket is $15 . Write a loop in which you ask users their age,\n# and then tell them the cost of their movie ticket .\n\n# print(\"\\nExercise 7-5\")\n#\n# while True:\n# answer = input(\"Enter your age \\nIf you would like to quit, type 'quit: \")\n# if answer == \"quit\":\n# print(\"Quitting!\")\n# break\n# elif int(answer) < 3:\n# print(\"The ticket is free!\")\n# continue\n# elif int(answer) > 3 and int(answer) <= 12:\n# print(\"Your ticket is $10\")\n# continue\n# elif int(answer) > 12:\n# print(\"Your ticket is $15.\")\n# continue\n\n# 7-6. Three Exits: Write different versions of either Exercise 7-4 or Exercise 7-5\n# that do each of the following at least once:\n# • Use a conditional test in the while statement to stop the loop .\n# • Use an active variable to control how long the loop runs .\n# • Use a break statement to exit the loop when the user enters a 'quit' value .\n#\n# 7-7. Infinity: Write a loop that never ends, and run it . (To end the loop, press ctrl-C or close\n# the window displaying the output .)\n## Used all of these\n\n# 7-8. Deli: Make a list called sandwich_orders and fill it with the names of various sandwiches .\n# Then make an empty list called finished_sandwiches . Loop through the list of sandwich orders\n# and print a message for each order, such as I made your tuna sandwich. As each sandwich is made,\n# move it to the list of finished sandwiches . After all the sandwiches have been made, print a\n# message listing each sandwich that was made .\nprint(\"\\nExercise 7-8\")\n\nsandwich_orders = [\"Hoagie\", \"The Works\", \"The Craps\", \"Turkey Bravo\"]\nfinished_orders = []\n\nwhile sandwich_orders:\n order_up = sandwich_orders.pop()\n print(\"Your \" + order_up + \" is finished.\")\n finished_orders.append(order_up)\n\n# 7-9. No Pastrami: Using the list sandwich_orders from Exercise 7-8, make sure the sandwich 'pastrami'\n# appears in the list at least three times . Add code near the beginning of your program to print a message\n# saying the deli has run out of pastrami, and then use a while loop to remove all occurrences of 'pastrami'\n# from sandwich_orders . Make sure no pastrami sandwiches end up in finished_sandwiches .\nprint(\"\\nExercise 7-9\")\n\nsandwich_orders = [\"Pastrami\", \"Hoagie\", \"The Works\", \"Pastrami\", \"The Craps\", \"Turkey Bravo\", \"Pastrami\"]\n\nwhile sandwich_orders:\n print(sandwich_orders)\n order_up = sandwich_orders.pop()\n if order_up in sandwich_orders:\n print(\"Sorry, we're out of Pastrami.\")\n while \"Pastrami\" in sandwich_orders:\n sandwich_orders.remove(\"Pastrami\")\n print(\"Removing Pastrami.\")\n print(\"Your \" + order_up + \" is finished.\")\n finished_orders.append(order_up)\n\n\n\n# 7-10. Dream Vacation: Write a program that polls users about their dream vacation . Write a prompt similar\n# to If you could visit one place in the world, where would you go? Include a block of code\n# that prints the results of the poll .\nprint(\"\\nExercise 7-10\")\n\nrespondent = \"\"\ndestination = \"\"\nanswer = \"yes\"\nvacation_dict = {}\n\n\nwhile answer == \"yes\":\n respondent = input(\"Hi, what is your name? \")\n destination = input(\"Where would you like to go on vacation? \")\n vacation_dict[respondent] = destination\n answer = input(\"Do you want to continue, yes/no \")\n\nfor key, value in vacation_dict.items():\n print(key, value)" }, { "alpha_fraction": 0.6569085717201233, "alphanum_fraction": 0.6720647811889648, "avg_line_length": 47.41205978393555, "blob_id": "deeee380b03c6fce1750e87d201cad8625fd2be7", "content_id": "71a2a46478b89691edb127882777f2178955cacc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9669, "license_type": "no_license", "max_line_length": 117, "num_lines": 199, "path": "/Chapter Six.py", "repo_name": "JoeKeating/PythonCrashCourse", "src_encoding": "UTF-8", "text": "# 6-1. Person: Use a dictionary to store information about a person you know . Store their first name, last name,\n# age, and the city in which they live . You should have keys such as first_name, last_name, age, and city .\n# Print each piece of information stored in your dictionary .\nprint(\"Exercise 6-1\")\n# Define person dictionary\n\nperson = {\"first_name\" : \"Joe\", \"last_name\" : \"Keating\", \"sex\" : \"Male\", \"age\" : \"55\", \"city\" : \"Philly\"}\n\n# Print values\n\nprint(person[\"first_name\"])\nprint(person[\"last_name\"])\nprint(person[\"sex\"])\nprint(person[\"age\"])\nprint(person[\"city\"])\n\n\n# 6-2. Favorite Numbers: Use a dictionary to store people’s favorite numbers . Think of five names,\n# and use them as keys in your dictionary . Think of a favorite number for each person, and store each as a value\n# in your dictionary . Print each person’s name and their favorite number . For even more fun, poll a few friends\n# and get some actual data for your program .\nprint(\"\\nExercise 6-2\")\n\ndict_numbers = {\"Joe\": 13, \"Paul\": 18, \"John\": 22, \"Leslie\": 17, \"Lindsey\": 9}\n\nprint(\"Joe's favorite number is: \" + str(dict_numbers[\"Joe\"]))\nprint(\"Paul's favorite number is: \" + str(dict_numbers[\"Paul\"]))\nprint(\"John's favorite number is: \" + str(dict_numbers[\"John\"]))\nprint(\"Leslie's favorite number is: \" + str(dict_numbers[\"Leslie\"]))\nprint(\"Lindsey's favorite number is: \" + str(dict_numbers[\"Lindsey\"]))\n\n# 6-3. Glossary: A Python dictionary can be used to model an actual dictionary . However, to avoid confusion,\n# let’s call it a glossary .\n# • Think of five programming words you’ve learned about in the previous chapters . Use these words as the\n# keys in your glossary, and store their meanings as values .\n# • Print each word and its meaning as neatly formatted output . You might print the word followed by a\n# colon and then its meaning, or print the word on one line and then print its meaning indented on a second line .\n# Use the newline character (\\n) to insert a blank line between each word-meaning pair in your output .\nprint(\"\\nExercise 6-3\")\ndefinitions = {\"len()\": \"Returns the length of a string.\", \"sort()\": \"Permanently sorts a list.\",\n \"reverse()\": \"Returns a list in reverse order, but does not sort it.\",\n \"string.lower()\": \"Returns a string in lower case.\",\n \"string.lstrip()\": \"Removes white space from the left of a string.\"}\n\nprint(\"The definition of len() is: \" + definitions[\"len()\"])\nprint(\"The definition of sort() is: \" + definitions[\"sort()\"])\nprint(\"The definition of reverse() is: \" + definitions[\"reverse()\"])\nprint(\"The definition of string.lower() is: \" + definitions[\"string.lower()\"])\nprint(\"The definition of string.lstrip() is: \" + definitions[\"string.lstrip()\"])\n\n# 6-4. Glossary 2: Now that you know how to loop through a dictionary, clean up the code from\n# Exercise 6-3 (page 102) by replacing your series of print statements with a loop that runs through the\n# dictionary’s keys and values . When you’re sure that your loop works, add five more Python terms to your glossary .\n# When you run your program again, these new words and meanings should automatically be included in the output .\n#\nprint(\"\\nExercise 6-4\")\ndefinitions = {\"len()\": \"Returns the length of a string.\", \"sort()\": \"Permanently sorts a list.\",\n \"reverse()\": \"Returns a list in reverse order, but does not sort it.\",\n \"string.lower()\": \"Returns a string in lower case.\",\n \"string.lstrip()\": \"Removes white space from the left of a string.\"}\n\nfor term, meaning in definitions.items():\n print(\"The definition of \" + term + \" is '\" + meaning + \"'\")\n\n\n\n\n# 6-5. Rivers: Make a dictionary containing three major rivers and the country each river runs through .\n# One key-value pair might be 'nile': 'egypt' .\n# • Use a loop to print a sentence about each river, such as The Nile runs through Egypt .\n# • Use a loop to print the name of each river included in the dictionary .\n# • Use a loop to print the name of each country included in the dictionary .\nprint(\"\\nExercise 6-5\")\nrivers = {\"McKenzie\": \"Canada\", \"Nile\": \"Egypt\", \"Amazon\": \"Brasil\", \"Volga\": \"Russia\"}\n\nfor key, value in rivers.items():\n print(\"The \" + key + \" runs through \" + value + \".\")\n\nfor key in rivers.keys():\n print(key)\n\nfor value in rivers.values():\n print(value)\n\n\n# 6-6. Polling: Use the code in favorite_languages.py (page 104) .\n# • Make a list of people who should take the favorite languages poll . Include\n# some names that are already in the dictionary and some that are not .\n# • Loop through the list of people who should take the poll . If they have already taken the poll,\n# print a message thanking them for responding . If they have not yet taken the poll,\n# print a message inviting them to take the poll .\nprint(\"\\nExercise 6-7\")\npollees = [\"Jim\", \"Janis\", \"Jimi\", \"Pete\"]\n\nfavorite_languages = {\"Fred\": \"Fortran\", \"Traci\": \"Cobol\", \"Jim\": \"C++\", \"Pete\": \"Python\"}\n\nfor pollee in pollees:\n if pollee in favorite_languages.keys():\n print(\"Thanks, \" + pollee + \" for responding!\" )\n else:\n print(\"Please, \" + pollee + \" take the poll!\")\n\n# 6-7. People: Start with the program you wrote for Exercise 6-1 (page 102) .\n# Make two new dictionaries representing different people, and store all three dictionaries in a list\n# called people . Loop through your list of people . As you loop through the list,\n# print everything you know about each person .\nprint(\"\\nExercise 6-7\")\nperson_1 = {\"first_name\" : \"Joe\", \"last_name\" : \"Keating\", \"sex\" : \"Male\", \"age\" : \"55\", \"city\" : \"Harpers Ferry\"}\nperson_2 = {\"first_name\" : \"John\", \"last_name\" : \"Keating\", \"sex\" : \"Male\", \"age\" : \"51\", \"city\" : \"Spring City\"}\nperson_3 = {\"first_name\" : \"Paul\", \"last_name\" : \"Keating\", \"sex\" : \"Male\", \"age\" : \"53\", \"city\" : \"New Hope\"}\n\nbros = []\nbros.append(person_1)\nbros.append(person_2)\nbros.append(person_3)\n\nfor bro in bros:\n print(\"\\n\")\n for key, value in bro.items():\n print(key, value)\n\n\n\n\n\n# 6-8. Pets: Make several dictionaries, where the name of each dictionary is the name of a pet . In each dictionary,\n# include the kind of animal and the owner’s name . Store these dictionaries in a list called pets .\n# Next, loop through your list and as you do print everything you know about each pet .\n\nmonchichi = {\"color\": \"Black and White\", \"type\": \"Cat\", \"breed\": \"Exotic Shorthair\"}\nweechi = {\"color\": \"Gray\", \"type\": \"Cat\", \"breed\": \"Exotic Shorthair\"}\nMax = {\"color\" : \"Peachy\", \"type\": \"Dog\", \"breed\": \"Pug Dog\"}\nZaboo = {\"color\": \"Fawn\", \"type\": \"Dog\", \"breed\": \"Pug Dog\"}\n\npets = [monchichi, weechi, Max, Zaboo]\n\nfor pet in pets:\n for key, value in pet.items():\n print(key, value)\n\n# 6-9. Favorite Places: Make a dictionary called favorite_places .\n# Think of three names to use as keys in the dictionary, and store one to three\n# favorite places for each person . To make this exercise a bit more interesting,\n# ask some friends to name a few of their favorite places . Loop through the dictionary, and\n# print each person’s name and their favorite places .\nprint(\"\\nExercise 6-9\")\n\nfavorite_places = {\"Joe\": \"Arizona\", \"Leslie\": \"Switzerland\", \"Cheri\": \"Florida\", \"Traci\": \"Garden\"}\n\nfor key, value in favorite_places.items():\n print(key + \"'s favorite place is \" + value + \".\")\n\n# 6-10. Favorite Numbers: Modify your program from Exercise 6-2 (page 102) so each person can\n# have more than one favorite number . Then print each person’s name along with their favorite numbers .\nprint(\"\\nExercise 6-10\")\n\ndict_numbers = {\"Joe\": [13], \"Paul\": [18,2], \"John\": [22,23,24,25] ,\"Leslie\": [17, 22], \"Lindsey\": [9, 113, 44]}\n\nfor key, value in dict_numbers.items():\n if len(value) == 1:\n print(key + \"'s favorite number is : \" + str(value[0]) + \".\")\n else:\n numbers_string = \"\"\n for i in range(len(value)):\n if i < len(value) - 1:\n numbers_string = numbers_string + str(value[i]) + \",\"\n else:\n numbers_string = numbers_string + str(value[i])\n print(key + \"'s favorite numbers are: \" + numbers_string + \".\")\n\n\n\n# 6-11. Cities: Make a dictionary called cities . Use the names of three cities as keys in your dictionary .\n# Create a dictionary of information about each city and include the country that the city is in,\n# its approximate population, and one fact about that city . The keys for each city’s dictionary\n# should be something like country, population, and fact . Print the name of each city and all of the\n# infor- mation you have stored about it .\n\nprint(\"\\nExercise 6-11\")\ncities = {\"Phjladelphia\": {\"population\": 2000000, \"country\": \"USA\", \"motto\": \"Brotherly Love\"},\n \"Paris\": {\"population\": 8000000, \"country\": \"France\", \"motto\": \"Eternal City\"},\n \"Los Angeles\": {\"population\": 12000000, \"country\": \"USA\", \"motto\": \"City of Angels\"}\n }\nfor key, value in cities.items():\n print(key)\n for subkey, subvalue in value.items():\n print(\"\\t\" + subkey + \":\" + str(subvalue))\n\ncities[\"Moscow\"] = {\"population\": 6000000, \"country\": \"Russia\",\"motto\":\"In Russia, you'd be dead.\"}\n\nfor key, value in cities.items():\n print(key)\n for subkey, subvalue in value.items():\n print(\"\\t\" + subkey + \":\" + str(subvalue))\n\n# 6-12. Extensions: We’re now working with examples that are complex enough that they can be extended in any\n# number of ways . Use one of the example pro- grams from this chapter, and extend it by adding new keys and values,\n# chang- ing the context of the program or improving the formatting of the output.\n#>>>> Already done throughout the previous exercises." }, { "alpha_fraction": 0.689555823802948, "alphanum_fraction": 0.7016794085502625, "avg_line_length": 34.188812255859375, "blob_id": "412fa35c4f1b8f73aeb7b4b1e041d5ce132891c7", "content_id": "6c2644e3756ebf3a599f740204bd216271996b23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10083, "license_type": "no_license", "max_line_length": 120, "num_lines": 286, "path": "/Chapter Eight.py", "repo_name": "JoeKeating/PythonCrashCourse", "src_encoding": "UTF-8", "text": "from time import sleep\n\n# 8-1. Message: Write a function called display_message() that prints one sen- tence telling everyone what you are\n# learning about in this chapter . Call the function, and make sure the message displays correctly .\nprint(\"\\nExercise 8-1\")\n\ndef display_message():\n print(\"We be learning about functions in ths chapter.\")\n\ndisplay_message()\n\n\n# 8-2. Favorite Book: Write a function called favorite_book() that accepts one parameter, title .\n# The function should print a message, such as One of my favorite books is Alice in Wonderland .\n# Call the function, making sure to include a book title as an argument in the function call.\n\ndef favorite_book(title):\n print(\"My favorite book is \" + title)\n\nfavorite_book(\"Game of Thrones\")\n\n# 8-3. T-Shirt: Write a function called make_shirt() that accepts a size and the text of a message that\n# should be printed on the shirt . The function should print a sentence summarizing the size of the shirt\n# and the message printed on it .\n# Call the function once using positional arguments to make a shirt . Call the function a second\n# time using keyword arguments .\n\nprint(\"\\nExercise 8-3\")\n\n\ndef make_shirt(size, message):\n print(\"This is a size \" + size.lower() + \" t-shirt that says '\" + message.lower().title() + \"' on the front.\")\n\n\nmake_shirt(\"medium\", \"make love not war\")\n\nmake_shirt(size = \"large\", message = \"Philadelphia eagles\")\n\n\n\n\n# 8-4. Large Shirts: Modify the make_shirt() function so that shirts are large\n# by default with a message that reads I love Python . Make a large shirt and a\n# medium shirt with the default message, and a shirt of any size with a different message .\nprint(\"\\nExercise 8-4\")\n\n\ndef make_shirt(size = \"large\", message = \"I Love Python.\"):\n print(\"This is a size \" + size.lower() + \" t-shirt that says '\" + message.lower().title() + \"' on the front.\")\n\nmake_shirt()\n\nmake_shirt(\"medium\")\n\nmake_shirt(\"small\", \"Peace Frog\")\n\n\n\n# 8-5. Cities: Write a function called describe_city() that accepts the name of a\n# city and its country . The function should print a simple sentence, such as Reykjavik\n# is in Iceland . Give the parameter for the country a default value .\n# Call your function for three different cities, at least one of which is not in the default country .\nsleep(3)\n\nprint(\"\\nExercise 8-5\")\n\n\ndef describe_city(city, country=\"USA\"):\n print(city.title() + \" is in \" + country.title() + \".\")\n\n\ndescribe_city(\"philadelphia\")\n\n\ndescribe_city(\"seattle\")\n\ndescribe_city(\"Paris\", \"France\")\n\n# 8-6. City Names: Write a function called city_country() that takes in the\n# name of a city and its country . The function should return a string formatted like this:\n# \"Santiago, Chile\"\n# Call your function with at least three city-country pairs, and print the value that’s returned .\nprint(\"\\nExercise 8-6\")\n\n\ndef city_country(city, country):\n return city.title() + \", \" + country.title()\n\n\ncity_1 = city_country(\"Philadelphia\", \"USA\")\ncity_2 = city_country(\"San Diego\", \"USA\")\ncity_3 = city_country(\"Moscow\", \"Russia\")\n\nprint(city_1)\nprint(city_2)\nprint(city_3)\n\n\n# 8-7. Album: Write a function called make_album() that builds a dictionary describing a music album .\n# The function should take in an artist name and an album title, and it should return a dictionary\n# containing these two pieces of information . Use the function to make three dictionaries representing\n# different albums . Print each return value to show that the dictionaries are storing the album information correctly .\n# Add an optional parameter to make_album() that allows you to store the number of tracks on an album .\n# If the calling line includes a value for the num- ber of tracks, add that value to the album’s dictionary .\n# Make at least one new function call that includes the number of tracks on an album .\nprint(\"\\nExercise 8-7\")\n\ndef make_album(artist, album_title, tracks = ''):\n if tracks == '':\n dict = {\"artist\" : artist, \"album_title\": album_title }\n else:\n dict = {\"artist\": artist, \"album_title\": album_title, \"tracks\": int(tracks)}\n return dict\n\nmusic_1 = make_album(\"Led Zeppelin\", \"Houses of the Holy\", 7)\n\nfor key, value in music_1.items():\n print(key, value)\n\nmusic_2 = make_album(\"Led Zeppelin\", \"Led Zeppelin IV\")\n\nfor key, value in music_2.items():\n print(key, value)\n\nmusic_3 = make_album(\"Led Zeppelin\", \"Physical Graffiti \", 15)\n\nfor key, value in music_3.items():\n print(key, value)\n\n\n\n\n# 8-8. User Albums: Start with your program from Exercise 8-7 . Write a while loop that allows users to\n# enter an album’s artist and title . Once you have that information, call make_album() with the user’s input and\n# print the dictionary that’s created . Be sure to include a quit value in the while loop .\nprint(\"\\nExercise 8-8\")\n\n\nwhile True:\n rocker = input (\"Enter the artist, or press 'y' to quit :\")\n print(\"The length of rocker is : \" + str(len(rocker)))\n if rocker == \"y\":\n break\n title = input(\"Enter the title or press 'y' to quit: \")\n print(\"The length of title is : \" + str(len(title)))\n if title == \"y\":\n break\n dictionary = make_album(rocker, title)\n print(dictionary)\n\n# 8-9. Magicians: Make a list of magician’s names . Pass the list to a function called show_magicians(),\n# which prints the name of each magician in the list .\nprint(\"\\nExercise 8-9\")\n\n\ndef show_magicians(magicians):\n for magician in magicians:\n print(magician)\n\nthe_magicians = [\"Impresso\", \"Mephisto\", \"Mysterio\", \"Ginger Baker\"]\n\nshow_magicians(the_magicians)\n\n# 8-10. Great Magicians: Start with a copy of your program from Exercise 8-9 . Write a function called make_great()\n# that modifies the list of magicians by add- ing the phrase the Great to each magician’s name . Call show_magicians()\n# to see that the list has actually been modified .\nprint(\"\\nExercise 8-10\")\n\n\ndef make_great(magicians):\n for i in range(len(magicians)):\n magicians[i] = magicians[i] + \" the Great\"\n\n\nmake_great(the_magicians)\n\nprint(the_magicians)\n\n\n\n\n# 8-11. Unchanged Magicians: Start with your work from Exercise 8-10 . Call the function make_great() with a copy\n# of the list of magicians’ names . Because the original list will be unchanged, return the new list and store it\n# in a separate list . Call show_magicians() with each list to show that you have one list of the origi- nal\n# names and one list with the Great added to each magician’s name .\nprint(\"\\nExercise 8-11\")\n\n\nthe_magicians = [\"Impresso\", \"Mephisto\", \"Mysterio\", \"Ginger Baker\"]\nthe_great_magicians = []\n\ndef make_great(magicians):\n for i in range(len(magicians)):\n magicians[i] = magicians[i] + \" the Great\"\n return magicians\n\n\nthe_great_magicians = make_great(the_magicians[:])\n\nprint(the_magicians)\nprint(the_great_magicians)\n\n# 8-12. Sandwiches: Write a function that accepts a list of items a person wants on a sandwich .\n# The function should have one parameter that collects as many items as the function call provides,\n# and it should print a summary of the sand- wich that is being ordered . Call the function three times,\n# using a different num- ber of arguments each time .\nprint(\"\\nExercise 8-12\")\n\n\ndef make_sandwich(name, *fixins):\n print(name.title() + \" wants this on his sammy:\")\n for fixin in fixins:\n print(\"\\t\" + fixin)\n\n\nmake_sandwich(\"Joe\", \"Salami\", \"Cheese\", \"Mustard\")\nmake_sandwich(\"Paul\", \"Tomato\", \"Cheese\")\nmake_sandwich(\"John\", \"Nuthin\")\n\n\n\n#\n# 8-13. User Profile: Start with a copy of user_profile.py from page 153 . Build\n# a profile of yourself by calling build_profile(), using your first and last names\n# and three other key-value pairs that describe you .\nprint(\"\\nExercise 8-3\")\n\n\ndef build_profile(first_name, last_name, **traits):\n print(\"Hello, \" + first_name.title() + \" \" + last_name.title() + \" here are your characteristics: \")\n if traits:\n for key, value in traits.items():\n print(\"\\t\" + key + \" : \" + str(value))\n\n\nbuild_profile(\"Joe\", \"Keating\", age = \"55\", height_in_inches = 72, hair = \"dirty blond\", weight = 230)\n\n\n# 8-14. Cars: Write a function that stores information about a car in a diction- ary .\n# The function should always receive a manufacturer and a model name . It should then accept an arbitrary\n# number of keyword arguments . Call the func- tion with the required information and two other name-value pairs,\n# such as a color or an optional feature . Your function should work for a call like this one:\n# car = make_car('subaru', 'outback', color='blue', tow_package=True)\n# Print the dictionary that’s returned to make sure all the information was stored correctly .\n# print(\"\\nExercise 8-14\")\n#\n#\n# def build_car(manufacturer, model, **features):\n#\n# # This function build a car\n#\n# car_dict = {\"manufacturer\": manufacturer, \"model\": model}\n# if features:\n# for key, value in features.items():\n# car_dict[key] = str(value)\n# return car_dict\n#\n#\n# my_car = build_car(\"Hyundai\", \"Sonata\", color = \"white\", transmission = \"automatic\", year = 2017)\n#\n# print(my_car)\n\n# 8-15. Printing Models: Put the functions for the example print_models.py in a\n# separate file called printing_functions.py . Write an import statement at the top of print_models.py,\n# and modify the file to use the imported functions .\nprint(\"\\nExercise 8-15\"\n )\nfrom cars import build_car as bc\n\nmy_dict = bc(\"Toyota\", \"Forerunner\", color = \"yellow\", price = 34221.34)\n\nprint(my_dict)\n\n# 8-16. Imports: Using a program you wrote that has one function in it, store that function in a separate file .\n# Import the function into your main program file, and call the function using each of these approaches:\n# import module_name\n# from module_name import function_name\n# from module_name import function_name as fn import module_name as mn\n# from module_name import *\n\n# Done in 8-15\n\n# 8-17. Styling Functions: Choose any three programs you wrote for this chapter,\n# and make sure they follow the styling guidelines described in this section .\n\n# Already done" } ]
11
surify/excel2db
https://github.com/surify/excel2db
76554e08c329ce18213f9556b65d65170def6efb
a864e3192c49eac4b8e777ae334ddb6a86f77ccc
c7230900f447e021dc5021cf8a87ff55663f8815
refs/heads/master
2020-03-18T09:29:42.169401
2018-05-23T23:03:44
2018-05-23T23:06:08
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5850067138671875, "alphanum_fraction": 0.5914026498794556, "avg_line_length": 30.4158878326416, "blob_id": "d24dd8d644c33964d7f85f978a9fc5931cef8a8d", "content_id": "6ee30e068fd9e885f69d0e86679067ed3c61b42c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6723, "license_type": "no_license", "max_line_length": 79, "num_lines": 214, "path": "/excel_to_db.py", "repo_name": "surify/excel2db", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\n\"\"\"\nAuthor: P Surya Teja\nLast Modified Date: 23-05-2018(DD-MM-YYYY)\n\nThe below script takes\n1) the path of a valid excel file and\n2) the path of an existing or new sqlite3 database\nfrom the user and transfers the table in the active sheet\nwith sheet's title as the database table name.\n\nIt currently assumes that the first row columns are headings\n\nIf there are any repeating column names, the user will be prompted\nfor a new name for that column in the middle of execution.\n\nThe source excel file will not be modified.\n\nIf you are giving the name of existing database, make sure that it\nhas no table with sheet's title in it(because it will be overwritten\nif it exists).\n\"\"\"\n\nimport datetime\nimport openpyxl\nimport os\nimport pprint\nimport re\nimport sqlite3\nimport sys\nfrom collections import OrderedDict\n\nheadings_types = {\n datetime.date: 'date',\n datetime.datetime: 'datetime',\n datetime.time: 'time',\n float: 'real',\n int: 'int',\n str: 'text'\n}\n\n\ndef main():\n # prompting user for excel file path\n while True:\n excel_filename = input(\"Enter the absolute path of a valid excel file.\"\n \"\\nLike 1)/home/user/example.xlsx in \"\n \"mac or linux and\\n\"\n \"2) C:\\\\Users\\\\example.xlsx in windows\\n>>>\")\n if not os.path.exists(excel_filename):\n print(\"{} doesn't exist.\".format(excel_filename))\n else:\n break\n\n # prompting user for database file path\n while True:\n db_filename = input(\"Enter the path of an existing sqlite3\"\n \" database file or a new sqlite3 file.\\n>>>\")\n # opening the db file and establishing connection\n try:\n conn = sqlite3.connect(db_filename)\n break\n except sqlite3.OperationalError:\n print(\"Unable to open database. Permission denied.\\n\")\n continue\n workbook = openpyxl.load_workbook(excel_filename)\n sheet = workbook.active\n\n # removing empty rows and columns\n remove_empty(sheet)\n\n # headings is a dictionary with keys as table headings and\n # values as their SQL types\n headings = get_headings(sheet) # type: dict\n table_name = \"\\\"\" + slugify(sheet.title) + \"\\\"\"\n cursor = conn.cursor()\n\n # creating the table\n cursor.execute(\"drop table if exists {}\".format(table_name))\n cursor.execute(create_table(headings, table_name))\n insert_values(table_name, cursor, sheet)\n conn.commit()\n\n print(\"All data from active sheet successfully written to the database.\")\n\n # closing opened things\n conn.close()\n workbook.close()\n\n\ndef remove_empty(sheet):\n \"\"\"\n Removes all rows and columns that are completely empty\n\n TODO: remove repeating code\n \"\"\"\n all_rows = list(sheet.rows)\n row_idx = 2\n while row_idx <= sheet.max_row:\n row_values = list(set([cell.value\n for cell in all_rows[row_idx - 1]]))\n if len(row_values) == 1 and row_values[0] is None:\n sheet.delete_rows(row_idx)\n else:\n row_idx += 1\n all_cols = list(sheet.columns)\n col_idx = 1\n while col_idx <= sheet.max_column:\n column_values = list(set([cell.value\n for cell in all_cols[col_idx - 1]]))\n if len(column_values) == 1 and column_values[0] is None:\n sheet.delete_cols(col_idx)\n else:\n col_idx += 1\n print(sheet.max_row)\n\n\ndef insert_values(table_name, cursor, sheet):\n \"\"\"\n inserts values from row 2 to last row into database\n \"\"\"\n all_rows_values = []\n for row in list(sheet.rows):\n all_rows_values.append([])\n for cell in row:\n all_rows_values[-1].append(cell.value)\n\n placeholder = \", \".join('?' * sheet.max_column)\n # inserting row by row\n try:\n cursor.executemany(\n \"insert into {} values ({})\".\n format(table_name, placeholder), all_rows_values[1:])\n except sqlite3.OperationalError as error:\n print(\"ERROR: \", error)\n sys.exit(1)\n except sqlite3.ProgrammingError as error:\n print(\"ERROR: \", error)\n sys.exit(1)\n all_rows = list(sheet.rows)\n placeholder = \", \".join('?' * sheet.max_column)\n for row in all_rows[1:]:\n try:\n cursor.execute(\n \"insert into {} values ({})\".\n format(table_name, placeholder), [cell.value for cell in row])\n except sqlite3.OperationalError:\n pprint.pprint([cell.value for cell in row])\n sys.exit(1)\n\n\ndef create_table(headings, table_name):\n \"\"\"\n creates table in the database using keys and values of headings dict\n as column names and column types\n \"\"\"\n temp = []\n for key, value in headings.items():\n temp.append(\"\\\"{}\\\" {}\".format(key, value))\n query = ['create', 'table', table_name, '(', \", \".join(temp), ')']\n # print(\" \".join(query))\n return \" \".join(query)\n\n\ndef get_headings(sheet):\n \"\"\"\n takes a worksheet object and returns a dictionary with keys as column\n names and their corresponding sql types as values\n \"\"\"\n headings = OrderedDict()\n row = 1 # that is where headings live\n for col in range(1, sheet.max_column + 1):\n column_name = sheet.cell(row, col).value\n if column_name in (None, \"\"):\n column_name = \"column\" + str(col)\n column_name = slugify(column_name)\n column_name = check_repetitions(column_name,\n headings.keys(),\n sheet.cell(row, col).column)\n headings[column_name] = headings_types[type(sheet.cell(2, col).value)]\n return headings\n\n\ndef check_repetitions(column_name, headings_names, column):\n \"\"\"\n If the table headings are repeated,\n it prompts user for new non repeating name\n \"\"\"\n while True:\n if column_name in headings_names:\n column_name = input(\"column name {} of Column \\'{}\\'\"\n \" already exists.\"\n \" Enter a new name: \".format(column_name,\n column))\n else:\n break\n return column_name\n\n\ndef slugify(some_string):\n \"\"\"\n allows only certain characters in the heading name,\n removes all others\n replaces multiple consequent spaces with a single underscore\n \"\"\"\n sanity_regex = re.compile(r\"\"\"[^\\w\\s/%.'\"()]+\"\"\")\n some_string = sanity_regex.sub('', some_string)\n space_regex = re.compile(r\"\\s+\")\n return space_regex.sub(\"_\", some_string.strip())\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.7819225192070007, "alphanum_fraction": 0.7890961170196533, "avg_line_length": 32.238094329833984, "blob_id": "25c9ddc62f6df80425464359b47adec61f39d712", "content_id": "76fd613ff3c84f61864194153641f08fc15dd78a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 697, "license_type": "no_license", "max_line_length": 68, "num_lines": 21, "path": "/README.md", "repo_name": "surify/excel2db", "src_encoding": "UTF-8", "text": "# excel2db\nTakes an excel file and loads into an sqlite3 database using python.\n\nDescription:\n\nThe below script takes\n1) the path of a valid excel file and\n2) the path of an existing or new sqlite3 database\nfrom the user and transfers the table in the active sheet\nwith sheet's title as the database table name.\n\nIt currently assumes that the first row columns are headings\n\nIf there are any repeating column names, the user will be prompted\nfor a new name for that column in the middle of execution.\n\nThe source excel file will not be modified.\n\nIf you are giving the name of existing database, make sure that it\nhas no table with sheet's title in it(because it will be overwritten\nif it exists)." } ]
2
souravsingh/LinkNet-model
https://github.com/souravsingh/LinkNet-model
dd08db70072f73b33cbc1b53800c771109109904
1b9e6dca20a15e34a23d7e8db852e2fdcd1d9003
f57d8459a72e2f5ec44128bfa554a44932c72f34
refs/heads/master
2021-07-25T04:11:53.117566
2017-11-06T16:34:32
2017-11-06T16:34:32
109,721,009
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6246597766876221, "alphanum_fraction": 0.6475231647491455, "avg_line_length": 44.35802459716797, "blob_id": "25eec5d1d7bc916bb10d2df6a8c03f0f81869830", "content_id": "108ee414c1ae609eb2c461bb93585f69c3a8b266", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7348, "license_type": "permissive", "max_line_length": 157, "num_lines": 162, "path": "/tf/model.py", "repo_name": "souravsingh/LinkNet-model", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom tensorflow.contrib.layers.python.layers import initializers\nslim = tf.contrib.slim\n\n'''\nLinkNet: Exploiting Encoder Representations for Efficient Semantic Segmentation\nBased on the paper: https://arxiv.org/pdf/1707.03718.pdf\n'''\n\[email protected]_arg_scope\ndef convBnRelu(input, num_channel, kernel_size, stride, is_training, scope, padding = 'SAME'):\n x = slim.conv2d(input, num_channel, [kernel_size, kernel_size], stride=stride, activation_fn=None, scope=scope+'_conv1', padding = padding)\n x = slim.batch_norm(x, is_training=is_training, fused=True, scope=scope+'_batchnorm1')\n x = tf.nn.relu(x, name=scope+'_relu1')\n return x\n\n\[email protected]_arg_scope\ndef deconvBnRelu(input, num_channel, kernel_size, stride, is_training, scope, padding = 'VALID'):\n x = slim.conv2d_transpose(input, num_channel, [kernel_size, kernel_size], stride=stride, activation_fn=None, scope=scope+'_fullconv1', padding = padding)\n x = slim.batch_norm(x, is_training=is_training, fused=True, scope=scope+'_batchnorm1')\n x = tf.nn.relu(x, name=scope+'_relu1')\n return x \n\[email protected]_arg_scope\ndef initial_block(inputs, is_training=True, scope='initial_block'):\n '''\n The initial block for Linknet has 2 branches: The convolution branch and Maxpool branch.\n INPUTS:\n - inputs(Tensor): A 4D tensor of shape [batch_size, height, width, channels]\n OUTPUTS:\n - net_concatenated(Tensor): a 4D Tensor that contains the \n '''\n #Convolutional branch\n net_conv = slim.conv2d(inputs, 64, [7,7], stride=2, activation_fn=None, scope=scope+'_conv')\n net_conv = slim.batch_norm(net_conv, is_training=is_training, fused=True, scope=scope+'_batchnorm')\n net_conv = tf.nn.relu(net_conv, name=scope+'_relu')\n\n #Max pool branch\n net_pool = slim.max_pool2d(net_conv, [3,3], stride=2, scope=scope+'_max_pool')\n\n return net_conv\n\[email protected]_arg_scope\ndef residualBlock(input, n_filters, is_training, stride=1, downsample= None, scope='residualBlock'):\n # Shortcut connection\n\n # Downsample the data or just pass original\n if downsample == None:\n shortcut = input\n else:\n shortcut = downsample\n\n # Residual\n x = convBnRelu(input, n_filters, kernel_size = 3, stride = stride, is_training = is_training, scope = scope + '/cvbnrelu')\n x = slim.conv2d(x, n_filters, [3,3], stride=1, activation_fn=None, scope=scope+'_conv2', padding = 'SAME')\n x = slim.batch_norm(x, is_training=is_training, fused=True, scope=scope+'_batchnorm2')\n \n # Shortcutr connection\n x = x + shortcut\n x = tf.nn.relu(x, name=scope+'_relu2')\n return x\n\n\[email protected]_arg_scope\ndef encoder(inputs, inplanes, planes, blocks, stride, is_training=True, scope='encoder'):\n '''\n Decoder of LinkNet\n INPUTS:\n - inputs(Tensor): A 4D tensor of shape [batch_size, height, width, channels]\n OUTPUTS:\n - net_concatenated(Tensor): a 4D Tensor that contains the \n '''\n \n # make downsample at skip connection if needed\n downsample = None\n if stride != 1 or inplanes != planes:\n downsample = slim.conv2d(inputs, planes, [1,1], stride=stride, activation_fn=None, scope=scope+'_conv_downsample')\n downsample = slim.batch_norm(downsample, is_training=is_training, fused=True, scope=scope+'_batchnorm_downsample')\n\n # Create mupliple block of ResNet\n output = residualBlock(inputs, planes, is_training, stride, downsample, scope = scope +'/residualBlock0')\n for i in range(1, blocks):\n output = residualBlock(output, planes, is_training, 1, scope = scope +'/residualBlock{}'.format(i))\n\n\n return output\n\[email protected]_arg_scope\ndef decoder(inputs, n_filters, planes, is_training=True, scope='decoder'):\n '''\n Encoder use ResNet block. As in paper, we will use ResNet18 block for learning.\n INPUTS:\n - inputs(Tensor): A 4D tensor of shape [batch_size, height, width, channels]\n OUTPUTS:\n - net_concatenated(Tensor): a 4D Tensor that contains the \n '''\n \n x = convBnRelu(inputs, n_filters/2, kernel_size = 1, stride = 1, is_training = is_training, padding = 'SAME', scope = scope + \"/c1\")\n x = deconvBnRelu(x, n_filters/2, kernel_size = 3, stride = 2, is_training = is_training, padding = 'SAME', scope = scope+ \"/dc1\")\n x = convBnRelu(x, planes, kernel_size = 1, stride = 1, is_training = is_training, padding = 'SAME', scope = scope+ \"/c2\")\n\n return x \n\n\n#Now actually start building the network\ndef LinkNet(inputs,\n num_classes,\n reuse=None,\n is_training=True,\n feature_scale=4,\n scope='LinkNet'):\n #Set the shape of the inputs first to get the batch_size information\n inputs_shape = inputs.get_shape().as_list()\n # inputs.set_shape(shape=(batch_size, inputs_shape[1], inputs_shape[2], inputs_shape[3]))\n\n layers = [2, 2, 2, 2]\n filters = [64, 128, 256, 512]\n filters = [x / feature_scale for x in filters]\n\n with tf.variable_scope(scope, reuse=reuse):\n #Set the primary arg scopes. Fused batch_norm is faster than normal batch norm.\n with slim.arg_scope([initial_block, encoder], is_training=is_training),\\\n slim.arg_scope([slim.batch_norm], fused=True), \\\n slim.arg_scope([slim.conv2d, slim.conv2d_transpose], activation_fn=None): \n #=================INITIAL BLOCK=================\n \n net = initial_block(inputs, scope='initial_block')\n\n enc1 = encoder(net, 64, filters[0], layers[0], stride=1, is_training=is_training, scope='encoder1')\n enc2 = encoder(enc1, filters[0], filters[1], layers[1], stride=2, is_training=is_training, scope='encoder2')\n enc3 = encoder(enc2, filters[1], filters[2], layers[2], stride=2, is_training=is_training, scope='encoder3')\n enc4 = encoder(enc3, filters[2], filters[3], layers[3], stride=2, is_training=is_training, scope='encoder4')\n\n \n decoder4 = decoder(enc4, filters[3], filters[2], is_training=is_training, scope='decoder4')\n decoder4 += enc3\n decoder3 = decoder(decoder4, filters[2], filters[1], is_training=is_training, scope='decoder3')\n decoder3 += enc2\n decoder2 = decoder(decoder3, filters[1], filters[0], is_training=is_training, scope='decoder2')\n decoder2 += enc1\n decoder1 = decoder(decoder2, filters[0], filters[0], is_training=is_training, scope='decoder1')\n\n f1 = deconvBnRelu(decoder1, 32/feature_scale, 3, stride = 2, is_training=is_training, scope='f1',padding = 'SAME')\n f2 = convBnRelu(f1, 32/feature_scale, 3, stride = 1, is_training=is_training, padding = 'SAME', scope='f2')\n logits = slim.conv2d(f2, num_classes, [2,2], stride=2, activation_fn=None, padding = 'SAME', scope='logits')\n\n return logits\n\n\ndef LinkNet_arg(weight_decay=2e-4,\n batch_norm_decay=0.1,\n batch_norm_epsilon=0.001):\n with slim.arg_scope([slim.conv2d],\n weights_regularizer=slim.l2_regularizer(weight_decay),\n biases_regularizer=slim.l2_regularizer(weight_decay)):\n\n # Set parameters for batch_norm.\n with slim.arg_scope([slim.batch_norm],\n decay=batch_norm_decay,\n epsilon=batch_norm_epsilon) as scope:\n return scope\n" }, { "alpha_fraction": 0.8166666626930237, "alphanum_fraction": 0.8166666626930237, "avg_line_length": 29, "blob_id": "8a482c4944b1f6c72b8c31fd34d532b2c72faa10", "content_id": "a774b92637c3e502b69654689bab224814262132", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 60, "license_type": "permissive", "max_line_length": 43, "num_lines": 2, "path": "/README.md", "repo_name": "souravsingh/LinkNet-model", "src_encoding": "UTF-8", "text": "# LinkNet-model\nModel for LinkNet in PyTorch and Tensorflow\n" } ]
2
Metafyzik/Genetic-algorithm
https://github.com/Metafyzik/Genetic-algorithm
1363ab2486fe863f6b1523d14e280d8bbcf018f9
746cb0c871c0eeac610fac9670fc3ef7d1b778c4
188827338e878dc809929d8a88e0d5fae17514bb
refs/heads/main
2023-07-08T04:20:39.863218
2021-08-11T20:10:10
2021-08-11T20:10:10
355,270,345
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5137763619422913, "alphanum_fraction": 0.5510534644126892, "avg_line_length": 31.473684310913086, "blob_id": "58a547a4c09e9ec7468881c4255a20943adf81f3", "content_id": "6d89e9e422d0fd5dfedcef018d05d12528810e2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 617, "license_type": "no_license", "max_line_length": 87, "num_lines": 19, "path": "/function_for_optimization.py", "repo_name": "Metafyzik/Genetic-algorithm", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom math import pi\n\n# Domain of a Rastringin function\nprecision = 2**10 # equivalent to number of values coded in binary string of length ten\nlower_bound = -5.12\nupper_bound = 5.12\nxy_domain = np.linspace(lower_bound,upper_bound, precision)\n \n# Rastingin plot\nX,Y = xy_domain,xy_domain\nX, Y = np.meshgrid(X, Y)\nA = 10\nn = 2\nZ = A*n + (X**2 - A*np.cos(2*pi*X) ) + (Y**2 -A*np.cos(2*pi*Y)) # codomain\n\ndef RastriginFun(x,y,A=10,n=2):\n Z = A*n + (x**2 - A*np.cos(2*pi*x) ) + (y**2 -A*np.cos(2*pi*y))\n return Z\n" }, { "alpha_fraction": 0.34994378685951233, "alphanum_fraction": 0.3604346215724945, "avg_line_length": 35.08108139038086, "blob_id": "dbd11ec4ee0f85c7ee54af2c559b1efc675434a2", "content_id": "a93b90ebf1bb9a65d87fac6d532314da8be31889", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2669, "license_type": "no_license", "max_line_length": 92, "num_lines": 74, "path": "/animation.py", "repo_name": "Metafyzik/Genetic-algorithm", "src_encoding": "UTF-8", "text": "import plotly.express as px\nimport plotly.graph_objects as go\n#frames to be vizualized\n\nframes_all = []\ntext_anima = \"Genetic algorithm, generation {}\"\n\ndef add_frames(x,y,z,cycle,frames_all): \n\tframes_all.append( go.Frame(data=[go.Scatter3d(x=x, \n \t\t\t\t y=y,z=z,mode=\"markers\",\n marker=dict(color=\"red\", size=8),) \n ], \n layout=go.Layout(title_text=text_anima.format(cycle)),\n name=str(cycle) \n ) \n )\n\ndef frame_args(duration):\n return {\n \"frame\": {\"duration\": duration,\"redraw\": \"redraw\"},\n \"mode\": \"immediate\",\n \"fromcurrent\": True,\n \"transition\": {\"duration\": 150, \"easing\": \"linear\"},\n }\n\ndef visualization(frames_all,X,Y,Z,lower_bound,upper_bound):\n sliders = [\n {\n \"pad\": {\"b\": 10, \"t\": 60},\n \"len\": 0.3,\n \"x\": 0.1,\n \"y\": 0.1,\n \"steps\": [\n {\n \"args\": [[frame.name], frame_args(0)],\n \"label\": str(k),\n \"method\": \"animate\",\n }\n for k, frame in enumerate(frames_all)\n ],\n }\n ]\n \n fig = go.Figure(\n data=[go.Surface(z=Z,x=X,y=Y),\n go.Surface(z=Z,x=X,y=Y )],\n layout=go.Layout(\n xaxis=dict(range=[lower_bound, upper_bound], \n \t autorange=False, \n \t zeroline=False),\n yaxis=dict(range=[lower_bound, upper_bound], \n \t autorange=False, \n \t zeroline=False),\n title_text=\"Genetic algorithm\", hovermode=\"closest\",\n updatemenus=[dict(type=\"buttons\",\n \t\t\t\t direction = \"left\",\n \t\t\t\t x = 0.1,\n \t\t\t\t y = 0.1,\n \t\t\t\t pad = dict(r= 10, t=70),\n buttons=[dict(label=\"Run\",\n method=\"animate\",\n args=[None, frame_args(200)] ),\n dict(label=\"Stop\",\n method=\"animate\",\n args=[[None],frame_args(0)] ) ],\n \n )\n ],\n\n sliders=sliders),\n frames=frames_all\n )\n \n fig.show()" }, { "alpha_fraction": 0.7967479825019836, "alphanum_fraction": 0.7967479825019836, "avg_line_length": 60.5, "blob_id": "61a7448c3594ac02f524481cbe2be3d8c3675c45", "content_id": "59214d6ea3c4b14614a3b0a84494eefdf46a2032", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 246, "license_type": "no_license", "max_line_length": 196, "num_lines": 4, "path": "/README.md", "repo_name": "Metafyzik/Genetic-algorithm", "src_encoding": "UTF-8", "text": "# Genetic algorithm\nBuilding a simple Genetic algorithm from sratch (more or less) and using it to find global extreme on Rastrigin function. Using modul numpy for its arrays and Plotly for interactive visualization.\n\n![](images/gen_alg_vis.gif)\n" }, { "alpha_fraction": 0.6695445775985718, "alphanum_fraction": 0.6809842586517334, "avg_line_length": 38.25423812866211, "blob_id": "fddc99f0afe7508c82a4fef36de035cf8cd51b46", "content_id": "459df91c4c329a3950f64bb7b7e36e35d3d7e71b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4633, "license_type": "no_license", "max_line_length": 119, "num_lines": 118, "path": "/genetic_algorithm.py", "repo_name": "Metafyzik/Genetic-algorithm", "src_encoding": "UTF-8", "text": "# imports\nfrom numpy import random\nimport numpy as np\n\n#! wild card import is not good practise\nfrom function_for_optimization import *\nfrom animation import *\n\ndef binarToDecim(binary_list):\n decimal_number = 0\n for index, binary in enumerate (binary_list[:: -1]):\n decimal_number += 2**index*int(binary)\n return decimal_number\n\ndef nullGeneration(num_individuals,string_len,values,num_coordinates): \n # Duplicate values are possible\n nullgeneration = random.randint(values, size=(num_individuals,num_coordinates,string_len))\n\n return nullgeneration\n\ndef evaluation(individuals, num_individuals=10): \n valued_individuals = np.array([],dtype=object) \n x_coordinates = []\n y_coordinates = []\n z_coordinates = []\n\n for individual in individuals: \n decimal_index_x = binarToDecim(individual[0])\n decimal_index_y = binarToDecim(individual[1])\n\n #coordinates of an individual on Rastrigin plot \n x = xy_domain[decimal_index_x]\n y = xy_domain[decimal_index_y]\n z = RastriginFun( x,y ) \n\n fitness = 1/z\n valued_individuals = np.append( np.array([individual,fitness],dtype=object,),valued_individuals ) \n\n # add individual for visualization\n x_coordinates.append(x)\n y_coordinates.append(y)\n z_coordinates.append(z)\n\n valued_individuals = valued_individuals.reshape(num_individuals,2) #! can I do it without reshaping?\n return valued_individuals,x_coordinates,y_coordinates,z_coordinates\n\ndef selection(valued_individuals,num_parents,num_individuals):\n sum_fitness = sum(valued_individuals[:,1])\n\n # propabality of individuals becoming a parent based on their fitness\n propability_individuals = valued_individuals[:,1]/(sum_fitness)\n \n #changing data type from float64 to float so that can be used as keyword \"p\" in random.choice\n propability_individuals = propability_individuals.astype('float')\n\n parents = np.random.choice(valued_individuals[0:num_individuals,0],size=(num_parents,2),p=propability_individuals )\n return parents\n \ndef recombine(prnt_1_bitstr,prnt_2_bitstr,point_recombin=4,string_len=8): \n # function for recombining two binary strings, point_recombin stands for point of recombination\n\n child_x= np.array([prnt_1_bitstr[ :point_recombin],prnt_2_bitstr[point_recombin:]])\n child_y = np.array([prnt_2_bitstr[ :point_recombin],prnt_1_bitstr[point_recombin:]])\n\n child_x = child_x.reshape(string_len) \n child_y = child_y.reshape(string_len)\n\n return [child_x,child_y]\n\ndef crossover(parents,string_len,point_recombin):\n children = []\n\n # every couple generates two children\n for couple in parents:\n child_1 = recombine(couple[0][0],couple[1][0],point_recombin,string_len)\n child_2 = recombine(couple[0][1],couple[1][1],point_recombin,string_len)\n\n children.append(child_1) \n children.append(child_2)\n \n children = np.array(children)\n return children\n\ndef mutation(children,indi_to_mutate,num_children,string_len,num_coordinates): #!clean up\n \n for i in range (indi_to_mutate):\n child = random.randint(num_children) # pick one of the children\n coordinate = random.randint(num_coordinates) # pick X or Y coordinate index (cooded in bit string)\n gene = random.randint(string_len) # pick one gene (bit) to change\n\n #! this code only work with binary so the mutation negates\n if children[child,coordinate,gene] == 1:\n children[child,coordinate,gene] = 0\n else:\n children[child,coordinate,gene] = 1\n\n return children\n\ndef geneticAglorithm (cycles=30,num_individuals=40,\n\tnum_parents=20,num_children=40,string_len=10,\n\tvalues=2,num_coordinates=2,point_recombin=5,indi_to_mutate=2):\n #incialization of the null gen\n generation = nullGeneration(num_individuals,string_len,values,\n \t\t\t\t\t\t\tnum_coordinates) \n for cycle in range (cycles):\n generation,x_coordinates,y_coordinates,z_coordinates = evaluation(generation, num_individuals)\n # creating frames for visualization\n add_frames(x_coordinates,y_coordinates,z_coordinates,cycle,frames_all)\n\n generation = selection(generation,num_parents,\n \t num_individuals)\n generation = crossover(generation,string_len,point_recombin)\n generation = mutation(generation,indi_to_mutate,\n \t num_children,string_len,num_coordinates)\n\n visualization(frames_all,X,Y,Z,lower_bound,upper_bound)\n \ngeneticAglorithm()\n\n" }, { "alpha_fraction": 0.8095238208770752, "alphanum_fraction": 0.8095238208770752, "avg_line_length": 5.666666507720947, "blob_id": "555801dd2aa860ee15fae91b06c1ce4b8b621d18", "content_id": "9ebc11eba650ef7777369c80792a22ace1080b6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 21, "license_type": "no_license", "max_line_length": 6, "num_lines": 3, "path": "/requirements.txt", "repo_name": "Metafyzik/Genetic-algorithm", "src_encoding": "UTF-8", "text": "numpy\r\nplotly\r\npandas" } ]
5
wujuguang/hichao-backend-suite
https://github.com/wujuguang/hichao-backend-suite
506f0c73378de7f297ca4871f81d020ba101a672
f95b50f2a8705839231ebf78c9e9097ca0e18e54
1111cdb48e0d33dff8cfa83ec0b9259f92c42c61
HEAD
2018-01-07T16:37:32.623459
2015-08-17T02:46:14
2015-08-17T02:46:14
37,501,830
3
1
null
null
null
null
null
[ { "alpha_fraction": 0.7145969271659851, "alphanum_fraction": 0.7145969271659851, "avg_line_length": 26.81818199157715, "blob_id": "7b14a804997be498dbe275c2be5c29200f33356f", "content_id": "0ecd34488d2616567b7e5c272607f79988facdcb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 918, "license_type": "no_license", "max_line_length": 132, "num_lines": 33, "path": "/README.rst", "repo_name": "wujuguang/hichao-backend-suite", "src_encoding": "UTF-8", "text": "====================\nhichao-backend-suite\n====================\n\nCookiecutter template for a Python package. See https://github.com/audreyr/cookiecutter.\n\nUsage\n-----\n\nGenerate a Python package project::\n\n cookiecutter https://github.com/wujuguang/hichao-backend-suite.git\n\nSetup\n-----\n\ndownload and execute setup.sh::\n\n wget https://raw.githubusercontent.com/wujuguang/hichao-backend-suite/box_backend/setup.sh && sh setup.sh <db_name> <table_name>\n\nMore Easy\n---------\n\n::\n\n wget https://raw.githubusercontent.com/wujuguang/hichao-backend-suite/box_backend/suite_client.sh\n wget https://raw.githubusercontent.com/wujuguang/hichao-backend-suite/box_backend/backend_suite/json_conf.py\n\n#. Use virtualenv command \"workon/source\" at Terminal, Switch to your <new_backend> virtualenv.\n\n#. Execute \"sh suite_client.sh <db_name> <table_name>\" at Terminal.\n\nNote: you only required suite_client.sh for More Easy.\n" }, { "alpha_fraction": 0.579119086265564, "alphanum_fraction": 0.5905383229255676, "avg_line_length": 25.65217399597168, "blob_id": "69bae0852f9d536fa703a079753be8e0ec73f034", "content_id": "bd49a6d36c7da1d44c1e78e47d385c29947504a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 657, "license_type": "no_license", "max_line_length": 73, "num_lines": 23, "path": "/backend_suite/work_build.py", "repo_name": "wujuguang/hichao-backend-suite", "src_encoding": "UTF-8", "text": "#!usr/bin/env python\n# coding: utf-8\n\nfrom __future__ import print_function, unicode_literals\nfrom cookiecutter.main import cookiecutter\nfrom json_build import main\n\nif __name__ == '__main__':\n \"\"\"测试.\n \"\"\"\n\n extra_context = main(context=\"dict\")\n print(\"extra_context Data:\")\n print(extra_context)\n print(\"=\" * 120)\n cookiecutter('https://github.com/wujuguang/hichao-backend-suite.git',\n no_input=True,\n checkout='new_backend',\n extra_context=extra_context)\n\n print(\"=\" * 120)\n print(\"活已完毕, 请验收目录下代码, 细节方面要对调哦(^_^)(^_^)(^_^)\")\n print()\n" }, { "alpha_fraction": 0.6982455849647522, "alphanum_fraction": 0.7122806906700134, "avg_line_length": 22.75, "blob_id": "655f46525a304b08ded6fb19e9f29cf2dba31390", "content_id": "b379dad82933f52394bcc0cea1f8e545a2088c4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 319, "license_type": "no_license", "max_line_length": 130, "num_lines": 12, "path": "/suite_client.sh", "repo_name": "wujuguang/hichao-backend-suite", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# 使用:\n# 1. 先workon new_backend虚拟环境\n# 2. sh suite_client.sh <db_name> <table_name>\n\n# 传入命令并赶驴拉磨\ndb_name=$1\ntable_name=$2\n\nwget https://raw.githubusercontent.com/wujuguang/hichao-backend-suite/box_backend/setup.sh && sh setup.sh ${db_name} ${table_name}\nrm setup.sh\n" }, { "alpha_fraction": 0.690744936466217, "alphanum_fraction": 0.697516918182373, "avg_line_length": 22.945945739746094, "blob_id": "8420944640cdba8e8083c4fcb9d926cad617445e", "content_id": "a5c70fa22e0a9a0a10cb9ca01d842b55e8cbc57b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 936, "license_type": "no_license", "max_line_length": 112, "num_lines": 37, "path": "/setup.sh", "repo_name": "wujuguang/hichao-backend-suite", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nif [ ! -f \"json_conf.py\" ]; then\n isWork=0\nelse\n ifWork=1\nfi\n\n# 下载脚本\nif [ \"$isWork\" -eq 0 ]; then\n wget https://raw.githubusercontent.com/wujuguang/hichao-backend-suite/box_backend/backend_suite/json_conf.py\nfi\n\nwget https://raw.githubusercontent.com/wujuguang/hichao-backend-suite/box_backend/backend_suite/json_build.py\nwget https://raw.githubusercontent.com/wujuguang/hichao-backend-suite/box_backend/backend_suite/work_build.py\n\n# 安装部署环境\npip install cookiecutter autoloads\n\n# 传入命令并赶驴拉磨\ndb_name=$1\necho \"come from ${db_name} database's data!\"\n\ntable_name=$2\necho \"generate ${table_name} table's business logic!\"\n\npython work_build.py ${db_name} ${table_name}\n\n# 删除执行文件\nrm work_build.py json_build.py\n\nif [ \"$isWork\" -eq 0 ]; then\n rm json_conf.py\nfi\n\nfind ./ -type f -name \"*.py[cod]\" -exec rm -rf {} \\;\nfind ./ -type f -name \"*~\" -exec rm -rf {} \\;\n" }, { "alpha_fraction": 0.5345963835716248, "alphanum_fraction": 0.5708401799201965, "avg_line_length": 21.481481552124023, "blob_id": "30a11bd243f6caca10ff73fc11f790b7a3e1cd3f", "content_id": "37e8cde027b3e590f021cf58809c30c6c31e4c91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1242, "license_type": "no_license", "max_line_length": 78, "num_lines": 54, "path": "/backend_suite/json_conf.py", "repo_name": "wujuguang/hichao-backend-suite", "src_encoding": "UTF-8", "text": "#!usr/bin/env python\n# coding: utf-8\n\nfrom __future__ import print_function, unicode_literals\n\necho = False\npool_recycle = 60\ncolumn_prefix = \"-\" # 为区别不使用下划线而特殊设置\n\nmysql_config = dict(\n host=\"127.0.0.1\",\n port=3306,\n user=\"develop\",\n passwd=\"12345678\",\n charset=\"utf8\")\n\ndict_content = {\n \"full_name\": \"wujuguang\",\n \"email\": \"[email protected]\",\n \"github_username\": \"wujuguang\",\n \"project_name\": \"backend\",\n \"repo_name\": \"new_backend\",\n \"project_short_description\": \"generating module of hichao's backend MIS.\",\n \"release_date\": \"2015-06-12\",\n \"year\": \"2015\",\n \"version\": \"0.1.0\",\n\n \"bases_models\": \"\",\n \"packs_name\": \"\",\n \"sheet_name\": \"\",\n \"class_name\": \"\",\n \"entity_name\": \"\",\n \"column_list\": \"\"\n}\n\njson_content = \"\"\"{\n \"full_name\": \"wujuguang\",\n \"email\": \"[email protected]\",\n \"github_username\": \"wujuguang\",\n \"project_name\": \"backend\",\n \"repo_name\": \"new_backend\",\n \"project_short_description\": \"generating module of hichao's backend MIS.\",\n \"release_date\": \"2015-06-12\",\n \"year\": \"2015\",\n \"version\": \"0.1.0\",\n\n \"bases_models\": \"%s\",\n \"packs_name\": \"%s\",\n \"sheet_name\": \"%s\",\n \"class_name\": \"%s\",\n \"entity_name\": \"%s\",\n \"column_list\": \"%s\",\n %s\n}\"\"\"\n" }, { "alpha_fraction": 0.575631320476532, "alphanum_fraction": 0.5777141451835632, "avg_line_length": 31.008333206176758, "blob_id": "db944aca591919ccafce62bdbe5f60c1cc0136ce", "content_id": "8eef916fa77424a4a21e3b91575355017d8f73c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3917, "license_type": "no_license", "max_line_length": 118, "num_lines": 120, "path": "/backend_suite/json_build.py", "repo_name": "wujuguang/hichao-backend-suite", "src_encoding": "UTF-8", "text": "#!usr/bin/env python\n# coding: utf-8\n\nfrom __future__ import print_function, unicode_literals\n\nfrom optparse import OptionParser\nfrom functools import partial\nfrom autoloads import Models\nfrom json_conf import echo, pool_recycle, column_prefix, mysql_config, dict_content, json_content\n\n\ndef generate_models(host_config, database_name, table_name):\n _models = Models(\n echo=echo,\n pool_recycle=pool_recycle,\n column_prefix=column_prefix,\n host=host_config['host'],\n port=host_config['port'],\n user=host_config['user'],\n database=database_name,\n tables=[table_name],\n passwd=host_config['passwd'],\n charset=host_config['charset'],\n schema=database_name)\n return _models\n\n\ngenerate_models_func = partial(\n generate_models,\n host_config=mysql_config)\n\n\ndef create_module_json(database_name, table_name, context=\"json\", **kargs):\n \"\"\"从数据库表里生成json配置.\n\n :param database_name: 数据库名\n :param table_name: 数据表名\n :param context: 生成数据类型 (\"json\",\"dict\")\n \"\"\"\n\n db_models = generate_models_func(database_name=str(database_name), table_name=str(table_name))\n table_model = db_models(table_name)\n\n unity_name = table_name.lower()\n class_name = table_name.title().replace('_', '')\n packs_name = unity_name.split('_')[0] if '_' in unity_name else unity_name\n bases_models = \"%s_models\" % database_name\n column_list = ['_%s' % i[1:] for i in dir(table_model) if i[0] == column_prefix]\n\n if context.lower() not in (\"json\", \"dict\"):\n raise Exception('Param \"context\" error!')\n\n if context == \"dict\":\n dict_content.update({\n \"bases_models\": bases_models,\n \"packs_name\": packs_name,\n \"sheet_name\": table_name,\n \"class_name\": class_name,\n \"entity_name\": unity_name,\n \"column_list\": column_list})\n dict_content.update(kargs)\n return dict_content\n else:\n if kargs:\n list_args = []\n for key, value in kargs.items():\n list_args.append('\"%s\": \"%s\"' % (key, value))\n str_args = r',\\n'.join(list_args)\n\n content = json_content % (bases_models, packs_name, table_name, class_name, unity_name, column_list, str_args)\n with open(\"cookiecutter.json\", 'wb') as f:\n f.write('%s' % content)\n return content\n\n\ndef main(context=\"json\"):\n \"\"\"提供外部 entry points 而用.\n\n :param context: 生成数据类型 (\"json\",\"dict\")\n \"\"\"\n\n parser = OptionParser()\n parser.add_option(\"-d\", \"--database_name\", type=\"string\",\n dest=\"database_name\",\n default=None,\n help=\"build json file from database.\")\n\n parser.add_option(\"-t\", \"--table_name\", type=\"string\",\n dest=\"table_name\",\n default=None,\n help=\"table's name build json file.\")\n\n parser.add_option(\"-s\", \"--status_field\", type=\"string\",\n dest=\"status_field\",\n default=\"_status\",\n help=\"State identification field.\")\n\n (options, args) = parser.parse_args()\n if len(args) < 2 and (not options.database_name or not options.table_name):\n parser.error(\"incorrect number of arguments\")\n return\n\n extra_dict = {}\n dict_options = eval(str(options))\n for key, value in dict_options.items():\n if key[0] == '_' or key in (\"database_name\", \"table_name\"):\n continue\n extra_dict[key] = value\n\n database_name = options.database_name or args[0]\n table_name = options.table_name or args[1]\n return create_module_json(str(database_name), str(table_name), context, **extra_dict)\n\n\nif __name__ == '__main__':\n \"\"\"测试.\n \"\"\"\n\n # print(main())\n print(main(\"dict\"))\n" } ]
6
AsahinaMikuruFans/ProjectFS
https://github.com/AsahinaMikuruFans/ProjectFS
fe158b54d403eda9f1a5664f7770b39662b89845
26a19edf3c793963124f45a5ae50626c21bb482a
3647d56c3b2ec0c89b87f92904c4ac66503b4ce0
refs/heads/master
2021-03-15T09:36:57.854397
2021-02-04T02:32:08
2021-02-04T02:32:08
246,840,482
2
0
null
2020-03-12T13:24:16
2020-03-29T12:26:02
2020-03-29T12:42:57
Python
[ { "alpha_fraction": 0.46950575709342957, "alphanum_fraction": 0.5039972066879272, "avg_line_length": 31.181230545043945, "blob_id": "097201d4de0dabc20e49dc1a3038174076066b38", "content_id": "2ca28fc772124c75e568a7daf1d913554d40b98c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21065, "license_type": "no_license", "max_line_length": 112, "num_lines": 618, "path": "/source/examples/reference.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import math\nimport random\nfrom math import cos, sin\n\nimport pygame\n\nfrom source.core.assembly.Painter import Painter\nfrom source.core.math.Vector import point2, vec2\nfrom source.core.math.MathConst import PI, PI_DOUBLE\nfrom source.core.math.MathUtil import mapping\nfrom source.core.math.Shape import Circle, Line\nfrom source.core.multimedia.MusicPlayer import musicPlayer\nfrom source.view.baseClazz.Scene import Scene\n\n\nclass drawingBoard(Scene):\n \"\"\"画板 按q清屏\n\n 展示了Scene一些内置对象与变量的基本用法\n \"\"\"\n\n def __init__(self, *args):\n super(drawingBoard, self).__init__(*args)\n self.color = (255, 255, 255)\n self.stork = 1\n self.isFill = False\n self.__start = point2()\n self.interval = 10\n self.caption = '测试场景:画板 按鼠标左键进行绘制,q键清屏'\n\n def draw(self):\n if not self.__start.isZero():\n Painter(self.screen).Lines([self.__start, point2(self.mousePos)], self.color, self.stork, 0, 1)\n self.__start = point2(self.mousePos)\n\n def doMouseButtonDownEvent(self, Button):\n if Button == 1:\n self.__start = point2(self.mousePos)\n\n def doMouseButtonUpEvent(self, Button):\n if Button == 1:\n self.__start = point2()\n\n def doKeyEvent(self, Key, Mod, Type, Unicode=None):\n if Key == 113:\n self.screen.fill((0, 0, 0))\n\n\nclass createWave(Scene):\n \"\"\"创建波纹\n\n 这个例子展示了Scene内置对象 sceneCanvas 与 screen的关系。\n\n 试着将isFill设置为True或删去,或将sceneCanvas相关的方法移动到初始化方法里,看看结果。\n \"\"\"\n\n def __init__(self, *args):\n super(createWave, self).__init__(*args)\n self.isFill = False\n self.t = 0.0\n self.sceneCanvas = self.screen.copy()\n self.caption = '测试场景:波纹'\n\n def draw(self):\n self.sceneCanvas.fill((0, 0, 0))\n self.sceneCanvas.set_alpha(20)\n # 创建圆\n for i in range(0, 800, 30):\n for j in range(0, 600, 30):\n # 每个圆的初始位置取决于鼠标位置\n ax = mapping(self.mouseX, 0, 800, -4 * PI, 4 * PI)\n ay = mapping(self.mouseY, 0, 600, -4 * PI, 4 * PI)\n\n # 根据圆的位置获取角度\n angle = ax * (i / 800) + ay * (j / 600)\n\n # 每个圆做圆周运动\n x = i + 20 * cos(2 * PI * self.t + angle)\n y = j + 20 * sin(2 * PI * self.t + angle)\n\n Painter(self.sceneCanvas).Circle(Circle(x, y, 10), (0, 255, 0), 0)\n self.t += 0.01 # 更新时间\n self.screen.blit(self.sceneCanvas, (0, 0))\n\n\nclass sketchSphere(Scene):\n \"\"\"在2维平面上画一个球体\n\n 这个例子展示了Scene内置对象 sceneCanvas 与 screen的关系。\n\n 或将sceneCanvas相关的方法移动到draw方法里,看看结果。\n \"\"\"\n\n def __init__(self, *args):\n super(sketchSphere, self).__init__(*args)\n self.t = 0.0\n self.sceneCanvas = self.screen.copy()\n self.sceneCanvas.fill((255, 255, 255))\n self.sceneCanvas.set_alpha(150)\n self.caption = '测试场景:草稿'\n\n def __randomChord(self):\n angle1 = random.uniform(0, PI_DOUBLE)\n x_pos1, y_pos1 = self.width / 2 + 200 * cos(angle1), self.height / 2 + 200 * sin(angle1)\n angle2 = random.uniform(0, PI_DOUBLE)\n x_pos2, y_pos2 = self.width / 2 + 200 * cos(angle2), self.height / 2 + 200 * sin(angle2)\n\n Painter(self.sceneCanvas).Lines([point2(x_pos1, y_pos1), point2(x_pos2, y_pos2)], (0, 0, 0), 1, 0, 1)\n self.screen.blit(self.sceneCanvas, (0, 0))\n\n def draw(self):\n self.__randomChord()\n self.__randomChord()\n\n\nclass chain(Scene):\n \"\"\"改写自p5.js范例,基于 Keith Peters 的代码\n\n 随鼠标移动的一条分段式线条。\n\n 每段之间的相对角度是用 atan2() 计算的,位置是用 sin() 和 cos() 计算的。\n \"\"\"\n\n def __init__(self, *args):\n super(chain, self).__init__(*args)\n self.segNum = 10\n self.segLength = 40\n self.x, self.y = [0] * self.segNum, [0] * self.segNum\n self.caption = '测试场景:链条'\n\n def __dragSegment(self, i, xin, yin):\n dx, dy = xin - self.x[i], yin - self.y[i]\n angle = math.atan2(dy, dx)\n self.x[i], self.y[i] = xin - cos(angle) * self.segLength, yin - sin(angle) * self.segLength\n self.__segment(self.x[i], self.y[i], angle)\n\n def __segment(self, x, y, a):\n line = Line(point2(x, y), a, self.segLength)\n Painter(self.screen).Line(line, (255, 255, 255), 10, 1)\n\n def draw(self):\n self.__dragSegment(0, self.mouseX, self.mouseY)\n for i in range(0, len(self.x) - 1):\n self.__dragSegment(i + 1, self.x[i], self.y[i])\n\n\nclass paramEquation(Scene):\n \"\"\"这个是参数方程的例子, 改写自p5.js范例,灵感来源于Alexander Miller的视频\"\"\"\n\n def __init__(self, *args):\n super(paramEquation, self).__init__(*args)\n self.t = 0 # x 和 y 所依靠的参数通常被视为 t\n self.caption = '数学之美:参数方程'\n\n def draw(self):\n for i in range(0, 100):\n s_point = point2(self.width / 2 + self.__x1(i), self.height / 2 + self.__y1(i))\n e_point = point2(self.width / 2 + self.__x2(i) + 20, self.height / 2 + self.__y2(i) + 20)\n Painter(self.screen).Lines([s_point, e_point], (255, 255, 255), 1, 0, 1)\n self.t += 0.15\n\n # 改变直线的初始 x 坐标\n def __x1(self, i):\n return sin((self.t + i) / 10) * 125 + sin((self.t + i) / 20) * 125 + sin((self.t + i) / 30) * 125\n\n # 改变直线的初始 y 坐标\n def __y1(self, i):\n return cos((self.t + i) / 10) * 125 + cos((self.t + i) / 20) * 125 + cos((self.t + i) / 30) * 125\n\n # 改变直线的最终 x 坐标\n def __x2(self, i):\n return sin((self.t + i) / 15) * 125 + sin((self.t + i) / 25) * 125 + sin((self.t + i) / 35) * 125\n\n # 改变直线的最终 y 坐标\n def __y2(self, i):\n return cos((self.t + i) / 15) * 125 + cos((self.t + i) / 25) * 125 + cos((self.t + i) / 35) * 125\n\n\nclass kaleidoscope(Scene):\n \"\"\"一个很有趣的万华筒,改写自p5.js的范例 按q键清空屏幕\n\n 万花筒是一个光学仪器,具有两个或多个互相倾斜的反射面。 此范例尝试模仿万花筒的效果。 通过 symmetry 变量设定反射的数量,并开始在屏幕上绘制\n \"\"\"\n\n def __init__(self, *args):\n super(kaleidoscope, self).__init__(*args)\n self.symmetry = 6\n self.angle = math.radians(360 / self.symmetry)\n self.isFill = False\n self.v = vec2(self.width / 2, self.height / 2)\n self.caption = '测试场景:万花筒 按下鼠标按键进行绘制,按q键清屏'\n self.painter = Painter(self.screen)\n\n def draw(self):\n if 0 < self.mouseX < self.width and 0 < self.mouseY < self.height:\n mx = self.mouseX - self.width / 2\n my = self.mouseY - self.height / 2\n pmx = self.lastMousePos[0] - self.width / 2\n pmy = self.lastMousePos[1] - self.height / 2\n\n v1_n = vec2(self.width / 2 + mx, self.height / 2 + my)\n v1_l = vec2(self.width / 2 + pmx, self.height / 2 + pmy)\n v2_n = vec2(self.width / 2 + mx, self.height / 2 - my)\n v2_l = vec2(self.width / 2 + pmx, self.height / 2 - pmy)\n\n if self.mousePressed:\n self.painter.push()\n for i in range(0, self.symmetry):\n # v1_n = self.__rotateBy(v1_n, self.width / 2, self.height / 2)\n # v1_l = self.__rotateBy(v1_l, self.width / 2, self.height / 2)\n # v2_n = self.__rotateBy(v2_n, self.width / 2, self.height / 2)\n # v2_l = self.__rotateBy(v2_l, self.width / 2, self.height / 2)\n\n self.painter.rotate(self.width / 2, self.height / 2, self.angle)\n self.painter.Lines([v1_n, v1_l], (255, 255, 255), 1, 0, 1)\n self.painter.Lines([v2_n, v2_l], (255, 255, 255), 1, 0, 1)\n self.painter.pop()\n\n # 将v以(x, y)点为中心进行旋转\n # def __rotateBy(self, v, x, y):\n # v = vec2(v.x - x, v.y - y)\n # v = v.rotate(self.angle)\n # v = vec2(v.x + x, v.y + y)\n # return v\n\n def doKeyEvent(self, Key, Mod, Type, Unicode=None):\n if Key == 113:\n self.screen.fill((0, 0, 0))\n\n\nclass snowScene(Scene):\n \"\"\"下雪的场景, 雪会随着音乐变化\"\"\"\n\n def __init__(self, *args):\n super(snowScene, self).__init__(*args)\n self.snowflakes = []\n self.music_path = 'resource/Test/雪之华.wav'\n # self.music_path = 'E:/Music/星之所在.wav'\n self.caption = '测试场景:音乐与动画交互 雪之华-中岛美嘉'\n self.player = musicPlayer()\n self.player.add('0', self.music_path)\n pygame.mixer.music.load(self.music_path)\n\n def draw(self):\n if not pygame.mixer.music.get_busy():\n self.player.active('0')\n pygame.mixer.music.play()\n ma, fps = 0, 60\n if self.FPS != 0:\n fps = self.FPS\n lis = self.player.getMsg('0', round(1 / fps * 8000))\n for n in lis:\n if n > ma:\n ma = n\n\n if ma != 0:\n p = mapping(ma, 0, 6000, 0, 5)\n p = round(p)\n else:\n p = 0\n\n t = self.frameCount / 180\n\n for i in range(random.randint(0, p)):\n self.snowflakes.append(snowFlake(self.width, self.height))\n\n for flake in self.snowflakes:\n flake.update(t, self.snowflakes)\n flake.display(self.screen)\n\n\nclass snowFlake:\n def __init__(self, w, h):\n self.width = w\n self.height = h\n self.posX = 0\n self.posY = random.randint(-50, 0)\n self.initial_angle = random.uniform(0, PI_DOUBLE)\n self.size = random.randint(2, 5)\n\n self.radius = math.sqrt(random.uniform(0, pow(self.width / 2, 2)))\n\n def update(self, time, ary):\n w = 0.6 # 角速度\n angle = w * time + self.initial_angle\n\n self.posX = self.width / 2 + self.radius * math.sin(angle)\n self.posY += pow(self.size, 0.5)\n\n if self.posY > self.height:\n ary.remove(self)\n\n def display(self, sur):\n Painter(sur).Circle((self.posX, self.posY, self.size / 2), (255, 255, 255), 0)\n\n\nclass MandelbrotSet(Scene):\n \"\"\"分形(fractal)模拟: 曼德勃罗集 Mandelbrot set\"\"\"\n\n def __init__(self, *args):\n super(MandelbrotSet, self).__init__(*args)\n self.caption = '测试场景: MandelbrotSet'\n\n self.width, self.height = 600, 600\n self.canvas = pygame.Surface((self.width, self.height))\n # self.canvas.lock()\n self.max_iteration = 100\n for x in range(self.width):\n for y in range(self.height):\n a = mapping(x, 0, self.width, -1.5, 1.5)\n b = mapping(y, 0, self.height, -1.5, 1.5)\n ca, cb = a, b\n\n n = 0\n while n < self.max_iteration: # 迭代\n aa, bb = a * a - b * b, 2 * a * b\n a, b = aa + ca, bb + cb\n if abs(a + b) > 16:\n break\n n += 1\n\n bright = mapping(n, 0, self.max_iteration, 0, 1)\n bright = mapping(math.sqrt(bright), 0, 1, 0, 255)\n if n is self.max_iteration:\n bright = 0\n\n self.canvas.set_at([x, y], (bright, bright, bright))\n # self.canvas.unlock()\n\n def draw(self):\n self.screen.blit(self.canvas, self.canvas.get_rect())\n\n\nclass JuliaSet(Scene):\n \"\"\"分形(fractal)模拟: 茱莉亚集 JuliaSet set\"\"\"\n\n def __init__(self, *args):\n super(JuliaSet, self).__init__(*args)\n self.caption = '测试场景: JuliaSet'\n\n self.real = -0.70176 # 0.285 # -0.70176 # -0.8 # 实部\n self.imaginary = -0.3842 # 0.01 # -0.3842 # 0.156 # 虚部\n\n self.width, self.height = 600, 600\n self.canvas = pygame.Surface((self.width, self.height))\n\n self.w = 5\n self.h = (self.w * self.height) / self.width\n\n self.x_min = - self.w / 2\n self.y_min = - self.h / 2\n self.x_max = self.x_min + self.w\n self.y_max = self.y_min + self.h\n\n self.dx = (self.x_max - self.x_min) / self.width\n self.dy = (self.y_max - self.y_min) / self.height\n\n self.max_iteration = 100\n\n self.y = self.y_min\n for i in range(self.width):\n self.x = self.x_min\n for j in range(self.height):\n a = self.y\n b = self.x\n\n n = 0\n while n < self.max_iteration: # 迭代\n aa, bb = a * a, b * b\n ab_double = 2 * a * b\n a, b = aa - bb + self.real, ab_double + self.imaginary\n if aa * aa + bb * bb > 16:\n break\n n += 1\n\n if n == self.max_iteration:\n self.canvas.set_at([i, j], (0, 0, 0))\n else:\n norm = mapping(n, 0, self.max_iteration, 0, 1)\n norm = mapping(math.sqrt(norm), 0, 1, 0, 255)\n self.canvas.set_at([i, j], (norm, norm, norm))\n\n self.x += self.dx\n self.y += self.dy\n\n def draw(self):\n self.screen.blit(self.canvas, self.canvas.get_rect())\n\n\nclass IFS(Scene):\n \"\"\"分形(fractal)模拟: Iterated function system 迭代分形系统\"\"\"\n\n def __init__(self, *args):\n super(IFS, self).__init__(*args)\n self.caption = '测试场景: Iterated function system 迭代分形系统'\n\n self.width, self.height = 600, 600\n self.canvas = pygame.Surface((self.width, self.height))\n\n self.max_iteration = 100\n for x in range(self.width):\n for y in range(self.height):\n a = mapping(x, 0, self.width, -1.5, 1.5)\n b = mapping(y, 0, self.height, -1.5, 1.5)\n ca, cb = a, b\n\n n = 0\n while n < self.max_iteration: # 迭代\n ran = random.randint(0, 3)\n if ran == 0:\n a, b = self.__rul_0(a, b, ca, cb)\n elif ran == 1:\n a, b = self.__rul_1(a, b, ca, cb)\n elif ran == 2:\n a, b = self.__rul_2(a, b, ca, cb)\n elif ran == 3:\n a, b = self.__rul_3(a, b, ca, cb)\n # aa, bb = a * a - b * b, 2 * a * b\n # a, b = aa + ca, bb + cb\n if abs(a + b) > 16:\n break\n n += 1\n\n bright = mapping(n, 0, self.max_iteration, 0, 1)\n bright = mapping(math.sqrt(bright), 0, 1, 0, 255)\n if n is self.max_iteration:\n bright = 0\n\n self.canvas.set_at([x, y], (bright, bright, bright))\n\n @staticmethod\n def __rul_0(a, b, ca, cb):\n aa, bb = a * a - b * b, 2 * a * b\n return aa + ca, bb + cb\n\n @staticmethod\n def __rul_1(a, b, ca, cb):\n aa, bb = a * a + b * b, 2 * a * b\n return aa + ca, bb + cb\n\n @staticmethod\n def __rul_2(a, b, ca, cb):\n aa, bb = a * a, 2 * a * b\n return aa + ca, bb + cb\n\n @staticmethod\n def __rul_3(a, b, ca, cb):\n aa, bb = b * b, 2 * a * b\n return aa + ca, bb + cb\n\n def draw(self):\n self.screen.blit(self.canvas, self.canvas.get_rect())\n\n\nclass LSystemScene(Scene):\n \"\"\"L-System 分形树,灵感来源于the Coding Train的视频\"\"\"\n\n def __init__(self, *args):\n super(LSystemScene, self).__init__(*args)\n\n rule_str1_1 = 'F->FF+[+F-F-F]-[-F+F+F]'\n rule_str1_2 = 'X->[-FX]+FX'\n rule_str1_3 = 'F->F[+FF][-FF]F[-F][+F]F'\n\n # rule_str2_1 = 'X->F+[[X]-X]-F[-FX]+X'\n rule_str2_1 = 'X->F[+X]F[-X]+X'\n rule_str2_2 = 'F->FF'\n\n self.__rule = self.rule(rule_str1_1)\n self.__rule2_1 = self.rule(rule_str2_1)\n self.__rule2_2 = self.rule(rule_str2_2)\n\n self.isFill = False\n self.caption = 'L-Systems生成树,鼠标点击,观看树的生长'\n\n self.l_system = LSystem([self.__rule], 'F', math.radians(35), self.screen)\n self.l_system.len = 10\n\n class rule: # 内部类\n def __init__(self, _str):\n self.__str = _str\n self.a, self.b = _str.split('->')\n\n def __str__(self):\n return self.__str\n\n def setup(self):\n self.createTextElement('规则:' + str(self.__rule), color=(153, 217, 234))\n self.createTextElement('根:' + 'F', color=(153, 217, 234))\n pass\n\n def doMouseButtonDownEvent(self, Button):\n self.l_system.generate(self.width / 2, self.height)\n # self.createTextElement(self.l_system.getSentence())\n\n\nclass LSystem:\n def __init__(self, rules, axiom, angle, sur):\n self.__axiom = axiom\n self.__rules = rules\n self.__sentence = self.__axiom\n self.__angle = angle\n self.len = 10\n self.painter = Painter(sur)\n\n def generate(self, x, y):\n nextSentence = ''\n for i in range(len(self.__sentence)):\n current = self.__sentence[i]\n found = False\n for j in range(len(self.__rules)):\n if current == self.__rules[j].a:\n found = True\n nextSentence += self.__rules[j].b\n if not found:\n nextSentence += current\n\n self.__sentence = nextSentence\n self.__show(x, y)\n\n def getSentence(self):\n return self.__sentence\n\n def __show(self, x=0, y=0):\n self.painter.resetCurrentMat()\n self.painter.translate(x, y)\n for i in range(len(self.__sentence)):\n current = self.__sentence[i]\n if current == 'F':\n self.painter.Lines([point2(0, 0), point2(0, -self.len)], (255, 255, 255), 1, 0)\n self.painter.translate(0, -self.len)\n elif current == '+':\n self.painter.rotate(self.__angle)\n elif current == '-':\n self.painter.rotate(-self.__angle)\n elif current == '[':\n self.painter.push()\n elif current == ']':\n self.painter.pop()\n\n\n# AnimatedCircle\nclass CircleEle(Circle):\n def __init__(self, x, y):\n super(CircleEle, self).__init__(x, y, 1)\n self.growing = True\n\n def grow(self):\n if self.growing:\n self.r = self.r + 1\n\n def edges(self, width, height):\n return self.x + self.r > width or self.x - self.r < 0 or self.y + self.r > height or self.y - self.r < 0\n\n\nclass AnimatedCircle(Scene):\n def __init__(self, *args):\n super(AnimatedCircle, self).__init__(*args)\n self.__circleLis = list()\n self.useDefaultDraw = False\n self.__total = 100\n\n def setup(self):\n self.caption = \"AnimatedCircle\"\n self.__circleLis.append(CircleEle(230, 350))\n\n def doClockEvent(self, NowClock):\n _c = self.__createCircle()\n _len = len(self.__circleLis)\n if _len < self.__total:\n if _c is not None:\n self.__circleLis.append(_c)\n\n def draw(self):\n for c in self.__circleLis:\n if c.edges(self.width, self.height):\n c.growing = False\n else:\n for oth in self.__circleLis:\n if c != oth:\n _d = vec2(c.x, c.y).dist(vec2(oth.x, oth.y))\n if _d - 2 < c.r + oth.r:\n c.growing = False\n break\n self.Circle(c, (255, 255, 255), 1)\n c.grow()\n\n def __createCircle(self):\n _x = random.randint(0, 800)\n _y = random.randint(0, 600)\n\n _flg_valid = True\n\n for c in self.__circleLis:\n _d = vec2(c.x, c.y).dist(vec2(_x, _y))\n if _d < c.r:\n _flg_valid = False\n break\n\n if _flg_valid:\n return CircleEle(_x, _y)\n else:\n return None\n\n\n#\nclass FollowMouseScene(Scene):\n def __init__(self, *args):\n super(FollowMouseScene, self).__init__(*args)\n self.__littleCircle = Circle(self.width / 2, self.height / 2, 20)\n self.__bigCircle = Circle(self.width / 2, self.height / 2, 100)\n\n def draw(self):\n self.Circle(self.__bigCircle, (255, 255, 255), 1)\n self.Circle(self.__littleCircle, (255, 255, 255), 1)\n\n def doClockEvent(self, NowClock):\n self.__littleCircle.x, self.__littleCircle.y = self.mouseX, self.mouseY\n\n" }, { "alpha_fraction": 0.5168024301528931, "alphanum_fraction": 0.545315682888031, "avg_line_length": 30.370607376098633, "blob_id": "916fdc6e85ecc87bc30dfb6bc5b6ed7ce05ac6bb", "content_id": "46f257a085b108c7fae8f3ac181e6e74c8cc2659", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9908, "license_type": "no_license", "max_line_length": 102, "num_lines": 313, "path": "/source/examples/physicsTest.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import math\nimport random\nimport pygame\n\nfrom source.core.assembly.IOEvent import IOEvent3, ioEvent3Enum\nfrom source.core.math.MathConst import PI_HALF\nfrom source.core.math.Shape import Rectangle\nfrom source.core.math.Vector import vec2, vec3\nfrom source.core.math.MathUtil import constrain\nfrom source.util.ToolsFuc import exKey\nfrom source.view.baseClazz.Scene import Scene\nfrom source.view.element.Elements import ImgElement\n\n\nclass Mover:\n def __init__(self, location, constraintScope, mass=None):\n self.location = location\n self.velocity = vec2()\n self.acceleration = vec2()\n self.constraintScope = constraintScope\n self.mass = mass\n if self.mass is None:\n self.mass = random.randint(1, 10)\n\n def display(self, screen):\n loc = int(self.location.x), int(self.location.y)\n pygame.draw.circle(screen, (0, 255, 0), loc, self.mass * 2 + 14, 1)\n\n def applyForce(self, force):\n f = force.mul(1 / self.mass)\n self.acceleration += f\n\n def update(self):\n self.velocity += self.acceleration\n self.location += self.velocity\n self.acceleration = self.acceleration.mul(0)\n\n def edges(self):\n right = self.constraintScope.right()\n bottom = self.constraintScope.bottom()\n left = self.constraintScope.left()\n top = self.constraintScope.top()\n if self.location.x > right:\n self.location.x = right\n self.velocity.x *= -1\n if self.location.y > bottom:\n self.location.y = bottom\n self.velocity.y *= -1\n if self.location.x < left:\n self.location.x = left\n self.velocity.x *= -1\n if self.location.y < top:\n self.location.y = top\n self.velocity.y *= -1\n\n\n# 模拟了重力,以及一般力,鼠标点击场景一下会施加一个平行的风力给小球\n# class PhysicsScene(Scene):\n# def __init__(self, screen, config, clock):\n# super(PhysicsScene, self).__init__(screen, config, clock)\n# self.movers = []\n# for i in range(0, 5):\n# self.movers.append(Mover(vec2(random.randint(0, 800), 300), Rectangle(0, 0, 800, 600)))\n#\n# def draw(self):\n#\n# for m in self.movers:\n# gravity = vec2(0, 0.3)\n# gravity = gravity.mul(m.mass)\n# m.applyForce(gravity)\n#\n#\n# m.update()\n# m.edges()\n# m.display(self.screen)\n#\n# def doMouseButtonDownEvent(self, MousePos, Button):\n# if Button == 1:\n# wind = vec2(0.2, 0)\n# for m in self.movers:\n# m.applyForce(wind)\n\n\n# 阻力与摩擦力\n# class PhysicsScene(Scene):\n# def __init__(self, screen, config, clock):\n# super(PhysicsScene, self).__init__(screen, config, clock)\n# self.mover = Mover(vec2(400, 0), Rectangle(0, 0, 800, 600), 1)\n#\n# def draw(self):\n# gravity = vec2(0, 0.3)\n# gravity = gravity.mul(self.mover.mass)\n# self.mover.applyForce(gravity)\n#\n# self.mover.update()\n# self.mover.edges()\n# self.mover.display(self.screen)\n#\n# def doMouseButtonDownEvent(self, MousePos, Button):\n# if Button == 1:\n# # 阻力\n# drag = self.mover.velocity.copy()\n# drag = drag.normal()\n# c = -4\n# speedSq = drag.len_square()\n# drag = drag.mulNum(c * speedSq)\n# self.mover.applyForce(drag)\n#\n# # 摩擦力\n# # friction = self.mover.velocity.copy()\n# # friction = friction.normal()\n# # c = -0.1\n# # friction = friction.mul(c)\n# # self.mover.applyForce(friction)\n\n\nclass Attractor:\n def __init__(self, location):\n self.location = location\n self.mass = 20\n self.G = 1\n self.dragOffset = vec2()\n self.Events = IOEvent3()\n self.Events.appendEvent(ioEvent3Enum.key_D | ioEvent3Enum.keyDown, lambda: self.__X(True), 0)\n self.Events.appendEvent(ioEvent3Enum.key_A | ioEvent3Enum.keyDown, lambda: self.__X(False), 0)\n\n def __X(self, isAdd):\n if isAdd:\n self.location.x += 1\n else:\n self.location.x -= 10\n\n def attract(self, m):\n force = self.location - m.location\n d = force.len()\n d = constrain(d, 0, 8)\n force = force.normal()\n strength = (self.G * self.mass * m.mass) / (d * d)\n\n return force.mul(strength)\n\n def display(self, screen):\n loc = int(self.location.x), int(self.location.y)\n pygame.draw.circle(screen, (0, 255, 0), loc, self.mass * 2 + 14, 1)\n\n\nclass PhysicsScene(Scene):\n def __init__(self, screen, config, clock):\n super(PhysicsScene, self).__init__(screen, config, clock)\n self.m = Mover(vec2(500, 50), Rectangle(0, 0, 800, 600), 1)\n self.a = Attractor(vec2(400, 300))\n\n def draw(self):\n f = vec2(0.1, 0)\n self.m.applyForce(f)\n\n fa = self.a.attract(self.m)\n self.m.applyForce(fa)\n\n self.m.update()\n # self.a.update()\n\n self.a.display(self.screen)\n self.m.display(self.screen)\n\n def doKeyEvent(self, Key, Mod, Type, Unicode=None):\n self.a.Events.doKeyboardKeyDown(exKey(Key))\n\n\nclass body:\n def __init__(self, m, pos):\n self.vel = vec2()\n self.pos = pos\n self.mass = m\n self.acc = vec2()\n self.new_acc = vec2()\n\n def applyForce(self, force):\n self.new_acc += force.dev(self.mass)\n\n def update(self, dt):\n new_pos = self.pos + self.vel.mul(dt) + self.acc.mul(dt ** 2 * 0.5)\n _vel = self.vel + self.acc.mul(0.5 * dt)\n new_acc = self.new_acc\n self.new_acc = self.new_acc.mul(0)\n new_vel = _vel + new_acc.mul(dt * 0.5)\n self.pos = new_pos\n self.vel = new_vel\n self.acc = new_acc\n\n def edges(self, constraintScope):\n right = constraintScope.right()\n bottom = constraintScope.bottom()\n left = constraintScope.left()\n top = constraintScope.top()\n if self.pos.x > right:\n self.pos.x = right\n self.vel.x *= -0.8\n if self.pos.y > bottom:\n self.pos.y = bottom\n self.vel.y *= -0.8\n if self.pos.x < left:\n self.pos.x = left\n self.vel.x *= -0.8\n if self.pos.y < top:\n self.pos.y = top\n self.vel.y *= -0.8\n\n\nclass verletScene(Scene):\n def __init__(self, *args):\n super(verletScene, self).__init__(*args)\n self.caption = 'VerletSceneTest'\n self.m = body(1, vec2(100, 100))\n\n def setup(self):\n self.m.applyForce(vec2(0, 9.8).mul(self.m.mass))\n\n def doClockEvent(self, NowClock):\n # if self.FPS != 0:\n # self.m.update(0.01)\n self.m.applyForce(vec2(0, 9.8))\n if self.mousePressed:\n self.m.applyForce(vec2(4, 0))\n self.m.update(0.1)\n self.m.edges(Rectangle(0, 0, self.width, self.height))\n\n def draw(self):\n self.Circle((self.m.pos.x, self.m.pos.y, 20), (0, 255, 0), 1)\n self.Lines((self.m.pos, self.m.vel + self.m.pos), (255, 255, 255), 1, 0)\n\n\nclass square:\n def __init__(self, i, area):\n self.ang_vel = 0\n self.vel = vec2()\n self.area = area\n self.acc_a = vec2()\n self.moi = i\n self.acc = vec2()\n self.angle = 0\n self.ang_acc = 0\n self.new_ang_acc = 0\n self.drag = 0.04\n\n def applyForce(self, force):\n v = vec2.fromPoint(self.area.barycenter(), force)\n self.new_ang_acc = 1 / self.moi * v.cross(force)\n # self.new_acc += force.dev(self.mass)\n\n def update(self, dt):\n new_angle = self.angle + self.ang_vel * dt + 0.5 * self.ang_acc * dt * dt\n # new_pos = self.pos + self.vel.mul(dt) + self.acc.mul(dt ** 2 * 0.5)\n _ang_vel = self.ang_vel + 0.5 * self.ang_acc * dt\n # _vel = self.vel + self.acc.mul(0.5 * dt)\n new_ang_acc = self.new_ang_acc\n # new_acc = self.new_acc\n self.new_ang_acc = 0\n # self.new_acc = self.new_acc.mul(0)\n new_ang_vel = _ang_vel + new_ang_acc * 0.5 * dt\n # new_vel = _vel + new_acc.mul(dt * 0.5)\n self.angle = new_angle\n # self.pos = new_pos\n self.ang_vel = new_ang_vel\n self.ang_vel = self.ang_vel * (1 - self.drag)\n # self.vel = new_vel\n self.ang_acc = new_ang_acc\n # self.acc = new_acc\n\n # def edges(self, constraintScope):\n # right = constraintScope.right()\n # bottom = constraintScope.bottom()\n # left = constraintScope.left()\n # top = constraintScope.top()\n # if self.pos.x > right:\n # self.pos.x = right\n # self.vel.x *= -0.8\n # if self.pos.y > bottom:\n # self.pos.y = bottom\n # self.vel.y *= -0.8\n # if self.pos.x < left:\n # self.pos.x = left\n # self.vel.x *= -0.8\n # if self.pos.y < top:\n # self.pos.y = top\n # self.vel.y *= -0.8\n\n\nclass verletSceneRotate(Scene):\n def __init__(self, *args):\n super(verletSceneRotate, self).__init__(*args)\n self.caption = 'VerletSceneRotateTest'\n self.m = square(100, Rectangle(300, 250, 200, 100))\n\n def setup(self):\n self.createTextElement()\n self.m.applyForce(vec2(300, 300))\n self.m.drag = 0\n\n def doClockEvent(self, NowClock):\n self.m.update(0.01)\n if abs(self.m.ang_vel) <= 3:\n self.m.drag = 0\n\n def draw(self):\n self.push()\n self.rotate(400, 300, self.m.angle)\n self.Rect(self.m.area, (255, 255, 255), 1)\n self.pop()\n if self.mousePressed:\n self.m.applyForce(vec2(100, 100))\n self.m.drag = 0.03\n self.getCreatedElement(0).setText(self.m.angle)\n\n" }, { "alpha_fraction": 0.5273010730743408, "alphanum_fraction": 0.538221538066864, "avg_line_length": 31.871795654296875, "blob_id": "3096c8ed8f4e517b169bd8663b5975f9863f66ff", "content_id": "09374ce3716de887954baf0db5734eb84caf26c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1282, "license_type": "no_license", "max_line_length": 84, "num_lines": 39, "path": "/source/core/assembly/CollidedProbe.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "class CollidedProbe:\n @staticmethod\n def execute(act, pas, unitTime):\n if not act.hasCollidedProbe:\n return\n if not pas.hasCollidedProbe:\n return\n\n actV = act.vel.copy()\n pasV = pas.vel.copy()\n\n M = act.mass + pas.mass\n actV_ = (actV.mul(act.mass - pas.mass) + pasV.mul(2 * pas.mass)).dev(M)\n pasV_ = (pasV.mul(pas.mass - act.mass) + actV.mul(2 * act.mass)).dev(M)\n\n actAveV = (actV + actV_).mul(0.5)\n pasAveV = (pasV + pasV_).mul(0.5)\n\n actD = actAveV.mul(1)\n pasD = pasAveV.mul(1)\n\n actD_inv = actD.invert()\n pasD_inv = pasD.invert()\n\n actF_ = actD_inv.mul((0.5 * act.mass * (actV_.dot(actV_) - actV.dot(actV))))\n pasF_ = pasD_inv.mul((0.5 * pas.mass * (pasV_.dot(pasV_) - pasV.dot(pasV))))\n\n if pas.collideArea.bottom() > act.collideArea.top():\n pas.collideArea.y = act.collideArea.top() - pas.collideArea.h\n if pas.collideArea.right() < act.collideArea.left():\n pas.collideArea.x = act.collideArea.left() - pas.collideArea.w\n\n act.applyForce(actF_)\n pas.applyForce(pasF_)\n\n # if act.vel.y < actV.y:\n # act.vel.y = 0\n # if pas.vel.y < pasV.y:\n # pas.vel.y = 0\n" }, { "alpha_fraction": 0.6137512922286987, "alphanum_fraction": 0.6208291053771973, "avg_line_length": 33.068965911865234, "blob_id": "020bdc07a969c37bf006e7c63a95f44365cdddea", "content_id": "4a14c5e8bd8884ec075818cab0b947cc71e2bdb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 989, "license_type": "no_license", "max_line_length": 119, "num_lines": 29, "path": "/source/view/baseClazz/Map.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import pygame\n\nfrom source.core.assembly.A_star import AStarArea\nfrom source.core.math.Shape import Rectangle\n\n\nclass Map2d:\n def __init__(self):\n self.length, self.width = 0, 0\n self.show_length, self.show_width = 0, 0\n self.A_Map = None\n self.__surface = None\n self.isInit = False\n\n def init(self, length, width, show_length, show_width, pathfinding_unit):\n self.width, self.length = width, length\n self.show_length, self.show_width = show_length, show_width\n self.A_Map = AStarArea(Rectangle(0, 0, self.show_length, self.show_width), self.show_length / pathfinding_unit,\n self.show_length / pathfinding_unit)\n self.__surface = pygame.Surface((self.length, self.width)).convert()\n self.isInit = True\n\n def setAstarMap(self, map):\n if not isinstance(map, AStarArea):\n return\n self.A_Map = map\n\n def show(self, surface):\n return self.__surface\n\n" }, { "alpha_fraction": 0.475340873003006, "alphanum_fraction": 0.48680010437965393, "avg_line_length": 33.64321517944336, "blob_id": "be6039b5cefae3dfd9dfa55917321bfc62a8da52", "content_id": "6bcd9c6ab8f4ef46c8a0a2853ea175c6a470a018", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7166, "license_type": "no_license", "max_line_length": 105, "num_lines": 199, "path": "/source/core/assembly/A_star.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.core.exception.SGFpyException import SGFpyException\n\n\nclass CoordinateException(SGFpyException):\n def __init__(self, pos, _str):\n self.pos = pos\n self._str = _str\n\n def __str__(self):\n return \"Coordinate({}, {}) \".format(self.pos[0], self.pos[1]) + self._str\n\n\n# 启发函数\ndef heuristic(a, b):\n return abs(a.i - b.i) + abs(a.j - b.j)\n\n\nclass Spot:\n def __init__(self, i, j):\n self.i = i # 该位置X坐标\n self.j = j # 该位置Y坐标\n self.g = 0 # 从起点到当前位置的距离\n self.h = 0 # 从终点到当前位置距离,需要计算\n self.f = 0 # g + h这是最短路径的依据,g + h最小,则说明该点越在最短路径上\n self.neighbors = [] # 邻居集合,即子节点\n self.previous = None # 父节点,即该位置的上一个位置\n self.wall = False # 是否是无法穿越的位置\n\n def addNeighbors(self, cols, rows, grid):\n i, j = self.i, self.j\n if i < cols - 1:\n self.neighbors.append(grid[i + 1][j])\n if i > 0:\n self.neighbors.append(grid[i - 1][j])\n if j < rows - 1:\n self.neighbors.append(grid[i][j + 1])\n if j > 0:\n self.neighbors.append(grid[i][j - 1])\n if i > 0 and j > 0:\n self.neighbors.append(grid[i - 1][j - 1])\n if i < cols - 1 and j > 0:\n self.neighbors.append(grid[i + 1][j - 1])\n if i > 0 and j < rows - 1:\n self.neighbors.append(grid[i - 1][j + 1])\n if i < cols - 1 and j < rows - 1:\n self.neighbors.append(grid[i + 1][j + 1])\n\n\nclass AStarArea:\n def __init__(self, rect, cols, rows, start=None, end=None):\n self.__grid = []\n self.rect = rect\n self.cols, self.rows = cols, rows\n self.unit_w, self.unit_h = self.rect.w / self.cols, self.rect.h / self.rows\n self.__openSet, self.__closeSet = [], []\n self.start, self.end = None, None\n self.__initArea()\n if start is not None:\n self.start = self.__grid[start[0]][start[1]]\n self.__openSet.append(self.start)\n if end is not None:\n self.end = self.__grid[end[0]][end[1]]\n self.__done = False\n self.__noSolution = False\n self.__resList = []\n self.__wallsMap = []\n\n def __initArea(self):\n self.__grid = [[Spot(i, j) for j in range(self.rows)] for i in range(self.cols)]\n\n for i in range(0, self.cols):\n for j in range(0, self.rows):\n self.__grid[i][j].addNeighbors(self.cols, self.rows, self.__grid)\n\n def addObstacle(self, x, y):\n if self.start is not None or self.end is not None:\n if self.start.i == x and self.start.j == y or self.end.i == x and self.end.j == y:\n raise CoordinateException((x, y), 'Obstacle coordinate should not be startPos or endPos')\n self.__grid[x][y].wall = True\n self.__wallsMap.append((x, y))\n\n def addObstacles(self, pos_list):\n for x, y in pos_list:\n self.addObstacle(x, y)\n\n def addObstacleArea(self, start_x, size_x, start_y, size_y):\n _x, _y = start_x, start_y\n for i in range(0, size_x):\n for j in range(0, size_y):\n self.addObstacle(_x + i, _y + j)\n\n def removeObstacle(self, x, y):\n self.__grid[x][y].wall = False\n self.__wallsMap.remove((x, y))\n\n def removeObstacles(self, pos_list):\n for x, y in pos_list:\n self.removeObstacle(x, y)\n\n def removeObstacleArea(self, start_x, size_x, start_y, size_y):\n _x, _y = start_x, start_y\n for i in range(0, size_x):\n for j in range(0, size_y):\n self.removeObstacle(_x + i, _y + j)\n\n def removeAllObstacles(self):\n for x, y in self.__wallsMap:\n self.__grid[x][y].wall = False\n self.__wallsMap.clear()\n\n def getObstaclesList(self):\n return self.__wallsMap\n\n def refresh(self):\n tempWall = self.__wallsMap\n self.__init__(self.rect, self.cols, self.rows)\n self.__wallsMap = tempWall\n for x, y in self.__wallsMap:\n self.__grid[x][y].wall = True\n\n def setStart(self, start):\n x, y = start[0], start[1]\n if self.__grid[x][y].wall:\n raise CoordinateException((x, y), 'has obstacle')\n self.start = self.__grid[x][y]\n self.__openSet.append(self.start)\n\n def setEnd(self, end):\n x, y = end[0], end[1]\n if self.__grid[x][y].wall:\n raise CoordinateException((x, y), 'has obstacle')\n self.end = self.__grid[x][y]\n\n def run(self):\n while not self.__done:\n if len(self.__openSet) > 0:\n winner = 0\n for i in range(0, len(self.__openSet)):\n if self.__openSet[i].f < self.__openSet[winner].f:\n winner = i\n\n current = self.__openSet[winner]\n\n if current == self.end:\n self.__done = True\n\n if not self.__done:\n self.__openSet.remove(current)\n self.__closeSet.append(current)\n\n neighbors = current.neighbors\n for n in neighbors:\n if n not in self.__closeSet and not n.wall:\n tempG = current.g + 1\n newPath = False\n if n in self.__openSet:\n if tempG < n.g:\n n.g = tempG\n newPath = True\n else:\n n.g = tempG\n newPath = True\n self.__openSet.append(n)\n if newPath:\n # 这里的启发函数是自定义的,用于测定启发点到当前点的距离(也可以理解成消耗资源量)\n n.h = heuristic(n, self.end)\n n.f = n.g + n.h\n n.previous = current\n else:\n self.__noSolution = True\n return []\n\n if not self.__done:\n self.__resList.clear()\n temp = current\n self.__resList.append((temp.i, temp.j))\n while temp is not None and temp.previous:\n self.__resList.append((temp.previous.i, temp.previous.j))\n temp = temp.previous\n else:\n self.__resList.reverse()\n self.__resList.append((self.end.i, self.end.j))\n return self.__resList\n\n# area = AStartArea(Rectangle(0, 0, 500, 500), 10, 10)\n# area.addObstacle(4, 4)\n# area.addObstacles([(5, 5), (3, 3), (6, 5)])\n# area.setStart((0, 0))\n# area.setEnd((9, 9))\n# print(area.run())\n# area.refresh()\n# area.removeAllObstacles()\n# area.setStart((0, 0))\n# area.setEnd((9, 9))\n# print(area.run())\n# area.refresh()\n# area.setStart((0, 0))\n# area.setEnd((9, 9))\n# print(area.run())\n" }, { "alpha_fraction": 0.5427690744400024, "alphanum_fraction": 0.5455946326255798, "avg_line_length": 35.69811248779297, "blob_id": "be930e22bcf45888e1c9c8da16920604df08d0d5", "content_id": "f59f0a52430975fb2df6cfc47c1754aa4845d98b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3893, "license_type": "no_license", "max_line_length": 116, "num_lines": 106, "path": "/source/view/baseClazz/Actor.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import pygame\n\nfrom source.core.math.Shape import Rectangle\n\n\nclass Actor:\n def __init__(self, texture, area=None, physicalBody=None, visual=True, zIndex=0, active=False):\n self.texture = texture\n self.visual = visual\n self.zIndex = zIndex\n self.physicalBody = physicalBody\n self.active = active\n self.area = area\n if self.area is None:\n w = self.texture.get_rect().w\n h = self.texture.get_rect().h\n self.area = Rectangle(0, 0, w, h)\n else:\n self.texture = pygame.transform.scale(self.texture, (self.area.w, self.area.h))\n self.initArea = self.area\n\n def collided(self, othActor):\n if not isinstance(othActor, Actor):\n raise Exception(\"Class '{}' must is a subclass of 'Actor'\".format(othActor))\n return self.area.intersects(othActor.area)\n\n def update(self, *args):\n pass\n\n def draw(self, screen):\n screen.blit(self.texture, self.area.local())\n\n\n# class ActorGroup:\n# def __init__(self, activeArea, *args):\n# self.actors = []\n# for p in args:\n# if not isinstance(p, Actor):\n# raise Exception(\"Class '{}' must is a subclass of 'Actor'\".format(p))\n# self.actors.append(p)\n# if not isinstance(activeArea, Shape):\n# raise Exception(\"Class '{}' must is a subclass of 'Shape'\".format(activeArea))\n# self.activeArea = activeArea\n# self.__activeArea = RectangleRange(activeArea.w / 2, activeArea.h / 2, activeArea.w / 2, activeArea.h / 2)\n# self.__quadTree = QuadTree(self.__activeArea, 4)\n# self.__collideDict = {}\n#\n# def add(self, *actors):\n# for a in actors:\n# if not isinstance(a, Actor):\n# raise Exception(\"Class '{}' must is a subclass of 'Actor'\".format(a))\n# self.actors.append(a)\n#\n# def remove(self, actor):\n# if actor in self.actors:\n# self.actors.remove(actor)\n#\n# def size(self):\n# return len(self.actors)\n#\n# def update(self):\n# self.__quadTree = QuadTree(self.__activeArea, 4)\n# self.__collideDict.clear()\n#\n# for a in self.actors:\n# if not a.frozen:\n# a.update()\n# node = Node(a.collideArea.x, a.collideArea.y, a)\n# self.__quadTree.insert(node)\n#\n# def draw(self, screen):\n# for a in self.actors:\n# if a.visual:\n# a.draw(screen)\n#\n# def getCollideDict(self):\n# for e in self.actors:\n# _list = []\n# _range = RectangleRange(e.collideArea.x, e.collideArea.y, e.collideArea.w * 2, e.collideArea.h * 2)\n# sprites = self.__quadTree.query(_range)\n# for _s in sprites:\n# if e is not _s.data and e.collided(_s.data):\n# _list.append(_s.data)\n# if _list:\n# self.__collideDict[e] = _list\n# return self.__collideDict\n#\n# def getCollideList(self, actor, isDel):\n# _lis = []\n# if not isinstance(actor, ActorGroup):\n# raise Exception(\"Class '{}' must is a subclass of 'Actor'\".format(actor))\n# for a in self.actors:\n# if a.collided(actor):\n# _lis.append(a)\n# if isDel:\n# self.remove(a)\n# return _lis\n#\n# def getCollide_with_Oth(self, oth):\n# raise Exception(\"function 'getCollide_with_Oth' not implemented\")\n# # if not isinstance(oth, ActorGroup):\n# # raise Exception(\"Class '{}' must is a subclass of 'ActorGroup'\".format(oth))\n# # if not self.activeArea.same(oth.activeArea):\n# # temp_new_area = Rectangle()\n# # temp_group = ActorGroup(oth.activeArea, oth.actors)\n# # temp_group.add(self.actors)\n\n\n\n" }, { "alpha_fraction": 0.7419354915618896, "alphanum_fraction": 0.7419354915618896, "avg_line_length": 14.5, "blob_id": "7f6053f8e95d9c4fc451e2bce29e32a46073765b", "content_id": "fb7e4badd853ba94746262b35ecb125bca4cded2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31, "license_type": "no_license", "max_line_length": 21, "num_lines": 2, "path": "/source/core/assembly/ResourceLoader.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "class ResourceLoader:\n pass\n" }, { "alpha_fraction": 0.5223586559295654, "alphanum_fraction": 0.5546084642410278, "avg_line_length": 42.91340637207031, "blob_id": "8c0deb9c17d9dd894fcef360d6cf418ef5ea636c", "content_id": "b8d4e2381f5cdf5a58ab44c62a34c2c935db7eb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15831, "license_type": "no_license", "max_line_length": 120, "num_lines": 358, "path": "/source/view/origin/Scenes.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import pygame\nfrom pygame.sprite import spritecollide\n\nfrom source.core.assembly.IOEvent import ioEvent3Enum\nfrom source.core.math.Vector import vec3\nfrom source.util.ToolsFuc import createSurfaceFromFile, centeredXPos, blankSurface, centeredYPos\nfrom source.view.baseClazz.Scene import Scene\nfrom source.view.baseClazz.Sprite import Sprite, SpriteGroup\nfrom source.view.element.Elements import ImgElement\n\ng_resPath = 'source/view/origin/res/'\n\n\nclass GearSprite(Sprite):\n def __init__(self, image, rect):\n super().__init__(image, rect)\n self._image = self.image\n self.rotate = 0\n self.beginTime = 0\n self.nowTime = 0\n\n def update(self, *args):\n if self.beginTime == 0:\n self.beginTime = args[0]\n self.nowTime = args[0]\n interval = self.nowTime - self.beginTime\n if interval > 10:\n self.rotate += 0.5\n self.beginTime = 0\n self.image = pygame.transform.rotate(self._image, self.rotate)\n self.rect = self.image.get_rect(center=self.rect.center)\n\n\nclass AirShipSprite(Sprite):\n def __init__(self, image, rect):\n super().__init__(image, rect)\n self._image = self.image\n self.vel = 1\n self.max_rectY = self.rect.y + 10\n self.min_rectY = self.rect.y - 10\n self.zIndex = 15\n\n self.beginTime = 0\n self.nowTime = 0\n\n def update(self, *args):\n if self.beginTime == 0:\n self.beginTime = args[0]\n self.nowTime = args[0]\n interval = self.nowTime - self.beginTime\n if interval > 100:\n self.rect.y += self.vel\n if self.rect.y >= self.max_rectY or self.rect.y <= self.min_rectY:\n self.vel = -self.vel\n self.beginTime = 0\n\n\nclass TravellerSprite(Sprite):\n def __init__(self, *args):\n super().__init__(*args)\n self.scale = 0.8\n self.__initImg = self.image\n self.__initRect = self.rect\n self.keyPoint = (\n vec3(self.rect.x, self.rect.y, 225), vec3(625, 642, 240), vec3(680, 620, 180), vec3(740, 610, 100),\n vec3(-999, -999, 0))\n self.zIndex = 21\n self.i = 0\n self.beginTime = 0\n self.nowTime = 0\n\n def update(self, *args):\n if self.beginTime == 0:\n self.beginTime = args[0]\n self.nowTime = args[0]\n interval = self.nowTime - self.beginTime\n if interval > 10000:\n self.i += 1\n if self.i == 5:\n self.i = -1\n self.setRect(self.__initRect)\n self.image = self.__initImg\n self.image.set_alpha(225)\n else:\n temp_scale = 1 if self.i == 0 else self.scale\n self.setRect((self.keyPoint[self.i].x, self.keyPoint[self.i].y, self.rect.w * temp_scale,\n self.rect.h * temp_scale))\n self.image.set_alpha(self.keyPoint[self.i].z)\n self.beginTime = 0\n\n\nclass OptionSprite(Sprite):\n def __init__(self, *args, colorKey=(0, 0, 0), clipSize=(0, 0)):\n super(OptionSprite, self).__init__(*args, isScale=False)\n self.__setup(colorKey, clipSize)\n self.zIndex = 100\n\n def __setup(self, colorKey, clipSize):\n temp = pygame.Surface((self.rect.w, self.rect.h))\n temp.set_colorkey(colorKey)\n temp.blit(self.image, (-clipSize[1], -clipSize[0]))\n self.image = temp\n\n\nclass PenElement(ImgElement):\n def __init__(self, *args):\n super(PenElement, self).__init__(*args)\n self.vel = 6\n self.__initArea = self.area\n self.zIndex = 99\n self.flag_animate = False\n self.beginTime = 0\n self.nowTime = 0\n\n def resort(self):\n self.area = self.__initArea\n self.beginTime = 0\n self.nowTime = 0\n self.flag_animate = False\n\n def update(self, time, dist):\n if self.beginTime == 0:\n self.beginTime = time\n self.nowTime = time\n if self.nowTime - self.beginTime > 100:\n self.area.x += self.vel\n if self.area.x >= dist:\n self.area.x = dist\n\n\nclass ReflectElement(ImgElement):\n def __init__(self, *args):\n super(ReflectElement, self).__init__(*args)\n self.vel = 2\n self.max_rectY = self.area.y + 20\n self.min_rectY = self.area.y - 20\n self.zIndex = 19\n\n self.beginTime = 0\n self.nowTime = 0\n\n def update(self, time):\n if self.beginTime == 0:\n self.beginTime = time\n self.nowTime = time\n interval = self.nowTime - self.beginTime\n if interval > 100:\n self.area.y += self.vel\n if self.area.y >= self.max_rectY or self.area.y <= self.min_rectY:\n self.vel = -self.vel\n self.beginTime = 0\n\n\nclass MaskElement(ImgElement):\n def __init__(self, *args):\n super(MaskElement, self).__init__(*args)\n self.zIndex = 1000\n self.a = 225\n\n self.__beginTime = 0\n self.__nowTime = 0\n\n def update(self, time):\n if self.__beginTime == 0:\n self.__beginTime = time\n self.__nowTime = time\n if self.a >= 0 or self.__nowTime - self.__beginTime > 400:\n self.a -= 8\n if self.a <= 0:\n self.a = 0\n self.active = False\n self.visual = False\n self.zIndex = -999\n self.setAlpha(self.a)\n self.__beginTime = 0\n\n\nclass OriginCGLogo(Scene):\n def __init__(self, *args):\n super(OriginCGLogo, self).__init__(*args)\n # 注册与该场景相关的场景\n from source.config.AppConfig import registerScene\n registerScene(101, OriginTitle)\n self.resPath = {'CG': 'logo.mp4'}\n self.useDefaultDraw = False\n\n def setup(self):\n self.mouseVisible = False\n self.setupSystemConsole = False\n self.resetMouse = True\n self.mouseX, self.mouseY = self.width / 2, self.height / 2\n self.mouseLimited = True\n self.caption = 'FinialSound:Origin 终曲:起源 v1.0.0'\n self.videoPlayer.add('CG', g_resPath + self.resPath['CG'])\n\n def draw(self):\n self.mouseX, self.mouseY = self.width / 2, self.height / 2\n if not self.isReadyToEnd:\n self.videoPlayer.preview('CG')\n self.isReadyToEnd = True\n else:\n # 这里的下一个场景是开场Logo\n self.nextSceneNum = 101\n self.isEnd = True\n\n\nclass OriginLogo(Scene):\n def __init__(self, *args):\n super(OriginLogo, self).__init__(*args)\n # 注册与该场景相关的场景\n from source.config.AppConfig import registerScene\n registerScene(101, OriginTitle)\n self.nextSceneNum = 101\n self.resPath = {'logoText1': 'logo.jpg', 'logoText2': 'logo2.jpg'}\n self.bgSurface = blankSurface((self.width, self.height))\n self.__ele_Logo1 = ImgElement((centeredXPos(self.width, 211), centeredYPos(self.height, 27) - 20, 211, 27),\n g_resPath + self.resPath['logoText1'])\n self.__ele_Logo2 = ImgElement((centeredXPos(self.width, 444), centeredYPos(self.height, 35) - 20, 444, 35),\n g_resPath + self.resPath['logoText2'])\n self.__ele_Logo2.visual = False\n self.__beginTime = 0\n self.__nextTime = 0\n self.__nowTime = 0\n\n def setup(self):\n self.caption = 'FinialSound:Origin 终曲:起源 v1.0.0'\n self.mouseVisible = False\n self.render.open()\n self.render.add(self.__ele_Logo1, self.__ele_Logo2)\n self.render.close()\n\n def doClockEvent(self, NowClock):\n if self.__beginTime == 0:\n self.__beginTime = NowClock\n self.__nowTime = NowClock\n if self.__nowTime - self.__beginTime > 2000:\n if self.__ele_Logo1.visual:\n self.__ele_Logo1.visual = False\n self.__ele_Logo2.visual = True\n self.__beginTime = 0\n else:\n self.isEnd = True\n\n\nclass OriginTitle(Scene):\n def __init__(self, *args):\n super(OriginTitle, self).__init__(*args)\n self.__tempSurf = None\n self.resPath = {'bg_back': 'bg_back.jpg', 'bg_gear': 'bg_gear.png', 'bg_town': 'bg_town.png',\n 'bg_airship': 'bg_airship.png', 'bgm': 'bg_BGM.wav', 'bg_title': 'bg_title.png',\n 'bg_options': 'bg_options.bmp', 'bg_rive': 'bg_rive.png', 'bg_reflect': 'bg_reflect.jpg',\n 'bg_traveller': 'bg_traveller.png', 'bg_bridge': 'bg_bridge.png', 'bg_pen': 'bg_pen.png',\n 'bg_copyright': 'bg_copyright.png', 'bg_penBk': 'bg_pen_bk.png', 'bg_cursor': 'cursor.bmp'}\n self.__ele_mask = MaskElement((0, 0, self.width, self.height))\n\n self.__bgGear_InitImg = pygame.image.load(g_resPath + self.resPath['bg_gear'])\n self.__spr_bgGear = GearSprite(self.__bgGear_InitImg, pygame.Rect(300, 100, 528, 528))\n self.__spr_bgGear.zIndex = 10\n self.__spr_airship0 = AirShipSprite(pygame.image.load(g_resPath + self.resPath['bg_airship']),\n pygame.Rect(250, 45, 166, 153))\n self.__spr_airship1 = AirShipSprite(pygame.image.load(g_resPath + self.resPath['bg_airship']),\n pygame.Rect(100, 70, 83, 77))\n self.__spr_airship1.vel = 2\n self.__spr_airship2 = AirShipSprite(pygame.image.load(g_resPath + self.resPath['bg_airship']),\n pygame.Rect(180, 200, 33, 31))\n self.__spr_airship2.vel = -1\n self.__spr_traveller = TravellerSprite(\n pygame.image.load(g_resPath + self.resPath['bg_traveller']).convert_alpha(), pygame.Rect(540, 660, 93, 47))\n self.__ele_bgTown = ImgElement((0, 0, 1280, 720), g_resPath + self.resPath['bg_town'])\n self.__ele_bgTown.zIndex = 20\n self.__ele_bgBridge = ImgElement((612, self.height - 173, 247, 173), g_resPath + self.resPath['bg_bridge'])\n self.__ele_bgBridge.zIndex = 30\n self.__ele_bgRive = ImgElement((0, 650, 1280, 70), g_resPath + self.resPath['bg_rive'])\n self.__ele_bgRive.zIndex = 18\n self.__ele_bgReflect = ReflectElement((-250, 570, 1280, 184), g_resPath + self.resPath['bg_reflect'], 80)\n self.__ele_bgTitle = ImgElement((centeredXPos(1280, 450) + 40, 240, 450, 80),\n g_resPath + self.resPath['bg_title'])\n self.__ele_bgTitle.zIndex = 100\n self.__ele_bgOptions = ImgElement((centeredXPos(self.width, 88), 320, 88, 109),\n g_resPath + self.resPath['bg_options'])\n # 选项与鼠标精灵##################################################################################\n self.__spr_currentOptList = []\n self.__spr_currentOpt = None\n self.__spr_lastOpt = None\n self.__spr_option1 = OptionSprite(g_resPath + self.resPath['bg_options'],\n (centeredXPos(self.width, 88), 320, 91, 25), clipSize=(0, 0))\n self.__spr_option1.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp,\n lambda: self.__clickOption('mouse_left_key_up: scene_title_option1\\n'), 1)\n self.__spr_option2 = OptionSprite(g_resPath + self.resPath['bg_options'],\n (centeredXPos(self.width, 88), 350, 91, 25), clipSize=(30, 0))\n self.__spr_option2.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp,\n lambda: self.__clickOption('mouse_left_key_up: scene_title_option2\\n'), 1)\n self.__spr_option3 = OptionSprite(g_resPath + self.resPath['bg_options'],\n (centeredXPos(self.width, 88), 380, 91, 25), clipSize=(60, 0))\n self.__spr_option3.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp,\n lambda: self.__clickOption('mouse_left_key_up: scene_title_option3\\n'), 1)\n self.__spr_option4 = OptionSprite(g_resPath + self.resPath['bg_options'],\n (centeredXPos(self.width, 88), 410, 91, 25), clipSize=(90, 0))\n self.__spr_option4.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp,\n lambda: self.__clickOption('mouse_left_key_up: scene_title_option4\\n'), 1)\n self.__sprg_mouse_pot = SpriteGroup(self.screenRect, self.__spr_option1, self.__spr_option2, self.__spr_option3,\n self.__spr_option4)\n self.__ele_bgPenBk = ImgElement((-999, -999, 102, 5),\n g_resPath + self.resPath['bg_penBk'])\n self.__ele_bgPenBk.zIndex = 98\n self.__ele_bgPen = PenElement((self.__ele_bgPenBk.area.x, self.__ele_bgPenBk.area.y, 12, 21),\n g_resPath + self.resPath['bg_pen'])\n self.__ele_bgCopyright = ImgElement((2, self.height - 22, 274, 18), g_resPath + self.resPath['bg_copyright'])\n self.__ele_bgCopyright.zIndex = 999\n\n self.rot = 0\n self.mixer.addSound('wave_bgm', g_resPath + self.resPath['bgm'])\n\n def __clickOption(self, text):\n self.systemConsole.log(text)\n\n def setup(self):\n self.caption = 'FinialSound:Origin 终曲:起源 v1.0.0'\n self.bgSurface = createSurfaceFromFile(g_resPath + self.resPath['bg_back'])\n self.mouseSprite.setImg(g_resPath + self.resPath['bg_cursor'])\n self.mouseSprite.setRect((0, 0, 5, 5))\n self.render.open()\n self.render.add(self.__spr_bgGear, self.__ele_bgTown, self.__spr_airship0,\n self.__spr_airship1, self.__spr_airship2, self.__ele_bgTitle,\n self.__ele_bgRive, self.__ele_bgReflect, self.__spr_traveller,\n self.__ele_bgBridge, self.__ele_bgCopyright, self.__ele_mask,\n self.__spr_option1, self.__spr_option2, self.__spr_option3,\n self.__spr_option4, self.__ele_bgPen, self.__ele_bgPenBk)\n # self.render.add(self.__spr_option1, self.__spr_option2, self.__spr_option3,\n # self.__spr_option4, self.__ele_bgPen, self.__ele_bgPenBk)\n self.render.close()\n self.mixer.playSound('wave_bgm', loops=-1)\n\n def doMouseMotion(self, MouseRel, Buttons):\n if len(self.__spr_currentOptList) > 0 and self.focus != self.__spr_currentOpt:\n self.__spr_currentOpt = self.__spr_currentOptList[0]\n self.__ele_bgPenBk.area.x = self.__spr_currentOpt.rect.x - 2\n self.__ele_bgPenBk.area.y = self.__spr_currentOpt.rect.y + 20\n self.__ele_bgPen.area.x = self.__ele_bgPenBk.area.x - 4\n self.__ele_bgPen.area.y = self.__ele_bgPenBk.area.y - 17\n elif len(self.__spr_currentOptList) == 0:\n self.__ele_bgPenBk.area.x = -999\n self.__ele_bgPenBk.area.y = -999\n self.__ele_bgPen.area.x = -999\n self.__ele_bgPen.area.y = -999\n\n def doClockEvent(self, NowClock):\n self.__ele_mask.update(NowClock)\n self.__spr_bgGear.update(NowClock)\n self.__spr_airship0.update(NowClock)\n self.__spr_airship1.update(NowClock)\n self.__spr_airship2.update(NowClock)\n self.__spr_traveller.update(NowClock)\n self.__ele_bgReflect.update(NowClock)\n self.mouseSprite.update(self.mousePos)\n self.__ele_bgPen.update(NowClock, self.__ele_bgPenBk.area.x + self.__ele_bgPenBk.area.w)\n self.__sprg_mouse_pot.update()\n self.__spr_currentOptList = spritecollide(self.mouseSprite, self.__sprg_mouse_pot, False)\n" }, { "alpha_fraction": 0.8130841255187988, "alphanum_fraction": 0.8140679001808167, "avg_line_length": 40.48979568481445, "blob_id": "fc98284fb644e54ad5cfc5369618a59c597dfbea", "content_id": "db02fb7cc990a1acbfb02e085491b78ad817d323", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2477, "license_type": "no_license", "max_line_length": 101, "num_lines": 49, "path": "/source/config/AppConfig.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "\"\"\"\n这是连接GameApp与Scene的主要媒介:\n\n将要测试的场景类填入SceneMap = {SCENENUM_INIT: [XXX]}\n的“XXX”处,运行程序即可\n\n注意:\\n\nXXX处的场景类必须继承source.view.baseClazz.Scene中的Scene\n如果想测试一些场景,在第一个场景类中注册下一个场景\n\n例子:\\n\nfrom source.config.AppConfig import registerScene\\n\nregisterScene(SCENENUM_TITLE, TitleScene)\n\nSCENENUM_TITLE: int 场景号,上一个场景的nextSceneNum必须和与这个场景号一致,\n两个场景才能连接起来\nTitleScene: className 下一个场景的类名称\n\n切记from...import...不能直接导入在代码头。例子中的两行必须写在一起。\n\"\"\"\nfrom source.core.const.Const import SCENENUM_INIT\n\nfrom source.examples.ActorTest import ActorScene # 物理场景测试\nfrom source.examples.AstartTest import AstartTest # A*寻路图形化演示\nfrom source.examples.CanvasTest import canvasTest, water2d # canvas测试与水纹模拟\nfrom source.examples.RTS_Test import RobotRunScene # Actor与A*结合测试场景\nfrom source.examples.SpringSimulate import SpringSimulateScene, SpringMassSystemTestScene # 弹簧模拟\nfrom source.examples.Sudoku import SudokuGame # 数独的游戏\nfrom source.examples.TestPainter import TestPainterScene # Painter测试\nfrom source.examples.TestPick import pickTest # pick测试\nfrom source.examples.TextAreaTest import TextAreaTest # textArea测试\nfrom source.examples.noiseTest import noiseTestScene, noise1DScene # 噪声测试\nfrom source.examples.physicsTest import PhysicsScene, verletScene, verletSceneRotate # 力学测试场景\nfrom source.examples.reference import drawingBoard, createWave, sketchSphere, chain, paramEquation, \\\n kaleidoscope, snowScene, MandelbrotSet, JuliaSet, IFS, LSystemScene, AnimatedCircle # 范例\nfrom source.examples.testSpriteScene import testSpriteScene, testAnimScene, trueAnimScene # 精灵场景测试\nfrom source.guitools.AnimaEditor import AnimaEditor # GUITools 动画编辑器\nfrom source.view.baseClazz.Scene import Scene # 空场景\nfrom source.view.origin.Scenes import OriginLogo, OriginTitle, OriginCGLogo # 起源\nfrom source.view.scene.Scenes import LogoScene # 正常游戏运行流程入口\n\nSceneMap = {SCENENUM_INIT: [OriginCGLogo]}\n\n\ndef registerScene(sceneNum, sceneClass, paramList=None):\n if paramList is None:\n paramList = []\n vList = [sceneClass] + paramList\n SceneMap[sceneNum] = vList\n" }, { "alpha_fraction": 0.3589065670967102, "alphanum_fraction": 0.5069084763526917, "avg_line_length": 38.370967864990234, "blob_id": "1640db4c55fe7ff7ed2152842ccf740bb4da562d", "content_id": "4d5dd576997c7ce6bb909e5284c11b566ec23c65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26875, "license_type": "no_license", "max_line_length": 115, "num_lines": 682, "path": "/source/core/assembly/IOEvent.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "LEN_MOUSE_EVENT = 13\nLEN_KB_EVENT = 0\n\n\ndef getIOEvent3EnumByAscii(a):\n return 0xC0000 + a - 97\n\n\ndef getAsciiByIOEvent3Enum(key_enum):\n return key_enum - 0xC0000 + 97\n\n\nclass ioEvent3Enum:\n # 鼠标\n mouseIn = 0xA0000\n mouseOut = 0xA0001\n mouseLeftKeyUp = 0xA0002\n mouseLeftKeyDown = 0xA0003\n mouseLeftKeyClick = 0xA0004\n mouseRightKeyUp = 0xA0005\n mouseRightKeyDown = 0xA0006\n mouseRightKeyClick = 0xA0007\n mouseMidKeyUp = 0xA0008\n mouseMidKeyDown = 0xA0009\n mouseMidKeyClick = 0xA000A\n mouseDoubleClick = 0xA000B\n mouseMotion = 0xA000C\n mouseRollUp = 0xA000D\n mouseRollDown = 0xA000E\n\n # 键盘\n keyDown = 0xB1000\n keyDowning = 0xB2000\n keyUp = 0xB3000\n key_a = 0xC0000\n key_b = 0xC0001\n key_c = 0xC0002\n key_d = 0xC0003\n key_e = 0xC0004\n key_f = 0xC0005\n key_g = 0xC0006\n key_h = 0xC0007\n key_i = 0xC0008\n key_j = 0xC0009\n key_k = 0xC000A\n key_l = 0xC000B\n key_m = 0xC000C\n key_n = 0xC000D\n key_o = 0xC000E\n key_p = 0xC000F\n key_q = 0xC0010\n key_r = 0xC0011\n key_s = 0xC0012\n key_t = 0xC0013\n key_u = 0xC0014\n key_v = 0xC0015\n key_w = 0xC0016\n key_x = 0xC0017\n key_y = 0xC0018\n key_z = 0xC0019\n key_0 = 0xC001A\n key_1 = 0xC001B\n key_2 = 0xC001C\n key_3 = 0xC001D\n key_4 = 0xC001E\n key_5 = 0xC001F\n key_6 = 0xC0020\n key_7 = 0xC0021\n key_8 = 0xC0022\n key_9 = 0xC0023\n key_F1 = 0xC0025\n key_F2 = 0xC0026\n key_F3 = 0xC0027\n key_F4 = 0xC0028\n key_F5 = 0xC0029\n key_F6 = 0xC002A\n key_F7 = 0xC002B\n key_F8 = 0xC002C\n key_F9 = 0xC002D\n key_F10 = 0xC002E\n key_F11 = 0xC002F\n key_F12 = 0xC0030\n key_Tab = 0xC0031\n key_CapsLock = 0xC0032\n key_Shift = 0xC0033\n key_Ctrl = 0xC0034\n key_Alt = 0xC0035\n key_Space = 0xC0036\n key_Enter = 0xC0037\n key_Backspace = 0xC0038\n key_Esc = 0xC0039\n key_Delete = 0xC003A\n key_Insert = 0xC003B\n key_Up = 0xC003C\n key_Down = 0xC003D\n key_Left = 0xC003E\n key_Right = 0xC003F\n key_Sym33 = 0xC0061\n key_Sym34 = 0xC0062\n key_Sym35 = 0xC0063\n key_Sym36 = 0xC0064\n key_Sym37 = 0xC0065\n key_Sym38 = 0xC0066\n key_Sym39 = 0xC0067\n key_Sym40 = 0xC0068\n key_Sym41 = 0xC0069\n key_Sym42 = 0xC006A\n key_Sym43 = 0xC006B\n key_Sym44 = 0xC006C\n key_Sym45 = 0xC006D\n key_Sym46 = 0xC006E\n key_Sym47 = 0xC006F\n\n\n# Element处理处理Io事件列表\nclass ElementHadDoEvent:\n def __init__(self):\n self.Key = None\n self.hadDoMouseIn = False\n self.hadDoMouseOut = True\n self.hadDoMouseLeftKeyUp = True\n self.hadDoMouseLeftKeyDown = False\n self.hadDoMouseLeftKeyClick = False\n self.hadDoMouseRightKeyUp = True\n self.hadDoMouseRightKeyDown = False\n self.hadDoMouseRightKeyClick = False\n self.hadDoMouseMidKeyUp = False\n self.hadDoMouseMidKeyDown = False\n self.hadDoMouseMidKeyClick = False\n self.hadDoDoubleClick = False\n self.hadDoKeyboardKeyUp = False\n self.hadDoKeyboardKeyDown = False\n self.hadDoKeyboardKeyDowning = False\n\n\nclass IOEvent:\n def doMouseMotion(self):\n pass\n\n def doMouseIn(self):\n pass\n\n def doMouseOut(self):\n pass\n\n def doMouseLeftKeyUp(self):\n pass\n\n def doMouseLeftKeyDown(self):\n pass\n\n def doMouseLeftKeyClick(self):\n pass\n\n def doMouseRightKeyUp(self):\n pass\n\n def doMouseRightKeyDown(self):\n pass\n\n def doMouseRightKeyClick(self):\n pass\n\n def doMouseMidKeyUp(self):\n pass\n\n def doMouseMidKeyDown(self):\n pass\n\n def doMouseMidKeyClick(self):\n pass\n\n def doDoubleClick(self):\n pass\n\n def doKeyboardKeyUp(self, Key):\n pass\n\n def doKeyboardKeyDown(self, Key):\n pass\n\n def doKeyboardKeyDowning(self, Key):\n pass\n\n\nclass IOEvent2:\n mouseIn = None\n mouseOut = None\n mouseLeftKeyUp = None\n mouseLeftKeyDown = None\n mouseLeftKeyClick = None\n mouseRightKeyUp = None\n mouseRightKeyDown = None\n mouseRightKeyClick = None\n mouseMidKeyUp = None\n mouseMidKeyDown = None\n mouseMidKeyClick = None\n doubleClick = None\n keyboardKeyUp = None\n keyboardKeyDown = None\n keyboardKeyDowning = None\n\n def __init__(self):\n self.mouseIn = []\n self.mouseOut = []\n self.mouseLeftKeyUp = []\n self.mouseLeftKeyDown = []\n self.mouseLeftKeyClick = []\n self.mouseRightKeyUp = []\n self.mouseRightKeyDown = []\n self.mouseRightKeyClick = []\n self.mouseMidKeyUp = []\n self.mouseMidKeyDown = []\n self.mouseMidKeyClick = []\n self.doubleClick = []\n self.keyboardKeyUp = {}\n self.keyboardKeyDown = {}\n self.keyboardKeyDowning = {}\n\n def doMouseMotion(self):\n pass\n\n def doMouseIn(self):\n if len(self.mouseIn) > 0:\n for e in self.mouseIn:\n e()\n\n def doMouseOut(self):\n if len(self.mouseOut) > 0:\n for e in self.mouseOut:\n e()\n\n def doMouseLeftKeyUp(self):\n if len(self.mouseLeftKeyUp) > 0:\n for e in self.mouseLeftKeyUp:\n e()\n\n def doMouseLeftKeyDown(self):\n if len(self.mouseLeftKeyDown) > 0:\n for e in self.mouseLeftKeyDown:\n e()\n\n def doMouseLeftKeyClick(self):\n if len(self.mouseLeftKeyClick) > 0:\n for e in self.mouseLeftKeyClick:\n e()\n\n def doMouseRightKeyUp(self):\n if len(self.mouseRightKeyUp) > 0:\n for e in self.mouseRightKeyUp:\n e()\n\n def doMouseRightKeyDown(self):\n if len(self.mouseRightKeyDown) > 0:\n for e in self.mouseRightKeyDown:\n e()\n\n def doMouseRightKeyClick(self):\n if len(self.mouseRightKeyClick) > 0:\n for e in self.mouseRightKeyClick:\n e()\n\n def doMouseMidKeyUp(self):\n if len(self.mouseMidKeyUp) > 0:\n for e in self.mouseMidKeyUp:\n e()\n\n def doMouseMidKeyDown(self):\n if len(self.mouseMidKeyDown) > 0:\n for e in self.mouseMidKeyDown:\n e()\n\n def doMouseMidKeyClick(self):\n if len(self.mouseMidKeyClick) > 0:\n for e in self.mouseMidKeyClick:\n e()\n\n def doDoubleClick(self):\n if len(self.doubleClick) > 0:\n for e in self.doubleClick:\n e()\n\n def addKeyboardKeyUpEvent(self, Key, fuc):\n if not self.keyboardKeyUp:\n self.keyboardKeyUp[Key] = []\n self.keyboardKeyUp[Key].append(fuc)\n\n def doKeyboardKeyUp(self, Key):\n eventList = self.keyboardKeyUp[Key]\n if len(eventList) > 0:\n for e in eventList:\n e()\n\n def addKeyboardKeyDownEvent(self, Key, fuc):\n if not self.keyboardKeyDown:\n self.keyboardKeyDown[Key] = []\n self.keyboardKeyDown[Key].append(fuc)\n\n def doKeyboardKeyDown(self, Key):\n eventList = self.keyboardKeyDown[Key]\n if len(eventList) > 0:\n for e in eventList:\n e()\n\n def addKeyboardKeyDowningEvent(self, Key, fuc):\n if not self.keyboardKeyDowning:\n self.keyboardKeyDowning[Key] = []\n self.keyboardKeyDowning[Key].append(fuc)\n\n def doKeyboardKeyDowning(self, Key):\n eventList = self.keyboardKeyDowning[Key]\n if len(eventList) > 0:\n for e in eventList:\n e()\n\n\nclass IOEvent3:\n def __init__(self, systemConsole=None):\n self.__Events = {0xA0000: [], 0xA0001: [], 0xA0002: [], 0xA0003: [], 0xA0004: [], 0xA0005: [], 0xA0006: [],\n 0xA0007: [], 0xA0008: [], 0xA0009: [], 0xA000A: [], 0xA000B: [], 0xA000C: [], 0xA000D: [],\n 0xA000E: [],\n 0xB1000: [], 0xB2000: [], 0xB3000: [],\n 0xF1000: [], 0xF2000: [], 0xF3000: [], 0xF1001: [], 0xF2001: [], 0xF3001: [], 0xF1002: [],\n 0xF2002: [], 0xF3002: [], 0xF1003: [], 0xF2003: [], 0xF3003: [], 0xF1004: [], 0xF2004: [],\n 0xF3004: [], 0xF1005: [], 0xF2005: [], 0xF3005: [], 0xF1006: [], 0xF2006: [], 0xF3006: [],\n 0xF1007: [], 0xF2007: [], 0xF3007: [], 0xF1008: [], 0xF2008: [], 0xF3008: [], 0xF1009: [],\n 0xF2009: [], 0xF3009: [], 0xF100A: [], 0xF200A: [], 0xF300A: [], 0xF100B: [], 0xF200B: [],\n 0xF300B: [], 0xF100C: [], 0xF200C: [], 0xF300C: [], 0xF100D: [], 0xF200D: [], 0xF300D: [],\n 0xF100E: [], 0xF200E: [], 0xF300E: [], 0xF100F: [], 0xF200F: [], 0xF300F: [], 0xF1010: [],\n 0xF2010: [], 0xF3010: [], 0xF1011: [], 0xF2011: [], 0xF3011: [], 0xF1012: [], 0xF2012: [],\n 0xF3012: [], 0xF1013: [], 0xF2013: [], 0xF3013: [], 0xF1014: [], 0xF2014: [], 0xF3014: [],\n 0xF1015: [], 0xF2015: [], 0xF3015: [], 0xF1016: [], 0xF2016: [], 0xF3016: [], 0xF1017: [],\n 0xF2017: [], 0xF3017: [], 0xF1018: [], 0xF2018: [], 0xF3018: [], 0xF1019: [], 0xF2019: [],\n 0xF3019: [], 0xF101A: [], 0xF201A: [], 0xF301A: [], 0xF101B: [], 0xF201B: [], 0xF301B: [],\n 0xF101C: [], 0xF201C: [], 0xF301C: [], 0xF101D: [], 0xF201D: [], 0xF301D: [], 0xF101E: [],\n 0xF201E: [], 0xF301E: [], 0xF101F: [], 0xF201F: [], 0xF301F: [], 0xF1020: [], 0xF2020: [],\n 0xF3020: [], 0xF1021: [], 0xF2021: [], 0xF3021: [], 0xF1022: [], 0xF2022: [], 0xF3022: [],\n 0xF1023: [], 0xF2023: [], 0xF3023: [], 0xF1024: [], 0xF2024: [], 0xF3024: [], 0xF1025: [],\n 0xF2025: [], 0xF3025: [], 0xF1026: [], 0xF2026: [], 0xF3026: [], 0xF1027: [], 0xF2027: [],\n 0xF3027: [], 0xF1028: [], 0xF2028: [], 0xF3028: [], 0xF1029: [], 0xF2029: [], 0xF3029: [],\n 0xF102A: [], 0xF202A: [], 0xF302A: [], 0xF102B: [], 0xF202B: [], 0xF302B: [], 0xF102C: [],\n 0xF202C: [], 0xF302C: [], 0xF102D: [], 0xF202D: [], 0xF302D: [], 0xF102E: [], 0xF202E: [],\n 0xF302E: [], 0xF102F: [], 0xF202F: [], 0xF302F: [], 0xF1030: [], 0xF2030: [], 0xF3030: [],\n 0xF1031: [], 0xF2031: [], 0xF3031: [], 0xF1032: [], 0xF2032: [], 0xF3032: [], 0xF1033: [],\n 0xF2033: [], 0xF3033: [], 0xF1034: [], 0xF2034: [], 0xF3034: [], 0xF1035: [], 0xF2035: [],\n 0xF3035: [], 0xF1036: [], 0xF2036: [], 0xF3036: [], 0xF1037: [], 0xF2037: [], 0xF3037: [],\n 0xF1038: [], 0xF2038: [], 0xF3038: [], 0xF1039: [], 0xF2039: [], 0xF3039: [], 0xF103A: [],\n 0xF203A: [], 0xF303A: [], 0xF103B: [], 0xF203B: [], 0xF303B: [], 0xF103C: [], 0xF203C: [],\n 0xF303C: [], 0xF103D: [], 0xF203D: [], 0xF303D: [], 0xF103E: [], 0xF203E: [], 0xF303E: [],\n 0xF103F: [], 0xF203F: [], 0xF303F: [], 0xF1040: [], 0xF2040: [], 0xF3040: [], 0xF1041: [],\n 0xF2041: [], 0xF3041: [], 0xF1042: [], 0xF2042: [], 0xF3042: [], 0xF1043: [], 0xF2043: [],\n 0xF3043: [], 0xF1044: [], 0xF2044: [], 0xF3044: [], 0xF1045: [], 0xF2045: [], 0xF3045: [],\n 0xF1046: [], 0xF2046: [], 0xF3046: [], 0xF1047: [], 0xF2047: [], 0xF3047: [], 0xF1048: [],\n 0xF2048: [], 0xF3048: [], 0xF1049: [], 0xF2049: [], 0xF3049: [], 0xF104A: [], 0xF204A: [],\n 0xF304A: [], 0xF104B: [], 0xF204B: [], 0xF304B: [], 0xF104C: [], 0xF204C: [], 0xF304C: [],\n 0xF104D: [], 0xF204D: [], 0xF304D: [], 0xF104E: [], 0xF204E: [], 0xF304E: [], 0xF104F: [],\n 0xF204F: [], 0xF304F: [], 0xF1050: [], 0xF2050: [], 0xF3050: [], 0xF1051: [], 0xF2051: [],\n 0xF3051: [], 0xF1052: [], 0xF2052: [], 0xF3052: [], 0xF1053: [], 0xF2053: [], 0xF3053: [],\n 0xF1054: [], 0xF2054: [], 0xF3054: [], 0xF1055: [], 0xF2055: [], 0xF3055: [], 0xF1056: [],\n 0xF2056: [], 0xF3056: [], 0xF1057: [], 0xF2057: [], 0xF3057: [], 0xF1058: [], 0xF2058: [],\n 0xF3058: [], 0xF1059: [], 0xF2059: [], 0xF3059: [], 0xF105A: [], 0xF205A: [], 0xF305A: [],\n 0xF105B: [], 0xF205B: [], 0xF305B: [], 0xF105C: [], 0xF205C: [], 0xF305C: [], 0xF105D: [],\n 0xF205D: [], 0xF305D: [], 0xF105E: [], 0xF205E: [], 0xF305E: [], 0xF105F: [], 0xF205F: [],\n 0xF305F: [], 0xF1060: [], 0xF2060: [], 0xF3060: [], 0xF1061: [], 0xF2061: [], 0xF3061: [],\n 0xF1062: [], 0xF2062: [], 0xF3062: [], 0xF1063: [], 0xF2063: [], 0xF3063: [], 0xF1064: [],\n 0xF2064: [], 0xF3064: [], 0xF1065: [], 0xF2065: [], 0xF3065: [], 0xF1066: [], 0xF2066: [],\n 0xF3066: [], 0xF1067: [], 0xF2067: [], 0xF3067: [], 0xF1068: [], 0xF2068: [], 0xF3068: [],\n 0xF1069: [], 0xF2069: [], 0xF3069: [], 0xF106A: [], 0xF206A: [], 0xF306A: [], 0xF106B: [],\n 0xF206B: [], 0xF306B: [], 0xF106C: [], 0xF206C: [], 0xF306C: [], 0xF106D: [], 0xF206D: [],\n 0xF306D: [], 0xF106E: [], 0xF206E: [], 0xF306E: [], 0xF106F: [], 0xF206F: [], 0xF306F: []}\n self.__KVMapping = {}\n self.__console = systemConsole\n\n def appendEvent(self, enumValue, fuc, ID) -> bool:\n if enumValue not in self.__Events.keys():\n return False\n _id = (ID << 6) + enumValue\n if _id in self.__KVMapping.keys():\n return False\n self.__Events[enumValue].append(_id)\n self.__KVMapping[_id] = fuc\n return True\n\n def removeEvent(self, enumValue, ID) -> bool:\n _id = (ID << 6) + enumValue\n if enumValue not in self.__Events.keys():\n return False\n\n _list = self.__Events[enumValue]\n if len(_list) < 1 or _id not in _list:\n return False\n\n self.__KVMapping.pop(_id)\n self.__Events[enumValue].remove(_id)\n return True\n\n def getSize(self):\n return len(self.__KVMapping)\n\n def doEvents(self, enumValue):\n _key = enumValue\n if _key not in self.__Events.keys():\n return\n for e in self.__Events[_key]:\n self.__KVMapping[e]()\n\n def doMouseIn(self):\n for e in self.__Events[0xA0000]:\n self.__KVMapping[e]()\n\n def doMouseOut(self):\n for e in self.__Events[0xA0001]:\n self.__KVMapping[e]()\n\n def doMouseLeftKeyUp(self):\n for e in self.__Events[0xA0002]:\n self.__KVMapping[e]()\n\n def doMouseLeftKeyDown(self):\n for e in self.__Events[0xA0003]:\n self.__KVMapping[e]()\n\n def doMouseLeftKeyClick(self):\n for e in self.__Events[0xA0004]:\n self.__KVMapping[e]()\n\n def doMouseRightKeyUp(self):\n for e in self.__Events[0xA0005]:\n self.__KVMapping[e]()\n\n def doMouseRightKeyDown(self):\n for e in self.__Events[0xA0006]:\n self.__KVMapping[e]()\n\n def doMouseRightKeyClick(self):\n for e in self.__Events[0xA0007]:\n self.__KVMapping[e]()\n\n def doMouseMidKeyUp(self):\n for e in self.__Events[0xA0008]:\n self.__KVMapping[e]()\n\n def doMouseMidKeyDown(self):\n for e in self.__Events[0xA0009]:\n self.__KVMapping[e]()\n\n def doMouseMidKeyClick(self):\n for e in self.__Events[0xA000A]:\n self.__KVMapping[e]()\n\n def doDoubleClick(self):\n for e in self.__Events[0xA000B]:\n self.__KVMapping[e]()\n\n def doMouseMotion(self):\n for e in self.__Events[0xA000C]:\n self.__KVMapping[e]()\n\n def doMouserRollUp(self):\n for e in self.__Events[0xA000D]:\n self.__KVMapping[e]()\n\n def doMouserRollDown(self):\n for e in self.__Events[0xA000E]:\n self.__KVMapping[e]()\n\n def doKeyUp(self, key):\n for e in self.__Events[ioEvent3Enum.keyUp]:\n self.__KVMapping[e](key)\n\n def doKeyboardKeyUp(self, keyEnum):\n _key = keyEnum | ioEvent3Enum.keyUp\n if _key not in self.__Events.keys():\n return\n for e in self.__Events[_key]:\n self.__KVMapping[e]()\n\n def doKeyDown(self, key):\n for e in self.__Events[ioEvent3Enum.keyDown]:\n self.__KVMapping[e](key)\n\n def doKeyboardKeyDown(self, keyEnum):\n _key = keyEnum | ioEvent3Enum.keyDown\n if _key not in self.__Events.keys():\n return\n for e in self.__Events[_key]:\n self.__KVMapping[e]()\n\n def doKeyDowning(self, key):\n for e in self.__Events[ioEvent3Enum.keyDowning]:\n self.__KVMapping[e](key)\n\n def doKeyboardKeyDowning(self, keyEnum):\n _key = keyEnum | ioEvent3Enum.keyDowning\n if _key not in self.__Events.keys():\n return\n for e in self.__Events[_key]:\n self.__KVMapping[e]()\n\n\nclass IOEvent4:\n def __init__(self, systemConsole=None):\n self.__Events = {0xA0000: [], 0xA0001: [], 0xA0002: [], 0xA0003: [], 0xA0004: [], 0xA0005: [], 0xA0006: [],\n 0xA0007: [], 0xA0008: [], 0xA0009: [], 0xA000A: [], 0xA000B: [], 0xA000C: [], 0xA000D: [],\n 0xA000E: [],\n 0xB1000: [], 0xB2000: [], 0xB3000: [],\n 0xF1000: [], 0xF2000: [], 0xF3000: [], 0xF1001: [], 0xF2001: [], 0xF3001: [], 0xF1002: [],\n 0xF2002: [], 0xF3002: [], 0xF1003: [], 0xF2003: [], 0xF3003: [], 0xF1004: [], 0xF2004: [],\n 0xF3004: [], 0xF1005: [], 0xF2005: [], 0xF3005: [], 0xF1006: [], 0xF2006: [], 0xF3006: [],\n 0xF1007: [], 0xF2007: [], 0xF3007: [], 0xF1008: [], 0xF2008: [], 0xF3008: [], 0xF1009: [],\n 0xF2009: [], 0xF3009: [], 0xF100A: [], 0xF200A: [], 0xF300A: [], 0xF100B: [], 0xF200B: [],\n 0xF300B: [], 0xF100C: [], 0xF200C: [], 0xF300C: [], 0xF100D: [], 0xF200D: [], 0xF300D: [],\n 0xF100E: [], 0xF200E: [], 0xF300E: [], 0xF100F: [], 0xF200F: [], 0xF300F: [], 0xF1010: [],\n 0xF2010: [], 0xF3010: [], 0xF1011: [], 0xF2011: [], 0xF3011: [], 0xF1012: [], 0xF2012: [],\n 0xF3012: [], 0xF1013: [], 0xF2013: [], 0xF3013: [], 0xF1014: [], 0xF2014: [], 0xF3014: [],\n 0xF1015: [], 0xF2015: [], 0xF3015: [], 0xF1016: [], 0xF2016: [], 0xF3016: [], 0xF1017: [],\n 0xF2017: [], 0xF3017: [], 0xF1018: [], 0xF2018: [], 0xF3018: [], 0xF1019: [], 0xF2019: [],\n 0xF3019: [], 0xF101A: [], 0xF201A: [], 0xF301A: [], 0xF101B: [], 0xF201B: [], 0xF301B: [],\n 0xF101C: [], 0xF201C: [], 0xF301C: [], 0xF101D: [], 0xF201D: [], 0xF301D: [], 0xF101E: [],\n 0xF201E: [], 0xF301E: [], 0xF101F: [], 0xF201F: [], 0xF301F: [], 0xF1020: [], 0xF2020: [],\n 0xF3020: [], 0xF1021: [], 0xF2021: [], 0xF3021: [], 0xF1022: [], 0xF2022: [], 0xF3022: [],\n 0xF1023: [], 0xF2023: [], 0xF3023: [], 0xF1024: [], 0xF2024: [], 0xF3024: [], 0xF1025: [],\n 0xF2025: [], 0xF3025: [], 0xF1026: [], 0xF2026: [], 0xF3026: [], 0xF1027: [], 0xF2027: [],\n 0xF3027: [], 0xF1028: [], 0xF2028: [], 0xF3028: [], 0xF1029: [], 0xF2029: [], 0xF3029: [],\n 0xF102A: [], 0xF202A: [], 0xF302A: [], 0xF102B: [], 0xF202B: [], 0xF302B: [], 0xF102C: [],\n 0xF202C: [], 0xF302C: [], 0xF102D: [], 0xF202D: [], 0xF302D: [], 0xF102E: [], 0xF202E: [],\n 0xF302E: [], 0xF102F: [], 0xF202F: [], 0xF302F: [], 0xF1030: [], 0xF2030: [], 0xF3030: [],\n 0xF1031: [], 0xF2031: [], 0xF3031: [], 0xF1032: [], 0xF2032: [], 0xF3032: [], 0xF1033: [],\n 0xF2033: [], 0xF3033: [], 0xF1034: [], 0xF2034: [], 0xF3034: [], 0xF1035: [], 0xF2035: [],\n 0xF3035: [], 0xF1036: [], 0xF2036: [], 0xF3036: [], 0xF1037: [], 0xF2037: [], 0xF3037: [],\n 0xF1038: [], 0xF2038: [], 0xF3038: [], 0xF1039: [], 0xF2039: [], 0xF3039: [], 0xF103A: [],\n 0xF203A: [], 0xF303A: [], 0xF103B: [], 0xF203B: [], 0xF303B: [], 0xF103C: [], 0xF203C: [],\n 0xF303C: [], 0xF103D: [], 0xF203D: [], 0xF303D: [], 0xF103E: [], 0xF203E: [], 0xF303E: [],\n 0xF103F: [], 0xF203F: [], 0xF303F: [], 0xF1040: [], 0xF2040: [], 0xF3040: [], 0xF1041: [],\n 0xF2041: [], 0xF3041: [], 0xF1042: [], 0xF2042: [], 0xF3042: [], 0xF1043: [], 0xF2043: [],\n 0xF3043: [], 0xF1044: [], 0xF2044: [], 0xF3044: [], 0xF1045: [], 0xF2045: [], 0xF3045: [],\n 0xF1046: [], 0xF2046: [], 0xF3046: [], 0xF1047: [], 0xF2047: [], 0xF3047: [], 0xF1048: [],\n 0xF2048: [], 0xF3048: [], 0xF1049: [], 0xF2049: [], 0xF3049: [], 0xF104A: [], 0xF204A: [],\n 0xF304A: [], 0xF104B: [], 0xF204B: [], 0xF304B: [], 0xF104C: [], 0xF204C: [], 0xF304C: [],\n 0xF104D: [], 0xF204D: [], 0xF304D: [], 0xF104E: [], 0xF204E: [], 0xF304E: [], 0xF104F: [],\n 0xF204F: [], 0xF304F: [], 0xF1050: [], 0xF2050: [], 0xF3050: [], 0xF1051: [], 0xF2051: [],\n 0xF3051: [], 0xF1052: [], 0xF2052: [], 0xF3052: [], 0xF1053: [], 0xF2053: [], 0xF3053: [],\n 0xF1054: [], 0xF2054: [], 0xF3054: [], 0xF1055: [], 0xF2055: [], 0xF3055: [], 0xF1056: [],\n 0xF2056: [], 0xF3056: [], 0xF1057: [], 0xF2057: [], 0xF3057: [], 0xF1058: [], 0xF2058: [],\n 0xF3058: [], 0xF1059: [], 0xF2059: [], 0xF3059: [], 0xF105A: [], 0xF205A: [], 0xF305A: [],\n 0xF105B: [], 0xF205B: [], 0xF305B: [], 0xF105C: [], 0xF205C: [], 0xF305C: [], 0xF105D: [],\n 0xF205D: [], 0xF305D: [], 0xF105E: [], 0xF205E: [], 0xF305E: [], 0xF105F: [], 0xF205F: [],\n 0xF305F: [], 0xF1060: [], 0xF2060: [], 0xF3060: [], 0xF1061: [], 0xF2061: [], 0xF3061: [],\n 0xF1062: [], 0xF2062: [], 0xF3062: [], 0xF1063: [], 0xF2063: [], 0xF3063: [], 0xF1064: [],\n 0xF2064: [], 0xF3064: [], 0xF1065: [], 0xF2065: [], 0xF3065: [], 0xF1066: [], 0xF2066: [],\n 0xF3066: [], 0xF1067: [], 0xF2067: [], 0xF3067: [], 0xF1068: [], 0xF2068: [], 0xF3068: [],\n 0xF1069: [], 0xF2069: [], 0xF3069: [], 0xF106A: [], 0xF206A: [], 0xF306A: [], 0xF106B: [],\n 0xF206B: [], 0xF306B: [], 0xF106C: [], 0xF206C: [], 0xF306C: [], 0xF106D: [], 0xF206D: [],\n 0xF306D: [], 0xF106E: [], 0xF206E: [], 0xF306E: [], 0xF106F: [], 0xF206F: [], 0xF306F: []}\n self.__KVMapping = {}\n self.__console = systemConsole\n\n def appendEvent(self, enumValue, fuc, ID) -> bool:\n if enumValue not in self.__Events.keys():\n return False\n _id = (ID << 6) + enumValue\n if _id in self.__KVMapping.keys():\n return False\n self.__Events[enumValue].append(_id)\n self.__KVMapping[_id] = fuc\n return True\n\n def removeEvent(self, enumValue, ID) -> bool:\n _id = (ID << 6) + enumValue\n if enumValue not in self.__Events.keys():\n return False\n\n _list = self.__Events[enumValue]\n if len(_list) < 1 or _id not in _list:\n return False\n\n self.__KVMapping.pop(_id)\n self.__Events[enumValue].remove(_id)\n return True\n\n def getSize(self):\n return len(self.__KVMapping)\n\n def doEvents(self, enumValue):\n _key = enumValue\n if _key not in self.__Events.keys():\n return\n for e in self.__Events[_key]:\n self.__KVMapping[e]()\n\n def doMouseIn(self):\n for e in self.__Events[0xA0000]:\n self.__KVMapping[e]()\n\n def doMouseOut(self):\n for e in self.__Events[0xA0001]:\n self.__KVMapping[e]()\n\n def doMouseLeftKeyUp(self):\n for e in self.__Events[0xA0002]:\n self.__KVMapping[e]()\n\n def doMouseLeftKeyDown(self):\n for e in self.__Events[0xA0003]:\n self.__KVMapping[e]()\n\n def doMouseLeftKeyClick(self):\n for e in self.__Events[0xA0004]:\n self.__KVMapping[e]()\n\n def doMouseRightKeyUp(self):\n for e in self.__Events[0xA0005]:\n self.__KVMapping[e]()\n\n def doMouseRightKeyDown(self):\n for e in self.__Events[0xA0006]:\n self.__KVMapping[e]()\n\n def doMouseRightKeyClick(self):\n for e in self.__Events[0xA0007]:\n self.__KVMapping[e]()\n\n def doMouseMidKeyUp(self):\n for e in self.__Events[0xA0008]:\n self.__KVMapping[e]()\n\n def doMouseMidKeyDown(self):\n for e in self.__Events[0xA0009]:\n self.__KVMapping[e]()\n\n def doMouseMidKeyClick(self):\n for e in self.__Events[0xA000A]:\n self.__KVMapping[e]()\n\n def doDoubleClick(self):\n for e in self.__Events[0xA000B]:\n self.__KVMapping[e]()\n\n def doMouseMotion(self):\n for e in self.__Events[0xA000C]:\n self.__KVMapping[e]()\n\n def doMouserRollUp(self):\n for e in self.__Events[0xA000D]:\n self.__KVMapping[e]()\n\n def doMouserRollDown(self):\n for e in self.__Events[0xA000E]:\n self.__KVMapping[e]()\n\n def doKeyUp(self, key):\n for e in self.__Events[ioEvent3Enum.keyUp]:\n self.__KVMapping[e](key)\n\n def doKeyboardKeyUp(self, keyEnum):\n _key = keyEnum | ioEvent3Enum.keyUp\n if _key not in self.__Events.keys():\n return\n for e in self.__Events[_key]:\n self.__KVMapping[e]()\n\n def doKeyDown(self, key):\n for e in self.__Events[ioEvent3Enum.keyDown]:\n self.__KVMapping[e](key)\n\n def doKeyboardKeyDown(self, keyEnum):\n _key = keyEnum | ioEvent3Enum.keyDown\n if _key not in self.__Events.keys():\n return\n for e in self.__Events[_key]:\n self.__KVMapping[e]()\n\n def doKeyDowning(self, key):\n for e in self.__Events[ioEvent3Enum.keyDowning]:\n self.__KVMapping[e](key)\n\n def doKeyboardKeyDowning(self, keyEnum):\n _key = keyEnum | ioEvent3Enum.keyDowning\n if _key not in self.__Events.keys():\n return\n for e in self.__Events[_key]:\n self.__KVMapping[e]()\n" }, { "alpha_fraction": 0.6217552423477173, "alphanum_fraction": 0.6229913234710693, "avg_line_length": 27.89285659790039, "blob_id": "c10cda557aafaadfa7062d93c516f199aa320c7d", "content_id": "0822c57725b0de16d7c168068852ac8aeabc1102", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2042, "license_type": "no_license", "max_line_length": 57, "num_lines": 56, "path": "/source/examples/sceneExample.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.view.scene.Scenes import Scene\n\n\nclass exampleScene(Scene):\n def __init__(self, screen, config):\n super().__init__(screen, config)\n self.isEnd = False\n self.nextSceneNum = 0\n\n print('第一个example场景创建完成')\n\n def draw(self):\n print('这是第一个example场景的draw')\n\n def doMouseMotion(self, MousePos, MouseRel, Buttons):\n print('这是第一个example场景的处理鼠标移动事件')\n print('鼠标位置:', MousePos)\n print('鼠标移动量:', MouseRel)\n print('鼠标的按键状态:', Buttons)\n\n def doMouseButtonDownEvent(self, MousePos, Button):\n print('这是第一个example场景的处理鼠标点击事件')\n print('鼠标位置:', MousePos)\n print('鼠标的按键:', Button)\n\n def doMouseButtonUpEvent(self, MousePos, Button):\n print('这是第一个example场景的处理鼠标松开事件')\n print('鼠标位置:', MousePos)\n print('鼠标的按键:', Button)\n\n\nclass exampleScene2(Scene):\n def __init__(self, screen, config):\n super().__init__(screen, config)\n self.isEnd = False\n self.nextSceneNum = None\n print('第二个example场景创建完成')\n\n def draw(self):\n print('这是第二个example场景的draw')\n\n def doMouseMotion(self, MousePos, MouseRel, Buttons):\n print('这是第二个example场景的处理鼠标移动事件')\n print('鼠标位置:', MousePos)\n print('鼠标移动量:', MouseRel)\n print('鼠标的按键状态:', Buttons)\n\n def doMouseButtonDownEvent(self, MousePos, Button):\n print('这是第二个example场景的处理鼠标点击事件')\n print('鼠标位置:', MousePos)\n print('鼠标的按键:', Button)\n\n def doMouseButtonUpEvent(self, MousePos, Button):\n print('这是第二个example场景的处理鼠标松开事件')\n print('鼠标位置:', MousePos)\n print('鼠标的按键:', Button)\n" }, { "alpha_fraction": 0.523658037185669, "alphanum_fraction": 0.5487077832221985, "avg_line_length": 32.092105865478516, "blob_id": "786d6e7b42194b7e812d2f17388507fbddbcb82a", "content_id": "d804094bf3241f487959ada8e36228d9664c82ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2557, "license_type": "no_license", "max_line_length": 108, "num_lines": 76, "path": "/source/core/component/Constructor.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.core.const.Const import gl_Font\nfrom source.core.math.Vector import vec2\nfrom source.util.ToolsFuc import centeredXPos, centeredYPos, centeredXYPos\nfrom source.view.element.Elements import TextElement\n\n\nclass Constructor:\n \"\"\"Element 生成器,可以生成Element\"\"\"\n nextElementY = 0\n id = 0\n\n TOP, LEFT, RIGHT, BOTTOM = 0, 1, 2, 3\n TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT = 10, 11, 12, 13\n CENTER = 99\n\n __CreatedElementList = list()\n\n def __init__(self, render, rect):\n self.__render = render\n self.__rect = rect\n\n def __getPos(self, x, length, size):\n if x == 0:\n return centeredXPos(self.__rect.w, length), 0\n if x == 1:\n return 0, centeredYPos(self.__rect.h, length)\n if x == 2:\n return self.__rect.w - length, centeredYPos(self.__rect.h, length)\n if x == 3:\n return centeredXPos(self.__rect.w, length), self.__rect.h - size\n if x == 10:\n return 0, 0\n if x == 11:\n return self.__rect.w - length, 0\n if x == 12:\n return 0, self.__rect.h - size\n if x == 13:\n return self.__rect.w - length, self.__rect.h - size\n if x == 99:\n return centeredXYPos(self.__rect.w, length, self.__rect.h, size)\n\n def getCreatedElement(self, index):\n return self.__CreatedElementList[index]\n\n def createTextElement(self, text=\"TextElement\", pos=(0, 0), size=18, length=None, color=(255, 255, 255),\n font=gl_Font, zIndex=999):\n \"\"\"\n\n :param text:\n :param pos: 可以是int型数字代码, 0,上居中\n :param size:\n :param length:\n :param color:\n :param font:\n :param zIndex:\n :return:\n \"\"\"\n if length is None:\n length = len(text) * size\n _top, _left = 0, self.nextElementY\n if isinstance(pos, tuple) or isinstance(pos, list):\n _top, _left = pos[0], self.nextElementY + pos[1]\n elif isinstance(pos, vec2):\n _top, _left = pos.x, self.nextElementY + pos.y\n elif isinstance(pos, int):\n _top, _left = self.__getPos(pos, length, size)\n\n e = TextElement((_top, _left, length * size + 2, size + 2), text, font, size, color, 1)\n e.zIndex = zIndex\n self.__CreatedElementList.append(e)\n self.__render.open()\n self.__render.add(e)\n self.__render.close()\n self.nextElementY += size + 4\n self.id += 1\n return e\n" }, { "alpha_fraction": 0.5461883544921875, "alphanum_fraction": 0.5641255378723145, "avg_line_length": 29.94444465637207, "blob_id": "34f1f4711579a902b9ccc6b0758655db373eb1da", "content_id": "f1a97d2e33afc4a225f1a2bb6e4bdf7bea3f381c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1115, "license_type": "no_license", "max_line_length": 91, "num_lines": 36, "path": "/source/core/physics/Mass.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.core.math.Vector import vec2\n\n\nclass Mass:\n def __init__(self, m):\n self.mass = m\n self.acceleration = vec2()\n self.velocity = vec2()\n self.local = vec2()\n self.__new_acc = vec2()\n\n def reset(self):\n self.acceleration = vec2()\n self.velocity = vec2()\n self.local = vec2()\n\n def applyForce(self, force):\n self.__new_acc += force.dev(self.mass)\n\n def update(self, dt=0.4):\n new_pos = self.local + self.velocity.mul(dt) + self.acceleration.mul(dt ** 2 * 0.5)\n _vel = self.velocity + self.acceleration.mul(0.5 * dt)\n new_acc = self.__new_acc\n self.__new_acc = self.__new_acc.mul(0)\n new_vel = _vel + new_acc.mul(dt * 0.5)\n self.local = new_pos\n self.velocity = new_vel\n self.acceleration = new_acc\n\n # def applyForce(self, force):\n # self.acceleration = force.dev(self.mass)\n #\n # def update(self, dt=1):\n # self.velocity += self.acceleration.mul(dt)\n # self.local += self.velocity.mul(dt)\n # self.acceleration = self.acceleration.mul(0)\n\n" }, { "alpha_fraction": 0.4956386387348175, "alphanum_fraction": 0.5570093393325806, "avg_line_length": 40.14102554321289, "blob_id": "a3d531296bdd3567e22e610d3975b833ba9aa10f", "content_id": "6fe0cc55efa2cf2b00f403576e2e1d46b98246c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3246, "license_type": "no_license", "max_line_length": 115, "num_lines": 78, "path": "/source/examples/CanvasTest.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import pygame\n\nfrom source.core.const.Const import gl_Font\nfrom source.view.baseClazz.Scene import Scene\nfrom source.view.element.Elements import TextElement\n\n\nclass canvasTest(Scene):\n def __init__(self, *args):\n super(canvasTest, self).__init__(*args)\n # self.can = canvas(color(0, 0, 0), vec2(800, 600))\n # self.brush = brush(self.can, (255, 255, 255, 0.5), 1)\n # self.painter = Painter(self.can.surface())\n self.blend = pygame.Surface((300, 300)).convert()\n self.blend.fill((255, 255, 255))\n self.blend.set_alpha(80)\n self.sceneCanvas = pygame.Surface((self.width, self.height))\n self.sceneCanvas.fill((255, 255, 255))\n self.sceneCanvas.set_alpha(100)\n self.__E_FPS = TextElement(pygame.Rect(self.width - 80, 0, 80, 20), 'FPS:', gl_Font, 18, (0, 255, 0), 1)\n\n def draw(self):\n # self.can.fill(color(0, 0, 0))\n # self.brush.drawLine((0, 0), (700, 500))\n # self.painter.Lines([point2(), point2(500, 700)], (255, 255, 255, 100), 1, 0)\n #\n # self.__E_FPS.draw(self.can.surface())\n # self.screen.blit(self.can.surface(), (0, 0))\n self.screen.blit(self.blend, (0, 0))\n self.screen.blit(self.sceneCanvas, (0, 0))\n self.__E_FPS.draw(self.screen)\n\n def doClockEvent(self, NowClock):\n fps = 'FPS:' + str(self.FPS)\n self.__E_FPS.setText(fps)\n\n\nclass water2d(Scene):\n def __init__(self, *args):\n super(water2d, self).__init__(*args)\n self.sceneCanvas = pygame.Surface((200, 200))\n self.cols, self.rows = 200, 200\n self.current = [[0 for i in range(self.cols)] for j in range(self.rows)]\n self.previous = [[0 for i in range(self.cols)] for j in range(self.rows)]\n self.caption = \"波纹模拟 点击屏幕左上角200X200的区域查看效果\"\n # self.background(220, 220, 220)\n self.dampening = 0.9\n # self.previous[100][100] = 255\n\n def draw(self):\n self.sceneCanvas.fill((0, 0, 0))\n for i in range(1, self.rows - 1):\n for j in range(1, self.cols - 1):\n self.current[i][j] = (self.previous[i - 1][j] + self.previous[i + 1][j] + self.previous[i][j - 1] +\n self.previous[i][j + 1]) / 2 - self.current[i][j]\n self.current[i][j] = self.current[i][j] * self.dampening\n gray = self.current[i][j]\n try:\n self.sceneCanvas.set_at((i, j), (round(200 * gray), round(200 * gray), round(200 * gray)))\n except TypeError:\n pass\n # print(gray)\n # print(round(255 * gray), round(255 * gray), round(255 * gray))\n\n self.previous, self.current = self.current, self.previous\n self.screen.blit(self.sceneCanvas, (0, 0))\n\n def doClockEvent(self, NowClock):\n pass\n\n def doMouseButtonDownEvent(self, Button):\n if Button == 1:\n if 0 < self.mouseX < 200 and 0 < self.mouseY < 200:\n self.previous[self.mouseX][self.mouseY] = 255\n\n # def doMouseMotion(self, MouseRel, Buttons):\n # if Buttons eq (1, 0, 0):\n # self.previous[self.mouseX][self.mouseY] = 255\n\n" }, { "alpha_fraction": 0.43109801411628723, "alphanum_fraction": 0.5136330127716064, "avg_line_length": 24.60377311706543, "blob_id": "d699bcbc04bbf6decd5a7a6041d3683100f54c9e", "content_id": "1019dd5b4fbab686eab7002e8f66b9c6e49b920d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1357, "license_type": "no_license", "max_line_length": 115, "num_lines": 53, "path": "/gameApp3d.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import pygame as pg\nfrom pygame.locals import *\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\n\ncubeVertices = ((1, 1, 1), (1, 1, -1), (1, -1, -1), (1, -1, 1), (-1, 1, 1), (-1, -1, -1), (-1, -1, 1), (-1, 1, -1))\ncubeEdges = ((0, 1), (0, 3), (0, 4), (1, 2), (1, 7), (2, 5), (2, 3), (3, 6), (4, 6), (4, 7), (5, 6), (5, 7))\ncubeQuads = ((0, 3, 6, 4), (2, 5, 6, 3), (1, 2, 5, 7), (1, 0, 4, 7), (7, 4, 6, 5), (2, 3, 0, 1))\n\n\ndef wireCube():\n glBegin(GL_LINES)\n for cubeEdge in cubeEdges:\n for cubeVertex in cubeEdge:\n glVertex3fv(cubeVertices[cubeVertex])\n glEnd()\n\n\ndef solidCube():\n glBegin(GL_QUADS)\n for cubeQuad in cubeQuads:\n for cubeVertex in cubeQuad:\n glVertex3fv(cubeVertices[cubeVertex])\n glEnd()\n\n\ndef main():\n pg.init()\n display = (1280, 720)\n # print(pg.DOUBLEBUF | pg.OPENGL)\n pg.display.set_mode(display, 1073741826)\n\n gluPerspective(45, (display[0] / display[1]), 0.1, 50.0)\n\n glTranslatef(0.0, 0.0, -5)\n\n while True:\n for event in pg.event.get():\n if event.type == pg.QUIT:\n pg.quit()\n quit()\n\n glRotatef(1, 0.3, 1, 1)\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n solidCube()\n #wireCube()\n pg.display.flip()\n # pg.time.wait(10)\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5263994932174683, "alphanum_fraction": 0.5419847369194031, "avg_line_length": 27.844036102294922, "blob_id": "ca01cb31de23a32d9879e1c4fd10004258cd86e1", "content_id": "96c26ce71cfa7a84b63b88a0e67a8431bb202e6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3268, "license_type": "no_license", "max_line_length": 111, "num_lines": 109, "path": "/source/core/physics/SpringMassSystem.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.core.math.Vector import vec2\nfrom source.core.physics.Mass import Mass\nfrom source.core.physics.Spring import Spring\n\n\nclass SMSystem:\n LINE, GRID, CROSS, GRID_CROSS = 0, 1, 2, 3\n\n def __init__(self, *args):\n \"\"\"0 质点的数量,1 质点的质量,2 劲度系数K,\n\n 3 弹簧长度,4 弹簧阻力系数,5 重力加速度,\n\n 6 空气阻力,7 地面斥力,8 地面摩擦力阻力,\n\n 9 地面引力,10 地面高度\"\"\"\n\n self.__mod = self.LINE\n\n self.massSum = args[0]\n self.massM = args[1]\n self.K = args[2]\n self.springLength = args[3]\n self.springFriction = args[4]\n self.g = args[5]\n\n self.airFriction = args[6]\n self.groundRepulsion = args[7]\n self.groundFriction = args[8]\n self.groundAbsorption = args[9]\n self.groundHeight = args[10]\n\n self.masses = list()\n self.springs = list()\n self.connections = list()\n\n def __createModel_LINE(self):\n for i in range(self.massSum):\n m = Mass(self.massM)\n m.local = vec2(i * self.springLength, 400)\n self.masses.append(m)\n if i > 0:\n self.springs.append(\n Spring(self.masses[i - 1], self.masses[i], self.K, self.springLength, self.springFriction))\n\n def getLocal(self):\n lis = []\n for m in self.masses:\n lis.append(m.local)\n return lis\n\n def createModel(self):\n if self.__mod == self.LINE:\n self.__createModel_LINE()\n\n def setMod(self, mod):\n self.__mod = mod\n\n def setConnections(self, *args):\n for p in args:\n self.connections.append(p)\n\n def simulate(self, dt=1):\n for i in range(self.massSum):\n self.masses[i].update(dt)\n\n for p in self.connections: # (index, vec2:vel)\n index = p[0]\n pos = p[1].mul(dt)\n if pos.y > self.groundHeight:\n pos.y = self.groundHeight\n p[1].y = 0\n\n self.masses[index].local = pos\n self.masses[index].velocity = p[1]\n\n def getMass(self, index):\n return self.masses[index]\n\n def operate(self, dt=1):\n self.resetMassForce()\n self.execute()\n self.simulate(dt)\n\n def execute(self):\n for i in range(self.massSum - 1):\n self.springs[i].execute()\n\n for i in range(self.massSum):\n self.masses[i].applyForce(self.g.mul(self.masses[i].mass))\n self.masses[i].applyForce(self.masses[i].velocity.negate().mul(self.airFriction))\n\n if self.masses[i].local.y > self.groundHeight:\n v = self.masses[i].velocity\n v.y = 0\n\n self.masses[i].applyForce(v.negate().mul(self.groundFriction))\n v = self.masses[i].velocity\n v.x = 0\n\n if v.y < 0:\n self.masses[i].applyForce(v.negate().mul(self.groundAbsorption))\n\n f = vec2(0, self.groundRepulsion).mul(self.masses[i].local.y - self.groundHeight)\n self.masses[i].applyForce(f)\n\n def resetMassForce(self):\n for i in range(self.massSum):\n self.masses[i].reset()\n" }, { "alpha_fraction": 0.6722221970558167, "alphanum_fraction": 0.6833333373069763, "avg_line_length": 24.714284896850586, "blob_id": "0fc882a421709107af052f1d6e3980a483ebc85c", "content_id": "1c00d0353d8b9a237ddbb116f0937bdc35f161b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 202, "license_type": "no_license", "max_line_length": 54, "num_lines": 7, "path": "/source/view/scene/chapter1-1.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "# 第一章:遥远的理想国度\nfrom source.view.baseClazz.Scene import Scene\n\n\nclass Chapter1(Scene):\n def __init__(self, screen, config):\n super(Chapter1, self).__init__(screen, config)\n" }, { "alpha_fraction": 0.5587611198425293, "alphanum_fraction": 0.5710648894309998, "avg_line_length": 33.661766052246094, "blob_id": "b2c2e9072a1c5ac652eba5fff5eb5fb596190f8e", "content_id": "e067006742595a002fd759a08d131b16504307ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4714, "license_type": "no_license", "max_line_length": 115, "num_lines": 136, "path": "/source/core/assembly/PhysicalBody.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.core.assembly.CollidedProbe import CollidedProbe\nfrom source.core.dataStructure.QuadTree import RectangleRange, QuadTree, Node\nfrom source.core.math.Vector import vec2\nfrom source.core.math.Shape import Shape\n\n\nclass BodyType:\n DYNAMIC = 0xA0001\n STATIC = 0xA0002\n\n RIGIDBODY = 0xB0001\n ELASTOMER = 0xB0002\n\n\nclass physicalBody:\n def __init__(self, mass=0, pos=vec2()):\n self.mass = mass\n self.vel = vec2()\n self.acc = vec2()\n self.pos = pos\n self.bodyType = 0\n self.drag = vec2()\n self.angularDrag = vec2()\n self.active = True\n self.isCollideChecked = False\n self.hasCollidedProbe = False\n\n def update(self, restrictedArea, unitTime):\n pass\n\n\nclass physicalScene:\n def __init__(self, activeArea, gravityAc, initTime):\n self.__bodies = []\n\n if not isinstance(activeArea, Shape):\n raise Exception(\"Class '{}' must is a subclass of 'Shape::Shape'\".format(activeArea))\n self.activeArea = activeArea\n\n if not isinstance(gravityAc, vec2):\n raise Exception(\"Class '{}' must is a subclass of 'Math2D::vec2'\".format(gravityAc))\n self.gravityAc = gravityAc\n\n self.__right = self.activeArea.right()\n self.__bottom = self.activeArea.bottom()\n self.__left = self.activeArea.left()\n self.__top = self.activeArea.top()\n\n self.__initTime = initTime\n self.__unitTime = 4 # 0.0033sce\n self.__interval = 0\n\n self.__collidedProbe = CollidedProbe()\n\n self.__activeRange = RectangleRange(activeArea.w / 2, activeArea.h / 2, activeArea.w / 2, activeArea.h / 2)\n self.__quadTree = QuadTree(self.__activeRange, 4)\n\n def add(self, *args):\n for a in args:\n if not isinstance(a, physicalBody):\n raise Exception(\"Class '{}' must is a subclass of 'Actor'\".format(a))\n self.__bodies.append(a)\n\n def remove(self, e):\n if e in self.__bodies:\n self.__bodies.remove(e)\n\n def size(self):\n return len(self.__bodies)\n\n def update(self, nowTime):\n\n self.__initTime = nowTime\n self.__quadTree = QuadTree(self.__activeRange, 4)\n\n for a in self.__bodies:\n if a.active:\n gravity = self.gravityAc.mul(a.mass)\n a.applyForce(gravity)\n a.update(self.activeArea, self.__unitTime)\n if a.collideArea.right() > self.__right:\n a.collideArea.x = self.__right - a.collideArea.w\n a.vel.x *= -a.restitution\n if a.collideArea.bottom() > self.__bottom:\n a.collideArea.y = self.__bottom - a.collideArea.h\n a.vel.y *= -a.restitution\n if a.collideArea.left() < self.__left:\n a.collideArea.x = self.__left\n a.vel.x *= -a.restitution\n if a.collideArea.top() < self.__top:\n a.collideArea.y = self.__top\n a.vel.y *= -a.restitution\n a.isCollideChecked = False\n node = Node(a.collideArea.x, a.collideArea.y, a)\n self.__quadTree.insert(node)\n\n for e in self.__bodies:\n sprites = self.__quadTree.query(\n RectangleRange(e.collideArea.x, e.collideArea.y, e.collideArea.w, e.collideArea.h))\n for _s in sprites:\n if e is not _s.data and e.collided(_s.data):\n if e.hasCollidedProbe and not e.isCollideChecked:\n self.__collidedProbe.execute(e, _s.data, self.__unitTime)\n e.isCollideChecked = True\n _s.data.isCollideChecked = True\n\n\nclass rigidBody(physicalBody):\n def __init__(self, mass, collideArea, _type):\n super(rigidBody, self).__init__(mass, collideArea.barycenter())\n self.bodyType = BodyType.RIGIDBODY | _type\n self.collideArea = collideArea\n self.density = 1\n self.friction = 0.1\n self.restitution = 1\n\n def applyForce(self, force):\n f = force.mul(1 / self.mass)\n self.acc += f\n\n def dis_bary(self):\n x1 = self.collideArea.right() - self.pos.x\n x2 = self.pos.x - self.collideArea.left()\n y1 = self.collideArea.bottom() - self.pos.y\n y2 = self.pos.y - self.collideArea.top()\n return x1, x2, y1, y2\n\n def collided(self, oth):\n return self.collideArea.intersects(oth.collideArea)\n\n def update(self, restrictedArea, unitTime):\n self.vel += self.acc\n self.pos += self.vel\n self.acc = self.acc.mul(0)\n\n self.collideArea.rebuildForBarycenter(self.pos)\n" }, { "alpha_fraction": 0.6164717078208923, "alphanum_fraction": 0.6224613785743713, "avg_line_length": 35.71821212768555, "blob_id": "690ec9cf8a2b4b147d01ef14b78df96b949d2973", "content_id": "45516f023423c9c2e47a850b2143fba2b7ea7f68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10915, "license_type": "no_license", "max_line_length": 103, "num_lines": 291, "path": "/source/view/baseClazz/Scene.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import math\nfrom operator import eq\n\nfrom source.core.assembly.IOEvent import getIOEvent3EnumByAscii\nfrom source.core.assembly.Painter import Painter\nfrom source.core.assembly.container import MiniQueue\nfrom source.core.component.Console import Console\nfrom source.core.component.Constructor import Constructor\nfrom source.core.component.VideoPlayer import VideoPlay\nfrom source.core.render.GameObjRender import gameObjRender\nfrom source.util.ToolsFuc import InElement\nfrom source.view.baseClazz.Element import Element\nfrom source.view.sprite.Sprites import CursorSprite\n\n\nclass Scene(Constructor, Painter):\n def __init__(self, *args):\n self.screen = args[0]\n self.config = args[1]\n self.config.readConfig()\n self.startClock = args[2]\n self.mixer = args[3]\n self.systemConsole = args[4]\n self.paramList = []\n if isinstance(args[-1], list):\n self.paramList = args[-1]\n\n self.caption = None\n self.width = self.screen.get_width()\n self.height = self.screen.get_height()\n self.screenRect = self.screen.get_rect()\n self.screenSize = (self.width, self.height)\n self.FPS = 0.0\n\n self.isReadyToEnter = False\n self.isEnter = False\n self.isEnd = False\n self.isReadyToEnd = False\n self.nextSceneNum = -1\n\n self.isFill = True\n self.fillColor = (0, 0, 0)\n self.frameCount = 0\n\n self.bgSurface = None\n self.bgSurfacePos = (0, 0)\n\n self.mousePos = (0, 0)\n self.lastMousePos = (0, 0)\n self.mouseX, self.mouseY = 0, 0\n self.focus = Element((0, 0, 0, 0))\n self.lastFocus = self.focus\n self.mouseVisible = True\n self.mouseLimited = False\n self.mousePressed = False\n self.keyPressed = False\n self.resetMouse = False\n\n self.useDefaultSetup = True\n self.useDefaultDraw = True\n self.useDefaultMouseHeading = True\n self.useDefaultKeyHeading = True\n self.useDefaultClock = True\n\n self.letDefaultDrawLast = False\n\n self.setupSystemConsole = True\n self.__recordMouseZIndexBeforeSystemConsoleShow = 0\n self.mouseSprite = CursorSprite()\n\n self.__focus_onClick = 0\n\n # 数据容器\n self.keyboardEventQueue = MiniQueue(1000)\n self.systemConsole.msgQueue = self.keyboardEventQueue\n\n self.render = gameObjRender()\n self.videoPlayer = VideoPlay()\n\n Constructor.__init__(self, self.render, self.screen.get_rect())\n Painter.__init__(self, self.screen)\n\n # 默认的处理函数,由useDefault开头的变量控制要不要启用\n # 默认为开启\n\n def __setup(self):\n self.render.add(self.mouseSprite)\n if self.setupSystemConsole:\n self.render.add(self.systemConsole)\n self.render.close()\n\n def __draw(self):\n self.render.render(self.screen)\n\n def __doMouseMotive(self, MouseRel, Buttons):\n for e in self.render.eventHandingList():\n if not e.active:\n continue\n if InElement(self.mousePos, e):\n if isinstance(e, Element):\n e.mouseLastPos = (self.lastMousePos[0] - e.area.x, self.lastMousePos[1] - e.area.y)\n e.mousePos = (self.mouseX - e.area.x, self.mouseY - e.area.y)\n e.mouseButtons = Buttons\n e.mouseRel = MouseRel\n if InElement(self.lastMousePos, e):\n e.Events.doMouseMotion()\n\n if self.focus != e:\n self.lastFocus = self.focus\n # print('失去焦点元素:', self.focus.area, '\\n鼠标位置:', self.mousePos)\n # print('确定焦点元素:', e.area, '\\n鼠标位置:', self.mousePos)\n self.focus = e\n\n if eq(Buttons, (0, 0, 0)) and not self.focus.EventsHadDo.hadDoMouseIn:\n self.focus.Events.doMouseIn()\n self.focus.EventsHadDo.hadDoMouseIn = True\n self.focus.EventsHadDo.hadDoMouseOut = False\n break\n\n if not InElement(self.mousePos, self.focus):\n self.lastFocus = self.focus\n self.focus = Element((0, 0, 0, 0))\n self.__focus_onClick = 0\n\n if self.lastFocus.EventsHadDo.hadDoMouseIn:\n self.lastFocus.Events.doMouseOut()\n self.lastFocus.EventsHadDo.hadDoMouseOut = True\n self.lastFocus.EventsHadDo.hadDoMouseIn = False\n\n if self.lastFocus.EventsHadDo.hadDoMouseLeftKeyDown:\n self.lastFocus.Events.doMouseLeftKeyUp()\n self.lastFocus.EventsHadDo.hadDoMouseLeftKeyDown = False\n self.lastFocus.EventsHadDo.hadDoMouseLeftKeyUp = True\n\n if self.lastFocus.EventsHadDo.hadDoMouseRightKeyDown:\n self.lastFocus.Events.doMouseRightKeyUp()\n self.lastFocus.EventsHadDo.hadDoMouseRightKeyDown = False\n self.lastFocus.EventsHadDo.hadDoMouseRightKeyUp = True\n\n def __doMouseButtonDownEvent(self, Button):\n if Button == 1: # 鼠标左键\n if InElement(self.mousePos, self.focus) and self.focus.EventsHadDo.hadDoMouseRightKeyUp:\n self.__focus_onClick = 1\n self.focus.Events.doMouseLeftKeyDown()\n self.focus.EventsHadDo.hadDoMouseLeftKeyDown = True\n self.focus.EventsHadDo.hadDoMouseLeftKeyUp = False\n if Button == 2: # 鼠标中键\n if InElement(self.mousePos, self.focus) and self.focus.EventsHadDo.hadDoMouseMidKeyUp:\n self.focus.Events.doMouseMidKeyDown()\n self.focus.EventsHadDo.hadDoMouseMidKeyDown = True\n self.focus.EventsHadDo.hadDoMouseMidKeyUp = False\n if Button == 3: # 鼠标右键键\n if InElement(self.mousePos, self.focus) and self.focus.EventsHadDo.hadDoMouseLeftKeyUp:\n self.focus.Events.doMouseRightKeyDown()\n self.focus.EventsHadDo.hadDoMouseRightKeyDown = True\n self.focus.EventsHadDo.hadDoMouseRightKeyUp = False\n if Button == 4: # 滚轮向上\n if InElement(self.mousePos, self.focus):\n self.focus.Events.doMouserRollUp()\n if Button == 5: # 滚轮向下\n if InElement(self.mousePos, self.focus):\n self.focus.Events.doMouserRollDown()\n\n def __doMouseButtonUpEvent(self, Button):\n if Button == 1: # 鼠标左键\n if InElement(self.mousePos, self.focus) and self.focus.EventsHadDo.hadDoMouseLeftKeyDown:\n self.focus.Events.doMouseLeftKeyUp()\n self.focus.EventsHadDo.hadDoMouseLeftKeyDown = False\n self.focus.EventsHadDo.hadDoMouseLeftKeyUp = True\n if self.__focus_onClick == 1: # click 事件\n self.focus.Events.doMouseLeftKeyClick()\n self.focus.EventsHadDo.hadDoMouseLeftKeyClick = True\n self.__focus_onClick = 0\n if Button == 2: # 鼠标中键\n if InElement(self.mousePos, self.focus) and self.focus.EventsHadDo.hadDoMouseMidKeyDown:\n self.focus.Events.doMouseMidKeyUp()\n self.focus.EventsHadDo.hadDoMouseMidKeyDown = False\n self.focus.EventsHadDo.hadDoMouseMidKeyUp = True\n if Button == 3: # 鼠标右键\n if InElement(self.mousePos, self.focus) and self.focus.EventsHadDo.hadDoMouseRightKeyDown:\n self.focus.Events.doMouseRightKeyUp()\n self.focus.EventsHadDo.hadDoMouseRightKeyDown = False\n self.focus.EventsHadDo.hadDoMouseRightKeyUp = True\n\n def __doClockEvent(self, NowClock):\n pass\n\n def __doKeyEvent(self, Key, Mod, Type, Unicode=None):\n if Type == 0: # 按下\n self.focus.Events.doKeyDown(getIOEvent3EnumByAscii(Key))\n if Type == 1: # 松开\n self.focus.Events.doKeyUp(getIOEvent3EnumByAscii(Key))\n\n def __doKeyPressedEvent(self, KeyPressedList):\n pass\n\n # super_开头的是gameApp调用的方法,禁止重写!\n\n def super_setup(self):\n if self.useDefaultSetup:\n self.__setup()\n\n self.setup()\n\n def super_draw(self):\n if self.bgSurface:\n self.screen.blit(self.bgSurface, self.bgSurfacePos)\n if self.letDefaultDrawLast:\n self.draw()\n if self.useDefaultDraw:\n self.__draw()\n if not self.letDefaultDrawLast:\n self.draw()\n\n def super_doMouseMotion(self, MouseRel, Buttons):\n if self.useDefaultMouseHeading:\n self.__doMouseMotive(MouseRel, Buttons)\n\n self.doMouseMotion(MouseRel, Buttons)\n\n def super_doMouseButtonDownEvent(self, Button):\n if self.useDefaultMouseHeading:\n self.__doMouseButtonDownEvent(Button)\n\n self.doMouseButtonDownEvent(Button)\n\n def super_doMouseButtonUpEvent(self, Button):\n if self.useDefaultMouseHeading:\n self.__doMouseButtonUpEvent(Button)\n\n self.doMouseButtonUpEvent(Button)\n\n def super_doClockEvent(self, NowClock):\n if self.useDefaultClock:\n self.__doClockEvent(NowClock)\n\n self.doClockEvent(NowClock)\n\n def super_doKeyEvent(self, Key, Mod, Type, Unicode=None):\n if self.useDefaultKeyHeading:\n self.__doKeyEvent(Key, Mod, Type, Unicode)\n\n if Key == 282 and Type == 0 and Mod == 0:\n visual = self.systemConsole.visual\n active = self.systemConsole.active\n if not visual and not active:\n self.__recordMouseZIndexBeforeSystemConsoleShow = self.mouseSprite.zIndex\n self.mouseSprite.zIndex = self.systemConsole.zIndex\n if visual and active:\n self.mouseSprite.zIndex = self.__recordMouseZIndexBeforeSystemConsoleShow\n self.systemConsole.visual = not self.systemConsole.visual\n self.systemConsole.active = not self.systemConsole.active\n self.focus = self.systemConsole\n\n if Type == 2:\n self.keyPressed = True\n else:\n self.keyPressed = False\n self.doKeyEvent(Key, Mod, Type, Unicode)\n\n def super_doKeyPressedEvent(self, KeyPressedList):\n if self.useDefaultKeyHeading:\n self.__doKeyPressedEvent(KeyPressedList)\n self.keyPressed = True\n self.doKeyPressedEvent(KeyPressedList)\n\n # 可以重写的方法\n\n def setup(self):\n pass\n\n def draw(self):\n pass\n\n def doMouseMotion(self, MouseRel, Buttons):\n pass\n\n def doMouseButtonDownEvent(self, Button):\n pass\n\n def doMouseButtonUpEvent(self, Button):\n pass\n\n def doKeyEvent(self, Key, Mod, Type, Unicode):\n pass\n\n def doKeyPressedEvent(self, KeyPressedList):\n pass\n\n def doClockEvent(self, NowClock):\n pass\n" }, { "alpha_fraction": 0.28626543283462524, "alphanum_fraction": 0.4367283880710602, "avg_line_length": 26.5744686126709, "blob_id": "2dd0176764142af62e243bda37158ac3d5ae640e", "content_id": "3791b78e41ff087433411bb23f381a317a697542", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1306, "license_type": "no_license", "max_line_length": 89, "num_lines": 47, "path": "/source/core/math/Random.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "# 梅森旋转法\ndef _int32(x):\n return int(0xFFFFFFFF & x)\n\n\ndef MT19937Random(seed):\n mt = [0] * 624\n mt[0] = seed\n for i in range(1, 624):\n mt[i] = _int32(1812433253 * (mt[i - 1] ^ mt[i - 1] >> 30) + i)\n\n for i in range(0, 624):\n y = _int32((mt[i] & 0x80000000) + (mt[(i + 1) % 624] & 0x7fffffff))\n mt[i] = y ^ mt[(i + 397) % 624] >> 1\n if y % 2 != 0:\n mt[i] = mt[i] ^ 0x9908b0df\n\n y = mt[0]\n y = y ^ y >> 11\n y = y ^ y << 7 & 2636928640\n y = y ^ y << 15 & 4022730752\n y = y ^ y >> 18\n return _int32(y)\n\n\nclass MT19937:\n def __init__(self, seed):\n self.mt = [0] * 624\n self.mt[0] = seed\n for i in range(1, 624):\n self.mt[i] = _int32(1812433253 * (self.mt[i - 1] ^ self.mt[i - 1] >> 30) + i)\n\n def extract_number(self):\n self.twist()\n y = self.mt[0]\n y = y ^ y >> 11\n y = y ^ y << 7 & 2636928640\n y = y ^ y << 15 & 4022730752\n y = y ^ y >> 18\n return _int32(y)\n\n def twist(self):\n for i in range(0, 624):\n y = _int32((self.mt[i] & 0x80000000) + (self.mt[(i + 1) % 624] & 0x7fffffff))\n self.mt[i] = y ^ self.mt[(i + 397) % 624] >> 1\n if y % 2 != 0:\n self.mt[i] = self.mt[i] ^ 0x9908b0df\n" }, { "alpha_fraction": 0.49368366599082947, "alphanum_fraction": 0.49722081422805786, "avg_line_length": 25.386667251586914, "blob_id": "d8a7aca024c46ed5b00e63041a542de143b36e90", "content_id": "58abc717fd3990045ae66e44566387f0825bab03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1991, "license_type": "no_license", "max_line_length": 100, "num_lines": 75, "path": "/source/core/assembly/AssetsFile.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "class AssetsType:\n SUB = 0\n COM = 1\n EXP = 2\n\n\nclass fileChunk:\n def __init__(self, path, name, file, _type=None):\n self.path = path\n self.name = name\n self.file = file\n self.type = _type\n\n\nclass AssetsFile:\n \"\"\"_path 所在目录\"\"\"\n\n def __init__(self, _path):\n self.__pa = _path\n self.__fs = []\n self.__fdct = {}\n self.__execute()\n\n def __readAll(self):\n import os\n files = os.listdir(self.__pa)\n _str = 'r'\n for fn in files:\n # f = open(os.path.join(self.__pa, fn), _str, encoding='utf-8')\n # flag = f.readline()\n # f.seek(0)\n fc = fileChunk(self.__pa, fn, open(os.path.join(self.__pa, fn), _str, encoding='utf-8'))\n self.__fs.append(fc)\n\n def __closeAll(self):\n for fc in self.__fs:\n fc.file.close()\n\n def __execute(self):\n self.__readAll()\n for fc in self.__fs:\n self.__fdct[fc.name] = fc.file.read()\n fc.file.close()\n\n # def __getFileByType(self, _type):\n # _dict = {}\n # for k, v in self.__fdct.items():\n # if v.type == _type:\n # _dict[k] = v\n # return _dict\n\n def __decodeSUB(self, file_name):\n return self.__fdct[file_name].split('\\n')\n\n def __decodeEXP(self, file_name):\n con = self.__fdct[file_name]\n con = con.replace('\\\\n', '\\n')\n return con.split('^^')\n\n def decode(self, file_name, _type):\n if len(self.__fdct) < 1:\n return\n if _type == AssetsType.SUB:\n return self.__decodeSUB(file_name)\n elif _type == AssetsType.COM:\n pass\n elif _type == AssetsType.EXP:\n return self.__decodeEXP(file_name)\n return\n\n\n# f = AssetsFile('F:/练习/PyCharm/PygameTest/data/assets/TitleScene')\n# print(f.decode('T_P.assets'))\n# print(f.decode('T_P_C.assets'))\n# print(f.decode('I_T.assets', AssetsType.EXP))\n" }, { "alpha_fraction": 0.5738786458969116, "alphanum_fraction": 0.5765171647071838, "avg_line_length": 25.13793182373047, "blob_id": "669aaed5b99271b679b7ed0dc310136cd793f71a", "content_id": "ce12fc56a2a6f94b66027d8e3dc05909a131ac12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 758, "license_type": "no_license", "max_line_length": 62, "num_lines": 29, "path": "/source/core/component/VideoPlayer.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from moviepy.audio.fx.volumex import volumex\nfrom moviepy.editor import *\n\n\nclass VideoPlay:\n _instance = None\n\n def __new__(cls, *args, **kwargs):\n if cls._instance is None:\n cls._instance = object.__new__(cls)\n cls.__clipDict = dict()\n return cls._instance\n\n def __init__(self):\n pass\n\n def add(self, strId, path, size=None, volume=None):\n clip = VideoFileClip(path)\n if size:\n clip.resize(size)\n if volume:\n clip = volumex(clip, volume)\n self.__clipDict[strId] = clip\n\n def preview(self, strId, fps=15, isAudio=True):\n self.__clipDict[strId].preview(fps=fps, audio=isAudio)\n\n def show(self, strId):\n self.__clipDict[strId].show()\n" }, { "alpha_fraction": 0.5438756942749023, "alphanum_fraction": 0.5571298003196716, "avg_line_length": 25.361446380615234, "blob_id": "562c2006a93d865e821a2298f7e38970b053d457", "content_id": "8034c931191c7f3ec292d19e1befe9ec8c26cf28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2212, "license_type": "no_license", "max_line_length": 86, "num_lines": 83, "path": "/source/core/dataStructure/TopologicalSort.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from collections import defaultdict\n\n\nclass Node:\n def __init__(self, data=None):\n self.data = data\n self.in_degree = list()\n\n\nclass AOVNet:\n def __init__(self):\n self.__nodes_dict = defaultdict()\n\n def copy(self):\n ret = AOVNet()\n ret.__nodes_dict = self.__nodes_dict\n return ret\n\n def insert(self, _id, node):\n self.__nodes_dict[_id] = node\n\n def add_in_degree(self, _id_root, _id_in_degree):\n if _id_root == _id_in_degree:\n return\n if _id_root not in self.__nodes_dict.keys():\n return\n if _id_in_degree not in self.__nodes_dict.keys():\n return\n self.__nodes_dict[_id_root].in_degree.append(self.__nodes_dict[_id_in_degree])\n\n def remove(self, _id):\n the_node = self.__nodes_dict[_id]\n self.__nodes_dict.pop(_id)\n for node in self.__nodes_dict.values():\n for n in node.in_degree:\n if n == the_node:\n node.in_degree.remove(the_node)\n\n def len(self):\n return len(self.__nodes_dict.keys())\n\n def get_O_in_degree_items(self):\n res_list = list()\n for item in self.__nodes_dict.items():\n if len(item[1].in_degree) == 0:\n res_list.append(item)\n return res_list\n\n\ndef topologicalSort(_AOVNet):\n if not isinstance(_AOVNet, AOVNet):\n return\n if _AOVNet.len() == 0:\n return\n res_list = list()\n while _AOVNet.len() > 0:\n O_list = _AOVNet.get_O_in_degree_items()\n while len(O_list) > 0:\n the_item = O_list.pop()\n res_list.append(the_item[1]) # 测试时可以改为0,以id看结果\n _AOVNet.remove(the_item[0])\n return res_list\n\n\n# aovnet = AOVNet()\n#\n# aovnet.insert(0, Node())\n# aovnet.insert(1, Node())\n# aovnet.insert(2, Node())\n# aovnet.insert(3, Node())\n# aovnet.insert(4, Node())\n# aovnet.insert(5, Node())\n# aovnet.insert(6, Node())\n#\n# aovnet.add_in_degree(2, 0)\n# aovnet.add_in_degree(6, 2)\n# aovnet.add_in_degree(5, 2)\n# aovnet.add_in_degree(3, 1)\n# aovnet.add_in_degree(3, 2)\n# aovnet.add_in_degree(4, 3)\n# aovnet.add_in_degree(5, 4)\n#\n# print((topologicalSort(aovnet.copy())))\n" }, { "alpha_fraction": 0.4626878798007965, "alphanum_fraction": 0.48624417185783386, "avg_line_length": 28.022958755493164, "blob_id": "cf944e99e8d0bd17fa8643124b00c622bdeeb8e7", "content_id": "98bfec8b671e94de7d4d1f4fee474a6a384e7bdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11415, "license_type": "no_license", "max_line_length": 120, "num_lines": 392, "path": "/source/core/math/Vector.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import math\nimport random\n\nfrom source.core.math.MathConst import PI_DOUBLE\n\n\nclass vec2:\n \"\"\"Vector::vec2\\n\n @overwrite: __str__, __add__, __sub__\n \"\"\"\n\n def __init__(self, x=0.0, y=0.0):\n if isinstance(x, tuple) or isinstance(x, list):\n self.__init__(x[0], x[1])\n else:\n self.x = float(x)\n self.y = float(y)\n\n def __str__(self):\n return '<vec2::{}({}, {})>'.format(self.__class__.__name__, self.x, self.y)\n\n def __add__(self, other):\n return vec2(self.x + other.x, self.y + other.y)\n\n def __sub__(self, other):\n return vec2(self.x - other.x, self.y - other.y)\n\n def __getitem__(self, item):\n return self.ary()[item]\n\n def __setitem__(self, key, value):\n if key == 0:\n self.x = value\n elif key == 1:\n self.y = value\n\n @staticmethod\n def fromAngle(angle, length=1):\n return vec2(length * math.cos(angle), length * math.sin(angle))\n\n @staticmethod\n def fromPoint(p1, p2):\n return vec2(p2.x - p1.x, p2.y - p1.y)\n\n @staticmethod\n def random(a=0, b=1):\n return vec2.fromAngle(random.uniform(a, b) * PI_DOUBLE)\n\n @staticmethod\n def lerp_between(v1, v2, amt):\n tar = v1.copy()\n return tar.lerp(v2, amt)\n\n def to_str(self, a=3):\n return '<vec2::({}, {})>'.format(round(self.x, a), round(self.y, a))\n\n def orient(self):\n return math.atan2(self.y, self.x)\n\n def copy(self):\n return vec2(self.x, self.y)\n\n def isZero(self):\n return self.x == 0.0 and self.y == 0.0\n\n def invert(self):\n x, y = 0, 0\n if self.x != 0:\n x = 1 / self.x\n if self.y != 0:\n y = 1 / self.y\n return vec2(x, y)\n\n def negate(self):\n return vec2(-self.x, -self.y)\n\n def same(self, *args) -> bool:\n if len(args) == 1:\n _v = args[0]\n if not isinstance(_v, vec2):\n return False\n return self.x == _v.x and self.y == _v.y\n else:\n if len(args) != 2:\n return False\n _x, _y = args[0], args[1]\n return self.x == _x and self.y == _y\n\n def dist(self, _vec2=None):\n temp_vec2 = _vec2\n if temp_vec2 is None:\n temp_vec2 = vec2()\n return pow(pow((self.x - temp_vec2.x), 2) + pow((self.y - temp_vec2.y), 2), 0.5)\n\n def len_square(self):\n return self.x * self.x + self.y * self.y\n\n def mul(self, num):\n return vec2(self.x * num, self.y * num)\n\n def dev(self, num):\n return vec2(self.x / num, self.y / num)\n\n def len(self):\n return pow(self.len_square(), 0.5)\n\n def setLen(self, length):\n v = self.normal().mul(length)\n self.x, self.y = v.x, v.y\n return self\n\n def dot(self, _vec2):\n return self.x * _vec2.x + self.y * _vec2.y\n\n def cross(self, _vec2):\n return self.x * _vec2.y - self.y * _vec2.x\n\n def normal(self):\n _len = self.len()\n if _len == 0:\n return vec2()\n return vec2(self.x / _len, self.y / _len)\n\n def limit(self, n):\n v = vec2(self.x, self.y)\n len_sq = self.len_square()\n if len_sq > n * n:\n v = v.dev(math.sqrt(len_sq)).mul(n)\n self.x, self.y = v.x, v.y\n return self\n\n def reflect(self, normal):\n normal.normal()\n return self - normal * (2 * self.dot(normal))\n\n def lerp(self, x, y, amt=0):\n if isinstance(x, vec2):\n self.lerp(x.x, x.y, y)\n else:\n self.x += (x - self.x) * amt or 0\n self.y += (y - self.y) * amt or 0\n return self\n\n def angle_cos(self, _vec2):\n return self.dot(_vec2) / (self.len() * _vec2.len())\n\n def angle(self, _vec2):\n return math.acos(min(1, max(-1, self.angle_cos(_vec2))))\n\n def rotate(self, angle):\n return vec2(self.x * math.cos(angle) - self.y * math.sin(angle),\n self.x * math.sin(angle) + self.y * math.cos(angle))\n\n def ary(self, exp=0):\n if exp == 0:\n return self.x, self.y\n if exp == 1:\n return int(self.x), int(self.y)\n\n\nclass point2(vec2):\n def __init__(self, x=0, y=0):\n super(point2, self).__init__(x, y)\n\n def __str__(self):\n return '<point2::{}({}, {})>'.format(self.__class__.__name__, self.x, self.y)\n\n\nclass vec3:\n \"\"\"Vector::vec3\\n\n @overwrite: __str__, __add__, __sub__\n \"\"\"\n\n def __init__(self, x=0.0, y=0.0, z=0.0):\n if isinstance(x, tuple) or isinstance(x, list):\n self.__init__(x[0], x[1], x[2])\n elif isinstance(x, vec2):\n self.__init__(x.x, x.y, y)\n else:\n self.x = float(x)\n self.y = float(y)\n self.z = float(z)\n\n def __str__(self):\n return '<vec3::{}({}, {}, {})>'.format(self.__class__.__name__, self.x, self.y, self.z)\n\n def __add__(self, other):\n return vec3(self.x + other.x, self.y + other.y, self.z + other.z)\n\n def __sub__(self, other):\n return vec3(self.x - other.x, self.y - other.y, self.z - other.z)\n\n def __getitem__(self, item):\n return self.ary()[item]\n\n def __setitem__(self, key, value):\n if key == 0:\n self.x = value\n elif key == 1:\n self.y = value\n elif key == 2:\n self.z = value\n\n @staticmethod\n def fromAngle(theta, phi, length=1):\n \"\"\"theta: number 极角(极坐标, 0,向上)\n\n phi: number 方位角(0, 屏幕外)\n \"\"\"\n cosPhi = math.cos(phi)\n sinPhi = math.sin(phi)\n cosTheta = math.cos(theta)\n sinTheta = math.sin(theta)\n\n return vec3(length * sinTheta * sinPhi, -length * cosTheta, length * sinTheta * cosPhi)\n\n @staticmethod\n def fromPoint(p1, p2):\n return vec3(p2.x - p1.x, p2.y - p1.y, p2.z - p1.z)\n\n @staticmethod\n def random(a=0, b=1):\n angle = random.uniform(a, b) * PI_DOUBLE\n vz = random.uniform(a, b) * 2 - 1\n vzBase = math.sqrt(1 - vz * vz)\n vx = vzBase * math.cos(angle)\n vy = vzBase * math.sin(angle)\n return vec3(vx, vy, vz)\n\n @staticmethod\n def lerp_between(v1, v2, amt):\n tar = v1.copy()\n return tar.lerp(v2, amt)\n\n def to_str(self, a=3):\n return '<vec3::({}, {}, {})>'.format(round(self.x, a), round(self.y, a), round(self.z, a))\n\n def copy(self):\n return vec3(self.x, self.y, self.z)\n\n def isZero(self):\n return self.x == 0.0 and self.y == 0.0 and self.z == 0\n\n def invert(self):\n x, y, z = 0, 0, 0\n if self.x != 0:\n x = 1 / self.x\n if self.y != 0:\n y = 1 / self.y\n if self.z != 0:\n z = 1 / self.z\n return vec3(x, y, z)\n\n def orient(self):\n return math.atan2(self.y, self.x)\n\n def negate(self):\n return vec3(-self.x, -self.y, -self.z)\n\n def same(self, *args) -> bool:\n if len(args) == 1:\n _v = args[0]\n if not isinstance(_v, vec3):\n return False\n return self.x == _v.x and self.y == _v.y and self.z == _v.z\n else:\n if len(args) != 3:\n return False\n _x, _y, _z = args[0], args[1], args[2]\n return self.x == _x and self.y == _y\n\n def dist(self, _vec3=None):\n temp_vec3 = _vec3\n if temp_vec3 is None:\n temp_vec3 = vec3()\n return pow(pow((self.x - temp_vec3.x), 2) + pow((self.y - temp_vec3.y), 2) + pow((self.z - temp_vec3.z), 2),\n 0.5)\n\n def len_square(self):\n return self.x * self.x + self.y * self.y + self.z * self.z\n\n def mul(self, num):\n return vec3(self.x * num, self.y * num, self.z * num)\n\n def dev(self, num):\n return vec3(self.x / num, self.y / num, self.z / num)\n\n def len(self):\n return pow(self.len_square(), 0.5)\n\n def setLen(self, length):\n v = self.normal().mul(length)\n self.x, self.y, self.z = v.x, v.y, v.z\n return self\n\n def dot(self, _vec3):\n return self.x * _vec3.x + self.y * _vec3.y + self.z * _vec3.z\n\n def cross(self, _vec3):\n return vec3(self.y * _vec3.z - self.z * _vec3.y, self.z * _vec3.x - self.x * _vec3.z,\n self.x * _vec3.y - self.y * _vec3.x)\n\n def normal(self):\n _len = self.len()\n if _len == 0:\n return vec3()\n return vec3(self.x / _len, self.y / _len, self.z / _len)\n\n def limit(self, n):\n v = vec3(self.x, self.y, self.z)\n len_sq = self.len_square()\n if len_sq > n * n:\n v = v.dev(math.sqrt(len_sq)).mul(n)\n self.x, self.y, self.z = v.x, v.y, v.z\n return self\n\n def reflect(self, normal):\n normal.normal()\n return self - normal * (2 * self.dot(normal))\n\n def lerp(self, x, y, z, amt=0):\n if isinstance(x, vec3):\n self.lerp(x.x, x.y, x.z, y)\n else:\n self.x += (x - self.x) * amt or 0\n self.y += (y - self.y) * amt or 0\n self.z += (z - self.z) * amt or 0\n return self\n\n def angle_cos(self, _vec3):\n return self.dot(_vec3) / (self.len() * _vec3.len())\n\n def angle(self, _vec2):\n return math.acos(min(1, max(-1, self.angle_cos(_vec2))))\n\n def rotate(self, angle, _vec3):\n \"\"\"_vec3: vec3 旋转向量\"\"\"\n v = self.copy()\n return v.mul(math.cos(angle)) + (1 - math.cos(angle)) * (self.dot(_vec3)) * _vec3 + v.cross(_vec3).mul(\n math.sin(angle))\n\n def ex_vec2(self):\n return vec2(self.x, self.y)\n\n def ary(self, exp=0):\n \"\"\"exp: 0 float xyz, 1 int xyz, 2 float xy, 3 int xy\"\"\"\n if exp == 0:\n return self.x, self.y, self.z\n elif exp == 1:\n return int(self.x), int(self.y), int(self.z)\n elif exp == 3:\n return self.x, self.y\n elif exp == 4:\n return int(self.x), int(self.y)\n\n\nclass vec4:\n def __init__(self, x=0.0, y=0.0, z=0.0, w=0.0):\n if (isinstance(x, tuple) or isinstance(x, list)) and (isinstance(y, tuple) or isinstance(y, list)):\n self.__init__(x[0], x[1], y[0], y[1])\n elif isinstance(x, tuple) or isinstance(x, list):\n self.__init__(x[0], x[1], x[2], x[3])\n elif isinstance(x, vec2) and isinstance(y, vec2):\n self.__init__(x.x, x.y, y.x, y.y)\n elif isinstance(x, vec3):\n self.__init__(x.x, x.y, x.z, y)\n else:\n self.x = float(x)\n self.y = float(y)\n self.z = float(z)\n self.w = float(w)\n\n def __str__(self):\n return '<vec4::({}, {}, {}, {})>'.format(self.x, self.y, self.z, self.w)\n\n def to_str(self, a=3):\n return '<vec4::({}, {}, {}, {})>'.format(round(self.x, a), round(self.y, a), round(self.z, a), round(self.w, a))\n\n def ary(self, exp=0):\n \"\"\"exp: 0 float xyzw, 1 int xyzw, 2 float xy, 3 int xy, 4 float zw, 5 int zw\"\"\"\n if exp == 0:\n return self.x, self.y, self.z, self.w\n elif exp == 1:\n return int(self.x), int(self.y), int(self.z), int(self.w)\n elif exp == 2:\n return self.x, self.y\n elif exp == 3:\n return int(self.x), int(self.y)\n elif exp == 4:\n return self.z, self.w\n elif exp == 5:\n return int(self.z), int(self.w)\n" }, { "alpha_fraction": 0.6684881448745728, "alphanum_fraction": 0.6757741570472717, "avg_line_length": 27.894737243652344, "blob_id": "214c6934267d06b213982a93b41de1a638355add", "content_id": "9f54b4d26341fd3a1dee51ffce5834248d8f5c85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 553, "license_type": "no_license", "max_line_length": 99, "num_lines": 19, "path": "/main.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "# _*_ coding: utf-8 _*_\nimport sys\n\nsys.path.append('F:/Practice/PyCharm/PygameTest/venv/Lib/site-packages/')\n\n\ndef main():\n from source.core.const.Const import gl_WindowWidth, gl_WindowHeight, gl_nextLevelWindowWidth, \\\n gl_nextLevelWindowHeight\n from gameApp import gameApp\n\n # print(os.path.abspath(__file__))\n game = gameApp(\"FinalSound终曲\", gl_nextLevelWindowWidth, gl_nextLevelWindowHeight, False, 0, 32)\n print('syclight_msg_gameapp_id: ' + str(game.getId()))\n game.MainLoop()\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.38571906089782715, "alphanum_fraction": 0.420754075050354, "avg_line_length": 25.060869216918945, "blob_id": "534d3c8b59e13d60636136f18e7a99f39ddab58b", "content_id": "08d273ebb021e06763231a7d26c27afa6f61e38a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2997, "license_type": "no_license", "max_line_length": 61, "num_lines": 115, "path": "/source/core/component/Transform.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import math\n\nfrom source.core.math.Matrix import mat3\nfrom source.core.math.Vector import vec2\n\n\nclass Transform:\n def __init__(self):\n self.__matStack = [mat3()]\n\n def getMatStack(self):\n return self.__matStack.copy()\n\n def getCurrentMat(self):\n return self.__matStack[0].copy()\n\n def push(self):\n mat = self.__matStack[0]\n self.__matStack.insert(0, mat)\n\n def pop(self):\n if len(self.__matStack) > 1:\n self.__matStack.pop(0)\n\n def popAll(self):\n self.__matStack.clear()\n self.__matStack.append(mat3())\n\n def resetCurrentMat(self):\n self.__matStack[0] = mat3()\n\n def resetAll(self):\n for i in range(len(self.__matStack)):\n self.__matStack[i] = mat3()\n\n def scale(self, *args):\n a, b = 1, 1\n x, y = 0, 0\n if len(args) == 1:\n v = args[0]\n if isinstance(v, list) or isinstance(v, tuple):\n a, b = v[0], v[1]\n if isinstance(v, vec2):\n a, b = v.x, v.y\n elif len(args) == 2:\n v = args[0]\n if isinstance(v, vec2):\n x, y = v.x, v.y\n a, b = args[1].x, args[1].y\n elif isinstance(v, list) or isinstance(v, tuple):\n x, y = v[0], v[1]\n a, b = args[1][0], args[1][1]\n else:\n a, b = args[0], args[1]\n elif len(args) == 4:\n x, y, a, b = args[0], args[1], args[2], args[3]\n\n _m = mat3()\n _m.set(0, 0, a)\n _m.set(1, 1, b)\n\n _mR = mat3()\n _mR[0] = 1, 0, x\n _mR[1] = 0, 1, y\n\n _m = _m * _mR\n\n self.__matStack[0] = self.__matStack[0] * _m\n\n def translate(self, *args):\n tx, ty = 0, 0\n if len(args) == 1:\n v = args[0]\n if isinstance(v, list) or isinstance(v, tuple):\n tx, ty = v[0], v[1]\n if isinstance(v, vec2):\n tx, ty = v.x, v.y\n else:\n tx, ty = args[0], args[1]\n\n _m = mat3()\n _m.set(0, 2, tx)\n _m.set(1, 2, ty)\n\n self.__matStack[0] = self.__matStack[0] * _m\n\n def rotate(self, *args):\n x, y, angle = 0, 0, 0\n if len(args) == 3:\n x, y, angle = args[0], args[1], args[2]\n elif len(args) == 1:\n angle = args[0]\n elif len(args) == 2:\n v = args[0]\n angle = args[1]\n if isinstance(v, vec2):\n x, y = v.x, v.y\n elif isinstance(v, list) or isinstance(v, tuple):\n x, y = v[0], v[1]\n\n sin_a, cos_a = math.sin(angle), math.cos(angle)\n _m = mat3()\n _m[0] = cos_a, -sin_a, 0\n _m[1] = sin_a, cos_a, 0\n _mL = mat3()\n _mL[0] = 1, 0, x\n _mL[1] = 0, 1, y\n _mR = mat3()\n _mR[0] = 1, 0, -x\n _mR[1] = 0, 1, -y\n\n _m = _mL * _m\n _m = _m * _mR\n\n self.__matStack[0] = self.__matStack[0] * _m\n" }, { "alpha_fraction": 0.4987930357456207, "alphanum_fraction": 0.5271345376968384, "avg_line_length": 33.73602294921875, "blob_id": "b36d767548faf861ec08c67f08fe1cf78cde6179", "content_id": "1c4df0ed0ff71a590306fd292a4cc4f7cbe11ed8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11213, "license_type": "no_license", "max_line_length": 117, "num_lines": 322, "path": "/source/examples/Sudoku.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import time\nimport pygame\n\nfrom source.core.assembly.IOEvent import ioEvent3Enum\nfrom source.core.const.Const import gl_Font_opt\nfrom source.core.math.Shape import Rectangle\nfrom source.util.ToolsFuc import blankSurface\nfrom source.view.baseClazz.Scene import Scene\nfrom source.view.element.Elements import ImgElement\n\n\nclass SudokuSprite(ImgElement):\n def __init__(self, area, path):\n super(SudokuSprite, self).__init__(area, path)\n self.__index = (0, 0)\n self.__shaderDistance = 10\n self.__mask = blankSurface((area.h, area.w), (40, 40, 40, 80))\n self.__val = 0\n self.__isStatic = False\n\n self.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: self.__chaShader(True), 0)\n self.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp, lambda: self.__chaShader(False), 0)\n self.Events.appendEvent(ioEvent3Enum.mouseRightKeyDown, lambda: self.__clearVal(), 0)\n\n def __clearVal(self):\n if not self.__isStatic:\n self.__val = 0\n self.setImg(blankSurface(self.area.size()))\n\n def setIndex(self, index):\n self.__index = index\n\n def getIndex(self):\n return self.__index\n\n def setValue(self, val):\n self.__val = val\n\n def getValue(self):\n return self.__val\n\n def setIsStatic(self, isStatic):\n if self.__val != 0:\n self.__isStatic = isStatic\n\n def getIsStatic(self):\n return self.__isStatic\n\n def draw(self, screen):\n if not self.__isStatic:\n screen.blit(self.__mask, (self.area.x + self.__shaderDistance, self.area.y + self.__shaderDistance))\n super().draw(screen)\n\n def __chaShader(self, isDown):\n if isDown:\n self.zIndex -= 1\n self.area.x += 2\n self.area.y += 2\n self.__shaderDistance = 6\n else:\n self.zIndex += 1\n self.area.x -= 2\n self.area.y -= 2\n self.__shaderDistance = 10\n\n\nclass SudokuMap:\n def getName(self):\n pass\n\n def getSucScore(self):\n pass\n\n def getSize(self):\n pass\n\n def getSpriteSize(self):\n pass\n\n def getPuzzleList(self):\n pass\n\n def getAnswerList(self):\n pass\n\n def getInitSpritePosList(self):\n pass\n\n def buildSpriteMap(self):\n pass\n\n def getSpritePath(self, number):\n pass\n\n def getStaticSpritePath(self, number):\n pass\n\n def getBgSurface(self):\n pass\n\n def getPos(self, sprite):\n pass\n\n def getSprite(self, pos):\n pass\n\n def getSumOfInitEmpty(self):\n pass\n\n def playClickSound(self):\n pass\n\n def playBGM(self):\n pass\n\n\nclass SudokuMapLv0(SudokuMap):\n def __init__(self):\n self.__resImgPath = \"F:\\\\Practice\\\\PyCharm\\\\PygameTest\\\\resource\\\\Test\\\\\"\n self.__resImgName = \"sudoku_\"\n self.__resStaticImgName = \"static_\"\n self.__resImgExt = \".jpg\"\n self.__resStaticImgExt = \".png\"\n self.__resBgImg = \"sudoku_bg_0.jpg\"\n self.__resSoundPathClick = \"F:\\\\Practice\\\\PyCharm\\\\PygameTest\\\\resource\\\\Wave\\\\Sound\\\\\"\n self.__resSoundNameClick = \"OPT_C.wav\"\n self.__resMusicsPath = \"F:\\\\Practice\\\\PyCharm\\\\PygameTest\\\\resource\\\\Test\\\\sudokuBGM\\\\\"\n pygame.mixer.music.load(self.__resMusicsPath + \"bgm0.mp3\")\n\n self.__resSoundClick = pygame.mixer.Sound(self.__resSoundPathClick + self.__resSoundNameClick)\n\n self.__row = 0\n self.__col = 0\n self.__length = 60\n self.__index = 0\n self.__sumOfInitEmpty = 0\n\n self.__indexDict = dict()\n self.__elements = list()\n self.__data = {\"puzzle\": [0, 1, 0, 0, 0, 8, 4, 0, 7,\n 9, 5, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 8, 0, 1, 0, 0, 0, 0,\n 0, 8, 2, 0, 0, 0, 0, 0, 0,\n 7, 0, 0, 4, 0, 6, 0, 0, 8,\n 0, 0, 0, 0, 0, 0, 6, 2, 0,\n 0, 0, 0, 0, 5, 0, 7, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 8, 2,\n 5, 0, 3, 2, 0, 0, 0, 1, 6],\n \"answer\": [2, 1, 6, 9, 3, 8, 4, 5, 7,\n 9, 5, 4, 7, 6, 2, 8, 3, 1,\n 3, 7, 8, 5, 1, 4, 2, 6, 9,\n 6, 8, 2, 1, 9, 5, 3, 7, 4,\n 7, 3, 5, 4, 2, 6, 1, 9, 8,\n 4, 9, 1, 8, 7, 3, 6, 2, 5,\n 8, 2, 9, 6, 5, 1, 7, 4, 3,\n 1, 6, 7, 3, 4, 9, 5, 8, 2,\n 5, 4, 3, 2, 8, 7, 9, 1, 6]}\n\n self.__initSpritePosList = list()\n\n def getName(self):\n return \"1\"\n\n def getSize(self):\n return self.__length * 9 + 2 * 6 + 4 * 2, self.__length * 9 + 2 * 6 + 4 * 2\n\n def getSucScore(self):\n return 81 - self.getSumOfInitEmpty()\n\n def getSpriteSize(self):\n return self.__length, self.__length\n\n def getPuzzleList(self):\n return self.__data[\"puzzle\"]\n\n def getAnswerList(self):\n return self.__data[\"answer\"]\n\n def getInitSpritePosList(self):\n length = len(self.__initSpritePosList)\n if length == 0:\n puzzleList = self.getPuzzleList()\n for i in range(0, len(puzzleList)):\n if puzzleList[i] != 0:\n self.__initSpritePosList.append(i)\n return self.__initSpritePosList\n\n def buildSpriteMap(self):\n rowMarginStep, colMarginStep = 4, 4\n rowMargin, colMargin = rowMarginStep, colMarginStep\n while self.__col < 9:\n rowMarginStep = 8 if ((self.__row + 1) % 3 == 0) else 2\n colMarginStep = 8 if ((self.__col + 1) % 3 == 0) else 2\n\n ret = Rectangle(100 + (self.__row * self.__length + rowMargin),\n 10 + (self.__col * self.__length + colMargin),\n self.__length, self.__length)\n number = self.__data[\"puzzle\"][self.__index]\n self.__index += 1\n\n if number != 0:\n resName = self.__resImgPath + self.__resImgName + self.__resStaticImgName + str(\n number) + self.__resStaticImgExt\n else:\n resName = self.__resImgPath + self.__resImgName + \"0\" + self.__resImgExt\n element = SudokuSprite(ret, resName)\n self.__indexDict[element] = (self.__row, self.__col)\n element.setIndex((self.__row, self.__col))\n element.setValue(number)\n element.setIsStatic(True)\n element.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: self.__resSoundClick.play(), 1)\n\n self.__elements.append(element)\n self.__row += 1\n rowMargin = rowMargin + rowMarginStep\n if self.__row == 9:\n self.__row = 0\n rowMargin = 4\n self.__col += 1\n colMargin = colMargin + colMarginStep\n\n return self.__elements\n\n def getSpritePath(self, number):\n return self.__resImgPath + self.__resImgName + str(number) + self.__resImgExt\n\n def getStaticSpritePath(self, number):\n return self.__resImgPath + self.__resImgName + self.__resStaticImgName + str(number) + self.__resStaticImgExt\n\n def getBgSurface(self):\n return pygame.image.load(self.__resImgPath + self.__resBgImg)\n\n def getPos(self, sprite):\n return self.__indexDict[sprite]\n\n def getSprite(self, pos):\n return self.__elements[pos[1] * 9 + pos[0]]\n\n def getSumOfInitEmpty(self):\n if self.__sumOfInitEmpty == 0:\n for i in self.__data:\n if i != 0:\n self.__sumOfInitEmpty += 1\n return self.__sumOfInitEmpty\n\n def playClickSound(self):\n self.__resSoundClick.play()\n\n def playBGM(self):\n pygame.mixer.music.play(loops=-1)\n # pygame.mixer.music.queue(self.__resMusicsPath + \"02.mp3\")\n\n\nclass SudokuGame(Scene):\n def __init__(self, *args):\n super(SudokuGame, self).__init__(*args)\n self.__sudokuMap = SudokuMapLv0()\n self.__nowSelect = None\n self.__mask = None\n self.__score = 0\n self.__sucScore = 0\n self.__insertList = list()\n self.__allSprite = list()\n self.__isSuc = False\n\n def setup(self):\n self.bgSurface = self.__sudokuMap.getBgSurface()\n self.__sucScore = self.__sudokuMap.getSucScore()\n self.__insertList = self.__sudokuMap.getInitSpritePosList()\n self.__mask = blankSurface(self.__sudokuMap.getSpriteSize(), (40, 40, 40, 80))\n self.__allSprite = self.__sudokuMap.buildSpriteMap()\n\n self.createTextElement(\"Time:\", color=(0, 0, 0), size=14)\n self.createTextElement(\"Level:\" + self.__sudokuMap.getName(), color=(0, 0, 0), size=14, pos=self.TOP_RIGHT)\n self.caption = \"Sudoku Game 数独的游戏 v1.0.0 by 小叮铃制作组\"\n\n self.render.open()\n self.render.add(self.__allSprite)\n self.render.close()\n # print(self.render,log())\n\n self.__sudokuMap.playBGM()\n\n def draw(self):\n if not self.__isSuc and self.__nowSelect and self.__nowSelect.area.x > 0 and isinstance(self.__nowSelect,\n SudokuSprite):\n self.screen.blit(self.__mask, (self.__nowSelect.area.x, self.__nowSelect.area.y))\n if self.__isSuc:\n self.createTextElement(\"成功!\", pos=self.CENTER, color=(100, 104, 255), font=gl_Font_opt, size=60)\n\n def doClockEvent(self, NowClock):\n self.getCreatedElement(0).setText(\"Time:\" + time.strftime(\"%H:%M:%S\", time.localtime()))\n\n def doMouseButtonDownEvent(self, Button):\n if Button == 1:\n self.__nowSelect = self.focus\n\n def doKeyEvent(self, Key, Mod, Type, Unicode):\n inputCorrect = False\n if not isinstance(self.__nowSelect, SudokuSprite):\n return\n if self.__nowSelect and self.__nowSelect.area.x > 0 and Type == 0:\n if self.__nowSelect.getIsStatic():\n return\n if Key == 127 or Key == 8:\n self.__nowSelect.setPath(self.__sudokuMap.getSpritePath(0))\n self.__nowSelect.setValue(0)\n inputCorrect = True\n elif 47 < Key < 58:\n self.__nowSelect.setPath(self.__sudokuMap.getSpritePath(Key - 48))\n self.__nowSelect.setValue(Key - 48)\n inputCorrect = True\n\n if inputCorrect:\n pos = self.__sudokuMap.getPos(self.__nowSelect)\n val = self.__nowSelect.getValue()\n if val == self.__sudokuMap.getAnswerList()[pos[1] * 9 + pos[0]]:\n self.__nowSelect.setPath(self.__sudokuMap.getStaticSpritePath(val))\n self.__nowSelect.setIsStatic(True)\n self.__insertList.append(pos[1] * 9 + pos[0])\n if len(self.__insertList) == len(self.__allSprite):\n self.__isSuc = True\n" }, { "alpha_fraction": 0.539089560508728, "alphanum_fraction": 0.5614794492721558, "avg_line_length": 35.08928680419922, "blob_id": "d3645736d332b371ecf00f78bf91e93e01856255", "content_id": "48e015d3f4e9314d1cc63b8aea3ca99da0512be9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8826, "license_type": "no_license", "max_line_length": 122, "num_lines": 224, "path": "/source/core/component/Console.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import time\nfrom queue import Queue\n\nimport pygame\nfrom numpy import random\n\nfrom source.core.assembly.IOEvent import ioEvent3Enum, getAsciiByIOEvent3Enum\nfrom source.core.math.MathConst import MAX_ZINDEX\nfrom source.core.math.MathUtil import constrain\nfrom source.util.ToolsFuc import blankSurface\nfrom source.view.baseClazz.Element import Element\nfrom source.view.element.Control import BlankElement, TextArea\nfrom source.view.element.Elements import TextElement\n\ncommDict = {}\nfunny = ['大爷,我现场采访您一下,您这样晨跑锻炼坚持几年了?\\n姑娘别挡道!我尿急!',\n '请问你是做什么工作的?\\n哦。我的工作是杀僵尸。\\n嗯?可是这个世界上没有僵尸啊!\\n你以为它们是怎么没有的?',\n '中午去买菜,感觉都不太新鲜了。\\n老板:早上刚到的,都新鲜的。\\n我:这菜看着就蔫蔫的啊?!\\n老板:从早上到现在,它以为没人要自己了,这不垂头丧气么!\\n我。。。',\n '我问他:你今天怎么没上班儿啊?\\n表弟:那大舌头老板说,让我上班的时候,顺路捎十块钱的“砂纸”,结果我听成了“烧纸”\\n我:那也不至于开除你啊\\n表弟又说:老板看我买错了,让拿出去扔了,\\n'\n '我跟他说,留着吧,万一再用上呢?',\n '周末,我和男友还有闺蜜一起乘地铁,人很多,\\n我在男友身后,闺蜜在男友前面,我脑子一抽,伸手在闺蜜臀部掐了一下,\\n闺蜜回头含情脉脉的看了我男友一眼,然后往男友身边靠近了些!\\n闺蜜你这。。。']\n\n\ndef registerComm(text, fuc):\n commDict[text] = fuc\n\n\ndef IsValidComm(text) -> bool:\n if text in commDict.keys():\n return True\n return False\n\n\ndef getCommBlock(text):\n if text:\n return CommBlock(1, 3, text, time.localtime())\n return None\n\n\nclass CommBlock:\n def __init__(self, level, type_, text, time_):\n self.__lv = level\n self.__type = type_\n self.__text = text\n self.__time = time_\n # runnable\n self.flag_isActive = False\n # suspend\n self.flag_isSuspend = False\n # new\n self.flag_isStart = False\n # dead\n self.flag_isDead = False\n # running\n self.flag_isPressing = False\n # valid\n self.flag_isValid = False\n\n\nclass CommMsgShowText(TextElement):\n def __init__(self, pos, width, margin_top, margin_left, font_size=14, color=(255, 255, 255)):\n super(CommMsgShowText, self).__init__((pos[0] + margin_top, pos[1] + margin_left, width, 0), '',\n 'source/view/origin/res/console.ttf', font_size, color, 1)\n\n def appendMsg(self, msg):\n if not isinstance(msg, str):\n return\n lines = msg.split('\\n')\n self.area.h = self.area.h + (len(lines) - 1) * (self.Size + self.LineSpace)\n self.setText(self.Text + msg)\n\n\nclass Scrollbar(Element):\n def __init__(self, *args):\n super(Scrollbar, self).__init__(*args)\n self.__bar = BlankElement((0, 0, self.area.w, self.area.h), (0, 0, 0, 100))\n self.res_surface = None\n self.__buildSurface()\n\n def __buildSurface(self):\n self.res_surface = self.__bar.res_surface\n\n def updateLength(self, step):\n self.area.y += step\n self.__bar.setSize((self.__bar.area.w, self.__bar.area.h - step))\n self.__buildSurface()\n\n def updatePos(self, up, step):\n t_step = int(constrain(step, 0, self.area.h))\n if up:\n self.area.y -= t_step\n else:\n self.area.y += t_step\n self.__buildSurface()\n\n\nclass Console(TextArea):\n def __init__(self, *args):\n super(Console, self).__init__(*args, font='source/view/origin/res/console.ttf',\n fontSize=14, fontColor=(255, 255, 255), bgColor=(0, 0, 0, 200),\n baseColor=(0, 0, 0, 200), textSpace=1)\n self.__version = '0.1'\n self.zIndex = MAX_ZINDEX\n self.visual = False\n self.active = False\n\n self.__commPtr = -1\n self.__inputList = []\n\n registerComm('clear', lambda: self.clearText())\n registerComm('cl', lambda: self.clearText())\n registerComm('do-some-funny', lambda: self.funny())\n\n def getVerStr(self):\n return self.__version\n\n def log(self, msg):\n self.appendText(msg)\n\n def logl(self, msg):\n self.appendText(str(msg) + '\\n')\n\n def keyInput(self, key):\n _key = getAsciiByIOEvent3Enum(key)\n # print(_key)\n # 8 - 退格 \n # 9 - Tab \n # 13 - 回车 \n # 16~18 - Shift, Ctrl, Alt \n # 37~40 - 左上右下 \n # 35~36 - End Home \n # 46 - Del \n # 112~123 - F1 - F12 \n if _key == 8:\n _text = self.getText()[:-1]\n self.__text = ''\n self.clearText()\n self.appendText(_text)\n elif _key == 13:\n text = self.getText().split('\\n')[-1]\n self.__inputList.append(text)\n self.__commPtr += 1\n self.appendText('\\n')\n if IsValidComm(text):\n commDict[text]()\n elif not text == '':\n self.appendText('\\'{}\\' is a invalid command'.format(text) + '\\n')\n elif 32 <= _key <= 126:\n self.appendText(chr(_key))\n elif _key == 273:\n if len(self.__inputList) > 0:\n self.appendLastLine(self.__inputList[self.__commPtr])\n self.__commPtr -= 1\n if self.__commPtr < 0:\n self.__commPtr = 0\n elif _key == 274:\n if len(self.__inputList) > 0:\n self.appendLastLine(self.__inputList[self.__commPtr])\n self.__commPtr += 1\n if self.__commPtr >= len(self.__inputList):\n self.__commPtr = len(self.__inputList) - 1\n\n def funny(self):\n self.logl(funny[random.randint(-1, 5)])\n\n def errorLog(self, text):\n self.appendText()\n\n# class Console(Element):\n# def __init__(self, *args):\n# super(Console, self).__init__(*args)\n# self.__commPtr = 0\n# self.__commWindBg = BlankElement((self.area.w, self.area.h - 20), (255, 255, 255, 100))\n# self.__commShowMsg = CommMsgShowText((self.area.x, self.area.y), self.area.w - 20, 10, 10)\n# self.__commShowMsg_blit_y = self.__commShowMsg.area.y\n# self.__commShowMsgSlid = Scrollbar((self.area.w - 10, 0, 10, self.__commWindBg.area.h))\n# self.__inputWindBack = BlankElement((self.area.w, 20), (200, 200, 200, 100))\n# self.__inputText = TextElement((0, 0, self.area.w, 20), '', 'source/view/origin/res/console.ttf', 18, (0, 0, 0),\n# 1)\n# self.__commNewQueue = Queue()\n# self.__commSuspendedQueue = Queue()\n# self.__commRunningQueue = Queue()\n# self.__commDeadQueue = Queue()\n# self.__commRunnableQueue = Queue()\n#\n# self.res_surface = None\n# self.zIndex = MAX_ZINDEX\n# self.visual = False\n# self.active = False\n#\n# self.__buildSurface()\n#\n# self.Events.appendEvent(ioEvent3Enum.mouseRollUp, lambda: self.__event_updateScrollBarPos(), 1)\n#\n# def __event_updateScrollBarPos(self):\n# self.__commShowMsgSlid.updatePos(True, 10)\n# self.__buildSurface()\n#\n# def __buildSurface(self):\n# self.res_surface = pygame.Surface((int(self.area.w), int(self.area.h))).convert()\n# self.res_surface.blit(self.__commWindBg.res_surface, (0, 0))\n# self.res_surface.blit(self.__inputWindBack.res_surface, (0, self.area.h - 20))\n# if (self.__commShowMsg.area.h - self.__commShowMsg.area.y) > (self.__commWindBg.area.h - 10):\n# self.__commShowMsg_blit_y = self.__commShowMsg_blit_y - 20\n# self.res_surface.blit(self.__commShowMsg.res_surface, (10, self.__commShowMsg_blit_y))\n# self.__commShowMsgSlid.updateLength(10)\n# self.res_surface.blit(self.__commShowMsgSlid.res_surface,\n# (self.__commShowMsgSlid.area.x, self.__commShowMsgSlid.area.y))\n# else:\n# self.res_surface.blit(self.__commShowMsg.res_surface, (10, 10))\n#\n# def setInputText(self, text):\n# self.__inputText.setText(text)\n# comm = getCommBlock(text)\n# if comm:\n# self.__commNewQueue.put(comm)\n# self.__buildSurface()\n#\n# def print(self, text):\n# self.__commShowMsg.appendMsg(str(text))\n# self.__buildSurface()\n#\n# def draw(self, screen):\n# screen.blit(self.res_surface, (self.area.x, self.area.y))\n" }, { "alpha_fraction": 0.6052129864692688, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 33.19565200805664, "blob_id": "dc5a4c43f88ef776dcaf6139efe965785106e194", "content_id": "2b5a1724686f6faf7182b81e46b6f44517c92279", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1573, "license_type": "no_license", "max_line_length": 68, "num_lines": 46, "path": "/source/view/baseClazz/Element.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.core.assembly.IOEvent import IOEvent3, ElementHadDoEvent\nfrom source.core.math.Shape import Shape\nfrom source.core.math.Shape import Rectangle\n\n\nclass Element:\n def __init__(self, area, msgQueue=None, Events=None):\n _area = None\n if isinstance(area, Shape):\n _area = area\n else:\n _area = Rectangle(area[0], area[1], area[2], area[3])\n self.area = _area\n self.msgQueue = msgQueue\n self.Events = Events\n if self.Events is None:\n self.Events = IOEvent3()\n self.EventsHadDo = ElementHadDoEvent()\n self.active = True\n self.zIndex = 0\n self.visual = True\n self.mouseLastPos = (0, 0)\n self.mousePos = (0, 0)\n self.mouseButtons = (0, 0, 0)\n self.mouseRel = (0, 0)\n\n def recoverEvent(self):\n # self.hadDoMouseIn = False\n # self.hadDoMouseOut = True\n # self.hadDoMouseLeftKeyUp = True\n # self.hadDoMouseLeftKeyDown = False\n # self.hadDoMouseLeftKeyClick = False\n # self.hadDoMouseRightKeyUp = False\n # self.hadDoMouseRightKeyDown = False\n # self.hadDoMouseRightKeyClick = False\n # self.hadDoMouseMidKeyUp = False\n # self.hadDoMouseMidKeyDown = False\n # self.hadDoMouseMidKeyClick = False\n # self.hadDoDoubleClick = False\n # self.hadDoKeyboardKeyUp = False\n # self.hadDoKeyboardKeyDown = False\n # self.hadDoKeyboardKeyDowning = False\n self.EventsHadDo = ElementHadDoEvent()\n\n def draw(self, screen):\n pass\n" }, { "alpha_fraction": 0.4831579029560089, "alphanum_fraction": 0.4884210526943207, "avg_line_length": 25.38888931274414, "blob_id": "710ed357742485858acd12c59bb79eda67d296c4", "content_id": "db99fdf93a766613680ec23e6e30ae05b3b66f65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 950, "license_type": "no_license", "max_line_length": 52, "num_lines": 36, "path": "/source/core/assembly/Command.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "class Comm:\n def __init__(self, name, fuc, *param):\n self.name = name\n self.callable = fuc\n self.param = param\n\n\nclass Command:\n def __init__(self):\n self.__comDict = dict()\n self.__MAXNUM = 125\n self.__curP = 0\n self.__sendCommList = list()\n self.__curStr = list()\n\n def registerCommand(self, c):\n if isinstance(Comm, c):\n self.__comDict[c.name] = c\n\n def sendComm(self, s):\n if s in self.__comDict.keys():\n self.__sendCommList.append(s)\n _comm = self.__comDict[s]\n _comm.callable(_comm.param)\n\n def inputComm(self, c):\n _length = len(self.__curStr)\n if _length < self.__MAXNUM:\n if _length == self.__curP:\n self.__curStr.append(c)\n else:\n self.__curStr.insert(self.__curP, c)\n self.__curP += 1\n\n # def __inputExc(self, c):\n # if c=\n" }, { "alpha_fraction": 0.6388888955116272, "alphanum_fraction": 0.6616161465644836, "avg_line_length": 11.806451797485352, "blob_id": "dcbffedb578a52fd77a5c941d65dd9a838c860c8", "content_id": "88590ccd83c2e764117f84a94365eebc74420917", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 406, "license_type": "no_license", "max_line_length": 77, "num_lines": 31, "path": "/source/examples/annotationTest.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import numpy as np\n\nimport matplotlib.pyplot as plt\n\nimport pylab\n\nimport imageio\n\nimport skimage.io\n\nimport cv2\n\ncap = cv2.VideoCapture('F:/练习/PyCharm/PygameTest/resource/Video/P_M_PCG.mp4')\n\nwhile cap.isOpened():\n\n ret, frame = cap.read()\n\n cv2.imshow('image', frame)\n\n k = cv2.waitKey(20)\n\n #q键退出\n\n if k & 0xff == ord('q'):\n\n break\n\ncap.release()\n\ncv2.destroyAllWindows()" }, { "alpha_fraction": 0.5763790607452393, "alphanum_fraction": 0.5792078971862793, "avg_line_length": 31.136363983154297, "blob_id": "854037bc3e6fd11586189344f0dce6cae1f77d7d", "content_id": "bd806bafb28bae27e2600533fc18f00b732c2d03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1414, "license_type": "no_license", "max_line_length": 107, "num_lines": 44, "path": "/source/core/assembly/RecordFile.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.core.const.Const import RECORDFILE_HEAD, RSA_PK_FILE_EXN, RECORDFILE_SAVE_EXN\nfrom source.core.assembly.RSA import rsaEncrypt, rsaDecrypt, outPrivateKeyToPS, getPrivateKeyFromPS\n\n\nclass NotRecordFileType(Exception):\n def __init__(self, arg):\n self.args = arg\n\n\nclass RecordFile:\n def __init__(self, path, fileName):\n self.__path = path\n self.__fileName = fileName\n self.__pf = path + fileName + RECORDFILE_SAVE_EXN\n self.__file = None\n self.__lis = []\n\n def create(self, lis):\n content = RECORDFILE_HEAD + '\\n'\n for v in lis:\n content += v + '\\n'\n crypto, privateKey = rsaEncrypt(content, 512)\n outPrivateKeyToPS(self.__path + self.__fileName + RSA_PK_FILE_EXN, privateKey)\n self.__file = open(self.__pf, 'wb')\n self.__file.write(crypto)\n self.__file.close()\n\n def getList(self):\n if not self.__lis:\n self.__lis.clear()\n\n self.__file = open(self.__pf, 'rb')\n content = self.__file.read()\n self.__file.close()\n content = rsaDecrypt(content, getPrivateKeyFromPS(self.__path + self.__fileName + RSA_PK_FILE_EXN))\n\n lis = content.split('\\n')\n lis.pop()\n if lis[0] != RECORDFILE_HEAD:\n return None\n lis.remove(RECORDFILE_HEAD)\n for v in lis:\n self.__lis.append(v)\n return self.__lis\n" }, { "alpha_fraction": 0.46110638976097107, "alphanum_fraction": 0.48459574580192566, "avg_line_length": 34.39156723022461, "blob_id": "3446640c3ee09366981589813acde9a5dbc950a8", "content_id": "7574cea4e376cfd0572e9e845b82ca8b1e78e27d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5891, "license_type": "no_license", "max_line_length": 110, "num_lines": 166, "path": "/source/examples/AstartTest.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import random\n\nimport pygame\n\nfrom source.core.const.Const import gl_Font\nfrom source.util.ToolsFuc import centeredXPos\nfrom source.view.baseClazz.Scene import Scene\nfrom source.view.element.Elements import TextElement\n\n\ndef heuristic(a, b):\n return abs(a.i - b.i) + abs(a.j - b.j)\n\n\nclass Spot:\n def __init__(self, i, j):\n self.i = i\n self.j = j\n self.f = 0\n self.g = 0\n self.h = 0\n self.neighbors = []\n self.previous = None\n self.wall = False\n if random.uniform(0, 1) < 0.5:\n self.wall = True\n\n def show(self, surface, col, w, h):\n color = col\n if self.wall:\n color = (0, 0, 0)\n # pygame.draw.rect(surface, color, (self.i * w, self.j * h, w - 1, h - 1), 0)\n # pygame.draw.circle(surface, color, (self.i * w + w / 2, self.j * h + h / 2), (w / 2), 1)\n pygame.draw.rect(surface, color, (self.i * w, self.j * h, w - 1, h - 1), 0)\n\n def addNeighbors(self, cols, rows, grid):\n i, j = self.i, self.j\n if i < cols - 1:\n self.neighbors.append(grid[i + 1][j])\n if i > 0:\n self.neighbors.append(grid[i - 1][j])\n if j < rows - 1:\n self.neighbors.append(grid[i][j + 1])\n if j > 0:\n self.neighbors.append(grid[i][j - 1])\n if i > 0 and j > 0:\n self.neighbors.append(grid[i - 1][j - 1])\n if i < cols - 1 and j > 0:\n self.neighbors.append(grid[i + 1][j - 1])\n if i > 0 and j < rows - 1:\n self.neighbors.append(grid[i - 1][j + 1])\n if i < cols - 1 and j < rows - 1:\n self.neighbors.append(grid[i + 1][j + 1])\n\n\nclass AstartTest(Scene):\n def __init__(self, screen, config, time):\n super(AstartTest, self).__init__(screen, config, time)\n self.cols, self.rows = 100, 100\n self.grid = []\n self.openSet, self.closeSet = [], []\n self.start, self.end = None, None\n self.w, self.h = screen.get_width() / self.cols, screen.get_height() / self.rows\n self.path = []\n self.done = False\n self.noSolution = False\n self.points = []\n self.__E_TEXT = TextElement(pygame.Rect(centeredXPos(self.width, 220), 260, 220, 60), '', gl_Font, 50,\n (255, 255, 0), 1)\n\n for i in range(0, self.cols):\n self.grid.append([])\n\n for i in range(0, self.cols):\n for j in range(0, self.rows):\n self.grid[i].append(Spot(i, j))\n\n for i in range(0, self.cols):\n for j in range(0, self.rows):\n self.grid[i][j].addNeighbors(self.cols, self.rows, self.grid)\n\n self.start = self.grid[0][0]\n self.end = self.grid[self.cols - 1][self.rows - 1]\n self.start.wall = False\n self.end.wall = False\n self.openSet.append(self.start)\n\n def draw(self):\n current = None\n if len(self.openSet) > 0:\n winner = 0\n for i in range(0, len(self.openSet)):\n if self.openSet[i].f < self.openSet[winner].f:\n winner = i\n\n current = self.openSet[winner]\n\n if current == self.end:\n self.done = True\n\n if not self.done:\n self.openSet.remove(current)\n self.closeSet.append(current)\n\n neighbors = current.neighbors\n for i in range(0, len(neighbors)):\n neighbor = neighbors[i]\n if neighbor not in self.closeSet and not neighbor.wall:\n tempG = current.g + 1\n newPath = False\n if neighbor in self.openSet:\n if tempG < neighbor.g:\n neighbor.g = tempG\n newPath = True\n else:\n neighbor.g = tempG\n newPath = True\n self.openSet.append(neighbor)\n if newPath:\n neighbor.h = heuristic(neighbor, self.end)\n neighbor.f = neighbor.g + neighbor.h\n neighbor.previous = current\n else:\n self.done = True\n self.__E_TEXT.setText('寻路失败')\n self.noSolution = True\n\n # self.screen.fill((255, 255, 255))\n\n for i in range(0, self.cols):\n for j in range(0, self.rows):\n self.grid[i][j].show(self.screen, (255, 255, 255), self.w, self.h)\n\n for i in range(0, len(self.openSet)):\n self.openSet[i].show(self.screen, (0, 255, 0), self.w, self.h)\n\n for i in range(0, len(self.closeSet)):\n self.closeSet[i].show(self.screen, (255, 0, 0), self.w, self.h)\n\n if not self.done:\n self.path.clear()\n temp = current\n self.path.append(temp)\n while temp is not None and temp.previous:\n self.path.append(temp.previous)\n temp = temp.previous\n elif self.done and not self.noSolution:\n self.path.append(self.end)\n self.__E_TEXT.setText('寻路成功')\n\n\n for i in range(0, len(self.path)):\n e = self.path[i]\n if e is not None:\n e.show(self.screen, (0, 0, 255), self.w, self.h)\n\n self.__E_TEXT.draw(self.screen)\n\n # for i in range(0, len(pathN)):\n # e = pathN[i]\n # if e is not None:\n # self.points.append([e.i * self.w + self.w / 2, e.j * self.h + self.h / 2])\n # if len(self.points) > 1:\n # print(self.points)\n # pygame.draw.line(self.screen, (250, 0, 100), self.points[0], self.points[1], 5)\n # self.points.pop(0)\n" }, { "alpha_fraction": 0.5983086824417114, "alphanum_fraction": 0.6088795065879822, "avg_line_length": 32.78571319580078, "blob_id": "8692aafd4972b26556c1f37f86f38f14f7c30da3", "content_id": "306b15f604f21af56ae6deb480dbe16c8106470d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 970, "license_type": "no_license", "max_line_length": 99, "num_lines": 28, "path": "/source/core/physics/Spring.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.core.math.Vector import vec2\n\n\nclass Spring:\n # K_normalSpring = 7.9 # 普通弹簧\n # K_stainlessSteelSpring = 7.2 # 不锈钢丝\n # K_siliconBronzeSpring = 4.1 # 硅青铜线\n\n def __init__(self, beginMass, endMass, length, K, frictionConst):\n self.beginMass = beginMass\n self.endMass = endMass\n self.length = length\n self.K = K\n self.frictionConst = frictionConst\n\n def execute(self, fixed=0):\n variable = self.beginMass.local - self.endMass.local\n var_len = variable.len()\n force = vec2()\n if var_len != 0:\n force += variable.dev(var_len).mul((var_len - self.length) * (-self.K))\n force += (self.beginMass.velocity - self.endMass.velocity).negate().mul(self.frictionConst)\n if not fixed:\n self.beginMass.applyForce(force)\n self.beginMass.update()\n\n self.endMass.applyForce(force.negate())\n self.endMass.update()\n" }, { "alpha_fraction": 0.5791245698928833, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 30.984615325927734, "blob_id": "fde3ba3d4e576c670f2f4be159612daa8cbbc974", "content_id": "0cf9153284d8fbd470409329b73185839c8e78a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10773, "license_type": "no_license", "max_line_length": 118, "num_lines": 325, "path": "/source/view/element/Elements.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import pygame\n\nfrom source.util.ToolsFuc import blankSurface, centeredXPos, centeredYPos\nfrom source.view.baseClazz.Element import Element\nfrom source.core.assembly.IOEvent import ioEvent3Enum\nfrom source.core.const.Const import gl_Font_opt, const_Text_LineSize, gl_Font_oth\n\n\n# 消息框Elements\nclass MessageBox(Element):\n def __init__(self, bgWidth, bgHeight, text):\n super(MessageBox, self).__init__(\n pygame.Rect(centeredXPos(bgWidth, 180, 0), centeredXPos(bgHeight, 100, 0), 180, 100))\n self.__Text = text\n self.__buildSurface()\n\n def __buildSurface(self):\n self.__E_bg = blankSurface((180, 100), (255, 255, 255, 100))\n concernWidth = len(self.__Text) * 18\n self.__E_Text = TextElement(\n pygame.Rect(centeredXPos(180, concernWidth, self.area.left), centeredYPos(100, 18, self.area.top),\n concernWidth, 20), self.__Text, gl_Font_opt, 18, (0, 0, 0), True)\n self.__E_okButt = TextElement(pygame.Rect(self.area.left + 40, self.area.top + 70, 36, 18), '确定', gl_Font_opt,\n 16, (0, 0, 0), True)\n self.__E_cancelButt = TextElement(pygame.Rect(self.area.left + 80, self.area.top + 70, 36, 18), '取消',\n gl_Font_opt, 16, (0, 0, 0), True)\n\n def draw(self, screen):\n screen.blit(self.__E_bg, (self.area.left, self.area.top))\n screen.blit(self.__E_Text.res_surface, (self.__E_Text.area.left, self.__E_Text.area.top))\n screen.blit(self.__E_okButt.res_surface, (self.__E_okButt.area.left, self.__E_okButt.area.top))\n screen.blit(self.__E_cancelButt.res_surface, (self.__E_cancelButt.area.left, self.__E_cancelButt.area.top))\n\n\n# 标题页面固定元素\nclass TitleConstElement(Element):\n def __init__(self, area, res_Surface):\n super(TitleConstElement, self).__init__(area)\n self.res_surface = res_Surface\n\n def setAlpha(self, alpha):\n self.res_surface.set_alpha(alpha)\n\n def draw(self, screen):\n screen.blit(self.res_surface, (self.area.x, self.area.y))\n\n\n# -----标题页面可交互元素及事件处理---开始-----\n\n# 鼠标左键按下鼠标改变元素位置事件\ndef changeAraPos(e):\n e.area.x += 1\n e.area.y += 1\n\n\n# 鼠标左键放开鼠标移出还原元素位置事件\ndef backAraPos(e):\n e.area.x -= 1\n e.area.y -= 1\n\n\n# 鼠标移入改变样式\ndef changeStyle(e):\n e.setClipRect((e.ClipRect[0] + 30, e.ClipRect[1], e.ClipRect[2], e.ClipRect[3]))\n\n\n# 鼠标移出改变样式\ndef backStyle(e):\n e.setClipRect((e.ClipRect[0] - 30, e.ClipRect[1], e.ClipRect[2], e.ClipRect[3]))\n\n\n# 标题页面选项元素\nclass TitleOptElement(Element):\n def __init__(self, area, res_img, clipRect, colorKey):\n super(TitleOptElement, self).__init__(area)\n self.res_Img = res_img\n self.ClipRect = clipRect\n self.ColorKey = colorKey\n self.__buildSurface()\n\n self.Events.appendEvent(ioEvent3Enum.mouseIn, lambda: changeStyle(self), 0)\n self.Events.appendEvent(ioEvent3Enum.mouseOut, lambda: backStyle(self), 0)\n self.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: changeAraPos(self), 0)\n self.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp, lambda: backAraPos(self), 0)\n\n def __buildSurface(self):\n self.res_surface = pygame.Surface((self.ClipRect[2], self.ClipRect[3])).convert()\n self.res_surface.set_colorkey(self.ColorKey)\n self.res_surface.blit(self.res_Img, (-self.ClipRect[1], -self.ClipRect[0]))\n\n def draw(self, screen):\n screen.blit(self.res_surface, (self.area.x, self.area.y))\n\n def setResImg(self, res_Img):\n self.res_Img = res_Img\n self.__buildSurface()\n\n def setClipRect(self, clipRect):\n self.ClipRect = clipRect\n self.__buildSurface()\n\n def setColorKey(self, colorKey):\n self.ColorKey = colorKey\n self.__buildSurface()\n\n def setAlpha(self, alpha):\n self.res_surface.set_alpha(alpha)\n\n def setParam(self, params):\n if params[0]:\n self.res_Img = params[0]\n if params[1]:\n self.ClipRect = params[1]\n if params[2]:\n self.ColorKey = params[2]\n self.__buildSurface()\n\n\nclass superTextElement(Element):\n \"\"\"<size=12, color=red, font=0>是</>\"\"\"\n\n def __init__(self, area, text, line_space):\n super(superTextElement, self).__init__(area)\n self.__text = text\n self.__line_space = line_space\n\n class Text:\n def __init__(self, font, size, color):\n self.font = font\n self.size = size\n self.color = color\n\n def __buildTextAry(self, text):\n pass\n\n\n# 文字元素及其事件处理\nclass TextElement(Element):\n def __init__(self, area, text, font, size, color, antiAlias, line_space=const_Text_LineSize):\n super(TextElement, self).__init__(area)\n self.Font = font\n self.Text = text\n self.Size = size\n self.Color = color\n self.AntiAlias = antiAlias\n self.LineSpace = line_space\n self.__buildSurface()\n\n # 这里是渲染非透明文本的方法,没有底色\n # def __buildSurface(self):\n # textTemp = pygame.font.Font(self.Font, self.Size)\n # self.res_surface = textTemp.render(self.Text, 1, self.Color)\n\n # 这里是渲染透明文本的方法, 无底色\n def __buildSurface(self):\n textTemp = pygame.font.Font(self.Font, self.Size)\n strList = self.Text.split('\\n')\n self.res_surface = pygame.Surface((self.area.w, self.area.h)).convert()\n self.res_surface.fill((128, 128, 128))\n self.res_surface.set_colorkey((128, 128, 128))\n Line = 0\n for s in strList:\n if s is not None and s != '':\n self.res_surface.blit(textTemp.render(s, self.AntiAlias, self.Color),\n (0, Line * (self.Size + self.LineSpace)))\n Line += 1\n if len(self.Color) >= 4:\n self.res_surface.set_alpha(self.Color[3])\n\n def draw(self, screen):\n screen.blit(self.res_surface, (self.area.x, self.area.y))\n\n def setAlpha(self, alpha):\n self.res_surface.set_alpha(alpha)\n\n def setText(self, text):\n self.Text = str(text)\n self.__buildSurface()\n\n def setFont(self, font):\n self.Font = font\n self.__buildSurface()\n\n def setSize(self, size):\n self.Size = size\n self.__buildSurface()\n\n def setColor(self, color):\n self.Color = color\n self.__buildSurface()\n\n def setParam(self, params):\n if params[0]:\n self.Text = params[0]\n if params[1]:\n self.Font = params[1]\n if params[2]:\n self.Size = params[2]\n if params[3]:\n self.Color = params[3]\n self.__buildSurface()\n\n\n# 图像元素及其事件处理\nclass ImgElement(Element):\n def __init__(self, area, path=None, alpha=255, colorKey=None):\n super(ImgElement, self).__init__(area)\n self.Path = path\n self.Alpha = alpha\n self.ColorKey = colorKey\n self.res_surface = None\n self.__buildSurface()\n\n def __buildSurface(self):\n if self.Path is None:\n self.res_surface = blankSurface(self.area.size(), (0, 0, 0, self.Alpha))\n else:\n self.res_surface = pygame.image.load(self.Path)\n self.res_surface.set_alpha(self.Alpha)\n if self.ColorKey:\n self.res_surface.set_colorkey(self.ColorKey)\n\n def draw(self, screen):\n screen.blit(self.res_surface, (self.area.x, self.area.y))\n\n def chaSize(self, w=None, h=None):\n if w:\n self.res_surface.get_rect().w = w\n if h:\n self.res_surface.get_rect().h = h\n\n def setPath(self, path):\n self.Path = path\n self.__buildSurface()\n\n def setImg(self, suf):\n self.res_surface = suf\n\n def setAlpha(self, alpha):\n self.res_surface.set_alpha(alpha)\n\n def clear(self, color):\n self.res_surface.fill(color)\n\n\n# 序章场景\n\n# 渲染单元\nclass RenderUnionElement(Element):\n def __init__(self, surface, pos, area):\n super(RenderUnionElement, self).__init__(area)\n self.res_surface = surface\n self.pos = pos\n\n\n# 设置页面元素\n\n# 鼠标左键按下鼠标改变元素位置事件\ndef Pos(e, isDown):\n if isDown:\n e.area.x += 1\n e.area.y += 1\n else:\n e.area.x -= 1\n e.area.y -= 1\n\n\nclass OptButtonElement(Element):\n def __init__(self, area, color):\n super(OptButtonElement, self).__init__(area)\n self.Color = color\n self.__buildSurface()\n\n self.Events.appendEvent(ioEvent3Enum.mouseIn, lambda: self.setAlpha(color[3] + 100), 0)\n self.Events.appendEvent(ioEvent3Enum.mouseOut, lambda: self.setAlpha(color[3]), 0)\n self.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp, lambda: Pos(self, False), 0)\n self.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: Pos(self, True), 0)\n\n def __buildSurface(self):\n self.res_surface = blankSurface((self.area.w, self.area.h), self.Color)\n\n def draw(self, screen):\n screen.blit(self.res_surface, (self.area.x, self.area.y))\n\n def setAlpha(self, alpha):\n self.res_surface.set_alpha(alpha)\n\n\n# 选择按钮\nclass OptUIElement(ImgElement):\n def __init__(self, area, path, alpha=255):\n super(OptUIElement, self).__init__(area, path, alpha)\n\n self.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp, lambda: Pos(self, False), 0)\n self.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: Pos(self, True), 0)\n\n\n# 继续游戏界面\n\n# 存储资料选项\nclass SaveDataElement(ImgElement):\n def __init__(self, area, path, alpha, lis):\n super(SaveDataElement, self).__init__(area, path, alpha)\n self.__buildBG((255, 255, 255, 100))\n self.__lis = lis\n print(self.__lis)\n self.__date = self.__lis[0]\n self.__time = self.__lis[1]\n self.__HP = self.__lis[2]\n self.__MP = self.__lis[3]\n self.__E_text_date = TextElement(area, self.__date, gl_Font_oth, 30, (0, 0, 0), 1)\n\n self.Events.appendEvent(ioEvent3Enum.mouseIn, lambda: self.__setBGAlpha(200), 0)\n self.Events.appendEvent(ioEvent3Enum.mouseOut, lambda: self.__setBGAlpha(100), 0)\n\n def __buildBG(self, color):\n self.__bg = blankSurface((self.area[2] - 22, self.area[3] - 22), color)\n\n def __setBGAlpha(self, alpha):\n self.__bg.set_alpha(alpha)\n\n def draw(self, screen):\n screen.blit(self.__bg, (self.area.x + 11, self.area.y + 11))\n super().draw(screen)\n self.__E_text_date.draw(screen)\n" }, { "alpha_fraction": 0.4187256097793579, "alphanum_fraction": 0.48244473338127136, "avg_line_length": 30.387754440307617, "blob_id": "2e78e5df78bf81e01aea2a5f08ee5a927baa98da", "content_id": "be4346a56b8e69ed3e234581ce51002f88c52d5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3088, "license_type": "no_license", "max_line_length": 121, "num_lines": 98, "path": "/source/core/draw/Color.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.core.math.Vector import vec3\n\n\n# class color:\n# \"\"\"颜色类\"\"\"\n# def __init__(self, r, g, b, a=255):\n# # self.valRGB = 0xFF000000 | ((round(r * a) & 0xFF) << 16) | ((round(g * a) & 0xFF) << 8) | round(b * a) & 0xFF\n# self.val = ((a & 0xFF) << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | b & 0xFF\n#\n# def aryRGBA(self):\n# return (self.val >> 16) & 0xff, (self.val >> 8) & 0xff, self.val & 0xff, (self.val >> 24) & 0xff\n#\n# def aryRGB(self):\n# return (self.val >> 16) & 0xff, (self.val >> 8) & 0xff, self.val & 0xff\n#\n# def getR(self):\n# return (self.val >> 16) & 0xff\n#\n# def getG(self):\n# return (self.val >> 8) & 0xff\n#\n# def getB(self):\n# return self.val & 0xff\n#\n# def getAlpha(self):\n# return (self.val >> 24) & 0xff\n#\n# def blendFactor(self):\n# return round(self.getAlpha() / 255, 1)\n#\n# @staticmethod\n# def mix__(bottom, top):\n# bf_a, tf_a = bottom.blendFactor(), top.blendFactor()\n# # br = bottom aryRGBA\n\nclass color:\n \"\"\"颜色类\"\"\"\n\n def __init__(self, *args):\n self.r, self.g, self.b, self.a = 0, 0, 0, 1\n if len(args) == 1:\n # Gray = (R * 38 + G * 75 + B * 15) >> 7\n gray = args[0]\n self.__init__(255 * gray, 255 * gray, 255 * gray)\n if len(args) == 2:\n gray = args[0]\n self.__init__(255 * gray, 255 * gray, 255 * gray, args[1])\n if len(args) == 3:\n self.r, self.g, self.b = round(args[0]), round(args[1]), round(args[2])\n if len(args) == 4:\n self.r, self.g, self.b, self.a = round(args[0]), round(args[1]), round(args[2]), args[3]\n\n def __str__(self):\n return '<color::{}({}, {}, {}, {})>'.format(self.__class__.__name__, self.r, self.g, self.b, self.a)\n\n @staticmethod\n def fromVec3(v, a=1):\n return color(v.x, v.y, v.z, a)\n\n @staticmethod\n def mix_(top, bottom):\n r1, g1, b1, a1 = top.r, top.g, top.b, top.a\n r2, g2, b2, a2 = bottom.r, bottom.g, bottom.b, bottom.a\n\n r3 = r1 * a1 + r2 * a2 * (1 - a1)\n g3 = g1 * a1 + g2 * a2 * (1 - a1)\n b3 = b1 * a1 + b2 * a2 * (1 - a1)\n a3 = 1 - (1 - a1) * (1 - a2)\n\n return color(r3, g3, b3, a3)\n\n def aryRGBA(self):\n return self.r, self.g, self.b, self.a\n\n def aryRGB(self):\n return round(self.r * self.a), round(self.g * self.a), round(self.b * self.a)\n\n def valRGBA(self):\n a_ = round(255 * self.a)\n return ((a_ & 0xFF) << 24) | ((self.r & 0xFF) << 16) | ((self.g & 0xFF) << 8) | self.b & 0xFF\n\n def valRGB(self):\n rgb = self.aryRGB()\n return 0xFF000000 | ((rgb[0] & 0xFF) << 16) | ((rgb[1] & 0xFF) << 8) | rgb[2] & 0xFF\n\n def vector3(self):\n rgb = self.aryRGB()\n vec3(rgb[0], rgb[1], rgb[2])\n\n# red = color(255, 0, 0, 255)\n# blue = color(0, 0, 255, 180)\n# mix = color.mix_(blue, red)\n# print(hex(mix.val))\n# print(hex(blue.val_), hex(red.val_), hex(mix.val_))\n\n# red = color(255, 10, 0, 105)\n#\n# print(red.aryRGBA())\n" }, { "alpha_fraction": 0.5336577296257019, "alphanum_fraction": 0.540145993232727, "avg_line_length": 22.264150619506836, "blob_id": "74df00820dd3169142e80275d993cb6d3650266f", "content_id": "70b81b08e080194c1d2bc6902c0c9f9089f328cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2466, "license_type": "no_license", "max_line_length": 85, "num_lines": 106, "path": "/source/core/assembly/Anime.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.core.math.Vector import vec4\n\n\nclass IntpolTypeEnum:\n line = 0\n cos = 1\n cubic = 2\n hermite = 3\n\n def __init__(self):\n self.param = list()\n\n\nclass AnimeFrame:\n def __init__(self, time=0, local=vec4()):\n self.time = time\n self.local = local\n\n def __str__(self):\n return \"Anime::AnimeFrame<time: {}, local: {}>\".format(self.time, self.local)\n\n def copy(self):\n return AnimeFrame(self.time, self.local)\n\n\nclass AnimePart:\n def __init__(self):\n self.__recordList = list()\n self.__index = -1\n\n def next(self):\n self.__index += 1\n if self.__index >= len(self.__recordList):\n self.__index = 0\n return self.__recordList[self.__index]\n\n def index(self):\n return self.__index\n\n def setData(self, animeFrame):\n self.__recordList.append(animeFrame)\n\n def setAllDatas(self, list):\n self.__recordList += list\n\n def getFrame(self, time, setPointer=False):\n for i in range(0, len(self.__recordList)):\n if self.__recordList[i].time == time:\n if setPointer:\n self.__index = i\n return self.__recordList[i].copy()\n return\n\n def setPointer(self, index):\n self.__index = index\n\n\nclass Anime:\n def __init__(self):\n self.__recordList = list()\n self.__index = -1\n\n def next(self):\n self.__index += 1\n if self.__index >= len(self.__recordList):\n self.__index = 0\n return self.__recordList[self.__index]\n\n def index(self):\n return self.__index\n\n def setData(self, animePart):\n self.__recordList.append(animePart)\n\n def getPark(self, index, setPointer=False):\n if setPointer:\n self.__index = index\n return self.__recordList[index]\n\n def getFarme(self, time):\n for f in self.__recordList:\n frame = f.getFrame(time)\n if frame is not None:\n return frame\n return\n\n def setPointer(self, index):\n self.__index = index\n\n\n# class AnimPlay:\n# def __init__(self, anim):\n# self.__anim = anim\n# self.__currentLocal = None\n#\n# def timeLoop(self, time):\n# self.__anim.\n# self.__currentLocal = self.__anim.next()\n#\n# def display(self, screen, index=-1):\n# if self.__currentLocal is not None:\n# if index == -1:\n\n\n# class AnimFile:\n# pass\n" }, { "alpha_fraction": 0.5108907222747803, "alphanum_fraction": 0.517749547958374, "avg_line_length": 41.3098030090332, "blob_id": "da03166d0ed78e209c582c099b474ef3feda57b5", "content_id": "fecfcf3e304e21fe53b77fbebe9572c57b03192e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10917, "license_type": "no_license", "max_line_length": 117, "num_lines": 255, "path": "/gameApp.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import os\n\nimport pygame\nimport gc\n\nfrom source.core.assembly.Config import Config\nfrom source.core.component.Console import Console\nfrom source.core.component.Mixer import Mixer\nfrom source.core.const.Const import SCENENUM_INIT\nfrom source.util.ToolsFuc import getNotN\n\n\nclass gameApp:\n def __init__(self, appTitle, wight, height, isFullScreen, screenMod, colorBits):\n # 初始化要用到的库\n pygame.init()\n os.environ['SDL_VIDEO_CENTERED'] = '1'\n self.__mixer = Mixer()\n\n # 初始化App属性\n self.__Id = id(self)\n self.__appTitle = appTitle\n self.__screenWidth = wight\n self.__screenHeight = height\n self.__isFullScreen = isFullScreen\n self.__screenMod = screenMod\n self.__colorBits = colorBits\n self.__frameControl = False\n self.__fill = True\n\n from source.config.AppConfig import SceneMap\n if not SceneMap:\n raise Exception(\"'SceneMap' is Empty in AppConfig, 'SceneMap' mast have at least one element\")\n self.__mapping = SceneMap\n\n pygame.display.set_caption(self.__appTitle)\n self.__screen = pygame.display.set_mode((self.__screenWidth, self.__screenHeight), self.__screenMod,\n self.__colorBits)\n self.__config = Config()\n self.__config.readConfig()\n self.__console = Console((0, 0, self.__screenWidth * 0.8, self.__screenHeight * 0.8))\n\n self.__clock = pygame.time.Clock()\n\n self.isQuit = False\n self.frameRate = self.__config.getFrameRate()\n if self.frameRate != 0:\n self.__frameControl = True\n\n self.__scene = self.__mapping[SCENENUM_INIT][0](self.__screen, self.__config, pygame.time.get_ticks(),\n self.__mixer, self.__console)\n self.__scene.super_setup()\n\n if self.__scene.caption is not None:\n pygame.display.set_caption(self.__scene.caption)\n self.__appTitle = self.__scene.caption\n pygame.mouse.set_visible(self.__scene.mouseVisible)\n\n self.__console.log('achieved with Syclight\\n' +\n 'inex recreation software 2020-2021 all rights reserved\\n' + 'console version: ' +\n self.__console.getVerStr() + '\\n' +\n self.__appTitle +\n '\\n------Console------\\n')\n\n def MainLoop(self):\n while not self.isQuit:\n if self.__scene.mouseLimited:\n pygame.mouse.set_pos(self.__scene.mouseX, self.__scene.mouseY)\n if self.__frameControl:\n self.__clock.tick(self.frameRate)\n else:\n self.__clock.tick()\n self.__scene.FPS = round(self.__clock.get_fps(), 1)\n\n # 画屏幕\n self.__scene.super_draw()\n self.__scene.frameCount += 1\n self.__scene.super_doClockEvent(pygame.time.get_ticks())\n\n # 事件处理\n keyPressedList = getNotN(pygame.key.get_pressed(), 0)\n if keyPressedList:\n pygame.event.post(pygame.event.Event(25, {\"keyPressedList\": keyPressedList}))\n\n for event in pygame.event.get():\n if event.type == 12: # QUIT\n self.__mixer.quit()\n pygame.quit()\n self.isQuit = True\n break\n elif event.type == 4: # mouseMotion\n self.__scene.super_doMouseMotion(event.rel, event.buttons)\n elif event.type == 5: # mouseDown\n self.__scene.mousePressed = True\n self.__scene.super_doMouseButtonDownEvent(event.button)\n elif event.type == 6: # mouseUp\n self.__scene.mousePressed = False\n self.__scene.super_doMouseButtonUpEvent(event.button)\n elif event.type == 2:\n self.__scene.super_doKeyEvent(event.key, event.mod, 0, event.unicode)\n elif event.type == 3:\n self.__scene.super_doKeyEvent(event.key, event.mod, 1)\n elif event.type == 25:\n self.__scene.super_doKeyPressedEvent(event.keyPressedList)\n if 3 < event.type < 7: # 与鼠标有关的事件\n self.__scene.lastMousePos = self.__scene.mousePos\n self.__scene.mousePos = event.pos\n self.__scene.mouseX = self.__scene.mousePos[0]\n self.__scene.mouseY = self.__scene.mousePos[1]\n\n if not self.isQuit:\n pygame.display.update()\n if self.__scene.isFill or self.__fill:\n self.__screen.fill(self.__scene.fillColor)\n self.__fill = False\n\n # 场景调度\n if self.__scene.isEnd:\n sceneNum = self.__scene.nextSceneNum\n nowScene = self.__mapping[sceneNum]\n del self.__scene\n gc.collect()\n if len(nowScene) > 1:\n self.__scene = nowScene[0](self.__screen, self.__config, pygame.time.get_ticks(), self.__mixer,\n self.__console, nowScene[1:])\n else:\n self.__scene = nowScene[0](self.__screen, self.__config, pygame.time.get_ticks(), self.__mixer,\n self.__console)\n self.__scene.super_setup()\n if self.__scene.resetMouse:\n pygame.mouse.set_pos(self.__scene.mouseX, self.__scene.mouseY)\n pygame.mouse.set_visible(self.__scene.mouseVisible)\n if self.__scene.caption is not None:\n self.__appTitle = self.__scene.caption\n pygame.display.set_caption(self.__scene.caption)\n\n def getId(self):\n return self.__Id\n\n# class gameApp:\n# def __init__(self, appTitle, wight, height, isFullScreen, screenMod, colorBits):\n# # 初始化要用到的库\n# pygame.init()\n# pygame.mixer.init()\n#\n# # 初始化App属性\n# self.__Id = id(self)\n# self.__appTitle = appTitle\n# self.__screenWidth = wight\n# self.__screenHeight = height\n# self.__isFullScreen = isFullScreen\n# self.__screenMod = screenMod\n# self.__colorBits = colorBits\n# self.__frameControl = False\n# self.__fill = True\n#\n# from source.config.AppConfig import SceneMap\n# if not SceneMap:\n# raise Exception(\"'SceneMap' is Empty in AppConfig, 'SceneMap' mast have at least one element\")\n# self.__mapping = SceneMap\n#\n# pygame.display.set_caption(appTitle)\n# self.__screen = pygame.display.set_mode((self.__screenWidth, self.__screenHeight), self.__screenMod,\n# self.__colorBits)\n# self.__config = Config()\n# self.__config.readConfig()\n#\n# self.__clock = pygame.time.Clock()\n#\n# self.isQuit = False\n# self.frameRate = self.__config.getFrameRate()\n# if self.frameRate != 0:\n# self.__frameControl = True\n#\n# print(appTitle + '\\n-----控制台-----')\n#\n# self.__scene = self.__mapping[SCENENUM_INIT][0](self.__screen, self.__config, pygame.time.get_ticks())\n#\n# # 创建线程:\n# self.__optLoop = core_thread(1, \"DrawLoop\", 1, lambda: self.__optThread())\n# self.__drawLoop = core_thread(2, \"DrawLoop\", 2, lambda: self.__drawThread())\n# self.__msgLoop = core_thread(3, \"MsgLoop\", 3, lambda: self.__drawThread())\n# self.__sceneLoop = core_thread(4, 'SceneEstablish', 4, lambda: self.__sceneThread())\n#\n# def MainLoop(self):\n# self.__optLoop.start()\n# self.__drawLoop.start()\n# self.__msgLoop.start()\n# self.__sceneLoop.start()\n# self.__optLoop.join()\n# self.__drawLoop.join()\n# self.__msgLoop.join()\n# self.__sceneLoop.join()\n#\n# def __optThread(self):\n# while not self.isQuit:\n# if self.__frameControl:\n# self.__clock.tick(self.frameRate)\n# else:\n# self.__clock.tick()\n# self.__scene.FPS = round(self.__clock.get_fps(), 1)\n#\n# def __drawThread(self):\n# while not self.isQuit:\n# if self.__scene.isFill or self.__fill:\n# self.__screen.fill(self.__scene.fillColor)\n# self.__fill = False\n#\n# # 画屏幕\n# self.__scene.draw()\n# pygame.display.update()\n#\n# def __msgThread(self):\n# while not self.isQuit:\n# self.__scene.doClockEvent(pygame.time.get_ticks())\n#\n# keyPressedList = getNotN(pygame.key.get_pressed(), 0)\n# if keyPressedList:\n# pygame.event.post(pygame.event.Event(25, {\"keyPressedList\": keyPressedList}))\n#\n# for event in pygame.event.get():\n# if event.type == 12: # QUIT\n# pygame.mixer.quit()\n# pygame.quit()\n# self.isQuit = True\n# break\n# elif event.type == 4: # mouseMotion\n# self.__scene.doMouseMotion(event.rel, event.buttons)\n# elif event.type == 5: # mouseDown\n# self.__scene.doMouseButtonDownEvent(event.button)\n# elif event.type == 6: # mouseUp\n# self.__scene.doMouseButtonUpEvent(event.button)\n# elif event.type == 2:\n# self.__scene.doKeyEvent(event.key, event.mod, 0, event.unicode)\n# elif event.type == 3:\n# self.__scene.doKeyEvent(event.key, event.mod, 1)\n# elif event.type == 25:\n# self.__scene.doKeyPressedEvent(event.keyPressedList)\n# if 3 < event.type < 7: # 与鼠标有关的事件\n# self.__scene.lastMousePos = self.__scene.mousePos\n# self.__scene.mousePos = event.pos\n# self.__scene.mouseX = self.__scene.mousePos[0]\n# self.__scene.mouseY = self.__scene.mousePos[1]\n#\n# def __sceneThread(self):\n# while not self.isQuit:\n# if self.__scene.isEnd:\n# sceneNum = self.__scene.nextSceneNum\n# nowScene = self.__mapping[sceneNum]\n# del self.__scene\n# gc.collect()\n# if len(nowScene) > 1:\n# self.__scene = nowScene[0](self.__screen, self.__config, pygame.time.get_ticks(), nowScene[1:])\n# else:\n# self.__scene = nowScene[0](self.__screen, self.__config, pygame.time.get_ticks())\n" }, { "alpha_fraction": 0.53125, "alphanum_fraction": 0.6044560074806213, "avg_line_length": 39.6588249206543, "blob_id": "846270c2c65789dce13ca5a4e2540f5af89b159e", "content_id": "f95bfd40a2acc0a6cfa7a75d794bee55f4e869df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3456, "license_type": "no_license", "max_line_length": 104, "num_lines": 85, "path": "/source/examples/SpringSimulate.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.core.math.Vector import vec2\nfrom source.core.physics.Mass import Mass\nfrom source.core.physics.Spring import Spring\nfrom source.core.physics.SpringMassSystem import SMSystem\nfrom source.view.baseClazz.Scene import Scene\n\n\nclass SpringSimulateScene(Scene):\n def __init__(self, *args):\n super(SpringSimulateScene, self).__init__(*args)\n self.m1, self.m2, self.m3, self.m4 = Mass(40), Mass(40), Mass(40), Mass(40)\n self.m5 = Mass(40)\n self.spring1 = Spring(self.m1, self.m2, 100, 0.2, 1)\n self.spring2 = Spring(self.m1, self.m3, 100, 0.2, 1)\n self.spring3 = Spring(self.m2, self.m4, 100, 0.2, 1)\n self.spring4 = Spring(self.m3, self.m4, 100, 0.2, 1)\n\n self.spring5 = Spring(self.m2, self.m5, 100, 0.2, 1)\n self.spring6 = Spring(self.m4, self.m5, 100, 0.2, 1)\n\n self.target = self.m5\n\n def setup(self):\n self.createTextElement('spring length1:')\n self.createTextElement('spring length2:')\n\n self.m1.local = vec2(100, 100)\n self.m2.local = vec2(200, 100)\n self.m3.local = vec2(100, 200)\n self.m4.local = vec2(200, 200)\n\n self.m5.local = vec2(280, 150)\n\n def draw(self):\n self.Lines((self.spring1.beginMass.local, self.spring1.endMass.local), (255, 255, 255), 1, 0, 1)\n self.Lines((self.spring2.beginMass.local, self.spring2.endMass.local), (255, 0, 0), 1, 0, 1)\n self.Lines((self.spring3.beginMass.local, self.spring3.endMass.local), (0, 255, 0), 1, 0, 1)\n self.Lines((self.spring4.beginMass.local, self.spring4.endMass.local), (0, 0, 255), 1, 0, 1)\n self.Lines((self.spring5.beginMass.local, self.spring5.endMass.local), (0, 255, 255), 1, 0, 1)\n self.Lines((self.spring6.beginMass.local, self.spring6.endMass.local), (255, 0, 255), 1, 0, 1)\n self.Circle((self.target.local.x, self.target.local.y, 1), (255, 255, 0), 1)\n\n def doClockEvent(self, NowClock):\n self.spring1.execute()\n self.spring2.execute()\n self.spring3.execute()\n self.spring4.execute()\n self.spring5.execute()\n self.spring6.execute()\n\n self.getCreatedElement(0).setText(\n 'spring length1:' + str(self.spring1.endMass.local.dist(self.spring1.beginMass.local)))\n self.getCreatedElement(1).setText(\n 'spring length2:' + str(self.spring2.endMass.local.dist(self.spring2.beginMass.local)))\n\n # def doMouseButtonDownEvent(self, Button):\n # self.spring.endMass.local += vec2(100, 0)\n\n def doMouseMotion(self, MouseRel, Buttons):\n if Buttons == (1, 0, 0):\n self.target.local.x += MouseRel[0]\n self.target.local.y += MouseRel[1]\n\n\nclass SpringMassSystemTestScene(Scene):\n def __init__(self, *args):\n super(SpringMassSystemTestScene, self).__init__(*args)\n self.springMassSys = SMSystem(10,\n 2.0,\n 0.9, 40, 0.2,\n vec2(0, 0.098),\n 2, 2, 1, 2, 700)\n\n def setup(self):\n self.springMassSys.createModel()\n self.springMassSys.setConnections((0, vec2(0, 0)))\n\n def draw(self):\n self.Lines(self.springMassSys.getLocal(), (255, 255, 255), 1, 0, 1)\n\n def doClockEvent(self, NowClock):\n self.springMassSys.simulate()\n\n def doMouseButtonDownEvent(self, Button):\n self.springMassSys.execute()\n" }, { "alpha_fraction": 0.5702479481697083, "alphanum_fraction": 0.5702479481697083, "avg_line_length": 19.16666603088379, "blob_id": "d0bb5c57fff1e32b738e0b5cc1a7cdf47be6f643", "content_id": "24985c6c1b81c58d8096e921bba30fe5677a7a27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 121, "license_type": "no_license", "max_line_length": 31, "num_lines": 6, "path": "/source/core/component/Window.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "class Window:\n def __init__(self, window):\n self.window = window\n\n def changeSize(self, size):\n pass\n" }, { "alpha_fraction": 0.47607553005218506, "alphanum_fraction": 0.5034786462783813, "avg_line_length": 32.379146575927734, "blob_id": "3b5083875332f8d37b04fcca8d4630969c906ed5", "content_id": "85599eb2de474e53b8fbc1672463e47979f9b1c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7501, "license_type": "no_license", "max_line_length": 97, "num_lines": 211, "path": "/source/core/assembly/Painter.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import pygame\n\n__all__ = [\n 'Painter',\n]\n\nfrom source.core.component.Transform import Transform\nfrom source.core.math.Vector import vec3\n\n\nclass Painter(Transform):\n \"\"\"将pygame.draw包装,可直接绘制Shape类型的图形,方便框架使用\n\n 因为使用pygame.draw,在线框模式下如果开启抗锯齿则width参数的值固定为1\n\n 绘制圆和椭圆时,抗锯齿无效\"\"\"\n\n def __init__(self, surf, onSurf=False):\n super().__init__()\n self.s = surf\n self.on = onSurf\n\n def Pixel(self, p, color):\n \"\"\"\n 绘制一个像素点\n\n :param p: Math2d::vec2 or Math2d::point2\n :param color: tuple (R, G, B)\n :return: None\n \"\"\"\n\n v = super().getCurrentMat().mul_vec3(vec3(p.x, p.y, 1))\n self.s.set_at([int(v.x + 0.5), int(v.y + 0.5)], color)\n\n def Line(self, line, color, width, aa=0):\n \"\"\"\n 绘制直线\n\n :param line: Shape::Line\n :param color: tuple (R, G, B)\n :param width: int 线宽\n :param aa: bool 是否抗锯齿\n :return: None\n \"\"\"\n raise Exception('暂时废除,请使用Lines')\n # sv = super().getCurrentMat().mul_vec3(vec3(line.pos.x, line.pos.y, 1))\n # sp = (int(sv.x), int(sv.y))\n # eps = line.dir.setLen(line.length)\n # # ev = super().getCurrentMat().mul_vec3(vec3(eps, 1))\n # # ep = (sp[0] + int(ev.x), sp[1] + int(ev.y))\n # ep = (sp[0] + int(eps.x), sp[1] + int(eps.y))\n # if aa:\n # pygame.draw.aaline(self.s, color, sp, ep, 1)\n # else:\n # pygame.draw.line(self.s, color, sp, ep, width)\n\n def Lines(self, points, color, width, closed, aa=0):\n \"\"\"\n 绘制连续的直线\n\n :param points: list len >= 2 if len < 2 ret\n :param color: tuple (R, G, B)\n :param width: int 线宽\n :param closed: bool 是否闭合\n :param aa: bool 是否抗锯齿\n :return: None\n \"\"\"\n sp, ep = None, None\n length = len(points)\n if length < 2:\n return\n for i in range(0, length - 1):\n p0, p1 = points[i], points[i + 1]\n _p0, _p1 = (int(p0[0] + 0.5), int(p0[1] + 0.5)), (int(p1[0] + 0.5), int(p1[1] + 0.5))\n v0 = super().getCurrentMat().mul_vec3(vec3(_p0[0], _p0[1], 1))\n v1 = super().getCurrentMat().mul_vec3(vec3(_p1[0], _p1[1], 1))\n if i == 0:\n sp = v0\n if i == length - 2:\n ep = v1\n if aa:\n pygame.draw.aaline(self.s, color, (v0.x, v0.y), (v1.x, v1.y), 1)\n else:\n pygame.draw.line(self.s, color, (v0.x, v0.y), (v1.x, v1.y), width)\n if closed:\n if aa:\n pygame.draw.aaline(self.s, color, (sp.x, sp.y), (ep.x, ep.y), 1)\n else:\n pygame.draw.line(self.s, color, (sp.x, sp.y), (ep.x, ep.y), width)\n\n def Arc(self, rect, start_angle, stop_angle, color, width):\n \"\"\"\n 绘制一条曲线\n\n :param color: tuple (R, G, B)\n :param rect: Shape::Rectangle 指定弧线所在的椭圆外围的限定矩形\n :param start_angle: angle 指定弧线的开始角度\n :param stop_angle: angle 指定弧线的结束角度\n :param width: int 线宽\n :return: None\n \"\"\"\n v = super().getCurrentMat().mul_vec3(vec3(rect.x, rect.y, 1))\n _rect = (int(v.x + 0.5), int(v.y + 0.5), int(rect.w + 0.5), int(rect.h + 0.5))\n pygame.draw.arc(self.s, color, _rect, start_angle, stop_angle, width)\n\n def Rect(self, rect, color, width, aa=0):\n \"\"\"\n 绘制矩形\n\n :param rect: Shape::Rectangle\n :param color: tuple (R, G, B)\n :param width: int 线宽 0表示填充\n :param aa: bool 是否抗锯齿\n :return: None\n \"\"\"\n v = super().getCurrentMat().mul_vec3(vec3(rect.x, rect.y, 1))\n _rect = (int(v.x + 0.5), int(v.y + 0.5), int(rect.w + 0.5), int(rect.h + 0.5))\n if width == 0:\n pygame.draw.rect(self.s, color, _rect, 0)\n if aa:\n points = rect.array()\n self.Lines(points, color, 1, 1, 1)\n else:\n points = rect.array()\n self.Lines(points, color, width, 1, aa)\n\n def Triangle(self, triangle, color, width, aa):\n \"\"\"\n 绘制一个三角形\n\n :param triangle: Shape::Triangle\n :param color: tuple (R, G, B)\n :param width: int 线宽 0表示填充\n :param aa: bool 是否抗锯齿\n :return: None\n \"\"\"\n v1 = super().getCurrentMat().mul_vec3(vec3(triangle.p1, 1))\n v2 = super().getCurrentMat().mul_vec3(vec3(triangle.p2, 1))\n v3 = super().getCurrentMat().mul_vec3(vec3(triangle.p3, 1))\n points = [v1.ex_vec2(), v2.ex_vec2(), v3.ex_vec2()]\n self.Polygon(points, color, width, aa)\n\n def Polygon(self, points, color, width, aa=0):\n \"\"\"\n 绘制一个多边形\n\n :param points: list [Math2d::vec2] or [Math2d::point2], and len >= 3 else ret\n :param color: tuple (R, G, B)\n :param width: int 线宽 0表示填充\n :param aa: bool 是否抗锯齿\n :return: None\n \"\"\"\n if len(points) < 3:\n return\n\n _points = []\n for p in points:\n v = super().getCurrentMat().mul_vec3(vec3(p, 1))\n _points.append((int(v.x + 0.5), int(v.y + 0.5)))\n\n pygame.draw.polygon(self.s, color, _points, width)\n\n if width == 0 and aa:\n self.Lines(_points, color, 1, 1, 1)\n\n def Circle(self, circle, color, width, aa=0):\n \"\"\"\n 绘制一个圆\n\n :param circle: Shape::Circle\n :param color: tuple (R, G, B)\n :param width: int 线宽 0表示填充\n :param aa: bool 是否抗锯齿\n :return: None\n \"\"\"\n if isinstance(circle, list) or isinstance(circle, tuple):\n pos = (int(circle[0] + 0.5), int(circle[1] + 0.5))\n radius = int(circle[2] + 0.5)\n else:\n pos = (int(circle.x + 0.5), int(circle.y + 0.5))\n radius = int(circle.r + 0.5)\n _pos = super().getCurrentMat().mul_vec3(vec3(pos[0], pos[1], 1))\n if self.on:\n temp = pygame.Surface((radius * 2, radius * 2)).convert_alpha()\n if len(color) > 3:\n temp.set_alpha(color[3])\n pygame.draw.circle(temp, color, (radius, radius), radius, width)\n self.s.blit(temp, (_pos[0] - radius, _pos[1] - radius))\n else:\n pygame.draw.circle(self.s, color, _pos.ary(4), radius, width)\n\n def Ellipse(self, ellipse, color, width, aa=0):\n \"\"\"\n 绘制一个椭圆\n\n :param ellipse: Shape::Ellipse\n :param color: tuple (R, G, B)\n :param width: int 线宽 0表示填充\n :param aa: bool 是否抗锯齿\n :return: None\n \"\"\"\n v = super().getCurrentMat().mul_vec3(vec3(ellipse.x, ellipse.y, 1))\n rect = (v.x - ellipse.a, v.y - ellipse.b, ellipse.a * 2, ellipse.b * 2)\n if self.on:\n temp = pygame.Surface((ellipse.a * 2, ellipse.b * 2)).convert_alpha()\n if len(color) > 3:\n temp.set_alpha(color[3])\n pygame.draw.ellipse(temp, color, temp.get_rect(), width)\n self.s.blit(temp, (v.x - ellipse.a, v.y - ellipse.b))\n else:\n pygame.draw.ellipse(self.s, color, rect, width)\n" }, { "alpha_fraction": 0.49514561891555786, "alphanum_fraction": 0.529819667339325, "avg_line_length": 22.010639190673828, "blob_id": "d232a725d6894a85ba2b45d367f7cd12792c1631", "content_id": "faf9de9e9f7802b5a7b4078b93b523c471aede58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2369, "license_type": "no_license", "max_line_length": 117, "num_lines": 94, "path": "/source/core/math/MathUtil.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from math import cos, pi\n\n__all__ = [\n 'signal', 'constrain', 'mapping',\n 'interpolation_lin', 'interpolation_cos', 'interpolation_cubic', 'interpolation_hermite', 'interpolation_hermite'\n]\n\n\ndef signal(e):\n \"\"\"\n 信号函数,如果是0则返回0,正数返回1,负数返回-1\n :param int or float:\n :return int:\n \"\"\"\n if e == 0:\n return 0\n if e < 0:\n return -1\n if e > 0:\n return 1\n\n\ndef constrain(x, low, high):\n \"\"\"\n 限制一个数字于最低值与最高值之间\n\n :param x: 数字\n :param low: 最低值\n :param high: 最高值\n :return: number\n \"\"\"\n return max(min(x, high), low)\n\n\ndef mapping(n, start1, stop1, start2, stop2, withinBounds=True):\n \"\"\"\n 从一个范围内映射一个数字去另一个范围\n\n :param n: 要映射的数字\n :param start1: 范围1开始\n :param stop1: 范围1结束\n :param start2: 范围2开始\n :param stop2: 范围2结束\n :param withinBounds: 是否限制在新范围的最高值和最低值之间\n :return: number\n \"\"\"\n newVal = (n - start1) / (stop1 - start1) * (stop2 - start2) + start2\n if not withinBounds:\n return newVal\n if start2 < stop2:\n return constrain(newVal, start2, stop2)\n else:\n return constrain(newVal, stop2, start2)\n\n\ndef interpolation_lin(a, b, amt):\n return amt * (b - a) + a\n\n\ndef interpolation_cos(a, b, amt):\n _amt = (1 - cos(amt * pi)) / 2\n return _amt * (b - a) + a\n\n\ndef interpolation_cubic(a, b, c, d, amt):\n \"\"\" b: great than a less then c\n\n c: less than d great than b\"\"\"\n _amt = amt * amt\n _a = d - c - a + b\n _b = a - b - _a\n _c = c - a\n _d = b\n return _a * _amt * amt + _b * _amt + _c * amt + _d\n\n\ndef interpolation_hermite(a, b, c, d, amt, tension, bias):\n \"\"\"tension: 1 is high, 0 is normal, -1 is\n\n low,bias: 0 is even, positive is towards first segment, negative towards the other\"\"\"\n _amt0 = amt * amt\n _amt1 = _amt0 * amt\n\n m0 = (b - a) * (1 + bias) * (1 - tension) / 2\n m0 += (c - b) * (1 - bias) * (1 - tension) / 2\n m1 = (c - b) * (1 + bias) * (1 - tension) / 2\n m1 += (d - c) * (1 - bias) * (1 - tension) / 2\n\n _a = 2 * _amt1 - 3 * _amt0 + 1\n _b = _amt1 - 2 * _amt0 + amt\n _c = _amt1 - _amt0\n _d = -2 * _amt1 + 3 * _amt0\n\n return _a * b + _b * m0 + _c * m1 + _d * c\n" }, { "alpha_fraction": 0.51039057970047, "alphanum_fraction": 0.5113921165466309, "avg_line_length": 41.036842346191406, "blob_id": "890221d6327dc6af6f17d916f2756f279e42c2d5", "content_id": "18dc4604635007814b6b53b0edd00117c5c97500", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8086, "license_type": "no_license", "max_line_length": 146, "num_lines": 190, "path": "/source/core/render/GameObjRender.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "\"\"\"\nsgf-py game object render\n\nElement, Actor, 统称为gameObject\n\"\"\"\nimport time\n\nfrom source.core.const.Const import gl_LogPath\nfrom source.core.dataStructure.TopologicalSort import AOVNet, Node\nfrom source.view.baseClazz.Sprite import Sprite\nfrom source.view.baseClazz.Actor import Actor\nfrom source.view.baseClazz.Element import Element\n\n\nclass gameObjRender:\n \"\"\"在添加完毕后调用close()方法,然后才能渲染,下次添加时需调用open()方法\n\n 如果出现异常,可调用getLog方法查看记录日志\"\"\"\n\n def __init__(self):\n self.__renderDict = {}\n self.__flag_add = True\n self.__sortedList = []\n self.__sortedRevList = []\n self.__objList = []\n self.__flag_record = True\n\n self.__log = 'Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S \", time.localtime()) + \\\n self.__class__.__name__ + ' be created\\n'\n # # self.__logFile = open(gl_LogPath + 'render.log', 'a')\n # # self.__logFile.write(self.__log)\n\n # def __del__(self):\n # self.__logFile.close()\n\n def __sortKey(self):\n temp = sorted(self.__renderDict.items(), key=lambda a: a[0])\n self.__sortedList.clear()\n for tr in temp:\n for e in tr[1]:\n self.__sortedList.append(e)\n # for e in reversed(self.__sortedList):\n # if e.active:\n # self.__sortedRevList.append(e)\n self.__sortedRevList = list(reversed(self.__sortedList))\n\n def add(self, *args):\n if not self.__flag_add:\n self.__log += 'Render Log Error: render closed, please use open() function open render before do this, add ' + str(args) + ' failed\\n'\n # self.__logFile.write('Render Log Error: render closed, add ' + str(args) + ' failed\\n')\n else:\n self.__log += 'Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' add start\\n'\n # self.__logFile.write('Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' add\n # start\\n')\n self.__add(*args)\n self.__log += 'Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' add finished\\n'\n # self.__logFile.write(\n # 'Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' add finished\\n')\n\n def remove(self, *args):\n if not self.__flag_add:\n self.__log += 'Render Log Error: render closed, remove ' + str(args) + ' failed\\n'\n # self.__logFile.write('Render Log Error: render closed, remove ' + str(args) + ' failed\\n')\n else:\n self.__log += 'Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' remove start\\n'\n # self.__logFile.write(\n # 'Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' remove start\\n')\n self.__remove(*args)\n self.__log += 'Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' remove finished\\n'\n # self.__logFile.write(\n # 'Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' remove finished\\n')\n\n def update(self, index, *args):\n if not self.__flag_add:\n self.__log += 'Render Log Error: render closed, update ' + str(args) + ' failed\\n'\n # self.__logFile.write('Render Log Error: render closed, update ' + str(args) + ' failed\\n')\n else:\n self.__log += 'Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' update start\\n'\n # self.__logFile.write(\n # 'Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' update start\\n')\n self.__update(index, *args)\n self.__log += 'Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' update finished\\n'\n # self.__logFile.write(\n # 'Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' update finished\\n')\n\n def clear(self):\n self.__sortedRevList.clear()\n self.__sortedList.clear()\n self.__log += 'Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' clear\\n'\n\n def __add(self, *args):\n if len(args) == 1:\n x = args[0]\n if isinstance(x, Element) or isinstance(x, Actor) or isinstance(x, Sprite):\n z = x.zIndex\n if z in self.__renderDict.keys():\n self.__renderDict[x.zIndex].append(x)\n else:\n self.__renderDict[x.zIndex] = [x]\n elif isinstance(x, list) or isinstance(x, tuple):\n for e in x:\n self.__add(e)\n else:\n self.__log += 'Render Log Error: ' + x.__class__.__name__ + ' is ' + str(\n x.__class__) + ' cant insert render record list\\n'\n # # self.__logFile.write(\n # 'Render Log Error: ' + x.__class__.__name__ + ' is ' + str(\n # x.__class__) + ' cant insert render record list\\n')\n else:\n for e in args:\n self.__add(e)\n\n def __remove(self, index, *args):\n if len(args) == 1:\n x = args[0]\n if isinstance(x, list) or isinstance(x, tuple):\n self.__remove(index, x)\n try:\n self.__renderDict[index].remove(x)\n except ValueError:\n self.__log += 'Render Log Error: remove value error ' + x.__class__.__name__ + ' \\n'\n # # self.__logFile.write('Render Log Error: remove value error ' + x.__class__.__name__ + ' \\n')\n except KeyError:\n self.__log += 'Render Log Error: remove index error ' + index + ' \\n'\n # # self.__logFile.write('Render Log Error: index error remove ' + index + ' \\n')\n else:\n for e in args:\n self.__remove(e)\n\n def __update(self, index, *args):\n self.__remove(index, *args)\n self.__add(*args)\n\n def close(self):\n if self.__flag_add:\n self.__sortKey()\n self.__flag_add = False\n self.__log += 'Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' close\\n'\n # # self.__logFile.write('Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' close\\n')\n # # self.__logFile.close()\n\n # def closeLog(self):\n # # self.__logFile.write(\n # 'Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S \", time.localtime())\n # + self.__class__.__name__ + ' be closed\\n')\n # # self.__logFile.close()\n\n def open(self):\n # # self.__logFile = open(gl_LogPath + 'render.log', 'a')\n self.__flag_add = True\n self.__flag_record = True\n self.__log += 'Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' open\\n'\n # # self.__logFile.write('Render Log: ' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + ' open\\n')\n\n def clearLog(self):\n self.__log = ''\n\n def getLog(self):\n return self.__log\n\n def renderList(self):\n return self.__sortedList\n\n def eventHandingList(self):\n return self.__sortedRevList\n\n def render(self, sur):\n if not self.__flag_add:\n for e in self.__sortedList:\n if e.visual:\n e.draw(sur)\n elif self.__flag_record:\n self.__log += 'Render Log Error: should close before render\\n'\n # self.__logFile.write('Render Log Error: should close before render\\n')\n self.__flag_record = False\n\n\nclass gameObjectRender0:\n def __init__(self):\n self.__objectAOVNet = AOVNet()\n self.__max = 0\n\n def add(self, obj):\n if not isinstance(Element, obj):\n return\n\n def __add(self, _id, obj):\n zIndex = obj.zIndex\n self.__max = zIndex if zIndex > self.__max else self.__max\n self.__objectAOVNet.insert(_id, Node(obj))\n\n" }, { "alpha_fraction": 0.4293670952320099, "alphanum_fraction": 0.4673417806625366, "avg_line_length": 21.965116500854492, "blob_id": "4639c426f0769d2b385075566aa8043aef7dab47", "content_id": "37042de6c111cc352c1776b3e35f78ba296bce3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1975, "license_type": "no_license", "max_line_length": 72, "num_lines": 86, "path": "/source/core/math/Noise.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import math\nimport random\n\nfrom source.core.math.MathConst import PI\n\nPERLIN_YWRAPB = 4\nPERLIN_YWRAP = 1 << PERLIN_YWRAPB\nPERLIN_ZWRAPB = 8\nPERLIN_ZWRAP = 1 << PERLIN_ZWRAPB\nPERLIN_SIZE = 4095\n\nperlin_octaves = 4\nperlin_amp_falloff = 0.5\n\n\ndef scaled_cosine(i):\n return 0.5 * (1.0 - math.cos(i * PI))\n\n\nperlin = []\n\n\ndef noise(x, y=0, z=0):\n if len(perlin) == 0:\n for i in range(0, PERLIN_SIZE + 1):\n perlin.append(random.uniform(0, 1))\n _x = x if x > 0 else -x\n _y = y if y > 0 else -y\n _z = z if z > 0 else -z\n\n _xi = math.floor(_x)\n _yi = math.floor(_y)\n _zi = math.floor(_z)\n\n _xf = _x - _xi\n _yf = _y - _yi\n _zf = _z - _zi\n\n r, ampl = 0, 0.5\n\n for o in range(0, perlin_octaves):\n of = _xi + (_yi << PERLIN_YWRAPB) + (_zi << PERLIN_ZWRAPB)\n rxf = scaled_cosine(_xf)\n ryf = scaled_cosine(_yf)\n\n n1 = perlin[of & PERLIN_SIZE]\n n1 += rxf * (perlin[(of + 1) & PERLIN_SIZE] - n1)\n n2 = perlin[(of + PERLIN_YWRAP) & PERLIN_SIZE]\n n2 += rxf * (perlin[(of + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n2)\n n1 += ryf * (n2 - n1)\n\n of += PERLIN_ZWRAP\n n2 = perlin[of & PERLIN_SIZE]\n n2 += rxf * (perlin[(of + 1) & PERLIN_SIZE] - n2)\n n3 = perlin[(of + PERLIN_YWRAP) & PERLIN_SIZE]\n n3 += rxf * (perlin[(of + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n3)\n n2 += ryf * (n3 - n2)\n\n n1 += scaled_cosine(_zf) * (n2 - n1)\n\n r += n1 * ampl\n ampl *= perlin_amp_falloff\n _xi <<= 1\n _xf *= 2\n _yi <<= 1\n _yf *= 2\n _zi <<= 1\n _zf *= 2\n\n if _xf >= 1.0:\n _xi += 1\n _xf -= 1\n if _yf >= 1.0:\n _yi += 1\n _yf -= 1\n if _zf >= 1.0:\n _zi += 1\n _zf -= 1\n\n return r\n\n# def noiseDetail(lod, falloff):\n# if lod > 0:\n# perlin_octaves = lod\n# if falloff > 0:\n# perlin_amp_falloff = falloff\n" }, { "alpha_fraction": 0.508249044418335, "alphanum_fraction": 0.6146886348724365, "avg_line_length": 44.82926940917969, "blob_id": "b08f971053970d681fe11ac45a7a3c48b9d5aa8b", "content_id": "070053ea58c78fa57947d725af8f13fa31c888ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1879, "license_type": "no_license", "max_line_length": 92, "num_lines": 41, "path": "/source/examples/TestPainter.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import math\nimport random\n\nfrom source.core.math.MathConst import PI\nfrom source.core.math.Shape import Line, Rectangle, Triangle, Circle, Ellipse, Ray\nfrom source.core.math.Vector import vec2, point2\nfrom source.core.assembly.Painter import Painter\nfrom source.view.baseClazz.Scene import Scene\n\n\nclass TestPainterScene(Scene):\n def __init__(self, screen, config, startClock):\n super(TestPainterScene, self).__init__(screen, config, startClock)\n self.painter = Painter(self.screen)\n self.points = []\n for i in range(0, 6):\n x = random.randint(0, 800)\n y = random.randint(0, 400)\n self.points.append(vec2(x, y))\n self.rect = Rectangle(400, 100, 200, 100)\n self.line = Ray(vec2(200, 200), math.radians(30), 400)\n self.white = (255, 255, 255)\n self.tra = Triangle(point2(100, 100), point2(60, 180), point2(140, 180))\n self.circle = Circle(400, 300, 100)\n self.ellipse = Ellipse(400, 300, 160, 70)\n\n def draw(self):\n # self.painter.Pixel(point2(700, 500), self.white)\n # self.painter.Triangle(self.tra, self.white, 0, 1)\n # self.painter.Rect(self.rect, self.white, 0, 1)\n # self.painter.Circle(self.circle, (255, 255, 255), 1)\n # self.painter.Ellipse(self.ellipse, self.white, 1)\n self.painter.Lines(self.points, (255, 255, 255), 1, 1, 1)\n # self.painter.Line(self.line, (255, 255, 255), 1, 0)\n # self.painter.Lines((point2(200, 200), point2(400, 400)), (255, 255, 255), 1, 0, 1)\n self.painter.push()\n self.painter.scale(self.points[0].x, self.points[0].y, 0.5, 0.5)\n self.painter.Lines(self.points, (255, 0, 0), 1, 1, 1)\n # self.painter.Lines((point2(200, 200), point2(400, 400)), (255, 0, 0), 1, 0, 1)\n self.painter.pop()\n # self.painter.Line(self.line, (255, 0, 0), 1, 0)\n" }, { "alpha_fraction": 0.6544901132583618, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 35.5, "blob_id": "1702d50cc16f0f030637cce99571f063c30efb53", "content_id": "033706e704177547d01393f85d9f7a60af452fee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1314, "license_type": "no_license", "max_line_length": 120, "num_lines": 36, "path": "/source/core/assembly/Config.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.core.const.Const import GLC_INI_NAME, GLC_INI_SECTION_DRAW, GLC_INI_PARAM_ANTIALIAS, GLC_INI_SECTION_WAVE, \\\n GLC_INI_PARAM_BGMVOLUME, GLC_INI_PARAM_SOUNDVOLUME, GLC_INI_PARAM_FRAMERATE\nfrom source.util.ToolsFuc import readINIBool, readINIFloat, readINIInt\n\n\nclass Config:\n def __init__(self):\n self.TextAntiAlias = None\n self.VolumeBGM = None\n self.VolumeSound = None\n self.FrameRate = None\n self.path = GLC_INI_NAME\n\n def readConfig(self):\n self.TextAntiAlias = readINIBool(self.path, GLC_INI_SECTION_DRAW, GLC_INI_PARAM_ANTIALIAS)\n self.VolumeBGM = readINIFloat(self.path, GLC_INI_SECTION_WAVE, GLC_INI_PARAM_BGMVOLUME)\n self.VolumeSound = readINIFloat(self.path, GLC_INI_SECTION_WAVE, GLC_INI_PARAM_SOUNDVOLUME)\n self.FrameRate = readINIInt(self.path, GLC_INI_SECTION_DRAW, GLC_INI_PARAM_FRAMERATE)\n\n def getTextAntiAlias(self):\n return self.TextAntiAlias\n\n def getVolumeBGM(self):\n return self.VolumeBGM * 0.1\n\n def getVolumeSound(self):\n return self.VolumeSound * 0.1\n\n def getFrameRate(self):\n if self.FrameRate == 0:\n return 0\n # if self.FrameRate < 30:\n # return 30\n if self.FrameRate > 120:\n return 120\n return self.FrameRate\n" }, { "alpha_fraction": 0.6169154047966003, "alphanum_fraction": 0.618573784828186, "avg_line_length": 36.6875, "blob_id": "91783a4695991af71935a67169463ea8c22a7095", "content_id": "3611204ae509db90f918c48e5b01c3a45ea96ff9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2416, "license_type": "no_license", "max_line_length": 114, "num_lines": 64, "path": "/source/core/assembly/XmlOperator.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "# from xml.dom.minidom import parse\nimport xml.dom.minidom\n\nfrom source.core.const.Const import DATATYPE_STR_BOOL, DATATYPE_STR_INT, DATATYPE_STR_STR, DATATYPE_STR_COMPLEX, \\\n DATATYPE_STR_FLOAT\n\n\nclass SceneNotException(Exception):\n def __init__(self, name):\n self.name = name\n\n def __str__(self):\n return str(\"Scene Class \\'\" + self.name + \"\\' not found\")\n\n\nclass XMLOperator:\n def __init__(self, path):\n self.__path = path\n self.__DOMTree = xml.dom.minidom.parse(self.__path)\n self.__collection = self.__DOMTree.documentElement\n\n\ndef ret_init_global_sceneList(path) -> list:\n _lis = []\n DOMTree = xml.dom.minidom.parse(path)\n collection = DOMTree.documentElement\n path_collection = collection.getElementsByTagName('baseclass-path')\n paths = path_collection[0].getElementsByTagName('path')\n for p in paths:\n if p.getAttribute('type') == 'scene':\n _lis.append((p.getAttribute('value')))\n path_collection = collection.getElementsByTagName('subclass-path')\n paths = path_collection[0].getElementsByTagName('path')\n for p in paths:\n if p.getAttribute('type') == 'scene':\n _lis.append((p.getAttribute('value')))\n return _lis\n\n\ndef loadSceneFormConfig(sceneNum):\n str_sceneNum = str(sceneNum)\n DOMTree = xml.dom.minidom.parse(\"F:/练习/PyCharm/PygameTest/framework-config/app-config.xml\")\n collection = DOMTree.documentElement\n registeredScene_collection = collection.getElementsByTagName('registered-scene')\n rgs = registeredScene_collection[0].getElementsByTagName('scene')\n class_str = ''\n param_list = []\n for s in rgs:\n if s.getAttribute('scene-num') == str_sceneNum:\n class_str = s.getAttribute('class-string')\n params = s.getElementsByTagName('param')\n for p in params:\n _type = p.getAttribute('type')\n _val = p.childNodes[0].data\n if _type == DATATYPE_STR_BOOL or _type == DATATYPE_STR_INT:\n param_list.append(int(_val))\n elif _type == DATATYPE_STR_FLOAT:\n param_list.append(float(_val))\n elif _type == DATATYPE_STR_STR:\n param_list.append(_val)\n elif _type == DATATYPE_STR_COMPLEX:\n param_list.append(complex(_val))\n break\n return class_str, param_list\n" }, { "alpha_fraction": 0.5071886777877808, "alphanum_fraction": 0.5452333688735962, "avg_line_length": 32.488887786865234, "blob_id": "b24ee029f4035d9914ddc844f70db0c4b1cce1ec", "content_id": "ef2973cdc199709762808ccee17d3944806e7e3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4529, "license_type": "no_license", "max_line_length": 102, "num_lines": 135, "path": "/source/examples/noiseTest.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import math\nimport random\n\nimport pygame\n\nfrom source.core.const.Const import gl_Font\nfrom source.core.assembly.Painter import Painter\nfrom source.core.math.MathConst import PI_DOUBLE\nfrom source.core.math.MathUtil import mapping\nfrom source.core.math.Vector import vec2, point2\nfrom source.core.math.Noise import noise\nfrom source.core.math.Shape import Circle\nfrom source.view.baseClazz.Scene import Scene\nfrom source.view.element.Elements import TextElement\n\n\nclass Particle:\n def __init__(self, width, height):\n self.w, self.h = width, height\n self.pos = vec2(random.randint(0, width), random.randint(0, height))\n self.vel, self.acc, self.prevPos = vec2(), vec2(), vec2()\n self.maxSpeed = 2\n\n def update(self):\n self.prevPos = self.pos\n self.vel += self.acc\n self.vel.limit(self.maxSpeed)\n self.pos += self.vel\n self.acc = self.acc.mul(0)\n\n def follow(self, scl, cols, vectors):\n x = math.floor(self.pos.x / scl)\n y = math.floor(self.pos.y / scl)\n index = x + y * cols\n try:\n force = vectors[index]\n self.applyForce(force)\n except IndexError:\n pass\n\n def applyForce(self, force):\n self.acc += force\n\n def show(self, surface):\n # Painter(surface).Pixel(self.pos, (255, 255, 255))\n Painter(surface, True).Circle(Circle(self.pos, 1), (0, 0, 0, 50), 0)\n self.edgesPrev()\n # pygame.draw.circle(surface, (255, 255, 255, 100), (int(self.pos.x), int(self.pos.y)), 2, 0)\n\n def edgesPrev(self):\n self.prevPos.x = self.pos.x\n self.prevPos.y = self.pos.y\n\n def edges(self):\n if self.pos.x > self.w:\n self.pos.x = 0\n self.edgesPrev()\n if self.pos.x < 0:\n self.pos.x = self.w\n self.edgesPrev()\n if self.pos.y > self.h:\n self.pos.y = 0\n self.edgesPrev()\n if self.pos.y < 0:\n self.pos.y = self.h\n self.edgesPrev()\n\n\nclass noiseTestScene(Scene):\n def __init__(self, *args):\n super(noiseTestScene, self).__init__(*args)\n self.caption = 'Perlin Noise'\n self.sceneCanvas = pygame.Surface((800, 600))\n self.sceneCanvas.fill((255, 255, 255))\n self.noiseScale = 0.02\n self._height, self._width = 600, 800\n self.inc = 0.1\n self.scl = 10\n self.zoff = 0\n self.cols, self.rows = math.floor(self._width / self.scl), math.floor(self._height / self.scl)\n self.particles = []\n self.flowField = [vec2()] * (self.cols * self.rows)\n for i in range(0, 2500):\n self.particles.append(Particle(self._width, self._height))\n\n # 噪音测试1\n def draw(self):\n for x in range(0, 800):\n noiseVal = noise((self.mouseX + x) * self.noiseScale, self.mouseY * self.noiseScale)\n Painter(self.screen).Lines([point2(x, self.mouseY + noiseVal * 80), point2(x, 600)],\n (noiseVal * 255, noiseVal * 255, noiseVal * 255), 1, 0)\n\n # def draw(self):\n # yoff = 0\n # for y in range(0, self.rows):\n # xoff = 0\n # for x in range(0, self.cols):\n # index = x + y * self.cols\n # angle = noise(xoff, yoff, self.zoff) * PI_DOUBLE * 4\n # v = vec2.fromAngle(angle)\n # v.setLen(1)\n # self.flowField[index] = v\n # xoff += self.inc\n # # line = Line(point2(x * self.scl, y * self.scl), v.orient(), 10)\n # # Painter(self.sceneCanvas).Line(line, (255, 255, 255), 1, 1)\n #\n # yoff += self.inc\n # self.zoff += 0.0003\n #\n # for p in self.particles:\n # p.follow(self.scl, self.cols, self.flowField)\n # p.update()\n # p.edges()\n # p.show(self.sceneCanvas)\n #\n # self.screen.blit(self.sceneCanvas, (0, 0))\n\n\nclass noise1DScene(Scene):\n def __init__(self, *args):\n super(noise1DScene, self).__init__(*args)\n\n self.pixies = list()\n\n def setup(self):\n for i in range(0, self.width, 20):\n y = mapping(noise(10), 0, 1, 0, 600)\n self.pixies.append(point2(i - 1, y))\n self.pixies.append(point2(i, 300))\n # self.pixies.append(point2(i + 1, y))\n\n def draw(self):\n self.Lines(self.pixies, (255, 255, 255), 1, 0, 1)\n # for p in self.pixies:\n # self.Pixel(p, (255, 255, 255))\n" }, { "alpha_fraction": 0.48529016971588135, "alphanum_fraction": 0.5058839321136475, "avg_line_length": 25.33098602294922, "blob_id": "5001944da5abbaa7b7ceb261714ddceb24b52779", "content_id": "941b4ddfc8efcd8ac02b43e4ec133c8d65dec335", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7600, "license_type": "no_license", "max_line_length": 108, "num_lines": 284, "path": "/source/core/math/Shape.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from math import pi\n\nfrom source.core.math.Matrix import dtm2\nfrom source.core.math.Vector import vec2, point2\n\n\nclass Shape:\n def contains(self, point) -> bool:\n pass\n\n def intersects(self, shape) -> bool:\n pass\n\n def same(self, shape) -> bool:\n pass\n\n def area(self):\n pass\n\n def girth(self):\n pass\n\n def left(self):\n pass\n\n def right(self):\n pass\n\n def top(self):\n pass\n\n def bottom(self):\n pass\n\n def barycenter(self):\n pass\n\n def doubleRange(self):\n pass\n\n def rebuildForBarycenter(self, point):\n pass\n\n\nclass Line(Shape):\n def __init__(self, x1, y1, x2, y2):\n if isinstance(x1, vec2):\n self.__init__(x1.x, x1.y, y1.x, y1.y)\n else:\n self.point1 = point2(x1, y2)\n self.point2 = point2(x2, y2)\n\n\nclass Ray(Shape):\n def __init__(self, x, y, angle=0, length=0):\n if isinstance(x, vec2):\n self.__init__(x.x, x.y, y, angle)\n else:\n self.pos = point2(x, y)\n self.dir = vec2.fromAngle(angle)\n self.length = length\n\n def setAngle(self, angle):\n self.dir = vec2.fromAngle(angle)\n\n def cast(self, a, b):\n x1 = a.x\n y1 = a.y\n x2 = b.x\n y2 = b.y\n\n x3 = self.pos.x\n y3 = self.pos.y\n x4 = self.pos.x + self.dir.x\n y4 = self.pos.y + self.dir.y\n dt = dtm2(x1 - x3, x3 - x4, y1 - y3, y3 - y4)\n du = dtm2(x1 - x2, x1 - x3, y1 - y2, y1 - y3)\n dd = dtm2(x1 - x2, x3 - x4, y1 - y2, y3 - y4)\n dd_val = dd.val()\n\n if dd_val == 0:\n return\n\n t = dt.val() / dd_val\n u = du.val() / dd_val\n\n if 0 < t < 1 and u > 0:\n return vec2(x1 + t * (x2 - x1), y1 + t * (y2 - y1))\n else:\n return\n\n\nclass Triangle(Shape):\n def __init__(self, *vec):\n self.p1 = vec[0]\n self.p2 = vec[1]\n self.p3 = vec[2]\n\n def __str__(self):\n return '<Shape::{}({}, {}, {})>'.format(self.__class__.__name__, self.p1, self.p2, self.p3)\n\n def barycenter(self):\n return point2((self.p1.x + self.p2.x + self.p3.x) / 3, (self.p1.y + self.p2.y + self.p3.y) / 3)\n\n def same(self, shape) -> bool:\n if not isinstance(shape, Triangle):\n return False\n return self.p1 == shape.p1 and self.p2 == shape.p2 and self.p3 == shape.p3\n\n\nclass Rectangle(Shape):\n def __init__(self, x, y, w, h):\n self.x = x\n self.y = y\n self.w = w\n self.h = h\n\n def __str__(self):\n return '<Shape::{}({}, {}, {}, {})>'.format(self.__class__.__name__, self.x, self.y, self.w, self.h)\n\n def contains(self, point) -> bool:\n return self.x + self.w > point.x > self.x and self.y < point.y < self.y + self.h\n\n def intersects(self, shape) -> bool:\n if not isinstance(shape, Rectangle):\n raise Exception(\"Param '{}' not a subclass of Shape::Rectangle\".format(shape))\n center1 = self.barycenter() # 获取自身的重心坐标\n center2 = shape.barycenter() # 获取要检测的重心坐标\n\n dist_x = abs(center1.x - center2.x) # 重心位于x方向上的距离\n dist_y = abs(center1.y - center2.y) # 重心位于y方向上的距离\n\n sum_x = self.w + shape.w # x方向上的边长之和\n sum_y = self.h + shape.h # y方向上的边长之和\n\n if dist_x * 2 <= sum_x and dist_y * 2 <= sum_y:\n return True\n return False\n\n def same(self, shape) -> bool:\n if not isinstance(shape, Rectangle):\n return False\n return self.x == shape.x and self.y == shape.y and self.w == shape.w and self.h == shape.h\n\n def array(self):\n p1, p2 = point2(self.x, self.y), point2(self.x + self.w, self.y)\n p4, p3 = point2(self.x, self.y + self.h), point2(self.x + self.w, self.y + self.h)\n return [p1, p2, p3, p4]\n\n def size(self):\n return self.w, self.h\n\n def local(self):\n return self.x, self.y\n\n def area(self):\n return self.w * self.h\n\n def girth(self):\n return (self.w + self.h) * 2\n\n def left(self):\n return self.x\n\n def right(self):\n return self.x + self.w\n\n def top(self):\n return self.y\n\n def bottom(self):\n return self.y + self.h\n\n def barycenter(self):\n return point2(self.x + self.w / 2, self.y + self.h / 2)\n\n def doubleRange(self):\n return self.x, self.y, self.w * 2, self.h * 2\n\n def rebuildForBarycenter(self, point):\n self.x = point.x - self.w / 2\n self.y = point.y - self.h / 2\n\n\nclass Square(Rectangle):\n def __init__(self, x, y, w):\n super(Square, self).__init__(x, y, w, w)\n\n def __str__(self):\n return '<Shape::{}({}, {}, {})>'.format(self.__class__.__name__, self.x, self.y, self.w)\n\n\nclass Ellipse(Shape):\n def __init__(self, x, y, a=2, b=1):\n if isinstance(x, vec2):\n self.__init__(x.x, x.y, y, a)\n else:\n self.x = x\n self.y = y\n self.a = a\n self.b = b\n\n def __str__(self):\n return '<Shape::{}({}, {}, {}, {})>'.format(self.__class__.__name__, self.x, self.y, self.a, self.b)\n\n def same(self, shape) -> bool:\n if not isinstance(shape, Ellipse):\n return False\n return self.x == shape.x and self.y == shape.y and self.a == shape.a and self.b == shape.b\n\n def barycenter(self):\n return point2(self.x, self.y)\n\n def area(self):\n return pi * self.a * self.b\n\n def doubleRange(self):\n return self.x, self.y, self.a * 2, self.b * 2\n\n\nclass Circle(Shape):\n def __init__(self, *args):\n x = args[0]\n if isinstance(x, vec2):\n self.__init__(x.x, x.y, args[1])\n else:\n self.x = args[0]\n self.y = args[1]\n self.r = args[2]\n\n def __str__(self):\n return '<Shape::{}({}, {}, {})>'.format(self.__class__.__name__, self.x, self.y, self.r)\n\n def same(self, shape) -> bool:\n if not isinstance(shape, Circle):\n return False\n return self.x == shape.x and self.y == shape.y and self.r == shape.r\n\n def contains(self, point) -> bool:\n return (self.x - point.x) ** 2 + (self.y - point.y) ** 2 < self.r ** 2\n\n def barycenter(self):\n return point2(self.x, self.y)\n\n def area(self):\n return pi * self.r * self.r\n\n def doubleRange(self):\n return self.x, self.y, self.r * 2\n\n def girth(self):\n return pi * self.r * 2\n\n # 内接圆\n\n\nclass InscribedCircle(Circle):\n def __init__(self, shape):\n if isinstance(shape, Square):\n r = shape.w / 2\n x = shape.x + r\n y = shape.y + r\n super(InscribedCircle, self).__init__(x, y, r)\n else:\n raise Exception(\"Param '{}' not a subclass of Shape::Square\".format(shape))\n\n\n# 外接圆\nclass CircumscribedCircle(Circle):\n def __init__(self, shape):\n if isinstance(shape, Square):\n w = shape.w / 2\n x = shape.x + w\n y = shape.y + w\n r = pow(pow(w, 2) * 2, 0.5)\n super(CircumscribedCircle, self).__init__(x, y, r)\n elif isinstance(shape, Rectangle):\n p = shape.barycenter()\n x = p.x\n y = p.y\n r = pow(pow(shape.w, 2) + pow(shape.h, 2), 0.5) / 2\n super(CircumscribedCircle, self).__init__(x, y, r)\n else:\n raise Exception(\"Param '{}' not a subclass of Shape::Square\".format(shape))\n" }, { "alpha_fraction": 0.44477611780166626, "alphanum_fraction": 0.6059701442718506, "avg_line_length": 32.5, "blob_id": "cee09384df6cf1ec2e100df87c6d0092a9c0db78", "content_id": "99b9783a9a2b2b9c9211cdb3382079354a3593db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 335, "license_type": "no_license", "max_line_length": 79, "num_lines": 10, "path": "/source/examples/RecordFileAndRSATest.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.core.assembly.RecordFile import RecordFile\n\n# m = {'DATE': '2020-3-22', 'TIME': '12:00:00', 'HP': '98', 'MP': '22'}\nm = ['2020-3-22', '12:00:00', '98', '22', 'AR56']\nrf = RecordFile('/', 'ss')\nrf.create(m)\nprint(rf.getList())\n\n# s = '[FS-RECORDHEAD]\\nTime&2020-3-2212:00:00\\nHP&98 MP&22\\nEquip&OBJ_ARMOR_0'\n# rsaEncrypt(s)\n" }, { "alpha_fraction": 0.6121718287467957, "alphanum_fraction": 0.6157518029212952, "avg_line_length": 26.326086044311523, "blob_id": "c92b08f24c7895f35639f868c8771cb1d2091367", "content_id": "deed2b8799222d664451b0dd7815eb777a8ac600", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2514, "license_type": "no_license", "max_line_length": 99, "num_lines": 92, "path": "/source/core/component/Mixer.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import pygame\n\n\nclass Mixer:\n _instance = None\n\n def __new__(cls, *args, **kwargs):\n if cls._instance is None:\n cls._instance = object.__new__(cls)\n cls.__soundDict = dict()\n cls.__channelDict = dict()\n cls.__musicDict = dict()\n pygame.mixer.init()\n return cls._instance\n\n def quit(self):\n self.__soundDict.clear()\n self.__musicDict.clear()\n self.__channelDict.clear()\n pygame.mixer.quit()\n\n def __init__(self):\n pass\n\n def addSound(self, strId, path):\n self.__soundDict[strId] = pygame.mixer.Sound(path)\n\n def playSound(self, strId, loops=0, maxTime=0, fadeMs=0):\n self.__soundDict[strId].play(loops, maxTime, fadeMs)\n\n def setVolSound(self, strId, vol):\n self.__soundDict[strId].set_volume(vol)\n\n def pauseSound(self, strId):\n self.__soundDict[strId].puse()\n\n def unpauseSound(self, strId):\n self.__soundDict[strId].unpause()\n\n def stopSound(self, strId):\n self.__soundDict[strId].stop()\n\n def createChannel(self, strId, channelId=None):\n if channelId:\n self.__channelDict[strId] = pygame.mixer.Channel(channelId)\n else:\n self.__channelDict[strId] = pygame.mixer.find_channel()\n\n def setVolChannel(self, strId, vol):\n self.__channelDict[strId].set_volume(vol)\n\n def playSoundByChannel(self, channelStrId, soundStrId, loops=0, maxTime=0, fadeMs=0):\n self.__channelDict[channelStrId].play(self.__soundDict[soundStrId], loops, maxTime, fadeMs)\n\n @staticmethod\n def numOfChannel(self):\n return pygame.mixer.get_num_channels()\n\n def addMusic(self, strId, path):\n self.__musicDict[strId] = path\n\n def loadMusic(self, strId):\n pygame.mixer.music.load(self.__musicDict[strId])\n\n @staticmethod\n def playMusic(self, loops=0, start=0.0):\n if not pygame.mixer.music.get_busy():\n pygame.mixer.music.play(loops, start)\n\n @staticmethod\n def replayMusic(self):\n pygame.mixer.music.rewind()\n\n @staticmethod\n def pauseMusic(self):\n pygame.mixer.music.pause()\n\n @staticmethod\n def stopMusic(self):\n pygame.mixer.music.stop()\n\n @staticmethod\n def restoreMusic(self):\n pygame.mixer.music.unpause()\n\n @staticmethod\n def fadeoutMusic(self, time):\n pygame.mixer.music.fadeout(time)\n\n @staticmethod\n def setVolumeMusic(self, val):\n pygame.mixer.music.set_volume(val)\n" }, { "alpha_fraction": 0.5945674180984497, "alphanum_fraction": 0.6418511271476746, "avg_line_length": 24.151899337768555, "blob_id": "b25ad6f5811d136c649bf0b11267a5281c645e47", "content_id": "7affa626f180946e04aa8b4e03a0ef01cdde3da7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2056, "license_type": "no_license", "max_line_length": 114, "num_lines": 79, "path": "/source/core/const/Const.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "gl_WindowWidth = 800\ngl_WindowHeight = 600\n\ngl_nextLevelWindowWidth = 1280\ngl_nextLevelWindowHeight = 720\n\ngl_maxLevelWindowWidth = 1440\ngl_maxLevelWindowHeight = 900\n\n#collidedAreaType\nRECT = 0\n\nDATATYPE_STR_BOOL = 'bool'\nDATATYPE_STR_INT = 'int'\nDATATYPE_STR_FLOAT = 'float'\nDATATYPE_STR_COMPLEX = 'complex'\nDATATYPE_STR_STR = 'str'\n\ngl_Font = 'resource/Font/Default_SC.ttf'\ngl_Font_oth = 'resource/Font/Default_SC_oth.otf'\ngl_Font_opt = 'resource/Font/Default_SC_opt.ttf'\n\ngl_ImgPath = 'resource/Img/'\ngl_MusicPath = 'resource/Wave/Music/'\ngl_SoundPath = 'resource/Wave/Sound/'\ngl_VideoPath = 'resource/Video/'\ngl_UIPath = 'resource/UI/'\ngl_AssetsPath = 'data/assets/'\n\ngl_LogPath = 'logs/'\n\n# option\nGLC_INI_NAME = 'Config.ini'\nGLC_INI_SECTION_WAVE = 'WAVE'\nGLC_INI_PARAM_BGMVOLUME = 'volbgm'\nGLC_INI_PARAM_SOUNDVOLUME = 'volsound'\nGLC_INI_SECTION_DRAW = 'Draw'\nGLC_INI_PARAM_ANTIALIAS = 'antialias'\nGLC_INI_PARAM_FRAMERATE = 'framerate'\n\n# color\nconst_red = (255, 0, 0)\nconst_color_white = (255, 255, 255)\nconst_color_black = (0, 0, 0)\nconst_colorKey = (128, 128, 128)\n\n# scene\nSCENENUM_INIT = 0\nSCENENUM_TITLE = 1\nSCENENUM_GAME_PROLOGUE = 10\nSCENENUM_GAME_STARTCG = 101\nSCENENUM_CONTINUE = 20\nSCENENUM_OPT = 30\nSCENENUM_OPT_APPLY = 301\n\n#RecordFile\nRECORDFILE_HEAD = 'RF'\nRECORDFILE_SAVE_PATH = 'data/save/'\nRECORDFILE_SAVE_NAMEHEAD = 'save'\nRECORDFILE_SAVE_EXN = '.rf'\nRSA_PK_FILE_EXN = '.prm'\n\n#APP-CONFIG_XML\nROOT_ELEMENT = 'app-config'\nCHUNK_REGISTERED_SCENE = 'registered-scene'\nATTRIBUTE_CLASS_STRING = 'class-string'\nATTRIBUTE_SCENE_NUM = 'scene-num'\n\n# PhysicsBody\nPHYSICSBODY_RIGIDBODY = 0\n\n\n# 数字码表\nNUM_DICT = {'1': '一', '2': '二', '3': '三', '4': '四', '5': '五', '6': '六', '7': '七', '8': '八', '9': '九', '0': '〇'}\nNUM_DICT_CN = {'1': '壹', '2': '贰', '3': '叁', '4': '肆', '5': '伍', '6': '陆', '7': '柒', '8': '捌', '9': '玖', '0': '零'}\nNUM_DICT_M = {'1': '游', '2': '型', '3': '个', '4': '布', '5': '戏', '6': '应', '7': '理', '8': '永', '9': '或', '0': '件'}\n\n# Text\nconst_Text_LineSize = 5\n\n" }, { "alpha_fraction": 0.5207710862159729, "alphanum_fraction": 0.5224002003669739, "avg_line_length": 28.70161247253418, "blob_id": "def38cb9de51c6a150124f4e0090443fa4426b63", "content_id": "100cc337c1dda5b721bf68b5c67956e7edd89d11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3683, "license_type": "no_license", "max_line_length": 93, "num_lines": 124, "path": "/source/core/dataStructure/QuadTree.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "class Range:\n def contains(self, node):\n pass\n\n def intersects(self, oth):\n pass\n\n\nclass RectangleRange(Range):\n def __init__(self, x, y, w, h):\n self.x = x\n self.y = y\n self.w = w\n self.h = h\n\n def contains(self, point):\n return (self.x - self.w <= point.x <= self.x + self.w and\n self.y - self.h <= point.y <= self.y + self.h)\n\n def intersects(self, oth):\n return not (oth.x - oth.w > self.x + self.w or\n oth.x + oth.w < self.x - self.w or\n oth.y - oth.h > self.y + self.h or\n oth.y + oth.h < self.y - self.h)\n\n\nclass CircleRange(Range):\n def __init__(self, x, y, r):\n self.x = x\n self.y = y\n self.r = r\n self.squared_r = self.r * self.r\n\n def contains(self, point):\n d = pow((point.x - self.x), 2) + pow((point.y - self.y), 2)\n return d <= self.squared_r\n\n def intersects(self, oth):\n dist_x = abs(oth.x - self.x)\n dist_y = abs(oth.y - self.y)\n r = self.r\n w = oth.w\n h = oth.h\n edges = pow((dist_x - w), 2) + pow((dist_y - h), 2)\n\n if dist_x > (r + w) or dist_y > (r + h):\n return False\n if dist_x <= w or dist_y <= h:\n return True\n return edges <= self.squared_r\n\n\nclass Node:\n def __init__(self, x, y, data):\n self.x = x\n self.y = y\n self.data = data\n\n\nclass QuadTree:\n def __init__(self, boundary, capacity):\n if not isinstance(boundary, Range):\n raise Exception(\"'{}' must implement class 'QuadTree::Range'\".format(boundary))\n\n self.boundary = boundary\n self.capacity = capacity\n self.points = []\n self.divided = False\n self.quadOne = None\n self.quadTwo = None\n self.quadThr = None\n self.quadFou = None\n\n def subdivide(self):\n x = self.boundary.x\n y = self.boundary.y\n w = self.boundary.w / 2\n h = self.boundary.h / 2\n\n self.quadOne = QuadTree(RectangleRange(x + w, y - h, w, h), self.capacity)\n self.quadTwo = QuadTree(RectangleRange(x - w, y - h, w, h), self.capacity)\n self.quadThr = QuadTree(RectangleRange(x + w, y + h, w, h), self.capacity)\n self.quadFou = QuadTree(RectangleRange(x - w, y + h, w, h), self.capacity)\n\n self.divided = True\n\n def insert(self, node):\n if not self.boundary.contains(node):\n return False\n if len(self.points) < self.capacity:\n self.points.append(node)\n return True\n if not self.divided:\n self.subdivide()\n return self.quadOne.insert(node) or self.quadTwo.insert(node) or self.quadThr.insert(\n node) or self.quadFou.insert(node)\n\n def query(self, _range, res=None):\n if not isinstance(_range, Range):\n raise Exception(\"'{}' must implement class 'QuadTree::Range'\".format(_range))\n\n if res is None:\n res = []\n if not self.boundary.intersects(_range):\n return res\n\n for p in self.points:\n if _range.contains(p):\n res.append(p)\n if self.divided:\n self.quadOne.query(_range, res)\n self.quadTwo.query(_range, res)\n self.quadThr.query(_range, res)\n self.quadFou.query(_range, res)\n return res\n\n def length(self):\n count = len(self.points)\n if self.divided:\n count += self.quadOne.length()\n count += self.quadTwo.length()\n count += self.quadThr.length()\n count += self.quadFou.length()\n return count\n" }, { "alpha_fraction": 0.5535824298858643, "alphanum_fraction": 0.5740829706192017, "avg_line_length": 37.18062973022461, "blob_id": "5c084777eb8c585c3fa137a185d5a8c5a8bb1de1", "content_id": "377703464a2d46b2aae3614fc6ad27894d6471fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14695, "license_type": "no_license", "max_line_length": 123, "num_lines": 382, "path": "/source/view/element/Control.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import time\n\nimport pygame\n\nfrom source.core.assembly.IOEvent import ioEvent3Enum, getAsciiByIOEvent3Enum\nfrom source.core.const.Const import gl_Font_opt, gl_Font\nfrom source.core.math.MathUtil import mapping, signal\nfrom source.util.KMP import KMPMatching\nfrom source.util.ToolsFuc import blankSurface, centeredYPos\nfrom source.view.baseClazz.Element import Element\n\n# 空的Element\nfrom source.view.element.Elements import TextElement\n\n\nclass BlankElement(Element):\n def __init__(self, area, color):\n t_Area = area\n if (isinstance(area, tuple) or isinstance(area, list)) and len(area) == 2:\n t_Area = (0, 0, area[0], area[1])\n super(BlankElement, self).__init__(t_Area)\n self.__col = color\n self.res_surface = None\n self.__build((self.area.w, self.area.h), self.__col)\n\n def __build(self, size, color):\n self.res_surface = blankSurface(size, color)\n\n def setSize(self, size):\n self.__build(size, self.__col)\n self.area.w = size[0]\n self.area.h = size[1]\n\n def setColor(self, color):\n self.__build((self.area.w, self.area.h), color)\n self.__col = color\n\n def setAlpha(self, val):\n self.res_surface.set_alpha(val)\n\n def draw(self, screen):\n screen.blit(self.res_surface, (self.area.x, self.area.y))\n\n\nclass Button(Element):\n def __init__(self, area, caption, size):\n super(Button, self).__init__(area)\n self.__caption = caption\n self.__textSize = size\n self.__size = self.area.size()\n self.__resShader = blankSurface(self.__size, (10, 10, 10, 200))\n self.__shaderRenderLocal = (self.area.x, self.area.y + 20)\n self.__resSuf = blankSurface(self.__size, (255, 255, 255))\n\n self.__build()\n\n self.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: self.__evn_chShader(True), 0)\n self.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp, lambda: self.__evn_chShader(False), 0)\n\n def __build(self):\n # _shader = blankSurface(self.__size, (10, 10, 10, 200))\n _textTemp = pygame.font.Font(gl_Font_opt, self.__textSize)\n __textSuf = pygame.Surface((self.__textSize * len(self.__caption), self.__textSize))\n __textSuf.blit(_textTemp.render(self.__caption, 1, (0, 0, 0)), (10, 10))\n self.__resSuf.blit(__textSuf, (2, 2))\n\n def __evn_chShader(self, picked):\n if picked:\n self.__shaderRenderLocal = (self.__shaderRenderLocal[0], self.__shaderRenderLocal[1] - 10)\n else:\n self.__shaderRenderLocal = (self.__shaderRenderLocal[0], self.__shaderRenderLocal[1] + 10)\n\n def draw(self, screen):\n # screen.blit(self.__resShader, self.__shaderRenderLocal)\n screen.blit(self.__resSuf, (self.area.x, self.area.y))\n\n\nclass TextRender:\n def __init__(self, text, antialias=1, color=(0, 0, 0), bgColor=None):\n self.text = text\n self.antialias = antialias\n self.color = color\n self.bgColor = bgColor\n self.posX = 0\n self.posY = 0\n\n def createLineRender(self, text):\n pass\n\n\n# 文本域\nclass TextArea(Element):\n ERROR_MSG = '<red>'\n HTML_TEAL = '</>'\n\n def __init__(self, area, padding_x=10, padding_y=10, font=gl_Font, fontSize=16, readonly=False,\n bgColor=(0, 0, 0, 255), baseColor=(0, 0, 0, 255), fontColor=(-1, -1, -1, -1),\n slidColor=(255, 255, 255, 100), slidWidth=10, autoLine=True, lineSpace=5,\n textSpace=2):\n super(TextArea, self).__init__(area)\n self.__padding_x = padding_x\n self.__padding_y = padding_y\n self.__font = font\n self.__fontSize = fontSize\n self.__readonly = readonly\n self.__bgColor = bgColor\n self.__baseColor = baseColor\n self.__antiBgColor = (255 - self.__bgColor[0], 255 - self.__bgColor[1], 255 - self.__bgColor[2], 255)\n if fontColor == (-1, -1, -1, -1):\n self.__fontColor = self.__antiBgColor\n else:\n self.__fontColor = fontColor\n self.__slidColor = slidColor\n self.__slidWidth = slidWidth\n self.__autoLine = autoLine\n self.__lineSpace = lineSpace\n self.__textSpace = textSpace\n\n self.__verticalSlidLock = True\n self.__horizontalSlidLock = True\n self.__rollToTop = False\n self.__rollToBottom = False\n self.__allTextLength = 0\n self.__maxTextWidth = 0\n self.__text = ''\n self.__renderTextList = list()\n self.trueOneFontSize = self.__fontSize\n self.__offsetHeight = -1\n self.res_surface = None\n\n self.__areaBg = blankSurface((self.area.w, self.area.h), self.__bgColor)\n self.__slid = blankSurface((self.__slidWidth, self.area.h), self.__slidColor)\n self.__fontType = pygame.font.Font(self.__font, self.__fontSize)\n self.__areaBgPos = (0, 0)\n self.__curPtr = 0\n self.__lineList = list()\n self.__slidPosY = 0\n self.__nextTextPosX = self.__padding_x\n self.__nextTextPosY = self.__padding_y\n self.__interval = 0\n self.__showFlash = True\n\n self.Events.appendEvent(ioEvent3Enum.mouseRollDown, lambda: self.rollDown(True, self.trueOneFontSize), 1)\n self.Events.appendEvent(ioEvent3Enum.mouseRollUp, lambda: self.rollDown(False, self.trueOneFontSize), 1)\n self.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: self.__mouKey(), 1)\n self.Events.appendEvent(ioEvent3Enum.mouseMotion, lambda: self.__dragSlidBar(), 1)\n self.Events.appendEvent(ioEvent3Enum.keyDown, self.keyInput, 1)\n self.Events.appendEvent(ioEvent3Enum.keyDowning, self.keyInput, 1)\n\n self.__buildSurface()\n\n self.__counter = 0\n\n def __mouKey(self):\n if (self.__slidPosY + self.__slid.get_rect().h > self.mousePos[1] > self.__slidPosY) and \\\n (self.area.w > self.mousePos[0] > self.area.w - self.__slidWidth):\n return\n self.appendText('yes\\n')\n\n # def __clickSlidChannel(self):\n # if self.__verticalSlidLock:\n # return\n # if self.area.w > self.mousePos[0] > (self.area.w - self.__slidWidth):\n # self.__areaBgPos = (\n # self.__areaBgPos[0],\n # int(mapping(self.mousePos[1], 0, self.area.h, 0, self.area.h - self.__allTextLength - self.__padding_y)))\n # self.appendText('clicked Slid\\n')\n\n def __dragSlidBar(self):\n if self.__verticalSlidLock:\n return\n if (self.__slidPosY + self.__slid.get_rect().h > self.mousePos[1] > self.__slidPosY) and \\\n (self.area.w > self.mousePos[0] > self.area.w - self.__slidWidth):\n if self.mouseButtons == (1, 0, 0):\n shortH = self.mousePos[1] - self.__slidPosY\n print(shortH)\n\n def keyInput(self, key):\n _key = getAsciiByIOEvent3Enum(key)\n # 8 - 退格 \n # 9 - Tab \n # 13 - 回车 \n # 16~18 - Shift, Ctrl, Alt \n # 37~40 - 左上右下 \n # 35~36 - End Home \n # 46 - Del \n # 112~123 - F1 - F12 \n\n if _key == 8:\n _text = self.__text[:-1]\n self.__text = ''\n self.appendText(_text)\n elif _key == 13:\n self.appendText('\\n')\n else:\n self.appendText(chr(_key))\n\n def __getSlidYByBgPos(self):\n return int(mapping(abs(self.__areaBgPos[1]), 0, self.__allTextLength, 0, self.area.h))\n\n def __getBgPosBySlidY(self):\n return self.__areaBgPos[0], int(mapping(self.__slidPosY, 0, self.area.h, 0, self.__allTextLength))\n\n def rollDown(self, isDown, step):\n if self.__verticalSlidLock:\n return\n # step += self.__padding_y\n if isDown and not self.__rollToBottom:\n self.__areaBgPos = (self.__areaBgPos[0], self.__areaBgPos[1] - step)\n if not isDown and not self.__rollToTop:\n self.__areaBgPos = (self.__areaBgPos[0], self.__areaBgPos[1] + step)\n self.__buildSurface()\n\n def __buildTextSurface(self):\n if not self.__text:\n return\n self.__nextTextPosY = self.__padding_y\n self.__nextTextPosX = self.__padding_x\n errorIndex = KMPMatching(self.__text, self.ERROR_MSG)\n for s in self.__text:\n renderText = TextRender(s, color=self.__fontColor)\n if renderText is not None:\n if renderText.text == '\\n':\n self.__nextTextPosY += self.trueOneFontSize + self.__lineSpace\n self.__nextTextPosX = self.__padding_x\n continue\n if renderText.text == '\\r':\n self.__nextTextPosX = self.__padding_x\n renderText.posY = self.__nextTextPosY\n renderText.posX = self.__nextTextPosX\n self.__areaBg.blit(\n self.__fontType.render(renderText.text, renderText.antialias, renderText.color, renderText.bgColor),\n (renderText.posX, renderText.posY))\n trueFontSize = self.__fontType.size(renderText.text)\n self.__renderTextList.append(renderText)\n self.__nextTextPosX += trueFontSize[0] + self.__textSpace\n\n def __buildSurface(self):\n self.res_surface = blankSurface((int(self.area.w), int(self.area.h)), self.__bgColor)\n if self.__offsetHeight >= 0:\n self.__areaBg = blankSurface((self.area.w, self.__allTextLength), self.__bgColor)\n if self.__verticalSlidLock:\n self.__verticalSlidLock = False\n else:\n self.__areaBg = blankSurface((self.area.w, self.area.h), self.__bgColor)\n if not self.__verticalSlidLock:\n self.__verticalSlidLock = True\n\n self.__buildTextSurface()\n\n if not self.__verticalSlidLock:\n slidHeight = (self.area.h / self.__allTextLength) * self.area.h\n self.__slid = blankSurface((self.__slidWidth, slidHeight), self.__slidColor)\n self.__slidPosY = self.__getSlidYByBgPos()\n if self.__areaBgPos[1] >= 0:\n self.__rollToTop = True\n else:\n self.__rollToTop = False\n if self.__allTextLength <= self.area.h + abs(self.__areaBgPos[1]):\n self.__rollToBottom = True\n else:\n self.__rollToBottom = False\n\n def appendText(self, text):\n text = str(text)\n self.__text += text\n self.__lineList = self.__text.split('\\n')\n textLen = len(text.split('\\n')) - 1\n\n if text:\n self.trueOneFontSize = self.__fontType.size(text[0])[1]\n else:\n self.trueOneFontSize = 0\n self.__allTextLength = self.__padding_y + len(self.__lineList) * (self.trueOneFontSize + self.__lineSpace)\n self.__offsetHeight = self.__allTextLength - self.area.h\n if self.__allTextLength - self.area.h > 0:\n self.rollDown(True, self.__padding_y + textLen * (self.trueOneFontSize + self.__lineSpace))\n self.__buildSurface()\n\n def insertText(self, pos, text):\n tempTextList = self.__text[:self.__getIndexByPos(pos)]\n _text = tempTextList[0] + text\n _text += tempTextList[1]\n self.__text = ''\n self.appendText(_text)\n\n def clearText(self):\n self.__text = ''\n self.__areaBgPos = (0, 0)\n self.__allTextLength = self.area.h\n self.__offsetHeight = self.__allTextLength - self.area.h\n self.appendText(self.__text)\n\n def appendLastLine(self, text):\n self.appendText(text)\n\n def getText(self):\n return self.__text\n\n def draw(self, screen):\n sec = time.clock()\n flashSurf = blankSurface((self.trueOneFontSize, self.trueOneFontSize), self.__bgColor)\n if sec - self.__interval >= 0.5:\n self.__showFlash = not self.__showFlash\n self.__interval = sec\n self.res_surface.fill(self.__bgColor)\n if self.__showFlash:\n flashSurf.blit(self.__fontType.render('|', 1, self.__antiBgColor), (0, 0))\n self.__areaBg.blit(flashSurf, (self.__nextTextPosX, self.__nextTextPosY))\n self.res_surface.blit(self.__areaBg, self.__areaBgPos)\n if not self.__verticalSlidLock:\n self.res_surface.blit(self.__slid, (self.area.w - self.__slidWidth, self.__slidPosY))\n screen.blit(self.res_surface, (self.area.x, self.area.y))\n\n\n# 文字元素及其事件处理\nclass InputElement(Element):\n def __init__(self, area, text, padding=2, font=gl_Font, color=(255, 255, 255), bgColor=(0, 0, 0), antiAlias=1):\n super(InputElement, self).__init__(area)\n self.__font = font\n self.__text = text\n self.__padding = padding\n self.__color = color\n self.__bgColor = bgColor\n self.__antiAlias = antiAlias\n self.__buildSurface()\n\n self.Events.appendEvent(ioEvent3Enum.keyDown, self.__doKeyInput, 0)\n self.Events.appendEvent(ioEvent3Enum.keyDowning, self.__doKeyInput, 0)\n\n def __buildSurface(self):\n textSize = self.area.h - self.__padding * 2\n textTemp = pygame.font.Font(self.__font, textSize)\n self.res_surface = blankSurface(self.area.size(), (200, 200, 200))\n textSurface = textTemp.render(self.__text, self.__antiAlias, self.__color, self.__bgColor)\n self.res_surface.blit(textSurface, (0, centeredYPos(self.area.h, textSize)))\n\n def __doKeyInput(self, key):\n # 8 - 退格 \n # 9 - Tab \n # 13 - 回车 \n # 16~18 - Shift, Ctrl, Alt \n # 37~40 - 左上右下 \n # 35~36 - End Home \n # 46 - Del \n # 112~123 - F1 - F12 \n\n if key == 8:\n self.setText(self.__text[:-1])\n # elif key in (9, 13, 16, 17, 18):\n # return\n # elif 36 < key < 41 or 34 < key < 37 or 111 < key < 124:\n # return\n else:\n self.setText(self.__text + chr(key))\n\n def draw(self, screen):\n screen.blit(self.res_surface, (self.area.x, self.area.y))\n\n def setBackgroundColor(self, bgColor):\n self.__bgColor = bgColor\n self.__buildSurface()\n\n def setPadding(self, padding):\n self.__padding = padding\n self.__buildSurface()\n\n def setText(self, text):\n self.__text = str(text)\n self.__buildSurface()\n\n def setFont(self, font):\n self.__font = font\n self.__buildSurface()\n\n def setSize(self, size):\n self.area.h = size + self.__padding\n self.__buildSurface()\n\n def setColor(self, color):\n self.__color = color\n self.__buildSurface()\n" }, { "alpha_fraction": 0.7554253935813904, "alphanum_fraction": 0.7957285642623901, "avg_line_length": 25.628440856933594, "blob_id": "e3943efe6d0edc81be38083fb38378edad0055a3", "content_id": "6015ae557b732631496b20b0758811346458cc34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 10310, "license_type": "no_license", "max_line_length": 85, "num_lines": 218, "path": "/README.md", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "# ProjectFS\nFS的python重置版,只不过没有资源\n\n关于这个框架的介绍和一些用法: \n\n* LOFTER主页: https://syclightframework.lofter.com 欢迎访问\n\n### 2020.3.17 Asheor\n* 修改了main.py 将注释删去,添加了入口函数\n* 修改了gameApp.py中循环的判断条件\n* 添加了example文件夹,用途是练习用的例子\n\n### 2020.3.18 Asheor\n* 主要更新了IOEvent.py中的IOEvent3\n> IOEvent3 更新:\n>>* Scene 可以自动识别可交互Element和固定Element\n>>* 现在支持去除已绑定的事件\n>>* 加入事件的ID标识,内部生成策略采用hash函数\n* 修改了与IOEvent3相关的代码\n> Scene.py 和 Element.py\n\n### 2020.3.19 Asheor\n* ToolsFuc.py 添加了一种随机数发生器,算法为梅森旋转法(Mersenne Twister MT)\n* Scene.py 去掉了Scene的无效导入\n* IOEvent.py 修改了IOevent3在处理键盘事件的细节\n\n### 2020.3.20 Asheor\n* Scene.py 每个场景的初始化方法均加入了参数列表,同时将CG播放场景和序章场景分割独立。\n> 原因:\n> 用以前的方法,在序章场景开始的时候,即便没有播放CG,程序也会提前运行FFmpeg的进程。\n> 将CG播放独立成一个场景,使得FFmpeg的进程在播放CG时开启,在播放完毕后销毁\n* Const.py 修正了一处英语单词的错误拼写,添加了新的CG场景的场景号 SCENENUM_GAME_STARTCG\n* 修改了CG资源的名称\n\n### 2020.3.21 Asheor\n* 新添加 clazz/RSA.py 用途是RSA文件加密\n* 新添加 RecordFile.py 用途是生成游戏的记录文件,文件格式.rf\n* 在 Element.py 中添加了 Element 接口,使所有的Element实现该接口\n* 在 Const.py 中添加了rf文件相关的常量和NUM_DICT系列映射关系\n* 在 ToolsFuc.py 中添加了根据Const映射转换的函数\n\n### 2020.3.22 Asheor\n* RecordFile.py 更新了游戏记录文件的文件结构\n* Scene.py 添加了继续游戏选项的场景(试行版)\n* Element.py 添加了一种继续游戏场景中的元素\n* RSA.py 优化程序对RSA函数的调用\n* 添加了一个测试:example/RecordFileAndRSATest.py\n* 添加了model文件夹,准备写用户模型,NPC模型,物理模型等\n\n### 2020.3.24 Asheor\n* Scene.py 将Scene由接口模式,转变成继承模式。同时将一些场景的事件触发机制做了调整。\n* IOEvent.py 向IOEvent3中添加了一种可处理的事件:鼠标在元素中移动事件\n* Config.py 调整了Config读取配置的方式,现在不需要再各场景中重新建立对象\n* gameApp.py 修改了在程序没有加载完成时,窗口标题显示为\"pygame window\"的情况\n* ToolsFuc.py 添加了归并排序\n* 关于Element,暂时决定成接口实现的模式,就这样吧\n\n### 2020.3.25 Asheor\n* gameApp.py 加入了帧率的设定,最大120帧,最小30帧,方便对游戏渲染过程的修改\n* Scene.py 重写了序章的场景,使其可以运行在相应帧率的配置下, 同时重新编排了场景的演出效果\n* 在 Const.py 与 Config.py 中加入了帧率相关设定,同时进一步改进了场景对Config的读取方式\n\n### 2020.3.26 Asheor\n* IOEvent.py, IOEvent3重大更新!\n> * 现在ioEvent3Enum 不继承enum类,因为python的enum类不太好用\n> * 修改了事件ID标识的处理方法,不再使用hash\n> * 完善了对键盘事件的支持\n> * 添加了一个关于IOEven3的测试例子,在example文件夹下\n* 添加了gameElementsAndScene文件夹,用来存放与游戏场景有关的类 Sprite.py\n* 在框架中添加了对精灵的支持,精灵也可以使用IOEvent3进行交互\n* ToolsFuc.py 添加了pygame按键到ioEvent3按键的映射函数,还有一些其它的\n* gameApp.py 添加了长按事件的支持\n* model文件夹下添加了一个Shape.py\n* Scene.py, Element.py 修改了Scene基类和Elements中的一些细节\n* 今天决定将这个游戏的框架命名为Syclight GameFramework with python,为Syclight的一份子\n\n### 2020.3.28 Asheor\n* 添加了SpriteGroup,主要是对pygame中的改造,可以实现组内碰撞检测,同时防止一些莫名其妙bug的产生\n> 碰撞检测数据结构:四叉树\n* 对QuadTree.py做了更加规范化的调整\n* 对Shape.py中的类做了升级优化\n* 添加了三例测试\n> ShapeTest.py 测试Shape.py,\n> 精灵动画播放测试:testSpriteScene.py,\n> 碰撞测试: testSpriteScene.py\n* 其它的做了一些修改\n\n### 2020.3.29 Asheor -Code:Reborn\n* 更新了目录结构 \n目录名称|子文件夹|备注 \nsource|(all)|包含全部的源文件 \nconfig|(null)|主要是App的配置文件 AppConfig \nconst|(null)|常量 \ncontroller|assembly,dataStructure|程序要用到的组件,数据结构等 \nexamples|(null)|测试用例 \nmodel|(null)|模型 \nutil|(null)|工具包 \nview|bassClass,element,entity,scene|游戏视图,baseClass中有一游戏中用到的基类\n* 继续完善了Shape.py\n* 新建立Actor.py,Actor为游戏中出现的所有物体\n\n### 2020.3.30 Asheor\n* 添加controller.assembly.XmlOperator.py用于操作XML文件\n* 添加PhysicalBody.py用于物理组件,同时还添加了PhysicsSystem\n* 添加chapter1-1.py准备进入第一章节游戏的编写\n* 将vec2等添加到util.Math2d.py中\n\n### 2020.4.4 Asheor\n* 主要更新2d物理方面的支持:力,与碰撞反馈\n* PhysicsSystem 更名为PhysicalScene\n* 与物理支持有关的文件:\n> 1.controller/assembly/CollidedProbe.py 该文件为碰撞处理探针,处理碰撞之后各个物理体的状态,由physicalScene调用 \n> 2.controller/assembly/PhysicalBody.py 该文件为主要的物理处理机,包含physicalBody与PhysicalScene \n> 3.util/Math2D.py 添加了许多2d向量的新计算方式,方便进行物理运算 \n> 4.controller/assembly/Shape.py 为方便物理运算添加了一些特性\n* 在examples下可以找到对应的测试场景,修改AppConfig.py以测试\n* 优化了gameApp.py, 现在在创建场景时要传入时间参数(这个时间一般用pygame.time.get_ticks()获得)\n\n### 2020.4.7 Asheor\n* 重大更新!本次主要添加了A*寻路算法\n* A-star.py 主要包含A*寻路算法的各种细节\n* 添加了MathUtil.py提供一些与数学相关的函数\n* 添加了一个测试AstartTest.py同样在AppConfig.py中配置后即可使用\n* 轻微修改了CollidedProbe.py与PhysicalBody.py\n\n### 2020.4.8 Asheor\n* 修改了A-start.py中的一些细节,使寻路在实际应用中更加方便\n\n### 2020.4.13 Asheor\n* 新增的Painter.py可以画出Shape中的形状\n* 新增了一个测试 TestPainter.py 用于测试绘制Shape的效果\n* 新增了MathConst.py 数学常量\n* Math2d.py 新增了行列式计算\n* A-start.py 更名为A_start.py,并做了少量修改。\n* Shape.py 新增了Line与Ellipse\n\n### 2020.4.14 Asheor\n* 对MathUtil.py,Painter.py,ToolsFuc.py,A_star.py进行了细节上的修改\n* 修改了测试TestPainter.py与testSpriteScene.py\n* 添加了RTS_Test.py测试A*和Actor结合,模拟RTS的寻路系统\n\n### 2020.4.15 Asheor\n* 将A*寻路结合到场景中,详见RTS_Test.py\n* 修复了Painter画直线时起点有时会错误的bug\n* 修复了Math2d.py中向量求夹角时cos值未定义边界而错误的问题,添加了求正方向的方法\n* MathUtil.py与MathCost.py中添加了插值函数相关的方法,现在支持:\n> 线性插值,三角插值,立方差值(三次插值),Hermite插值\n* 添加SGFpyException.py,是框架中所有异常的基类\n* A_star.py现在支持插入一个障碍物域与删除障碍物域,并添加了位置错误异常\n\n### 2020.4.16 Asheor\n* 柏林噪声终于在框架中实现,参考了p5.js,core.math.Noise\n* 重新将代码目录分配,新建了core,主要存放框架的核心支撑代码\n* 数学有管的在core.math下\n* 修改了Scene基类,现在在初始化时,可以直接传参*args\n* 新增了Map.py, noiseTest.py, Random.py\n\n### 2020.4.17 Asheor\n* 添加了非常有趣的测试场景,someFunTestScene.py\n> 画板,波图像,绘制球体草稿与链条。用做框架Scene的教学,代码逻辑参考了p5.js的范例\n* 修改了若干bug\n* 新调整了gameApp的逻辑和新增Scene内置对象\n* 我开通了LOFTER主页: https://syclightframework.lofter.com 欢迎访问\n\n### 2020.4.20 Asheor\n* 修改了若干代码\n* 主要是研究canvas的实现,发现需要硬件加速来完成,不然像素计算太慢了。\n* 添加了Matrix.py 用于矩阵的计算。\n* 进一步修改scene的基类的结构,使其更加合理。\n\n### 2020.4.27 Asheor\n* 修改了gameApp的结构,scene的结构\n> 带有super前缀的方法,不能重写。 \n> 添加了许多内置对象与变量,方便编程\n* 添加了渲染器类,用于分层渲染,类似于html中标签的z-index属性\n* 添加了有趣的例子,用于学习使用该框架编程\n\n### 2020.4.30 Asheor\n* 添加了Component目录,里面是组件\n> Constructor.py 生成器 \n> Transform.py 变换组件\n\n### 2020.5.7 Asheor\n* 添加了弹簧,质点等物理组件,用于物理模拟。\n* 修改了Scene的部分代码\n* 想转用d2d做这个框架了。。。\n\n### 2020.6.1 Asheor\n* 添加了一个sgf-py GUITools, AnimeEditor, 可用该工具制作简单的变换动画\n* 目前只支持变换(transform), 不支持形变(deformation)\n\n### 2020.7.13 Asheor\n* 优化了Scene\n* 使用框架写了一个数独游戏 SudokuGame\n\n### 2021.1.4 Asheor\n* 新年好,考完研了。\n* 修改了若干bug\n\n### 2021.1.8 Asheor\n* 改进了若干代码,完善了框架\n* 添加了Origin的相关代码\n\n### 2021.1.10 Asheor\n* 完成了Origin的TitleScene的编写\n\n### 2021.2.3 Asheor\n时间拖的有点久,因为这次更新了许多功能,向着成熟的Syclight迈进\n* 现在可在脱离Pycharm的环境下直接用命令行启动\n* 添加了KMP字符串匹配算法,在source.util下\n* 修改了一些element的bug\n* 将sprite,element与actor整合。\n* 稍微修改了事件触发的方式。\n* 添加了一些列新的控件,文本域,滑动条\n* 在新控件的基础上开发了Syclight with Py的图形节目控制台,在本框架开发的游戏中按f1键即可开启\n* 整合了pygame的mixer模块和moviepy的播放模块,将其包装进Syclight。\n* 添加了一个容器,source.core.assembly.container.MiniQueue\n* 为父类Scene,Element,添加了一些功能性的变量\n\n" }, { "alpha_fraction": 0.3554065525531769, "alphanum_fraction": 0.48113998770713806, "avg_line_length": 26.113636016845703, "blob_id": "56a70a584890ef495db5a8abce0eba596f2f9434", "content_id": "27acdd019087ea1a38f6d134276cb31a5f6f520e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1267, "license_type": "no_license", "max_line_length": 76, "num_lines": 44, "path": "/source/examples/ioEvent3EnumGenerate.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "# 生成a-z键\n# for i in range(97, 123):\n# print('key_' + chr(i) + ' =', '0x%X' % (0xC0000 + i - 97))\n\n# 生成所有数字\n# for i in range(0, 10):\n# print('key_' + str(i) + ' =', '0x%X' % (0xC0019 + i + 1))\n\n# 生成所有功能键\n# for i in range(1, 13):\n# print('key_F' + str(i) + ' =', '0x%X' % (0xC0023 + i + 1))\n\n# 生成A-Z键\n# for i in range(65, 91):\n# print('key_' + chr(i) + ' =', '0x%X' % ((0xC0000 + i - 65) + 0xC0033))\n\n# 生成特殊符号\n# for i in range(33, 48):\n# \"\"\"对应的是'!' ~ '?' \"\"\"\n# print('key_Sym' + str(i) + ' =', '0x%X' % (0xC003F + i + 1))\n\n# 生成self.__Events语句\n# i = 0xC0000\n# while i <= 0xC006F:\n# if i == 0xC0000:\n# print('self.__Events = {', end='')\n# print('0x%X' % (i | 0xB1000) + ': [], ', end='')\n# print('0x%X' % (i | 0xB2000) + ': [], ', end='')\n# print('0x%X' % (i | 0xB3000) + ': [], ', end='')\n# if i == 0xC006F:\n# print('}', end='')\n# i += 1\n\nfrom source.core.assembly.IOEvent import IOEvent3\nimport sys\n\nprint('IOEvent3占字节数', sys.getsizeof(IOEvent3()))\nprint(0xA000E, 0xA0000)\nprint((100 << 6) + 0xA0000)\nprint((1 << 6) + 0xA000E)\nprint((2 << 6) + 0xA0000)\nprint((2 << 6) + 0xA000E)\nprint((3 << 6) + 0xA0000)\nprint((3 << 6) + 0xA000E)\n" }, { "alpha_fraction": 0.513775110244751, "alphanum_fraction": 0.5420699715614319, "avg_line_length": 24.826923370361328, "blob_id": "d7727d9867487c37cd1a4ca7373a7dce90714179", "content_id": "b6d327f89cd26b073129b7308d1bbce34c8724d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1359, "license_type": "no_license", "max_line_length": 67, "num_lines": 52, "path": "/source/core/multimedia/MusicPlayer.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import wave\nimport numpy as np\n\n\nclass musicPlayer:\n def __init__(self, ):\n self.__pathMap = {}\n self.__activeMap = {}\n\n def add(self, name, path):\n self.__pathMap[name] = path\n\n def addAll(self, lis):\n for e in lis:\n self.__pathMap[e[0]] = e[1]\n\n def play(self, name):\n pass\n\n def active(self, name):\n f = wave.open(self.__pathMap[name], 'rb')\n self.__activeMap[name] = f\n\n def close(self, name):\n self.__activeMap[name].close()\n\n def getMsg(self, name, step):\n m = self.__activeMap[name]\n # params = m.getparams()\n # nchannels, sampwidth, framerate, nframes = params[:4]\n # print(framerate)\n str_data = m.readframes(step) # 80000是前10秒\n # print(str_data)\n wave_data = np.frombuffer(str_data, dtype=np.short)\n wave_data.shape = -1, 2\n wave_data = wave_data.T\n return wave_data[0]\n # time = np.arange(0, 80000) * (1.0 / 44100)\n\n # pl.subplot(211)\n # pl.plot(time, wave_data[0])\n # pl.subplot(212)\n # pl.plot(time, wave_data[1], c=\"g\")\n # pl.xlabel(\"time (seconds)\")\n # pl.show()\n\n\n# player = musicPlayer()\n# player.add('0', 'F:/练习/PyCharm/PygameTest/resource/Test/雪之华.wav')\n# player.active('0')\n# player.getMsg('0')\n# player.close('0')\n" }, { "alpha_fraction": 0.5370065569877625, "alphanum_fraction": 0.5419408082962036, "avg_line_length": 25.434782028198242, "blob_id": "90748df09005356f08a58cc156594aa38eab316c", "content_id": "32b54ddea3e078247de0a7269893b0fe645fc9aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1232, "license_type": "no_license", "max_line_length": 76, "num_lines": 46, "path": "/source/core/draw/Canvas.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import pygame\n\nfrom source.core.draw.Color import color\nfrom source.core.math.Vector import vec2\n\n\nclass canvas:\n \"\"\"画布,可进行alpha混合\"\"\"\n\n def __init__(self, *args):\n col, e = args[0], args[1]\n\n self.__suf = None\n self.__recordPix = []\n self.width, self.height = 0, 0\n\n if isinstance(e, vec2):\n self.width, self.height = int(e.x), int(e.y)\n self.__suf = pygame.Surface((self.width, self.height)).convert()\n elif isinstance(e, pygame.Surface):\n self.width, self.height = e.get_width(), e.get_height()\n self.__suf = e.copy()\n\n self.__init(col)\n\n def __init(self, col):\n self.__recordPix = [col] * self.width * self.height\n self.__suf.fill(col.aryRGBA())\n\n def setSurface(self, suf):\n self.__suf = suf.copy()\n\n def surface(self):\n return self.__suf\n\n def getPix(self, x, y):\n return self.__recordPix[y * self.width + x]\n\n def setPix(self, x, y, col):\n _col = self.getPix(x, y)\n _col = color.mix_(col, _col)\n self.__recordPix[y * self.width + x] = _col\n self.__suf.set_at([x, y], _col.aryRGB())\n\n def fill(self, col):\n self.__init(col)\n" }, { "alpha_fraction": 0.737500011920929, "alphanum_fraction": 0.75, "avg_line_length": 25.66666603088379, "blob_id": "1d920e98fa7228d70783bea37ccabff21e43527f", "content_id": "a452dc854b129334b456836033c92379ab423547", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 164, "license_type": "no_license", "max_line_length": 62, "num_lines": 6, "path": "/source/examples/SpriteTest.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.view.baseClazz.Sprite import Sprite\n\ns = Sprite()\nprint(s.rect)\ns2 = Sprite('F:/练习/PyCharm/PygameTest/resource/UI/OPT_BL.png')\nprint(s2.rect.width)\n" }, { "alpha_fraction": 0.6004319787025452, "alphanum_fraction": 0.6004319787025452, "avg_line_length": 24.66666603088379, "blob_id": "ce398c7f2ae3ca0e080d0b25b01162e535f54368", "content_id": "0e2af0d86228f95fe00c5d06402583274e453ecb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 463, "license_type": "no_license", "max_line_length": 49, "num_lines": 18, "path": "/source/core/assembly/Widget.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.view.baseClazz.Element import Element\n\n\nclass Widget(Element):\n def __init__(self, area):\n super(Widget, self).__init__(area)\n\n\nclass ComboBox(Widget):\n def __init__(self, area, keyValDict):\n super(Widget, self).__init__(area)\n self.__content = keyValDict\n self.__currentSelect = None\n self.__defaultText = ''\n self.__defaultButt = ''\n\n def setCaption(self, text):\n self.__defaultText = text\n\n" }, { "alpha_fraction": 0.6086105704307556, "alphanum_fraction": 0.6125244498252869, "avg_line_length": 23.380952835083008, "blob_id": "865db473700cb70d5d94c6ed4dfd2ff2817b7c6a", "content_id": "c6da2deb5608acaaf9b47edb96d6a581a7dabf2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 601, "license_type": "no_license", "max_line_length": 82, "num_lines": 21, "path": "/source/core/assembly/HtmlOperator.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from lxml import etree\n\n\nclass HtmlOperator:\n def __init__(self):\n pass\n\n @staticmethod\n def readFromFilePath(path, encoding='utf-8'):\n f = open(path, 'r', encoding=encoding) # 读取文件\n f = f.read() # 把文件内容转化为字符串\n html = etree.HTML(f) # 把字符串转化为可处理的格式\n return html\n\n @staticmethod\n def readText(Text):\n return etree.HTML(Text) # 把字符串转化为可处理的格式\n\nh = HtmlOperator()\ns = h.readText('<a href=\"javascript:void(0);\" id=\"green_channel_digg\" \">好文要顶</a>')\nprint(s)" }, { "alpha_fraction": 0.46815288066864014, "alphanum_fraction": 0.5, "avg_line_length": 21.285715103149414, "blob_id": "3aeb36fdcc4d587b53d59cd2d9fa81e5c3aed52f", "content_id": "893b72a5584ce2ad1728df0e9006f156a87a2231", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 314, "license_type": "no_license", "max_line_length": 36, "num_lines": 14, "path": "/source/core/assembly/Timer.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "class Timer:\n def __init__(self):\n self.__secondsPerCount = 0.0\n self.__deltaTime = -1.0\n\n self.__baseTime = 0\n self.__pausedTime = 0\n self.__stopTime = 0\n self.__prevTime = 0\n self.__currTime = 0\n\n self.__stopped = False\n\n self.countsPerSec = 0\n\n\n" }, { "alpha_fraction": 0.5114745497703552, "alphanum_fraction": 0.5436679720878601, "avg_line_length": 47.34062576293945, "blob_id": "a1b3c18cbd617f6357e26831def5e05d8a794996", "content_id": "0560b3511730be10172c6406eea1ad2c1fa01586", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31636, "license_type": "no_license", "max_line_length": 121, "num_lines": 640, "path": "/source/view/scene/Scenes.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import os\nimport time\nfrom operator import eq\n\nfrom source.core.assembly.AssetsFile import AssetsFile, AssetsType\nfrom source.core.assembly.IOEvent import ioEvent3Enum\nfrom source.view.baseClazz.Scene import Scene\nfrom source.view.element.Elements import TitleConstElement, TitleOptElement, TextElement, ImgElement, OptButtonElement, \\\n OptUIElement, SaveDataElement\nfrom source.core.const.Const import *\nfrom source.core.assembly.RecordFile import RecordFile\nfrom source.util.ToolsFuc import *\n\n\n# Logo场景\nclass LogoScene(Scene):\n def __init__(self, *args):\n super().__init__(*args)\n # 注册与该场景相关的场景\n from source.config.AppConfig import registerScene\n registerScene(SCENENUM_TITLE, TitleScene)\n\n self.Logo = 'IEELogo.bmp'\n self.__alpha = 0\n self.bg = pygame.image.load(gl_ImgPath + self.Logo)\n\n self.__step = 4\n self.__frameRate = self.config.getFrameRate()\n if self.__frameRate != 0:\n self.__step = 255 / (2 * self.__frameRate)\n self.setupSystemConsole = False\n\n def draw(self):\n if self.isReadyToEnter:\n self.__alpha -= self.__step\n else:\n self.__alpha += self.__step\n if self.__alpha > 255:\n self.isReadyToEnter = True\n if self.__alpha < 0:\n self.isEnd = True\n self.nextSceneNum = SCENENUM_TITLE\n blitAlpha(self.screen, self.bg, (0, 0), self.__alpha)\n\n\n# 标题场景\nclass TitleScene(Scene):\n def __init__(self, *args):\n # 注册场景\n super().__init__(*args)\n self.useDefaultDraw = False\n from source.config.AppConfig import registerScene\n registerScene(SCENENUM_GAME_PROLOGUE, Title_PrologueScene)\n registerScene(SCENENUM_OPT, OptionScene)\n registerScene(SCENENUM_CONTINUE, Continue_Scene)\n\n self.alpha = 0\n self.flag = False\n self.isMusicPlay = False\n\n self.wave_bgm = 'titleBackground.wav'\n self.titleBgName = 'titleBg.bmp'\n self.titleOptionName = 'titleOpts.bmp'\n self.titleName = 'titleTop.bmp'\n self.__res_s_cloud = 'T_S_C.png'\n self.__ast_name = 'I_T.assets'\n\n self.res_wave_bgm = pygame.mixer.Sound(gl_MusicPath + self.wave_bgm)\n self.res_wave_bgm.set_volume(self.config.getVolumeBGM())\n self.bg = pygame.image.load(gl_ImgPath + self.titleBgName)\n self.res_optionNewGame = pygame.image.load(gl_ImgPath + self.titleOptionName)\n self.res_title = pygame.image.load(gl_ImgPath + self.titleName)\n self.__frameRate = self.config.getFrameRate()\n\n self.__expBoardText = AssetsFile(os.path.join(gl_AssetsPath, 'TitleScene')).decode(\n self.__ast_name, AssetsType.EXP)\n\n # 创建相应的Element\n self.__board = TitleConstElement((gl_WindowWidth - 380, gl_WindowHeight - 80, 380, 80),\n blankSurface((380, 180), (255, 255, 255, 100)))\n self.__title = TitleConstElement((0, 0, 465, 74), clipResImg(self.res_title, (0, 0, 465, 74), (0, 0, 0)))\n self.__text = TextElement((gl_WindowWidth - 380, gl_WindowHeight - 80, 380, 80), self.__expBoardText[0],\n gl_Font, 16, (0, 0, 0), self.config.getTextAntiAlias())\n self.__optNewGame = TitleOptElement((140, 140, 116, 30), self.res_optionNewGame, (0, 0, 116, 30),\n (128, 128, 128))\n self.__optContinue = TitleOptElement((125, 180, 116, 30), self.res_optionNewGame, (0, 116, 116, 30),\n (128, 128, 128))\n self.__optOption = TitleOptElement((130, 220, 116, 30), self.res_optionNewGame, (0, 232, 116, 30),\n (128, 128, 128))\n self.__optExit = TitleOptElement((135, 260, 61, 30), self.res_optionNewGame, (0, 348, 61, 30), (128, 128, 128))\n\n self.__spriteCloud = ImgElement((801, -120, 750, 396), gl_ImgPath + self.__res_s_cloud)\n self.__spriteCloud.zIndex = -1\n self.__step = 1\n\n self.render.add(self.__board, self.__title, self.__text, self.__optNewGame, self.__optContinue,\n self.__optOption, self.__optExit)\n self.render.close()\n # 这里绑定和控件有交互的事件\n # ---NewGame选项绑定事件---\n self.__optNewGame.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick,\n lambda: self.__retSignalIsReadyToEnd(SCENENUM_GAME_PROLOGUE), 1)\n self.__optNewGame.Events.appendEvent(ioEvent3Enum.mouseIn,\n lambda: self.__changeBoardText(self.__expBoardText[1]), 1)\n self.__optNewGame.Events.appendEvent(ioEvent3Enum.mouseOut,\n lambda: self.__changeBoardText(self.__expBoardText[0]), 1)\n # ---Continue选项绑定事件---\n self.__optContinue.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick,\n lambda: self.__retSignalIsReadyToEnd(SCENENUM_CONTINUE), 1)\n self.__optContinue.Events.appendEvent(ioEvent3Enum.mouseIn,\n lambda: self.__changeBoardText(self.__expBoardText[2]), 1)\n self.__optContinue.Events.appendEvent(ioEvent3Enum.mouseOut,\n lambda: self.__changeBoardText(self.__expBoardText[0]), 1)\n # ---Option选项绑定事件---\n self.__optOption.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick,\n lambda: self.__retSignalIsReadyToEnd(SCENENUM_OPT), 1)\n self.__optOption.Events.appendEvent(ioEvent3Enum.mouseIn,\n lambda: self.__changeBoardText(self.__expBoardText[3]), 1)\n self.__optOption.Events.appendEvent(ioEvent3Enum.mouseOut,\n lambda: self.__changeBoardText(self.__expBoardText[0]), 1)\n # ---Exit选项绑定事件---\n self.__optExit.Events.appendEvent(ioEvent3Enum.mouseIn,\n lambda: self.__changeBoardText(self.__expBoardText[4]), 1)\n self.__optExit.Events.appendEvent(ioEvent3Enum.mouseOut,\n lambda: self.__changeBoardText(self.__expBoardText[0]), 1)\n self.__optExit.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick,\n lambda: pygame.event.post(pygame.event.Event(12)), 1)\n\n # 渲染参数\n self.__step_in = 2\n self.__step_out = 5\n if self.__frameRate != 0:\n self.__step_in = 255 / (2 * self.__frameRate)\n self.__step_out = 255 / (1.5 * self.__frameRate)\n\n # ---选项单独事件-开始---\n\n # 改变text渲染的文字\n def __changeBoardText(self, text):\n self.__text.setText(text)\n\n # 传递信号\n def __retSignalIsReadyToEnd(self, SceneNum):\n self.isReadyToEnd = True\n self.nextSceneNum = SceneNum\n\n # ---选项单独事件-结束---\n\n def draw(self):\n if not self.flag:\n self.alpha += self.__step_in\n if self.alpha >= 255:\n if not self.isMusicPlay:\n self.isMusicPlay = True\n self.res_wave_bgm.play(loops=-1)\n self.alpha = 255\n self.flag = True\n blitAlpha(self.screen, self.bg, (0, 0), self.alpha)\n if self.flag and not self.isReadyToEnd:\n # pass\n self.render.render(self.screen)\n # for e in self.__ElementsList:\n # e.draw(self.screen)\n if self.isReadyToEnd:\n self.res_wave_bgm.fadeout(2000)\n if self.alpha > 0:\n self.alpha -= self.__step_out\n blitAlpha(self.screen, self.bg, (0, 0), self.alpha)\n if self.alpha <= 0:\n self.res_wave_bgm.stop()\n self.isMusicPlay = False\n self.isEnd = True\n\n # def doClockEvent(self, NowClock):\n # _x = self.__spriteCloud.area.x\n # if _x < -750:\n # self.__spriteCloud.area.x = 801\n # # self.__step *= -1\n # self.__spriteCloud.area.x -= self.__step\n # # print((NowClock, _x))\n\n\n# 新游戏序章场景\nclass Title_PrologueScene(Scene):\n def __init__(self, *args):\n # 初始化场景参数\n super().__init__(*args)\n\n # resource name\n self.res_Img1 = 'NG_F_SS_1.bmp'\n self.res_Img2 = 'NG_F_SS_2.bmp'\n self.Sound_PourWine = 'NG_F_SS_PW.wav'\n self.Sound_Cup = 'NG_F_SS_C.wav'\n self.Sound_Drink = 'NG_F_SS_D.wav'\n self.Sound_Weak = 'NG_F_SS_W.wav'\n self.Music_BGM = 'NG_F_SS_BGM.wav'\n\n # assets name\n self.__asf_name1 = 'T_P.assets'\n self.__asf_name2 = 'T_P_C.assets'\n\n # 注册场景\n from source.config.AppConfig import registerScene\n registerScene(SCENENUM_GAME_STARTCG, Prologue_StartCGScene)\n\n # 音频\n # pygame.mixer.music.load(gl_MusicPath + \"TP_F_SS_BGM.mp3\")\n\n self.res_Sound_PourWine = pygame.mixer.Sound(gl_SoundPath + self.Sound_PourWine)\n self.res_Sound_PourWine.set_volume(self.config.getVolumeSound())\n\n self.res_Sound_Cup = pygame.mixer.Sound(gl_SoundPath + self.Sound_Cup)\n self.res_Sound_Cup.set_volume(self.config.getVolumeSound())\n\n self.res_Sound_Drink = pygame.mixer.Sound(gl_SoundPath + self.Sound_Drink)\n self.res_Sound_Drink.set_volume(self.config.getVolumeSound())\n\n self.res_Sound_Weak = pygame.mixer.Sound(gl_SoundPath + self.Sound_Weak)\n self.res_Sound_Weak.set_volume(self.config.getVolumeSound())\n\n self.res_Music_BGM = pygame.mixer.Sound(gl_MusicPath + self.Music_BGM)\n self.res_Music_BGM.set_volume(self.config.getVolumeBGM())\n\n # 其它元素\n self.__assetsFile = AssetsFile(os.path.join(gl_AssetsPath, 'PrologueScene'))\n self.__TextList = self.__assetsFile.decode(self.__asf_name1, AssetsType.SUB)\n self.__DialogueList = self.__assetsFile.decode(self.__asf_name2, AssetsType.SUB)\n\n self.__TextShow = TextElement((200, 460, 270, 18), self.__TextList[0], gl_Font_oth, 16, (255, 255, 255),\n self.config.getTextAntiAlias())\n self.__ImgShow = ImgElement((80, 0, 640, 480), gl_ImgPath + self.res_Img1)\n self.__DialogueShow = TextElement((0, 500, 430, 18), self.__DialogueList[0], gl_Font_oth, 16, (255, 255, 255),\n self.config.getTextAntiAlias())\n\n # 注册元素\n self.__ElementsList = []\n\n # 设定渲染时的参数\n self.__flag_Num = 0\n self.__flag_BGMPlayed = False\n self.now_time, self.interval = None, None\n self.__TextShow_Interval, self.__DialogueShow_Interval = 5000, 6000\n self.__alphaStep_Text, self.__alphaStep_Dia = 0, 0\n self.__index, self.__alpha = 0, 0\n self.__frameRate = self.config.getFrameRate()\n if self.__frameRate == 0:\n self.__alphaStep_Text = self.__TextShow_Interval / 1000 * 0.036\n self.__alphaStep_Dia = self.__DialogueShow_Interval / 1000 * 0.416\n else:\n self.__alphaStep_Text = 255 / (((self.__TextShow_Interval - 1500) / 1000) * self.__frameRate)\n self.__alphaStep_Dia = 255 / self.__frameRate\n\n def draw(self):\n self.now_time = pygame.time.get_ticks()\n self.interval = self.now_time - self.startClock\n\n if not self.isReadyToEnd:\n if self.__flag_Num == 0:\n # if not pygame.mixer.music.get_busy():\n # pygame.mixer.music.play()\n if self.interval > self.__TextShow_Interval:\n self.__alpha = 0\n self.startClock = pygame.time.get_ticks()\n self.__index += 1\n if self.__index >= len(self.__TextList):\n self.__index = 0\n self.__flag_Num = 1\n self.__alpha = 0\n pygame.mixer.music.stop()\n self.__ElementsList = [self.__ImgShow, self.__DialogueShow]\n else:\n self.__TextShow.setText(self.__TextList[self.__index])\n self.__alpha += self.__alphaStep_Text\n self.__TextShow.setAlpha(self.__alpha)\n self.screen.blit(self.__TextShow.res_surface, (\n centeredXPos(self.screen.get_width(), len(self.__TextShow.Text) * self.__TextShow.Size), 400))\n elif self.__flag_Num == 1:\n if not self.__flag_BGMPlayed:\n self.res_Music_BGM.play()\n self.__flag_BGMPlayed = True\n if self.__index == 0 or self.__index == 1:\n self.__alpha += self.__alphaStep_Dia\n self.__ImgShow.setAlpha(self.__alpha)\n self.__DialogueShow.setAlpha(self.__alpha - self.__alphaStep_Dia * self.__frameRate)\n if self.interval > self.__DialogueShow_Interval:\n self.__alpha = 0\n self.startClock = pygame.time.get_ticks()\n self.__index += 1\n if self.__index >= len(self.__DialogueList):\n self.res_Sound_Cup.play()\n time.sleep(1.4)\n self.isReadyToEnd = True\n else:\n self.__DialogueShow.setText(self.__DialogueList[self.__index])\n if self.__index == 1:\n self.res_Sound_Weak.play()\n self.__ImgShow.setPath(gl_ImgPath + self.res_Img2)\n if self.__index == 2:\n self.res_Sound_Cup.play()\n if self.__index == 3:\n self.res_Sound_PourWine.play()\n if self.__index == 4:\n self.res_Sound_Drink.play()\n self.screen.blit(self.__ImgShow.res_surface, (self.__ImgShow.area.x, self.__ImgShow.area.y))\n self.screen.blit(self.__DialogueShow.res_surface, (\n centeredXPos(self.screen.get_width(), len(self.__DialogueShow.Text) * self.__DialogueShow.Size),\n self.__DialogueShow.area.y))\n else:\n self.nextSceneNum = SCENENUM_GAME_STARTCG\n self.isEnd = True\n\n\n# 序章播放CG的场景,接下来的场景还没有编写,所以这里的下一个场景是开场Logo\nclass Prologue_StartCGScene(Scene):\n def __init__(self, *args):\n super().__init__(*args)\n vol = self.config.VolumeBGM\n print(vol)\n self.__PrologueCG = 'P_M_PCG.mp4'\n # 视频\n self.videoPlayer.add('bg_cg', gl_VideoPath + self.__PrologueCG, volume=[vol * 0.1, vol * 0.1])\n\n def draw(self):\n if not self.isReadyToEnd:\n self.videoPlayer.preview('bg_cg')\n self.isReadyToEnd = True\n else:\n # 这里的下一个场景是开场Logo\n self.nextSceneNum = SCENENUM_INIT\n self.isEnd = True\n\n\ndef ChePos(e, isDown):\n if isDown:\n e.area.x += 1\n e.area.y += 1\n else:\n e.area.x -= 1\n e.area.y -= 1\n\n\nclass OptionScene(Scene):\n def __init__(self, *args):\n super().__init__(*args)\n\n self.__flag_isEnter = False\n self.__alpha = 0\n self.__flag_recordStartTime = False\n self.__start_time = 0\n self.__now_time = 0\n\n if len(self.paramList) > 0:\n self.__flag_isEnter = self.paramList[0]\n\n # 注册与该场景相关的场景\n from source.config.AppConfig import registerScene\n registerScene(SCENENUM_OPT_APPLY, OptionScene, [True])\n\n self.res_Img_BG_Name = 'OPT_BG.bmp'\n self.res_Sound_Choose_Name = 'OPT_C.wav'\n self.res_UI_RightButton = 'OPT_BR.png'\n self.res_UI_LeftButton = 'OPT_BL.png'\n\n self.__Clock = pygame.time.Clock()\n self.__KV_AA = {}\n self.__KV_WAVE = {}\n self.__ElementsMap = {}\n\n if self.config.getTextAntiAlias():\n self.__KV_AA['key'] = '开'\n self.__KV_AA['val'] = '1'\n else:\n self.__KV_AA['key'] = '关'\n self.__KV_AA['val'] = '0'\n\n self.res_Sound_Choose = pygame.mixer.Sound(gl_SoundPath + self.res_Sound_Choose_Name)\n self.res_Sound_Choose.set_volume(self.config.getVolumeSound())\n\n self.res_Img_BG = pygame.image.load(gl_ImgPath + self.res_Img_BG_Name)\n\n self.__E_BGBlankL1 = OptButtonElement((40, 60, 200, 40), (255, 255, 255, 100))\n self.__E_BGBlankL2 = OptButtonElement((40, 110, 200, 40), (255, 255, 255, 100))\n self.__E_BGBlankL3 = OptButtonElement((40, 160, 200, 40), (255, 255, 255, 100))\n self.__E_BGBlankLRet = OptButtonElement((50, 520, 80, 40), (255, 255, 255, 100))\n self.__E_BGBlankLApply = OptButtonElement((150, 520, 80, 40), (255, 255, 255, 100))\n self.__E_BGBlankR = TitleConstElement((260, 60, 510, 500), blankSurface((510, 500), (255, 255, 255, 100)))\n self.__E_Text_Apply = TextElement((centeredXPos(80, 40, 150), centeredYPos(40, 20, 520), 120, 20), '应用',\n gl_Font_opt, 20, (0, 0, 0), self.config.getTextAntiAlias())\n self.__E_Text_Ret = TextElement((centeredXPos(80, 40, 50), centeredYPos(40, 20, 520), 120, 20), '返回',\n gl_Font_opt, 20, (0, 0, 0), self.config.getTextAntiAlias())\n\n self.__E_Text_Draw = TextElement((centeredXPos(200, 80, 40), centeredYPos(40, 20, 60), 80, 20), '画面设置',\n gl_Font_opt, 20, (0, 0, 0), self.config.getTextAntiAlias())\n self.__E_Text_AntiAlias = TextElement((270, 70, 120, 20), '抗锯齿:', gl_Font_opt, 18, (0, 0, 0),\n self.config.getTextAntiAlias())\n self.__E_Text_AA_Val = TextElement((670, 70, 20, 20), self.__KV_AA['key'], gl_Font_opt, 18, (0, 0, 0),\n self.config.getTextAntiAlias())\n\n self.__E_UI_AA_RightButton = OptUIElement((700, 70, 20, 20), gl_UIPath + self.res_UI_RightButton)\n self.__E_UI_AA_LeftButton = OptUIElement((640, 70, 20, 20), gl_UIPath + self.res_UI_LeftButton)\n self.__E_Text_Wave = TextElement((centeredXPos(200, 80, 40), centeredYPos(40, 20, 110), 80, 20), '声音设置',\n gl_Font_opt, 20, (0, 0, 0), self.config.getTextAntiAlias())\n self.__E_Text_BGMVolume = TextElement((270, 70, 120, 20), '音乐音量:', gl_Font_opt, 18, (0, 0, 0),\n self.config.getTextAntiAlias())\n self.__E_Text_BGM_Val = TextElement((660, 70, 30, 20), str(self.config.VolumeBGM), gl_Font_opt, 18, (0, 0, 0),\n self.config.getTextAntiAlias())\n self.__E_UI_BGM_RightButton = OptUIElement((700, 70, 20, 20), gl_UIPath + self.res_UI_RightButton)\n self.__E_UI_BGM_LeftButton = OptUIElement((630, 70, 20, 20), gl_UIPath + self.res_UI_LeftButton)\n self.__E_Text_SoundVolume = TextElement((270, 100, 120, 20), '音效音量:', gl_Font_opt, 18, (0, 0, 0),\n self.config.getTextAntiAlias())\n self.__E_Text_Sou_Val = TextElement((660, 100, 30, 20), str(self.config.VolumeSound), gl_Font_opt, 18,\n (0, 0, 0), self.config.getTextAntiAlias())\n self.__E_UI_Sou_RightButton = OptUIElement((700, 100, 20, 20), gl_UIPath + self.res_UI_RightButton)\n self.__E_UI_Sou_LeftButton = OptUIElement((630, 100, 20, 20), gl_UIPath + self.res_UI_LeftButton)\n\n self.__E_Text_Licence = TextElement(\n (centeredXPos(200, 120, 40), centeredYPos(40, 20, 160), 120, 20), '开源软件许可', gl_Font_opt, 20,\n (0, 0, 0), self.config.getTextAntiAlias())\n self.__E_Img_Licence = ImgElement(self.__E_BGBlankR.area, gl_ImgPath + 'OPT_L.lice', 255, (128, 128, 128))\n\n # 画面设置绑定事件\n self.__E_BGBlankL1.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: ChePos(self.__E_Text_Draw, True),\n 1)\n self.__E_BGBlankL1.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: self.__rebuildElementsToList2(\n [self.__E_Text_AntiAlias, self.__E_Text_AA_Val, self.__E_UI_AA_RightButton, self.__E_UI_AA_LeftButton]), 2)\n self.__E_BGBlankL1.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp, lambda: ChePos(self.__E_Text_Draw, False), 1)\n\n # 声音设置绑定事件\n self.__E_BGBlankL2.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: ChePos(self.__E_Text_Wave, True),\n 1)\n self.__E_BGBlankL2.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: self.__rebuildElementsToList2(\n [self.__E_Text_BGMVolume, self.__E_Text_SoundVolume, self.__E_Text_BGM_Val, self.__E_Text_Sou_Val,\n self.__E_UI_BGM_RightButton, self.__E_UI_BGM_LeftButton, self.__E_UI_Sou_RightButton,\n self.__E_UI_Sou_LeftButton]), 2)\n self.__E_BGBlankL2.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp, lambda: ChePos(self.__E_Text_Wave, False), 1)\n\n # 开源软件许可按钮绑定事件\n self.__E_BGBlankL3.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown,\n lambda: ChePos(self.__E_Text_Licence, True), 1)\n self.__E_BGBlankL3.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown,\n lambda: self.__rebuildElementsToList2([self.__E_Img_Licence]), 2)\n self.__E_BGBlankL3.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp, lambda: ChePos(self.__E_Text_Licence, False),\n 1)\n\n # 应用按钮绑定事件\n self.__E_BGBlankLApply.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown,\n lambda: ChePos(self.__E_Text_Apply, True), 1)\n self.__E_BGBlankLApply.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp,\n lambda: ChePos(self.__E_Text_Apply, False), 1)\n self.__E_BGBlankLApply.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick,\n lambda: self.__retSignalIsReadyToEnd(SCENENUM_OPT_APPLY), 1)\n self.__E_BGBlankLApply.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick, lambda: self.__updConfig(), 2)\n\n # 返回按钮绑定事件\n self.__E_BGBlankLRet.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: ChePos(self.__E_Text_Ret, True),\n 1)\n self.__E_BGBlankLRet.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp, lambda: ChePos(self.__E_Text_Ret, False),\n 1)\n self.__E_BGBlankLRet.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick,\n lambda: self.__retSignalIsReadyToEnd(SCENENUM_TITLE), 1)\n\n # 抗锯齿UI按钮绑定事件\n self.__E_UI_AA_LeftButton.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick, lambda: self.__chVal_AA_Txt(), 1)\n self.__E_UI_AA_RightButton.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick, lambda: self.__chVal_AA_Txt(), 1)\n\n # 改变音量UI按钮绑定事件\n self.__E_UI_BGM_LeftButton.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick,\n lambda: self.__chVal_WaveParam_Txt(self.__E_Text_BGM_Val, False,\n GLC_INI_PARAM_BGMVOLUME), 1)\n self.__E_UI_BGM_RightButton.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick,\n lambda: self.__chVal_WaveParam_Txt(self.__E_Text_BGM_Val, True,\n GLC_INI_PARAM_BGMVOLUME), 1)\n self.__E_UI_Sou_LeftButton.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick,\n lambda: self.__chVal_WaveParam_Txt(self.__E_Text_Sou_Val, False,\n GLC_INI_PARAM_SOUNDVOLUME), 1)\n self.__E_UI_Sou_RightButton.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick,\n lambda: self.__chVal_WaveParam_Txt(self.__E_Text_Sou_Val, True,\n GLC_INI_PARAM_SOUNDVOLUME), 1)\n\n self.__ElementsMap['Draw1'] = [self.__E_BGBlankL1, self.__E_BGBlankL2, self.__E_BGBlankL3, self.__E_BGBlankR,\n self.__E_Text_Draw, self.__E_Text_Wave, self.__E_Text_Licence,\n self.__E_BGBlankLApply,\n self.__E_Text_Apply, self.__E_BGBlankLRet, self.__E_Text_Ret]\n self.__ElementsMap['Draw2'] = [self.__E_Text_AntiAlias, self.__E_Text_AA_Val, self.__E_UI_AA_RightButton,\n self.__E_UI_AA_LeftButton]\n self.__ElementsMap['Interact1'] = [self.__E_BGBlankL1, self.__E_BGBlankL2, self.__E_BGBlankL3,\n self.__E_BGBlankLApply, self.__E_BGBlankLRet]\n self.__ElementsMap['Interact2'] = [self.__E_UI_AA_RightButton, self.__E_UI_AA_LeftButton]\n\n self.__ElementsMap['Draw'] = self.__ElementsMap['Draw1'] + self.__ElementsMap['Draw2']\n self.__ElementsMap['Interact'] = self.__ElementsMap['Interact1'] + self.__ElementsMap['Interact2']\n\n # 设定渲染参数\n self.__step = 4\n self.__frameRate = self.config.getFrameRate()\n if self.__frameRate:\n self.__step = 255 / (1.5 * self.__frameRate)\n\n # 替换ElementsList2的内容\n def __rebuildElementsToList2(self, _list):\n if _list is None or len(_list) <= 0:\n return\n self.__ElementsMap['Draw2'] = _list\n self.__ElementsMap['Interact2'].clear()\n for e in _list:\n if e.Events.getSize() > 0:\n self.__ElementsMap['Interact2'].append(e)\n self.__ElementsMap['Draw'] = self.__ElementsMap['Draw1'] + self.__ElementsMap['Draw2']\n self.__ElementsMap['Interact'] = self.__ElementsMap['Interact1'] + self.__ElementsMap['Interact2']\n\n # 改变抗锯齿UI所对应的值\n def __chVal_AA_Txt(self):\n if self.__KV_AA['val'] == '1':\n self.__KV_AA['key'] = '关'\n self.__KV_AA['val'] = '0'\n else:\n self.__KV_AA['key'] = '开'\n self.__KV_AA['val'] = '1'\n self.__E_Text_AA_Val.setText(self.__KV_AA['key'])\n\n # 改变Wave UI所对应的值\n def __chVal_WaveParam_Txt(self, elem, add, para):\n valF = float(elem.Text)\n if add:\n valF += 0.5\n if valF > 10:\n valF = 10.0\n else:\n valF -= 0.5\n if valF < 0:\n valF = 0.0\n self.__KV_WAVE[para] = str(valF)\n elem.setText(self.__KV_WAVE[para])\n\n # 序列化值更新设置文件\n def __updConfig(self):\n updateINI(GLC_INI_NAME, GLC_INI_SECTION_DRAW, GLC_INI_PARAM_ANTIALIAS, self.__KV_AA['val'])\n for k, v in self.__KV_WAVE.items():\n updateINI(GLC_INI_NAME, GLC_INI_SECTION_WAVE, k, v)\n\n # 传递信号\n def __retSignalIsReadyToEnd(self, SceneNum):\n self.isReadyToEnd = True\n self.nextSceneNum = SceneNum\n\n def draw(self):\n if not self.__flag_recordStartTime:\n self.__start_time = pygame.time.get_ticks()\n self.__flag_recordStartTime = True\n self.__now_time = pygame.time.get_ticks()\n\n blitAlpha(self.screen, self.res_Img_BG, (0, 0), self.__alpha)\n\n if not self.__flag_isEnter and not self.isReadyToEnd:\n self.__alpha += self.__step\n if self.__alpha >= 255:\n self.__alpha = 255\n self.__flag_isEnter = True\n elif self.__flag_isEnter and not self.isReadyToEnd:\n self.__alpha = 255\n for e in self.__ElementsMap['Draw']:\n e.draw(self.screen)\n if self.isReadyToEnd:\n self.isEnd = True\n\n def doMouseMotion(self, MouseRel, Buttons):\n # 鼠标移动事件\n for e in self.__ElementsMap['Interact']:\n if InElement(self.mousePos, e):\n self.focus = e\n if InElement(self.lastMousePos, e):\n e.Events.doMouseMotion()\n elif eq(Buttons, (0, 0, 0)):\n e.Events.doMouseIn()\n elif InElement(self.lastMousePos, e):\n e.Events.doMouseOut()\n if e.EventsHadDo.hadDoMouseLeftKeyDown:\n e.Events.doMouseLeftKeyUp()\n e.EventsHadDo.hadDoMouseLeftKeyDown = False\n e.EventsHadDo.hadDoMouseLeftKeyUp = True\n\n\nclass Continue_Scene(Scene):\n __ElementsList = None\n\n def __init__(self, *args):\n super().__init__(*args)\n self.__ElementsList = []\n self.__mappingList = []\n self.__res_n_OPT = 'CTU_OPT.png'\n self.__buildList()\n\n def __buildList(self):\n fs = []\n import os\n for root, dirs, files in os.walk(RECORDFILE_SAVE_PATH):\n fs += files\n for name in fs:\n if name.find(RECORDFILE_SAVE_NAMEHEAD) == 0 and name.find(RECORDFILE_SAVE_EXN) > 0:\n n = name.replace(RECORDFILE_SAVE_EXN, '')\n dataList = RecordFile(RECORDFILE_SAVE_PATH, n).getList()\n if dataList is not None:\n self.__ElementsList.append(\n SaveDataElement((83, 30, 636, 114), gl_UIPath + self.__res_n_OPT, 255, dataList))\n if len(self.__ElementsList) == 0:\n self.__ElementsList.append(\n (TextElement((centeredXPos(800, 220), centeredXPos(600, 35), 220, 35), '未找到游戏记录', gl_Font_oth, 30,\n (255, 255, 255, 255), self.config.getTextAntiAlias())))\n\n def __retSignalIsReadyToEnd(self, SceneNum):\n self.isReadyToEnd = True\n self.nextSceneNum = SceneNum\n\n def draw(self):\n if not self.isReadyToEnd:\n for e in self.__ElementsList:\n e.draw(self.screen)\n else:\n self.isEnd = True\n\n def doMouseMotion(self, MouseRel, Buttons):\n\n # 鼠标移动事件\n for e in self.__ElementsList:\n if InElement(self.mousePos, e):\n self.focus = e\n if InElement(self.lastMousePos, e):\n e.Events.doMouseMotion()\n elif eq(Buttons, (0, 0, 0)):\n e.Events.doMouseIn()\n elif InElement(self.lastMousePos, e):\n e.Events.doMouseOut()\n if e.EventsHadDo.hadDoMouseLeftKeyDown:\n e.Events.doMouseLeftKeyUp()\n e.EventsHadDo.hadDoMouseLeftKeyDown = False\n e.EventsHadDo.hadDoMouseLeftKeyUp = True\n\n def doMouseButtonDownEvent(self, Button):\n if Button == 3: # 左键\n self.__retSignalIsReadyToEnd(SCENENUM_TITLE)\n" }, { "alpha_fraction": 0.5735735893249512, "alphanum_fraction": 0.684684693813324, "avg_line_length": 21.200000762939453, "blob_id": "06d63838e3911084452e18b49aeaba762ae2c7c6", "content_id": "f6d3809c61a9cfb89f12ef374f901913c4f3fc71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 333, "license_type": "no_license", "max_line_length": 68, "num_lines": 15, "path": "/source/examples/ShapeTest.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.util.Shape import Square, Rectangle, CircumscribedCircle\n\n# c1 = Circle(10, 10, 5)\nsq1 = Square(10, 10, 5)\nsq2 = Rectangle(10, 10, 5, 6)\nsq3 = Square(10, 10, 5)\n# print(sq1)\n# c2 = InscribedCircle(sq1)\nc3 = CircumscribedCircle(sq2)\n# print(c2)\n# print(c3)\n# print(sq1.intersects(sq2))\nprint(c3.x)\n\n# print(sq2.same(sq1))\n" }, { "alpha_fraction": 0.4613220691680908, "alphanum_fraction": 0.4739803075790405, "avg_line_length": 22.700000762939453, "blob_id": "5133373996cfb3f69a89d58f68e281fafa47cf94", "content_id": "9a0f4fd597fcb028dddba64cd8b0bef88e788869", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 711, "license_type": "no_license", "max_line_length": 47, "num_lines": 30, "path": "/source/core/assembly/container.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "class MiniQueue:\n def __init__(self, capacity):\n self.__capacity = capacity\n self.__ptr = -1\n self.__list = [None] * self.__capacity\n\n def __str__(self):\n return self.__list.__str__()\n\n def __len__(self):\n return self.__ptr + 1\n\n def content(self):\n return self.__list\n\n def size(self):\n return self.__capacity\n\n def push(self, e):\n self.__ptr += 1\n if self.__ptr > self.__capacity - 1:\n self.pop()\n self.__list[self.__ptr] = e\n\n def pop(self):\n e = self.__list[0]\n for i in range(0, self.__capacity - 1):\n self.__list[i] = self.__list[i + 1]\n self.__ptr -= 1\n return e\n" }, { "alpha_fraction": 0.6168224215507507, "alphanum_fraction": 0.6355140209197998, "avg_line_length": 31.923076629638672, "blob_id": "ff3d58906cc7658dd09489413065ba3aa9acc958", "content_id": "a93d5053e66dd40a708202684023bbf50db04cb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 428, "license_type": "no_license", "max_line_length": 116, "num_lines": 13, "path": "/source/view/sprite/Sprites.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.view.baseClazz.Sprite import Sprite\n\n\nclass CursorSprite(Sprite):\n def __init__(self, *args, colorKey=(0, 0, 0)):\n super(CursorSprite, self).__init__(image='F:/Practice/PyCharm/PygameTest/source/view/origin/res/cursor.bmp')\n self.zIndex = 100\n self.image.set_colorkey(colorKey)\n self.visual = False\n\n def update(self, pos):\n self.rect.x = pos[0]\n self.rect.y = pos[1]\n" }, { "alpha_fraction": 0.5005780458450317, "alphanum_fraction": 0.5098266005516052, "avg_line_length": 23.02777862548828, "blob_id": "df508d1b358cdcc0428ba76354a64721b486efbb", "content_id": "af70904da87a9fce59f434f09e285abdc1d35a13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 865, "license_type": "no_license", "max_line_length": 103, "num_lines": 36, "path": "/source/view/baseClazz/ConsoleVariable.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "class CVState:\n ready = 0\n active = 1\n wait = 2\n running = 3\n dead = 4\n\n def returnName(self, num):\n if num == self.ready:\n return 'ready'\n if num == self.active:\n return 'active'\n if num == self.wait:\n return 'wait'\n if num == self.running:\n return 'running'\n if num == self.dead:\n return 'dead'\n\n\nclass ConsoleVariable:\n counter = 0\n\n def __init__(self):\n self.name = 'ConsoleVariable' + str(self.counter)\n self.val = 0\n self.describe = 'null'\n self.fuc = lambda: ()\n self.__state = CVState.ready\n self.counter += 1\n\n def __str__(self):\n return self.name + ': \\n' + self.describe + '\\n' + 'state: ' + CVState.returnName(self.__state)\n\n def changeSate(self, state):\n self.__state = state\n" }, { "alpha_fraction": 0.5658363103866577, "alphanum_fraction": 0.5658363103866577, "avg_line_length": 20.615385055541992, "blob_id": "644d33ef9ed5af8adb911334d5eca72867d2ad70", "content_id": "3b303288f99463aa772dcb69d50db4d979bbbc4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 281, "license_type": "no_license", "max_line_length": 34, "num_lines": 13, "path": "/source/core/render/Renderer.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "class Renderer:\n def __init__(self, trans):\n self.__transform = trans\n self.__renderList = []\n\n def setTransform(self, trans):\n self.__transform = trans\n\n def getTransform(self):\n return self.__transform\n\n def add(self, *args):\n pass\n" }, { "alpha_fraction": 0.5687496066093445, "alphanum_fraction": 0.5959609150886536, "avg_line_length": 41.60055923461914, "blob_id": "56f93f83c7b8933de93e8a5a99987c925ffad36d", "content_id": "9ba82a36d1431a8c967fe39df8db07a2226f29aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15627, "license_type": "no_license", "max_line_length": 119, "num_lines": 358, "path": "/source/guitools/AnimaEditor.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import tkinter.filedialog\nimport tkinter.messagebox\nfrom operator import eq\n\nimport pygame\n\nfrom source.core.assembly.Anime import AnimeFrame, AnimePart\nfrom source.core.const.Const import gl_Font_opt\nfrom source.core.math.Shape import Rectangle\nfrom source.core.math.Vector import vec2, vec4\nfrom source.util.ToolsFuc import centeredXPos, centeredYPos, InElement\nfrom source.view.baseClazz.Actor import Actor\nfrom source.view.baseClazz.Element import Element\nfrom source.view.baseClazz.Scene import Scene\nfrom source.view.element.Control import InputElement\nfrom source.view.element.Elements import TextElement, ioEvent3Enum, ImgElement\n\n\n# def openFiledialog():\n# root = tkinter.Tk()\n# root.withdraw()\n# print(tkinter.filedialog.askopenfilenames(title='选择一个文件', filetypes=[('Images', '.jpg .jpge .bmp .png')])\n\n\n# class Operation:\n# def __init__(self, name, width, height, _id):\n# texture = pygame.image.load(name)\n# texture_w = texture.get_rect().w\n# texture_h = texture.get_rect().h\n# area = Rectangle(centeredXPos(width, texture_w), centeredYPos(height, texture_h), texture_w, texture_h)\n# self.actor = Actor(texture, area)\n# self.element = ImgElement(area, name)\n# self.id = _id\n\nclass showImgWin(ImgElement):\n def __init__(self, area):\n super(showImgWin, self).__init__(area, path=None, alpha=255, colorKey=None)\n\n def showImg(self, currentOperation):\n _tex = currentOperation.getInitTexture()\n _texW = _tex.get_rect().w\n _texH = _tex.get_rect().h\n if _texH > _texW:\n scaleSizeY = self.area.size()[1]\n scaleSizeX = scaleSizeY / _texH * _texW\n blitLocal = (centeredXPos(self.area.w, scaleSizeX), 0)\n else:\n scaleSizeX = self.area.size()[0]\n scaleSizeY = scaleSizeX / _texW * _texH\n blitLocal = (0, centeredYPos(self.area.h, scaleSizeY))\n suf = pygame.transform.scale(_tex, (int(scaleSizeX), int(scaleSizeY)))\n self.clear((0, 0, 0))\n self.res_surface.blit(suf, blitLocal)\n\n\nclass butElement(TextElement):\n def __init__(self, area, text, font, size, color, antiAlias):\n super(butElement, self).__init__(area, text, font, size, color, antiAlias)\n self.zIndex = 999\n self.Events.appendEvent(ioEvent3Enum.mouseIn, lambda: self.__evn_chColor(1), 0)\n self.Events.appendEvent(ioEvent3Enum.mouseOut, lambda: self.__evn_chColor(0), 0)\n\n def __evn_chColor(self, isIn):\n if isIn:\n self.setColor((0, 162, 232))\n else:\n self.setColor((255, 255, 255))\n\n\nclass Operation(ImgElement):\n def __init__(self, name, bgWidth, bgHeight, _id):\n self.texture = pygame.image.load(name)\n self.__texture_w = self.texture.get_rect().w\n self.__texture_h = self.texture.get_rect().h\n area = Rectangle(centeredXPos(bgWidth, self.__texture_w), centeredYPos(bgHeight, self.__texture_h),\n self.__texture_w, self.__texture_h)\n super(Operation, self).__init__(area, name)\n self.id = _id\n self.Interpolation = None\n self.InterpData = dict()\n self.__bkupTex = self.texture\n\n self.__AnimeSequence = list()\n self.__AnimeFrames = list()\n\n self.Events.appendEvent(ioEvent3Enum.mouseRollDown, lambda: self.__evn_downsizeTex(1), 0)\n self.Events.appendEvent(ioEvent3Enum.mouseRollUp, lambda: self.__evn_downsizeTex(0), 0)\n\n self.__index = 0\n\n # def showOperate(self):\n #\n\n def __evn_downsizeTex(self, typ):\n if typ:\n self.texture = pygame.transform.scale(self.__bkupTex, (\n int(self.__texture_w - 0.1 * self.__texture_w), int(self.__texture_h - 0.1 * self.__texture_h)))\n else:\n self.texture = pygame.transform.scale(self.__bkupTex, (\n int(self.__texture_w + 0.1 * self.__texture_w), int(self.__texture_h + 0.1 * self.__texture_h)))\n self.area = Rectangle(self.area.x, self.area.y, self.texture.get_rect().w,\n self.texture.get_rect().h)\n self.__texture_w = self.area.w\n self.__texture_h = self.area.h\n self.res_surface = self.texture\n\n def getInitTexture(self):\n return self.__bkupTex\n\n def clearAnimeData(self):\n self.__AnimeFrames.clear()\n\n def record(self, time):\n _animeFrame = AnimeFrame(time, vec4(self.area.local(), self.area.size()))\n self.__AnimeFrames.append(_animeFrame)\n\n def showAnime(self):\n if len(self.__AnimeFrames) > 0:\n _frame = self.__AnimeFrames[self.__index]\n self.area.x = _frame.local.x\n self.area.y = _frame.local.y\n self.res_surface = pygame.transform.scale(self.__bkupTex, (int(_frame.local.z), int(_frame.local.w)))\n self.__index += 1\n if self.__index >= len(self.__AnimeFrames):\n self.__index = 0\n\n def getAnimeFrames(self):\n return self.__AnimeFrames\n\n # def __evn_enlargeTex(self):\n # self.texture = pygame.transform.scale(self.texture, (\n # int(self.__texture_w + 0.1 * self.__texture_w), int(self.__texture_h + 0.1 * self.__texture_h)))\n # self.__texture_w = self.texture.get_rect().w\n # self.__texture_h = self.texture.get_rect().h\n # self.res_surface = self.texture\n\n # def draw(self, screen):\n # screen.blit(texture)\n\n\nclass AnimaEditor(Scene):\n def __init__(self, *args):\n super(AnimaEditor, self).__init__(*args)\n self.caption = \"sgf-py GUITools AnimeEditor GUI工具 动画编辑器\"\n self.materialList = list()\n self.butOutput = butElement((10, 10, 34, 18), \"导出\", gl_Font_opt, 16, (255, 255, 255), 1)\n self.butInput = butElement((50, 10, 34, 18), \"导入\", gl_Font_opt, 16, (255, 255, 255), 1)\n self.butClear = butElement((90, 10, 34, 18), \"清空\", gl_Font_opt, 16, (255, 255, 255), 1)\n self.butDel = butElement((130, 10, 34, 18), \"删除\", gl_Font_opt, 16, (255, 255, 255), 1)\n self.butStart = butElement((170, 10, 34, 18), \"开始\", gl_Font_opt, 16, (255, 255, 255), 1)\n self.__flg_isStart = False\n self.butKeyFrame = butElement((210, 10, 82, 18), \"设定关键帧\", gl_Font_opt, 16, (255, 255, 255), 1)\n self.butSetTime = butElement((300, 10, 66, 18), \"设定时间\", gl_Font_opt, 16, (255, 255, 255), 1)\n self.butSetIntpol = butElement((370, 10, 66, 18), \"插值方式\", gl_Font_opt, 16, (255, 255, 255), 1)\n self.butHelp = butElement((440, 10, 34, 18), \"帮助\", gl_Font_opt, 16, (255, 255, 255), 1)\n\n self.currentShow = showImgWin((600, 0, 200, 150))\n self.currentShow.zIndex = 999\n\n self.butReshow = butElement((10, self.height - 30, 34, 18), \"回放\", gl_Font_opt, 16, (255, 255, 255), 1)\n self.__flg_reshow = False\n self.butReshowAll = butElement((50, self.height - 30, 66, 18), \"全部回放\", gl_Font_opt, 16, (255, 255, 255), 1)\n self.butClearData = butElement((120, self.height - 30, 66, 18), \"清除数据\", gl_Font_opt, 16, (255, 255, 255), 1)\n self.__flg_reshowAll = False\n\n self.__flg_currentShowIsDownsize = False\n self.currentShow.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick, lambda: self.__evn_scale(), 1)\n\n self.inputBox = InputElement((centeredXPos(self.width, 200), self.height - 30, 200, 20), \"input\")\n self.inputBox.zIndex = 999\n\n self.currtOp = None\n self.__prop_Interval = 1\n\n self.__recordStartTime = 0\n self.__index = 0\n\n def __evn_scale(self):\n if not self.__flg_currentShowIsDownsize:\n self.currentShow.area.x = 750\n self.__flg_currentShowIsDownsize = True\n else:\n self.currentShow.area.x = 600\n self.__flg_currentShowIsDownsize = False\n\n def setup(self):\n self.render.open()\n self.render.add(self.currentShow)\n self.render.add(self.butOutput)\n self.render.add(self.butInput)\n self.render.add(self.butClear)\n self.render.add(self.butDel)\n self.render.add(self.butStart)\n self.render.add(self.butKeyFrame)\n self.render.add(self.butSetTime)\n self.render.add(self.butSetIntpol)\n self.render.add(self.butReshow)\n self.render.add(self.butHelp)\n self.render.add(self.butReshowAll)\n self.render.add(self.butClearData)\n self.render.add(self.inputBox)\n self.render.close()\n self.id = 0\n\n self.butInput.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick, lambda: self.__evn_selMaterials(), 1)\n self.butOutput.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick, lambda: self.__evn_save(), 1)\n self.butClear.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick, lambda: self.__evn_clear(), 1)\n self.butDel.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick, lambda: self.__evn_del(), 1)\n self.butStart.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick, lambda: self.__evn_start(), 1)\n self.butSetTime.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick, lambda: self.__evn_setTime(), 1)\n self.butReshow.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick, lambda: self.__evn__reshow(), 1)\n self.butReshowAll.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick, lambda: self.__evn_reshowAll(), 1)\n self.butClearData.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick, lambda: self.__evn_clearData(), 1)\n\n self.createTextElement(\"\", pos=self.BOTTOM_RIGHT, length=180, font=gl_Font_opt, color=(255, 127, 39))\n self.createTextElement(\"FPS:\" + str(self.FPS), pos=self.TOP_RIGHT, font=gl_Font_opt, color=(255, 127, 39))\n\n def __evn_clearData(self):\n if self.currtOp:\n self.currtOp.clearAnimeData()\n self.getCreatedElement(0).setText(\"已删除对象动画数据\")\n\n def __evn_reshowAll(self):\n if len(self.materialList) > 0:\n self.__flg_reshowAll = not self.__flg_reshowAll\n if self.__flg_reshowAll:\n self.butReshow.active = False\n self.getCreatedElement(0).setText(\"正在播放全部对象动画\")\n self.butReshowAll.setText(\"全部暂停\")\n else:\n self.butReshow.active = True\n self.getCreatedElement(0).setText(\"全部对象动画播放完毕\")\n self.butReshowAll.setText(\"全部回放\")\n\n def __evn__reshow(self):\n if len(self.materialList) > 0:\n self.__flg_reshow = not self.__flg_reshow\n if self.__flg_reshow:\n self.getCreatedElement(0).setText(\"正在播放当前对象动画\")\n self.butReshow.setText(\"暂停\")\n else:\n self.getCreatedElement(0).setText(\"当前对象动画播放完毕\")\n self.butReshow.setText(\"回放\")\n\n def __evn_setTime(self):\n def on_click():\n _interval_str = xls_text.get().lstrip()\n if len(_interval_str) != 0:\n try:\n time_float = float(_interval_str)\n except ValueError:\n return\n finally:\n root.quit()\n root.destroy()\n self.__prop_Interval = time_float\n self.caption += \" interval:\" + _interval_str\n\n # root = tkinter.Tk()\n root = tkinter.Tk()\n root.title(\"设定时间\")\n xls_text = tkinter.StringVar()\n l1 = tkinter.Label(root, text=\"请输入时间,时间必须为整型或浮点数:\")\n l1.pack() # 这里的side可以赋值为LEFT RTGHT TOP BOTTOM\n xls = tkinter.Entry(root, textvariable=xls_text)\n xls_text.set(\" \")\n xls.pack()\n tkinter.Button(root, text=\"确认\", command=on_click).pack()\n root.mainloop()\n # root.withdraw()\n # tkinter.messagebox.askyesno(title='系统提示', message='是否需要')\n\n def __evn_start(self):\n if len(self.materialList) > 0:\n if self.__flg_reshow or self.__flg_reshowAll:\n self.getCreatedElement(0).setText(\"正在播放,无法录制\")\n return\n if not self.__flg_isStart:\n # if not self.__flg_isStart and self.currtOp:\n self.__flg_isStart = True\n self.getCreatedElement(0).setText(\"已开始捕捉动画\")\n self.butStart.setText(\"完成\")\n else:\n self.__flg_isStart = False\n self.getCreatedElement(0).setText(\"捕捉动画停止\")\n self.butStart.setText(\"开始\")\n\n # def __evn_stop(self):\n # if self.__flg_isStart:\n # self.__flg_isStart = False\n # self.getCreatedElement(0).setText(\"捕捉动画停止\")\n\n def __evn_selMaterials(self):\n root = tkinter.Tk()\n root.withdraw()\n _nameTuple = tkinter.filedialog.askopenfilenames(title='选择一个文件', filetypes=[('Images', '.jpg .jpge .bmp .png'),\n ('sgfPyAnimeData', '.anime')])\n for name in _nameTuple:\n op = Operation(name, self.width, self.height, self.id)\n op.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: self.__evn_curt(), 1)\n op.Events.appendEvent(ioEvent3Enum.mouseRightKeyDown, lambda: self.__evn_start(), 1)\n self.materialList.append(op)\n self.render.open()\n self.render.add(op)\n self.render.close()\n self.id += 1\n\n def __evn_save(self):\n root = tkinter.Tk()\n root.withdraw()\n _nameTuple = tkinter.filedialog.asksaveasfile(filetypes=[('sgfPyAnimeData', '.anime')])\n\n def __evn_clear(self):\n self.render.clearLog()\n self.render.open()\n for e in self.materialList:\n self.render.remove(e.zIndex, e)\n self.render.close()\n self.materialList.clear()\n\n def __evn_curt(self):\n self.currtOp = self.focus\n self.__index = 0\n\n def __evn_del(self):\n if self.currtOp in self.materialList:\n self.materialList.remove(self.currtOp)\n self.render.open()\n self.render.remove(self.currtOp.zIndex, self.currtOp)\n self.render.close()\n\n def doMouseMotion(self, MouseRel, Buttons):\n if self.currtOp and eq(Buttons, (1, 0, 0)) and InElement(self.mousePos, self.currtOp):\n barycenter = self.currtOp.area.barycenter()\n barycenter.x += self.mousePos[0] - self.lastMousePos[0]\n barycenter.y += self.mousePos[1] - self.lastMousePos[1]\n self.currtOp.area.rebuildForBarycenter(barycenter)\n\n def doClockEvent(self, NowClock):\n self.getCreatedElement(1).setText(\"FPS:\" + str(self.FPS))\n if self.currtOp:\n self.currentShow.showImg(self.currtOp)\n if self.currtOp and self.__flg_isStart:\n if self.__recordStartTime == 0:\n self.__recordStartTime = NowClock\n self.currtOp.record(NowClock - self.__recordStartTime)\n if self.currtOp and self.__flg_reshow:\n self.currtOp.showAnime()\n if self.__flg_reshowAll and len(self.materialList) > 0:\n self.__flg_reshow = False\n self.butReshow.setText(\"回放\")\n for op in self.materialList:\n op.showAnime()\n\n def doKeyEvent(self, Key, Mod, Type, Unicode):\n if Type == 0:\n self.inputBox.Events.doKeyDown(Key)\n print(Key, chr(Key), Mod, Unicode)\n" }, { "alpha_fraction": 0.5411764979362488, "alphanum_fraction": 0.5411764979362488, "avg_line_length": 23.14285659790039, "blob_id": "88fb845ea69505baf703184b58ec58882be92754", "content_id": "ed44a869360bfffd37a7cafaa9bc144015e5db77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 170, "license_type": "no_license", "max_line_length": 36, "num_lines": 7, "path": "/source/core/dataType/CallBack.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "class CallBack:\n def __init__(self, name, param):\n self.__fucName = name\n self.__param = param\n\n def exc(self):\n self.__fucName(self.__param)\n\n" }, { "alpha_fraction": 0.4485900104045868, "alphanum_fraction": 0.48242950439453125, "avg_line_length": 31.928571701049805, "blob_id": "ae16ba602a13345b36f40f72bb64b04ab64415af", "content_id": "3d03cfa7b3fcf5898306bc7114ae0e87f2293d0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2337, "license_type": "no_license", "max_line_length": 106, "num_lines": 70, "path": "/source/core/draw/Brush.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import pygame\n\nfrom source.core.draw.Color import color\nfrom source.core.exception.SGFpyException import SGFpyException\nfrom source.core.math.MathUtil import mapping\nfrom source.core.math.Vector import vec3\n\n\nclass outOfRangeException(SGFpyException):\n def __init__(self, num, limit):\n self.num = num\n self.limit = limit\n\n def __str__(self):\n return '{} out of limit RectRange{}'.format(self.num, self.limit)\n\n\nclass brush:\n def __init__(self, canvas, _color, width):\n self.width = width\n a = _color[3] if len(_color) > 3 else 1\n self.color = color(_color[0], _color[1], _color[2], a)\n self.canvas = canvas\n\n def drawLine(self, start, stop, aa=0):\n # pix = []\n x1, y1, x2, y2 = int(start[0]), int(start[1]), int(stop[0]), int(stop[1])\n if x1 > self.canvas.width or x1 < 0 or y1 > self.canvas.height or y1 < 0 \\\n or x2 > self.canvas.width or x2 < 0 or y2 > self.canvas.height or y2 < 0:\n raise outOfRangeException(((x1, y1), (x2, y2)), (0, 0, self.canvas.width, self.canvas.height))\n dx, dy, yy = int(abs(x2 - x1)), int(abs(y2 - y1)), 0\n\n if dx < dy:\n yy = 1\n x1, y1 = y1, x1\n x2, y2 = y2, x2\n dx, dy = dy, dx\n\n ix = 1 if x2 - x1 > 0 else -1\n iy = 1 if y2 - y1 > 0 else -1\n cx, cy = x1, y1\n n2dy, n2dydx = dy * 2, (dy - dx) * 2\n d = dy * 2 - dx\n\n if yy: # 直线与x轴大于45度\n while cx != x2:\n if d < 0:\n d += n2dy\n else:\n cy += iy\n d += n2dydx\n # pix.append((cy, cx))\n self.canvas.setPix(cy, cx, self.color)\n cx += ix\n else: # 直线与x轴小于等于45度\n while cx != x2:\n if d < 0:\n d += n2dy\n else:\n cy += iy\n d += n2dydx\n # pix.append((cx, cy))\n self.canvas.setPix(cx, cy, self.color)\n\n cx += ix\n\n # if aa:\n # pygame.draw.aaline(self.canvas.surface(), self.color.aryRGB(), start, stop, 1)\n # else:\n # pygame.draw.line(self.canvas.surface(), self.color.aryRGB(), start, stop, self.width)\n" }, { "alpha_fraction": 0.5858895778656006, "alphanum_fraction": 0.5858895778656006, "avg_line_length": 22.285715103149414, "blob_id": "c618853b22c33eb4638300c5117873fbe159e377", "content_id": "293abe171ff729284381435ec03c9859ab43d8df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 326, "license_type": "no_license", "max_line_length": 53, "num_lines": 14, "path": "/source/core/thread/Thread.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import threading\n\n\nclass core_thread(threading.Thread):\n def __init__(self, threadID, name, counter, fuc):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n self.fuc = fuc\n\n def run(self):\n print(self.name)\n self.fuc()\n" }, { "alpha_fraction": 0.6559633016586304, "alphanum_fraction": 0.6559633016586304, "avg_line_length": 26.25, "blob_id": "f6b0e9106b77eeee0f0b92d26f3134773cb2bc59", "content_id": "bd4a9a985cef03c5039ce02d619049d564c225c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 218, "license_type": "no_license", "max_line_length": 45, "num_lines": 8, "path": "/source/view/entity/NPC.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.view.baseClazz.Actor import Actor\nfrom source.model.User import User\n\n\nclass NPC(Actor, User):\n def __init__(self, texture, area):\n Actor.__init__(self, texture, area)\n User.__init__(self)\n" }, { "alpha_fraction": 0.46060606837272644, "alphanum_fraction": 0.47999998927116394, "avg_line_length": 22.571428298950195, "blob_id": "199129ef1eadd43fa14f15f77ef7552688a3ffa6", "content_id": "4b3ca1448947bd816be69aee9adf2348cc7fd16a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 903, "license_type": "no_license", "max_line_length": 55, "num_lines": 35, "path": "/source/util/KMP.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "def get_next_group(one_str) -> list:\n \"\"\" 获取到next数组 \"\"\"\n length = len(one_str)\n next_group = [0] * length\n next_group[0] = -1\n point = -1\n i = 0\n while i < length - 1:\n if point == -1 or one_str[i] == one_str[point]:\n point += 1\n i += 1\n next_group[i] = point\n else:\n point = next_group[point]\n return next_group\n\n\ndef KMPMatching(s, t) -> int:\n \"\"\"\n KMP算法匹配字符串\n :param s:要匹配的字符串\n :param t:模式串\n :return:int 要匹配的字符串中的索引, 匹配失败返回-1\n \"\"\"\n nextGroup = get_next_group(t)\n j, i = -1, -1\n while j != len(t) and i < len(s):\n if s[i] == t[j] or j == -1:\n i, j = i + 1, j + 1\n else:\n j = nextGroup[j]\n return i - j if j == len(t) else -1\n\n\nprint(KMPMatching('ababxbabcdabdfdsss', 'aba'))\n" }, { "alpha_fraction": 0.5106382966041565, "alphanum_fraction": 0.5398514270782471, "avg_line_length": 35.55555725097656, "blob_id": "4784ff9fb4453c2afbc59f02e33508efc899f420", "content_id": "bccfefd4fa2c7a4dfaefc8e447329b5ee2eae6b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5936, "license_type": "no_license", "max_line_length": 106, "num_lines": 162, "path": "/source/examples/RTS_Test.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import random\n\nimport pygame\n\nfrom source.core.const.Const import gl_Font\nfrom source.core.assembly.A_star import AStarArea, CoordinateException\nfrom source.core.math.Vector import point2\nfrom source.core.math.Shape import Rectangle\nfrom source.core.assembly.Painter import Painter\nfrom source.view.baseClazz.Actor import Actor\nfrom source.view.baseClazz.Scene import Scene\nfrom source.view.element.Elements import TextElement\n\n\nclass RobotActor(Actor):\n def __init__(self, area):\n path = 'F:/Practice/PyCharm/PygameTest/resource/Test/robot.png'\n super(RobotActor, self).__init__(pygame.image.load(path), area)\n self.__linePoints = [point2(), point2()]\n self.__startCord = self.area.barycenter()\n self.max_speed = 10\n self.__pathList = []\n self.__interPath = []\n\n def setPathList(self, lis):\n self.__pathList = lis.copy()\n\n def draw(self, screen):\n screen.blit(self.texture, (self.area.left(), self.area.top()))\n sp, ep = self.__linePoints[0], self.__linePoints[1]\n if not sp.same(ep):\n Painter(screen).Lines(self.__linePoints, (0, 255, 0), 1, 0)\n\n def update(self, point, speed, end_point):\n pos = self.area.barycenter()\n if point.same(end_point):\n pos.x = point.x\n pos.y = point.y\n self.__linePoints.clear()\n self.__linePoints = [end_point, pos]\n self.area.rebuildForBarycenter(pos)\n if pos.same(point):\n return True\n else:\n dir_x, dir_y = 0, 0\n if pos.x < point.x:\n dir_x = 1\n elif pos.x > point.x:\n dir_x = -1\n\n if pos.y < point.y:\n dir_y = 1\n elif pos.y > point.y:\n dir_y = -1\n\n pos.x += dir_x * speed\n pos.y += dir_y * speed\n\n self.__linePoints.clear()\n self.__linePoints = [end_point, pos]\n self.area.rebuildForBarycenter(pos)\n return False\n\n def getLocal(self):\n return self.area.barycenter()\n\n\nclass Container(Actor):\n def __init__(self, area):\n path = 'F:/Practice/PyCharm/PygameTest/resource/Test/container.jpg'\n super(Container, self).__init__(pygame.image.load(path), area)\n\n def draw(self, screen):\n screen.blit(self.texture, (self.area.left(), self.area.top()))\n\n\nclass RobotRunScene(Scene):\n def __init__(self, screen, config, startClock):\n super(RobotRunScene, self).__init__(screen, config, startClock)\n self.w, self.h = self.screen.get_width(), self.screen.get_height()\n self.__As_MAP = AStarArea(Rectangle(0, 0, 800, 600), 80, 60)\n self.caption = 'Actor与A*结合测试场景'\n self.__containers = []\n for i in range(0, 6):\n x = int(random.randint(100, self.w - 150) / 10) * 10\n y = int(random.randint(100, self.h - 150) / 10) * 10\n w = int(random.randint(50, 150) / 10) * 10\n h = int(random.randint(50, 150) / 10) * 10\n self.__containers.append(Container(Rectangle(x, y, w, h)))\n _x, _y = int(x / self.__As_MAP.unit_w), int(y / self.__As_MAP.unit_h)\n _w, _h = int(w / self.__As_MAP.unit_w), int(h / self.__As_MAP.unit_h)\n self.__As_MAP.addObstacleArea(_x, _w, _y, _h)\n\n self.__A_Robot = RobotActor(Rectangle(0, 0, 100, 100))\n self.__E_Msg = TextElement((600, 0, 200, 60), 'Robotlocal:(0, 0)\\nMouselocal:(0, 0)', gl_Font, 12,\n (255, 255, 255), 1)\n self.__E_Msg2 = TextElement((600, 40, 200, 600), 'Astart:\\n', gl_Font, 10, (255, 255, 255), 1)\n self.__pathList = []\n self.__normalLis = []\n self.__build_As_Map()\n self.__i = 0\n self.__end = (0, 0)\n\n def __build_As_Map(self):\n self.__As_MAP.setStart((0, 0))\n\n def __updateMap(self, point):\n h, w = self.__As_MAP.unit_h, self.__As_MAP.unit_w\n pos = self.__A_Robot.getLocal()\n x = int(pos.x / w)\n y = int(pos.y / h)\n try:\n self.__As_MAP.setStart((x, y))\n except CoordinateException as e:\n return e.pos\n x = int(point[0] / w)\n y = int(point[1] / h)\n try:\n self.__As_MAP.setEnd((x, y))\n except CoordinateException as e:\n return e.pos\n\n def __normalList(self):\n self.__normalLis.clear()\n h, w = self.__As_MAP.unit_h, self.__As_MAP.unit_w\n for p in self.__pathList:\n self.__normalLis.append(point2(p[0] * w, p[1] * h))\n if len(self.__normalLis) > 1:\n self.__normalLis.pop(0)\n self.__A_Robot.setPathList(self.__normalLis)\n\n def draw(self):\n # for e in self.__As_MAP.getObstaclesList():\n # Painter(self.screen).Rect(Rectangle(e[0] * 10, e[1] * 10, 10, 10), (255, 255, 255), 0)\n for container in self.__containers:\n container.draw(self.screen)\n self.__A_Robot.draw(self.screen)\n self.__E_Msg.draw(self.screen)\n self.__E_Msg2.draw(self.screen)\n\n def doClockEvent(self, NowClock):\n if self.__i < len(self.__normalLis):\n if self.__A_Robot.update(self.__normalLis[self.__i], 5, self.__normalLis[-1]):\n self.__i += 1\n p = self.__A_Robot.area.barycenter()\n p2 = self.__end\n lis_str = 'A-start:\\n'\n for _p in self.__normalLis:\n lis_str += str(_p) + '\\n'\n self.__E_Msg.setText('Robotlocal:({}, {})\\nMouselocal:({}, {})\\n'.format(p.x, p.y, p2[0], p2[1]))\n self.__E_Msg2.setText(lis_str)\n\n def doMouseButtonDownEvent(self, Button):\n if Button == 1:\n self.__end = self.mousePos\n pos = self.__updateMap(self.__end)\n if pos:\n return\n self.__pathList = self.__As_MAP.run()\n self.__normalList()\n self.__As_MAP.refresh()\n self.__i = 0\n" }, { "alpha_fraction": 0.39191320538520813, "alphanum_fraction": 0.4475345313549042, "avg_line_length": 36.27941131591797, "blob_id": "9a884a5868622ba251e6462f720e99e79702dc34", "content_id": "3e5a5e81f0bce950feacaae05e1f267cbf93572b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5070, "license_type": "no_license", "max_line_length": 117, "num_lines": 136, "path": "/source/core/math/Matrix.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "from source.core.math.Vector import vec3\n\n\nclass dtm2:\n \"\"\"determinant_2x2:\n |x1 y1|\\n\n |x2 y2|\n @ rewrite __str__, __add__, __mul__, __truediv__\\n\n \"\"\"\n\n def __init__(self, x1, y1, x2, y2):\n self.x1, self.y1, self.x2, self.y2 = x1, y1, x2, y2\n\n def __str__(self):\n return '<dtm2::{}\\n(|{}, {}|\\n|{}, {}|)>'.format(self.__class__.__name__, self.x1, self.y1, self.x2, self.y2)\n\n def __add__(self, other):\n return self.val() + other.val()\n\n def __mul__(self, other):\n return self.val() * other.val()\n\n def __truediv__(self, other):\n return self.val() / other.val()\n\n def mul(self, num):\n return dtm2(self.x1 * num, self.y1 * num, self.x2, self.y2)\n\n def div(self, num):\n return dtm2(self.x1 / num, self.y1 / num, self.x2, self.y2)\n\n def val(self):\n return self.x1 * self.y2 - self.y1 * self.x2\n\n\nclass mat3:\n \"\"\"matrix_3x3:\n |m0 m1 m2|\\n\n |m3 m4 m5|\\n\n |m6 m7 m8|\n @ rewrite __str__, __add__, __mul__, __truediv__\\n\n \"\"\"\n\n def __init__(self, *args):\n self.m = [0] * 9\n if len(args) == 3:\n if isinstance(args[0], vec3):\n self.m[0], self.m[1], self.m[2] = args[0].x, args[0].y, args[0].z\n self.m[3], self.m[4], self.m[5] = args[1].x, args[1].y, args[1].z\n self.m[6], self.m[7], self.m[8] = args[2].x, args[2].y, args[2].z\n elif isinstance(args[0], tuple) or isinstance(args[0], list):\n self.m[0], self.m[1], self.m[2] = args[0][0], args[0][1], args[0][2]\n self.m[3], self.m[4], self.m[5] = args[1][0], args[1][1], args[1][2]\n self.m[6], self.m[7], self.m[8] = args[2][0], args[2][1], args[2][2]\n elif len(args) == 9:\n self.m[0], self.m[1], self.m[2] = args[0], args[1], args[2]\n self.m[3], self.m[4], self.m[5] = args[3], args[4], args[5]\n self.m[6], self.m[7], self.m[8] = args[6], args[7], args[8]\n else:\n self.m[0], self.m[1], self.m[2] = 1, 0, 0\n self.m[3], self.m[4], self.m[5] = 0, 1, 0\n self.m[6], self.m[7], self.m[8] = 0, 0, 1\n\n def __add__(self, other):\n return mat3(\n self.m[0] + other.m[0], self.m[1] + other.m[1], self.m[2] + other.m[2],\n self.m[3] + other.m[3], self.m[4] + other.m[4], self.m[5] + other.m[5],\n self.m[6] + other.m[6], self.m[7] + other.m[7], self.m[8] + other.m[8]\n )\n\n def __sub__(self, other):\n return mat3(\n self.m[0] - other.m[0], self.m[1] - other.m[1], self.m[2] - other.m[2],\n self.m[3] - other.m[3], self.m[4] - other.m[4], self.m[5] - other.m[5],\n self.m[6] - other.m[6], self.m[7] - other.m[7], self.m[8] - other.m[8]\n )\n\n def __mul__(self, other):\n return mat3(\n self.m[0] * other.m[0] + self.m[1] * other.m[3] + self.m[2] * other.m[6],\n self.m[0] * other.m[1] + self.m[1] * other.m[4] + self.m[2] * other.m[7],\n self.m[0] * other.m[2] + self.m[1] * other.m[5] + self.m[2] * other.m[8],\n self.m[3] * other.m[0] + self.m[4] * other.m[3] + self.m[5] * other.m[6],\n self.m[3] * other.m[1] + self.m[4] * other.m[4] + self.m[5] * other.m[7],\n self.m[3] * other.m[2] + self.m[4] * other.m[5] + self.m[5] * other.m[8],\n self.m[6] * other.m[0] + self.m[7] * other.m[3] + self.m[8] * other.m[6],\n self.m[6] * other.m[1] + self.m[7] * other.m[4] + self.m[8] * other.m[7],\n self.m[6] * other.m[2] + self.m[7] * other.m[5] + self.m[8] * other.m[8]\n )\n\n def __truediv__(self, other):\n pass\n\n def __getitem__(self, item):\n index = item * 3\n return [self.m[index], self.m[index + 1], self.m[index + 2]]\n\n def __setitem__(self, key, value):\n index = key * 3\n self.m[index], self.m[index + 1], self.m[index + 2] = value\n\n def __str__(self):\n return '<mat3::{}([{}, {}, {}][{}, {}, {}][{}, {}, {}])>'.format(\n self.__class__.__name__,\n self.m[0], self.m[1], self.m[2],\n self.m[3], self.m[4], self.m[5],\n self.m[6], self.m[7], self.m[8])\n\n @staticmethod\n def isZero_(mat):\n for n in mat.m:\n if n != 0:\n return False\n return True\n\n def set(self, row, col, val):\n self.m[col + row * 3] = val\n\n def copy(self):\n return mat3(self.m[0], self.m[1], self.m[2],\n self.m[3], self.m[4], self.m[5],\n self.m[6], self.m[7], self.m[8])\n\n def trans(self):\n return mat3(\n self.m[0], self.m[3], self.m[6],\n self.m[1], self.m[4], self.m[7],\n self.m[2], self.m[5], self.m[8]\n )\n\n def mul_vec3(self, v):\n return vec3(\n self.m[0] * v.x + self.m[1] * v.y + self.m[2] * v.z,\n self.m[3] * v.x + self.m[4] * v.y + self.m[5] * v.z,\n self.m[6] * v.x + self.m[7] * v.y + self.m[8] * v.z,\n )\n" }, { "alpha_fraction": 0.5081585049629211, "alphanum_fraction": 0.5617715716362, "avg_line_length": 36.30434799194336, "blob_id": "1d5739ff5688ad6786c0f5ca5df35ab6d55dd639", "content_id": "2413790e31ce5a2c280d853ef6593eaca6b3ac1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 988, "license_type": "no_license", "max_line_length": 134, "num_lines": 23, "path": "/source/examples/TextAreaTest.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import pygame\n\nfrom source.core.const.Const import gl_Font\nfrom source.view.baseClazz.Scene import Scene\nfrom source.view.element.Control import TextArea\n\n\nclass TextAreaTest(Scene):\n def __init__(self, *args):\n super(TextAreaTest, self).__init__(*args)\n self.__ta = TextArea((200, 100, 600, 600), bgColor=(0, 0, 0, 200), fontColor=(255, 255, 255), slidColor=(255, 255, 255, 100))\n\n def setup(self):\n self.fillColor = (128, 0, 128)\n self.__ta.appendText('你好,\\n'\n '我是asheor:\\n'\n ' 我尊敬的先生,很高兴能和你互通信件。我有一件事想要请教您。\\n'\n '是关于DirectRenderPipeline, \\n'\n '在一条管线中如何分配多个obj的顶点目标是非常令人费解的。')\n # self.__ta.appendText('你好Jack')\n self.render.open()\n self.render.add(self.__ta)\n self.render.close()\n" }, { "alpha_fraction": 0.6405375003814697, "alphanum_fraction": 0.654348611831665, "avg_line_length": 23.248868942260742, "blob_id": "3da9faf6117df6094917d8c37576248c963be9b0", "content_id": "f21d64609c255ae37be270496c20a553cd36adef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6052, "license_type": "no_license", "max_line_length": 94, "num_lines": 221, "path": "/source/util/ToolsFuc.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import pygame\nimport configparser\n\n# 空的surface\nfrom source.core.math.Shape import Rectangle\nfrom source.core.math.Vector import point2\nfrom source.view.baseClazz.Element import Element\nfrom source.view.baseClazz.Sprite import Sprite\n\n\ndef blankSurface(size, color=(255, 255, 255, 255)):\n temp = pygame.Surface(size).convert()\n temp.fill(color)\n if len(color) > 3:\n temp.set_alpha(color[3])\n return temp\n\n# 从文件读取图片资源作为Surface\ndef createSurfaceFromFile(file_path):\n return pygame.image.load(file_path)\n\n\n# 文字surface\ndef textSurface(text, font, size, color):\n textTemp = pygame.font.SysFont(font, size)\n return textTemp.render(text, 1, color)\n\n\n# 带有文字的surface这里的\ndef blankTextSurface(size_WH, background_color, text, font, font_size, font_color, offset_XY):\n temp = blankSurface(size_WH, background_color)\n temp.blit(textSurface(text, font, font_size, font_color), offset_XY)\n return temp\n\n\n# 裁剪资源图\ndef clipResImg(tarImg, rect, colorKey):\n temp = pygame.Surface((rect[2], rect[3])).convert()\n temp.set_colorkey(colorKey)\n temp.blit(tarImg, (-rect[1], -rect[0]))\n return temp\n\n\n# 改变alpha值\ndef blitAlpha(tar, source, loc, opacity):\n temp = pygame.Surface((source.get_width(), source.get_height())).convert()\n temp.blit(source, (0, 0))\n temp.set_alpha(opacity)\n tar.blit(temp, loc)\n\n\n# 返回水平居中的水平位置\ndef centeredXPos(bg_width, obj_width, bg_left=0):\n return (bg_width / 2 - obj_width / 2) + bg_left\n\n\n# 返回铅直居中的水平位置\ndef centeredYPos(bg_height, obj_height, bg_top=0):\n return (bg_height / 2 - obj_height / 2) + bg_top\n\n\n# 返回垂直位置(X, Y)\ndef centeredXYPos(bg_width, obj_width, bg_height, obj_height) -> tuple:\n return centeredXPos(bg_width, obj_width), centeredYPos(bg_height, obj_height)\n\n\n# 判断pos是否在矩形区域内\ndef InRect(pos, rect) -> bool:\n if rect[0] + rect[2] > pos[0] > rect[0] and rect[1] < pos[1] < rect[1] + rect[3]:\n return True\n return False\n\n\n# 判断pos是否在圆形区域内\ndef InCircular(pos, cir) -> bool:\n if pow(pow(pos[0] - cir.left, 2) + pow(pos[1] - cir.top, 2), 0.5) > cir.r:\n return False\n return True\n\n\n# 判断pos是否在Element内\ndef InElement(pos, element) -> bool:\n if isinstance(element, Sprite):\n return InSprite(pos, element)\n if not element:\n return False\n area = element.area\n return area.contains(point2(pos))\n\n\n# 判断pos是否在Sprite内\ndef InSprite(pos, sprite, _type=0) -> bool:\n if not sprite:\n return False\n if _type == 0:\n return InRect(pos, sprite.rect)\n elif _type == 1:\n return InCircular(pos, sprite.area)\n\n\n# 读取InI文件内容\n# 参数:\n# @path ini文件的地址\n# @section ini文件中的节点\n# @param ini文件中该节点下的元素,默认为None,如果取列表的话可以不填\n# 返回值:列表\n# 【0】该ini文件section下,param对应的值\n# 【1】ini文件section下,所有的键值对,为字典\n# 【2】ini文件section下,所以得变量值\ndef readINI(path, section, param=None) -> list:\n conf = configparser.ConfigParser()\n conf.read(path)\n return [conf.get(section, param), conf.items(section), conf.options(section)]\n\n\n# 添加INI文件中的项\ndef addINI(path, section, param, val):\n conf = configparser.ConfigParser()\n conf.read(path)\n if not conf.has_section(section):\n conf.add_section(section)\n conf.set(section, param, val)\n conf.write(open(path, \"w+\"))\n\n\n# 修改INI文件\ndef updateINI(path, section, param, val):\n conf = configparser.ConfigParser()\n conf.read(path)\n conf.set(section, param, val)\n conf.write(open(path, \"w+\"))\n\n\n# 读取INI文件内容为int\ndef readINIInt(path, section, param):\n return int(readINI(path, section, param)[0])\n\n\n# 读取INI文件内容为bool\ndef readINIBool(path, section, param):\n return bool(readINIInt(path, section, param))\n\n\n# 读取INI文件内容为Float\ndef readINIFloat(path, section, param):\n return float(readINI(path, section, param)[0])\n\n\n# 将数字转换成中文字符串\n# @param int num 要转换的数字 eg. 123, 567\n# @param Const.NUM_DICT mapping 对应规则, 在Const.py 中定义的NUM_DICT系列常量\n# @ret str 对应规则下的字符串\ndef IntToStr(num, mapping) -> str:\n s = str(num)\n res = ''\n for c in s:\n res += mapping[c]\n return res\n\n\n# 将中文字符串转换成数字\n# @param str s 要转换的字符串,必须在 Const.NUM_DICT 中有对应关系\n# @param Const.NUM_DICT mapping 对应规则, 在Const.py 中定义的NUM_DICT系列常量\n# @ret int 对应规则下的数字\ndef StrToInt(s, mapping) -> int:\n new_dict = {v: k for k, v in mapping.items()}\n res = ''\n for c in s:\n res += new_dict[c]\n return int(res)\n\n\n# 归并排序:\ndef MergeSort(lists) -> list:\n if len(lists) <= 1:\n return lists\n num = int(len(lists) / 2)\n left = MergeSort(lists[:num])\n right = MergeSort(lists[num:])\n return Merge(left, right)\n\n\ndef Merge(left, right):\n rt, lf = 0, 0\n result = []\n while lf < len(left) and rt < len(right):\n if left[lf] <= right[rt]:\n result.append(left[lf])\n lf += 1\n else:\n result.append(right[rt])\n rt += 1\n result += list(left[lf:])\n result += list(right[rt:])\n return result\n\n\n# 针对Ioevent3Enum的转换器,将pygameKey转换成IoEvent3的Key\ndef exKey(key) -> int:\n return int(key) - 97 + 0xC0000\n\n\n# 将Shape.py中的形状转换为pygame.Rect\ndef ex_toRect(rect) -> pygame.Rect:\n return pygame.Rect(rect.x, rect.y, rect.w, rect.h)\n\n\n# 将pygame.Rect转换为Shape.py中的Rectangle\ndef ex_toRectTangle(rect) -> Rectangle:\n return Rectangle(rect.x, rect.y, rect.w, rect.h)\n\n\n# 在一维容器中选出非n数的地址值\ndef getNotN(container, n) -> list:\n res = []\n i = 0\n for b in container:\n if b != n:\n res.append(i)\n i += 1\n return res" }, { "alpha_fraction": 0.5108957290649414, "alphanum_fraction": 0.5502334833145142, "avg_line_length": 55.087303161621094, "blob_id": "5c368b5938784199d1cf941e1840ff7d17a357cb", "content_id": "ad7e9249e04c09bf226e1d5f8c35a1fc5e82e8e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14416, "license_type": "no_license", "max_line_length": 120, "num_lines": 252, "path": "/source/examples/TestPick.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import pygame\n\nfrom source.core.const.Const import gl_ImgPath, GLC_INI_NAME, GLC_INI_SECTION_WAVE, GLC_INI_PARAM_ANTIALIAS, \\\n GLC_INI_SECTION_DRAW, GLC_INI_PARAM_BGMVOLUME, SCENENUM_TITLE, gl_Font_opt, gl_UIPath, GLC_INI_PARAM_SOUNDVOLUME, \\\n SCENENUM_OPT_APPLY, gl_SoundPath\nfrom source.core.assembly.IOEvent import ioEvent3Enum\nfrom source.util.ToolsFuc import blitAlpha, updateINI, centeredYPos, centeredXPos, blankSurface\nfrom source.view.baseClazz.Scene import Scene\nfrom source.view.element.Elements import ImgElement, TextElement, TitleConstElement, OptButtonElement, \\\n OptUIElement\n\n\ndef ChePos(e, isDown):\n if isDown:\n e.area.x += 1\n e.area.y += 1\n else:\n e.area.x -= 1\n e.area.y -= 1\n\n\nclass pickTest(Scene):\n def __init__(self, *args):\n super(pickTest, self).__init__(*args)\n\n self.__flag_isEnter = False\n self.__alpha = 0\n self.__flag_recordStartTime = False\n self.__start_time = 0\n self.__now_time = 0\n\n self.res_Img_BG_Name = 'OPT_BG.bmp'\n self.res_Sound_Choose_Name = 'OPT_C.wav'\n self.res_UI_RightButton = 'OPT_BR.png'\n self.res_UI_LeftButton = 'OPT_BL.png'\n\n self.__Clock = pygame.time.Clock()\n self.__KV_AA = {}\n self.__KV_WAVE = {}\n self.__ElementsMap = {}\n\n if self.config.getTextAntiAlias():\n self.__KV_AA['key'] = '开'\n self.__KV_AA['val'] = '1'\n else:\n self.__KV_AA['key'] = '关'\n self.__KV_AA['val'] = '0'\n\n self.res_Sound_Choose = pygame.mixer.Sound(gl_SoundPath + self.res_Sound_Choose_Name)\n self.res_Sound_Choose.set_volume(self.config.getVolumeSound())\n\n self.res_Img_BG = pygame.image.load(gl_ImgPath + self.res_Img_BG_Name)\n\n self.__E_BGBlankL1 = OptButtonElement((40, 60, 200, 40), (255, 255, 255, 100))\n self.__E_BGBlankL2 = OptButtonElement((40, 110, 200, 40), (255, 255, 255, 100))\n self.__E_BGBlankL3 = OptButtonElement((40, 160, 200, 40), (255, 255, 255, 100))\n self.__E_BGBlankLRet = OptButtonElement((50, 520, 80, 40), (255, 255, 255, 100))\n self.__E_BGBlankLApply = OptButtonElement((150, 520, 80, 40), (255, 255, 255, 100))\n self.__E_BGBlankR = TitleConstElement((260, 60, 510, 500), blankSurface((510, 500), (255, 255, 255, 100)))\n self.__E_Text_Apply = TextElement((centeredXPos(80, 40, 150), centeredYPos(40, 20, 520), 120, 20), '应用',\n gl_Font_opt, 20, (0, 0, 0), self.config.getTextAntiAlias())\n self.__E_Text_Apply.zIndex = 1\n self.__E_Text_Ret = TextElement((centeredXPos(80, 40, 50), centeredYPos(40, 20, 520), 120, 20), '返回',\n gl_Font_opt, 20, (0, 0, 0), self.config.getTextAntiAlias())\n self.__E_Text_Ret.zIndex = 1\n\n self.__E_Text_Draw = TextElement((centeredXPos(200, 80, 40), centeredYPos(40, 20, 60), 80, 20), '画面设置',\n gl_Font_opt, 20, (0, 0, 0), self.config.getTextAntiAlias())\n self.__E_Text_Draw.zIndex = 1\n self.__E_Text_AntiAlias = TextElement((270, 70, 120, 20), '抗锯齿:', gl_Font_opt, 18, (0, 0, 0),\n self.config.getTextAntiAlias())\n self.__E_Text_AntiAlias.zIndex = 1\n self.__E_Text_AA_Val = TextElement((670, 70, 20, 20), self.__KV_AA['key'], gl_Font_opt, 18, (0, 0, 0),\n self.config.getTextAntiAlias())\n self.__E_Text_AA_Val.zIndex = 1\n self.__E_UI_AA_RightButton = OptUIElement((700, 70, 20, 20), gl_UIPath + self.res_UI_RightButton)\n self.__E_UI_AA_RightButton.zIndex = 1\n self.__E_UI_AA_LeftButton = OptUIElement((640, 70, 20, 20), gl_UIPath + self.res_UI_LeftButton)\n self.__E_UI_AA_LeftButton.zIndex = 1\n self.__E_Text_Wave = TextElement((centeredXPos(200, 80, 40), centeredYPos(40, 20, 110), 80, 20), '声音设置',\n gl_Font_opt, 20, (0, 0, 0), self.config.getTextAntiAlias())\n self.__E_Text_Wave.zIndex = 1\n self.__E_Text_BGMVolume = TextElement((270, 70, 120, 20), '音乐音量:', gl_Font_opt, 18, (0, 0, 0),\n self.config.getTextAntiAlias())\n self.__E_Text_BGMVolume.zIndex = 1\n self.__E_Text_BGM_Val = TextElement((660, 70, 30, 20), str(self.config.VolumeBGM), gl_Font_opt, 18, (0, 0, 0),\n self.config.getTextAntiAlias())\n self.__E_Text_BGM_Val.zIndex = 1\n self.__E_UI_BGM_RightButton = OptUIElement((700, 70, 20, 20), gl_UIPath + self.res_UI_RightButton)\n self.__E_UI_BGM_RightButton.zIndex = 1\n self.__E_UI_BGM_LeftButton = OptUIElement((630, 70, 20, 20), gl_UIPath + self.res_UI_LeftButton)\n self.__E_UI_BGM_LeftButton.zIndex = 1\n self.__E_Text_SoundVolume = TextElement((270, 100, 120, 20), '音效音量:', gl_Font_opt, 18, (0, 0, 0),\n self.config.getTextAntiAlias())\n self.__E_Text_SoundVolume.zIndex = 1\n self.__E_Text_Sou_Val = TextElement((660, 100, 30, 20), str(self.config.VolumeSound), gl_Font_opt, 18,\n (0, 0, 0), self.config.getTextAntiAlias())\n self.__E_Text_Sou_Val.zIndex = 1\n self.__E_UI_Sou_RightButton = OptUIElement((700, 100, 20, 20), gl_UIPath + self.res_UI_RightButton)\n self.__E_UI_Sou_RightButton.zIndex = 1\n self.__E_UI_Sou_LeftButton = OptUIElement((630, 100, 20, 20), gl_UIPath + self.res_UI_LeftButton)\n self.__E_UI_Sou_LeftButton.zIndex = 1\n\n self.__E_Text_Licence = TextElement(\n (centeredXPos(200, 120, 40), centeredYPos(40, 20, 160), 120, 20), '开源软件许可', gl_Font_opt, 20,\n (0, 0, 0), self.config.getTextAntiAlias())\n self.__E_Text_Licence.zIndex = 1\n self.__E_Img_Licence = ImgElement(self.__E_BGBlankR.area, gl_ImgPath + 'OPT_L.lice', 255, (128, 128, 128))\n self.__E_Img_Licence.zIndex = 1\n\n # 画面设置绑定事件\n self.__E_BGBlankL1.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: ChePos(self.__E_Text_Draw, True),\n 1)\n self.__E_BGBlankL1.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: self.__rebuildElementsToList2(\n [self.__E_Text_AntiAlias, self.__E_Text_AA_Val, self.__E_UI_AA_RightButton, self.__E_UI_AA_LeftButton]), 2)\n self.__E_BGBlankL1.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp, lambda: ChePos(self.__E_Text_Draw, False), 1)\n\n # 声音设置绑定事件\n self.__E_BGBlankL2.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: ChePos(self.__E_Text_Wave, True),\n 1)\n self.__E_BGBlankL2.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: self.__rebuildElementsToList2(\n [self.__E_Text_BGMVolume, self.__E_Text_SoundVolume, self.__E_Text_BGM_Val, self.__E_Text_Sou_Val,\n self.__E_UI_BGM_RightButton, self.__E_UI_BGM_LeftButton, self.__E_UI_Sou_RightButton,\n self.__E_UI_Sou_LeftButton]), 2)\n self.__E_BGBlankL2.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp, lambda: ChePos(self.__E_Text_Wave, False), 1)\n\n # 开源软件许可按钮绑定事件\n self.__E_BGBlankL3.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown,\n lambda: ChePos(self.__E_Text_Licence, True), 1)\n self.__E_BGBlankL3.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown,\n lambda: self.__rebuildElementsToList2([self.__E_Img_Licence]), 2)\n self.__E_BGBlankL3.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp, lambda: ChePos(self.__E_Text_Licence, False),\n 1)\n\n # 应用按钮绑定事件\n self.__E_BGBlankLApply.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown,\n lambda: ChePos(self.__E_Text_Apply, True), 1)\n self.__E_BGBlankLApply.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp,\n lambda: ChePos(self.__E_Text_Apply, False), 1)\n self.__E_BGBlankLApply.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick,\n lambda: self.__retSignalIsReadyToEnd(SCENENUM_OPT_APPLY), 1)\n self.__E_BGBlankLApply.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick, lambda: self.__updConfig(), 2)\n\n # 返回按钮绑定事件\n self.__E_BGBlankLRet.Events.appendEvent(ioEvent3Enum.mouseLeftKeyDown, lambda: ChePos(self.__E_Text_Ret, True),\n 1)\n self.__E_BGBlankLRet.Events.appendEvent(ioEvent3Enum.mouseLeftKeyUp, lambda: ChePos(self.__E_Text_Ret, False),\n 1)\n self.__E_BGBlankLRet.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick,\n lambda: self.__retSignalIsReadyToEnd(SCENENUM_TITLE), 1)\n\n # 抗锯齿UI按钮绑定事件\n self.__E_UI_AA_LeftButton.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick, lambda: self.__chVal_AA_Txt(), 1)\n self.__E_UI_AA_RightButton.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick, lambda: self.__chVal_AA_Txt(), 1)\n\n # 改变音量UI按钮绑定事件\n self.__E_UI_BGM_LeftButton.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick,\n lambda: self.__chVal_WaveParam_Txt(self.__E_Text_BGM_Val, False,\n GLC_INI_PARAM_BGMVOLUME), 1)\n self.__E_UI_BGM_RightButton.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick,\n lambda: self.__chVal_WaveParam_Txt(self.__E_Text_BGM_Val, True,\n GLC_INI_PARAM_BGMVOLUME), 1)\n self.__E_UI_Sou_LeftButton.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick,\n lambda: self.__chVal_WaveParam_Txt(self.__E_Text_Sou_Val, False,\n GLC_INI_PARAM_SOUNDVOLUME), 1)\n self.__E_UI_Sou_RightButton.Events.appendEvent(ioEvent3Enum.mouseLeftKeyClick,\n lambda: self.__chVal_WaveParam_Txt(self.__E_Text_Sou_Val, True,\n GLC_INI_PARAM_SOUNDVOLUME), 1)\n\n self.__ElementsMap['Draw1'] = [self.__E_BGBlankL1, self.__E_BGBlankL2, self.__E_BGBlankL3, self.__E_BGBlankR,\n self.__E_Text_Draw, self.__E_Text_Wave, self.__E_Text_Licence,\n self.__E_BGBlankLApply,\n self.__E_Text_Apply, self.__E_BGBlankLRet, self.__E_Text_Ret]\n self.__ElementsMap['Draw2'] = [self.__E_Text_AntiAlias, self.__E_Text_AA_Val, self.__E_UI_AA_RightButton,\n self.__E_UI_AA_LeftButton]\n self.__ElementsMap['Interact1'] = [self.__E_BGBlankL1, self.__E_BGBlankL2, self.__E_BGBlankL3,\n self.__E_BGBlankLApply, self.__E_BGBlankLRet]\n self.__ElementsMap['Interact2'] = [self.__E_UI_AA_RightButton, self.__E_UI_AA_LeftButton]\n\n self.__ElementsMap['Draw'] = self.__ElementsMap['Draw1'] + self.__ElementsMap['Draw2']\n self.__ElementsMap['Interact'] = self.__ElementsMap['Interact1'] + self.__ElementsMap['Interact2']\n\n self.render.add(self.__ElementsMap['Draw1'])\n self.render.add(self.__ElementsMap['Interact'])\n self.render.close()\n\n # 设定渲染参数\n self.__step = 4\n self.__frameRate = self.config.getFrameRate()\n if self.__frameRate:\n self.__step = 255 / (1.5 * self.__frameRate)\n\n # 替换ElementsList2的内容\n def __rebuildElementsToList2(self, _list):\n if _list is None or len(_list) <= 0:\n return\n self.__ElementsMap['Draw2'] = _list\n self.__ElementsMap['Interact2'].clear()\n for e in _list:\n if e.Events.getSize() > 0:\n self.__ElementsMap['Interact2'].append(e)\n self.__ElementsMap['Draw'] = self.__ElementsMap['Draw1'] + self.__ElementsMap['Draw2']\n self.__ElementsMap['Interact'] = self.__ElementsMap['Interact1'] + self.__ElementsMap['Interact2']\n\n # 改变抗锯齿UI所对应的值\n def __chVal_AA_Txt(self):\n if self.__KV_AA['val'] == '1':\n self.__KV_AA['key'] = '关'\n self.__KV_AA['val'] = '0'\n else:\n self.__KV_AA['key'] = '开'\n self.__KV_AA['val'] = '1'\n self.__E_Text_AA_Val.setText(self.__KV_AA['key'])\n\n # 改变Wave UI所对应的值\n def __chVal_WaveParam_Txt(self, elem, add, para):\n valF = float(elem.Text)\n if add:\n valF += 0.5\n if valF > 10:\n valF = 10.0\n else:\n valF -= 0.5\n if valF < 0:\n valF = 0.0\n self.__KV_WAVE[para] = str(valF)\n elem.setText(self.__KV_WAVE[para])\n\n # 序列化值更新设置文件\n def __updConfig(self):\n updateINI(GLC_INI_NAME, GLC_INI_SECTION_DRAW, GLC_INI_PARAM_ANTIALIAS, self.__KV_AA['val'])\n for k, v in self.__KV_WAVE.items():\n updateINI(GLC_INI_NAME, GLC_INI_SECTION_WAVE, k, v)\n\n # 传递信号\n def __retSignalIsReadyToEnd(self, SceneNum):\n self.isReadyToEnd = True\n self.nextSceneNum = SceneNum\n\n def draw(self):\n blitAlpha(self.screen, self.res_Img_BG, (0, 0), self.__alpha)\n\n if not self.__flag_isEnter and not self.isReadyToEnd:\n self.__alpha += self.__step\n if self.__alpha >= 255:\n self.__alpha = 255\n self.__flag_isEnter = True\n elif self.__flag_isEnter and not self.isReadyToEnd:\n self.__alpha = 255\n self.render.render(self.screen)\n if self.isReadyToEnd:\n self.isEnd = True\n" }, { "alpha_fraction": 0.6079396605491638, "alphanum_fraction": 0.6407480239868164, "avg_line_length": 43.173912048339844, "blob_id": "80d83d72539ce9d53e82d4ec853c454fb2964da6", "content_id": "56ec512a017830e89b68cdc13daae1545439e10c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3068, "license_type": "no_license", "max_line_length": 120, "num_lines": 69, "path": "/source/examples/ActorTest.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import pygame\n\nfrom source.core.assembly.PhysicalBody import rigidBody, physicalScene, BodyType\nfrom source.core.math.Vector import vec2\nfrom source.core.math.Shape import Rectangle\nfrom source.util.ToolsFuc import ex_toRect\nfrom source.view.baseClazz.Actor import Actor\nfrom source.view.baseClazz.Scene import Scene\n\n\nclass wallActor(Actor):\n def __init__(self, texture, rect=None):\n super(wallActor, self).__init__(texture, rect)\n\n def draw(self, screen):\n screen.blit(self.texture, ex_toRect(self.area))\n\n\nclass containerActor(Actor):\n def __init__(self, texture, rect=None):\n super(containerActor, self).__init__(texture, rect)\n self.physicalBody = rigidBody(1, self.area, BodyType.DYNAMIC)\n self.physicalBody.drag = vec2(0, 0)\n self.physicalBody.hasCollidedProbe = True\n self.physicalBody.restitution = 0.8\n\n def update(self):\n self.area = self.physicalBody.collideArea\n\n def draw(self, screen):\n screen.blit(self.texture, ex_toRect(self.area))\n\n\nclass ActorScene(Scene):\n def __init__(self, screen, config, clock):\n super(ActorScene, self).__init__(screen, config, clock)\n rect_container = Rectangle(600, 200, 100, 100)\n rect_container2 = Rectangle(600, 0, 100, 100)\n rect_container3 = Rectangle(0, 0, 100, 100)\n rect_container4 = Rectangle(400, 200, 100, 100)\n rect_wall = Rectangle(0, 200, 400, 400)\n\n self.__A_wall = wallActor(pygame.image.load('F:/练习/PyCharm/PygameTest/resource/Test/wall.jpg'), rect_wall)\n self.__A_container = containerActor(pygame.image.load('F:/练习/PyCharm/PygameTest/resource/Test/container1.jpg'),\n rect_container)\n self.__A_container2 = containerActor(pygame.image.load('F:/练习/PyCharm/PygameTest/resource/Test/container2.jpg'),\n rect_container2)\n self.__A_container3 = containerActor(pygame.image.load('F:/练习/PyCharm/PygameTest/resource/Test/container3.jpg'),\n rect_container3)\n self.__A_container4 = containerActor(pygame.image.load('F:/练习/PyCharm/PygameTest/resource/Test/container4.jpg'),\n rect_container4)\n self.__A_container2.physicalBody.vel = vec2(0, 3)\n self.__A_container3.physicalBody.vel = vec2(0, 3)\n self.ps = physicalScene(Rectangle(0, 0, 800, 600), vec2(0, 0.098), self.startClock)\n self.ps.add(self.__A_container.physicalBody)\n self.ps.add(self.__A_container2.physicalBody)\n self.ps.add(self.__A_container3.physicalBody)\n self.ps.add(self.__A_container4.physicalBody)\n\n def draw(self):\n # self.__A_wall.draw(self.screen)\n self.__A_container.draw(self.screen)\n self.__A_container2.draw(self.screen)\n self.__A_container3.draw(self.screen)\n self.__A_container4.draw(self.screen)\n\n def doClockEvent(self, NowClock):\n self.ps.update(NowClock)\n self.__A_wall.update()\n" }, { "alpha_fraction": 0.5714587569236755, "alphanum_fraction": 0.5805496573448181, "avg_line_length": 35.953125, "blob_id": "5d776f16d38bef3b368255926906deb613637029", "content_id": "e65c923a7baec8d38f92aa99cdf8afe938a48cda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5098, "license_type": "no_license", "max_line_length": 120, "num_lines": 128, "path": "/source/view/baseClazz/Sprite.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import pygame\n\nfrom source.core.assembly.IOEvent import IOEvent3, ElementHadDoEvent\nfrom source.core.dataStructure.QuadTree import QuadTree, Node, RectangleRange\nfrom source.core.math.Shape import Rectangle\n\n\nclass Sprite(pygame.sprite.Sprite):\n \"\"\"游戏中所有精灵的父类 框架:Syclight Framework with pygame\n\n 实现自pygame.sprite.sprite(*groups):\n\n 在本框架中的声明精灵时要求继承该类,否则将会导致出错\n\n 当继承该类时,要求使用该类的变量和实现必要的方法,用不到的方法可以忽略\n\n \"\"\"\n\n def __init__(self, image, rect=None, isScale=True):\n super().__init__()\n self.image = image\n self.rect = rect\n if isinstance(rect, list) or isinstance(rect, tuple):\n self.rect = pygame.Rect(rect[0], rect[1], rect[2], rect[3])\n elif isinstance(rect, Rectangle):\n self.rect = pygame.Rect(rect.x, rect.y, rect.w, rect.h)\n if isinstance(self.image, str):\n self.image = pygame.image.load(image)\n if self.rect is None:\n self.rect = self.image.get_rect()\n elif isScale:\n self.image = pygame.transform.scale(self.image, (self.rect.w, self.rect.h))\n\n self.Events = IOEvent3()\n self.EventsHadDo = ElementHadDoEvent()\n self.visual = True\n self.active = True\n self.zIndex = 0\n self.mouseLastPos = (0, 0)\n self.mousePos = (0, 0)\n self.mouseButtons = (0, 0, 0)\n self.mouseRel = (0, 0)\n self.physicalBodyType = None\n if isinstance(rect, tuple):\n self.collidedArea = Rectangle(self.rect[0], self.rect[1], self.rect[2], self.rect[3])\n else:\n self.collidedArea = Rectangle(self.rect.x, self.rect.y, self.rect.w, self.rect.h)\n\n def setRect(self, rec):\n if (isinstance(rec, tuple) or isinstance(rec, list)) and len(rec) >= 4:\n self.rect = pygame.Rect(rec[0], rec[1], rec[2], rec[3])\n else:\n self.rect = rec\n self.image = pygame.transform.scale(self.image, (self.rect.w, self.rect.h))\n self.collidedArea = Rectangle(self.rect.x, self.rect.y, self.rect.w, self.rect.h)\n\n def setImg(self, arg):\n if isinstance(arg, str):\n self.image = pygame.image.load(arg)\n if isinstance(arg, pygame.Surface):\n self.image = arg\n\n def draw(self, surface):\n if self.image:\n surface.blit(self.image, self.rect)\n\n def collided(self, oth):\n if not isinstance(oth, Sprite):\n raise Exception(\"Param '{}' must is a subclass of 'sprite'\".format(oth))\n if self.zIndex != oth.zIndex:\n return False\n return self.collidedArea.intersects(oth.collidedArea)\n\n\nclass SpriteGroup(pygame.sprite.Group):\n \"\"\"游戏中所有精灵的精灵组 框架:Syclight Framework with pygame\n\n 实现自pygame.sprite.Group:\n\n 所有的精灵在建立精灵组时不一定要实现该类\n\n 主要是弥补pygame没有精灵组组内检测碰撞的方法,组内碰撞采用四叉树\n\n 注意:重写了pygame.sprite.Group的update方法和draw方法,主要是因为Sprite类中的draw方法\n 如果不重写会在draw时会产生一些莫名其妙的bug\n\n \"\"\"\n\n def __init__(self, activeArea, *sprites):\n super(SpriteGroup, self).__init__(*sprites)\n # if not hasattr(activeArea, 'w'):\n # raise Exception(\"Class '{}' must have attribute 'w'\".format(activeArea))\n # if not hasattr(activeArea, 'h'):\n # raise Exception(\"Class '{}' must have attribute 'h'\".format(activeArea))\n if isinstance(activeArea, list) or isinstance(activeArea, tuple):\n self.__activeArea = RectangleRange((activeArea[2] + activeArea[0]) / 2, (activeArea[3] - activeArea[1]) / 2,\n activeArea[2] / 2, activeArea[3] / 2)\n else:\n self.__activeArea = RectangleRange((activeArea.w + activeArea.x) / 2, (activeArea.h + activeArea.y) / 2,\n activeArea.w / 2, activeArea.h / 2)\n\n self.__quadTree = QuadTree(self.__activeArea, 4)\n self.__collideDict = {}\n\n def update(self, *args):\n self.__quadTree = QuadTree(self.__activeArea, 4)\n self.__collideDict.clear()\n\n for s in self.sprites():\n s.update(*args)\n node = Node(s.rect.x, s.rect.y, s)\n self.__quadTree.insert(node)\n\n def draw(self, surface):\n for s in self.sprites():\n s.draw(surface)\n\n def getCollideDict(self):\n for e in self.sprites():\n _list = []\n _range = RectangleRange(e.rect.x, e.rect.y, e.rect.w * 2, e.rect.h * 2)\n sprites = self.__quadTree.query(_range)\n for _s in sprites:\n if e is not _s.data and e.collided(_s.data):\n _list.append(_s.data)\n if _list:\n self.__collideDict[e] = _list\n return self.__collideDict\n" }, { "alpha_fraction": 0.5725158452987671, "alphanum_fraction": 0.6023960709571838, "avg_line_length": 38.85955047607422, "blob_id": "6dd7179762470a5d7fb9e4b8e8c1dc1cacbece7b", "content_id": "4001293e5a347bab95db1636604f9afd3bf42a63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7133, "license_type": "no_license", "max_line_length": 123, "num_lines": 178, "path": "/source/examples/testSpriteScene.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import os\nimport random\n\nimport pygame\n\nfrom source.core.assembly.IOEvent import ioEvent3Enum\nfrom source.core.const.Const import gl_WindowHeight, gl_Font\nfrom source.core.dataStructure.QuadTree import RectangleRange\nfrom source.util.ToolsFuc import clipResImg, exKey\nfrom source.view.element.Elements import TextElement, ImgElement\nfrom source.view.scene.Scenes import Scene\nfrom source.view.baseClazz.Sprite import Sprite, SpriteGroup\nfrom source.core.math.Shape import Rectangle\n\n\nclass GameSprite(Sprite):\n def __init__(self, image, speed=1):\n super().__init__(image)\n self.speed = speed\n\n def update(self, *args):\n self.rect.x += self.speed\n self.rect.y += self.speed\n if self.rect.y > gl_WindowHeight or self.rect.y < 0:\n self.speed = -self.speed\n\n\nclass gearSprite(Sprite):\n def __init__(self, image, rect):\n super().__init__(image, rect)\n self._image = self.image\n self.rotate = 0\n\n def update(self, *args):\n self.rotate += 1\n self.image = pygame.transform.rotate(self._image, self.rotate)\n self.rect = self.image.get_rect(center=self.rect.center)\n\n\nclass CubeSprite(Sprite):\n def __init__(self, image, rect):\n super(CubeSprite, self).__init__(image, rect)\n self.__x = self.rect.x\n self.__y = self.rect.y\n self.image.set_alpha(100)\n self.highLight = False\n\n def update(self, *args):\n self.highLight = False\n self.rect = pygame.Rect(self.__x + random.uniform(-1, 1), self.__y + random.uniform(-1, 1), self.rect.w,\n self.rect.h)\n self.collidedArea = Rectangle(self.rect.x, self.rect.y, self.rect.w, self.rect.h)\n\n def draw(self, surface):\n if self.highLight:\n self.image.set_alpha(255)\n else:\n self.image.set_alpha(100)\n surface.blit(self.image, self.rect)\n\n\ndef chPos(step, sprite, isY):\n if isY:\n sprite.setRect(pygame.Rect(sprite.rect.x, sprite.rect.y + step, sprite.rect.w, sprite.rect.h))\n else:\n sprite.setRect(pygame.Rect(sprite.rect.x + step, sprite.rect.y, sprite.rect.w, sprite.rect.h))\n\n\n# test 播放动画\nclass testAnimScene(Scene):\n def __init__(self, *args):\n super(testAnimScene, self).__init__(*args)\n self.img = pygame.image.load('F:/Practice/PyCharm/PygameTest/resource/Img/TEST_ANIM.jpg').convert_alpha()\n self.enemy = GameSprite(clipResImg(self.img, pygame.Rect(0, 0, 278, 153), (45, 45, 45)), 0)\n self.enemy.rect.x = 200\n self.enemy.rect.y = 200\n # self.enemy1 = GameSprite(pygame.image.load(\"F:/练习/PyCharm/PygameTest/resource/Img/gear.png\"), 2)\n self.enemy1 = gearSprite(pygame.image.load(\"F:/Practice/PyCharm/PygameTest/resource/Img/gear.png\").convert_alpha(),\n pygame.Rect(220, 220, 548, 549))\n # 创建精灵组\n self.enemy_group = SpriteGroup(RectangleRange(0, 0, 800, 600), self.enemy, self.enemy1)\n # self.enemy_group = pygame.sprite.Group(self.enemy, self.enemy1)\n self.enemy.Events.appendEvent(ioEvent3Enum.key_W | ioEvent3Enum.keyDowning,\n lambda: chPos(-1, self.enemy, True), 1)\n self.enemy.Events.appendEvent(ioEvent3Enum.key_S | ioEvent3Enum.keyDowning,\n lambda: chPos(1, self.enemy, True), 1)\n self.enemy.Events.appendEvent(ioEvent3Enum.key_A | ioEvent3Enum.keyDowning,\n lambda: chPos(-1, self.enemy, False), 1)\n self.enemy.Events.appendEvent(ioEvent3Enum.key_D | ioEvent3Enum.keyDowning,\n lambda: chPos(1, self.enemy, False), 1)\n self.interval = None\n self.clipRect = pygame.Rect(0, 0, 278, 153)\n self.__flag_raw = 1\n\n def draw(self):\n self.enemy_group.update()\n self.enemy_group.draw(self.screen)\n\n def doClockEvent(self, nowClock):\n print(self.enemy_group.getCollideDict())\n\n self.interval = nowClock - self.startClock\n if self.interval >= 100:\n self.startClock = nowClock\n if self.clipRect.top >= 612 and self.clipRect.left >= 278:\n self.clipRect = pygame.Rect(-278, 0, 278, 153)\n self.__flag_raw = 1\n if self.__flag_raw == 1:\n self.clipRect = pygame.Rect(self.clipRect.left + self.clipRect.width, self.clipRect.top,\n 278, 153)\n self.__flag_raw = 2\n elif self.__flag_raw == 2:\n self.clipRect = pygame.Rect(0, self.clipRect.top + self.clipRect.height, 278, 153)\n self.__flag_raw = 1\n self.enemy.image = clipResImg(self.img, self.clipRect, (45, 45, 45))\n\n def doKeyPressedEvent(self, keyPressedList):\n for key in keyPressedList:\n self.enemy.Events.doKeyboardKeyDowning(exKey(key))\n self.enemy1.Events.doKeyboardKeyDowning(exKey(key))\n\n\n# test 组内碰撞检测\nclass testSpriteScene(Scene):\n def __init__(self, screen, config, startClock):\n super(testSpriteScene, self).__init__(screen, config, startClock)\n self.img = pygame.Surface((5, 5)).convert()\n self.img.fill((255, 255, 255))\n self.sprintsGroup1 = SpriteGroup(RectangleRange(0, 0, 800, 600))\n self.__E_FPS = TextElement(pygame.Rect(self.width - 80, 0, 80, 20), 'FPS:', gl_Font, 18, (0, 255, 0), 1)\n for i in range(0, 1000):\n x, y = random.randint(0, 800), random.randint(0, 600)\n self.sprintsGroup1.add(CubeSprite(self.img, pygame.Rect(x, y, 5, 5)))\n\n def draw(self):\n _dict = self.sprintsGroup1.getCollideDict()\n for w in _dict.keys():\n w.highLight = True\n self.sprintsGroup1.draw(self.screen)\n self.sprintsGroup1.update()\n self.__E_FPS.draw(self.screen)\n\n def doClockEvent(self, NowClock):\n fps = 'FPS:' + str(self.FPS)\n self.__E_FPS.setText(fps)\n\n # def doKeyPressedEvent(self, keyPressedList):\n # for key in keyPressedList:\n # self.sp1.Events.doKeyboardKeyDowning(exKey(key))\n\n\nclass trueAnimScene(Scene):\n def __init__(self, *args):\n super(trueAnimScene, self).__init__(*args)\n self.allFilesName = list()\n self.path = 'F:\\\\图片\\\\ACG\\\\pix\\\\'\n self.length = 0\n self.index = -1\n # self.img = pygame.image.load(self.path + '0.jpg')\n self.img = ImgElement((0, 0, 1280, 720), self.path + 'Banshee_Queen_Mercy_1.jpg')\n self.allImg = list()\n\n def setup(self):\n for name in os.listdir(self.path):\n self.allImg.append(ImgElement((0, 0, 1280, 720), self.path + name))\n # self.allFilesName.append(self.path + name)\n self.length = len(self.allImg)\n\n def doClockEvent(self, NowClock):\n self.index += 1\n if self.index >= self.length:\n self.index = 0\n self.img = self.allImg[self.index]\n # self.img.setPath(self.allFilesName[self.index])\n print(self.FPS)\n\n def draw(self):\n self.img.draw(self.screen)\n" }, { "alpha_fraction": 0.4482758641242981, "alphanum_fraction": 0.5, "avg_line_length": 18.33333396911621, "blob_id": "4bda317cddbf1382b5c6531143c9123bf3e3c96c", "content_id": "1a2a458b77d07c0842a24ab65d3cc205e07fef98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 58, "license_type": "no_license", "max_line_length": 23, "num_lines": 3, "path": "/source/model/User.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "class User:\n def __init__(self):\n self.hp = 100\n" }, { "alpha_fraction": 0.6570014357566833, "alphanum_fraction": 0.6633663177490234, "avg_line_length": 29.085105895996094, "blob_id": "fd122cda95c8b5bb83d7dc6a4412e680427390d5", "content_id": "ad828973c52062d68d8136cec285c360478c0521", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1496, "license_type": "no_license", "max_line_length": 119, "num_lines": 47, "path": "/source/core/assembly/RSA.py", "repo_name": "AsahinaMikuruFans/ProjectFS", "src_encoding": "UTF-8", "text": "import rsa\nimport json\n\nfrom rsa import PrivateKey\n\n\n# 存储私钥,用getPrivateKeyFromPS读取\ndef outPrivateKeyToPS(path, privateKey) -> None:\n from source.util.ToolsFuc import IntToStr\n from source.core.const.Const import NUM_DICT_M\n _lis = [IntToStr(privateKey.n, NUM_DICT_M), IntToStr(privateKey.e, NUM_DICT_M), IntToStr(privateKey.d, NUM_DICT_M),\n IntToStr(privateKey.p, NUM_DICT_M), IntToStr(privateKey.q, NUM_DICT_M)]\n file = open(path, 'wb')\n byte = json.dumps(_lis).encode('utf-8')\n file.write(byte)\n file.close()\n\n\n# 读取用outPrivateKeyToPS存储的私钥\ndef getPrivateKeyFromPS(path) -> PrivateKey:\n from source.util.ToolsFuc import StrToInt\n from source.core.const.Const import NUM_DICT_M\n file = open(path, 'rb')\n byte = file.read()\n file.close()\n pks = byte.decode('utf-8')\n pko = json.loads(pks)\n return PrivateKey(StrToInt(pko[0], NUM_DICT_M), StrToInt(pko[1], NUM_DICT_M), StrToInt(pko[2], NUM_DICT_M),\n StrToInt(pko[3], NUM_DICT_M), StrToInt(pko[4], NUM_DICT_M))\n\n\n# rsa加密\ndef rsaEncrypt(con, size) -> (str, PrivateKey):\n # 生成公钥、私钥\n (publicKey, privateKey) = rsa.newkeys(size)\n # 明文编码格式\n byte = con.encode('utf-8')\n # 公钥加密\n crypto = rsa.encrypt(byte, publicKey)\n return crypto, privateKey\n\n\n# rsa解密\ndef rsaDecrypt(byte, privateKey) -> str:\n # 私钥解密\n con = rsa.decrypt(byte, privateKey)\n return con.decode('utf-8')\n" } ]
84
jamesmeneghello/pytaghash
https://github.com/jamesmeneghello/pytaghash
d0469098fcf81249f77f6d6ac3ab3d6bbed02742
95c5c7c6d4421c50a2e0c7ff3af20c62393bd0ec
14f3b160bf31c73c73199029e233501c25e42f51
refs/heads/master
2021-06-01T05:45:37.995088
2015-11-28T08:32:29
2015-11-28T08:32:29
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6290322542190552, "alphanum_fraction": 0.6505376100540161, "avg_line_length": 36.20000076293945, "blob_id": "6c1f07c964f55b75fa884a463c264a08af7e6ba8", "content_id": "31a7e2050cada43336db9a1cb1116b6464820784", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 186, "license_type": "no_license", "max_line_length": 117, "num_lines": 5, "path": "/pytaghash/__init__.py", "repo_name": "jamesmeneghello/pytaghash", "src_encoding": "UTF-8", "text": "\"\"\"pytaghash - An extension of BeautifulSoup 4 Tags to provide additional XPath and feature hashing capabilities.\"\"\"\n\n__version__ = '0.1.0'\n__author__ = 'James Meneghello <[email protected]>'\n__all__ = []\n" }, { "alpha_fraction": 0.6494845151901245, "alphanum_fraction": 0.6512027382850647, "avg_line_length": 17.1875, "blob_id": "0bf5cd14a7fa0090e6a1492a14ff6b35a6fd5491", "content_id": "1594d4bc68e8c3faedb27de9bc333d1f513e77ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 582, "license_type": "no_license", "max_line_length": 99, "num_lines": 32, "path": "/README.rst", "repo_name": "jamesmeneghello/pytaghash", "src_encoding": "UTF-8", "text": "pytaghash\n=========\n\n.. image:: https://pypip.in/v/pytaghash/badge.png\n :target: https://pypi.python.org/pypi/pytaghash\n :alt: Latest PyPI version\n\n.. image:: https://travis-ci.org/Murodese/pytaghash.png\n :target: https://travis-ci.org/Murodese/pytaghash\n :alt: Latest Travis CI build status\n\n An extension of BeautifulSoup 4 Tags to provide additional XPath and feature hashing capabilities.\n\nUsage\n-----\n\nInstallation\n------------\n\nRequirements\n^^^^^^^^^^^^\n\nCompatibility\n-------------\n\nLicence\n-------\n\nAuthors\n-------\n\n`pytaghash` was written by `James Meneghello <[email protected]>`_.\n" }, { "alpha_fraction": 0.42304807901382446, "alphanum_fraction": 0.44873663783073425, "avg_line_length": 71.40835571289062, "blob_id": "39729257eb2d62c692ef9ccc45bd35d6f5abc0d1", "content_id": "9a68a600d4a8e9dfbdcbab78a5d00cfa2a8e0cd9", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "Python", "length_bytes": 418089, "license_type": "no_license", "max_line_length": 852, "num_lines": 5767, "path": "/pytaghash/tests/fixtures/tags.py", "repo_name": "jamesmeneghello/pytaghash", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport bs4\n\ncomplex1 = bs4.BeautifulSoup('''\n <li>\n <div></div>\n <p></p>\n <dl>\n <dd></dd>\n <dt></dt>\n </dl>\n <p>\n <br />\n </p>\n </li>\n ''', 'lxml').li\n\ncomplex1_attrib = bs4.BeautifulSoup('''\n <li>\n <div name=\"butt\"></div>\n <p></p>\n <dl>\n <dd></dd>\n <dt></dt>\n </dl>\n <p id=\"poop\">\n <br />\n </p>\n </li>\n ''', 'lxml').li\n\ncomplex1_attrib_diff = bs4.BeautifulSoup('''\n <li name=\"something\">\n <div id=\"blugh\" name=\"butt\"></div>\n <p id=\"stuff\" name=\"butt\"></p>\n <dl id=\"comments\">\n <dd id=\"dong\"></dd>\n <dt name=\"stuff\"></dt>\n </dl>\n <p id=\"poop\" name=\"butt\">\n <br />\n </p>\n </li>\n ''', 'lxml').li\n\ncomplex2 = bs4.BeautifulSoup('''\n <li>\n <div></div>\n <p></p>\n <dl>\n <dd></dd>\n <dt></dt>\n </dl>\n <p>\n <br />\n <br />\n </p>\n </li>\n ''', 'lxml').li\n\ncomplex3 = bs4.BeautifulSoup('''\n <li>\n <div name=\"butt\">\n <p>\n <br />\n <br />\n </p>\n </div>\n <div></div>\n <p></p>\n <a><img></img><p></p></a>\n <div></div>\n <a></a>\n </li>\n ''', 'lxml').li\n\ncomplex4 = bs4.BeautifulSoup('''\n <li>\n <div></div>\n <p></p>\n <dl>\n <p></p>\n </dl>\n <dl>\n <dd></dd>\n <dt></dt>\n </dl>\n <p>\n <br />\n </p>\n </li>\n ''', 'lxml').li\n\nnested_comments_abc = bs4.BeautifulSoup('''\n<ul>\n <li>\n <a id=\"m_ucMessageDisplay1548290_m_anchMessageAnchor\" name=\"m1548290\"></a>\n <h3 class=\"\">Patrick:</h3>\n <p class=\"date\">29 Jan 2015 3:15:55pm</p>\n <p>Abbott displays all the hallmarks of a highly delusional right-man. He appears egotistical in the extreme and it should now be obvious to all that he is an extremely dangerous individual and one who should never be in a position of power, let alone being leader of a nation</p>\n <p>\n <span>\n <a class=\"popup\" href=\"http://www2b.abc.net.au/tmb/View/NewMessage.aspx?b=69&amp;t=12532&amp;tn=&amp;dm=1&amp;m=1548290&amp;tpa=&amp;r=%2ftmb%2fView%2fMessage.aspx%3fb%3d69%26t%3d12532%26a%3d0%26ps%3d50%26tpa%3d%26uto%3d1%26dm%3d4%26ci%3d0%26pd%3d1%26so%3dDateTime%26soa%3dTrue%26p%3d1%26p2%3d0\">Reply</a>\n </span>\n <span>\n <a class=\"popup\" href=\"http://www2b.abc.net.au/tmb/View/AlertModerator.aspx?b=69&amp;m=1548290&amp;tpa=&amp;r=%2ftmb%2fView%2fMessage.aspx%3fb%3d69%26t%3d12532%26a%3d0%26ps%3d50%26tpa%3d%26uto%3d1%26dm%3d4%26ci%3d0%26pd%3d1%26so%3dDateTime%26soa%3dTrue%26p%3d1%26p2%3d0\">\n Alert moderator\n </a>\n </span>\n </p>\n <ul>\n <li>\n <a id=\"m_ucMessageDisplay1548290_m_ucMessageChildren_m_ucMessageDisplay1548374_m_anchMessageAnchor\" name=\"m1548374\"></a>\n <h3 class=\"\">Tony:</h3>\n <p class=\"date\">29 Jan 2015 3:47:38pm</p>\n <p><br>\n Every footy team needs a head-kicker but you don't make him captain.<br></p>\n <p><span><a class=\"popup\" href=\"http://www2b.abc.net.au/tmb/View/NewMessage.aspx?b=69&amp;t=12532&amp;tn=&amp;dm=1&amp;m=1548374&amp;tpa=&amp;r=%2ftmb%2fView%2fMessage.aspx%3fb%3d69%26t%3d12532%26a%3d0%26ps%3d50%26tpa%3d%26uto%3d1%26dm%3d4%26ci%3d0%26pd%3d1%26so%3dDateTime%26soa%3dTrue%26p%3d1%26p2%3d0\">Reply</a></span> <span><a class=\"popup\" href=\"http://www2b.abc.net.au/tmb/View/AlertModerator.aspx?b=69&amp;m=1548374&amp;tpa=&amp;r=%2ftmb%2fView%2fMessage.aspx%3fb%3d69%26t%3d12532%26a%3d0%26ps%3d50%26tpa%3d%26uto%3d1%26dm%3d4%26ci%3d0%26pd%3d1%26so%3dDateTime%26soa%3dTrue%26p%3d1%26p2%3d0\">Alert moderator</a></span></p>\n <ul>\n <li>\n <a id=\"m_ucMessageDisplay1548290_m_ucMessageChildren_m_ucMessageDisplay1548374_m_ucMessageChildren_m_ucMessageDisplay1548466_m_anchMessageAnchor\" name=\"m1548466\"></a>\n <h3 class=\"\">JohnC:</h3>\n <p class=\"date\">29 Jan 2015 4:17:03pm</p>\n <p>@Tony:<br>\n Tony Abbott displayed all of his head kicking prowess as Leader of the Opposition so the LNP would have been fully aware of who they were appointing as team captain. The problem that they now have is that the transition from opposition to government is proving more difficult than expected and the skipper's form on the field is more about playing deep in defence than kicking goals.</p>\n <p><span><a class=\"popup\" href=\"http://www2b.abc.net.au/tmb/View/NewMessage.aspx?b=69&amp;t=12532&amp;tn=&amp;dm=1&amp;m=1548466&amp;tpa=&amp;r=%2ftmb%2fView%2fMessage.aspx%3fb%3d69%26t%3d12532%26a%3d0%26ps%3d50%26tpa%3d%26uto%3d1%26dm%3d4%26ci%3d0%26pd%3d1%26so%3dDateTime%26soa%3dTrue%26p%3d1%26p2%3d0\">Reply</a></span> <span><a class=\"popup\" href=\"http://www2b.abc.net.au/tmb/View/AlertModerator.aspx?b=69&amp;m=1548466&amp;tpa=&amp;r=%2ftmb%2fView%2fMessage.aspx%3fb%3d69%26t%3d12532%26a%3d0%26ps%3d50%26tpa%3d%26uto%3d1%26dm%3d4%26ci%3d0%26pd%3d1%26so%3dDateTime%26soa%3dTrue%26p%3d1%26p2%3d0\">Alert moderator</a></span></p>\n </li>\n <li>\n <a id=\"m_ucMessageDisplay1548290_m_ucMessageChildren_m_ucMessageDisplay1548374_m_ucMessageChildren_m_ucMessageDisplay1548785_m_anchMessageAnchor\" name=\"m1548785\"></a>\n <h3 class=\"\">Arthur:</h3>\n <p class=\"date\">29 Jan 2015 6:07:58pm</p>\n <p>Like<br></p>\\\n <p><span><a class=\"popup\" href=\"http://www2b.abc.net.au/tmb/View/NewMessage.aspx?b=69&amp;t=12532&amp;tn=&amp;dm=1&amp;m=1548785&amp;tpa=&amp;r=%2ftmb%2fView%2fMessage.aspx%3fb%3d69%26t%3d12532%26a%3d0%26ps%3d50%26tpa%3d%26uto%3d1%26dm%3d4%26ci%3d0%26pd%3d1%26so%3dDateTime%26soa%3dTrue%26p%3d1%26p2%3d0\">Reply</a></span> <span><a class=\"popup\" href=\"http://www2b.abc.net.au/tmb/View/AlertModerator.aspx?b=69&amp;m=1548785&amp;tpa=&amp;r=%2ftmb%2fView%2fMessage.aspx%3fb%3d69%26t%3d12532%26a%3d0%26ps%3d50%26tpa%3d%26uto%3d1%26dm%3d4%26ci%3d0%26pd%3d1%26so%3dDateTime%26soa%3dTrue%26p%3d1%26p2%3d0\">Alert moderator</a></span></p>\n </li>\n </ul>\n </li>\n </ul>\n </li>\n <li>\n <a id=\"m_ucMessageDisplay1548290_m_ucMessageChildren_m_ucMessageDisplay1548374_m_ucMessageChildren_m_ucMessageDisplay1548466_m_anchMessageAnchor\" name=\"m1548466\"></a>\n <h3 class=\"\">JohnC:</h3>\n <p class=\"date\">29 Jan 2015 4:17:03pm</p>\n <p>@Tony:<br>\n Tony Abbott displayed all of his head kicking prowess as Leader of the Opposition so the LNP would have been fully aware of who they were appointing as team captain. The problem that they now have is that the transition from opposition to government is proving more difficult than expected and the skipper's form on the field is more about playing deep in defence than kicking goals.</p>\n <p><span><a class=\"popup\" href=\"http://www2b.abc.net.au/tmb/View/NewMessage.aspx?b=69&amp;t=12532&amp;tn=&amp;dm=1&amp;m=1548466&amp;tpa=&amp;r=%2ftmb%2fView%2fMessage.aspx%3fb%3d69%26t%3d12532%26a%3d0%26ps%3d50%26tpa%3d%26uto%3d1%26dm%3d4%26ci%3d0%26pd%3d1%26so%3dDateTime%26soa%3dTrue%26p%3d1%26p2%3d0\">Reply</a></span> <span><a class=\"popup\" href=\"http://www2b.abc.net.au/tmb/View/AlertModerator.aspx?b=69&amp;m=1548466&amp;tpa=&amp;r=%2ftmb%2fView%2fMessage.aspx%3fb%3d69%26t%3d12532%26a%3d0%26ps%3d50%26tpa%3d%26uto%3d1%26dm%3d4%26ci%3d0%26pd%3d1%26so%3dDateTime%26soa%3dTrue%26p%3d1%26p2%3d0\">Alert moderator</a></span></p>\n </li>\n <li>\n <a id=\"m_ucMessageDisplay1548290_m_ucMessageChildren_m_ucMessageDisplay1548374_m_ucMessageChildren_m_ucMessageDisplay1548785_m_anchMessageAnchor\" name=\"m1548785\"></a>\n <h3 class=\"\">Arthur:</h3>\n <p class=\"date\">29 Jan 2015 6:07:58pm</p>\n <p>Like<br></p>\\\n <p><span><a class=\"popup\" href=\"http://www2b.abc.net.au/tmb/View/NewMessage.aspx?b=69&amp;t=12532&amp;tn=&amp;dm=1&amp;m=1548785&amp;tpa=&amp;r=%2ftmb%2fView%2fMessage.aspx%3fb%3d69%26t%3d12532%26a%3d0%26ps%3d50%26tpa%3d%26uto%3d1%26dm%3d4%26ci%3d0%26pd%3d1%26so%3dDateTime%26soa%3dTrue%26p%3d1%26p2%3d0\">Reply</a></span> <span><a class=\"popup\" href=\"http://www2b.abc.net.au/tmb/View/AlertModerator.aspx?b=69&amp;m=1548785&amp;tpa=&amp;r=%2ftmb%2fView%2fMessage.aspx%3fb%3d69%26t%3d12532%26a%3d0%26ps%3d50%26tpa%3d%26uto%3d1%26dm%3d4%26ci%3d0%26pd%3d1%26so%3dDateTime%26soa%3dTrue%26p%3d1%26p2%3d0\">Alert moderator</a></span></p>\n </li>\n</ul>\n''', 'lxml')\n\nnested_comments_kotaku = bs4.BeautifulSoup('''\n<div class=\"post-meta\" id=\"comments\">\n <div class=\"ribbon-separator dark\">\n <span class=\"colour sprite sprite-comments\" style=\"font-style: italic\"></span>\n\n <h4 class=\"pull-left\">Discuss</h4><span class=\"sub pull-right\">23 Comments | <a class=\"anchor-link track_action\" data-tracking-name=\"Jump to Reply Box\" href=\"#respond\">Reply <i class=\"icon-chevron-down icon-white\"></i></a></span>\n </div>\n\n <ul class=\"commentlist\">\n <li class=\"comment depth-1\" data-comment-id=\"3260248\" id=\"comment-3260248\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-32 photo\" height=\"32\" src=\"http://1.gravatar.com/avatar/ffae2ad1f2fda5478ac40f003539f6ad?s=32&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D32&amp;r=G\" width=\"32\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260248\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260248\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260248\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"dre666\">\n dre666 <small><a href=\"/user/dre666/\">@dre666</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 12:17 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>Rally x comes to mind. Colours are wrong though..</p><input class=\"original_comment hide\" type=\"hidden\" value=\"Rally x comes to mind. Colours are wrong though..\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260248#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260248\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260248\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n </li>\n\n <li class=\"comment depth-1\" data-comment-id=\"3260252\" id=\"comment-3260252\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-32 photo\" height=\"32\" src=\"http://0.gravatar.com/avatar/056291335d7a67feb26739dead5d52c5?s=32&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D32&amp;r=G\" width=\"32\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260252\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260252\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260252\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"mickd\">\n mickd <small><a href=\"/user/mickd/\">@mickd</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 12:18 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>what the hell is this \"Also on Kotaku\"</p>\n\n <p>new?</p>\n\n <p>can this please go after comments section</p><input class=\"original_comment hide\" type=\"hidden\" value=\"what the hell is this &quot;Also on Kotaku&quot; new? can this please go after comments section\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260252#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260252\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-success\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260252\" data-toggle=\"modal\" title=\"View Voters\">8</a></span></span>\n </div>\n </div>\n </div><br>\n\n <ul class=\"children\">\n <li class=\"comment depth-2\" data-comment-id=\"3260360\" id=\"comment-3260360\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-24 photo\" height=\"24\" src=\"http://0.gravatar.com/avatar/0993ff5db94278ace29aec8c830da215?s=24&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D24&amp;r=G\" width=\"24\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260360\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260360\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260360\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"edenist\">\n edenist <small><a href=\"/user/edenist/\">@edenist</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 12:59 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>There already is one at the bottom after comments, for the whole Allure network. Seems they've put one up top too.</p>\n\n <p>I agree I really find it visibly irritating when there is advertising content between the article and the comments. Just forcing more content in the readers face any way possible.</p>\n\n <p>EDIT: It's clear they do it for people who come to an article via direct link [from reddit, facebook etc], to expose them to content on the site elsewhere. But for those who browse the front page, we've already seen the articles it displays, I don't want to see them again. Perhaps have a check to disable the middle ad's if you come from the main page?</p>\n\n <p class=\"meta\">Last edited March 10, 2015 1:01 pm</p><input class=\"original_comment hide\" type=\"hidden\" value=\"There already is one at the bottom after comments, for the whole Allure network. Seems they've put one up top too. I agree I really find it visibly irritating when there is advertising content between the article and the comments. Just forcing more content in the readers face any way possible. EDIT: It's clear they do it for people who come to an article via direct link [from reddit, facebook etc], to expose them to content on the site elsewhere. But for those who browse the front page, we've already seen the articles it displays, I don't want to see them again. Perhaps have a check to disable the middle ad's if you come from the main page?\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260360#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260360\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260360\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n </li>\n </ul>\n </li>\n\n <li class=\"comment depth-1\" data-comment-id=\"3260253\" id=\"comment-3260253\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-32 photo\" height=\"32\" src=\"http://0.gravatar.com/avatar/62aeeba5ef45e82d2f6b9a7c4e8f294f?s=32&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D32&amp;r=G\" width=\"32\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260253\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260253\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260253\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"Talicca\">\n Talicca <small><a href=\"/user/talicca/\">@talicca</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 12:19 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>Is that... Adventure? (Atari).</p><input class=\"original_comment hide\" type=\"hidden\" value=\"Is that... Adventure? (Atari).\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260253#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260253\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260253\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n\n <ul class=\"children\">\n <li class=\"comment depth-2\" data-comment-id=\"3260283\" id=\"comment-3260283\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-24 photo\" height=\"24\" src=\"http://1.gravatar.com/avatar/f58277fc869eb4bbbfe36effc8ed9352?s=24&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D24&amp;r=G\" width=\"24\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260283\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260283\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260283\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"WiseHacker\">\n WiseHacker <small><a href=\"/user/wisehacker/\">@wisehacker</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 12:28 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>Dayum. Beat me to it.</p><input class=\"original_comment hide\" type=\"hidden\" value=\"Dayum. Beat me to it.\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260283#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260283\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260283\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n </li>\n\n <li class=\"comment depth-2\" data-comment-id=\"3260285\" id=\"comment-3260285\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-24 photo\" height=\"24\" src=\"http://0.gravatar.com/avatar/2671376cdc60fb70b45a7f2832342789?s=24&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D24&amp;r=G\" width=\"24\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260285\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260285\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260285\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"gnawnborg\">\n gnawnborg <small><a href=\"/user/gnawnborg/\">@gnawnborg</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 12:29 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>Was thinking that as well, but don't think it's quite right</p><input class=\"original_comment hide\" type=\"hidden\" value=\"Was thinking that as well, but don't think it's quite right\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260285#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260285\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260285\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n </li>\n </ul>\n </li>\n\n <li class=\"comment depth-1\" data-comment-id=\"3260254\" id=\"comment-3260254\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-32 photo\" height=\"32\" src=\"http://0.gravatar.com/avatar/c21039d2f9fa4de64662e7af672a7656?s=32&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D32&amp;r=G\" width=\"32\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260254\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260254\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260254\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"Beavwa\">\n Beavwa <small><a href=\"/user/beavwa/\">@beavwa</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 12:19 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>Reminds me of Combat on Atari but there's too much wall and not enough open space.</p><input class=\"original_comment hide\" type=\"hidden\" value=\"Reminds me of Combat on Atari but there's too much wall and not enough open space.\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260254#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260254\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260254\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n\n <ul class=\"children\">\n <li class=\"comment depth-2\" data-comment-id=\"3260255\" id=\"comment-3260255\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-24 photo\" height=\"24\" src=\"http://0.gravatar.com/avatar/c21039d2f9fa4de64662e7af672a7656?s=24&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D24&amp;r=G\" width=\"24\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260255\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260255\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260255\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"Beavwa\">\n Beavwa <small><a href=\"/user/beavwa/\">@beavwa</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 12:20 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>Found the answer but not posting it since I don't Remember This...</p><input class=\"original_comment hide\" type=\"hidden\" value=\"Found the answer but not posting it since I don't Remember This...\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260255#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260255\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260255\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n </li>\n </ul>\n </li>\n\n <li class=\"comment depth-1\" data-comment-id=\"3260257\" id=\"comment-3260257\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-32 photo\" height=\"32\" src=\"http://1.gravatar.com/avatar/5a217a1aab6c8813cdb7a3743fbd7c11?s=32&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D32&amp;r=G\" width=\"32\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260257\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260257\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260257\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"lemonmule\">\n lemonmule <small><a href=\"/user/lemonmule/\">@lemonmule</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 12:21 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>I feel like this might be an atari game..</p>\n\n <p>This \"also on kotaku\" section isn't so bad on browser, but my God ! On mobile it's so in your face and obstructing. Please change it for mobile viewing please.</p><input class=\"original_comment hide\" type=\"hidden\" value=\"I feel like this might be an atari game.. This &quot;also on kotaku&quot; section isn't so bad on browser, but my God ! On mobile it's so in your face and obstructing. Please change it for mobile viewing please.\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260257#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260257\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260257\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n </li>\n\n <li class=\"comment depth-1\" data-comment-id=\"3260262\" id=\"comment-3260262\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-32 photo\" height=\"32\" src=\"http://1.gravatar.com/avatar/d71c37e81746d0a6a9eda145bd09d5ac?s=32&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D32&amp;r=G\" width=\"32\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260262\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260262\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260262\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"Live Long And Prosper\">\n Live Long And Prosper <small><a href=\"/user/cufcfan616/\">@cufcfan616</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 12:23 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>If it was a black background I'd say Bubble Bobble but it's not :(</p><input class=\"original_comment hide\" type=\"hidden\" value=\"If it was a black background I'd say Bubble Bobble but it's not :(\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260262#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260262\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260262\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n\n <ul class=\"children\">\n <li class=\"comment depth-2\" data-comment-id=\"3261606\" id=\"comment-3261606\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-24 photo\" height=\"24\" src=\"http://1.gravatar.com/avatar/16e105590c20bb3de5f39ed031a4a304?s=24&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D24&amp;r=G\" width=\"24\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3261606\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3261606\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3261606\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"matthew\">\n matthew <small><a href=\"/user/matthew/\">@matthew</a></small>\n </div>\n\n <div class=\"meta\">\n March 11, 2015 9:30 am\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>I played Bubble Bobble for a few hours on the weekend. So many happy memories :)</p><input class=\"original_comment hide\" type=\"hidden\" value=\"I played Bubble Bobble for a few hours on the weekend. So many happy memories :)\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3261606#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3261606\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3261606\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n </li>\n </ul>\n </li>\n\n <li class=\"comment depth-1\" data-comment-id=\"3260266\" id=\"comment-3260266\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-32 photo\" height=\"32\" src=\"http://0.gravatar.com/avatar/a8780bff92bcc1d8302b5fca88dcead8?s=32&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D32&amp;r=G\" width=\"32\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260266\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260266\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260266\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"poita\">\n poita <small><a href=\"/user/poita/\">@poita</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 12:24 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>Adventure on the 2600?</p><input class=\"original_comment hide\" type=\"hidden\" value=\"Adventure on the 2600?\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260266#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260266\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260266\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n </li>\n\n <li class=\"comment depth-1\" data-comment-id=\"3260273\" id=\"comment-3260273\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-32 photo\" height=\"32\" src=\"http://0.gravatar.com/avatar/a8780bff92bcc1d8302b5fca88dcead8?s=32&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D32&amp;r=G\" width=\"32\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260273\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260273\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260273\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"poita\">\n poita <small><a href=\"/user/poita/\">@poita</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 12:26 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>Or maybe slot racers on the 2600. My brother and I used to pound that game.</p><input class=\"original_comment hide\" type=\"hidden\" value=\"Or maybe slot racers on the 2600. My brother and I used to pound that game.\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260273#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260273\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260273\" data-toggle=\"modal\" title=\"View Voters\">3</a></span></span>\n </div>\n </div>\n </div><br>\n\n <ul class=\"children\">\n <li class=\"comment depth-2\" data-comment-id=\"3260347\" id=\"comment-3260347\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-24 photo\" height=\"24\" src=\"http://0.gravatar.com/avatar/82f234eb541549955d3775b43aebefbd?s=24&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D24&amp;r=G\" width=\"24\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260347\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260347\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260347\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"konaju\">\n konaju <small><a href=\"/user/konaju/\">@konaju</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 12:52 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>It is indeed.<br>\n <a href=\"http://www.atarimania.com/game-atari-2600-vcs-slot-racers_7374.html\" rel=\"nofollow\">http://www.atarimania.com/game-atari-2600-vcs-slot-racers_7374.html</a></p><input class=\"original_comment hide\" type=\"hidden\" value=\"It is indeed. http://www.atarimania.com/game-atari-2600-vcs-slot-racers_7374.html\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260347#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260347\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260347\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n </li>\n\n <li class=\"comment depth-2\" data-comment-id=\"3260471\" id=\"comment-3260471\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-24 photo\" height=\"24\" src=\"http://1.gravatar.com/avatar/713ae57e2ca20d0e10e82746322ef459?s=24&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D24&amp;r=G\" width=\"24\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260471\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260471\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260471\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"WhitePointer\">\n WhitePointer <small><a href=\"/user/whitepointer/\">@whitepointer</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 1:47 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>Yup, looks like it. Bravo.</p>\n\n <p><a href=\"https://www.youtube.com/watch?v=yyO_G8OBu9w\" rel=\"nofollow\">https://www.youtube.com/watch?v=yyO_G8OBu9w</a></p>\n\n <p>I remember playing this game, and it was pretty bad :/</p>\n\n <p class=\"meta\">Last edited March 10, 2015 1:49 pm</p><input class=\"original_comment hide\" type=\"hidden\" value=\"Yup, looks like it. Bravo. https://www.youtube.com/watch?v=yyO_G8OBu9w I remember playing this game, and it was pretty bad :/\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260471#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260471\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260471\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n\n <ul class=\"children\">\n <li class=\"comment depth-3\" data-comment-id=\"3260633\" id=\"comment-3260633\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-24 photo\" height=\"24\" src=\"http://0.gravatar.com/avatar/a8780bff92bcc1d8302b5fca88dcead8?s=24&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D24&amp;r=G\" width=\"24\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260633\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260633\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260633\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"poita\">\n poita <small><a href=\"/user/poita/\">@poita</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 3:03 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>We only had three games at the time, so we thought it was awesome.</p><input class=\"original_comment hide\" type=\"hidden\" value=\"We only had three games at the time, so we thought it was awesome.\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260633#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260633\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260633\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n </li>\n </ul>\n </li>\n\n <li class=\"comment depth-2\" data-comment-id=\"3260611\" id=\"comment-3260611\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-24 photo\" height=\"24\" src=\"http://1.gravatar.com/avatar/379afc0c121f0b9ab36b11fa2bc59988?s=24&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D24&amp;r=G\" width=\"24\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260611\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260611\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260611\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"oggob\">\n oggob <small><a href=\"/user/oggob/\">@oggob</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 2:56 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>Never seen this one before, but it's basically a bad Combat... lol</p><input class=\"original_comment hide\" type=\"hidden\" value=\"Never seen this one before, but it's basically a bad Combat... lol\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260611#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260611\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260611\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n </li>\n </ul>\n </li>\n\n <li class=\"comment depth-1\" data-comment-id=\"3260300\" id=\"comment-3260300\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-32 photo\" height=\"32\" src=\"http://1.gravatar.com/avatar/bdd66505554b75489fc56a20b12b2e43?s=32&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D32&amp;r=G\" width=\"32\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260300\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260300\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260300\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"bob3\">\n bob3 <small>Guest</small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 12:32 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>Mark obviously went to the classic games postmortem at GDC on Adventure.</p><input class=\"original_comment hide\" type=\"hidden\" value=\"Mark obviously went to the classic games postmortem at GDC on Adventure.\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260300#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260300\"><a class=\"btn btn-mini disabled icon-chevron-up\" style=\"font-style: italic\" title=\"You can't vote on your own comment\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" style=\"font-style: italic\" title=\"You can't vote on your own comment\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260300\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n </li>\n\n <li class=\"comment depth-1\" data-comment-id=\"3260311\" id=\"comment-3260311\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-32 photo\" height=\"32\" src=\"http://0.gravatar.com/avatar/0d9de22c790dc6b1e880868a88c331e5?s=32&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D32&amp;r=G\" width=\"32\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260311\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260311\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260311\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"Zetrox2k\">\n Zetrox2k <small><a href=\"/user/zetrox2k/\">@zetrox2k</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 12:36 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>Pacman - Atari 2600?</p><input class=\"original_comment hide\" type=\"hidden\" value=\"Pacman - Atari 2600?\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260311#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260311\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260311\" data-toggle=\"modal\" title=\"View Voters\">1</a></span></span>\n </div>\n </div>\n </div><br>\n\n <ul class=\"children\">\n <li class=\"comment depth-2\" data-comment-id=\"3260543\" id=\"comment-3260543\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-24 photo\" height=\"24\" src=\"http://1.gravatar.com/avatar/f5ba540c1d18568a6dd513d7a59cece0?s=24&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D24&amp;r=G\" width=\"24\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260543\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260543\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260543\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"pupp3tmast3r\">\n pupp3tmast3r <small><a href=\"/user/pupp3tmast3r/\">@pupp3tmast3r</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 2:21 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>This. The centre arrangement of squares looks a lot like Pacman.</p><input class=\"original_comment hide\" type=\"hidden\" value=\"This. The centre arrangement of squares looks a lot like Pacman.\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260543#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260543\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260543\" data-toggle=\"modal\" title=\"View Voters\">1</a></span></span>\n </div>\n </div>\n </div><br>\n </li>\n </ul>\n </li>\n\n <li class=\"comment depth-1\" data-comment-id=\"3260316\" id=\"comment-3260316\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-32 photo\" height=\"32\" src=\"http://0.gravatar.com/avatar/ac4ed35c82c0f172c46b846fbb56891f?s=32&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D32&amp;r=G\" width=\"32\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260316\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260316\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260316\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"over30yearsofsharing\">\n over30yearsofsharing <small><a href=\"/user/over30yearsofsharing/\">@over30yearsofsharing</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 12:37 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>its minuture golf on the atari 2600</p><input class=\"original_comment hide\" type=\"hidden\" value=\"its minuture golf on the atari 2600\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260316#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260316\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260316\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n </li>\n\n <li class=\"comment depth-1\" data-comment-id=\"3260476\" id=\"comment-3260476\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-32 photo\" height=\"32\" src=\"http://0.gravatar.com/avatar/25ca23a2abec96ecd1b85954bca4dfa2?s=32&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D32&amp;r=G\" width=\"32\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260476\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260476\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260476\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"decoy\">\n decoy <small><a href=\"/user/decoy/\">@decoy</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 1:50 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>Biker Mice from MArs</p><input class=\"original_comment hide\" type=\"hidden\" value=\"Biker Mice from MArs\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260476#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260476\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260476\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n </li>\n\n <li class=\"comment depth-1\" data-comment-id=\"3260801\" id=\"comment-3260801\">\n <div class=\"comment_container\">\n <div class=\"comment_avatar\"><img alt=\"\" class=\"avatar avatar-32 photo\" height=\"32\" src=\"http://1.gravatar.com/avatar/3dd231727df49b9a6799f581191034d3?s=32&amp;d=http%3A%2F%2Fedge.alluremedia.com.au%2Fassets%2Ftechnetwork%2Fimg%2Fkotaku%2Fgravatar.jpg%3Fs%3D32&amp;r=G\" width=\"32\"></div>\n\n <ul class=\"comment_config\">\n <li class=\"showhide\">\n <a class=\"track_action icon-minus\" data-tracking-name=\"Toggle Comment Collapse\" style=\"font-style: italic\" title=\"Hide\"></a>\n </li>\n\n <li class=\"permalink\">\n <a class=\"track_action icon-bookmark\" data-target=\"/wp-admin/admin-ajax.php?id=get_permalink&amp;link=http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260801\" data-toggle=\"modal\" data-tracking-name=\"Permalink\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/comment-page-1/#comment-3260801\" style=\"font-style: italic\" title=\"Permalink\"></a>\n </li>\n\n <li class=\"report\">\n <a class=\"disabled track_action icon-flag\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_report\" data-toggle=\"modal\" data-tracking-name=\"Login to Report\" id=\"report-3260801\" style=\"font-style: italic\" title=\"Login to report this comment\"></a>\n </li>\n </ul>\n\n <div class=\"comment-content-wrap\">\n <div class=\"comment-heading\">\n <div class=\"title\" data-display-name=\"grim-one\">\n grim-one <small><a href=\"/user/grim-one/\">@grim-one</a></small>\n </div>\n\n <div class=\"meta\">\n March 10, 2015 4:31 pm\n </div>\n </div>\n\n <div class=\"comment-content\">\n <p>Reminds me of Wizard of Wor, but it isn't quite right for my C64 copy</p><input class=\"original_comment hide\" type=\"hidden\" value=\"Reminds me of Wizard of Wor, but it isn't quite right for my C64 copy\">\n </div>\n\n <div class=\"comment_reply tracking_article_comments\">\n <a class=\"comment-reply-link\" data-tracking-name=\"Reply\" href=\"/2015/03/remember-this-735/?replytocom=3260801#respond\" title=\"Reply\"><i class=\"icon-share\"></i> Reply</a> <span class=\"comment-vote\" data-comment-id=\"3260801\"><a class=\"btn btn-mini disabled icon-chevron-up\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Up Vote\"></a> <a class=\"btn btn-mini disabled icon-chevron-down\" data-target=\"/wp-admin/admin-ajax.php?id=login_to_vote\" data-toggle=\"modal\" style=\"font-style: italic\" title=\"Down Vote\"></a> <span class=\"vote-count\"><a class=\"btn btn-mini btn-normal\" data-target=\"/wp-admin/admin-ajax.php?id=view_votes&amp;comment=3260801\" data-toggle=\"modal\" title=\"View Voters\">0</a></span></span>\n </div>\n </div>\n </div><br>\n </li>\n </ul>\n\n <div class=\"well\" id=\"respond\">\n <a class=\"btn btn-mini pull-right track_action\" data-tracking-name=\"Cancel Reply\" href=\"http://www.kotaku.com.au/2015/03/remember-this-735/#respond\" id=\"cancel-comment-reply-link\" rel=\"nofollow\" style=\"display:none;\">Cancel Reply</a>\n\n <h3 id=\"reply-title\">Join the discussion!</h3><a class=\"btn btn-mini pull-right track_action\" data-tracking-name=\"Back to log In\" href=\"/user/login/\" id=\"close_comment_login_panel\">Back to log In</a>\n\n <div class=\"clearfix\" id=\"comment_login_panel\">\n <div class=\"panel\">\n <a class=\"btn btn-block btn-primary track_action\" data-target=\"/wp-admin/admin-ajax.php?id=log_in\" data-toggle=\"modal\" data-tracking-name=\"Log In\" href=\"/user/login/\"><i class=\"icon-user icon-white\"></i> Log In</a>\n </div>\n\n <div class=\"panel\">\n <a class=\"btn btn-block track_action\" data-target=\"/wp-admin/admin-ajax.php?id=user_registration\" data-toggle=\"modal\" data-tracking-name=\"Register\" href=\"/user/register/\"><i class=\"icon-plus\"></i> Register</a>\n </div>\n\n <div class=\"panel last\">\n <a class=\"btn btn-block track_action\" data-tracking-name=\"Guest Access\" id=\"show_comment_guest_panel\"><i class=\"icon-chevron-down\"></i> Guest Access</a>\n </div>\n </div>\n\n <form action=\"http://www.kotaku.com.au/2015/03/remember-this-735/\" id=\"comment_form\" method=\"post\" name=\"comment_form\" novalidate=\"novalidate\" style=\"display: none;\">\n <div class=\"comment_text_container clearfix\" id=\"comment_guest_panel\">\n <div class=\"pull-left\">\n <label class=\"placeholder\" for=\"guest_name\">Your Name</label> <input class=\"input-xlarge\" id=\"guest_name\" name=\"guest_name\" placeholder=\"Your Name\" type=\"text\" value=\"\">\n </div>\n\n <div class=\"pull-right\">\n <label class=\"placeholder\" for=\"guest_email\">Your Email</label> <input class=\"input-xlarge\" id=\"guest_email\" name=\"guest_email\" placeholder=\"Your Email\" type=\"text\" value=\"\">\n </div>\n </div>\n\n <div class=\"comment_textarea_container html_editor\">\n <label class=\"placeholder\" for=\"comment_content\">Join the discussion!</label>\n\n <div class=\"btn-toolbar html_editor_bar\" data-target=\"#comment_content\">\n <div class=\"btn-group\">\n <a class=\"btn bold icon-bold\" style=\"font-style: italic\" title=\"Bold\"></a> <a class=\"btn italic icon-italic\" style=\"font-style: italic\" title=\"Italic\"></a> <a class=\"btn underline icon-underline\" style=\"font-style: italic\" title=\"Underline\"></a> <a class=\"btn quote icon-comment-alt\" style=\"font-style: italic\" title=\"Quote\"></a> <a class=\"btn mention icon-bullhorn\" style=\"font-style: italic\" title=\"@ Mention User\"></a> <a class=\"btn spoiler icon-eye-open\" style=\"font-style: italic\" title=\"Toggle Spoiler Content\"></a>\n </div>\n </div>\n <textarea class=\"comment_textarea input-xlarge\" id=\"comment_content\" name=\"comment_content\" placeholder=\"Join the discussion!\" style=\"overflow: hidden; height: 80px;\">\n</textarea>\n </div>\n\n <div class=\"pull-left\" id=\"reply-status\">\n <div class=\"alert alert-success no-close\">\n You are starting a new discussion\n </div>\n </div>\n\n <div class=\"form-submit pull-right\">\n <input class=\"btn btn-primary track_action\" data-tracking-name=\"Submit New Comment\" id=\"comment_submit\" name=\"submit_comment\" type=\"submit\" value=\"Submit\"> <input id=\"comment_post_ID\" name=\"comment_post_ID\" type=\"hidden\" value=\"697351\"> <input id=\"comment_parent\" name=\"comment_parent\" type=\"hidden\" value=\"0\"> <input id=\"post_comment_wpnonce\" name=\"post_comment_wpnonce\" type=\"hidden\" value=\"88aa68ea66\"><input name=\"_wp_http_referer\" type=\"hidden\" value=\"/2015/03/remember-this-735/\"> <input id=\"author\" name=\"author\" style=\"display:none;\" tabindex=\"101\" type=\"text\" value=\"\"> <input id=\"email\" name=\"email\" style=\"display:none;\" tabindex=\"102\" type=\"text\" value=\"\"> <input id=\"url\" name=\"url\" style=\"display:none;\" tabindex=\"103\" type=\"text\" value=\"\">\n <textarea name=\"comment\" style=\"display:none;\" tabindex=\"104\">\n</textarea> <input name=\"datetime\" type=\"hidden\" value=\"1426039439\"> <input name=\"js_data\" type=\"hidden\" value=\"\">\n </div>\n </form>\n </div>\n</div>\n''', 'lxml')\n\nnested_comments_disqus = bs4.BeautifulSoup('''\n<div id=\"posts\">\n <div id=\"form\">\n <form class=\"reply\">\n <div class=\"postbox\">\n <div></div>\n\n <div class=\"avatar\">\n <span class=\"user\"><img alt=\"Avatar\" data-role=\"user-avatar\" src=\"//a.disquscdn.com/next/embed/assets/img/noavatar92.b677f9ddbee6f4bb22f473ae3bd61b85.png\"></span>\n </div>\n\n <div class=\"textarea-wrapper\" data-role=\"textarea\" dir=\"auto\">\n <div>\n <span class=\"placeholder\">Join the discussion…</span>\n\n <div class=\"textarea\" contenteditable=\"true\" data-role=\"editable\" style=\"overflow: auto; max-height: 350px;\" tabindex=\"0\">\n <p><br></p>\n </div>\n\n <div style=\"display: none;\">\n <ul class=\"suggestions\">\n <li class=\"header\">\n <h5>in this conversation</h5>\n </li>\n </ul>\n </div>\n </div>\n\n <div class=\"media-drag-hover\" data-role=\"drag-drop-placeholder\" style=\"display: none\">\n <div class=\"drag-text\">\n ⬇ Drag and drop your images here to upload them.\n </div>\n </div>\n\n <div class=\"media-preview empty\" data-role=\"media-preview\">\n <ul data-role=\"media-legacy-list\"></ul>\n\n <ul data-role=\"media-progress-list\"></ul>\n\n <ul data-role=\"media-rich-list\"></ul>\n\n <div class=\"media-expanded empty\" data-role=\"media-preview-expanded\"><img alt=\"Media preview placeholder\" data-role=\"media-preview-expanded-image\" src=\"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\"></div>\n </div>\n\n <div class=\"edit-alert\"></div>\n\n <div class=\"post-actions\">\n <ul class=\"wysiwyg\">\n <li>\n <a class=\"attach\" data-action=\"attach\" href=\"#\" tabindex=\"-1\" title=\"Upload Images\"><span>Attach</span></a> <input accept=\"image/*\" class=\"regular\" data-role=\"media-upload\" tabindex=\"-1\" type=\"file\">\n </li>\n </ul>\n </div>\n </div>\n\n <div data-role=\"login-form\">\n <div>\n <section class=\"auth-section logged-out\">\n <div class=\"connect\">\n <h6>Sign in with</h6>\n\n <ul class=\"services login-buttons\" data-role=\"login-menu\">\n <li class=\"auth-disqus\"><button class=\"icon-disqus\" data-action=\"auth:disqus\" style=\"font-style: italic\" title=\"Disqus\" type=\"button\"></button></li>\n\n <li class=\"auth-facebook\"><button class=\"icon-facebook-circle\" data-action=\"auth:facebook\" style=\"font-style: italic\" title=\"Facebook\" type=\"button\"></button></li>\n\n <li class=\"auth-twitter\"><button class=\"icon-twitter-circle\" data-action=\"auth:twitter\" style=\"font-style: italic\" title=\"Twitter\" type=\"button\"></button></li>\n\n <li class=\"auth-google\"><button class=\"icon-google-plus-circle\" data-action=\"auth:google\" style=\"font-style: italic\" title=\"Google\" type=\"button\"></button></li>\n </ul>\n </div>\n\n <div class=\"guest\">\n <h6 class=\"guest-form-title\">or register with Disqus</h6>\n\n <div class=\"what-is-disqus help-icon\">\n <div class=\"tooltip show\" id=\"rules\">\n <h3>Disqus is a conversation network</h3>\n\n <ul>\n <li><span>Disqus never moderates or censors. The rules on this community are its own.</span></li>\n\n <li><span>Your email is safe with us. It's only used for moderation and optional notifications.</span></li>\n\n <li><span>Don't be a jerk or do anything illegal. Everything is easier that way.</span></li>\n </ul>\n\n <p class=\"clearfix\"><a class=\"btn btn-small\" href=\"https://docs.disqus.com/kb/terms-and-policies/\" target=\"_blank\">Read full terms and conditions</a></p>\n </div>\n </div>\n\n <p class=\"input-wrapper\"><input dir=\"auto\" id=\"view288_display_name\" maxlength=\"30\" name=\"display_name\" placeholder=\"Name\" type=\"text\"></p>\n\n <div class=\"guest-details\" data-role=\"guest-details\">\n <p class=\"input-wrapper\"><input dir=\"auto\" id=\"view288_email\" name=\"email\" placeholder=\"Email\" type=\"email\"></p>\n\n <p class=\"input-wrapper\"><input dir=\"auto\" id=\"view288_password\" name=\"password\" placeholder=\"Password\" type=\"password\"></p><input name=\"author-guest\" style=\"display:none\" type=\"checkbox\">\n </div>\n </div>\n\n <div class=\"proceed\">\n <button class=\"btn submit\" type=\"submit\"><span class=\"icon-proceed\"></span></button>\n </div>\n </section>\n </div>\n </div>\n </div>\n </form>\n </div><button class=\"alert realtime\" data-role=\"realtime-notification\" style=\"display: none;\"></button>\n\n <div id=\"no-posts\" style=\"display: none;\">\n Be the first to comment.\n </div>\n\n <ul class=\"post-list\" id=\"post-list\">\n <li class=\"post\" id=\"post-1896292556\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"megaseven\" href=\"https://disqus.com/by/megaseven/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"66214858\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"megaseven\" href=\"https://disqus.com/by/megaseven/\">DJ Schway</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896292556\" title=\"Monday, March 9, 2015 6:22 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Welp, I'm depressed. Not only was he a protector of the people, but he was there to buy a gift for his son. /sigh</p>\n\n <p>Also, way to go Ramone. Go back to the scene of the crime like a dingus and get caught.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-28\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">28</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-1\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896292556\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896292556\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1896348335\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"extatix\" href=\"https://disqus.com/by/extatix/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"63760512\" src=\"//a.disquscdn.com/uploads/users/6376/512/avatar92.jpg?1426002765\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"extatix\" href=\"https://disqus.com/by/extatix/\">Giovanni</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896292556\"><i class=\"icon-forward\" title=\"in reply to\"></i> DJ Schway</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896348335\" title=\"Monday, March 9, 2015 7:33 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Other \"news outlets\" differ on the Williams part.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896348335\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896348335\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n </ul>\n </li>\n\n <li class=\"post\" id=\"post-1896292863\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-177e32c9135cbd89ce90cb7cebf0270c\" href=\"https://disqus.com/by/modernmethod-177e32c9135cbd89ce90cb7cebf0270c/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"31408399\" src=\"//a.disquscdn.com/uploads/users/3140/8399/avatar92.jpg?1425957114\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-177e32c9135cbd89ce90cb7cebf0270c\" href=\"https://disqus.com/by/modernmethod-177e32c9135cbd89ce90cb7cebf0270c/\">ph00p</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896292863\" title=\"Monday, March 9, 2015 6:23 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Too soon for the \"blame Battlefield:Hardline\" comment?</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-1\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">1</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-2\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896292863\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896292863\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1896312124\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-73043400d135f80e05f12572b60b2b17\" href=\"https://disqus.com/by/modernmethod-73043400d135f80e05f12572b60b2b17/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"102066339\" src=\"//a.disquscdn.com/uploads/users/10206/6339/avatar92.jpg?1426037586\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-73043400d135f80e05f12572b60b2b17\" href=\"https://disqus.com/by/modernmethod-73043400d135f80e05f12572b60b2b17/\">JBroXNari99</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896292863\"><i class=\"icon-forward\" title=\"in reply to\"></i> ph00p</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896312124\" title=\"Monday, March 9, 2015 6:49 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Yeah, too soon.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-8\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">8</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-1\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896312124\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896312124\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1896593133\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"cyrylthewolf\" href=\"https://disqus.com/by/cyrylthewolf/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"1621535\" src=\"//a.disquscdn.com/uploads/users/162/1535/avatar92.jpg?1425911676\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"cyrylthewolf\" href=\"https://disqus.com/by/cyrylthewolf/\">cyrylthewolf</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896312124\"><i class=\"icon-forward\" title=\"in reply to\"></i> JBroXNari99</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896593133\" title=\"Monday, March 9, 2015 9:40 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>FOREVER.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-3\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">3</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896593133\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896593133\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n\n <li class=\"post\" id=\"post-1897887213\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-76a969fc1d1adaac804d2dabce3451f5\" href=\"https://disqus.com/by/modernmethod-76a969fc1d1adaac804d2dabce3451f5/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"34208920\" src=\"//a.disquscdn.com/uploads/users/3420/8920/avatar92.jpg?1426042481\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-76a969fc1d1adaac804d2dabce3451f5\" href=\"https://disqus.com/by/modernmethod-76a969fc1d1adaac804d2dabce3451f5/\">Kanten</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896312124\"><i class=\"icon-forward\" title=\"in reply to\"></i> JBroXNari99</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1897887213\" title=\"Tuesday, March 10, 2015 7:13 AM\">a day ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>It's never too soon to throw mud at EA.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-1\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">1</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1897887213\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1897887213\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n </ul>\n </li>\n </ul>\n </li>\n\n <li class=\"post\" id=\"post-1896302935\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"renaudb90\" href=\"https://disqus.com/by/renaudb90/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"79133339\" src=\"//a.disquscdn.com/uploads/users/7913/3339/avatar92.jpg?1382807761\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"renaudb90\" href=\"https://disqus.com/by/renaudb90/\">RenaudB90</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896302935\" title=\"Monday, March 9, 2015 6:37 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Well that's just the worst thing ever.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-24\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">24</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-1\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896302935\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896302935\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n\n <li class=\"post\" id=\"post-1896305588\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-0a63135f0a24d85527a1b30f0aeccaa5\" href=\"https://disqus.com/by/modernmethod-0a63135f0a24d85527a1b30f0aeccaa5/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"34201003\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-0a63135f0a24d85527a1b30f0aeccaa5\" href=\"https://disqus.com/by/modernmethod-0a63135f0a24d85527a1b30f0aeccaa5/\">Devin Lee</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896305588\" title=\"Monday, March 9, 2015 6:41 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>most cop news now days is about how the asshole cops get away with shooting people point blank for pretty much no reason, and its a good cop that gets shot in a robbery...</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-4\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">4</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896305588\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896305588\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1896312595\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"Nekrosys\" href=\"https://disqus.com/by/Nekrosys/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"104252315\" src=\"//a.disquscdn.com/uploads/users/10425/2315/avatar92.jpg?1425200107\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"Nekrosys\" href=\"https://disqus.com/by/Nekrosys/\">Nekrosys</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896305588\"><i class=\"icon-forward\" title=\"in reply to\"></i> Devin Lee</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896312595\" title=\"Monday, March 9, 2015 6:49 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>See, I'm under the impression that a lot (most - almost all) cops are of good intent. I may be a little biased considering I have an aunt who works for the police, however.</p>\n\n <p>Putting aside the political and social debates about police, however, the act of intentionally taking another person's life (aside from legitimate cases of self-defence and the like) is beyond reprehensible.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-15\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">15</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-1\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896312595\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896312595\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1898058633\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"disqus_gwRZGkQcwi\" href=\"https://disqus.com/by/disqus_gwRZGkQcwi/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"51506332\" src=\"//a.disquscdn.com/uploads/users/5150/6332/avatar92.jpg?1369207961\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"disqus_gwRZGkQcwi\" href=\"https://disqus.com/by/disqus_gwRZGkQcwi/\">Tiredman</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896312595\"><i class=\"icon-forward\" title=\"in reply to\"></i> Nekrosys</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898058633\" title=\"Tuesday, March 10, 2015 9:14 AM\">a day ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>yeah, i am a bit different. I have no issues with cops myself, but so many of my family members who live in smaller areas have mostly horror stories about cops. Getting beat up for no reason, and being unable to do anything about it because in small towns a lot of the folks in charge are usually related in some way or part of some of the same groups so they tend to stick together.</p>\n\n <p>There are plenty of good cops, but I wouldn't go with \"almost all\". I would say probably 60/40 to 70/30 on the good / not so good ratio.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-1\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">1</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898058633\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1898058633\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1898092831\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"Nekrosys\" href=\"https://disqus.com/by/Nekrosys/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"104252315\" src=\"//a.disquscdn.com/uploads/users/10425/2315/avatar92.jpg?1425200107\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"Nekrosys\" href=\"https://disqus.com/by/Nekrosys/\">Nekrosys</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898058633\"><i class=\"icon-forward\" title=\"in reply to\"></i> Tiredman</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898092831\" title=\"Tuesday, March 10, 2015 9:39 AM\">a day ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Well there may also be cultural differences.</p>\n\n <p>See, I do think a lot of horror stories of cops get latched on to by media outlets just because it allows for a good (read: profitable) story. While there are without a doubt cops of ill-intent, I would assume (read: hope like hell) that they're few and far-between. Though there are the occasional stories over here of cops using their guns as sex toys (that actually happened a month or two ago - it was weird).</p>\n\n <p>As is, most of the 'horror stories' I've heard first-hand about cops over here (Australia, so again, cultural differences) are more stories of people being in the wrong and throwing a fit about it because they got caught speeding or some stupid shit along those lines.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898092831\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1898092831\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1898105608\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"disqus_gwRZGkQcwi\" href=\"https://disqus.com/by/disqus_gwRZGkQcwi/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"51506332\" src=\"//a.disquscdn.com/uploads/users/5150/6332/avatar92.jpg?1369207961\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"disqus_gwRZGkQcwi\" href=\"https://disqus.com/by/disqus_gwRZGkQcwi/\">Tiredman</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898092831\"><i class=\"icon-forward\" title=\"in reply to\"></i> Nekrosys</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898105608\" title=\"Tuesday, March 10, 2015 9:49 AM\">a day ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>You see, the stories have to happen to be reported on, otherwise those places would get sued into dust. That is the problem now. With the internet and cell phones, cop abuse no longer stays between the cops and the victim. Yes cops have a hard job, but they shouldn't be allowed to take out their stress on the innocent.</p>\n\n <p>And aye, my family are located in the mountains of Eastern Kentucky, bible belt country. The town I am living in right now only has a population of 3600, with many of the surrounding small towns being even smaller. Moved here a few years ago, and now I am counting the minutes till I can move away, hopefully sometime this year.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-1\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">1</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898105608\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1898105608\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1898122053\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"Nekrosys\" href=\"https://disqus.com/by/Nekrosys/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"104252315\" src=\"//a.disquscdn.com/uploads/users/10425/2315/avatar92.jpg?1425200107\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"Nekrosys\" href=\"https://disqus.com/by/Nekrosys/\">Nekrosys</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898105608\"><i class=\"icon-forward\" title=\"in reply to\"></i> Tiredman</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898122053\" title=\"Tuesday, March 10, 2015 10:02 AM\">a day ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\" style=\"height: 374px;\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Yeah, but I mean, for every \"cop does evil shit\" story, there's likely to be thousands of \"cop does good shit\" stories that won't be reported on by the media. Naturally, people see more bad-cop stories than good-cop ones. That's just the way media works. Not to mention I don't believe many people will be filming cops if they're doing their jobs properly. Though without a doubt they'll have their phones out if a cop misbehaves.</p>\n\n <p>All of that can lead to a slightly skewed picture with regards to actual police brutality. We're quicker to latch on to the negatives rather than the positives.</p>\n\n <p>Without a doubt, there are cops that aren't doing the right thing. And they should be dealt with accordingly. But I do genuinely think that most of them have the right idea. Or at least, that's what I've personally seen a lot more of.</p>\n\n <p>That may be because where I live just doesn't have as much violent crime. So I guess our police force just aren't as on-edge as they are in a country where dangerous weapons are readily available (pardon for getting a little political with regards to guns). That may be a contributing factor.</p>\n\n <p>Now I do think that if a cop commits a violent crime, they should be dealt with. I also think that police should be held to much greater accountability than most of the populace, considering these people are meant to protect the people and serve as an example. But I do not think that the majority are corrupt.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-1\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898122053\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1898122053\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1898266925\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"disqus_gwRZGkQcwi\" href=\"https://disqus.com/by/disqus_gwRZGkQcwi/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"51506332\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"disqus_gwRZGkQcwi\" href=\"https://disqus.com/by/disqus_gwRZGkQcwi/\">Tiredman</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898122053\"><i class=\"icon-forward\" title=\"in reply to\"></i> Nekrosys</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898266925\" title=\"Tuesday, March 10, 2015 12:20 PM\">a day ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>What it all boils down to is the police need stricter standards of hiring. Also they need to up their game to get these issues stopped, preferably before they happen through psych evaluations and training. Even if it is only a handful of bad apples, they are dealing with people's lives, which makes it a huge problem when one of those few bad things happen.</p>\n\n <p>The last thing is, as you say, if a cop does a violent crime, they should be dealt with. We are having an issue at the moment where the corruption is showing in the lime light. In the US its knowing that lawyers and judges will protect the police force, even when the police are in the wrong. A new story recently talked about a lawyer in an area who actually went against a cop in that same area.</p>\n\n <p>After the trial, which I can't remember if it was a win or a loss for the lawyer, the police force in mass started not participating with the justice department on crimes, and making the job harder for that lawyer and others who were buddies with that lawyer. That is a serious problem. When the police protect those who broke the law, even when they know that cop broke the law, it shows how deep the corruption has gone. And even when judges and lawyers get in on it, then justice truly is blind because it can't tell when it is being abused.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-2\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">2</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898266925\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1898266925\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n </ul>\n </li>\n </ul>\n </li>\n </ul>\n </li>\n </ul>\n </li>\n </ul>\n </li>\n\n <li class=\"post\" id=\"post-1896334848\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"Beoslasher\" href=\"https://disqus.com/by/Beoslasher/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"66156770\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"Beoslasher\" href=\"https://disqus.com/by/Beoslasher/\">Miles Wilburn</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896305588\"><i class=\"icon-forward\" title=\"in reply to\"></i> Devin Lee</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896334848\" title=\"Monday, March 9, 2015 7:16 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Unfortunately, these shooting cases are probably more than just asshole cops shooting people for no reason. The media is gonna portray whatever side will get them the most ratings. The mistake people make is that they think media sources are their friends. However, in this case it's cut and dry and its a damn shame that the officer had to be killed. Hope these criminals get their just desserts.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-6\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">6</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-3\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896334848\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896334848\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1896972779\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-05f747f9753a0b4172a8faf1128a78e1\" href=\"https://disqus.com/by/modernmethod-05f747f9753a0b4172a8faf1128a78e1/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"34194483\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-05f747f9753a0b4172a8faf1128a78e1\" href=\"https://disqus.com/by/modernmethod-05f747f9753a0b4172a8faf1128a78e1/\">Retrofraction</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896334848\"><i class=\"icon-forward\" title=\"in reply to\"></i> Miles Wilburn</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896972779\" title=\"Tuesday, March 10, 2015 12:28 AM\">a day ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>It is so true, most media corporations are owned by banks... and rather focus on news to better themselves.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896972779\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896972779\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n\n <li class=\"post\" id=\"post-1897052828\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"disqus_fq3Dz51T3b\" href=\"https://disqus.com/by/disqus_fq3Dz51T3b/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"96832845\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"disqus_fq3Dz51T3b\" href=\"https://disqus.com/by/disqus_fq3Dz51T3b/\">bob loblaw</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896334848\"><i class=\"icon-forward\" title=\"in reply to\"></i> Miles Wilburn</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1897052828\" title=\"Tuesday, March 10, 2015 12:58 AM\">a day ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Its easy to say not being a cop. Have a job where getting shot is a daily possibility, then see how you react to someone who charges you and goes for your gun, or makes a stupid quick motion with their hand from their belt.<br>\n Very easy to say its just cops being assholes and shooting people because of color. Completely different reality when you are a cop and losing you life earning a middle class salary is a real possibility.<br>\n Im sure if you ask any cop involved in recent shooting, they all would have preferred things didn't go that way, but I guarantee you you wouldn't be ready to sacrifice your life in the name of social justice.<br>\n If you ask me, how stupid does someone have to be to either charge a cop with his gun drawn, or not follow the simple orders a cop gives you when they approach you with a gun drawn? Cops doesn't know you, who you are, what you have on you, or your intent. Just play along put your hand up and let the cop determine you are no threat and no one gets shot.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-1\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1897052828\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1897052828\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1898066378\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"disqus_gwRZGkQcwi\" href=\"https://disqus.com/by/disqus_gwRZGkQcwi/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"51506332\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"disqus_gwRZGkQcwi\" href=\"https://disqus.com/by/disqus_gwRZGkQcwi/\">Tiredman</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1897052828\"><i class=\"icon-forward\" title=\"in reply to\"></i> bob loblaw</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898066378\" title=\"Tuesday, March 10, 2015 9:20 AM\">a day ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Watch the video on the hispanic man who was shot in Washington. That is why people are spooked by police. If you find the unedited video, you hear of a man throwing small rocks at police. Then police draw guns after a taser didn't work, and when the man is running across a road, the police open fire on him on a crowded street where their bullets could easily hit innocent bystanders. Then the police crossed the street after the man who had fallen do his knees. He held his arms up to the police who were hovering over him and finished him off execution style. A man was throwing rocks, and in return 3 or 4 cops filled him full of bullets.</p>\n\n <p>The problem is that is not an isolated story thanks to mobile phones and the internet. Actually, that isn't a problem, that is a good thing that will hopefully cause the police force to start screening who it lets in and gives a license to kill. Too many power hungry people who have bully tendencies get into law enforcement just so they can be state backed bully's.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-1\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">1</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898066378\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1898066378\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n </ul>\n </li>\n\n <li class=\"post\" id=\"post-1898059462\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"disqus_gwRZGkQcwi\" href=\"https://disqus.com/by/disqus_gwRZGkQcwi/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"51506332\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"disqus_gwRZGkQcwi\" href=\"https://disqus.com/by/disqus_gwRZGkQcwi/\">Tiredman</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896334848\"><i class=\"icon-forward\" title=\"in reply to\"></i> Miles Wilburn</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898059462\" title=\"Tuesday, March 10, 2015 9:15 AM\">a day ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>First degree murder, yeah, they will either get life without parole or death sentence if they are in a state with it.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898059462\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1898059462\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n </ul>\n </li>\n\n <li class=\"post\" id=\"post-1896431132\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-84f44305ddacdb3c69e8aaf21312b343\" href=\"https://disqus.com/by/modernmethod-84f44305ddacdb3c69e8aaf21312b343/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"48332509\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-84f44305ddacdb3c69e8aaf21312b343\" href=\"https://disqus.com/by/modernmethod-84f44305ddacdb3c69e8aaf21312b343/\">Keiichi Morisato</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896305588\"><i class=\"icon-forward\" title=\"in reply to\"></i> Devin Lee</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896431132\" title=\"Monday, March 9, 2015 8:34 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>actually, in one of the cases that you are thinking of *chough* Ferguson *cough* the sole eyewitness lied because she beforehand already had a bias against police officers.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-1\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">1</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896431132\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896431132\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n\n <li class=\"post\" id=\"post-1896604100\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"the_ferginator\" href=\"https://disqus.com/by/the_ferginator/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"48323331\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"the_ferginator\" href=\"https://disqus.com/by/the_ferginator/\">The Ferginator</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896305588\"><i class=\"icon-forward\" title=\"in reply to\"></i> Devin Lee</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896604100\" title=\"Monday, March 9, 2015 9:47 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\" style=\"height: 374px;\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p><span></span></p>\n\n <div class=\"media-container media-mode-deferred\">\n <a class=\"media-button media-button-expand publisher-color publisher-border-color\" data-action=\"expand\" href=\"https://www.facebook.com/video.php?v=2296766557537&amp;pnref=storyhttps://www.facebook.com/video.php?v=2296766557537&amp;pnref=story\" rel=\"nofollow\" target=\"_blank\" title=\"Facebook – Jerry LLanes | Facebook\"><i class=\"icon-video publisher-background-color\"></i> View</a> <a class=\"media-button media-button-contract publisher-color publisher-border-color\" data-action=\"contract\" href=\"#\" target=\"_blank\"><i class=\"icon-cancel publisher-background-color\"></i> Hide</a>\n\n <div class=\"media-content-loader\" data-role=\"content-loader\"></div>\n\n <div class=\"media-content-placeholder\" data-role=\"content-placeholder\" style=\"height: 384px;\">\n <a class=\"media-force-load icon-video\" data-action=\"force-load\" href=\"#\" style=\"font-style: italic\"></a>\n </div>\n </div>\n <p>\n\n <p>I'm not condoning incidents like the Tamir Rice shooting, obviously that was just bullshit, but when you see what they have to put up with a lot of the time is it really that surprising when these things happen from time to time? Anyone who thinks the Ferguson riots were justified or has a mentality that thinks cop killing is justified by isolated incidents or even that these incidents reflect law enforcement as a whole, can go fuck themselves as far as i'm concerned.</p>\n\n <p>R.I.P. Brother.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-4\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">4</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-1\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896604100\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896604100\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n </ul>\n </li>\n\n <li class=\"post\" id=\"post-1896306633\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-945201efd3c41709a17cfd4ee2eb0f81\" href=\"https://disqus.com/by/modernmethod-945201efd3c41709a17cfd4ee2eb0f81/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"31405479\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-945201efd3c41709a17cfd4ee2eb0f81\" href=\"https://disqus.com/by/modernmethod-945201efd3c41709a17cfd4ee2eb0f81/\">Osaka</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896306633\" title=\"Monday, March 9, 2015 6:42 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Hipps.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896306633\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896306633\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n\n <li class=\"post\" id=\"post-1896307060\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"Nekrosys\" href=\"https://disqus.com/by/Nekrosys/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"104252315\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"Nekrosys\" href=\"https://disqus.com/by/Nekrosys/\">Nekrosys</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896307060\" title=\"Monday, March 9, 2015 6:43 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Would now be the right time to make a comment about Amiibo being in low supply?</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-1\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896307060\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896307060\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1896310939\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-73043400d135f80e05f12572b60b2b17\" href=\"https://disqus.com/by/modernmethod-73043400d135f80e05f12572b60b2b17/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"102066339\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-73043400d135f80e05f12572b60b2b17\" href=\"https://disqus.com/by/modernmethod-73043400d135f80e05f12572b60b2b17/\">JBroXNari99</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896307060\"><i class=\"icon-forward\" title=\"in reply to\"></i> Nekrosys</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896310939\" title=\"Monday, March 9, 2015 6:48 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>If a rare Amiibo came out today, that would have been terrible. The folks in New England are having to go out in freezing cold temperatures in the morning of they even want a chance of finding a rare, and now this happens? If he wanted to get him an Amiibo, that would have been terrible.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896310939\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896310939\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n\n <li class=\"post\" id=\"post-1896835423\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-6ae650374b519325eb34d8187f5aa757\" href=\"https://disqus.com/by/modernmethod-6ae650374b519325eb34d8187f5aa757/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"38215922\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-6ae650374b519325eb34d8187f5aa757\" href=\"https://disqus.com/by/modernmethod-6ae650374b519325eb34d8187f5aa757/\">BlunderBuss</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896307060\"><i class=\"icon-forward\" title=\"in reply to\"></i> Nekrosys</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896835423\" title=\"Monday, March 9, 2015 11:49 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Not really, those things are worthless enough as it is.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896835423\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896835423\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n </ul>\n </li>\n\n <li class=\"post\" id=\"post-1896311806\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"michaelrabattino\" href=\"https://disqus.com/by/michaelrabattino/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"55669613\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"michaelrabattino\" href=\"https://disqus.com/by/michaelrabattino/\">Michael Rabattino</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896311806\" title=\"Monday, March 9, 2015 6:48 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Hate to be this guy, but...*Philadelphia</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896311806\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896311806\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1896601400\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-8702581b10fc44c8ee9021a967744624\" href=\"https://disqus.com/by/modernmethod-8702581b10fc44c8ee9021a967744624/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"34193529\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-8702581b10fc44c8ee9021a967744624\" href=\"https://disqus.com/by/modernmethod-8702581b10fc44c8ee9021a967744624/\">Charlietime</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896311806\"><i class=\"icon-forward\" title=\"in reply to\"></i> Michael Rabattino</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896601400\" title=\"Monday, March 9, 2015 9:46 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Philly is a great place, just don't go across the river unless you have to.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896601400\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896601400\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1896739572\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"michaelrabattino\" href=\"https://disqus.com/by/michaelrabattino/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"55669613\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"michaelrabattino\" href=\"https://disqus.com/by/michaelrabattino/\">Michael Rabattino</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896601400\"><i class=\"icon-forward\" title=\"in reply to\"></i> Charlietime</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896739572\" title=\"Monday, March 9, 2015 11:13 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>I live in South Jersey so I'm quite familiar with the greatness of Philly.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-1\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">1</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896739572\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896739572\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1898213857\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-8702581b10fc44c8ee9021a967744624\" href=\"https://disqus.com/by/modernmethod-8702581b10fc44c8ee9021a967744624/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"34193529\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-8702581b10fc44c8ee9021a967744624\" href=\"https://disqus.com/by/modernmethod-8702581b10fc44c8ee9021a967744624/\">Charlietime</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896739572\"><i class=\"icon-forward\" title=\"in reply to\"></i> Michael Rabattino</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898213857\" title=\"Tuesday, March 10, 2015 11:20 AM\">a day ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>then you've crossed the river and done fucked up. My misses is from cherry hill and I lived in lindenwold for a bit.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1898213857\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1898213857\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n </ul>\n </li>\n </ul>\n </li>\n\n <li class=\"post\" id=\"post-1896605514\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"CaptainProtonX\" href=\"https://disqus.com/by/CaptainProtonX/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"35032243\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"CaptainProtonX\" href=\"https://disqus.com/by/CaptainProtonX/\">CaptainProtonX</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896311806\"><i class=\"icon-forward\" title=\"in reply to\"></i> Michael Rabattino</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896605514\" title=\"Monday, March 9, 2015 9:48 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Philadelphia is a metropolitan center with over 1.5 million residents. It is experiencing a massive dip in crime, and is seeing a rise in equity.</p>\n\n <p>Like any major city, it will experience crime as opportunists will take advantage of situations they feel will lead to a payoff. Blaming the situation on the city being a city is a vacuous argument and brings nothing to the topic of a brave individual dying in the line of fire.</p>\n\n <p>Hate to be this guy, but...*Troll.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896605514\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896605514\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1896736634\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"michaelrabattino\" href=\"https://disqus.com/by/michaelrabattino/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"55669613\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"michaelrabattino\" href=\"https://disqus.com/by/michaelrabattino/\">Michael Rabattino</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896605514\"><i class=\"icon-forward\" title=\"in reply to\"></i> CaptainProtonX</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896736634\" title=\"Monday, March 9, 2015 11:12 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>What the hell are you talking about? I was referring to the author's gross misspelling of the name of the city. It's been fixed since I posted, but it was \"Philidelphia\" before.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-2\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">2</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-1\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896736634\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896736634\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n </ul>\n </li>\n </ul>\n </li>\n\n <li class=\"post\" id=\"post-1896323246\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"S_Daedalus\" href=\"https://disqus.com/by/S_Daedalus/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"37813913\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"S_Daedalus\" href=\"https://disqus.com/by/S_Daedalus/\">S_Daedalus</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896323246\" title=\"Monday, March 9, 2015 7:01 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Madness...</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-2\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">2</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896323246\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896323246\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n\n <li class=\"post\" id=\"post-1896325736\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"dieger\" href=\"https://disqus.com/by/dieger/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"39073275\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"dieger\" href=\"https://disqus.com/by/dieger/\">dieger</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896325736\" title=\"Monday, March 9, 2015 7:04 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>shit ;/</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-1\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">1</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896325736\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896325736\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n\n <li class=\"post\" id=\"post-1896337348\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"ThePerro\" href=\"https://disqus.com/by/ThePerro/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"96350405\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"ThePerro\" href=\"https://disqus.com/by/ThePerro/\">Perro</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896337348\" title=\"Monday, March 9, 2015 7:19 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>So senseless, I hope for the best for his family during this hard time.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-2\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">2</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896337348\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896337348\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n\n <li class=\"post\" id=\"post-1896337645\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"disqus_gzIN10nmNv\" href=\"https://disqus.com/by/disqus_gzIN10nmNv/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"80723001\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"disqus_gzIN10nmNv\" href=\"https://disqus.com/by/disqus_gzIN10nmNv/\">EGG™</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896337645\" title=\"Monday, March 9, 2015 7:20 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>That's so petty I hate it</p>\n\n <p>Why didnt they</p>\n\n <p>yknow</p>\n\n <p>try to rob another day?</p>\n\n <p>it doesnt solve the problem but any normal human being with common sense wouldve been scared and fleed instead of come up with lets get in a giant shootout with the cop over gamestop money</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896337645\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896337645\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1896351646\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-1d971eb3ba4f14c10bd64455b86b89aa\" href=\"https://disqus.com/by/modernmethod-1d971eb3ba4f14c10bd64455b86b89aa/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"38909424\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-1d971eb3ba4f14c10bd64455b86b89aa\" href=\"https://disqus.com/by/modernmethod-1d971eb3ba4f14c10bd64455b86b89aa/\">Chist</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896337645\"><i class=\"icon-forward\" title=\"in reply to\"></i> EGG™</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896351646\" title=\"Monday, March 9, 2015 7:36 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Any crime that results in the loss of a life is petty. Nothing is worth that price.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-3\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">3</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896351646\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896351646\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n </ul>\n </li>\n\n <li class=\"post\" id=\"post-1896338816\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-1d971eb3ba4f14c10bd64455b86b89aa\" href=\"https://disqus.com/by/modernmethod-1d971eb3ba4f14c10bd64455b86b89aa/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"38909424\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-1d971eb3ba4f14c10bd64455b86b89aa\" href=\"https://disqus.com/by/modernmethod-1d971eb3ba4f14c10bd64455b86b89aa/\">Chist</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896338816\" title=\"Monday, March 9, 2015 7:21 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>This is an inappropriate article to be cracking jokes on, guys. Let's set aside the sarcasm and funny bone, guy was a badass and a hero, so just take the time to show him some respect, and appreciate the kind of danger he put himself in to keep civilians out of the crossfire.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-65\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">65</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-2\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896338816\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896338816\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1896344471\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-97d0145823aeb8ed80617be62e08bdcc\" href=\"https://disqus.com/by/modernmethod-97d0145823aeb8ed80617be62e08bdcc/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"31411170\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-97d0145823aeb8ed80617be62e08bdcc\" href=\"https://disqus.com/by/modernmethod-97d0145823aeb8ed80617be62e08bdcc/\">pedrovay2003</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896338816\"><i class=\"icon-forward\" title=\"in reply to\"></i> Chist</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896344471\" title=\"Monday, March 9, 2015 7:28 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>That's not going to stop people, unfortunately, as we can already see.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896344471\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896344471\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n\n <li class=\"post\" id=\"post-1896362061\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"Nekrosys\" href=\"https://disqus.com/by/Nekrosys/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"104252315\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"Nekrosys\" href=\"https://disqus.com/by/Nekrosys/\">Nekrosys</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896338816\"><i class=\"icon-forward\" title=\"in reply to\"></i> Chist</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896362061\" title=\"Monday, March 9, 2015 7:48 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>I'm probably an outlier here, but I'm very much of the impression that making a joke about a shitty situation can be used as a way to cheer oneself (and others - depending on the people) up just a little.</p>\n\n <p>You know, unless the joke is specifically targeted at the victim as a method of belittling them.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-12\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">12</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896362061\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896362061\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1896363796\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-1d971eb3ba4f14c10bd64455b86b89aa\" href=\"https://disqus.com/by/modernmethod-1d971eb3ba4f14c10bd64455b86b89aa/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"38909424\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-1d971eb3ba4f14c10bd64455b86b89aa\" href=\"https://disqus.com/by/modernmethod-1d971eb3ba4f14c10bd64455b86b89aa/\">Chist</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896362061\"><i class=\"icon-forward\" title=\"in reply to\"></i> Nekrosys</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896363796\" title=\"Monday, March 9, 2015 7:50 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>No, I get it, it's fine to crack a joke in private, but this isn't the place for that kind of grieving.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-1\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">1</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-3\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896363796\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896363796\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1896459696\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-73a492c854b0e4827cbd5684a8a5a076\" href=\"https://disqus.com/by/modernmethod-73a492c854b0e4827cbd5684a8a5a076/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"48333072\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-73a492c854b0e4827cbd5684a8a5a076\" href=\"https://disqus.com/by/modernmethod-73a492c854b0e4827cbd5684a8a5a076/\">whereismymind86</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896363796\"><i class=\"icon-forward\" title=\"in reply to\"></i> Chist</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896459696\" title=\"Monday, March 9, 2015 8:42 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>shut the hell up, what makes you fucking special?</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-4\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896459696\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896459696\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1896461449\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-1d971eb3ba4f14c10bd64455b86b89aa\" href=\"https://disqus.com/by/modernmethod-1d971eb3ba4f14c10bd64455b86b89aa/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"38909424\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-1d971eb3ba4f14c10bd64455b86b89aa\" href=\"https://disqus.com/by/modernmethod-1d971eb3ba4f14c10bd64455b86b89aa/\">Chist</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896459696\"><i class=\"icon-forward\" title=\"in reply to\"></i> whereismymind86</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896461449\" title=\"Monday, March 9, 2015 8:43 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Absolutely nothing. I'm just asking for some basic respect to be shown.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-10\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">10</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-1\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896461449\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896461449\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n\n <li class=\"post\" id=\"post-1896471934\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"Nekrosys\" href=\"https://disqus.com/by/Nekrosys/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"104252315\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"Nekrosys\" href=\"https://disqus.com/by/Nekrosys/\">Nekrosys</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896459696\"><i class=\"icon-forward\" title=\"in reply to\"></i> whereismymind86</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896471934\" title=\"Monday, March 9, 2015 8:52 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Disagree with Chist as much as you like, but that's a little bit unnecessarily harsh.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-4\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">4</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896471934\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896471934\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n\n <li class=\"post\" id=\"post-1896477534\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-daed210307f1dbc6f1dd9551408d999f\" href=\"https://disqus.com/by/modernmethod-daed210307f1dbc6f1dd9551408d999f/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"34417113\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-daed210307f1dbc6f1dd9551408d999f\" href=\"https://disqus.com/by/modernmethod-daed210307f1dbc6f1dd9551408d999f/\">JACK of No Trades</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896459696\"><i class=\"icon-forward\" title=\"in reply to\"></i> whereismymind86</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896477534\" title=\"Monday, March 9, 2015 8:55 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>He is right, you are wrong. Deal with it punk.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-1\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896477534\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896477534\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n\n <li class=\"post\" id=\"post-1896712696\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"coppersam\" href=\"https://disqus.com/by/coppersam/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"117937138\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"coppersam\" href=\"https://disqus.com/by/coppersam/\">coppersam</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896459696\"><i class=\"icon-forward\" title=\"in reply to\"></i> whereismymind86</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896712696\" title=\"Monday, March 9, 2015 10:59 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>move along. come back in a few years when your maturity allows you to participate in social discourse like an adult.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-1\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896712696\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896712696\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n </ul>\n </li>\n </ul>\n </li>\n\n <li class=\"post\" id=\"post-1896426571\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"Absolutfreak\" href=\"https://disqus.com/by/Absolutfreak/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"27373701\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"Absolutfreak\" href=\"https://disqus.com/by/Absolutfreak/\">Absolutfreak</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896362061\"><i class=\"icon-forward\" title=\"in reply to\"></i> Nekrosys</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896426571\" title=\"Monday, March 9, 2015 8:30 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>I agree with you, but generally the internet is the place where things get right out of hand.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-3\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">3</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896426571\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896426571\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n\n <li class=\"post\" id=\"post-1896553941\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-9b31229c5fd58c1ddb694f0232d0dd1f\" href=\"https://disqus.com/by/modernmethod-9b31229c5fd58c1ddb694f0232d0dd1f/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"31431672\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-9b31229c5fd58c1ddb694f0232d0dd1f\" href=\"https://disqus.com/by/modernmethod-9b31229c5fd58c1ddb694f0232d0dd1f/\">Ragnar Dragonfyre</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896362061\"><i class=\"icon-forward\" title=\"in reply to\"></i> Nekrosys</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896553941\" title=\"Monday, March 9, 2015 9:20 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>There are situations where you can make light of a shitty situation to cheer oneself up.</p>\n\n <p>This is not one of them.</p>\n\n <p>A man is dead. Show some fucking respect.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-3\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">3</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-1\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896553941\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896553941\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\">\n <li class=\"post\" id=\"post-1896559709\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"Nekrosys\" href=\"https://disqus.com/by/Nekrosys/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"104252315\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"Nekrosys\" href=\"https://disqus.com/by/Nekrosys/\">Nekrosys</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896553941\"><i class=\"icon-forward\" title=\"in reply to\"></i> Ragnar Dragonfyre</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896559709\" title=\"Monday, March 9, 2015 9:23 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>That's a pretty disrespectful way of asking for respect, if I do say so myself.</p>\n\n <p>Is that the way you speak to everyone with a difference of opinion?</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-4\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">4</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-3\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896559709\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896559709\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n </ul>\n </li>\n\n <li class=\"post\" id=\"post-1897252124\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"modernmethod-cd9015a609618aa8dcd0a7ff7941c475\" href=\"https://disqus.com/by/modernmethod-cd9015a609618aa8dcd0a7ff7941c475/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"31592297\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"modernmethod-cd9015a609618aa8dcd0a7ff7941c475\" href=\"https://disqus.com/by/modernmethod-cd9015a609618aa8dcd0a7ff7941c475/\">MuddBstrd</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896362061\"><i class=\"icon-forward\" title=\"in reply to\"></i> Nekrosys</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1897252124\" title=\"Tuesday, March 10, 2015 2:23 AM\">a day ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Dude, this isn't about cheering YOU up, it's about showing respect for someone else. By making the situation about what you want, you're being incredibly self-centered.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-1\" data-action=\"upvote\" href=\"#\" title=\"\"><span class=\"updatable count\" data-role=\"likes\">1</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1897252124\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1897252124\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n </ul>\n </li>\n\n <li class=\"post\" id=\"post-1896607633\">\n <div></div>\n\n <div class=\"post-content\" data-role=\"post-content\">\n <ul class=\"post-menu dropdown\" data-role=\"menu\">\n <li class=\"collapse\">\n <a data-action=\"collapse\" href=\"#\" title=\"Collapse\"><span>−</span></a>\n </li>\n\n <li class=\"expand\">\n <a data-action=\"collapse\" href=\"#\" title=\"Expand\"><span>+</span></a>\n </li>\n\n <li class=\"\">\n <a class=\"dropdown-toggle icon icon-flag\" data-action=\"flag\" data-role=\"flag\" href=\"#\" style=\"font-style: italic\" title=\"Flag as inappropriate\"></a>\n </li>\n </ul>\n\n <div class=\"indicator\"></div>\n\n <div class=\"avatar hovercard\">\n <a class=\"user\" data-action=\"profile\" data-username=\"KymikoLoco\" href=\"https://disqus.com/by/KymikoLoco/\"><img alt=\"Avatar\" data-role=\"user-avatar\" data-user=\"75932539\" src=\"//a.disquscdn.com/uploads/forums/68/1221/avatar92.jpg?1387564011\"></a>\n </div>\n\n <div class=\"post-body\">\n <header>\n <span class=\"post-byline\"><span class=\"author publisher-anchor-color\"><a data-action=\"profile\" data-role=\"username\" data-username=\"KymikoLoco\" href=\"https://disqus.com/by/KymikoLoco/\">KymikoLoco</a></span> <span><a class=\"parent-link\" data-role=\"parent-link\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896338816\"><i class=\"icon-forward\" title=\"in reply to\"></i> Chist</a></span></span> <span class=\"post-meta\"><span class=\"bullet time-ago-bullet\">•</span> <a class=\"time-ago\" data-role=\"relative-time\" href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896607633\" title=\"Monday, March 9, 2015 9:50 PM\">2 days ago</a></span>\n </header>\n\n <div class=\"post-body-inner\">\n <div class=\"post-message-container\" data-role=\"message-container\">\n <div class=\"publisher-anchor-color\" data-role=\"message-content\">\n <div class=\"post-message\" data-role=\"message\" dir=\"auto\">\n <p>Who was cracking jokes?</p>\n\n <p>Seriously, this is a featured comment, but I only saw one deleted comment that I presume was 'joking'.</p>\n\n <p>The featured comment should be the one about the fund set up for the officer's family.</p>\n </div><span class=\"post-media\"></span>\n\n <ul data-role=\"post-media-list\"></ul>\n </div>\n </div><a class=\"see-more hidden\" data-action=\"see-more\" title=\"see more\">see more</a>\n </div>\n\n <footer>\n <ul>\n <li class=\"voting\" data-role=\"voting\">\n <a class=\"vote-up count-0\" data-action=\"upvote\" href=\"#\" title=\"Vote up\"><span class=\"updatable count\" data-role=\"likes\">0</span> <span class=\"control icon icon-arrow-2\" style=\"font-style: italic\"></span></a> <span class=\"vote-down count-0\" data-action=\"downvote\" title=\"Vote down\"><span class=\"control icon icon-arrow\" style=\"font-style: italic\"></span></span>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"reply\" data-role=\"reply-link\">\n <a data-action=\"reply\" href=\"#\"><i class=\"icon icon-mobile icon-reply\"></i><span class=\"text\">Reply</span></a>\n </li>\n\n <li class=\"bullet\">•</li>\n\n <li class=\"share\">\n <a class=\"toggle\"><i class=\"icon icon-mobile icon-share\"></i><span class=\"text\">Share ›</span></a>\n\n <ul>\n <li class=\"twitter\">\n <a data-action=\"share:twitter\" href=\"#\">Twitter</a>\n </li>\n\n <li class=\"facebook\">\n <a data-action=\"share:facebook\" href=\"#\">Facebook</a>\n </li>\n\n <li class=\"link\">\n <a href=\"http://www.destructoid.com/police-officer-killed-during-gamestop-robbery-288794.phtml#comment-1896607633\">Link</a>\n </li>\n </ul>\n </li>\n\n <li class=\"realtime\" data-role=\"realtime-notification:1896607633\">\n <span class=\"realtime-replies\" style=\"display:none;\"></span> <a class=\"btn btn-small\" href=\"#\" style=\"display:none;\"></a>\n </li>\n </ul>\n </footer>\n </div>\n\n <div data-role=\"blacklist-form\"></div>\n\n <div class=\"reply-form-container\" data-role=\"reply-form\"></div>\n </div>\n\n <ul class=\"children\" data-role=\"children\"></ul>\n </li>\n </ul>\n </li>\n </ul>\n\n <div class=\"load-more\" data-role=\"more\" style=\"\">\n <a class=\"btn\" data-action=\"more-posts\" href=\"#\">Load more comments</a>\n </div>\n</div>\n''', 'lxml')\n" }, { "alpha_fraction": 0.42561104893684387, "alphanum_fraction": 0.4544810354709625, "avg_line_length": 30.372222900390625, "blob_id": "f72e0c75bc80e043093ef352aa94b054948c4d4b", "content_id": "763dc34da2a53fc1c1e7363d6176650b9143195a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5646, "license_type": "no_license", "max_line_length": 140, "num_lines": 180, "path": "/pytaghash/tests/test_taghash.py", "repo_name": "jamesmeneghello/pytaghash", "src_encoding": "UTF-8", "text": "import pytaghash.taghash\npytaghash.taghash.patch()\n\nfrom .fixtures.tags import *\nfrom .fixtures import abc_drum\n\n\nclass TestTagHash:\n def test_hash(self):\n hash = complex1.hash(depth=1)\n assert hash == {\n 'li.00': [\n {'div.00': []},\n {'p.00': []},\n {'dl.00': []},\n {'p.00': []}\n ]\n }\n\n hash = complex1.hash(depth=2)\n assert hash == {\n 'li.00': [\n {'div.00': []},\n {'p.00': []},\n {'dl.00': [\n {'dd.00': []},\n {'dt.00': []},\n ]},\n {'p.00': [\n {'br.00': []}\n ]}\n ]\n }\n\n hash = complex3.hash(depth=3)\n assert hash == {\n 'li.00': [\n {'div.01': [\n {'p.00': [\n {'br.00': []},\n {'br.00': []}\n ]}\n ]},\n {'div.00': []},\n {'p.00': []},\n {'a.00': [\n {'img.00': []},\n {'p.00': []}\n ]},\n {'div.00': []},\n {'a.00': []}\n ]\n }\n\n def test_compare_hash(self):\n # simple\n assert complex1.hash_compare(complex2, depth=1)\n # assert not complex1.hash_compare(complex4, depth=2)\n assert not complex1.hash_compare(complex3, depth=1)\n\n # compare with attributes\n # not much difference\n assert complex1.hash_compare(complex1_attrib, depth=1)\n\n # lots of difference\n assert not complex1.hash_compare(complex1_attrib_diff, depth=2)\n\n # deeper\n assert complex1.hash_compare(complex2, depth=2)\n assert not complex1.hash_compare(complex3, depth=2)\n\n def test_compare_hash_abc(self):\n ts1 = bs4.BeautifulSoup(abc_drum.short_comment_list, 'lxml').ul.li\n ts2 = bs4.BeautifulSoup(abc_drum.short_comment_list, 'lxml').ul.li.ul.li.ul.li\n\n assert not ts1.hash_compare(ts2, depth=2)\n\n def test_is_list(self):\n tag = nested_comments_abc\n assert not tag.li.is_list()\n assert tag.ul.li.ul.is_list()\n\n def test_is_list_kotaku(self):\n count = 0\n for tag in nested_comments_kotaku.div.find_all(True):\n if tag.is_list(depth=2, minimum_tags=3):\n count += 1\n assert count == 7\n\n def test_is_list_disqus(self):\n count = 0\n for tag in nested_comments_disqus.div.find_all(True):\n if tag.is_list(depth=2, minimum_tags=3):\n count += 1\n assert count == 60\n\n def test_structure_xpath(self):\n xpath = complex1.structure_xpath(depth=1)\n assert xpath == '// li [ count(div)=1 and count(dl)=1 and count(p)=2 ]'\n assert len(complex1.lxml.xpath(xpath)) == 1\n\n xpath = complex1.structure_xpath(depth=2)\n assert xpath == '// li [ count(div)=1 and count(dl)=1 and count(p)=2 and dl [ count(dd)=1 and count(dt)=1 ] and p [ count(br)=1 ] ]'\n assert len(complex1.lxml.xpath(xpath)) == 1\n\n tag = bs4.BeautifulSoup(abc_drum.short_comment_list, 'lxml').ul\n xpath = tag.structure_xpath(depth=1)\n assert xpath == '// ul [ count(li)=2 ]'\n assert len(tag.lxml.xpath(xpath)) == 2\n\n xpath = tag.structure_xpath(depth=2)\n assert xpath == '// ul [ count(li)=2 and li [ count(a)=1 and count(h3)=1 and count(p)=3 ] ]'\n assert len(tag.lxml.xpath(xpath)) == 2\n\n xpath = tag.structure_xpath(depth=3)\n assert xpath == '// ul [ count(li)=2 and li [ count(a)=1 and count(h3)=1 and count(p)=3 and p [ count(span)=2 ] ] ]'\n assert len(tag.lxml.xpath(xpath)) == 2\n\n xpath = '// li [ count(a)=1 and count(h3)=1 and count(p)=3 ]'\n assert len(tag.lxml.xpath(xpath)) == 4\n\n def test_identifying_xpath(self):\n ts = bs4.BeautifulSoup('''\n <html>\n <head>\n </head>\n <body>\n <ul class='comments-paginate page'>\n <li>1</li>\n <li>2</li>\n <li>3</li>\n <li>4</li>\n </ul>\n <ul id='comments'>\n <li>some shit</li>\n <li>\n <ul>\n <li> some more shit</li>\n </ul>\n </li>\n <li>butts</li>\n </ul>\n </body>\n </html>\n ''', 'lxml')\n\n xpath = ts.find_all('ul')[1].find_all('li')[3].identifying_xpath()\n assert xpath == '//ul[@id=\"comments\"]/li[3]'\n assert len(ts.lxml.xpath(xpath)) == 1\n xpath = ts.find_all('ul')[0].find_all('li')[1].identifying_xpath()\n assert xpath == '//ul[contains(@class, \"comments-paginate\") and contains(@class, \"page\")]/li[2]'\n assert len(ts.lxml.xpath(xpath)) == 1\n\n def test_count(self):\n assert complex1.count(depth=1) == 4\n assert complex1.count(depth=2) == 7\n\n def test_relative_xpath(self):\n tag = complex1.find('dt')\n xpath = tag.relative_xpath(complex1)\n\n assert xpath == 'dl[1]/dt[1]'\n assert len(complex1.lxml.xpath(xpath)) == 1\n\n def test_level(self):\n tag = bs4.BeautifulSoup('''\n <html>\n <body>\n <table>\n <tr>\n <td>\n <p></p>\n </td>\n </tr>\n </table>\n </body>\n </html>\n ''', 'lxml')\n\n assert tag.p.level == 6" }, { "alpha_fraction": 0.8715596199035645, "alphanum_fraction": 0.8807339668273926, "avg_line_length": 9.899999618530273, "blob_id": "6ffb458063defc21863b2a7093ca0bbe79ffc4a8", "content_id": "ba4e722ad75cccdb3abd55eee8dd58bfb32d64f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 109, "license_type": "no_license", "max_line_length": 20, "num_lines": 10, "path": "/requirements.txt", "repo_name": "jamesmeneghello/pytaghash", "src_encoding": "UTF-8", "text": "lxml\nbeautifulsoup4\ndatadiff\nregex\ncodecov\nbackports.statistics\nsix\nbackport_collections\ncoverage\npytest-cov\n" }, { "alpha_fraction": 0.534379780292511, "alphanum_fraction": 0.542036771774292, "avg_line_length": 32.92207717895508, "blob_id": "a0358b0fff123a9fca9a727816a6a6032c4e20aa", "content_id": "c532af61b3b7615877772c75be00af51832824aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13060, "license_type": "no_license", "max_line_length": 111, "num_lines": 385, "path": "/pytaghash/taghash.py", "repo_name": "jamesmeneghello/pytaghash", "src_encoding": "UTF-8", "text": "from __future__ import division\n\ntry:\n from collections import Counter\nexcept ImportError:\n from backport_collections import Counter\n\nimport json\n\ntry:\n import statistics\nexcept ImportError:\n import backports.statistics as statistics\n\nimport bs4\nimport datadiff\nimport lxml.html\nimport regex\nimport six\n\n\nINNER_TEXT_TAGS = ['b', 'i', 'u', 'strong', 'br', 'p', 'code', 'big', 'small']\nLIST_TAGS = ['ul', 'ol', 'table']\n\nFEATURE_REGEX = regex.compile('([\\'\"]\\w+\\.\\d{2}[\\'\"])')\nDIFF_REGEX = regex.compile('[+-].*([\\'\"]\\w+\\.\\d{2}[\\'\"])', regex.M)\n\nTREE_SIMILARITY_THRESHOLD = 0.8\nLIST_SENSITIVITY_THRESHOLD = 0.80\n\n\nclass TagHash(bs4.Tag):\n \"\"\"\n Holder class for monkey-patching functions.\n \"\"\"\n\n def _hash(self, depth):\n # cache the hash depth and string\n if not self._hash_depth or self._hash_depth != depth:\n self._hash_dict = self._tag_hash(depth)\n self._hash_string = json.dumps(self._hash_dict)\n self._hash_depth = depth\n return self._hash_dict\n\n def _tag_hash(self, depth, level=0):\n if self.children and not level == depth and self.name not in LIST_TAGS:\n children = [tag._tag_hash(depth, level + 1) for tag in self.children or [] if type(tag) == bs4.Tag]\n else:\n children = []\n return {self._feature_hash(): children}\n\n def _feature_hash(self):\n \"\"\"\n Create a feature hash for this tag (not children).\n\n :param tag: BS4 Tag\n :return: string: name.00\n \"\"\"\n return '{0}.{1}'.format(self.name, ''.join(['1' if x else '0' for x in (\n self.get('id'), self.get('name')\n )]))\n\n def _tag_hash_compare(self, tag, depth):\n return TagHash._hash_compare(self.hash(depth), tag.hash(depth))\n\n @staticmethod\n def _hash_compare(hash1, hash2):\n # quickly: if the top-level tag doesn't match, ditch it\n if list(hash1.keys())[0] != list(hash2.keys())[0]:\n return False\n\n # otherwise, diff it and find differences\n diff = datadiff.diff(hash1, hash2)\n hash1_string = json.dumps(hash1)\n hash2_string = json.dumps(hash2)\n\n total = len(FEATURE_REGEX.findall(hash1_string)) + len(FEATURE_REGEX.findall(hash2_string))\n\n score = 0\n for line in str(diff).splitlines():\n if line.lstrip().startswith(('+', '-')):\n if line.lstrip().startswith(('+++', '---')):\n # it's a diff header line, skip\n continue\n elif '{' in line and '}' in line:\n # not a modification\n # penalise by 2 (parent + children as a group)\n # and reduce the total by (len)\n count = len(FEATURE_REGEX.findall(line))\n score += 2\n total -= count\n else:\n # modification, only half a point since it does it twice\n score += 0.5 * len(FEATURE_REGEX.findall(line))\n\n res = 1 - score / total\n return res >= TREE_SIMILARITY_THRESHOLD\n\n def _recursive_structure_xpath(self, depth, level=0):\n if self.children and not level == depth:\n children = Counter([\n tag.name for tag in self.children if\n type(tag) == bs4.Tag and tag.name not in LIST_TAGS\n ])\n parts = []\n parts.append('{0}'.format(' and '.join(\n ['count({0})={1}'.format(tag_name, number) for tag_name, number in sorted(children.items())]\n )))\n recurse_children = [tag._recursive_structure_xpath(depth, level + 1) for tag in self.children if\n type(tag) == bs4.Tag and tag.name not in LIST_TAGS]\n parts.append(' and '.join(\n [child for child in recurse_children if child]\n ))\n children_xpath = ' and '.join([part for part in parts if part])\n if children_xpath:\n children_xpath = '[ {0} ]'.format(children_xpath)\n else:\n children_xpath = ''\n\n if children_xpath:\n return '{0} {1}'.format(self.name, children_xpath)\n else:\n return ''\n\n def _structure_xpath(self, depth=None):\n depth = depth or self._hash_depth\n if not self._xpath_depth or self._xpath_depth != depth:\n self._xpath = '// ' + self._recursive_structure_xpath(depth)\n self._xpath_depth = depth\n return self._xpath\n\n def _tag_sibling_position(self):\n if not self.parent:\n return None\n\n type_siblings = [\n sibling for sibling in self.parent.children\n if type(sibling) == bs4.Tag and sibling.name == self.name\n ]\n if len(type_siblings) > 1:\n index = 0\n for i, sibling in enumerate(type_siblings):\n if sibling == self:\n index = i\n break\n return '{0}[{1}]'.format(self.name, index + 1)\n else:\n return '{0}[1]'.format(self.name)\n\n def _identifying_xpath(self):\n tag = self\n path_components = []\n while True:\n if tag.get('id'):\n path = '{0}[@id=\"{1}\"]'.format(tag.name, tag.get('id'))\n path_components.append(path)\n break\n elif tag.get('class'):\n class_paths = []\n for cls in tag.get('class'):\n class_paths.append('contains(@class, \"{0}\")'.format(cls))\n path = '{0}[{1}]'.format(tag.name, ' and '.join(class_paths))\n path_components.append(path)\n break\n else:\n if tag.parent:\n path_components.append(tag._tag_sibling_position())\n tag = tag.parent\n else:\n path_components.append('{0}'.format(tag.name))\n break\n\n xpath = '//' + '/'.join(reversed(path_components))\n return xpath\n\n def _relative_xpath(self, target):\n tag = self\n path_components = []\n while True:\n if tag == target:\n break\n else:\n if tag.parent:\n path_components.append(tag._tag_sibling_position())\n tag = tag.parent\n else:\n path_components.append('{0}'.format(tag.name))\n break\n\n xpath = '/'.join(reversed(path_components))\n return xpath\n\n def _count(self, depth):\n return self._recursive_count(depth=depth) - 1\n\n def _recursive_count(self, depth, level=0):\n if depth == level:\n return 1\n\n count = 1\n if self.children:\n for child in self.children:\n if type(child) == bs4.Tag and child.name not in LIST_TAGS:\n count += child._recursive_count(depth, level + 1)\n\n return count or 1\n\n def _iterate(self, depth=None, dfs=True, skip_first=False, nested=True):\n return TagHash._tag_iterate(self, depth=depth, dfs=dfs, skip_first=skip_first, nested=nested)\n\n def _is_list(self, depth=None, minimum_tags=None):\n return TagHash._tag_is_list(self, depth=depth)\n\n @staticmethod\n def _tag_is_list(tag, depth=None):\n children = tag.find_all(True, recursive=False)\n if children:\n # if there's only one child, it's a lot tricker\n # check if it has an identical parent somewhere\n has_identical_parent = [1 if child.has_identical_parent(depth=depth) else 0 for child in children]\n perc = statistics.mean(has_identical_parent)\n if perc >= LIST_SENSITIVITY_THRESHOLD:\n return True\n else:\n return False\n else:\n # there wasn't any children ._.\n return False\n\n def _has_identical_parent(self, depth=None):\n return TagHash._tag_has_identical_parent(self, depth=depth)\n\n @staticmethod\n def _tag_has_identical_parent(tag, depth=None):\n node = tag\n while True:\n if node.name == tag.name and node is not tag:\n # compare hashes\n if tag.hash_compare(node, depth=depth):\n # found an identical parent!\n return True\n\n if node.parent:\n node = node.parent\n else:\n return False\n\n @property\n def _level(self):\n \"\"\"\n Returns the depth of the tag from the top-level parent.\n\n :return: int\n \"\"\"\n return TagHash._tag_level(self)\n\n @property\n def _inner_text(self):\n \"\"\"\n Get text inside tag, but not inside children.\n\n :param tag:\n :return: string: text\n \"\"\"\n text = ''\n\n for element in self.children:\n if type(element) == bs4.NavigableString:\n if element.strip():\n text += ' ' + element\n elif element.name in INNER_TEXT_TAGS:\n if element.string:\n string = element.string.strip()\n if string:\n text += ' ' + string\n\n # convert it to a str so we're not leaving a reference\n return str(text.strip())\n\n @property\n def _lxml(self):\n return lxml.html.fromstring(str(self))\n\n @classmethod\n def _tag_iterate(cls, tag, depth=None, dfs=True, skip_first=False, nested=True):\n \"\"\"\n Iterate depth-first through children of tag to depth.\n\n :param tag: Tag to start at\n :param depth: Maximum depth to iterate to\n :param dfs: boolean: depth-first or breadth-first\n :param skipfirst: boolean: skip first element\n :return: bs4.Tag: next node in dfs pre-order\n \"\"\"\n # add a level to the tag so we can track depth\n tag._hash_level = 0\n\n # and start off the tree stack with this node\n stack = [tag]\n nodes = []\n\n # if there's no elements left in the stack, don't continue\n while stack:\n if dfs:\n # get the last element, so we're depth-first\n node = stack.pop()\n else:\n # otherwise get the first, which is breadth-first\n node = stack.pop(0)\n\n # check the node level\n if depth:\n if node._hash_level >= depth:\n # if we're already deep enough, skip this node\n continue\n\n if not skip_first or node != tag:\n if not nested:\n if node.is_list(depth=tag._hash_depth):\n continue\n # nodes.append(node)\n yield node\n\n # from this node, find all tags (not strings) that are immediate children\n children = node.find_all(True, recursive=False)\n for child in children:\n child._hash_level = node._hash_level + 1\n\n # in order to go top-down, dfs wants the stack extended in reverse\n if dfs:\n stack.extend(reversed(children))\n else:\n # bfs doesn't, though.\n stack.extend(children)\n\n @staticmethod\n def _tag_level(tag):\n level = 0\n while True:\n if not tag.parent:\n break\n level += 1\n tag = tag.parent\n\n return level\n\n\ndef list_difference(a, b):\n count = Counter(a) # count items in a\n count.subtract(b) # subtract items that are in b\n diff = []\n for x in a:\n if count[x] > 0:\n count[x] -= 1\n diff.append(x)\n return diff\n\n\ndef patch():\n \"\"\"\n Patch `bs4.Tag` to include new functionality.\n\n :return:\n \"\"\"\n bs4.Tag._feature_hash = six.get_unbound_function(TagHash._feature_hash)\n bs4.Tag._tag_hash = six.get_unbound_function(TagHash._tag_hash)\n bs4.Tag.hash = six.get_unbound_function(TagHash._hash)\n bs4.Tag.hash_compare = six.get_unbound_function(TagHash._tag_hash_compare)\n\n bs4.Tag._recursive_structure_xpath = six.get_unbound_function(TagHash._recursive_structure_xpath)\n bs4.Tag.structure_xpath = six.get_unbound_function(TagHash._structure_xpath)\n\n bs4.Tag._tag_sibling_position = six.get_unbound_function(TagHash._tag_sibling_position)\n bs4.Tag.identifying_xpath = six.get_unbound_function(TagHash._identifying_xpath)\n bs4.Tag.relative_xpath = six.get_unbound_function(TagHash._relative_xpath)\n\n bs4.Tag._recursive_count = six.get_unbound_function(TagHash._recursive_count)\n bs4.Tag.count = six.get_unbound_function(TagHash._count)\n\n bs4.Tag.lxml = TagHash._lxml\n bs4.Tag.iterate = six.get_unbound_function(TagHash._iterate)\n bs4.Tag.inner_text = TagHash._inner_text\n bs4.Tag.level = TagHash._level\n bs4.Tag.is_list = six.get_unbound_function(TagHash._is_list)\n bs4.Tag.has_identical_parent = six.get_unbound_function(TagHash._has_identical_parent)\n" }, { "alpha_fraction": 0.6257961988449097, "alphanum_fraction": 0.6385350227355957, "avg_line_length": 25.16666603088379, "blob_id": "83072520cfa0cf5d0c591f0b7cb0770d6ff6c43f", "content_id": "271b8331a1de84733d8638d3c07b144753986172", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 628, "license_type": "no_license", "max_line_length": 118, "num_lines": 24, "path": "/setup.py", "repo_name": "jamesmeneghello/pytaghash", "src_encoding": "UTF-8", "text": "import setuptools\n\nsetuptools.setup(\n name=\"pytaghash\",\n version=\"0.1.0\",\n url=\"https://github.com/Murodese/pytaghash\",\n\n author=\"James Meneghello\",\n author_email=\"[email protected]\",\n\n description=\" An extension of BeautifulSoup 4 Tags to provide additional XPath and feature hashing capabilities.\",\n long_description=open('README.rst').read(),\n\n packages=setuptools.find_packages(),\n\n install_requires=[],\n\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n ],\n)\n" } ]
7
MartaLinux/learningPython
https://github.com/MartaLinux/learningPython
2e15d0d1e745be881318b9ca19b6d32245b6c04b
ef73d5d4dce2e197b68bfc11d89d97d48688ce40
8c828fd9840654c4e79b98a4c01a2a49dce8d3e9
refs/heads/main
2023-04-07T03:00:08.184502
2021-04-07T18:54:51
2021-04-07T18:54:51
333,577,546
0
0
null
2021-01-27T22:28:11
2021-01-29T22:19:46
2021-01-31T16:58:52
Python
[ { "alpha_fraction": 0.502439022064209, "alphanum_fraction": 0.5170731544494629, "avg_line_length": 19.600000381469727, "blob_id": "b28f920950d2325ed2cacede1c912a25bbf56852", "content_id": "11138d86c2609eece292525bdd2447cc7f45f8c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 205, "license_type": "no_license", "max_line_length": 47, "num_lines": 10, "path": "/main.py", "repo_name": "MartaLinux/learningPython", "src_encoding": "UTF-8", "text": "cube = lambda x: x * x * x\nn = int(input(\"Input n:\"))\nmas = []\nfor i in range(n):\n if i <= 1:\n mas.append(i)\n else:\n mas.append(int(mas[i-1])+int(mas[i-2]))\n\nprint(list(map(cube, mas)))" }, { "alpha_fraction": 0.6598360538482666, "alphanum_fraction": 0.6659836173057556, "avg_line_length": 26.16666603088379, "blob_id": "bb9296b6e0f2c859ec3963afb5ef3f06c95756c0", "content_id": "c0649d7ddaadff3d2c5d64cb5caef20a4ceb2568", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 488, "license_type": "no_license", "max_line_length": 69, "num_lines": 18, "path": "/taskone.py", "repo_name": "MartaLinux/learningPython", "src_encoding": "UTF-8", "text": "#https://www.hackerrank.com/challenges/collections-counter/problem\n# Enter your code here. Read input from STDIN. Print output to STDOUT\n\nimport collections\nfrom collections import Counter\nX = int(input()) # --\nmy_list = collections.Counter(map(int, input().split()))\n#print(Counter(my_list))\nn = int(input())\ncounter = 0\ni = 0\nfor i in range(n):\n size, price = map(int, input().split(' '))\n if my_list[size]:\n counter += price\n my_list[size] -= 1\n\nprint(counter)" }, { "alpha_fraction": 0.6051948070526123, "alphanum_fraction": 0.6129870414733887, "avg_line_length": 24.399999618530273, "blob_id": "1b1677d6daf7311e5572b6b09fe588d0f5ea17dd", "content_id": "5b2806a880ada9048d989bbe96609ebaaa53ebaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 385, "license_type": "no_license", "max_line_length": 56, "num_lines": 15, "path": "/program.py", "repo_name": "MartaLinux/learningPython", "src_encoding": "UTF-8", "text": "import collections\nfrom collections import Counter\nX = int(input(\"kol obuvi v magaze: \")) # --\nmy_list = collections.Counter(map(int, input().split()))\nprint(Counter(my_list))\nn = int(input('Klient:'))\ncounter = 0\ni = 0\nfor i in range(n):\n size, price = map(int, input().split(' '))\n if my_list[size]:\n counter += price\n my_list[size] -= 1\n\nprint(counter)\n\n\n\n\n" } ]
3
BYU-ACM/warm-up-day-2-gsmithh
https://github.com/BYU-ACM/warm-up-day-2-gsmithh
a17de641509b8e8058590bcb965e915da8200d06
30295933a9a96864a9a7d068e41530d9604b5ffa
514136cffd60b33cc698b2796c35e1a53d58fdce
refs/heads/master
2021-01-11T21:24:21.899975
2017-01-19T18:59:29
2017-01-19T18:59:29
78,778,136
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5785609483718872, "alphanum_fraction": 0.6798825263977051, "avg_line_length": 34.842105865478516, "blob_id": "6252901ed859054a552737cde458b3f65fe780fb", "content_id": "54883ca465b8bbbd8445a82892ed12c26634061d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 681, "license_type": "no_license", "max_line_length": 49, "num_lines": 19, "path": "/test_public_Binary_Search_sol.py", "repo_name": "BYU-ACM/warm-up-day-2-gsmithh", "src_encoding": "UTF-8", "text": "import pytest\nfrom sol import Binary_Search\n\ndef test_returns_correct_for_arange_list():\n assert Binary_Search(range(0,100), 99) == 99\n assert Binary_Search(range(0,100), 50) == 50\n assert Binary_Search(range(0,100), 34) == 34\n assert Binary_Search(range(0,100), 14) == 14\n assert Binary_Search(range(0,100), 49) == 49\n\ndef test_returns_correctly_for_sqaure_list():\n my_list = [x**2 for x in range(100)]\n assert Binary_Search(my_list, 64**2) == 64\n assert Binary_Search(my_list, 8**2) == 8\n assert Binary_Search(my_list, 34**2) == 34\n assert Binary_Search(my_list, 77**2) == 77\n\ndef test_returns_none_when_not_in_list():\n assert Binary_Search(range(0,100), 100) == None\n" }, { "alpha_fraction": 0.6430615186691284, "alphanum_fraction": 0.6487839818000793, "avg_line_length": 52.69230651855469, "blob_id": "01e0f61fb63b405047dfed763a594d738a540e37", "content_id": "89165487320cc87b9143911808b2303b7286419d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1398, "license_type": "no_license", "max_line_length": 118, "num_lines": 26, "path": "/sol.py", "repo_name": "BYU-ACM/warm-up-day-2-gsmithh", "src_encoding": "UTF-8", "text": "def Binary_Search(arr, to_find):\n \"\"\"A direct implementation of Newton's Method\n (For sanity assume that func and func_prime define there own division correctly,\n that is, don't cast anything to a float)\n params: arr (a list ordered from least to greatest)\n to_find (the item to find in arr)\n returns: index (int), x, s.t. arr[x] == to_find\n None(none-type) if for all x, arr[x] != to_find\n \"\"\"\n for i in range(len(arr)):\n if to_find == arr[i]:\n return i\n\ndef Bisection(func, left_side, right_side, tol=1e-5):\n \"\"\"A direct implementation of Newton's Method\n (For sanity assume that func and func_prime define there own division correctly,\n that is, don't cast anything to a float)\n params: func (a function)\n left_side (a value for the function to take on, it should have opposite sign from `right_side`)\n right_side (a value for the function to take on, it should have opposite sign from `left_side`)\n tol (a value for which the function should return once a value at least that distance from zero is found)\n returns: root (float), x, s.t. abs(func(x))<tol\n None(none-type) if func(left_side), func(right_side) < 0 or func(left_side), func(right_side) > 0\n \"\"\"\n if func(left_side) >0 and func(right_side) >0 or func(left_side) <0 and func(right_side) <0:\n return None\n\n\n" }, { "alpha_fraction": 0.706198513507843, "alphanum_fraction": 0.7087065577507019, "avg_line_length": 52.67307662963867, "blob_id": "aa60a09d19e7c44b1104431838b3bd11c88a74ea", "content_id": "bebbeb6bbf003cf44cde35e16d8d80ca42ed5875", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2791, "license_type": "no_license", "max_line_length": 228, "num_lines": 52, "path": "/README.md", "repo_name": "BYU-ACM/warm-up-day-2-gsmithh", "src_encoding": "UTF-8", "text": "# ACM Warm Up Day Two\n## What is a Warm up?\nWe will use warm ups in this class to review algorithm(s) that should already be familiar to us. Depending on the day Warm ups can take anywhere from 5 to 30 minutes and may include one to many different algorithms to implement.\nEach day if anything important needs to be conveyed (specifically about the warm up) that information can be found in this file (README.md) and will likely be discussed in class as well.\n\n## Rule's of the Warm up\n**Warm up's are closed notes, closed friend, and closed internet (unless a link is provided for you)**\n\n**You may not use awesome packages (like Numpy or Scipy) in Warmups. (Use math: eg. \"import math as m\")**\n\n**Please at very least attempt the warm-ups. They will be the medium for feedback in this Class**\n\n## Public Test Cases\nSometimes a \"public\\_test\\_[Method\\_Name].py\" is provided for you. You can run all of these tests by running the following in the terminal: `pytest`\n\nNote: You don't need to specify which file to test, py.test will find all the files that match the following regular expression: \"^test.\\*\\.py$\" (start with test and end with .py).\n\nFor more information on how py.test go to: http://doc.pytest.org/en/latest/\n\n#Binary Search\nIn the file: \"sol.py\" You will find the following function:\n```python\ndef Binary_Search(arr, to_find):\n \"\"\"A direct implementation of Newton's Method\n (For sanity assume that func and func_prime define there own division correctly,\n that is, don't cast anything to a float)\n params: arr (a list ordered from least to greatest)\n to_find (the item to find in arr)\n returns: index (int), x, s.t. arr[x] == to_find\n None(none-type) if for all x, arr[x] != to_find\n \"\"\"\n pass\n```\nYour job is to simply fill in \"pass\" with the appropriate iterative solution.\n\n#Binary Root Finder\nIn the file: \"sol.py\" You will find the following function:\n```python\ndef Bisection(func, left_side, right_side, tol=1e-5):\n \"\"\"A direct implementation of Newton's Method\n (For sanity assume that func and func_prime define there own division correctly,\n that is, don't cast anything to a float)\n params: func (a function)\n left_side (a value for the function to take on, it should have opposite sign from `right_side`)\n right_side (a value for the function to take on, it should have opposite sign from `left_side`)\n tol (a value for which the function should return once a value at least that distance from zero is found)\n returns: root (float), x, s.t. abs(func(x))<tol\n None(none-type) if func(left_side), func(right_side) < 0 or func(left_side), func(right_side) > 0\n \"\"\"\n pass\n```\nYour job is to simply fill in \"pass\" with the appropriate iterative solution.\n" }, { "alpha_fraction": 0.6233766078948975, "alphanum_fraction": 0.673160195350647, "avg_line_length": 27.875, "blob_id": "f8a2ca95df445c6be722a116599a10d0cb51b7bf", "content_id": "6c02f3ac5aa3b1f2f42e8ce3da296424dc1986f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 462, "license_type": "no_license", "max_line_length": 106, "num_lines": 16, "path": "/test_public_Bisection_sol.py", "repo_name": "BYU-ACM/warm-up-day-2-gsmithh", "src_encoding": "UTF-8", "text": "import pytest\nfrom sol import Bisection\n\ndef approx_equal(val1, val2):\n if not(isinstance(val1, (int, long, float, complex)) and isinstance(val2, (int, long, float, complex))):\n return val1==val2\n else:\n return abs(val1 - val2) < 1e-5\n\ndef test_linear_function():\n func = lambda x: 5*x - 3\n assert approx_equal(Bisection(func, 0, 2), 3/5.)\n\ndef test_quadratic_function():\n func = lambda x: 3*x**2-5*x-2\n assert approx_equal(Bisection(func, 1, 4), 2)\n" } ]
4
pombredanne/django-restlayer
https://github.com/pombredanne/django-restlayer
0e4e60655a1c171a7e0e73931946cda0fdb6b3ea
4b27e4b2d6ca827cab4e4d52caccb5d3f861348f
1d717fc0a29211f65576ecf1bae90ecdb879037c
refs/heads/master
2017-12-03T13:48:02.285191
2011-08-28T12:37:05
2011-08-28T12:37:05
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6253041625022888, "alphanum_fraction": 0.628953754901886, "avg_line_length": 28.35714340209961, "blob_id": "6031570a2fd5b8376186519e36c107053fbcc0bf", "content_id": "1954624faa70328f7776f80feb4a9b62d6233f36", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 822, "license_type": "permissive", "max_line_length": 84, "num_lines": 28, "path": "/setup.py", "repo_name": "pombredanne/django-restlayer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# This file is part of Django restlayer released under the MIT license.\n# See the LICENSE for more information.\n\nfrom setuptools import setup, find_packages\n\nversion = '0.5'\npackages = ['restlayer'] + ['restlayer.%s' % x for x in find_packages('restlayer',)]\n\nsetup(\n name='restlayer',\n version=version,\n description='HTTP Toolkit',\n author='Olivier Meunier',\n author_email='[email protected]',\n url='https://github.com/olivier-m/django-restlayer',\n packages=packages,\n classifiers=[\n 'Development Status :: %s' % version,\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: Utilities'\n ],\n)\n" }, { "alpha_fraction": 0.7487437129020691, "alphanum_fraction": 0.7537688612937927, "avg_line_length": 32.33333206176758, "blob_id": "74d852a2d3c38ba6255e354e1a250e3904bedf9f", "content_id": "94796276bbc8e47c8d7f73a706fb06065ce2384b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 199, "license_type": "permissive", "max_line_length": 71, "num_lines": 6, "path": "/restlayer/__init__.py", "repo_name": "pombredanne/django-restlayer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# This file is part of Django restlayer released under the MIT license.\n# See the LICENSE for more information.\n\nfrom restlayer.base import Response, ModelResponse, Resource" }, { "alpha_fraction": 0.5609237551689148, "alphanum_fraction": 0.5682913064956665, "avg_line_length": 33.23786544799805, "blob_id": "fbcb0b3260705b6185132422af27a9138af60c68", "content_id": "3bf0578bbcc6f5bc071fbcfed8dcc5807e7e42f4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7058, "license_type": "permissive", "max_line_length": 147, "num_lines": 206, "path": "/restlayer/base.py", "repo_name": "pombredanne/django-restlayer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# This file is part of Django restlayer released under the MIT license.\n# See the LICENSE for more information.\n\nimport json\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\nimport sys\nimport traceback\n\nimport mimeparse\n\nfrom django.conf import settings\nfrom django.core.mail import mail_admins\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.http import HttpResponse, HttpResponseNotAllowed, Http404\n\nfrom restlayer.exc import HttpException, Http406\nfrom restlayer.utils import ModelDataLoader, get_request_data, xml_dumps\n\nclass BaseResponse(type):\n def __new__(cls, names, bases, attrs):\n new_class = super(BaseResponse, cls).__new__(cls, names, bases, attrs)\n \n new_class.methods = []\n \n # Prepare HEAD response based on GET when possible.\n if not hasattr(new_class, 'response_head') and hasattr(new_class, 'response_get'):\n new_class.response_head = new_class._response_head\n \n for meth in dir(new_class):\n if meth.startswith('response_') and callable(getattr(new_class, meth)):\n new_class.methods.append(meth[9:])\n \n return new_class\n \n\nclass Response(HttpResponse):\n __metaclass__ = BaseResponse\n \n serializers = (\n ('application/json', lambda x: json.dumps(x, indent=1, cls=DjangoJSONEncoder)),\n ('application/xml', xml_dumps),\n ('application/python-pickle', pickle.dumps)\n )\n \n deserializers = (\n ('application/x-www-form-urlencoded', get_request_data),\n ('application/json', lambda req: json.loads(req.raw_post_data or \"{}\")),\n )\n \n def __init__(self, *args, **kwargs):\n super(Response, self).__init__(*args, **kwargs)\n self.mime = 'application/json'\n self.charset = 'UTF-8'\n \n self.data_loader = lambda x, req, **k: x\n \n def response_options(self, request, *args, **kwargs):\n self['Allow'] = ', '.join([x.upper() for x in self.methods])\n self.status_code = 204\n return self\n \n def _response_head(self, request, *args, **kwargs):\n if not hasattr(self, 'response_get'):\n raise Http406\n \n response = self.response_get(request, *args, **kwargs)\n response.content = ''\n return response\n \n def serialize(self, request, res, **options):\n # Get Python Data\n result = None\n if callable(self.data_loader):\n result = self.data_loader(res, request, **options)\n \n # Formatting result\n renderer = dict(self.serializers).get(self.mime)\n if not renderer:\n raise Http406\n \n self['content-type'] = '%s; charset=%s' % (self.mime, self.charset)\n return renderer(result)\n \n def init_response(self, request):\n accept = request.META.get('HTTP_ACCEPT', None)\n if not accept:\n raise Http406\n \n try:\n self.mime = mimeparse.best_match([x[0] for x in self.serializers], accept)\n if not self.mime:\n raise ValueError\n except ValueError:\n raise Http406\n \n # Reading data\n if request.method in ('POST', 'PUT'):\n content_type = request.META.get('CONTENT_TYPE', '').split(';',1)[0]\n \n deserializers = dict(self.deserializers)\n deserializer = deserializers.get(content_type)\n # We may have a default deserializer\n if not deserializer:\n deserializer = deserializers.get('*/*')\n \n if not deserializer:\n raise Http406\n try:\n request.data = deserializer(request)\n except BaseException, e:\n raise HttpException(str(e), 400)\n \n def make_response(self, request, *args, **kwargs):\n if request.method.lower() not in self.methods:\n return HttpResponseNotAllowed(self.methods)\n \n meth = getattr(self, 'response_%s' % request.method.lower())\n \n try:\n self.init_response(request)\n res = meth(request, *args, **kwargs)\n if isinstance(res, HttpResponse):\n if hasattr(res, 'set_common_headers'):\n res.set_common_headers(request)\n if request.method == 'HEAD':\n res.content = ''\n return res\n self.content = self.serialize(request, res)\n except Http404:\n self.status_code = 404\n self.content = self.serialize(request, \"Resource not found\")\n except Http406, e:\n self.status_code = e.args[1]\n self.content = ''\n self['content-type'] = 'text/plain'\n except HttpException, e:\n self.status_code = e.args[1]\n self.content = self.serialize(request, e.args[0])\n except BaseException, e:\n e.resp_obj = self\n raise\n \n self.set_common_headers(request)\n return self\n \n def get_common_headers(self, request):\n return {}\n \n def set_common_headers(self, request):\n for k, v in self.get_common_headers(request).items():\n if k not in self:\n self[k] = v\n \n\nclass ModelResponse(Response):\n fields = ('id',)\n \n def __init__(self, *args, **kwargs):\n super(ModelResponse, self).__init__(*args, **kwargs)\n self.data_loader = ModelDataLoader(self.fields)\n \n def serialize(self, request, res, **options):\n return super(ModelResponse, self).serialize(request, res, fields=self.fields, resp=self, **options)\n \n\nclass Resource(object):\n csrf_exempt = True\n \n def __init__(self, resp_class):\n self.resp_class = resp_class\n \n def __call__(self, request, *args, **kwargs):\n try:\n return self.resp_class().make_response(request, *args, **kwargs)\n except BaseException, e:\n return self.handle_exception(e, request)\n \n def handle_exception(self, exc, request):\n trace = '\\n'.join(traceback.format_exception(*sys.exc_info()))\n if hasattr(exc, 'resp_obj'):\n resp = exc.resp_obj\n resp.status_code = 500\n resp.content = ''\n resp.set_common_headers(request)\n else:\n resp = HttpResponse('', status=500, content_type='text/plain')\n resp.content = ''\n \n if settings.DEBUG:\n resp.content = trace\n else:\n subject = 'Error (%s IP): %s' % ((request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), request.path)\n try:\n request_repr = repr(request)\n except:\n request_repr = \"Request repr() unavailable\"\n message = \"%s\\n\\n%s\" % (trace, request_repr)\n mail_admins(subject, message, fail_silently=True)\n \n resp['Content-Type'] = 'text/plain'\n return resp\n \n" }, { "alpha_fraction": 0.5573204159736633, "alphanum_fraction": 0.5580110549926758, "avg_line_length": 27.959999084472656, "blob_id": "202def62c2f21e403154f654e12c79ce0cc62b67", "content_id": "94fba50b11f25532167d9f8498fa1041f7a54ce0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2896, "license_type": "permissive", "max_line_length": 71, "num_lines": 100, "path": "/restlayer/utils.py", "repo_name": "pombredanne/django-restlayer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# This file is part of Django restlayer released under the MIT license.\n# See the LICENSE for more information.\n\ntry:\n import cStringIO as StringIO\nexcept ImportError:\n import StringIO\n\nfrom django import db\nfrom django.utils.encoding import smart_unicode\nfrom django.utils.xmlutils import SimplerXMLGenerator\n\nclass ModelDataLoader(object):\n def __init__(self, fields):\n self.fields = fields\n \n def __call__(self, res, request, **options):\n if isinstance(res, db.models.query.QuerySet):\n return [self(x, request, **options) for x in res]\n \n elif isinstance(res, db.models.Model):\n return dict([\n (x, self.get_field_value(res, x, request, **options))\n for x in options.get('fields', ('pk',))\n ])\n \n return res\n \n def get_field_value(self, instance, field, request, **options):\n resp = options.get('resp')\n if resp:\n f = getattr(resp, field, None)\n if callable(f):\n return f(instance, request)\n \n try:\n f = getattr(instance, field)\n if callable(f):\n return f()\n return f\n except AttributeError:\n pass\n \n raise Exception('Field %s not found.' % field)\n \n\ndef get_request_data(request):\n \"\"\"\n Django doesn't particularly understand REST.\n In case we send data over PUT, Django won't\n actually look at the data and load it. We need\n to twist its arm here.\n \n The try/except abominiation here is due to a bug\n in mod_python. This should fix it.\n \"\"\"\n if request.method == \"PUT\":\n try:\n request.method = \"POST\"\n request._load_post_and_files()\n request.method = \"PUT\"\n except AttributeError:\n request.META['REQUEST_METHOD'] = 'POST'\n request._load_post_and_files()\n request.META['REQUEST_METHOD'] = 'PUT'\n \n return request.POST\n elif request.method == \"POST\":\n return request.POST\n \n\ndef xml_dumps(data):\n def to_xml(xml, data):\n if isinstance(data, (list, tuple)):\n for item in data:\n xml.startElement(\"resource\", {})\n to_xml(xml, item)\n xml.endElement(\"resource\")\n elif isinstance(data, dict):\n for key, value in data.iteritems():\n xml.startElement(key, {})\n to_xml(xml, value)\n xml.endElement(key)\n else:\n xml.characters(smart_unicode(data))\n \n stream = StringIO.StringIO()\n \n xml = SimplerXMLGenerator(stream, \"utf-8\")\n xml.startDocument()\n xml.startElement(\"response\", {})\n \n to_xml(xml, data)\n \n xml.endElement(\"response\")\n xml.endDocument()\n \n return stream.getvalue()\n" }, { "alpha_fraction": 0.649754524230957, "alphanum_fraction": 0.67103111743927, "avg_line_length": 27.85714340209961, "blob_id": "bd5d230b1b355069440146c0a0347472271b580f", "content_id": "f1ce7d8527469d5553e00229b6ecddc236856662", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 611, "license_type": "permissive", "max_line_length": 79, "num_lines": 21, "path": "/restlayer/exc.py", "repo_name": "pombredanne/django-restlayer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# This file is part of Django restlayer released under the MIT license.\n# See the LICENSE for more information.\n\nfrom django.http import HttpResponse\n\nclass HttpException(Exception):\n def __init__(self, msg, status=500):\n super(HttpException, self).__init__(msg, status)\n \nclass Http406(HttpException):\n def __init__(self):\n super(HttpException, self).__init__('', 406)\n\nclass FormErrors(dict):\n pass\n\nclass FormValidationError(HttpException):\n def __init__(self, form):\n super(FormValidationError, self).__init__(FormErrors(form.errors), 400)\n \n" } ]
5
IngMachine/LEXER-ricardo-y-fredy-
https://github.com/IngMachine/LEXER-ricardo-y-fredy-
d19c1adda78a39008fddac58c1248199fe0466d1
c6948d815ff9df9f3f791044e8051dfb02ed5243
41b37a8ff30cfb17ef21b455ff20aa2e0deee0e6
refs/heads/master
2021-01-24T11:44:55.298051
2018-02-26T05:25:07
2018-02-26T05:25:07
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5588235259056091, "alphanum_fraction": 0.5588235259056091, "avg_line_length": 20.25, "blob_id": "8d48606fffba15dbbbdc69808f58a0a4168f2cfa", "content_id": "2a5dae28c5b7eab64976cd25671dee17c3643b22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 170, "license_type": "no_license", "max_line_length": 32, "num_lines": 8, "path": "/rfc-lexer-archivo.py", "repo_name": "IngMachine/LEXER-ricardo-y-fredy-", "src_encoding": "UTF-8", "text": "from rfc_lexer import *\n\nif __name__ == '__main__':\n filename = \"lexerr.rfc\", \"r\"\n file = open(filename)\n caracteres = file.read()\n file.close()\n tokens =\n" }, { "alpha_fraction": 0.5966785550117493, "alphanum_fraction": 0.6168445944786072, "avg_line_length": 28.10344886779785, "blob_id": "35675f3fc6252a10673c400a158b07a36fad35bf", "content_id": "a7d041a19c628a450bdf92202aae8e33495537ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 851, "license_type": "no_license", "max_line_length": 114, "num_lines": 29, "path": "/barraespera.py", "repo_name": "IngMachine/LEXER-ricardo-y-fredy-", "src_encoding": "UTF-8", "text": "from time import sleep\n\ndef mostrar_Progreso_Barra (iteracion, total, prefijo = '', sufijo = '', decimal = 1, longitud = 100, fill = 'ᛞ'):\n \n porcentaje = (\"{0:.\" + str(decimal) + \"f}\").format(100 * (iteracion / float(total)))\n filledLength = int(longitud * iteracion // total)\n bar = fill * filledLength + '-' * (longitud - filledLength)\n print'\\r%s โ%sโ %s%% %s' % prefijo, bar, porcentaje, sufijo, end = '\\r\\r\\r'\n # Imprimir nuevo caracter \n\n\n if iteracion == total: \n print()\n\n \n\n\n\n# lista de lineas o caracteres `ᛞ`\ncaracteres = list(range(0, 50))\nl = len(caracteres)\n\n# muestra desde 0%\n\nfor i, caracteres in enumerate(caracteres):\n # Do stuff...\n sleep(0.1)\n # Actualizando el proseco de barra\n mostrar_Progreso_Barra(i + 1, l, prefijo = 'Progreso:', sufijo = 'Completado', longitud = 50)" }, { "alpha_fraction": 0.6004343032836914, "alphanum_fraction": 0.6297502517700195, "avg_line_length": 25.05714225769043, "blob_id": "d66ef8f56d06a42e2e71508c21b2f44bccad6f5a", "content_id": "77ab8c03e466359bbd39f84dc41f39b29e9e9e63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 929, "license_type": "no_license", "max_line_length": 104, "num_lines": 35, "path": "/ClaseBarra.py", "repo_name": "IngMachine/LEXER-ricardo-y-fredy-", "src_encoding": "UTF-8", "text": "class Barra:\n\titeracion=1\n\ttotal=1\n\tprefijo = ''\n\tsufijo = ''\n\tdecimal = 1\n\tlongitud = 100\n\tfill = 'ᛞ'\n\tdef mostrar_Progreso_Barra (self):\n \n \tporcentaje = (\"{0:.\" + str(self.decimal) + \"f}\").format(100 * (self.iteracion / float(self.total)))\n \tfilledLength = int(self.longitud * self.iteracion // self.total)\n \tbar = self.fill * filledLength + '-' * (self.longitud - filledLength)\n \t\n \t# Imprimir nuevo caracter \n \tif self.iteracion == self.total: \n \tprint()\n return '\\r%s โ%sโ %s%% %s' % (self.prefijo, bar, porcentaje, self.sufijo), end = '\\r\\r\\r'\t\n\n\ncaracteres = list(range(0, 50))\nl = len(caracteres) \t\n\nfor i, caracteres in enumerate(caracteres):\n\tbarra1=Barra()\n\tbarra1.iteracion=i+1\n\tbarra1.total=l\n\tbarra1.prefijo='Progreso:'\n\tbarra1.sufijo='Completado'\n\tbarra1.longitud=50\n\tbarra1.decimal=1\n\tfill = 'ᛞ'\n\tsleep(0.1)\n\tbarra1.mostrar_Progreso_Barra()\n # Do stuff...\n \n " } ]
3
MatCyg/SBWprojekt
https://github.com/MatCyg/SBWprojekt
50e90b2ccb3fa5a78f72be7093f094bb070c6fc8
49ea8d7a7f9348d1cd070ed273027a4ae65f14e2
e6efcf6bf97a9a0bcd13bf7155e71ad32a50bda5
HEAD
2018-02-06T20:19:46.395471
2014-04-01T17:31:28
2014-04-01T17:31:28
18,337,042
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.758152186870575, "alphanum_fraction": 0.7635869383811951, "avg_line_length": 29.66666603088379, "blob_id": "c42d6cb335bd14b6787c2d4a61ca319626c6ef57", "content_id": "dae050fc93cd2fd1330417734b08769819a05e9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 385, "license_type": "no_license", "max_line_length": 131, "num_lines": 12, "path": "/README.md", "repo_name": "MatCyg/SBWprojekt", "src_encoding": "UTF-8", "text": "SBWprojekt\n==========\n1\nDane wejściowe będą w jsonie lub csv do wyboru (tak najwygodniej mi zwraca scrapy). \nPola, które ściągam z forum to dla każdego wpisu:\n# autor\n# treść\n# tytuł wątku\n\nczyli tak trochę zdenormalizowane to wyszło.\n\nNiestety, czas z forum lola nie ma sensownego formatu (1 hour ago). Bez logowania nie ma możliwości dostępu do profilu użytkownika.\n" }, { "alpha_fraction": 0.5841983556747437, "alphanum_fraction": 0.5859284996986389, "avg_line_length": 36.69565200805664, "blob_id": "f407baa1194647c344dc4fbfc0d96e67c8efe5c8", "content_id": "18291d9f3c210396502c5a47b2bfa6a1cfdf3de2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1734, "license_type": "no_license", "max_line_length": 102, "num_lines": 46, "path": "/bot/lol/lol/spiders/lolspider.py", "repo_name": "MatCyg/SBWprojekt", "src_encoding": "UTF-8", "text": "from scrapy.contrib.spiders import CrawlSpider, Rule\nfrom scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor\nfrom scrapy.selector import Selector\nfrom lol.items import *\nfrom lxml.html.clean import Cleaner\n\nclass LolSpider(CrawlSpider):\n name = \"lol\"\n allowed_domains = [\"forums.na.leagueoflegends.com\"]\n start_urls = \\\n [\"http://forums.na.leagueoflegends.com/board/forumdisplay.php?s=&f=19\"]\n\n rules = (\n Rule(SgmlLinkExtractor(allow=('showthread\\.php', )), callback='thread'),\n Rule(SgmlLinkExtractor(allow=('forumdisplay\\.php', )), callback='parse_threads'),\n )\n\n def thread(self, response):\n cleaner = Cleaner()\n sel = Selector(response)\n posts = sel.xpath('//div[@class=\"white-stone post-row\"]')\n result = []\n topic = sel.xpath('//h3/text()').extract()\n for p in posts:\n post = Post()\n post['topic'] = ''.join(topic)\n post['author'] = \\\n ''.join(p.xpath('div/div/div/p[@class=\"post-user\"]/text()').extract())\n post['content'] = ''.join(p.xpath('div/div/div/div[@class=\"post-message\"]').extract())\n post['content'] = cleaner.clean_html(post['content'])\n result.append(post)\n print post['topic'], post['author']#, post['content']\n return result\n\n\n def parse_threads(self, response):\n sel = Selector(response)\n threads = sel.xpath('//td[@class=\"title riot\"]')\n result = []\n for t in threads:\n topic = Topic()\n s = t.xpath('a[@class=\"float-left thread-title-link thread-status_new\"]/text()').extract()\n topic['title'] = ''.join(s)\n result.append(topic)\n\n return\n" } ]
2
mheen/mdp
https://github.com/mheen/mdp
a62f955b3e6b6798e989df51e74284456493fbc1
487c7c36a09be84bde16058ea219189ffb149686
db8f92bf85b642246719e652db110222b2b0e2a6
refs/heads/master
2018-10-22T14:35:13.079688
2018-09-19T07:29:19
2018-09-19T07:29:19
84,056,101
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6371030211448669, "alphanum_fraction": 0.645817220211029, "avg_line_length": 53.073299407958984, "blob_id": "8522dba7babe1c7e17bcab619d5bc81b67d7fc68", "content_id": "b49ae79d2b72e630f87a7b75fd894c54a20b88d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10328, "license_type": "no_license", "max_line_length": 129, "num_lines": 191, "path": "/main.py", "repo_name": "mheen/mdp", "src_encoding": "UTF-8", "text": "from drifter.read import Drifters\nfrom imos_hfradar.read import Hfradar\nfrom bom_wind.read import WindMeasurements\nfrom dot_waves.read import WaveMeasurements\nfrom dot_waves.stokes import StokesDrift\nfrom sst.read import Sst\nfrom analysis.events import Event\nfrom analysis.interpolate import interpolate_rectilinear_vfield\nfrom models.velocity_fields import VelocityField,get_combined_swell_sea_stokes\nfrom models.velocity_fields import get_eulerian_wind_field,get_lagrangian_field,get_lagrangian_wind_field\nfrom models.inertial_velocity import get_measured_inertial_velocity,get_undrogued_drifter_constants,get_drogued_drifter_constants\nfrom models.run import run_daily_restart,run_event\nfrom models.parcels import ParticleDensity\nfrom plotting.environmental_conditions import plot_timeseries_to_file,plot_daily_map_to_file,plot_wind_waves_to_file\nfrom plotting.simulation_results import plot_daily_simulated_tracks_to_file\nfrom plotting.drifters import plot_velocity_comparison_to_file\nfrom utilities.timeseries import get_l_time_range,get_same_timeseries,get_rmse,get_mae\nfrom utilities.vectors import get_vector_correlation\nfrom utilities.dirs import PlotDirs\nimport pickle\nimport numpy as np\nimport datetime\n\n# ------------------------------------------------------------------------------\n# PARCELS BROWNIAN MOTION SIMULATIONS\n# ------------------------------------------------------------------------------\ndef plot_particle_density():\n x_range = (-50000,50000)\n y_range = (-50000,50000)\n grid_resolution = 500\n density_c1 = ParticleDensity(x_range,y_range,grid_resolution,'lagrangian_wind_c1')\n density_c2 = ParticleDensity(x_range,y_range,grid_resolution,'lagrangian_wind_c2')\n drifters = Drifters.read_from_netcdf()\n drifters_c1 = drifters.drifter[:5]\n drifters_c2 = drifters.drifter[5:]\n density_c1.plot(drifter=drifters_c1)\n density_c2.plot(drifter=drifters_c2)\n\n# ------------------------------------------------------------------------------\n# VELOCITY COMPARISONS\n# ------------------------------------------------------------------------------\ndef load_velocities():\n total_event = Event.read_from_json('total')\n hfradar = Hfradar.read_time_range_from_netcdfs(total_event.start_time,total_event.end_time)\n swell = StokesDrift.get_swell()\n sea = StokesDrift.get_sea()\n stokes = get_combined_swell_sea_stokes(swell,sea)\n wind = WindMeasurements.read_from_csv('rottnest')\n u_L = VelocityField(hfradar.time,hfradar.lon,hfradar.lat,hfradar.u,hfradar.v)\n u_L_wind = get_eulerian_wind_field(hfradar,wind,alpha=0.01)\n _,dau_drogued,R_drogued = get_drogued_drifter_constants()\n _,dau_undrogued,R_undrogued = get_undrogued_drifter_constants()\n u_inertial_drogued = get_measured_inertial_velocity(hfradar,wind,dau_drogued,R_drogued)\n u_inertial_undrogued = get_measured_inertial_velocity(hfradar,wind,dau_undrogued,R_undrogued)\n return u_L,u_L_wind,u_inertial_drogued,u_inertial_undrogued\n\ndef load_interpolated_velocities():\n drifters = Drifters.read_from_netcdf()\n for drifter in drifters.drifter:\n drifter.get_hourly_averages()\n u_L,u_L_wind,u_inertial_drogued,u_inertial_undrogued = load_velocities()\n u_L_interp = interpolate_rectilinear_vfield(drifters,u_L,'u_L')\n u_L_wind_interp = interpolate_rectilinear_vfield(drifters,u_L_wind,'u_L_wind')\n u_inertial_drogued_interp = interpolate_rectilinear_vfield(drifters,u_inertial_drogued,'u_intertial_drogued')\n u_inertial_undrogued_interp = interpolate_rectilinear_vfield(drifters,u_inertial_undrogued,'u_intertial_undrogued')\n u = [u_L_interp,u_L_wind_interp,u_inertial_drogued_interp,u_inertial_undrogued_interp]\n u_names = ['$u_L$','$u_L+\\\\alpha u_A$','$u_{inertial,drogued}$','$u_{inertial,undrogued}$']\n return u,u_names,drifters\n\ndef get_vector_correlation_and_rmse(drifters,u,events):\n if not type(events) == list:\n events = [events]\n r = np.empty((len(events),len(drifters.drifter),len(u)))*np.nan\n rmse = np.empty((len(events),len(drifters.drifter),len(u)))*np.nan\n rrmse = np.empty((len(events),len(drifters.drifter),len(u)))*np.nan\n mae = np.empty((len(events),len(drifters.drifter),len(u)))*np.nan\n rmae = np.empty((len(events),len(drifters.drifter),len(u)))*np.nan\n for e,event in enumerate(events):\n for d,drifter in enumerate(drifters.drifter):\n l_time_drifter = get_l_time_range(drifter.time,event.start_time,event.end_time)\n time_drifter = drifter.time[l_time_drifter]\n u_drifter = drifter.u[l_time_drifter]\n v_drifter = drifter.v[l_time_drifter]\n vel_drifter = drifter.vel[l_time_drifter]\n for m in range(len(u)):\n l_time_u = get_l_time_range(u[m][d].time,event.start_time,event.end_time)\n time_vfield = u[m][d].time[l_time_u]\n u_vfield = u[m][d].u[l_time_u]\n v_vfield = u[m][d].v[l_time_u]\n vel_vfield = np.sqrt(u_vfield**2+v_vfield**2)\n # match drifter timeseries to vfield timeseries\n u_drifter_matched,v_drifter_matched = [],[]\n for t in time_vfield:\n i = np.where(time_drifter==t)[0][0]\n u_drifter_matched.append(u_drifter[i])\n v_drifter_matched.append(v_drifter[i])\n u_drifter_matched = np.array(u_drifter_matched)\n v_drifter_matched = np.array(v_drifter_matched)\n r[e,d,m] = get_vector_correlation(u_drifter_matched,v_drifter_matched,u_vfield,v_vfield)\n rmse[e,d,m] = get_rmse(time_drifter,vel_drifter,time_vfield,vel_vfield)\n rrmse[e,d,m] = rmse[e,d,m]/np.nanmean(vel_drifter)\n mae[e,d,m] = get_mae(time_drifter,vel_drifter,time_vfield,vel_vfield)\n rmae[e,d,m] = mae[e,d,m]/np.nanmean(vel_drifter)\n return r,rmse,rrmse,mae,rmae\n\ndef plot_drifter_velocity_comparisons(drifters,u,u_names,events,selected_drifters=[0]):\n output_dir = PlotDirs.read_from_json().simulations\n if not type(events) == list:\n events = [events]\n linestyles = ['--',':','-','-']\n linecolors = ['#000000','#000000','#808080','#000000']\n for event in events:\n for d in selected_drifters:\n u_d = []\n for m in range(len(u)):\n u_d.append(u[m][d])\n output_path = output_dir+'velocity_comparison_d'+str(d)+'.png'\n plot_velocity_comparison_to_file(event,drifters.drifter[d],u_d,u_names,linestyles,linecolors,output_path)\n\n\n# ------------------------------------------------------------------------------\n# PARTICLE TRACKING SIMULATIONS\n# ------------------------------------------------------------------------------\ndef run_simulations(events):\n if not type(events) == list:\n events = [events]\n total_event = Event.read_from_json('total')\n drifters = Drifters.read_from_netcdf()\n hfradar = Hfradar.read_time_range_from_netcdfs(total_event.start_time,total_event.end_time)\n swell = StokesDrift.get_swell()\n sea = StokesDrift.get_sea()\n stokes = get_combined_swell_sea_stokes(swell,sea)\n wind = WindMeasurements.read_from_csv('rottnest')\n model_names = ['lagrangian','lagrangian_wind','inertial_drogued','inertial_undrogued']\n u_L = hfradar\n u_L_wind = get_eulerian_wind_field(hfradar,wind,alpha=0.01)\n _,dau_drogued,R_drogued = get_drogued_drifter_constants()\n _,dau_undrogued,R_undrogued = get_undrogued_drifter_constants()\n u_inertial_drogued = get_measured_inertial_velocity(hfradar,wind,dau_drogued,R_drogued)\n u_inertial_undrogued = get_measured_inertial_velocity(hfradar,wind,dau_undrogued,R_undrogued)\n u = [u_L,u_L_wind,u_inertial_drogued,u_inertial_undrogued]\n sims_drifters = []\n for event in events:\n sim_drifters = run_event(u,model_names,event,drifters,dt=10*60)\n sims_drifters.append(sim_drifters)\n if len(sims_drifters) == 1:\n return sim_drifters,model_names\n else:\n return sims_drifters,model_names\n\ndef plot_daily_simulation_results():\n total_event = Event.read_from_json('total')\n sim_drifters = pickle.load(open('sim_drifters.pickle','rb'))\n sim_inertial_drifters = pickle.load(open('sim_inertial_drifters.pickle','rb'))\n output_dir = PlotDirs.read_from_json().simulations\n n = np.int((total_event.end_time-total_event.start_time).total_seconds()/(24*60*60))\n for i in range(n):\n requested_date = total_event.start_time+datetime.timedelta(days=i)\n output_path = output_dir+'sim_'+requested_date.strftime('%d-%m-%Y')+'.pdf'\n plot_daily_simulated_tracks_to_file(sim_drifters,sim_inertial_drifters,requested_date,output_path,alpha=0.01)\n\n# ------------------------------------------------------------------------------\n# ENVIRONMENTAL CONDITIONS\n# ------------------------------------------------------------------------------\ndef plot_timeseries_wind_wave_heights(event,output_path):\n wind = WindMeasurements.read_from_csv('rottnest')\n swell = WaveMeasurements.read_swell_from_xls()\n sea = WaveMeasurements.read_sea_from_xls()\n plot_wind_waves_to_file(event,wind,swell,sea,output_path)\n\ndef plot_timeseries_wind_waves(event,output_path):\n wind = WindMeasurements.read_from_csv('rottnest')\n swell = StokesDrift.get_swell()\n sea = StokesDrift.get_sea()\n stokes = get_combined_swell_sea_stokes(swell,sea)\n plot_timeseries_to_file(event,wind,stokes,output_path)\n\ndef plot_daily_sst_hfradar_drifter_maps():\n total_event = Event.read_from_json('total')\n drifters = Drifters.read_from_netcdf()\n for drifter in drifters.drifter:\n drifter.get_hourly_averages()\n hfradar = Hfradar.read_time_range_from_netcdfs(total_event.start_time,total_event.end_time)\n sst = Sst.read_from_netcdf()\n output_dir = PlotDirs.read_from_json().environmental\n # plot daily maps of sst, hf-radar and drifter tracks\n n = np.int((total_event.end_time-total_event.start_time).total_seconds()/(24*60*60))\n for i in range(n):\n requested_time = total_event.start_time+datetime.timedelta(days=i)\n output_path = output_dir+'daily_map_'+requested_time.strftime('%d-%m-%Y')+'.pdf'\n plot_daily_map_to_file(sst,hfradar,drifters,requested_time,output_path)\n" } ]
1
ayan-iiitd/maximum-rectilinear-crossing-number-of-uniform-hypergraphs
https://github.com/ayan-iiitd/maximum-rectilinear-crossing-number-of-uniform-hypergraphs
13e8d2673f2f7cacdfdeedade0ef3b57fa94b4e1
1ca56ef28a32bfbcaec600ecc2dde4d8499b4fa4
1503be9bc45bf3c89caa2ac8a30de94a98122d48
refs/heads/master
2020-11-30T05:41:50.432156
2020-01-17T17:37:08
2020-01-17T17:37:08
230,317,359
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6751173734664917, "alphanum_fraction": 0.6901408433914185, "avg_line_length": 30.323530197143555, "blob_id": "bd9955b5256fdd0ceb0e53ff47f65ccc424b4c5d", "content_id": "a06443e70ccdfd6cb58950cb9bd951fc80b51bb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1065, "license_type": "no_license", "max_line_length": 138, "num_lines": 34, "path": "/README.md", "repo_name": "ayan-iiitd/maximum-rectilinear-crossing-number-of-uniform-hypergraphs", "src_encoding": "UTF-8", "text": "# maximum-rectilinear-crossing-number-of-uniform-hypergraphs\nComplete source code for generating all results published in the paper.\n\nThis repository contains all the source code along with the outputs.\n\nFor running the programs yourself -\n\n1. Make sure to have read, write and execute access in the directory you are cloning this repository to and have the following installed -\n ```\n python 3.5+\n pandas 0.20+\n ```\n \n For Debian derivatives the package `glpk-utils` is needed.\n \n For RHEL and Arch Linux derivatives the package `glpk` is needed.\n \n \n 2. Create a new directory and copy `all_point_sets.txt` and all the `.py` files in it.\n ```\n mkdir test\n\n cp code1_convert_hex_to_int.py \\\n code2_generate_feasible_points.py \\\n code3_check_for_balanced_set.py \\\n code4_1_check_for_ptset_details_where_max_feasible_colorings_is_12.py \\\n code4_2_check_for_max_balanced_colors_without_M_or_I_aka_neighbourly_polytopes.py \\\n point_set_hex.txt \\\n run.py\n\n cd test\n\n python run.py\n ```\n" }, { "alpha_fraction": 0.43633413314819336, "alphanum_fraction": 0.672749400138855, "avg_line_length": 56.372093200683594, "blob_id": "f753184826991703b18161a14608c254c9541a9d", "content_id": "a89730b9ccebb30282ad9414f19c01994c3524f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2466, "license_type": "no_license", "max_line_length": 861, "num_lines": 43, "path": "/code4_1_check_for_ptset_details_where_max_feasible_colorings_is_12.py", "repo_name": "ayan-iiitd/maximum-rectilinear-crossing-number-of-uniform-hypergraphs", "src_encoding": "UTF-8", "text": "import os\nimport pandas\n\ndef run():\n\n\tfor file_no in range(1, 3316):\n\t\t\n\t\tfile_name = \"./feasible_point_sets_with_color_check/point_set_\" + str(file_no) + \"_with_color_check.csv\"\n\t\tpoint_set_details = pandas.DataFrame()\n\n\t\t## Sometimes when reading directly from a directory, Python converts the file names to byte strings, so a conversion to UTF-8 before they can be worked with is neccesary\n\t\tif (type(file_name) == 'bytes'):\n\t\t\tfeasible_ptset = pandas.read_csv(file_name.decode('utf-8'))\n\t\telse:\n\t\t\tfeasible_ptset = pandas.read_csv(file_name)\n\t\t\t\n\t\t## Checking if the maximum number of balanced color configurations is twelve for all possible colorings of a point set.\n\t\tif (list(feasible_ptset.iloc[-1])[4] == '12'):\n\t\t\n\t\t\tpoint_set_details['PointSet'] = feasible_ptset['PointSet']\n\t\t\tpoint_set_details['Feasible_Set_Size'] = feasible_ptset['Feasible_Set_Size']\n\t\t\tpoint_set_details['Feasible_Set_Indices'] = feasible_ptset['Feasible_Set_Indices']\n\t\t\tpoint_set_details['Feasible_Set_Points'] = feasible_ptset['Feasible_Set_Points']\n\t\t\tfound_flag = 0\n\t\n\t\t\trequired_colors = ['00001111', '00010111', '00011011', '00011101', '00011110', '00100111', '00101011', '00101101', '00101110', '00110011', '00110101', '00110110', '00111001', '00111010', '00111100', '01000111', '01001011', '01001101', '01001110', '01010011', '01010101', '01010110', '01011001', '01011010', '01011100', '01100011', '01100101', '01100110', '01101001', '01101010', '01101100', '01110001', '01110010', '01110100', '01111000', '10000111', '10001011', '10001101', '10001110', '10010011', '10010101', '10010110', '10011001', '10011010', '10011100', '10100011', '10100101', '10100110', '10101001', '10101010', '10101100', '10110001', '10110010', '10110100', '10111000', '11000011', '11000101', '11000110', '11001001', '11001010', '11001100', '11010001', '11010010', '11010100', '11011000', '11100001', '11100010', '11100100', '11101000', '11110000']\n\t\n\t\t\tfor color in required_colors:\n\t\t\t\tone_side_color = feasible_ptset[color].values.tolist()\n\t\t\t\t\n\t\t\t\t## Checking if a particular color has a total of twelve balanced colorings\n\t\t\t\tif (one_side_color[-2] == '12'):\n\t\t\t\t\tfound_flag = 1\n\t\t\t\t\tpoint_set_details[color] = feasible_ptset[color]\n\t\t\t\t\n\t\t\tif not os.path.exists('./12_balanced_colors'):\n\t\t\t\tos.makedirs('./12_balanced_colors')\n\t\t\t\n\t\t\tif found_flag == 1:\n\t\t\t\tpoint_set_details.to_csv('12_balanced_colors/' + str(file_no) + '.csv', sep = ',', index = False)\n\t\t\nif __name__== \"__main__\":\n\trun()" }, { "alpha_fraction": 0.5181695818901062, "alphanum_fraction": 0.6543292999267578, "avg_line_length": 48, "blob_id": "c445bded6b569d0dba5a9bc591900b02b516ee1c", "content_id": "0e8d85d5a8b69d4841a46964cee5b11fbfe46966", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4458, "license_type": "no_license", "max_line_length": 276, "num_lines": 91, "path": "/code3_check_for_balanced_set.py", "repo_name": "ayan-iiitd/maximum-rectilinear-crossing-number-of-uniform-hypergraphs", "src_encoding": "UTF-8", "text": "import os\nimport pandas\n\ndef run():\n\n\tdirectory = \"./feasible_point_sets/\"\n\tfiles = os.listdir(directory)\n\t\n\t#The list of 70 possible colors with equal number of points of both colors\n\trequired_colors = ['00001111', '00010111', '00011011', '00011101', '00011110', '00100111', '00101011', '00101101', '00101110',\n\t\t\t\t\t '00110011', '00110101', '00110110', '00111001', '00111010', '00111100', '01000111', '01001011', '01001101',\n\t\t\t\t\t '01001110', '01010011', '01010101', '01010110', '01011001', '01011010', '01011100', '01100011', '01100101',\n\t\t\t\t\t '01100110', '01101001', '01101010', '01101100', '01110001', '01110010', '01110100', '01111000', '10000111',\n\t\t\t\t\t '10001011', '10001101', '10001110', '10010011', '10010101', '10010110', '10011001', '10011010', '10011100',\n\t\t\t\t\t '10100011', '10100101', '10100110', '10101001', '10101010', '10101100', '10110001', '10110010', '10110100',\n\t\t\t\t\t '10111000', '11000011', '11000101', '11000110', '11001001', '11001010', '11001100', '11010001', '11010010',\n\t\t\t\t\t '11010100', '11011000', '11100001', '11100010', '11100100', '11101000', '11110000']\n\t\n\tfor file in files:\n\t\t\n\t\tfile_name = directory + file\n\t\tfeasible_ptset = pandas.read_csv(file_name)\n\t\trow_for_total_balanced = [\"\", \"\", \"\", \"Total Balanced Sets\"]\n\t\trow_for_max_balanced = [\"\", \"\", \"\", \"Size of Maximum Balanced Sets\"]\n\t\t\n\t\tfeasible_indices_str = list(feasible_ptset['Feasible_Set_Indices'])\n\t\tfeasible_indices = [eval(feasible_indices_str[index]) for index in range(len(feasible_indices_str))]\n\t\tnumber_of_balanced_set = []\n\n\t\tfor color in required_colors:\n\t\t\t\n\t\t\tcolor_result = []\n\t\t\tbalance_counter = 0\n\t\t\tmonochrome_flag_4set = 0\n\t\t\t\n\t\t\tfor indices in feasible_indices:\n\t\t\t\t\n\t\t\t\tsetsize = len(indices)\n\t\t\t\t\n\t\t\t\t#If the number of points is two then the possiblites are either both are of same color i.e. it is monochromatic or two points are of different colors, i.e. equal number of points of each color, therefore balanced\n\t\t\t\tif setsize == 2:\n\t\t\t\t\tone_side_color = color[indices[0]] + color [indices[1]]\n\t\t\t\t\tif one_side_color.count('1') == 1:\n\t\t\t\t\t\tcolor_result.append(one_side_color + \" - B\")\n\t\t\t\t\t\tbalance_counter += 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tcolor_result.append(one_side_color + \" - M\")\n\t\t\t\t\t\t\n\t\t\t\t#If the number of points are three then there are two possiblites, they all are of same color i.e. monochromatic or two points are of same color and the other one is different, i.e. they are imbalanced\n\t\t\t\telif setsize == 3:\n\t\t\t\t\tone_side_color = color[indices[0]] + color [indices[1]] + color[indices[2]]\n\t\t\t\t\tif one_side_color.count('1') == 2 or one_side_color.count('0') == 2:\n\t\t\t\t\t\tcolor_result.append(one_side_color + \" - I\")\n\t\t\t\t\telif one_side_color.count('1') == 3 or one_side_color.count('0') == 3:\n\t\t\t\t\t\tcolor_result.append(one_side_color + \" - M\")\n\t\t\t\t\n\t\t\t\t#If the number of points are four then there are four possiblites, they all are of same color i.e. monochromatic or two points are of same color and the other two are same, i.e. they are balanced and lastly threee are of the same color and one is different i.e. imbalanced\n\t\t\t\telif setsize == 4:\n\t\t\t\t\tone_side_color = color[indices[0]] + color [indices[1]] + color[indices[2]] + color[indices[3]]\n\t\t\t\t\tif one_side_color.count('1') == 2:\n\t\t\t\t\t\tcolor_result.append(one_side_color + \" - B\")\n\t\t\t\t\t\tbalance_counter += 1\n\t\t\t\t\telif one_side_color.count('1') == 1 or one_side_color.count('0') == 1:\n\t\t\t\t\t\tcolor_result.append(one_side_color + \" - I\")\n\t\t\t\t\telif one_side_color.count('1') == 0 or one_side_color.count('1') == 4:\n\t\t\t\t\t\tcolor_result.append(one_side_color + \" - M\")\n\t\t\t\t\t\tmonochrome_flag_4set = 1\n\t\t\t\n\t\t\tfeasible_ptset[color] = color_result\n\n\t\t\tif monochrome_flag_4set == 1:\n\t\t\t\trow_for_total_balanced.append('NA')\n\t\t\telse:\n\t\t\t\tnumber_of_balanced_set.append(balance_counter)\n\t\t\t\trow_for_total_balanced.append(balance_counter)\n\t\t\n\t\trow_for_max_balanced.append(max(number_of_balanced_set))\n\t\trow_for_max_balanced.extend(['']*abs(len(row_for_total_balanced) - len(row_for_max_balanced)))\n\t\tfeasible_ptset.loc[-1] = row_for_total_balanced\n\t\tfeasible_ptset.index = feasible_ptset.index + 1\n\t\tfeasible_ptset.loc[-1] = row_for_max_balanced\n\t\t\n\t\tif not os.path.exists('./feasible_point_sets_with_color_check'):\n\t\t\tos.makedirs('./feasible_point_sets_with_color_check')\n\t\t\t\n\t\tfile_name_to_save = './feasible_point_sets_with_color_check/' + file[:-4] + \"_with_color_check.csv\"\n\t\tfeasible_ptset.to_csv(file_name_to_save, sep = ',', index = False)\n\t\n\nif __name__== \"__main__\":\n\trun()" }, { "alpha_fraction": 0.7561597228050232, "alphanum_fraction": 0.7757009267807007, "avg_line_length": 68.29412078857422, "blob_id": "7a130666604a62e8134d2a7d930c1b65e63f998f", "content_id": "98a9003e4e8e1c36382a251c29a4da622a9b01e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1177, "license_type": "no_license", "max_line_length": 208, "num_lines": 17, "path": "/run.py", "repo_name": "ayan-iiitd/maximum-rectilinear-crossing-number-of-uniform-hypergraphs", "src_encoding": "UTF-8", "text": "import code1_convert_hex_to_int as code_1\nimport code2_generate_feasible_points as code_2\nimport code3_check_for_balanced_set as code_3\nimport code4_1_check_for_ptset_details_where_max_feasible_colorings_is_12 as code_4_1\nimport code4_2_check_for_max_balanced_colors_without_M_or_I_aka_neighbourly_polytopes as code_4_2\nimport datetime\n\nprint (\"Execution started at\\t\", datetime.datetime.now())\ncode_1.run()\nprint (\"\\n\\nConversion of hexadecimal to integer completed at\\t\", datetime.datetime.now(), '\\n\\n\\nStarting to check point sets for feasibility.')\ncode_2.run()\nprint (\"\\n\\nChecking point sets for feasibility finished at\\t\", datetime.datetime.now(), '\\n\\n\\nStarting to check for balanced, monochrome and imbalanced colors.')\ncode_3.run()\nprint (\"\\n\\nChecking for balanced, monochrome and imbalanced colors finished at\\t\", datetime.datetime.now(), '\\nStarting to check for details of point sets with maximum umber of balanced feasible colorings.')\ncode_4_1.run()\nprint (\"\\n\\nChecking for details of point sets with maximum umber of balanced feasible colorings finished at\\t\", datetime.datetime.now(), '\\nStarting to check for neighboourly polytopes where.')\ncode_4_2.run()" }, { "alpha_fraction": 0.6298850774765015, "alphanum_fraction": 0.6379310488700867, "avg_line_length": 23.19444465637207, "blob_id": "5eb2f4143118bbd5a96127c3f428d953fd78f187", "content_id": "5e9c29fa6aac80fcd3378f25a1581f31b5caa02c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 870, "license_type": "no_license", "max_line_length": 67, "num_lines": 36, "path": "/code1_convert_hex_to_int.py", "repo_name": "ayan-iiitd/maximum-rectilinear-crossing-number-of-uniform-hypergraphs", "src_encoding": "UTF-8", "text": "def run():\n\n\t## Reading the file and saving it as a list of strings\n\twith open(\"./point_set_hex.txt\", \"r\") as hexfile:\n\t\thexlines = hexfile.readlines()\n\t\t\n\tall_point_coordinates = []\n\t\n\tfor line in hexlines:\n\t\t\n\t\t## Splitting the line into list of coordinates, still as a string\n\t\tpoint_set = []\n\t\tpoints = line.split()\n\t\t\n\t\tfor point in points:\n\t\t\t\n\t\t\t## Convertng points from hexadecimal string into ints\n\t\t\tx_coord = int(point[0:2], 16)\n\t\t\ty_coord = int(point[2:], 16)\n\t\t\t\n\t\t\tpoint_set.append((x_coord, y_coord))\n\t\t\n\t\tall_point_coordinates.append(list(point_set))\n\t\t\t\n\t\t\t## Saving list of points in integer format to a file\n\t\n\twith open(\"all_point_sets.txt\", \"w\") as point_set_file:\n\t\tfor point_set in all_point_coordinates:\n\t\t\tfor point in point_set:\n\t\t\t\tpoint_set_file.write(str(point) + \", \")\n\t\t\t\n\t\t\tpoint_set_file.write(\"\\n\")\n\t\t\t\n\nif __name__== \"__main__\":\n\trun()" }, { "alpha_fraction": 0.6067695617675781, "alphanum_fraction": 0.6231956481933594, "avg_line_length": 32.214874267578125, "blob_id": "1435b089dcc271eb80903bb9c2409a9fe2bfb84f", "content_id": "a87932051d47ff0d6c6e018f5a87f8271ffc53c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4018, "license_type": "no_license", "max_line_length": 236, "num_lines": 121, "path": "/code2_generate_feasible_points.py", "repo_name": "ayan-iiitd/maximum-rectilinear-crossing-number-of-uniform-hypergraphs", "src_encoding": "UTF-8", "text": "import ast\nimport datetime\nimport os\nimport pandas\nimport subprocess\nfrom itertools import combinations, islice\n\ndef run():\n\n\tindex_combos = []\n\t\n\t## Generating all possible combinations of points of sizes 2, 3 and 4\n\tfor size in [2, 3, 4]:\n\t\tif size !=4 :\n\t\t\tindex_combos = index_combos + list(combinations(range(0, 8), size))\n\t\t\n\t\telse:\n\t\t\tindex_combos = index_combos + list(islice(combinations(range(0, 8), 4), 35))\n\t\n\t\n\twith open(\"all_point_sets.txt\", \"r\") as ptsfile:\n\t\tallpts_str = ptsfile.readlines()\n\t\n\tline_no = 1\n\tfor line in allpts_str:\n\t\t\n\t\t## Converting point set from string to usable list of tuples\n\t\tpointset_details = pandas.DataFrame()\n\t\tpoint_set = list(ast.literal_eval(line))\n\t\n\t\toptimals = [[], [], []]\n\t\n\t\tif not os.path.exists('./feasible_point_sets'):\n\t\t\tos.makedirs('./feasible_point_sets')\n\t\t\n\t\tpointset_filename = \"feasible_point_sets/point_set_\" + str(line_no)\n\t\n\t\tfor indices in index_combos:\n\t\n\t\t\tremaining_indices = list(set(range(0, 8)).difference(indices))\n\t\t\t\n\t\t\tcombo, remaining_points = [], []\n\t\t\tfor index in indices:\n\t\t\t\tcombo.append(point_set[index])\n\t\t\t\n\t\t\tfor index in remaining_indices:\n\t\t\t\tremaining_points.append(point_set[index])\n\t\n\t\t\t## Generating .mod file for solving as LP\n\t\t\t## After separating the points into two separate sets, a set can lie on either side of the separating line. To check if a configuration or its inverse is feasible , the contraints need to be checked after reversing their inequalities\n\t\t\t\n\t\t\tfor repeat in [1, 2]:\n\t\t\t\t\n\t\t\t\tlp_file = open(\"run.mod\", \"w\")\n\t\t\t\tlp_file.write(\"var x1;\\nvar x2;\\n\")\n\t\t\t\tlp_file.write(\"maximize obj: x1 + x2;\\n\")\n\t\t\t\t\n\t\t\t\tif repeat == 1:\n\t\t\t\t\t\n\t\t\t\t\tconstraint_count = 1\n\t\t\t\t\t\n\t\t\t\t\tfor coordinates in combo:\n\t\n\t\t\t\t\t\tto_print = \"s.t. c\" + str(constraint_count) + \": \" + str(coordinates[0]) + \" * x1 + \" + str(coordinates[1]) + \"* x2 >= 1;\\n\"\n\t\t\t\t\t\tlp_file.write(to_print)\n\t\t\t\t\t\tconstraint_count += 1\n\t\t\t\t\t\n\t\t\t\t\tfor coordinates in remaining_points:\n\t\t\t\t\t\tto_print = \"s.t. c\" + str(constraint_count) + \": \" + str(coordinates[0]) + \" * x1 + \" + str(coordinates[1]) + \"* x2 <= 1;\\n\"\n\t\t\t\t\t\tlp_file.write(to_print) \n\t\t\t\t\t\tconstraint_count += 1\n\t\t\t\t\t\n\t\t\t\t\tlp_file.write(\"solve;\\nend;\")\n\t\t\t\t\tlp_file.close()\n\t\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\t\n\t\t\t\t\tconstraint_count = 1\n\t\t\t\t\t\n\t\t\t\t\tfor coordinates in combo:\n\t\t\t\t\t\tto_print = \"s.t. c\" + str(constraint_count) + \": \" + str(coordinates[0]) + \" * x1 + \" + str(coordinates[1]) + \"* x2 <= 1;\\n\"\n\t\t\t\t\t\tlp_file.write(to_print)\n\t\t\t\t\t\tconstraint_count += 1\n\t\t\t\t\t\n\t\t\t\t\tfor coordinates in remaining_points:\n\t\t\t\t\t\tto_print = \"s.t. c\" + str(constraint_count) + \": \" + str(coordinates[0]) + \" * x1 + \" + str(coordinates[1]) + \"* x2 >= 1;\\n\"\n\t\t\t\t\t\tlp_file.write(to_print)\n\t\t\t\t\t\tconstraint_count += 1\n\t\n\t\t\t\t\tlp_file.write(\"solve;\\nend;\")\n\t\t\t\t\tlp_file.close()\n\t\t\t\t\t\n\t\t\t\t## Using glpsol tool from GLPK GNU tool as a python subprocess and checking for feasibility and if feasible save the details of the point set and move to the next\n\t\t\t\tsolving_LP = subprocess.run(\"glpsol --math run.mod > LP_result\", shell = True)\n\t\t\t\twith open(\"LP_result\", \"r\") as lp_result:\n\t\t\t\t\tif 'NO PRIMAL FEASIBLE' not in lp_result.read():\n\t\t\t\t\t\tif combo not in optimals[0]:\n\t\t\t\t\t\t\toptimals[0].append(combo)\n\t\t\t\t\t\t\toptimals[1].append(len(combo))\n\t\t\t\t\t\t\toptimals[2].append(indices)\n\t\n\t\tif len(point_set) > len(optimals[0]):\n\t\t\toptimals[0].extend(['']*abs(len(point_set) - len(optimals[0])))\n\t\t\toptimals[1].extend(['']*abs(len(point_set) - len(optimals[0])))\n\t\t\toptimals[2].extend(['']*abs(len(point_set) - len(optimals[0])))\n\t\t\n\t\telse:\n\t\t\tpoint_set.extend(['']*abs(len(optimals[0]) - len(point_set)))\n\t\t\t\n\t\tpointset_details['PointSet'] = point_set\n\t\tpointset_details['Feasible_Set_Size'] = optimals[1]\n\t\tpointset_details['Feasible_Set_Indices'] = optimals[2]\n\t\tpointset_details['Feasible_Set_Points'] = optimals[0]\n\t\t\n\t\tpointset_details.to_csv(pointset_filename + \".csv\", sep = ',', index = False)\n\t\tprint ('Checking point set ', line_no, \"\\t finished at\\t\", datetime.datetime.now())\n\t\tline_no += 1\n\n\nif __name__== \"__main__\":\n\trun()" }, { "alpha_fraction": 0.4484574794769287, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 48.24074172973633, "blob_id": "452a3decceb6d86879bd12a525ed5b28f981dc77", "content_id": "9b09afccaa2ead37a9b5bc18522f4c3c0f2747ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2658, "license_type": "no_license", "max_line_length": 860, "num_lines": 54, "path": "/code4_2_check_for_max_balanced_colors_without_M_or_I_aka_neighbourly_polytopes.py", "repo_name": "ayan-iiitd/maximum-rectilinear-crossing-number-of-uniform-hypergraphs", "src_encoding": "UTF-8", "text": "import os\nimport pandas\n\ndef run():\n\t\n\tfor file_no in range(1, 3316):\n\t\t\n\t\tfile_name = \"./feasible_point_sets_with_color_check/point_set_\" + str(file_no) + \"_with_color_check.csv\"\n\n\t\t## Sometimes when reading directly from a directory, Python converts the file names to byte strings, so a conversion to UTF-8 before they can be worked with is neccesary\n\t\tif (type(file_name) == 'bytes'):\n\t\t\tfeasible_ptset = pandas.read_csv(file_name.decode('utf-8'))\n\t\telse:\n\t\t\tfeasible_ptset = pandas.read_csv(file_name)\n\t\t\n\t\tpointset_details = pandas.DataFrame()\n\t\t\n\t\tfor col_name in list(feasible_ptset.columns)[:4]:\n\t\t\tpointset_details[col_name] = feasible_ptset[col_name].values\n\t\t\t\n\t\t\tsize_of_all_feasible_sets = feasible_ptset['Feasible_Set_Size'].values.tolist()\n\n\t\trequired_colors = ['00001111', '00010111', '00011011', '00011101', '00011110', '00100111', '00101011', '00101101', '00101110', '00110011', '00110101', '00110110', '00111001', '00111010', '00111100', '01000111', '01001011', '01001101', '01001110', '01010011', '01010101', '01010110', '01011001', '01011010', '01011100', '01100011', '01100101', '01100110', '01101001', '01101010', '01101100', '01110001', '01110010', '01110100', '01111000', '10000111', '10001011', '10001101', '10001110', '10010011', '10010101', '10010110', '10011001', '10011010', '10011100', '10100011', '10100101', '10100110', '10101001', '10101010', '10101100', '10110001', '10110010', '10110100', '10111000', '11000011', '11000101', '11000110', '11001001', '11001010', '11001100', '11010001', '11010010', '11010100', '11011000', '11100001', '11100010', '11100100', '11101000', '11110000']\n\t\n\t\tfor color in required_colors:\n\n\t\t\tone_side_color = feasible_ptset[color].values.tolist()\n\t\t\tmonochrome_found = 0\n\t\t\t\n\t\t\tfor index in range(0, len(size_of_all_feasible_sets)):\n\t\t\t\t\n\t\t\t\t## Checking if a monochrome exists for 2 sets and 3 sets and if a monochrome or imbalanced coloring is found for 4 sets\n\t\t\t\tif size_of_all_feasible_sets[index] == 2 or size_of_all_feasible_sets[index] == 3:\n\t\t\t\t\tif ('M' in one_side_color[index]):\n\t\t\t\t\t\tmonochrome_found = 1\n\t\t\t\t\t\tbreak\n\t\t\t\telif size_of_all_feasible_sets[index] == 4:\n\t\t\t\t\tif ('M' in one_side_color[index] or 'I' in one_side_color[index]):\n\t\t\t\t\t\tmonochrome_found = 1\n\t\t\t\t\t\tbreak\n\t\t\t\n\t\t\tif monochrome_found == 0:\n\t\t\t\tpointset_details[color] = feasible_ptset[color].values\n\t\t\t\t\n\t\tif (len(pointset_details.columns) > 4):\n\t\t\t\n\t\t\tif not os.path.exists('./max_feasible_without_M_or_I'):\n\t\t\t\tos.makedirs('./max_feasible_without_M_or_I')\n\n\t\t\tpointset_details.to_csv('max_feasible_without_M_or_I/Balanced_Set_' + str(file_no) + '.csv', sep = ',', index = False)\n\n\nif __name__== \"__main__\":\n\trun()" } ]
7
yaehei/gfw_whitelist-1
https://github.com/yaehei/gfw_whitelist-1
9fd95c1c9fae26cb2f15bc733e52cb9797209872
38d0a29f7fb0e374dec6caf38cb7c15f75453acd
ca02e7317467f4f5fcefc7f603c4baec89901c6a
refs/heads/master
2021-01-24T23:12:56.322354
2014-11-08T15:30:52
2014-11-08T15:30:52
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4914211630821228, "alphanum_fraction": 0.618970513343811, "avg_line_length": 24.733333587646484, "blob_id": "8afb0c3bf09658c6990fc30939df3d30289bf54a", "content_id": "1ffa8f1781c7a00683b9ef58be7753d4555399fb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3089, "license_type": "permissive", "max_line_length": 113, "num_lines": 120, "path": "/mainip.py", "repo_name": "yaehei/gfw_whitelist-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom argparse import ArgumentParser\n\nfakeIpList = [\n'74.125.127.102',\n'74.125.155.102',\n'74.125.39.102',\n'74.125.39.113',\n'209.85.229.138',\n'128.121.126.139',\n'159.106.121.75',\n'169.132.13.103',\n'192.67.198.6',\n'202.106.1.2',\n'202.181.7.85',\n'203.161.230.171',\n'203.98.7.65',\n'207.12.88.98',\n'208.56.31.43',\n'209.145.54.50',\n'209.220.30.174',\n'209.36.73.33',\n'211.94.66.147',\n'213.169.251.35',\n'216.221.188.182',\n'216.234.179.13',\n'243.185.187.39',\n'37.61.54.158',\n'4.36.66.178',\n'46.82.174.68',\n'59.24.3.173',\n'64.33.88.161',\n'64.33.99.47',\n'64.66.163.251',\n'65.104.202.252',\n'65.160.219.113',\n'66.45.252.237',\n'72.14.205.104',\n'72.14.205.99',\n'78.16.49.15',\n'8.7.198.45',\n'93.46.8.89'\n]\n\ndef ip2int(ipstr):\n\tintlist = ipstr.split('.')\n\tret = 0\n\tfor i in range(4):\n\t\tret = ret * 256 + int(intlist[i])\n\treturn ret\n\ndef parse_args():\n\tparser = ArgumentParser()\n\tparser.add_argument('-i', '--input', dest='input', default='data\\\\whiteiplist.pac',\n\t\thelp='path to gfwlist')\n\tparser.add_argument('-o', '--output', dest='output', default='whiteiplist.pac',\n\t\thelp='path to output pac', metavar='PAC')\n\tparser.add_argument('-p', '--proxy', dest='proxy', default='\"PROXY 127.0.0.1:1080;\"',\n\t\thelp='the proxy parameter in the pac file, for example,\\\n\t\t\"127.0.0.1:1080;\"', metavar='PROXY')\n\treturn parser.parse_args()\n\ndef get_all_list(lists):\n\tall_list = set()\n\tresult = list()\n\tfor item in lists:\n\t\tall_list = all_list | item.getlist()\n\tall_list.remove('')\n\tsort_list = []\n\tfor item in all_list:\n\t\tsort_list.append(item)\n\tsort_list.sort()\n\tfor item in sort_list:\n\t\tresult.append('\\n \"' + item + '\": 1,')\n\treturn result\n\ndef get_file_data(filename):\n\tcontent = ''\n\twith open(filename, 'r') as file_obj:\n\t\tcontent = file_obj.read()\n\treturn content\n\ndef final_list():\n\tfileobj = open(\"data/cn_ip_range.txt\", \"r\")\n\tcontent = ''\n\tif fileobj:\n\t\tlist_result = []\n\t\tlines_list = [line.rstrip('\\n').split(' ') for line in fileobj]\n\t\tlist_result = [ \"0x%x:%s,\" % (int(line[0]),int(line[1])) for line in lines_list ]\n\t\t#for mask in [2**v for v in range(8, 23)]:\n\t\t#\tlist_result_mask = [ \"0x%x:%s,\" % (int(line[0]),int(line[1])) for line in lines_list if int(line[1]) == mask]\n\t\t#\tlist_result += [\"%d:{\"%mask] + list_result_mask + [\"},\"]\n\t\tcontent = '\\n'.join(list_result)\n\tcontent = '{\\n' + content[:-1] + \"\\n}\"\n\treturn content\n\ndef fake_list():\n\tcontent = ''\n\tlist_result = [ \"0x%x:1,\" % int(ip2int(ip)) for ip in fakeIpList ]\n\tcontent = '\\n'.join(list_result)\n\tcontent = '{\\n' + content[:-1] + \"\\n}\"\n\treturn content\n\ndef writefile(input_file, proxy, output_file):\n\tip_content = final_list()\n\tfake_ip_content = fake_list()\n\tproxy_content = get_file_data(input_file)\n\tproxy_content = proxy_content.replace('__PROXY__', proxy)\n\tproxy_content = proxy_content.replace('__IP_LIST__', ip_content)\n\tproxy_content = proxy_content.replace('__FAKE_IP_LIST__', fake_ip_content)\n\twith open(output_file, 'w') as file_obj:\n\t\tfile_obj.write(proxy_content)\n\ndef main():\n\targs = parse_args()\n\twritefile(args.input, '\"' + args.proxy.strip('\"') + '\"', args.output)\n\nif __name__ == '__main__':\n\tmain()\n\n" }, { "alpha_fraction": 0.5700344443321228, "alphanum_fraction": 0.6538461446762085, "avg_line_length": 22.527027130126953, "blob_id": "e410cb902e370c7568af9bc2a5584ab28c652fa6", "content_id": "e0c941bc1db1370d4a00a0864fc5461999f0c60d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1742, "license_type": "permissive", "max_line_length": 56, "num_lines": 74, "path": "/data/whiteiplist.pac", "repo_name": "yaehei/gfw_whitelist-1", "src_encoding": "UTF-8", "text": "var cnIpRange = __IP_LIST__;\n\nvar fakeIpRange = __FAKE_IP_LIST__;\n\nvar subnetIpRange = {\n167772160:16777216,\t//10.0.0.0/8\n2886729728:1048576,\t//172.16.0.0/12\n3232235520:65536,\t//192.168.0.0/16\n2130706432:256\t\t//127.0.0.0/24\n};\n\nvar wall_proxy = __PROXY__;\nvar nowall_proxy = \"DIRECT;\";\nvar direct = \"DIRECT;\";\n\nvar hasOwnProperty = Object.hasOwnProperty;\n\nfunction convertAddress(ipchars) {\n\tvar bytes = ipchars.split('.');\n\tvar result = (bytes[0] << 24) |\n\t(bytes[1] << 16) |\n\t(bytes[2] << 8) |\n\t(bytes[3]);\n\treturn result >>> 0;\n};\nfunction isInRange(ipRange, intIp) {\n\tfor ( var range = 256; range <= 4194304; range*=2 ) {\n\t\tvar sub = intIp & (range-1);\n\t\tvar masterIp = intIp - sub;\n\t\tif ( hasOwnProperty.call(ipRange[range], masterIp) )\n\t\t\treturn sub < range;\n\t}\n\treturn 0;\n}\nfunction isInSingleRange(ipRange, intIp) {\n\tfor ( var range = 256; range <= 4194304; range*=2 ) {\n\t\tvar sub = intIp & (range-1);\n\t\tvar masterIp = intIp - sub;\n\t\tif ( hasOwnProperty.call(ipRange, masterIp) )\n\t\t\treturn sub < ipRange[masterIp];\n\t}\n\treturn 0;\n}\nfunction isInSubnetRange(ipRange, intIp) {\n\tfor ( var range = 256; range <= 16777216; range*=16 ) {\n\t\tvar sub = intIp & (range-1);\n\t\tvar masterIp = intIp - sub;\n\t\tif ( hasOwnProperty.call(ipRange, masterIp) )\n\t\t\treturn sub < ipRange[masterIp];\n\t}\n\treturn 0;\n}\nfunction FindProxyForURL(url, host) {\n\tif ( isPlainHostName(host) === true ) {\n\t\treturn direct;\n\t}\n\n\tvar strIp = dnsResolve(host);\n\tif (!strIp) {\n\t\treturn wall_proxy;\n\t}\n\t\n\tvar intIp = convertAddress(strIp);\n\tif ( hasOwnProperty.call(fakeIpRange, intIp) ) {\n\t\treturn wall_proxy;\n\t}\n\tif ( isInSubnetRange(subnetIpRange, intIp) ) {\n\t\treturn direct;\n\t}\n\tif ( isInSingleRange(cnIpRange, intIp) ) {\n\t\treturn nowall_proxy;\n\t}\n\treturn wall_proxy;\n}\n\n" }, { "alpha_fraction": 0.6440781354904175, "alphanum_fraction": 0.6581196784973145, "avg_line_length": 28.23214340209961, "blob_id": "758ea0b5927b15a7c899ad98613fc5ff992452ec", "content_id": "44e07f4d3948b3000b65f8d74f78c349de618827", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1638, "license_type": "permissive", "max_line_length": 86, "num_lines": 56, "path": "/main.py", "repo_name": "yaehei/gfw_whitelist-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom argparse import ArgumentParser\n\ndef parse_args():\n\tparser = ArgumentParser()\n\tparser.add_argument('-i', '--input', dest='input', default='data\\\\whitelist.pac',\n\t\thelp='path to gfwlist')\n\tparser.add_argument('-o', '--output', dest='output', default='whitelist.pac',\n\t\thelp='path to output pac', metavar='PAC')\n\tparser.add_argument('-p', '--proxy', dest='proxy', default='\"PROXY 127.0.0.1:1080;\"',\n\t\thelp='the proxy parameter in the pac file, for example,\\\n\t\t\"127.0.0.1:1080;\"', metavar='PROXY')\n\treturn parser.parse_args()\n\ndef get_all_list(lists):\n\tall_list = set()\n\tresult = list()\n\tfor item in lists:\n\t\tall_list = all_list | item.getlist()\n\tall_list.remove('')\n\tsort_list = []\n\tfor item in all_list:\n\t\tsort_list.append(item)\n\tsort_list.sort()\n\tfor item in sort_list:\n\t\tresult.append('\\n\\t\"' + item + '\": 1,')\n\treturn result\n\ndef get_file_data(filename):\n\tcontent = ''\n\twith open(filename, 'r') as file_obj:\n\t\tcontent = file_obj.read()\n\treturn content\n\ndef final_list():\n\timport lists\n\tlist_result = get_all_list(lists.get_list_set())\n\tcontent = ''.join(list_result)\n\tcontent = '{' + content[:-1] + \"\\n}\"\n\treturn content\n\ndef writefile(input_file, proxy, output_file):\n\tdomains_content = final_list()\n\tproxy_content = get_file_data(input_file)\n\tproxy_content = proxy_content.replace('__PROXY__', proxy)\n\tproxy_content = proxy_content.replace('__DOMAINS__', domains_content)\n\twith open(output_file, 'w') as file_obj:\n\t\tfile_obj.write(proxy_content)\n\ndef main():\n\targs = parse_args()\n\twritefile(args.input, '\"' + args.proxy.strip('\"') + '\"', args.output)\n\nif __name__ == '__main__':\n\tmain()\n\n" }, { "alpha_fraction": 0.7532695531845093, "alphanum_fraction": 0.8253219127655029, "avg_line_length": 10.617729187011719, "blob_id": "5253594854f624a983b90f44b7c2f03bb34b344e", "content_id": "425af07f432ca96bc9ce0ebcec2738d1ba0aac9f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208515, "license_type": "permissive", "max_line_length": 41, "num_lines": 17948, "path": "/lists/auto.py", "repo_name": "yaehei/gfw_whitelist-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\ndef getlist():\n liststr = \"\"\"\n126.am\ntao.bb\n7daysinn.biz\nankang.biz\nchangan.biz\nchinafastener.biz\nhongsui.biz\nncce.biz\nqianyan.biz\nzhaopinhui.biz\n010.cc\n0311.cc\n0513.cc\n0566fc.cc\n0570.cc\n073.cc\n0774.cc\n1-l.cc\n1000kan.cc\n1133.cc\n1144.cc\n123du.cc\n1377.cc\n163k.cc\n181.cc\n1news.cc\n2144.cc\n21ce.cc\n2344.cc\n237.cc\n256.cc\n263.cc\n3216.cc\n340.cc\n3456.cc\n365url.cc\n3wmm.cc\n414.cc\n4299.cc\n4366.cc\n4wan.cc\n5055.cc\n509.cc\n51314.cc\n5137.cc\n5281.cc\n52mh.cc\n55.cc\n55g.cc\n5648.cc\n592wg.cc\n6wang.cc\n7190.cc\n7360.cc\n77wan.cc\n7899.cc\n7bei.cc\n7mo.cc\n8161.cc\n8682.cc\n893.cc\n959.cc\n96555.cc\n9844.cc\n987.cc\n9tu.cc\nafz.cc\nagui.cc\nahbb.cc\nahly.cc\nanhui.cc\naoyou.cc\nappcms.cc\naqw.cc\nayrc.cc\nbaise.cc\nbamaol.cc\nbeitu.cc\nbhtv.cc\nbinxian.cc\nbjcn.cc\nbzhan.cc\nc100.cc\nc2000.cc\ncc11.cc\ncetc.cc\nchadao.cc\nchaohu.cc\nchashui.cc\nchemstar.cc\nchengche.cc\nchenghai.cc\nchinahome.cc\nchinatimes.cc\nchuban.cc\nchuxiong.cc\nciid.cc\ncnalu.cc\ncomac.cc\nd17.cc\ndaman.cc\ndanhuang.cc\nddoo.cc\ndenglu.cc\ndiwuji.cc\ndj114.cc\ndker.cc\ndonglingying.cc\ndown.cc\ne0575.cc\necang.cc\nejiaju.cc\nerrenzhuan.cc\nfahao.cc\nfangke.cc\nfarc.cc\nfeixi.cc\nfengfeng.cc\nfenggang.cc\nfengrun.cc\nfy168.cc\ngczx.cc\nglobalbuy.cc\ngmtv.cc\ngoodtea.cc\ngqw.cc\nguanshangyu.cc\nguoyang.cc\ngusu.cc\nguyi.cc\nhaijingfang.cc\nhaishui.cc\nhan-tang.cc\nhao315.cc\nhaodir.cc\nhaoxuexiao.cc\nhaoyingshi.cc\nhb114.cc\nhbfcw.cc\nhbw.cc\nhbzp.cc\nhcms.cc\nhefei.cc\nheiye.cc\nheyang.cc\nheze.cc\nhezefangchan.cc\nhezefc.cc\nhezeqc.cc\nhezeqiche.cc\nhezerencai.cc\nhfw.cc\nhk5.cc\nhltm.cc\nhnh.cc\nhnnews.cc\nhnzz.cc\nhsds.cc\nhty.cc\nhuai.cc\nhuanghelou.cc\nhudong.cc\nhuoshan.cc\nhyw.cc\nhzedu.cc\nhzfc.cc\nhzgz.cc\nhzrcw.cc\nhzzp.cc\ni3v.cc\nicoat.cc\nidarling.cc\niepz.cc\nitudou.cc\niyd.cc\njgzx.cc\njiaju.cc\njialaxin.cc\njiangxia.cc\njianzaoshi.cc\njide123.cc\njimonet.cc\njinliyu.cc\njinnong.cc\njinxun.cc\njinyuzd.cc\njiuzi.cc\njkdb.cc\njlzx.cc\njnzx.cc\njumin.cc\njxzp.cc\njz.cc\njz6.cc\nkao8.cc\nkb.cc\nkjw.cc\nkmw.cc\nkongqueyuzd.cc\nkongyaji.cc\nkp52.cc\nkuhema.cc\nlanguang.cc\nlbx.cc\nlingdan.cc\nljlj.cc\nlongyu.cc\nluohanyu.cc\nlyrc.cc\nmallcn.cc\nmeishi.cc\nmianhuatang.cc\nmiit.cc\nmn520.cc\nmohe.cc\nmoko.cc\nmywood.cc\nmzsky.cc\nn21.cc\nnabel.cc\nnec.cc\nneihuang.cc\nnengyuan.cc\nngacn.cc\nnuo.cc\no-star.cc\np9p9.cc\npanzi.cc\npinchao.cc\npinjie.cc\npowersemi.cc\npp.cc\npp6.cc\npuercha.cc\npyedu.cc\nqc8.cc\nqcr.cc\nqiandaohu.cc\nqina.cc\nqj.cc\nqk.cc\nqqiii.cc\nqqmingzi.cc\nqqzl.cc\nquanxi.cc\nqw.cc\nqxw.cc\nqzone.cc\nqzz.cc\nrc.cc\nrddesign.cc\nrongzhong.cc\nrxs.cc\nsanhucidiao.cc\nseeyoo.cc\nsgnet.cc\nsgren.cc\nshangqi.cc\nshanhe.cc\nshaofang.cc\nshenxianyu.cc\nsheyang.cc\nshidao.cc\nshiyan.cc\nshowtime.cc\nshuicao.cc\nshuichan.cc\nsjz.cc\nsnsfun.cc\nstarbaby.cc\nswl.cc\nsyfc.cc\ntaiqian.cc\ntaizhou.cc\ntbt.cc\ntcnews.cc\ntcxw.cc\nteambuy.cc\ntucao.cc\ntuku.cc\ntxt99.cc\ntyn.cc\ntyx.cc\ntz.cc\ntzckj.cc\ntzjob.cc\nuc8.cc\nucbug.cc\nujian.cc\num5.cc\nuu.cc\nuuuu.cc\nuyan.cc\nvfe.cc\nvipsoft.cc\nwanbocai.cc\nwandu.cc\nweiguang.cc\nweishan.cc\nwenbo.cc\nwotoo.cc\nwuhu.cc\nwuqing.cc\nwutongxiang.cc\nwxi.cc\nxb5.cc\nxialingying.cc\nxiaomei.cc\nxpf.cc\nxszp.cc\nxzrj.cc\ny80s.cc\nyahui.cc\nyc.cc\nydfcw.cc\nyfyc.cc\nyingwuyuzd.cc\nyl114.cc\nyoulila.cc\nytx.cc\nyujiang.cc\nyxks.cc\nyy88.cc\nyzw.cc\nzdian.cc\nzhibo8.cc\nzhuojie.cc\nzhuwang.cc\n0464.cm\n4.cm\n60.cm\nbengou.cm\ncq.cm\ngcw.cm\nguilin.cm\nyy.cm\nbanzhu.co\nccig.co\nciyuan.co\nhengqian.co\nhuangchuan.co\njjjg.co\nlixin.co\ntestmart.co\nwbiao.co\nxgyy.co\nxiaomayi.co\nychdzx.co\n0-100s.com\n0-6.com\n0001688.com\n0001k.com\n0001wan.com\n00042.com\n000dn.com\n001ce.com\n001cndc.com\n001en.com\n001hr.com\n001job.com\n001pp.com\n001sxy.com\n001zhe.com\n003job.com\n007258.com\n007dp.com\n007swz.com\n007yx.com\n008wan.com\n009hr.com\n010bjzs.com\n010hr.com\n010jiaoshi.com\n010lf.com\n010lyzg.com\n010zihua.com\n011job.com\n01hr.com\n01teacher.com\n01yo.com\n020.com\n020h.com\n020job.com\n020k.com\n0214.com\n021cai.com\n021wy.com\n022ee.com\n022net.com\n022sy.com\n022v.com\n0233.com\n02342.com\n023aq.com\n023v.com\n023yts.com\n023zjj.com\n023zp.com\n024zol.com\n024zxw.com\n025.com\n025ct.com\n025kd.com\n025syedu.com\n025xl.com\n025zp.com\n025zph.com\n02751766.com\n027art.com\n027deru.com\n027hpedu.com\n027hpit.com\n028-56.com\n028668.com\n028aide.com\n028cbd.com\n028ccx.com\n028f.com\n028gcw.com\n028jiajiao.com\n028kj.com\n028office.com\n028sp.com\n028town.com\n029-88810000.com\n029558.com\n029k.com\n029yoyo.com\n029zp.com\n02edu.com\n02yc.com\n031086.com\n0314job.com\n0316fdc.com\n031924.com\n031rc.com\n0335qc.com\n0335travel.com\n0350tv.com\n035166.com\n0352fang.com\n0355wxr.com\n0356.com\n0356f.com\n0357hz.com\n0358lvl.com\n0359fdc.com\n0359rencai.com\n0359tv.com\n0370home.com\n0370zp.com\n0371job.com\n0371www.com\n0371zm.com\n0372job.com\n0373job.com\n0375jk.com\n0377auto.com\n0377jobs.com\n0378job.com\n0379house.com\n0379jk.com\n037g.com\n0384.com\n0391job.com\n0392job.com\n0393fcw.com\n0393job.com\n0396e.com\n0398job.com\n03th.com\n0411921.com\n0411hd.com\n0417u.com\n0418hr.com\n0419car.com\n0427qcw.com\n0431jia.com\n0434w.com\n0438news.com\n0452e.com\n0452zhaopin.com\n0454.com\n0460.com\n0471fcw.com\n0472.com\n0510.com\n051000.com\n0510syedu.com\n0510yx.com\n0511qcw.com\n0511y.com\n051291.com\n0512a.com\n0512dz.com\n0512rx.com\n0512uu.com\n0512yy.com\n0512zp.com\n0513info8.com\n0513nttc.com\n0513syedu.com\n0514.com\n0514dq.com\n051591.com\n0515auto.com\n0515cw.com\n051661.com\n0516zpw.com\n0517cw.com\n0517mall.com\n0517offer.com\n0517w.com\n05188.com\n0518cw.com\n0518hj.com\n0518rcw.com\n0519.com\n0519net.com\n0519syedu.com\n051jk.com\n051wc.com\n0523gg.com\n0523tv.com\n0523zp.com\n0527c.com\n0527car.com\n0527city.com\n0527lsw.com\n0527tao.com\n0527zp.com\n0530fangchan.com\n0531.com\n0531wt.com\n0532cate.com\n0532hq.com\n0532jiaozhou.com\n0534.com\n0535-0411.com\n0536home.com\n0536qiche.com\n0536qz.com\n0537qcw.com\n0537yz.com\n0537zp.com\n0538fc.com\n0538taian.com\n0543bbs.com\n0543fcw.com\n0543house.com\n0543hr.com\n0543jobs.com\n0543sem.com\n0543zxw.com\n054400.com\n0546fdc.com\n0550cw.com\n0550qcw.com\n055178.com\n0551fangchan.com\n0551ren.com\n0551up.com\n0551zhuang.com\n0552jie.com\n0553qcw.com\n0554coal.com\n0554news.com\n0554x.com\n0554zp.com\n0555cw.com\n0555fc.com\n0555qcw.com\n0555rcw.com\n0555yi.com\n0557100.com\n0557che.com\n0558.com\n0558t.com\n0559fc.com\n0561house.com\n0561life.com\n0562auto.com\n0563job.com\n0564abc.com\n0564job.com\n0564luan.com\n0564shw.com\n0565fc.com\n0566car.com\n0566fc.com\n0566fw.com\n0566job.com\n0567.com\n05701234.com\n057191.com\n0571car.com\n0571lkhs.com\n0572gb.com\n0572home.com\n0573rcw.com\n0573ren.com\n0573syedu.com\n0574bbs.com\n0574byedu.com\n0574yye.com\n0575.com\n0575bbs.com\n0575eshop.com\n0575j.com\n0575jzw.com\n0575lt.com\n0575rl.com\n0576fang.com\n0577hr.com\n0577job.com\n0577wzlf.com\n0578rencai.com\n0579818.com\n0579com.com\n0579fdc.com\n057yx.com\n0591job.com\n05927.com\n0593r.com\n0594.com\n0595rc.com\n0596cs.com\n0596fc.com\n0596lh.com\n0597.com\n0597car.com\n0597ok.com\n0597yd.com\n0598777.com\n0598rc.com\n0598yu.com\n05job.com\n05sun.com\n05wan.com\n05youxi.com\n0600.com\n063.com\n0631rc.com\n0634.com\n0635jia.com\n063yy.com\n0663auto.com\n0663job.com\n0671.com\n0685.com\n06game.com\n0701.com\n07073.com\n07073sy.com\n0710.com\n0710520.com\n0710fz.com\n0710hf.com\n0710rcw.com\n0710rencai.com\n0712f.com\n0712fang.com\n0713hb.com\n0713rcw.com\n0714.com\n0714job.com\n0715fc.com\n0716fw.com\n0716jl.com\n07177.com\n0719house.com\n0722fc.com\n0722fw.com\n0722h.com\n0724tx.com\n0725.com\n0728f.com\n0728h.com\n0728i.com\n0728zpw.com\n0730news.com\n0730qc.com\n0731520.com\n0731esf.com\n0731fdc.com\n0731jiaju.com\n0731job.com\n0731tg.com\n0732fc.com\n0734.com\n0734zpw.com\n0735.com\n07356.com\n07358.com\n0735jz.com\n0736.com\n0736fdc.com\n0736house.com\n0736rencai.com\n0737job.com\n0738fdc.com\n0738ld.com\n0738rc.com\n0739bbs.com\n0739fz.com\n073img.com\n073uu.com\n073wan.com\n073yx.com\n0745job.com\n0746yc.com\n0750f.com\n0750rc.com\n0752qc.com\n0754cars.com\n0754ok.com\n0755bzf.com\n0755car.com\n0755cits.com\n0755rc.com\n0756zx.com\n0757cfw.com\n0757chongkong.com\n0757fc.com\n0757rc.com\n0757zhaopin.com\n0759h.com\n0759home.com\n0759job.com\n0759lt.com\n0759u.com\n0759zhiye.com\n0760.com\n0760js.com\n0760jz.com\n0760rc.com\n076299.com\n0762home.com\n0762r.com\n076999.com\n0769auto.com\n0769che.com\n0769rc.com\n0769xw.com\n0771bc.com\n0771rc.com\n0772fang.com\n0772job.com\n0773web.com\n0775fcw.com\n0775fw.com\n0775jzw.com\n0775qc.com\n0776rc.com\n0791abc.com\n0791look.com\n0791quanquan.com\n0792c.com\n0792job.com\n0792rs.com\n0793.com\n0793p.com\n0794work.com\n0795gaoan.com\n0795rc.com\n0797rs.com\n07jm.com\n07ka.com\n07ly.com\n07ux.com\n0817ch.com\n0817f.com\n0817rc.com\n0818hr.com\n0818jy.com\n0818work.com\n0824.com\n0830e.com\n0830qc.com\n0831che.com\n0831home.com\n0832h.com\n0832mh.com\n0838.com\n0839fc.com\n0839zp.com\n0851gx.com\n0852job.com\n0852zpw.com\n0853fdc.com\n0853news.com\n0853rc.com\n0854job.com\n0855job.com\n0856job.com\n0857job.com\n0859job.com\n0891zp.com\n0898cx.com\n0898dichan.com\n0898f.com\n0898hq.com\n08cms.com\n08fang.com\n08px.com\n08zfw.com\n0902rc.com\n0909wan.com\n090job.com\n0912job.com\n0913car.com\n0914bbs.com\n0914cn.com\n0915auto.com\n0915home.com\n0915rc.com\n0916auto.com\n0916i.com\n0916rencai.com\n0916tea.com\n0917888.com\n094wan.com\n0951job.com\n09635.com\n0979news.com\n0991dj.com\n0991fc.com\n0997job.com\n099sky.com\n09ge.com\n0car0.com\n0duw.com\n100.com\n10000job.com\n10000link.com\n10000yao.com\n10000zy.com\n1000islandlake.com\n1000tuan.com\n1000z.com\n10010.com\n1001p.com\n100365.com\n100580.com\n10086gouji.com\n100autoshow.com\n100bt.com\n100chee.com\n100cs.com\n100fsc.com\n100jn.com\n100jnled.com\n100kk.com\n100ksw.com\n100lunwen.com\n100njz.com\n100ppi.com\n100shuai.com\n100t.com\n100tal.com\n100xhs.com\n100xiao.com\n100xuexi.com\n100yangsheng.com\n100yiyao.com\n100yue.com\n100zhuang.com\n1010jz.com\n10155.com\n101jiajiao.com\n101wo.com\n10333.com\n10339.com\n103wx.com\n105zx.com\n10628789.com\n1073.com\n1080t.com\n108jj.com\n10and9.com\n10fang.com\n10oa.com\n10s1.com\n10yan.com\n110.com\n1111.com\n11124.com\n11157.com\n11186.com\n1118yx.com\n111jz.com\n111ttt.com\n1122.com\n1122xyx.com\n114-0510.com\n11467.com\n114best.com\n114cbd.com\n114chn.com\n114huoche.com\n114ic.com\n114la.com\n114nba.com\n114nz.com\n114piaowu.com\n114px.com\n114study.com\n114xialingying.com\n114xueche.com\n114zhibo.com\n115.com\n11584.com\n115bc.com\n115img.com\n115kf.com\n116.com\n1166.com\n11665.com\n116yx.com\n11773.com\n1177you.com\n1179house.com\n1188.com\n118jiancai.com\n11919.com\n119g.com\n119hn.com\n119tx.com\n11chuangye.com\n11yeyou.com\n120-job.com\n120ask.com\n120askimages.com\n120gubing.com\n12114job.com\n12114rc.com\n1212wan.com\n121314.com\n121tianqi.com\n122park.com\n12306pk.com\n12333.com\n12333sb.com\n123456dj.com\n1234h.com\n1234kan.com\n1234wu.com\n1234xw.com\n12365auto.com\n123cha.com\n123huijia.com\n123ido.com\n123langlang.com\n123lvxing.com\n123tsg.com\n123yingyu.com\n123youhuo.com\n123ypw.com\n123zcyy.com\n12530.com\n12580.com\n12580xy.com\n125job.com\n126.com\n127q.com\n128rc.com\n128uu.com\n12999.com\n12chai.com\n12gang.com\n12ky.com\n12yao.com\n130wan.com\n1314gz.com\n131cc.com\n1322.com\n133998.com\n133jz.com\n1350135.com\n1360.com\n13688854328.com\n1377.com\n137home.com\n137wan.com\n138edu.com\n138jm.com\n138job.com\n138mr.com\n139.com\n1390130.com\n139931.com\n139cai.com\n139js.com\n139life.com\n139shop.com\n139yd.com\n139zhuti.com\n13cr.com\n13ddd.com\n13ejob.com\n13ie.com\n144yx.com\n1488.com\n148com.com\n14xf.com\n150z.com\n15153.com\n1518.com\n1518wan.com\n151wan.com\n1545ts.com\n156580.com\n15666.com\n15880.com\n1588yx.com\n159.com\n159cai.com\n15bl.com\n15gg.com\n15gift.com\n15hr.com\n15iacc.com\n15lu.com\n15sjw.com\n15too.com\n15ux.com\n15w.com\n160.com\n1617k.com\n161gg.com\n1626.com\n163.com\n1633.com\n1637.com\n163disk.com\n163gov.com\n163k.com\n163ns.com\n163yu.com\n164580.com\n1651ky.com\n1666.com\n166wan.com\n1688.com\n16888.com\n1688wan.com\n168cb.com\n168dc.com\n168hm.com\n168hs.com\n168job.com\n168liuxue.com\n168pd.com\n168xd.com\n168xiezi.com\n168yinhe.com\n169369.com\n16999.com\n169gold.com\n16cp.com\n16fan.com\n16good.com\n16house.com\n16kang.com\n16p.com\n16sucai.com\n16tz.com\n16u.com\n170u.com\n17173.com\n17173cdn.com\n17173ie.com\n1717kf.com\n1717pk.com\n1718001.com\n1718006.com\n1718china.com\n1718world.com\n171ju.com\n172xiaoyuan.com\n173.com\n1737game.com\n173daxue.com\n173eg.com\n173kt.com\n173pk.com\n173zsw.com\n17446.com\n175game.com\n175ha.com\n175kh.com\n175pt.com\n175wan.com\n176.com\n17611.com\n17673.com\n1773.com\n1773y.com\n178.com\n178178qp.com\n17888.com\n178good.com\n178yy.com\n178zmy.com\n179179.com\n1797wan.com\n179v.com\n179xizang.com\n17caifu.com\n17cma.com\n17coolz.com\n17daili.com\n17dm.com\n17fangte.com\n17fee.com\n17gai.com\n17guagua.com\n17heli.com\n17hihi.com\n17house.com\n17jita.com\n17k.com\n17kapai.com\n17liuxue.com\n17m3.com\n17maoyi.com\n17mcp.com\n17miyou.com\n17ms.com\n17oh.com\n17ps8.com\n17qzx.com\n17sucai.com\n17u.com\n17ugo.com\n17usoft.com\n17utt.com\n17wendao.com\n17xinghun.com\n17yy.com\n17zhuang.com\n17zwd.com\n180img.com\n180kids.com\n180mi.com\n18108.com\n18183.com\n1818hm.com\n183read.com\n1851688.com\n186it.com\n188.com\n188cyw.com\n188dm.com\n188fu.com\n189house.com\n189rc.com\n189share.com\n189store.com\n189yo.com\n18heyou.com\n18ladys.com\n18ph.com\n18qiang.com\n18report.com\n18touch.com\n18yl.com\n1905.com\n192job.com\n19687.com\n197c.com\n198526.com\n198du.com\n198game.com\n199it.com\n199youxi.com\n19lou.com\n19wan.com\n19yxw.com\n19zhan.com\n19zu.com\n1b2g.com\n1bd1.com\n1beng.com\n1d11.com\n1dancong.com\n1diaocha.com\n1f11.com\n1fabric.com\n1g31.com\n1gjh.com\n1haomeng.com\n1kejian.com\n1kepu.com\n1kkk.com\n1koreannews.com\n1linli.com\n1m3d.com\n1mall.com\n1mishu.com\n1n11.com\n1nongjing.com\n1nsou.com\n1o26.com\n1oo2.com\n1p1g.com\n1p365.com\n1peizai.com\n1ppt.com\n1qwe3r.com\n1shoucang.com\n1ting.com\n1ty.com\n1v1offcn.com\n1wwtx.com\n1y2y.com\n1youxi.com\n1zihua.com\n1zjob.com\n1zw.com\n2000888.com\n2001com.com\n200dy.com\n2016kaoyan.com\n201980.com\n202wan.com\n2046sheying.com\n2095114.com\n20uk.com\n21-cmjob.com\n21-part.com\n21-rent.com\n21-sun.com\n21-used.com\n2100book.com\n2114.com\n211600.com\n211lx.com\n212300.com\n2125.com\n21253.com\n2160.com\n2197079.com\n21af.com\n21c168.com\n21caas.com\n21cbh.com\n21cbr.com\n21ccnn.com\n21cn.com\n21cnimg.com\n21cnjy.com\n21cnlunwen.com\n21cp.com\n21dagong.com\n21dcw.com\n21dianchi.com\n21dianyuan.com\n21dnn.com\n21edu8.com\n21fengchao.com\n21food.com\n21hgjx.com\n21hh.com\n21hospital.com\n21hubei.com\n21hulian.com\n21ic.com\n21itjob.com\n21its.com\n21jrr.com\n21js.com\n21nowart.com\n21our.com\n21part.com\n21peitao.com\n21pw.com\n21rcw.com\n21rv.com\n21sb.com\n21sea.com\n21sew.com\n21shipin.com\n21so.com\n21spv.com\n21taiyang.com\n21tb.com\n21tyn.com\n21wanwan.com\n21wecan.com\n21xc.com\n21xsl.com\n21yod.com\n21yq.com\n2200book.com\n22086.com\n221400job.com\n22157.com\n221600job.com\n221700.com\n22197.com\n223you.com\n224200.com\n2243.com\n224600.com\n2258.com\n225s.com\n2265.com\n226531.com\n226y.com\n2280.com\n228cai.com\n2295.com\n2298.com\n22bw.com\n22edu.com\n22w.com\n2300sjz.com\n230jc.com\n2323u.com\n2323wan.com\n23255555.com\n233.com\n233000.com\n2344.com\n2345.com\n2345a.com\n2366.com\n23class.com\n23du.com\n23ks.com\n23ps.com\n23qcw.com\n23rencai.com\n246ys.com\n24k.com\n24k99.com\n25000li.com\n2500che.com\n2500sz.com\n253u.com\n255star.com\n25622.com\n25788.com\n258en.com\n25az.com\n25game.com\n25nc.com\n25pp.com\n25xz.com\n25yz.com\n263.com\n264006.com\n264g.com\n265.com\n265588.com\n2657.com\n26595.com\n265g.com\n265vv.com\n266wan.com\n2676.com\n26923.com\n26abc.com\n26lady.com\n271you.com\n2720668.com\n274500.com\n279wo.com\n27qq.com\n27xs.com\n28.com\n280.com\n285868.com\n2881.com\n288job.com\n289.com\n28jmw.com\n28ktv.com\n28sn.com\n28y.com\n28yun.com\n2cto.com\n2danji.com\n2dianban.com\n2ge8.com\n2hua.com\n2m2j.com\n2m3m.com\n2mjob.com\n2mould.com\n2pjob.com\n2uuzs.com\n3000f.com\n300cleaners.com\n301688.com\n302wan.com\n304t.com\n30556.com\n30buy.com\n30edu.com\n30gov.com\n30kp.com\n310tv.com\n310win.com\n311wan.com\n312168.com\n312tree.com\n313.com\n3131job.com\n313job.com\n3145.com\n3155.com\n315700.com\n3158.com\n3158yww.com\n315ad.com\n315che.com\n315city.com\n315hyw.com\n315img.com\n315mro.com\n315ok.com\n318918.com\n318yishu.com\n31alu.com\n31bag.com\n31bear.com\n31bee.com\n31boiler.com\n31bxg.com\n31byq.com\n31bzjx.com\n31cable.com\n31cf.com\n31cgw.com\n31chair.com\n31ddc.com\n31ddgj.com\n31dry.com\n31dt.com\n31expo.com\n31feed.com\n31fg.com\n31fish.com\n31fj.com\n31fluid.com\n31food.com\n31fsbw.com\n31gcjx.com\n31gear.com\n31glass.com\n31glasses.com\n31hgyq.com\n31hqyp.com\n31hrq.com\n31huiyi.com\n31hwyp.com\n31hzp.com\n31jc.com\n31jf.com\n31jgj.com\n31jhsb.com\n31jiaju.com\n31jmw.com\n31jxw.com\n31light.com\n31lp.com\n31mada.com\n31md.com\n31metals.com\n31mjg.com\n31mold.com\n31myhome.com\n31nk.com\n31oil.com\n31print.com\n31pump.com\n31rcw.com\n31rzp.com\n31seal.com\n31shipin.com\n31shoes.com\n31sjjx.com\n31spcar.com\n31spjx.com\n31taoci.com\n31tjj.com\n31toy.com\n31tqw.com\n31weld.com\n31wenju.com\n31wj.com\n31wood.com\n31xf.com\n31xjd.com\n31xm.com\n31yj.com\n31yr.com\n31yrhg.com\n31ysj.com\n31yyqd.com\n31zj.com\n31zscl.com\n31zzw.com\n320106.com\n320921.com\n3234.com\n323g.com\n32ka.com\n32wan.com\n3310.com\n3323.com\n33383338.com\n333xin.com\n33456.com\n33519.com\n3366.com\n3366img.com\n337g.com\n337y.com\n3393.com\n3399.com\n33dvd.com\n33erwo.com\n33lc.com\n33ly.com\n33trip.com\n342225.com\n3454.com\n34job.com\n35.com\n35313.com\n3533.com\n356ys.com\n358wan.com\n35941.com\n35metal.com\n35pic.com\n35q.com\n35tool.com\n35wl.com\n35yao.com\n35you.com\n35zhe.com\n3600t.com\n360aiyi.com\n360buy.com\n360buyimg.com\n360changshi.com\n360che.com\n360doo.com\n360eol.com\n360gann.com\n360gxi.com\n360js.com\n360junshi.com\n360kad.com\n360kan.com\n360kxr.com\n360mobao.com\n360qc.com\n360qikan.com\n360safe.com\n360sky.com\n360top.com\n360tpcdn.com\n360uu.com\n360wyw.com\n360xzl.com\n360youtu.com\n3618med.com\n361games.com\n361sport.com\n364000.com\n365500.com\n365724.com\n36578.com\n36588zs.com\n365a8.com\n365ajw.com\n365anfang.com\n365art.com\n365auto.com\n365azw.com\n365bj.com\n365cgw.com\n365exam.com\n365groups.com\n365guipian.com\n365haofang.com\n365hf.com\n365jilin.com\n365mo.com\n365pk.com\n365qilu.com\n365rili.com\n365soso.com\n365ta.com\n365tkt.com\n365tlf.com\n365webcall.com\n365wj.com\n365zhanlan.com\n365zhaosheng.com\n365zhongzi.com\n365zl.com\n3661.com\n36683.com\n366health.com\n368tea.com\n369.com\n36dj.com\n36dsj.com\n36kr.com\n36krcnd.com\n36sfw.com\n36tr.com\n36zm.com\n37.com\n371.com\n37168.com\n371love.com\n371weiyi.com\n37201.com\n3737.com\n3737k.com\n373f.com\n373house.com\n373w.com\n375ba.com\n3761.com\n376che.com\n3777w.com\n37937.com\n3798.com\n37cs.com\n37cu.com\n37cy.com\n37k.com\n37nixi.com\n37pk49.com\n37wan.com\n37wanimg.com\n37wanwan.com\n37youwan.com\n37youyou.com\n3839.com\n383yx.com\n387a.com\n38xf.com\n3911.com\n391k.com\n39269222.com\n3937.com\n3949000.com\n3987.com\n39kf.com\n39txt.com\n39yss.com\n39yst.com\n39ysw.com\n3apaint.com\n3b2o.com\n3bwx.com\n3chao.com\n3cjob.com\n3conline.com\n3d66.com\n3ddmjob.com\n3dfc.com\n3dkezhan.com\n3dmgame.com\n3dtaiyuan.com\n3dtaomo.com\n3etravel.com\n3fantizi.com\n3g210.com\n3g2y.com\n3ghuashang.com\n3h3.com\n3hrc.com\n3hsh.com\n3j3f.com\n3jgo.com\n3jrx.com\n3jy.com\n3kfw.com\n3lian.com\n3lsc.com\n3need.com\n3nong.com\n3qhouse.com\n3s001.com\n3visual3.com\n3wmas.com\n3wmm.com\n3xgd.com\n3yx.com\n400516.com\n4006666688.com\n4006713114.com\n4006777711.com\n4006787252.com\n4006888808.com\n4006hr.com\n4008000000.com\n4008208040.com\n4008885166.com\n400job.com\n400jz.com\n40407.com\n404wan.com\n405400.com\n4065.com\n411au.com\n4124.com\n4136.com\n41717.com\n41cs.com\n42144.com\n432520.com\n4355.com\n4362.com\n437900.com\n438g.com\n4399.com\n43999yx.com\n4399dmw.com\n4399er.com\n4399j.com\n4399pk.com\n4399vv.com\n43house.com\n43nv.com\n44755.com\n44957.com\n44hr.com\n44pq.com\n45451.com\n45575.com\n457000.com\n458000.com\n45fan.com\n46sj.com\n4738.com\n4765.com\n47yun.com\n4806549.com\n488u.com\n4891111.com\n4908.com\n49358.com\n49369.com\n4997.com\n49you.com\n4aqq.com\n4dmil.com\n4dtime.com\n4edy.com\n4gfang.com\n4gfy.com\n4ggamer.com\n4jxl.com\n4lou.com\n4lzx.com\n4plmarket.com\n4sjob.com\n4zhe.com\n500.com\n500365.com\n5004.com\n500cache.com\n500wan.com\n502pk.com\n5054399.com\n505wan.com\n5068.com\n50769.com\n508job.com\n51.com\n51-cf.com\n510.com\n510560.com\n5105wan.com\n5113178.com\n5118114.com\n5118wan.com\n511wan.com\n5120.com\n51240.com\n512auto.com\n512ms.com\n512pk.com\n512play.com\n512test.com\n512zp.com\n513cc.com\n514193.com\n514200.com\n5151home.com\n5151sc.com\n5151xqg.com\n5155wan.com\n5156edu.com\n5156yuwen.com\n51595.com\n51643.com\n516lyw.com\n5173.com\n5173766.com\n5173cdn.com\n51766.com\n5179.com\n517best.com\n517dv.com\n517ee.com\n517gf.com\n517huwai.com\n517japan.com\n517sc.com\n517wjw.com\n517zzw.com\n5184.com\n5188b2b.com\n518ad.com\n518fang.com\n519d.com\n51able.com\n51anf.com\n51app.com\n51aspx.com\n51atgc.com\n51auto.com\n51aya.com\n51bafu.com\n51banban.com\n51baocai.com\n51bdks.com\n51bi.com\n51buy.com\n51bxg.com\n51cacg.com\n51charge.com\n51chudui.com\n51chuji.com\n51chuli.com\n51ci.com\n51cm.com\n51cnhr.com\n51coma.com\n51comp.com\n51credit.com\n51cto.com\n51dc.com\n51dianlan.com\n51ditu.com\n51duide.com\n51duoying.com\n51dzw.com\n51e-online.com\n51edu.com\n51etong.com\n51ey.com\n51f.com\n51fanli.com\n51fdc.com\n51fzflw.com\n51fzh.com\n51g3.com\n51gaifang.com\n51garlic.com\n51gdrc.com\n51ggwu.com\n51grb.com\n51hanhua.com\n51haojob.com\n51hbjob.com\n51hcw.com\n51hejia.com\n51htxw.com\n51huoche.com\n51idc.com\n51iec.com\n51ielts.com\n51img1.com\n51img3.com\n51jam.com\n51jb.com\n51jiameng.com\n51jiaxiao.com\n51jiemeng.com\n51jishu.com\n51job.com\n51jobcdn.com\n51jrjob.com\n51junshi.com\n51kaihui.com\n51kaishan.com\n51kids.com\n51kiosk.com\n51kqn.com\n51kybg.com\n51labour.com\n51lama.com\n51lenovo.com\n51lieyou.com\n51liucheng.com\n51live.com\n51lunwen.com\n51lvsewang.com\n51lxrc.com\n51meishu.com\n51mingche.com\n51mingren.com\n51mobilejob.com\n51mole.com\n51nacs.com\n51nb.com\n51neixun.com\n51netu.com\n51nianheji.com\n51nuoqi.com\n51offer.com\n51office.com\n51pigai.com\n51pinwei.com\n51pla.com\n51pot.com\n51ps.com\n51qc.com\n51qingjiao.com\n51qinxue.com\n51rattan.com\n51rc.com\n51rencai.com\n51report.com\n51rrp.com\n51scb.com\n51sdjob.com\n51seer.com\n51shengyue.com\n51sheyuan.com\n51shiyan.com\n51shoushi.com\n51shworkshops.com\n51sjyx.com\n51sole.com\n51soma.com\n51stujob.com\n51sxue.com\n51sya.com\n51t.com\n51talk.com\n51talkenglish.com\n51taonan.com\n51taoshi.com\n51taoyang.com\n51tbl.com\n51testbook.com\n51tie.com\n51toefl.com\n51touch.com\n51tujia.com\n51tuzhi.com\n51tz.com\n51uuo.com\n51value.com\n51vv.com\n51wan.com\n51wf.com\n51wp.com\n51xly.com\n51xuesheji.com\n51yala.com\n51ych.com\n51yes.com\n51yey.com\n51yilu.com\n51yoho.com\n51you.com\n51youcai.com\n51yougo.com\n51yuding.com\n51yys.com\n51zhijia.com\n51zhu.com\n51zhucai.com\n51zjob.com\n51zjxm.com\n51zlwx.com\n51znt.com\n51zr.com\n51zsjc.com\n51zsrcw.com\n51ztzj.com\n51zuoche.com\n51zupu.com\n51zx.com\n52.com\n520apk.com\n520bn.com\n520cpw.com\n520e3e4.com\n520tianmei.com\n520ux.com\n520wawa.com\n520xy8.com\n52173.com\n521auto.com\n521che.com\n521g.com\n522g.com\n52372.com\n52396.com\n523che.com\n523fang.com\n5253.com\n525jmall.com\n525zb.com\n526wan.com\n527k.com\n527pk.com\n5281.com\n52954.com\n52article.com\n52bar.com\n52bmw.com\n52che.com\n52chizhou.com\n52ciqi.com\n52design.com\n52djq.com\n52dopod.com\n52e-mail.com\n52ezx.com\n52fangzi.com\n52foto.com\n52funs.com\n52fuqing.com\n52game.com\n52guoman.com\n52hardware.com\n52hc.com\n52huapai.com\n52huaqiao.com\n52hxw.com\n52ij.com\n52kaoyan.com\n52liezheng.com\n52liuzhou.com\n52miji.com\n52njl.com\n52ph.com\n52pk.com\n52player.com\n52psxt.com\n52rd.com\n52shehua.com\n52solution.com\n52steel.com\n52suda.com\n52swine.com\n52udl.com\n52waha.com\n52wubi.com\n52wuhan.com\n52wuling.com\n52xiangyou.com\n52xiaohuahui.com\n52xsj.com\n52xyz.com\n52ykjob.com\n52youju.com\n52youxue.com\n52z.com\n52zhushan.com\n52zikao.com\n531springs.com\n533.com\n5336.com\n538538.com\n5399.com\n53gou.com\n53info.com\n53kf.com\n54086.com\n54114.com\n5433.com\n54535.com\n54game.com\n54hcz.com\n54heb.com\n54jj.com\n54job.com\n54op.com\n54paike.com\n54pc.com\n54qnr.com\n54xsr.com\n54yo.com\n54youshi.com\n55.com\n55167.com\n55188.com\n5523.com\n55255.com\n553.com\n553000.com\n553you.com\n5555d.com\n55577.com\n5566wan.com\n556wan.com\n5577.com\n5588yx.com\n5599.com\n55bbs.com\n55gps.com\n55it.com\n55la.com\n55tuan.com\n55tuanimg.com\n55usedcar.com\n55you.com\n55zm.com\n56.com\n560731.com\n56135.com\n56156.com\n5617.com\n561hr.com\n562wan.com\n56360.com\n56380.com\n563wan.com\n5652.com\n566.com\n566855.com\n5669.com\n566job.com\n5676.com\n5678job.com\n567go.com\n567job.com\n569.com\n5694.com\n56bbw.com\n56golf.com\n56img.com\n56iq.com\n56uu.com\n57023.com\n57315.com\n5757wan.com\n576.com\n57616.com\n576rcw.com\n576tv.com\n5778.com\n577fang.com\n57821.com\n57go.com\n57nepal.com\n57px.com\n57tbs.com\n57tibet.com\n58.com\n581518.com\n582hr.com\n585.com\n5858.com\n586jz.com\n5874.com\n587766.com\n588qh.com\n58bama.com\n58cyjm.com\n58dm.com\n58fenlei.com\n58food.com\n58game.com\n58guakao.com\n58gzw.com\n58hukou.com\n58pem.com\n58pic.com\n58player.com\n58spx.com\n58wan.com\n58xzz.com\n5911.com\n591hx.com\n591wed.com\n591wy.com\n5925car.com\n592xyx.com\n593yx.com\n5959.com\n595wan.com\n596fc.com\n597.com\n5973.com\n597mm.com\n597rcw.com\n598rc.com\n599z.com\n59hq.com\n59wujin.com\n5aaa.com\n5acbd.com\n5aicp.com\n5aipai.com\n5ajob.com\n5alz.com\n5article.com\n5aspx.com\n5biying.com\n5booking.com\n5bzx.com\n5d6d.com\n5dmx.com\n5douy.com\n5ds.com\n5est.com\n5etv.com\n5fen.com\n5fwan.com\n5g.com\n5hoom.com\n5i5aj.com\n5i5j.com\n5i9u.com\n5icbs.com\n5ijr.com\n5ikfc.com\n5ipatent.com\n5its.com\n5itx.com\n5iucn.com\n5iwl.com\n5iyq.com\n5izhuangban.com\n5jcao.com\n5jss.com\n5jzp.com\n5kbox.com\n5khouse.com\n5ktd.com\n5lux.com\n5muu.com\n5nd.com\n5nexus.com\n5o5k.com\n5qwan.com\n5sai.com\n5u588.com\n5ucom.com\n5utaoke.com\n5w.com\n5wenxue.com\n5x1job.com\n5xueba.com\n5ydj.com\n5ygame.com\n5yi.com\n5zrc.com\n6000job.com\n600258.com\n600hr.com\n600jp.com\n602.com\n606job.com\n60886666.com\n60junshi.com\n60malaysia.com\n61.com\n6103.com\n6111cq.com\n61166.com\n611wan.com\n612.com\n612345.com\n6164.com\n61658.com\n616wan.com\n6175.com\n6188.com\n6188cp.com\n618hr.com\n61baobao.com\n61bbw.com\n61bus.com\n61diy.com\n61duocai.com\n61ertong.com\n61f.com\n61flash.com\n61hr.com\n61mami.com\n61meiwen.com\n61new.com\n61tg.com\n61un.com\n61ux.com\n61xue.com\n628.com\n628go.com\n62b2b.com\n63063.com\n63hr.com\n63wan.com\n64365.com\n65.com\n6528.com\n654buy.com\n655u.com\n655wan.com\n65gz.com\n65singapore.com\n65wan.com\n660wan.com\n66163.com\n6617.com\n661d.com\n6637.com\n66378.com\n6655.com\n6665.com\n666ccc.com\n6676.com\n6677bank.com\n6681.com\n66880.com\n6688wan.com\n668news.com\n669art.com\n66diqiu.com\n66hao315.com\n66house.com\n66lv.com\n66qhd.com\n66rpg.com\n66ruian.com\n66tuzhi.com\n66u.com\n66wc.com\n66weibo.com\n66wl.com\n66wz.com\n66xue.com\n66you.com\n66zhuang.com\n67.com\n6711.com\n6777111.com\n677game.com\n678114.com\n6789123.com\n6789g.com\n6789uu.com\n679wan.com\n680.com\n6816.com\n68211.com\n685.com\n6868g.com\n688n.com\n68apk.com\n68flash.com\n68wan.com\n68zhuan.com\n6949.com\n6969g.com\n69js.com\n69kan.com\n69xiu.com\n69zw.com\n6c6.com\n6ddd.com\n6eat.com\n6guilin.com\n6jk.com\n6luling.com\n6niu.com\n6pingm.com\n6renyou.com\n6rooms.com\n6wan.com\n6xiu.com\n6zrc.com\n7-hk.com\n70.com\n700yx.com\n703804.com\n7060.com\n70e.com\n70god.com\n70yx.com\n71096.com\n711g.com\n7127.com\n7160.com\n717199.com\n718cfw.com\n7192.com\n71gq.com\n71lady.com\n71peixun.com\n71study.com\n71zs.com\n72177.com\n7230.com\n726100.com\n72622.com\n726ux.com\n727.com\n7273.com\n72ce.com\n72dj.com\n72g.com\n72up.com\n72xuan.com\n731c.com\n733dm.com\n737.com\n7374.com\n7377.com\n738car.com\n7399.com\n73994.com\n739hr.com\n7474.com\n7476.com\n747wan.com\n74cms.com\n7599.com\n75pk.com\n761.com\n7614.com\n762rc.com\n7651.com\n766.com\n766cn.com\n766z.com\n7676.com\n76hai.com\n76ju.com\n76yc.com\n7706.com\n771wan.com\n7723.com\n7729.com\n77313.com\n774g.com\n7755.com\n77745.com\n777fly.com\n777zp.com\n778669.com\n77883.com\n7789.com\n7799520.com\n779you.com\n77hh.com\n77hunjia.com\n77jz.com\n77l.com\n77music.com\n77nt.com\n77pvp.com\n77vcd.com\n77y8.com\n77zp.com\n77zxw.com\n7808.com\n78187.com\n7878.com\n78793.com\n787y.com\n7881.com\n788hr.com\n789gg.com\n789hi.com\n78baby.com\n78oa.com\n78zph.com\n79.com\n7937.com\n7940.com\n7979la.com\n7979u.com\n797sun.com\n798edu.com\n798play.com\n798yx.com\n798zxw.com\n7999wan.com\n799job.com\n79abc.com\n79w.com\n7acg.com\n7ahr.com\n7c.com\n7cha.com\n7czw.com\n7dajiao.com\n7dapei.com\n7djob.com\n7edown.com\n7fgame.com\n7h365.com\n7hcn.com\n7hhome.com\n7hon.com\n7iaoshou.com\n7k7k.com\n7kcc.com\n7l7l.com\n7lean.com\n7mato.com\n7mgame.com\n7mok.com\n7po.com\n7sgsoft.com\n7tyy.com\n7uyn.com\n7vk.com\n7wenta.com\n7xdown.com\n7xz.com\n7y7.com\n7yueji.com\n7zhan.com\n7zzy.com\n8000ad.com\n8008200958.com\n800fc.com\n800hr.com\n800pai.com\n800pharm.com\n8014.com\n8020rc.com\n802wan.com\n804.com\n80710.com\n8080wan.com\n808707.com\n8090.com\n8090kk.com\n8090vision.com\n8090xx.com\n8090yx.com\n8090yxs.com\n80tian.com\n80xb.com\n81256.com\n81499.com\n8158.com\n818.com\n818222.com\n81874.com\n81junhun.com\n81tech.com\n82222919.com\n82341.com\n8234567.com\n826.com\n8264.com\n8265.com\n826wan.com\n828g.com\n82b2b.com\n82yx.com\n830836.com\n83133.com\n83480900.com\n83838.com\n83923888.com\n844a.com\n8477.com\n84g.com\n84ju.com\n84ny.com\n85118.com\n85277777.com\n852wan.com\n8558.com\n855you.com\n85814.com\n860527.com\n862sc.com\n86516.com\n86838683.com\n8684.com\n86angel.com\n86auto.com\n86che.com\n86chemnet.com\n86control.com\n86djy.com\n86echr.com\n86fsp.com\n86garden.com\n86hh.com\n86jnjp.com\n86jobs.com\n86jzjob.com\n86kx.com\n86kyjob.com\n86mdo.com\n86name.com\n86nb.com\n86office.com\n86pla.com\n86ps.com\n86qc.com\n86sb.com\n86signs.com\n86sme.com\n86techan.com\n86tree.com\n86wan.com\n86wind.com\n86xinxi.com\n87050.com\n87188718.com\n8721.com\n8783.com\n8787g.com\n8791.com\n87dailian.com\n87money.com\n87pk.com\n88.com\n88055116.com\n880735.com\n88119966.com\n8813yx.com\n88152.com\n8825.com\n8864.com\n88680.com\n887g.com\n887you.com\n8884321.com\n889xp.com\n88dj.com\n88gogo.com\n88gs.com\n88j84.com\n88jh.com\n88kuka.com\n88lan.com\n88mh.com\n88order.com\n88tc.com\n88yn.com\n88yoo.com\n88yx.com\n88yz.com\n88zf.com\n890pk.com\n89178.com\n89902511.com\n8999wan.com\n89ws.com\n89xd.com\n8breed.com\n8cheche.com\n8dn.com\n8edy.com\n8fkd.com\n8gl.com\n8gongzi.com\n8l8e.com\n8le8le.com\n8lnet.com\n8mhh.com\n8yee.com\n8ztc.com\n900gold.com\n90576.com\n90912.com\n90fer.com\n90he.com\n90tiyu.com\n91.com\n91120.com\n9117hi.com\n911xs.com\n911you.com\n913u.com\n915.com\n9158.com\n917.com\n9188.com\n9188wan.com\n918jin.com\n918s.com\n9191mr.com\n9199.com\n91ac.com\n91accp.com\n91aiyx.com\n91b2b.com\n91baiju.com\n91cha.com\n91cps.com\n91cye.com\n91danji.com\n91feizhuliu.com\n91goodschool.com\n91haojob.com\n91ielts.com\n91jiafang.com\n91jm.com\n91jmw.com\n91job.com\n91jsj.com\n91lx.com\n91metal.com\n91office.com\n91px.com\n91rb.com\n91rencai.com\n91spj.com\n91student.com\n91toefl.com\n91town.com\n91wan.com\n91weile.com\n91xbkm.com\n91zhongkao.com\n9211.com\n921rc.com\n92296.com\n925pk.com\n927953.com\n927vip.com\n92913.com\n92ay.com\n92gzc.com\n92ha.com\n92mp.com\n92sns.com\n92wudao.com\n92wy.com\n92you.com\n92zc.com\n9351.com\n9355.com\n9377.com\n93pk.com\n93rc.com\n93tyy.com\n94176.com\n9453job.com\n94656.com\n9466.com\n9487.com\n94rc.com\n95095.com\n95191.com\n951it.com\n9527baby.com\n9527lady.com\n955113.com\n9553.com\n95572.com\n9564.com\n9588.com\n958shop.com\n9595wan.com\n95gq.com\n95px.com\n960755.com\n960rc.com\n962013.com\n9637.com\n96520.com\n96567.com\n96580.com\n966.com\n9666sr.com\n966733.com\n9669.com\n969g.com\n96ak.com\n96hq.com\n96pk.com\n96scsh.com\n96u.com\n9724.com\n973.com\n9777wan.com\n9787.com\n97973.com\n9797ly.com\n97ba.com\n97ic.com\n97jz.com\n97ls.com\n97wanle.com\n97zm.com\n98523.com\n98654.com\n987jy.com\n987k.com\n98892.com\n988yx.com\n9891.com\n98nba.com\n98player.com\n98ps.com\n98wine.com\n98znz.com\n99.com\n99114.com\n99166.com\n992you.com\n9939.com\n99425.com\n99447.com\n9949.com\n996.com\n9966333.com\n99809.com\n999.com\n9991.com\n999120.com\n999ask.com\n999lyk.com\n999wan.com\n99ashw.com\n99bill.com\n99cad.com\n99cfw.com\n99danji.com\n99fang.com\n99fund.com\n99hots.com\n99inf.com\n99jee.com\n99jianzhu.com\n99jxw.com\n99leba.com\n99mc.com\n99qh.com\n99qumingzi.com\n99rfid.com\n99sjyx.com\n99sushe.com\n99wed.com\n99xcs.com\n99xr.com\n99xyx.com\n99ys.com\n99yx.com\n99zihua.com\n99zuowen.com\n9aoduo.com\n9ask.com\n9ban.com\n9buys.com\n9che.com\n9chew.com\n9chun.com\n9cka.com\n9ddf.com\n9fbank.com\n9fzs.com\n9hello.com\n9hiwan.com\n9ht.com\n9hyou.com\n9i2s.com\n9ihome.com\n9ijia.com\n9ijm.com\n9ijr.com\n9ist.com\n9jcw.com\n9juren.com\n9jut.com\n9jwan.com\n9k9k.com\n9k9k99k.com\n9ku.com\n9miao.com\n9ria.com\n9sky.com\n9suv.com\n9to.com\n9twan.com\n9u.com\n9u8u.com\n9upk.com\n9v8v.com\n9vwan.com\n9wan.com\n9xiqi.com\n9xwang.com\n9yaocn.com\n9ye.com\n9you.com\n9zhen.com\n9zsb.com\na0598.com\na0816.com\na0bi.com\na21yishion.com\na22.com\na5588.com\na67.com\na688888.com\na8888.com\na9188.com\na963.com\na9jj.com\na9soft.com\na9vg.com\naan5.com\naatuzhi.com\nabab.com\nabang.com\nabc788.com\nabcache.com\nabcdao.com\nabchina.com\nabiz.com\nablesky.com\naccgame.com\naccorhotels.com\nacdorm.com\nacgmall.com\nacgwan.com\nacs86.com\nad189.com\nad63.com\naddpv.com\nadhhouse.com\nadjol.com\nadjyc.com\nadmaimai.com\nadmin10000.com\nadmin5.com\nadmin6.com\nadminxy.com\nadobe.com\nadquan.com\nadsage.com\nadsame.com\nadtchrome.com\nadunioncode.com\nadyun.com\naeenets.com\naf360.com\nafjk.com\nafjob88.com\nafnhk.com\naft888.com\nafuchina.com\nafuzg.com\nafwing.com\nafzhan.com\nag365.com\nagrisg.com\nagrodt.com\nagrofairs.com\nagrofed.com\nagronf.com\nagronj.com\nagrorc.com\nagrosc.com\nagrosg.com\nagrowsw.com\nagroxq.com\nagroyl.com\nah3nong.com\nahauto.com\nahbzfdc.com\nahbztv.com\nahcar.com\nahchanyi.com\nahctc.com\nahdznews.com\nahfeixi.com\nahgame.com\nahglj.com\nahhntz.com\nahhome.com\nahhouse.com\nahhzl.com\nahjdq.com\nahjia.com\nahjiaju.com\nahjtxx.com\nahlife.com\nahljnews.com\nahlongre.com\nahlottery.com\nahlsg.com\nahlydc.com\nahnxs.com\nahsalt.com\nahscb.com\nahsjxjy.com\nahsouche.com\nahss168.com\nahssnews.com\nahswine.com\nahszjob.com\nahtarena.com\nahtrader.com\nahwjnews.com\nahzp.com\nai0513.com\naibala.com\naibang.com\naibangjuxin.com\naibeiwang.com\naibo123.com\naicai.com\naicaicdn.com\naicairen.com\naicarzu.com\naicdn.com\naicunfu.com\naidigong.com\naidonghai.com\naifang.com\naifanggou.com\naifangke.com\naifcdn.com\naifeipin.com\naifengjie.com\naifmb.com\naigexing.com\naigo.com\naigounet.com\naihami.com\naihuaan.com\naihuaju.com\naiimg.com\naijunwang.com\naik120.com\naiketour.com\naikuirui.com\naili.com\nailiuwa.com\nailushan.com\nailvxing.com\naimuju.com\naipai.com\naipiaoke.com\naipingxiang.com\naipintuan.com\naiqin88.com\nairchinagroup.com\nairjipiao.com\nairmate-china.com\nairmb.com\naisbeijing.com\naishengri.com\naisy.com\nait123.com\naitaoad.com\naitingwang.com\naituan.com\naituwo.com\naiutrip.com\naiwanyizu.com\naiwou.com\naixingpin.com\naixueche.com\naiyeyou.com\naiyidu.com\naiyijob.com\naiyingli.com\naiyiqu.com\naiyouxi.com\naiyuncheng.com\naizhan.com\naizhishang.com\naizongyi.com\najbox.com\najbtv.com\najkcdn.com\najkimg.com\najwang.com\nakangdi.com\nakdanji.com\nakjunshi.com\naksrc.com\naksxw.com\nal93.com\naladingyidong.com\nali213.com\nalibaba.com\nalibado.com\nalibbw.com\nalibole.com\nalibuybuy.com\nalicdn.com\nalidanji.com\naliexpress.com\nalihuahua.com\nalihz.com\naliimg.com\naliloan.com\nalimama.com\nalipay.com\nalipayobjects.com\naliresearch.com\nalisoft.com\naliunicorn.com\nalivv.com\nalixixi.com\naliyiba.com\naliyun.com\naliyuncdn.com\naliyuncs.com\nallallyes.com\nallbrightlaw.com\nallcates.com\nallfang.com\nalltriple.com\nallyes.com\naltxw.com\nalu1886.com\nalwindoor.com\nalwooo.com\nalxw.com\nalyisheng.com\namannisha.com\namaomb.com\namap.com\nambchina.com\namerealtygroup.com\nami001.com\nampcn.com\namutong.com\nandaike.com\nanfan.com\nanfensi.com\nangeeks.com\nangelyeast.com\nanguanjia.com\nanhuaw.com\nanhuinews.com\nanjia.com\nanjiala.com\nanjian.com\nanjirencai.com\nanjuke.com\nanjukestatic.com\nankangs.com\nankangwang.com\nanqingonline.com\nanqu.com\nanquan365.com\nanquanbao.com\nanquanren.com\nanquanshi.com\nanquye123.com\nanruan.com\nansteelgroup.com\nanting.com\nanxi.com\nanxin.com\nanxinews.com\nanxinwh.com\nanxiw.com\nany2000.com\nanyangedu.com\nanychem.com\nanyisheng.com\nanymacro.com\nanzbc.com\nanzhi.com\nanzhuo2.com\nanzhuostore.com\nanzow.com\nanzuche.com\naoaob.com\naobi.com\naobosoft.com\naodi.com\naodiango.com\naofenglu.com\naojiyouxue.com\naojiyuke.com\naokang.com\naolaituan.com\naoliday.com\naooshe.com\naoqi168.com\naoshitang.com\naoshu.com\naosoo.com\naotian.com\naotudq.com\naowin.com\naoya-hk.com\naoyou.com\naoyuyj.com\nap88.com\napendi.com\napetdog.com\napinpai.com\napk3g.com\napk90.com\napkbus.com\napkol.com\napkyx.com\napkzu.com\napoints.com\napp111.com\napp17.com\napparelsos.com\nappchina.com\nappdp.com\napper8.com\nappgame.com\nappinn.com\nappjzy.com\napple.com\nappvv.com\nappying.com\naptchina.com\napusic.com\naq365.com\naqapk.com\naqbbw.com\naqioo.com\naqqiche.com\naqqx.com\naqrczp.com\naqrenren.com\naqtg.com\naqtour.com\naqwblm.com\naqzpw.com\naqzyzx.com\naringhb.com\narkoo.com\narmystar.com\narpun.com\nart-ba-ba.com\nart-child.com\nart-liuxue.com\nart-zj.com\nart139.com\nart456.com\nartddu.com\nartebuy.com\nartgoin.com\nartguangxi.com\narthoop.com\narting365.com\nartjingya.com\nartohe.com\nartohes.com\nartrade.com\nartsbuy.com\nartweekip.com\nartxun.com\nasdf37.com\naseantradecenter.com\nasgajj.com\nashsh.com\nasiabt.com\nasiachinachina.com\naskci.com\naskt7.com\naslzw.com\nasp168.com\nasp300.com\naspirecn.com\naspjzy.com\naspoo.com\nasqql.com\nasscb.com\nasuswork.com\nat188.com\nataozx.com\nataw-art.com\natobo.com\natpanel.com\nauak.com\naudio160.com\nauditcn.com\nausingroup.com\nausinvisa.com\naustargroup.com\nauto-made.com\nauto0722.com\nauto0754.com\nauto0760.com\nauto0768.com\nauto18.com\nauto318.com\nauto328.com\nauto373.com\nautobaidu.com\nautobaojun.com\nautochina360.com\nautodg.com\nautoho.com\nautohunan.com\nautono1.com\nautosup.com\nautowj.com\nauugame.com\nauyou.com\nav-window.com\nav001.com\nav010.com\nav118.com\navzq.com\naw99.com\nawotuan.com\nax597.com\naxatp.com\naxjlxh.com\naxmro.com\naxmw.com\naygjj.com\nayhsnm.com\nayican.com\nayijx.com\nayjewelry.com\nayrbs.com\nayrc.com\nayu100.com\nayyx.com\nb-tea.com\nb2005.com\nb2b-1.com\nb2b110.com\nb2b168.com\nb2b179.com\nb2bfenlei.com\nb2bgujian.com\nb2bhs.com\nb2bic.com\nb2bkk.com\nb2bmy.com\nb2bvip.com\nb2tong.com\nb5m.com\nba1314.com\nbab720.com\nbababaike.com\nbababian.com\nbabai.com\nbabakk.com\nbabapi.com\nbabeltime.com\nbaby-edu.com\nbaby0515.com\nbaby611.com\nbaby868.com\nbabydao.com\nbabytoo.com\nbabytree.com\nbabytreeimg.com\nbacic5i5j.com\nbadao37.com\nbag-hr.com\nbagsnet.com\nbai58.com\nbaibaidu.com\nbaicai.com\nbaicaolu.com\nbaicheng.com\nbaicheng360.com\nbaicmotor.com\nbaidajob.com\nbaidu.com\nbaiducontent.com\nbaiduhm.com\nbaidustatic.com\nbaiduyy.com\nbaietu.com\nbaifendian.com\nbaifubao.com\nbaihe.com\nbaiherc.com\nbaihuabaiyou.com\nbaijia520.com\nbaike.com\nbaike126.com\nbailitop.com\nbaima.com\nbaimao.com\nbaimei.com\nbaimin.com\nbainawang.com\nbaipaopao.com\nbaipu365.com\nbaishan.com\nbaishibaike.com\nbaishuiapple.com\nbaitianinfo.com\nbaitugu.com\nbaiwanzhan.com\nbaixing.com\nbaixinger.com\nbaixingjd.com\nbaixingjob.com\nbaiyinjg.com\nbaiyintouzi.com\nbaiyjk.com\nbaiyou100.com\nbaiyunpiaopiao.com\nbaizhuwang.com\nbamaol.com\nbamatea.com\nbamboo18.com\nbamboochar.com\nbamuyu.com\nbanbaowang.com\nbanbijiang.com\nbangboer.com\nbangexam.com\nbanggo.com\nbangongzs.com\nbangzaizai.com\nbangzhu123.com\nbanjiajia.com\nbank-of-china.com\nbankcomm.com\nbankhr.com\nbanklilv.com\nbanknotestudy.com\nbankofchina.com\nbankofshanghai.com\nbanksteel.com\nbanma.com\nbanwojia.com\nbanyouguoji.com\nbao21.com\nbaobao001.com\nbaobao18.com\nbaobao88.com\nbaobaohua.com\nbaobaomm.com\nbaobei360.com\nbaobeigou.com\nbaobeihr.com\nbaobeihuijia.com\nbaoerle.com\nbaofeng.com\nbaogao.com\nbaogaoku.com\nbaoji168.com\nbaojia.com\nbaojiaba.com\nbaojidaily.com\nbaojijob.com\nbaojiphoto.com\nbaojizx.com\nbaojk.com\nbaolubxg.com\nbaomihua.com\nbaoming.com\nbaomiye.com\nbaoruan.com\nbaoshanhui.com\nbaoshanjie.com\nbaosteel.com\nbaotang5.com\nbaotime.com\nbaotu.com\nbaoxian.com\nbaoyeah.com\nbaoyi100.com\nbaoyilego.com\nbaoyuntong.com\nbaozang.com\nbaozoudawang.com\nbaronchina.com\nbase888.com\nbatteryhr.com\nbavlo.com\nbaxue.com\nbayecao.com\nbayuche.com\nbayueju.com\nbbhun.com\nbbicn.com\nbbioo.com\nbblfloor.com\nbblft.com\nbbmalls.com\nbbready.com\nbbs0370.com\nbbs0556.com\nbbskaoyan.com\nbbstoday.com\nbbszjj.com\nbbwcq.com\nbbwfish.com\nbbwmw.com\nbcactc.com\nbcgjob.com\nbcjy123.com\nbcpcn.com\nbcyimg.com\nbczph.com\nbdall.com\nbdchina.com\nbdgbw.com\nbdimg.com\nbdjtd.com\nbdqnht.com\nbdqnxh.com\nbdr114.com\nbds-tech.com\nbdstatic.com\nbead-diy.com\nbeat11.com\nbecod.com\nbeelineser.com\nbeelink.com\nbeianbeian.com\nbeibaotu.com\nbeibeico.com\nbeibeidai.com\nbeidajj.com\nbeidaxueshihou.com\nbeidoulian.com\nbeifangdianlan.com\nbeifangfoshifen.com\nbeifangguolv.com\nbeiguorc.com\nbeihai365.com\nbeihaidc.com\nbeijing-office.com\nbeijingbang.com\nbeijingbaomu.com\nbeijingnongjiayuan.com\nbeijingrc.com\nbeijingshots.com\nbeijingxa.com\nbeingmate.com\nbeisen.com\nbeitanews.com\nbeitiao.com\nbeiwaibest.com\nbeiwaiclass.com\nbeiwaionline.com\nbeiwaiqingshao.com\nbeiww.com\nbeiyistar.com\nbeiyupeixun.com\nbenber.com\nbendibao.com\nbengbeng.com\nbengou.com\nbeniao.com\nbenimg.com\nbenmaz.com\nbenniaocn.com\nbenshouji.com\nbensino.com\nbenxiaoqu.com\nbenyouhui.com\nberqin.com\nberui.com\nbest73.com\nbestb2b.com\nbestopview.com\nbet500.com\nbeva.com\nbf35.com\nbfjr.com\nbfyx.com\nbgl88.com\nbgrimm.com\nbgsdyz.com\nbgyedu.com\nbgyks.com\nbh-hotel.com\nbh111.com\nbh5.com\nbhdlw.com\nbhwzd.com\nbhxww.com\nbiancui.com\nbianews.com\nbianfeng.com\nbianmincn.com\nbianwanjia.com\nbianzhirensheng.com\nbiaonews.com\nbiaoyu114.com\nbiaoyu168.com\nbibitie.com\nbicpaedu.com\nbidchance.com\nbieshu.com\nbifen520.com\nbifengxia.com\nbiftedu.com\nbig-bit.com\nbigzhu.com\nbihannet.com\nbijiafloor.com\nbilibili.com\nbiligame.com\nbilinstar.com\nbimawen.com\nbincailiuxue.com\nbinfang.com\nbingchengwang.com\nbinglanggu.com\nbingtuannet.com\nbinguanzs.com\nbinhai100.com\nbinvor.com\nbinzhoumama.com\nbio1000.com\nbioon.com\nbisenet.com\nbitauto.com\nbitautoimg.com\nbitautotech.com\nbitscn.com\nbiwo.com\nbiyong007.com\nbiz178.com\nbiz72.com\nbizcn.com\nbiznewscn.com\nbj-cl.com\nbj-gzjlb.com\nbj-lexus.com\nbj-mobiletv.com\nbj-sihemy.com\nbj1777.com\nbj597.com\nbjaccp.com\nbjbenet.com\nbjbkws.com\nbjbus.com\nbjcankao.com\nbjcf.com\nbjcshy.com\nbjdskgl.com\nbjdtv.com\nbjdushu.com\nbjedu.com\nbjfair.com\nbjgxs.com\nbjhhlv.com\nbjhonglu.com\nbjhoutai.com\nbjhuaboyy.com\nbjhuiyou.com\nbjhxjz.com\nbjhypx.com\nbjlmfq.com\nbjlot.com\nbjlyjszx.com\nbjmama.com\nbjmanyuan.com\nbjmmhh.com\nbjmtv.com\nbjp321.com\nbjpzs.com\nbjrc.com\nbjrcb.com\nbjrzx.com\nbjsdkj.com\nbjsoyo.com\nbjspw.com\nbjsqgy.com\nbjsubway.com\nbjsyqw.com\nbjtarena.com\nbjtjd.com\nbjtopli.com\nbjtptk.com\nbjtxc.com\nbjwmys.com\nbjxatq.com\nbjxfpp.com\nbjxiangda.com\nbjxinniang.com\nbjxinyou.com\nbjxyxd.com\nbjypw.com\nbjyxl.com\nbjzs.com\nbjzyhs.com\nbk010.com\nbkill.com\nbkpcn.com\nbl81890.com\nblctwed.com\nbleju.com\nblnjw.com\nblogbus.com\nblogchina.com\nbloomgamer.com\nbloves.com\nblqx.com\nblshe.com\nbluehn.com\nblueidea.com\nblyol.com\nbmindex.com\nbmlink.com\nbmymtz.com\nbnapp.com\nbndaily.com\nbnncn.com\nbnpower.com\nboai.com\nboaigx.com\nboairc.com\nbobo.com\nbohaitoday.com\nboheshop.com\nboke001.com\nbokecc.com\nbokeccimg.com\nbokee.com\nbole766.com\nbolijob.com\nbon-top.com\nbookben.com\nbookdao.com\nbookschina.com\nbookuu.com\nboosj.com\nbootcss.com\nboqee.com\nboqii.com\nborlonclan.com\nborpor.com\nbosafe.com\nbosera.com\nbosidata.com\nbosideng.com\nbosnn.com\nbosshr.com\nbostpx.com\nboxuu.com\nbozhong.com\nboznews.com\nbqqm.com\nbrandcn.com\nbrandjs.com\nbroadks.com\nbs-car.com\nbs2005.com\nbsjhhzs.com\nbsmhw.com\nbsqc.com\nbsrczpw.com\nbssfc.com\nbssmm.com\nbswxw.com\nbsyjrb.com\nbtbsm.com\nbtc114.com\nbtcha.com\nbtcman.com\nbtctrade.com\nbtesi.com\nbtgms.com\nbtophr.com\nbtrcsc.com\nbtsteel.com\nbtwmb.com\nbubukua.com\nbufan.com\nbuild365.com\nbuildhr.com\nbukade.com\nbumiu.com\nbundpic.com\nbunyn.com\nbus84.com\nbusyan.com\nbusyouxi.com\nbutao.com\nbuycarcn.com\nbuyiju.com\nbuzzopt.com\nbwchinese.com\nbx169.com\nbxd365.com\nbxdyt.com\nbxgfw.com\nbxgtd.com\nbxhq.com\nbxi8.com\nbxkxw.com\nbxrcw.com\nbxycw.com\nbxynzz.com\nbxzxw.com\nby-bbs.com\nbyandon.com\nbycmw.com\nbyecity.com\nbyf.com\nbykjhb.com\nbynmc.com\nbyywee.com\nbyzc.com\nbz169.com\nbz800.com\nbzcars.com\nbzfccs.com\nbzfxw.com\nbzgd.com\nbzjw.com\nbzonl.com\nbzqcw.com\nbzshw.com\nbzsj.com\nbztdxxl.com\nbzw315.com\nbzwscgs.com\nbzys001.com\nbzzpw.com\nc-bm.com\nc-c.com\nc-ctrip.com\nc-ly.com\nc029.com\nc168c.com\nc21ax.com\nc2qz.com\nc393.com\nc3crm.com\nc969.com\nca-maimai.com\nca168.com\nca39.com\nca800.com\ncaa1949.com\ncaaad.com\ncaamei.com\ncaanb.com\ncabhr.com\ncable-ex.com\ncableabc.com\ncableex.com\ncabling-system.com\ncacgame.com\ncacos.com\ncadmm.com\ncaexpo.com\ncafacds.com\ncaffeenglish.com\ncago365.com\ncaifx.com\ncaigou2003.com\ncaigu.com\ncaiguu.com\ncaihao.com\ncaijj.com\ncaiku.com\ncaikuu.com\ncailele.com\ncailiao.com\ncailizhong.com\ncaing.com\ncaipiao365.com\ncaipiaogu.com\ncaipiaokong.com\ncaishijie.com\ncaitoo.com\ncaixin.com\ncaixinhui.com\ncaiyun.com\ncaizhuang.com\ncake400.com\ncali-light.com\ncallwan.com\ncalusy.com\ncan-goldlink.com\ncando100.com\ncandou.com\ncanenglish.com\ncang.com\ncangbao.com\ncangjinbao.com\ncangvip.com\ncangworld.com\ncanju114.com\ncankaoxiaoxi.com\ncanyin88.com\ncanyouhn.com\ncaomeipai.com\ncaoyuanfeng.com\ncar0575.com\ncar0596.com\ncar885.com\ncardbaobao.com\ncarimg.com\ncarixy.com\ncarjol.com\ncarnoc.com\ncars178.com\ncarschina.com\ncartoonb2b.com\ncartooncentury.com\ncartoonhr.com\ncarword.com\ncarxoo.com\ncaspm.com\ncasshr.com\ncat898.com\ncatwaji.com\ncaupd.com\ncazpw.com\ncb-h.com\ncb310.com\ncbd-china.com\ncbe21.com\ncbex.com\ncbh-jj.com\ncbice.com\ncbiec.com\ncbinews.com\ncbminfo.com\ncbrx.com\ncbs86.com\ncbsbw.com\ncbskc.com\ncbsrc.com\ncbt9.com\ncbtia.com\ncbw365.com\ncc-office.com\ncc0595.com\ncc148.com\ncc520.com\ncc9d.com\nccaabb.com\nccapress.com\nccartd.com\nccav5.com\nccb.com\nccbfutures.com\nccbookfair.com\nccc333.com\ncccacc.com\ncccdzxw.com\nccceedu.com\nccdol.com\nccedip.com\nccedisp.com\nccedpw.com\nccedu24.com\ncceep.com\nccement.com\nccenn.com\nccfdw.com\nccfei.com\nccgaa.com\nccic.com\nccidcom.com\nccidconsulting.com\nccidedu.com\nccidgroup.com\nccidjl.com\nccidnet.com\nccidreport.com\nccidthinktank.com\nccits618.com\nccjex.com\nccjoy.com\ncclcn.com\nccm-1.com\nccmama.com\nccmedu.com\nccmetro.com\nccn360.com\ncco100.com\nccoalnews.com\nccost.com\nccpc360.com\nccpit-ah.com\nccpittex.com\nccpitzs.com\nccpm168.com\nccprec.com\nccrjia.com\nccsph.com\ncct88588.com\ncctalk.com\ncctccb.com\ncctcct.com\ncctime.com\ncctourcollege.com\ncctv.com\ncctv-19.com\ncctv1-15.com\ncctvcaizhi.com\ncctvcj.com\ncctvmall.com\ncctvpic.com\ncctvxf.com\nccutchi.com\nccutu.com\nccv160.com\nccv5.com\nccvita.com\nccwcw.com\nccxcn.com\nccxinkezhan.com\nccyts.com\ncd-lotton.com\ncd-motorshow.com\ncd-pa.com\ncdbdks.com\ncdcmzx.com\ncdculture.com\ncddtz.com\ncdeaa.com\ncdedu.com\ncdeledu.com\ncdfds.com\ncdgjbus.com\ncdgjlxs.com\ncdjzs.com\ncdknj.com\ncdn-apple.com\ncdndm.com\ncdndm5.com\ncdnet110.com\ncdpta.com\ncdqcp.com\ncdqss.com\ncdsb.com\ncdsjjy.com\ncdsme.com\ncdspld.com\ncdvns.com\ncdxuntu.com\ncdyee.com\ncdysxx.com\ncdzjj.com\ncdzmkm.com\ncdzxyy.com\nce-air.com\nce-idc.com\nceair.com\ncebbank.com\ncecb2b.com\nceccen.com\nceeia.com\ncehome.com\ncehui8.com\ncehuiyc.com\ncehuizizhi.com\nceiea.com\ncement365.com\ncementren.com\ncentanet.com\ncentury21cn.com\ncenwor.com\ncenxiao.com\nceoba.com\nceoedu.com\nceolearn.com\nceowan.com\nceping114.com\nceramicschina.com\ncernet.com\ncersp.com\ncespc.com\ncet-46.com\ncetcit.com\ncetimes.com\ncetv.com\ncf086.com\ncf5156.com\ncf571.com\ncfcyb.com\ncfd163.com\ncfhot.com\ncfiin.com\ncfmmc.com\ncfsbcn.com\ncfscrm.com\ncftjob.com\ncfvin.com\ncfwjob.com\ncfyd168.com\ncfzpw.com\ncg009.com\ncg1993.com\ncg577.com\ncg98.com\ncgbolo.com\ncgebook.com\ncgjoy.com\ncgmol.com\ncgtz.com\ncguardian.com\ncguwan.com\nch-em.com\nch7w.com\nch9888.com\nch999.com\nch999img.com\nchachaba.com\nchaduo.com\nchaej.com\nchahaoba.com\nchahaotai.com\nchajie.com\nchakd.com\nchamei.com\nchamenhu.com\nchanel.com\nchanghong.com\nchangjiangtimes.com\nchangshannews.com\nchangshuhr.com\nchangyou.com\nchangzhinews.com\nchaoji.com\nchaoji007.com\nchaojupai.com\nchaorenwang.com\nchaoshanren.com\nchaoxing.com\nchaozhoudaily.com\nchasfz.com\nchashebao.com\nchawenyi.com\nchaxiao.com\nchaxunbang.com\nchayou365.com\nchazidian.com\nchbcnet.com\nchbds.com\nchcpmc.com\nchczz.com\nchdajob.com\nche12.com\nche127.com\nche168.com\nche2.com\nche310.com\nche777.com\ncheaa.com\ncheari.com\nchebadu.com\nchebiaow.com\nchechong.com\nchechuan.com\ncheduoshao.com\ncheertea.com\nchefans.com\nchejl.com\nchekb.com\nchelink.com\nchem-men.com\nchem17.com\nchem234.com\nchem31.com\nchem960.com\nchem99.com\nchemayi.com\nchemcp.com\nchemdrug.com\nchemishu.com\nchemmade.com\nchemn.com\nchemnet.com\nchemrp.com\nchemsb.com\nchenair.com\nchengbaoo.com\nchengdechina.com\nchengdetv.com\nchengdujjw.com\nchengguw.com\nchengkao365.com\nchengruide.com\nchengshiw.com\nchengtu.com\nchengw.com\nchengyiju.com\nchenhr.com\nchenpeipei.com\nchepin88.com\nchepuer.com\ncherriespie.com\ncheshi.com\ncheshi-img.com\ncheshitv.com\nchetx.com\nchetxia.com\ncheweixiu.com\nchewen.com\nchexiang.com\nchexianinfo.com\nchexinwen.com\nchexiu.com\nchexun.com\ncheyes.com\ncheyian.com\ncheyipai.com\ncheyisou.com\ncheyou123.com\ncheyou360.com\ncheyuan.com\ncheyun.com\nchgjjzx.com\nchihao.com\nchina.com\nchina-315.com\nchina-ah.com\nchina-anjian.com\nchina-asahi.com\nchina-b.com\nchina-cdt.com\nchina-chigo.com\nchina-chuwei.com\nchina-cloud.com\nchina-cpp.com\nchina-dalian.com\nchina-designer.com\nchina-ef.com\nchina-eia.com\nchina-esi.com\nchina-fire-retardant.com\nchina-flower.com\nchina-guiyuan.com\nchina-house.com\nchina-huaxue.com\nchina-insurance.com\nchina-lawfirm.com\nchina-lushan.com\nchina-moutai.com\nchina-nengyuan.com\nchina-papernet.com\nchina-pec.com\nchina-pub.com\nchina-qg.com\nchina-ssp.com\nchina-sss.com\nchina-tin.com\nchina-up.com\nchina-zibo.com\nchina001.com\nchina114net.com\nchina183.com\nchina2car.com\nchina3-d.com\nchina35.com\nchina3608.com\nchina5e.com\nchina91.com\nchina9986.com\nchinaacademyofart.com\nchinaacc.com\nchinaacn.com\nchinaadec.com\nchinaadren.com\nchinaaet.com\nchinaamc.com\nchinaaqnews.com\nchinaart-eye.com\nchinaasnews.com\nchinaautolighting.com\nchinaautosupplier.com\nchinababy365.com\nchinabaifukang.com\nchinabancai.com\nchinabathware.com\nchinabatteryonline.com\nchinabbnews.com\nchinabcnews.com\nchinabdh.com\nchinabdnews.com\nchinabei.com\nchinabgao.com\nchinabidding.com\nchinabim.com\nchinabmi.com\nchinaboxi.com\nchinabreed.com\nchinabsnews.com\nchinabuses.com\nchinabx.com\nchinabxnews.com\nchinabyte.com\nchinabznews.com\nchinabzp.com\nchinac.com\nchinacaipu.com\nchinacars.com\nchinacbe.com\nchinaccm.com\nchinaccnet.com\nchinaccnews.com\nchinacdnews.com\nchinaceot.com\nchinachangzhinews.com\nchinachangzhounews.com\nchinachemnet.com\nchinachizhounews.com\nchinachnews.com\nchinachugui.com\nchinachuzhounews.com\nchinacnr.com\nchinacoal.com\nchinacoop.com\nchinacpx.com\nchinacqsb.com\nchinactv.com\nchinacutv.com\nchinacynews.com\nchinacznews.com\nchinadance.com\nchinadandongnews.com\nchinadarktea.com\nchinadazhaxie.com\nchinadeda.com\nchinadengshi.com\nchinadlh.com\nchinadlnews.com\nchinadqnews.com\nchinadrtv.com\nchinadtnews.com\nchinae.com\nchinaecec.com\nchinaedu.com\nchinaedunet.com\nchinaeea.com\nchinaeinet.com\nchinaeku.com\nchinaenvironment.com\nchinaepe.com\nchinafarming.com\nchinafeedonline.com\nchinafife.com\nchinafix.com\nchinaforklift.com\nchinaforkliftpart.com\nchinafranchiseexpo.com\nchinafsnews.com\nchinafudaoban.com\nchinafxnews.com\nchinafynews.com\nchinafznews.com\nchinagayles.com\nchinagba.com\nchinagdda.com\nchinagiftsfair.com\nchinagne.com\nchinagocar.com\nchinagoldgroup.com\nchinagreentown.com\nchinagwxz.com\nchinagwy.com\nchinagynews.com\nchinagzn.com\nchinahanews.com\nchinahazelnut.com\nchinahbi.com\nchinahdnews.com\nchinahfnews.com\nchinahgnews.com\nchinahhnews.com\nchinahightech.com\nchinahjbh.com\nchinahldnews.com\nchinahobypaper.com\nchinahr.com\nchinahsnews.com\nchinahti.com\nchinahuainannews.com\nchinahuangshannews.com\nchinahvacr.com\nchinahyyj.com\nchinaidp.com\nchinaidr.com\nchinaigbt.com\nchinaiiss.com\nchinaimnet.com\nchinainfoseek.com\nchinaiol.com\nchinaios.com\nchinairn.com\nchinaitlab.com\nchinajcnews.com\nchinajiuquan.com\nchinajixinews.com\nchinajlnews.com\nchinajmsnews.com\nchinajnhb.com\nchinajnzz.com\nchinajob.com\nchinajsxx.com\nchinajznews.com\nchinakaoyan.com\nchinakehai.com\nchinakingo.com\nchinakyxx.com\nchinalao.com\nchinalaobao.com\nchinalawedu.com\nchinalawinfo.com\nchinalawyeryn.com\nchinaled114.com\nchinalfnews.com\nchinaliaoyangnews.com\nchinaliaoyuannews.com\nchinalinfennews.com\nchinalishi.com\nchinallnews.com\nchinalongyannews.com\nchinaluan.com\nchinaluju.com\nchinaluxehome.com\nchinaluxus.com\nchinalygnews.com\nchinamaho.com\nchinamasnews.com\nchinamdjnews.com\nchinamedevice.com\nchinamendu.com\nchinamenwang.com\nchinamingci.com\nchinamining.com\nchinamobile.com\nchinamsr.com\nchinamypp.com\nchinandnews.com\nchinanet-online.com\nchinanetcenter.com\nchinanetsun.com\nchinanews.com\nchinanjnews.com\nchinanpnews.com\nchinantnews.com\nchinaoct.com\nchinaore.com\nchinapay.com\nchinape168.com\nchinapet.com\nchinapjnews.com\nchinaplasm.com\nchinaports.com\nchinapost-life.com\nchinapp.com\nchinaptnews.com\nchinaqbw.com\nchinaqhdnews.com\nchinaqthnews.com\nchinaqw.com\nchinaqznews.com\nchinaredstar.com\nchinaren.com\nchinarjw.com\nchinascsmh.com\nchinashaodong.com\nchinashj.com\nchinashoes.com\nchinashoujipp.com\nchinashuozhounews.com\nchinasilk.com\nchinasipingnews.com\nchinasjznews.com\nchinasmnews.com\nchinaso.com\nchinasongyuannews.com\nchinasqbg.com\nchinasqnews.com\nchinasspp.com\nchinasuzhounews.com\nchinaswitch.com\nchinasych.com\nchinasynews.com\nchinasysnews.com\nchinataitan.com\nchinataizhounews.com\nchinatarena.com\nchinatat.com\nchinatcw.com\nchinatelecom-ec.com\nchinatelecomiot.com\nchinatet.com\nchinatex.com\nchinathnews.com\nchinatibetnews.com\nchinatlnews.com\nchinatonglingnews.com\nchinatour-net.com\nchinatpg.com\nchinatpm.com\nchinatsi.com\nchinatsnews.com\nchinatynews.com\nchinaui.com\nchinauma.com\nchinaunicom.com\nchinaunionpay.com\nchinaups.com\nchinavanward.com\nchinavegnet.com\nchinavisual.com\nchinavnet.com\nchinavoa.com\nchinawaternet.com\nchinawaternews.com\nchinawbsyxh.com\nchinawebmap.com\nchinaweiyu.com\nchinawestagr.com\nchinawhnews.com\nchinawin2000.com\nchinawoodnet.com\nchinawudang.com\nchinawutong.com\nchinawxnews.com\nchinawyx.com\nchinaxcnews.com\nchinaxiamennews.com\nchinaxiaokang.com\nchinaxnnews.com\nchinaxuzhounews.com\nchinaxwcb.com\nchinaxznews.com\nchinayanchengnews.com\nchinayanghe.com\nchinayichunnews.com\nchinayigou.com\nchinayigui.com\nchinayknews.com\nchinaymqg.com\nchinayoubang.com\nchinayouji.com\nchinayqnews.com\nchinayucinews.com\nchinayunchengnews.com\nchinayyjx.com\nchinaz.com\nchinazhoukou.com\nchinazichan.com\nchinazikao.com\nchinazjknews.com\nchinazjnews.com\nchinazznews.com\nchinese-luxury.com\nchinese-no1.com\nchinese-os.com\nchineseall.com\nchinesejy.com\nchivast.com\nchizhou007.com\nchizhoujob.com\nchizhouren.com\nchizhouxueyuan.com\nchiznews.com\nchlngg.com\nchn0769.com\nchnart.com\nchnci.com\nchncomic.com\nchndesign.com\nchnir.com\nchnjet.com\nchnlung.com\nchnmilitary.com\nchnrailway.com\nchnroad.com\nchnsuv.com\nchnvc.com\nchnweiyu.com\nchnwp.com\nchnyhg.com\nchnyin.com\nchofn.com\nchongwujiaoyi.com\nchouti.com\nchris-tina.com\nchrunsoft.com\nchtangyao.com\nchtf.com\nchtgc.com\nchtpe.com\nchuandakaoyan.com\nchuandong.com\nchuangdian114.com\nchuangshachang.com\nchuangye.com\nchuanke.com\nchuanmeicn.com\nchuchuwan.com\nchufw.com\nchuguo78.com\nchuguohome.com\nchuguoqu.com\nchuji8.com\nchunqiuwang.com\nchunshuitang.com\nchushan.com\nchushixx.com\nchuyouke.com\nchvacuum.com\nchyee.com\nchyxx.com\nchzhw.com\nchzpw.com\nci123.com\nci800.com\ncibohui.com\ncicaf.com\nciceme.com\ncicgf.com\ncidianwang.com\ncigna-cmc.com\ncignacmb.com\nciid09.com\nciidoo.com\nciidsh.com\nciif-expo.com\nciku5.com\ncilanie.com\ncilogo.com\ncioage.com\nciotimes.com\nciotour.com\ncirmall.com\ncis-expo.com\ncisregister.com\ncisskwt.com\ncitic.com\nciticsf.com\ncitscq.com\ncitshlj.com\ncitsnj.com\ncitswx.com\ncitvc.com\ncity8.com\ncitygaga.com\ncitygf.com\ncityn.com\ncitysbs.com\ncityy.com\ncivilness.com\nciweek.com\nciweekforum.com\ncjdby.com\ncjfcw.com\ncjlap.com\ncjol.com\ncjolimg.com\ncjrcsc.com\ncjt1996.com\ncjtzlss.com\ncjxtv.com\ncjzww.com\nckimg.com\nckplayer.com\ncl2000.com\ncl597.com\nclass01.com\nclassic023.com\nclcjob.com\nclcmw.com\ncldol.com\ncleanbird.com\nclemf.com\nclfg.com\nclhweb.com\ncljmmm123.com\ncljob.com\nclner.com\nclothr.com\nclothw.com\ncloudapply.com\ncloverhostel.com\nclpifa.com\nclssn.com\nclxww.com\nclysolar.com\nclzqdf.com\ncm188.com\ncmaaicpa.com\ncmbchina.com\ncmejob.com\ncmfchina.com\ncmfu.com\ncmgame.com\ncmhk.com\ncmingde.com\ncminin.com\ncmiy.com\ncmiyu.com\ncmmri.com\ncmol.com\ncmpay.com\ncmpbook.com\ncmread.com\ncmstop.com\ncmwb.com\ncmxrcw.com\ncmzd.com\ncmzz100.com\ncn-edu.com\ncn-em.com\ncn-healthcare.com\ncn-java.com\ncn-jnrc.com\ncn-truck.com\ncn-tyn.com\ncn0-6.com\ncn0556.com\ncn0851.com\ncn0874.com\ncn0917.com\ncn21edu.com\ncn2che.com\ncn357.com\ncn5135.com\ncn716.com\ncn939.com\ncnaction.com\ncnad.com\ncnadtop.com\ncnaf.com\ncnagri.com\ncnair.com\ncnal.com\ncnanzhi.com\ncnapt.com\ncnautonews.com\ncnbagnet.com\ncnbdw.com\ncnbeta.com\ncnbidding.com\ncnblogs.com\ncnbmys.com\ncnccar.com\ncncelab.com\ncnchainnet.com\ncnchu.com\ncncn.com\ncncoke.com\ncncookernet.com\ncncotton.com\ncncproduct.com\ncncraftinfo.com\ncncrk.com\ncncxhw.com\ncnd8.com\ncndbscw.com\ncndds.com\ncndeaf.com\ncndesign.com\ncndewei.com\ncndingxi.com\ncndlsh.com\ncndns.com\ncndoornet.com\ncndoors.com\ncndrsq.com\ncndrynet.com\ncndsi.com\ncndw.com\ncndwine.com\ncndzys.com\ncndzz.com\ncne163.com\ncnelc.com\ncnele.com\ncnena.com\ncnenzyme.com\ncnep001.com\ncnepaper.com\ncnestate.com\ncnfda.com\ncnfdnet.com\ncnfeol.com\ncnffi.com\ncnfilternet.com\ncnfla.com\ncnfluidnet.com\ncnfol.com\ncnfolimg.com\ncnfoodsafety.com\ncnforex.com\ncnfruit.com\ncnfzflw.com\ncngaosu.com\ncngba.com\ncngbbs.com\ncngoldres.com\ncngoto.com\ncngpc.com\ncngrain.com\ncngulu.com\ncngzbj.com\ncnhan.com\ncnhangyun.com\ncnhaomen.com\ncnhetianyu.com\ncnhmsq.com\ncnhouse.com\ncnhubei.com\ncnhvacr.com\ncnhvacrnet.com\ncnhyc.com\ncnhzpjy.com\ncnicif.com\ncnijoy.com\ncnimba.com\ncnin-net.com\ncninsp.com\ncnipr.com\ncnitblog.com\ncnitdc.com\ncnjdyp.com\ncnjiaju.com\ncnjiajun.com\ncnjiaren.com\ncnjidan.com\ncnjj.com\ncnjjbc.com\ncnjly.com\ncnjnsb.com\ncnjob.com\ncnjobedu.com\ncnjsqw.com\ncnjutiao.com\ncnjxol.com\ncnjy99.com\ncnjzjj.com\ncnkang.com\ncnkfjob.com\ncnkjz.com\ncnlacenet.com\ncnlai.com\ncnled114.com\ncnledw.com\ncnlight.com\ncnlightnet.com\ncnliti.com\ncnlive.com\ncnlogo8.com\ncnlsqy.com\ncnlsspxx.com\ncnluan.com\ncnluye.com\ncnlyrcw.com\ncnmcg-expo.com\ncnmeiw.com\ncnmet.com\ncnmmhh.com\ncnmo.com\ncnnaihuo.com\ncnnauto.com\ncnnb.com\ncnnbfdc.com\ncnnbpi.com\ncnnbzj.com\ncnnfhy.com\ncnnzxx.com\ncnoa360.com\ncnobol.com\ncnoee.com\ncnpatent.com\ncnpcjob.com\ncnpeak.com\ncnpenjing.com\ncnpickups.com\ncnpignet.com\ncnpmetal.com\ncnpowdernet.com\ncnpre.com\ncnprophoto.com\ncnpubg.com\ncnput.com\ncnpv.com\ncnqjc.com\ncnqjw.com\ncnradio.com\ncnrdn.com\ncnree.com\ncnrencai.com\ncnrepark.com\ncnrexue.com\ncnrmobile.com\ncnsaw.com\ncnscdc.com\ncnscore.com\ncnsdjxw.com\ncnsea-pump.com\ncnsepu.com\ncnshipnet.com\ncnshipping.com\ncnsikao.com\ncnsilver.com\ncnslfp.com\ncnsnpj.com\ncnsoftnews.com\ncnsphoto.com\ncnsppl.com\ncnstm.com\ncnstock.com\ncnsuning.com\ncnsuv.com\ncnsynews.com\ncnta.com\ncntaijiquan.com\ncntaiping.com\ncntc.com\ncntexjob.com\ncntff.com\ncntheory.com\ncntianliao.com\ncntizi.com\ncntour2.com\ncntour365.com\ncntrades.com\ncntronics.com\ncntsmr.com\ncntvchina.com\ncntxw.com\ncnutg.com\ncnv168.com\ncnvdf.com\ncnwav.com\ncnwear.com\ncnwebshow.com\ncnwee.com\ncnwep.com\ncnwest.com\ncnwest88.com\ncnwinenews.com\ncnwlkj.com\ncnwlxxw.com\ncnwnews.com\ncnwpem.com\ncnwuhu.com\ncnwuyun.com\ncnwzcx.com\ncnxds.com\ncnxiantao.com\ncnxianzai.com\ncnxibu.com\ncnxnyw.com\ncnycedu.com\ncnyigui.com\ncnync.com\ncnys.com\ncnyu.com\ncnzhantuan.com\ncnzhengmu.com\ncnzhixiang.com\ncnzicai.com\ncnzjgc.com\ncnzjnet.com\ncnzjqi.com\ncnzpxx.com\ncnzsyz.com\ncnztjx.com\ncnzxsoft.com\ncnzyjc.com\ncnzz.com\nco188.com\ncoal-link.com\ncoalcn.com\ncoalstudy.com\ncoating-cn.com\ncoatingol.com\ncoco90.com\ncocoachina.com\ncocodiy.com\ncocoren.com\ncofco.com\ncofeed.com\ncofool.com\ncoinabc.com\ncokeic.com\ncoli688.com\ncombadc.com\ncomenb.com\ncomeshang.com\ncomicdd.com\ncomicer.com\ncomicyu.com\ncomingchina.com\ncompanycn.com\ncomponentcn.com\ncomsenz.com\ncomuu.com\nconcrete365.com\ncoo8.com\ncoocaa.com\ncoodir.com\ncooflower.com\ncooguo.com\ncool-de.com\ncool999.com\ncoolchuan.com\ncooldock.com\ncoolgy.com\ncoolool.com\ncooltuku.com\ncoolxap.com\ncosco.com\ncosdiv.com\ncosplay8.com\ncost168.com\ncoubei.com\ncp2y.com\ncp520.com\ncpa800.com\ncpato.com\ncpbay.com\ncpc-ex.com\ncpdyj.com\ncppc360.com\ncppccnews.com\ncppfoto.com\ncpplay.com\ncps800.com\ncpspew.com\ncpspt.com\ncptjob.com\ncq315house.com\ncq6.com\ncqacmm.com\ncqcoal.com\ncqcsrc.com\ncqdnet.com\ncqdxy.com\ncqfire.com\ncqfygzfw.com\ncqgtjt.com\ncqism.com\ncqjbly.com\ncqjiaz.com\ncqjjnet.com\ncqjjrcw.com\ncqjob.com\ncqjsrc.com\ncqjsxx.com\ncqjxjp.com\ncqkx.com\ncqleaders.com\ncqlozz.com\ncqlp.com\ncqmap.com\ncqmmgo.com\ncqour.com\ncqph.com\ncqsalt.com\ncqshangceng.com\ncqshipping.com\ncqskl.com\ncqspbxz.com\ncqsq.com\ncqswyq.com\ncqtlrc.com\ncqtn.com\ncquae.com\ncqueap.com\ncqvip.com\ncqwaitan.com\ncqwin.com\ncqwsrc.com\ncqxyw.com\ncqyznews.com\ncqzls.com\ncqzol.com\ncqzprc.com\ncqzql.com\ncr-expo.com\ncr-nielsen.com\ncr173.com\ncrecg.com\ncric.com\ncrm1001.com\ncrmgz.com\ncrossmo.com\ncrsky.com\ncrystaledu.com\ncs090.com\ncs53.com\ncs6s.com\ncs81.com\ncsadec.com\ncsair.com\ncsau.com\ncsbew.com\ncsc86.com\ncscb2b.com\ncscec.com\ncscoal.com\ncscse-germany.com\ncscsf.com\ncseac.com\ncsfcw.com\ncsgholding.com\ncsgm168.com\ncshaojob.com\ncskaoyan.com\ncslleather.com\ncslygs.com\ncsnaxin.com\ncsoei.com\ncsoly.com\ncsqc.com\ncsrcsc.com\ncssmoban.com\ncssponline.com\ncssqt.com\ncsteelnews.com\ncstif.com\ncsueus.com\ncsvw.com\ncsxb.com\ncsxnews.com\ncsxww.com\ncsyamei.com\ncsyjx.com\ncsytv.com\ncszhan.com\ncszhibei.com\ncszpw.com\ncsztv.com\nct-xz.com\nct10000.com\nct165.com\nct597.com\nctaoci.com\nctcnn.com\nctctc.com\nctcte.com\ncteaw.com\ncthnet.com\ncthy.com\nctiforum.com\nctn1986.com\nctocio.com\nctppumps.com\nctqcp.com\nctraining365.com\nctrip.com\nctsdc.com\nctsho.com\nctsmice.com\nctsscs.com\nctsto.com\nctxyw.com\ncubead.com\ncuctv.com\ncuew.com\ncug2313.com\ncuilai.com\ncunan.com\ncuncun8.com\ncuncunle.com\ncunlie.com\ncuntuba.com\ncuplayer.com\ncusteel.com\ncut35.com\ncutv.com\ncuwell.com\ncv-nz.com\ncv51.com\ncvcri.com\ncw100.com\ncwan.com\ncwddd.com\ncwestc.com\ncwmaya.com\ncwmining.com\ncwroom.com\ncwyan.com\ncwyx.com\ncxcyds.com\ncxdpsp.com\ncxfish.com\ncxh99.com\ncxhr.com\ncxt8.com\ncxtuku.com\ncxw.com\ncxzw.com\ncy.com\ncy580.com\ncycnet.com\ncyegushi.com\ncyguilin.com\ncyheb.com\ncyikao.com\ncyipu.com\ncyol.com\ncyw100.com\ncyz7.com\ncyzypm.com\ncz0355.com\ncz121.com\ncz365.com\nczairport.com\nczbank.com\nczbfw.com\nczcaizi.com\nczcits.com\nczcqw.com\nczepb.com\nczfcw.com\nczflcp.com\nczgjj.com\nczgm.com\nczgongzuo.com\nczhr.com\nczlook.com\nczmei.com\nczmuseum.com\nczqcw.com\nczrc114.com\nczrcw.com\nczrxw.com\nczsgjj.com\nczsnlw.com\nczsrc.com\ncztaole.com\ncztour.com\ncztv.com\ncztv6.com\ncztzy.com\nczwljyw.com\nczwlzx.com\nczxiu.com\nczxls.com\nczxnews.com\nczzp.com\nczzsw.com\nd-edu.com\nd0818.com\nd1cm.com\nd1com.com\nd1net.com\nd399.com\nd586.com\nd7ol.com\nd8360.com\nd8wed.com\nd9soft.com\ndaba.com\ndabandichan.com\ndabaoku.com\ndacai.com\ndachangtex.com\ndachenglaw.com\ndachengnet.com\ndada360.com\ndadou.com\ndaeee.com\ndafengso.com\ndaflw.com\ndagangcheng.com\ndagong.com\ndaguantao.com\ndaguirc.com\ndaguozhenzimiao.com\ndahainan.com\ndahangzhou.com\ndahecc.com\ndahecw.com\ndahei.com\ndaheshui.com\ndahew.com\ndahuaping.com\ndahuatech.com\ndahuawang.com\ndaihr.com\ndailiba.com\ndailyqd.com\ndaimg.com\ndairy123.com\ndairyexpo.com\ndaishan.com\ndaishu.com\ndaixiaomi.com\ndaixiwan.com\ndajiabao.com\ndajianet.com\ndajiawan.com\ndajiazhao.com\ndajie.com\ndajieimg.com\ndajunshi.com\ndakawang.com\ndalianjob.com\ndalianxueche.com\ndalidaily.com\ndalings.com\ndalooss.com\ndamuzzz.com\ndance365.com\ndanding.com\ndandongjob.com\ndangbei.com\ndangdaiyishu.com\ndangdang.com\ndangjian.com\ndanji6.com\ndanji8.com\ndanpinku.com\ndanyang.com\ndanyanghr.com\ndanyrc.com\ndanzhengyuan.com\ndao50.com\ndaodao.com\ndaogoubang.com\ndaoguo.com\ndaoguqihuo.com\ndaoxila.com\ndapu.com\ndapuimg.com\ndaqi.com\ndaqin029.com\ndarczpw.com\ndarryring.com\ndashi.com\ndashilike.com\ndashipin.com\ndasuanwang.com\ndata68.com\ndatang5.com\ndataodu.com\ndatatang.com\ndatianmen.com\ndatihu.com\ndatouyouxi.com\ndavinfo.com\ndawanghui.com\ndaxi.com\ndaxiangkeji.com\ndaxiangnews.com\ndaxiangrc.com\ndaxiangwang.com\ndaxin360.com\ndaxue52.com\ndaxuecn.com\ndaxuewa.com\ndayanzhu.com\ndayirc.com\ndayiwang.com\ndayiwangluo.com\ndayoo.com\ndayou123.com\ndayouwooden.com\ndayuchang.com\ndayunmotor.com\ndayuonline.com\ndazhangqiu.com\ndazhe5.com\ndazhenzimiao.com\ndazhicm.com\ndazhongemiao.com\ndazhonghr.com\ndazhongzhou.com\ndazhoushan.com\ndazhuangwang.com\ndazhurc.com\ndazibo.com\ndazpin.com\ndb-nw.com\ndb2car.com\ndbafmh.com\ndbank.com\ndcdjt.com\ndcdrcw.com\ndcement.com\ndcfjw.com\ndchpv.com\ndcjianghu.com\ndcjol.com\ndcn88.com\ndcwzg.com\ndd188.com\ndd288.com\ndd373.com\nddc999.com\nddeng.com\nddfchina.com\nddkspdt.com\nddmap.com\nddmapimg.com\nddmeishi.com\nddooo.com\nddove.com\nddport.com\nddqcw.com\nddttn.com\nddvip.com\nddxia.com\ndecorcn.com\ndecwhy.com\ndedecms.com\ndedewan.com\ndefensecn.com\ndehuaca.com\ndemage.com\ndemaxiya.com\ndemingtang.com\ndeng6.com\ndenghuo.com\ndeppon.com\nderenbs.com\ndesign521.com\ndesktopsky.com\ndesktx.com\ndestoon.com\ndeyetown.com\ndeyi.com\ndeyiso.com\ndezhi.com\ndezhong365.com\ndezhoudaily.com\ndf-118.com\ndf818.com\ndfcfw.com\ndffsj.com\ndfhon.com\ndfjyhome.com\ndflgnc.com\ndfsrcw.com\ndfstw.com\ndfyuan.com\ndg-dx.com\ndg121.com\ndg699.com\ndgaccpx.com\ndgcaomei.com\ndggcc.com\ndginfo.com\ndgjt.com\ndgpx88.com\ndgqjj.com\ndgrcpq.com\ndgs6.com\ndgsme.com\ndgwxys.com\ndgzstx.com\ndgzzm.com\ndh597.com\ndhang123.com\ndhcmzs.com\ndhgate.com\ndhifi.com\ndhrczx.com\ndhteach.com\ndian5000.com\ndiandian.com\ndiandong.com\ndianhangjia.com\ndianji007.com\ndianli114.com\ndiannaoban.com\ndiannaojishu.com\ndianping.com\ndianrong.com\ndianshifu.com\ndiantijob.com\ndianxian999.com\ndianxin.com\ndianxinnews.com\ndianyuan.com\ndianzp.com\ndianzubuluo.com\ndiaoyanbao.com\ndiaoyu.com\ndiaoyu123.com\ndicaiwang.com\ndichan.com\ndidatuan.com\ndidipai.com\ndidown.com\ndidunews.com\ndihuasen.com\ndili360.com\ndinbon.com\ndinghuaren.com\ndingniugu.com\ndingyuannews.com\ndingyx.com\ndinju.com\ndionly.com\ndiqiuw.com\ndiscoversources.com\ndiscuz.com\ndisoso.com\nditan360.com\nditan500.com\ndivcss5.com\ndiyiapp.com\ndiyicai.com\ndiyiche8.com\ndiyiyou.com\ndiyizby.com\ndiypda.com\ndiytrade.com\ndj020.com\ndj19.com\ndj520.com\ndj7.com\ndj97.com\ndjbozi.com\ndjbstatic.com\ndjkk.com\ndjob.com\ndju8.com\ndjwma.com\ndjxww.com\ndjye.com\ndjyjob.com\ndlairport.com\ndlaitc.com\ndlbyg.com\ndld.com\ndldcdn.com\ndledu.com\ndlgaoji.com\ndlgxw.com\ndlhmjw.com\ndlhnews.com\ndlicw.com\ndlkhgl.com\ndlmonita.com\ndlpuwan.com\ndlqh.com\ndlqinzi.com\ndlsysy.com\ndlxp.com\ndlxww.com\ndlxxsd.com\ndlysgh.com\ndlzfgjj.com\ndlzzm.com\ndm-rc.com\ndm300.com\ndm456.com\ndm5.com\ndm591.com\ndm76.com\ndmcbd.com\ndmdfchina.com\ndmkor.com\ndmshu.com\ndmsxxw.com\ndmtrck.com\ndmwhj.com\ndmzj.com\ndmzx.com\ndn1234.com\ndnake.com\ndnbbs.com\ndnc21.com\ndnfwan.com\ndnheimuer.com\ndnwx.com\ndnxf.com\ndo93.com\ndocer.com\ndocin.com\ndodo8.com\ndodonew.com\ndoershow.com\ndog126.com\ndoguo.com\ndoido.com\ndoname.com\ndonews.com\ndongannews.com\ndongao.com\ndongbei8.com\ndongfang.com\ndongfang8.com\ndongjidao.com\ndongjinyu.com\ndongkounews.com\ndongnanshan.com\ndongpingren.com\ndongqiudi.com\ndongsheng2010.com\ndooland.com\ndoooor.com\ndoor-expo.com\ndooreb.com\ndoorhr.com\ndoserv.com\ndospy.com\ndostor.com\ndotamax.com\ndouanju.com\ndouban.com\ndouguo.com\ndoulai.com\ndoulewu.com\ndouluodalu123.com\ndouni.com\ndoupobook.com\ndouxie.com\ndouyutv.com\ndowater.com\ndowncc.com\ndowndownz.com\ndowng.com\ndownhot.com\ndownkr.com\ndownxia.com\ndoyor.com\ndozedu.com\ndpfile.com\ndpin100.com\ndpm360.com\ndq-fx.com\ndq247.com\ndqccc.com\ndqdaily.com\ndqdm.com\ndqjob88.com\ndqpump.com\ndqxxw.com\ndragonmil.com\ndraw-more.com\ndrcnet.com\ndreams-travel.com\ndrivergenius.com\ndriversdown.com\ndrugadmin.com\ndrughuloo.com\nds-360.com\nds-is.com\nds123456.com\nds599.com\ndsbjq.com\ndsfauto.com\ndsfunds.com\ndsgkt.com\ndshigao.com\ndshmama.com\ndshrc.com\ndslpool.com\ndsrczp.com\ndswjob.com\ndt12318.com\ndt511.com\ndtcoalmine.com\ndthr.com\ndthuawei.com\ndtlsw.com\nduanwenxue.com\nduapp.com\nduba.com\nduhub.com\nduidea.com\nduitang.com\ndukuai.com\nduobei.com\nduohaode.com\nduoic.com\nduokan.com\nduomai.com\nduomi.com\nduorou42.com\nduoshuo.com\nduote.com\nduotegame.com\nduouoo.com\nduowan.com\nduoww.com\nduoxinqi.com\nduoyi.com\ndushi118.com\ndushifang.com\ndushiline.com\ndutbbs.com\ndute520.com\nduwenz.com\nduwenzhang.com\nduxiu.com\nduzhebao.com\nduzhihai.com\ndv37.com\ndvbcn.com\ndvwu.com\ndw20.com\ndwgou.com\ndwstatic.com\ndwywooden.com\ndx-job.com\ndxb2b.com\ndxbei.com\ndxcang.com\ndxcjjzx.com\ndxlfile.com\ndxsbb.com\ndxsheng.com\ndxsjz.com\ndxszxy.com\ndxxnews.com\ndxycdn.com\ndxyy91.com\ndxzx.com\ndy-bus.com\ndy369.com\ndy8.com\ndy86.com\ndycars.com\ndyfcw.com\ndyhjw.com\ndyp2p.com\ndyqc.com\ndyrbw.com\ndytdc.com\ndyteam.com\ndytfw.com\ndytjj.com\ndyxtw.com\ndyxw.com\ndz-z.com\ndz090.com\ndz1982.com\ndz211.com\ndz600.com\ndzcnc.com\ndzfang.com\ndzfc.com\ndzgjj.com\ndzhaoj.com\ndzkfq.com\ndzmall.com\ndzqiche.com\ndzqxj.com\ndzrbs.com\ndzrc8.com\ndzrtv.com\ndzsc.com\ndzsm.com\ndzso.com\ndzsrcw.com\ndzszb.com\ndzwcity.com\ndzwindows.com\ndzwww.com\ndzztgw.com\ne-dyer.com\ne-jjj.com\ne-qdpm.com\ne0453.com\ne0514.com\ne0570.com\ne0575.com\ne0734.com\ne0756.com\ne0838.com\ne118114.com\ne1617.com\ne1988.com\ne21cn.com\ne2say.com\ne51home.com\ne521.com\ne6w6.com\ne7uu.com\ne8online.com\ne974.com\nea-china.com\nea3w.com\neach9.com\neachnet.com\neachnic.com\neagtop.com\neahot.com\nean98.com\nearthedu.com\neasdo.com\neaseeyes.com\neasiu.com\neasou.com\neastcang.com\neastday.com\neasteat.com\neastfair.com\neastib.com\neastmoney.com\neastradio.com\neastshepin.com\neastsilver.com\neastsoo.com\neastts.com\neastups.com\neasysino.com\neasyvoa.com\neb80.com\nebaocheng.com\nebatong.com\nebdoor.com\nebiaoegou.com\nebieshu.com\nebigear.com\neblockschina.com\nebnew.com\neboce.com\nebrun.com\nebscn.com\nebseek.com\nec2ec.com\nec517.com\necaihr.com\necasee.com\necbaby.com\neccn.com\neccnmall.com\neceeg.com\neceibs.com\nechangye.com\nechinagov.com\nechinajob.com\nechocontrol.com\necidi.com\necitic.com\necmao.com\necp888.com\necppn.com\necqun.com\necshop.com\necstv.com\necvvby.com\neczn.com\nedai.com\nedaocha.com\nedazhang.com\nedianchi.com\nedianyou.com\nedtqy.com\nedu-010.com\nedu-hb.com\nedu-nw.com\nedu03.com\nedu1488.com\nedu201.com\nedu24ol.com\nedu5a.com\nedu63.com\nedu80.com\nedu84.com\neducaizhi.com\nedudo.com\neduease.com\neduego.com\neduei.com\nedufang.com\neduglobal.com\nedulida.com\neduour.com\nedushi.com\nedutt.com\neduu.com\neduuu.com\neduvv.com\neduwo.com\neeboard.com\neec-sh.com\neechina.com\neecnt.com\neeeen.com\neeeff.com\neefocus.com\neehu.com\neeju.com\neelly.com\neenzo.com\neetrend.com\neeyy.com\nef168.com\nef360.com\nef75.com\nefubo.com\nefuhr.com\nefuyang.com\negoedu.com\negou.com\negouz.com\neguanzhu.com\nehaier.com\nehaoyao.com\nehomeday.com\nehometu.com\nehsy.com\nehualang.com\nehuatai.com\nehvacr.com\neiacn.com\neiafans.com\neiiq.com\neis100.com\neisdl.com\neistudy.com\neit0571.com\nejee.com\nejeegroup.com\nejeepay.com\neju.com\nek6.com\nekan123.com\nekingo.com\nekoooo.com\nelanw.com\nele001.com\nelecfans.com\nelecinfo.com\nelexcon.com\nelht.com\nellechina.com\nelong.com\nelongstatic.com\nels88.com\nelvyo.com\nemai360.com\nemalljs.com\nemaozi.com\nemarbox.com\nembatimes.com\nemcsino.com\neme2000.com\nemeixian.com\nemmacn.com\nems517.com\nemtx.com\nemu618.com\nemui.com\nen51.com\nen84.com\nename.com\nenboedu.com\nenbowang.com\nenetedu.com\nenetsz.com\nenfodesk.com\neng24.com\nenglishtown.com\nenglishvip.com\nenguo.com\nenkj.com\nenmuo.com\nenshi9e.com\nenshifdc.com\nenshijob.com\nenshisport.com\nenterdesk.com\nenvirofortune.com\neoeandroid.com\neoemarket.com\neoffcn.com\neoledu.com\neotour.com\nepaidai.com\nepanshi.com\nepchina.com\nepday.com\nepi88.com\nepiaogo.com\nepinv.com\nepjob88.com\neptrc.com\neptxw.com\nepweike.com\nepzpw.com\neq-gc1.com\neq-hl.com\neqinrun.com\neqyn.com\nercac.com\nereneben.com\nerongtu.com\nerpchn.com\nersoso.com\neryoutang.com\nes370.com\nescdn.com\neserexpo.com\nesfimg.com\nesfxx.com\neshiyan.com\neshouyao.com\neshow365.com\neshowgo.com\nesnai.com\nesoche.com\nesqimg.com\nessaycn.com\nestc8.com\nesuliao.com\neswine.com\netaicang.com\netaiyang.com\netao.com\netc-sbc.com\netest8.com\netf88.com\netfjijin.com\nethainan.com\netiantian.com\netlong.com\netonkids.com\netowz.com\netpass.com\nett-cn.com\netuan.com\neuibe.com\nev123.com\nevaad.com\nevdays.com\nevergrande.com\neverychina.com\nevlook.com\nevpartner.com\nevsou.com\newang.com\newangpai.com\newjar.com\newkimg.com\newoka.com\neworksglobal.com\neworldship.com\newsos.com\newstudy.com\newteacher.com\nex-cp.com\nexam001.com\nexam76.com\nexam8.com\nexamda.com\nexamw.com\nexamzz.com\nexbulk.com\nexbxg.com\nexiaba.com\nexiaoba.com\nexpai.com\nexpeak.com\nexpo-china.com\nexpo-cn.com\nexpo-yy.com\nexpowindow.com\nexrtz.com\nexw360.com\neyou.com\neyuyao.com\nezhiol.com\neztxw.com\nf0580.com\nf139.com\nf139content.com\nf1688.com\nf537.com\nf61.com\nf737.com\nfa-today.com\nfa597.com\nfabao365.com\nfabric114.com\nfabu114.com\nfacang.com\nface321.com\nfad123.com\nfadianxitong.com\nfadui.com\nfahaola.com\nfahaole.com\nfaidns.com\nfajiaowang.com\nfalongfa.com\nfaloo.com\nfamenbao.com\nfamens.com\nfamensy.com\nfancai.com\nfanfou.com\nfang.com\nfang33.com\nfang86.com\nfang99.com\nfangbx.com\nfangchan.com\nfangchankaoshi.com\nfangdr.com\nfangedai.com\nfanging.com\nfangjia.com\nfangjiadp.com\nfangjiaw.com\nfangle.com\nfanglincar.com\nfangtan007.com\nfangte.com\nfangtoo.com\nfangtuwang.com\nfangtw.com\nfangtx.com\nfangxiaoer.com\nfangxinbao.com\nfangxinmai.com\nfangyou.com\nfangyuan365.com\nfangyuanglass.com\nfangzhanhui.com\nfangzhi-china.com\nfangzhur.com\nfanhuan.com\nfanqun.com\nfansimg.com\nfansjw.com\nfantizi5.com\nfanxian.com\nfanxuefei.com\nfanyizhijia.com\nfar2000.com\nfashangji.com\nfashiontrenddigest.com\nfastener500.com\nfavolist.com\nfaw-mazda.com\nfaw-vw.com\nfawan.com\nfaxingzhan.com\nfayifa.com\nfblife.com\nfboos.com\nfc0531.com\nfc0575.com\nfc0592.com\nfc0595.com\nfc0596.com\nfc0597.com\nfc0633.com\nfc571.com\nfc593.com\nfc85.com\nfccs.com\nfccscar.com\nfcdbz.com\nfcfcg.com\nfcfxb.com\nfcg360.com\nfcgic.com\nfcgsnews.com\nfcgyc.com\nfcjob88.com\nfclubimg.com\nfcrc114.com\nfcsc517.com\nfcxlib.com\nfcxnews.com\nfcyhw.com\nfd597.com\nfdc0737.com\nfdc0746.com\nfdc315.com\nfdcew.com\nfdckj.com\nfdfang.com\nfdgzw.com\nfdxww.com\nfeedsky.com\nfeelcars.com\nfeeliu.com\nfeeyo.com\nfei580.com\nfeichengjob.com\nfeicuiedu.com\nfeicuiwuyu.com\nfeidm.com\nfeihucg.com\nfeijs.com\nfeiku.com\nfeiliu.com\nfeipin.com\nfeixue.com\nfeizl.com\nfenfen.com\nfeng.com\nfeng91.com\nfengbao.com\nfengbuy.com\nfengdu100.com\nfengj.com\nfengjierc.com\nfengjing.com\nfenglu-alu.com\nfengmu6.com\nfengniao.com\nfengone.com\nfengsung.com\nfengyunlive.com\nfengyunzhibo.com\nfenlei168.com\nfenleidao.com\nfentishebei.com\nferrygame.com\nfetionpic.com\nffdyk.com\nffpic.com\nffwan.com\nfhgame.com\nfhlczy.com\nfhlyou.com\nfhmob.com\nfilterhz.com\nfinanceun.com\nfindzd.com\nfireflytrip.com\nfirstgood.com\nfish-photo.com\nfishrc.com\nfit120.com\nfj007.com\nfj3091.com\nfjber.com\nfjcet.com\nfjcha.com\nfjcoop.com\nfjdaily.com\nfjdh.com\nfjfdi.com\nfjgb.com\nfjgczj.com\nfjgczl.com\nfjgrain.com\nfjgzjy.com\nfjhrss.com\nfjhun.com\nfjhzrc.com\nfjii.com\nfjjcjy.com\nfjjdrcw.com\nfjjgxy.com\nfjjyxy.com\nfjlcnews.com\nfjlearning.com\nfjlh.com\nfjlyta.com\nfjmwjx.com\nfjnet.com\nfjprxx.com\nfjpta.com\nfjqlw.com\nfjsalt.com\nfjsen.com\nfjsyxww.com\nfjszgjj.com\nfjta.com\nfjteanews.com\nfjtj.com\nfjtvnews.com\nfjwuzi.com\nfjxmw.com\nfjydnews.com\nfjzlym.com\nfjzol.com\nfjzsjy.com\nfkbxg.com\nfkyycl.com\nfl928.com\nflash1890.com\nflashget.com\nflingba.com\nflrcw.com\nfltrp.com\nfm-job.com\nfm1036.com\nfm1039.com\nfm1054.com\nfm914.com\nfm936.com\nfmbimg.com\nfnrcw.com\nfocussend.com\nfocustt.com\nfojiaoyongpin.com\nfoloda.com\nfondcool.com\nfoodjol.com\nfoodjx.com\nfoods1.com\nfoodspl.com\nfoodszs.com\nfoolcars.com\nfoooooot.com\nfor68.com\nforbeschina.com\nforesky.com\nforestryfair.com\nforkliftnet.com\nfornature.com\nfortunevc.com\nfotile.com\nfotosay.com\nfoundersc.com\nfpdisplay.com\nfphs5.com\nfpky188.com\nfpwap.com\nfq597.com\nfqpai.com\nfqrsw.com\nfqwh.com\nfreezph.com\nfrjie.com\nfrpjh.com\nfrsky.com\nfruitday.com\nfs024.com\nfs121.com\nfs31.com\nfs7000.com\nfscfrc.com\nfsclzs.com\nfskzpw.com\nfsmama.com\nfsmeeting.com\nfspcdn.com\nfssgjj.com\nfsshyd.com\nfstcb.com\nfstta.com\nfswanlei.com\nfswchina.com\nft22.com\nftgsct.com\nftuan.com\nftxgame.com\nfu08.com\nfuanjob.com\nfuanrc.com\nfubaore.com\nfuchan024.com\nfudankao.com\nfudaonet.com\nfuguangchina.com\nfuhaodq.com\nfujian-window.com\nfujianrc.com\nfujiantulou.com\nfuliansheng.com\nfuliao.com\nfuling.com\nfuliyuwang.com\nfumanhua.com\nfumin.com\nfumu.com\nfumubang.com\nfumuhui.com\nfuning114.com\nfunshion.com\nfunuo.com\nfunxoo.com\nfunxun.com\nfupiaopifa.com\nfupingjiazheng.com\nfuqiangw.com\nfurielec.com\nfushenshop.com\nfushr.com\nfututa.com\nfuxianren.com\nfuyang.com\nfuyin365.com\nfuzhuanghome.com\nfw3721.com\nfw55555.com\nfwsir.com\nfx168.com\nfx1718.com\nfx678.com\nfx898.com\nfx963.com\nfxfk4.com\nfxingw.com\nfxsol-uk.com\nfxtiyu.com\nfxxz.com\nfxyqw.com\nfxytzz.com\nfy14.com\nfy22.com\nfyapw.com\nfygjj.com\nfysns.com\nfytcw.com\nfytest.com\nfz12358.com\nfz597.com\nfzbbw.com\nfzbm.com\nfzcj.com\nfzengine.com\nfzfu.com\nfzfzjx.com\nfzg360.com\nfzhitech.com\nfzjol.com\nfzlol.com\nfzlu.com\nfzlwc.com\nfzpchome.com\nfzpig.com\nfzpp.com\nfzqnrc.com\nfzrczpw.com\nfzrsrc.com\nfzsjob.com\nfzsme.com\nfzwnjjw.com\nfzzfgjj.com\nfzzxbbs.com\ng1080.com\ng12e.com\ng207.com\ng2b2b.com\ng312.com\ng361.com\ng855.com\nga-me.com\ngacmotor.com\ngai001.com\ngaibar.com\ngaitu.com\ngalaxyinfo.com\ngalshi.com\ngame012.com\ngame080.com\ngame166.com\ngame28.com\ngame3737.com\ngame3939.com\ngame511.com\ngame798.com\ngamebbq.com\ngamecomb.com\ngamedg.com\ngameres.com\ngamerlol.com\ngamersky.com\ngamfe.com\nganayinxiang.com\nganggg.com\nganhuoche.com\nganji.com\nganjiangrc.com\nganjistatic1.com\ngannanw.com\nganniu.com\nganpen.com\ngansuci.com\ngansupost.com\nganttcn.com\ngantuan.com\nganwan.com\nganyu.com\nganzhe.com\nganzhouw.com\ngao7.com\ngao8dou.com\ngaoan.com\ngaobohr.com\ngaodun.com\ngaofen.com\ngaojieya.com\ngaokao.com\ngaokao789.com\ngaokaopai.com\ngaokw.com\ngaolehui.com\ngaoloumi.com\ngaopeng.com\ngaosheng520.com\ngaoshipf.com\ngaosiedu.com\ngaosivip.com\ngaosubao.com\ngaotieshike.com\ngaotiewang.com\ngaoxiaobaitai.com\ngaoxiaojob.com\ngaoxiaola.com\ngaoxinkeji.com\ngaoyizaixian.com\ngaoyoujob.com\ngaoyouzhaopin.com\ngarefu.com\ngarmentoffice.com\ngasgoo.com\ngashw.com\ngasshow.com\ngaszx.com\ngatewang.com\ngayleshome.com\ngb87.com\ngbdfang.com\ngbeqo.com\ngcb56.com\ngcchina.com\ngcjc.com\ngctezw.com\ngcwdq.com\ngcwzj.com\ngd-china.com\ngd-donglong.com\ngd-e.com\ngd-jiaoyu.com\ngdalpha.com\ngdart.com\ngdcct.com\ngdcoop.com\ngdcost.com\ngdcostzx.com\ngdcrj.com\ngddvb.com\ngdedu123.com\ngdeea.com\ngdepi.com\ngdglc.com\ngdgpo.com\ngdjrw.com\ngdjxzs.com\ngdkepu.com\ngdlands.com\ngdmxjy.com\ngdongw.com\ngdonlyedu.com\ngdpp.com\ngdrc.com\ngdrc360.com\ngdsalt.com\ngdshafa.com\ngdsrcw.com\ngdstc.com\ngdswine.com\ngdsxxw.com\ngdtarena.com\ngdtoption.com\ngdxxb.com\ngdyctour.com\ngdyjs.com\ngdzhaojiao.com\ngdzijin.com\ngdzj8.com\ngeautos.com\ngeedu.com\ngeely.com\ngeetest.com\ngeilidaquan.com\ngeilidjy.com\ngeilirc.com\ngemdale.com\ngeneralichina.com\ngensee.com\ngenvict.com\ngeo-show.com\ngeo2k.com\ngeochina.com\ngeren-jianli.com\ngesep.com\ngewara.com\ngexing.com\ngexings.com\ngeyanw.com\ngezila.com\ngfan.com\ngfcang.com\ngfgt.com\ngfw0898.com\ngfwz100.com\ngfzihua.com\ngg-art.com\ngg-led.com\ngg1z.com\nggact.com\nggcj.com\nggd5.com\ngggjs.com\ngghappy.com\nggsafe.com\nggsgg.com\nghjie.com\nghjmz.com\nghzpw.com\ngiabbs.com\ngialen.com\ngifore.com\ngift12345.com\ngiftjie.com\ngiftsbeijing.com\ngjgzpw.com\ngjjnhb.com\ngk-z.com\ngk505.com\ngk99.com\ngkcity.com\ngkfree.com\ngkong.com\ngkstk.com\ngkzhan.com\ngkzy100.com\ngl110.com\nglasshr.com\nglassinchina.com\nglinfo.com\nglituan.com\nglmama.com\nglobal-trade-center.com\nglobalchemmade.com\nglobalcompressor.com\nglobalfabric.com\nglobalhardwares.com\nglobeedu.com\nglobeimmi.com\nglobepv.com\nglobrand.com\ngloryre.com\nglosspp.com\nglpx.com\nglrcw.com\nglwmw.com\ngly360.com\nglyrc.com\nglzy8.com\ngm263.com\ngm86.com\ngn00.com\ngndaily.com\ngo007.com\ngo24k.com\ngo2map.com\ngo823.com\ngo9939.com\ngoart100.com\ngodsignal.com\ngoepe.com\ngoes123.com\ngogohome.com\ngoheee.com\ngohku.com\ngohoedu.com\ngojiaju.com\ngold186.com\ngold58.com\ngold678.com\ngoldenagri.com\ngoldenholiday.com\ngolue.com\ngomeart.com\ngong123.com\ngong7jun.com\ngongchang.com\ngongjiao.com\ngongjiaomi.com\ngongjing880.com\ngongkong.com\ngongpingjia.com\ngongshunews.com\ngongyequan.com\ngongyishibao.com\ngongzuo365.com\ngoo2sc.com\ngoodbaby.com\ngoodjd.com\ngoodjob100.com\ngoodkejian.com\ngoogle-analytics.com\ngoogleadservices.com\ngooglesyndication.com\ngooniu.com\ngooooal.com\ngoootech.com\ngopuu.com\ngotohz.com\ngotoip1.com\ngotoip2.com\ngotoip4.com\ngotoip55.com\ngotoningbo.com\ngotoread.com\ngotosd.com\ngou3618.com\ngoubuy.com\ngouchezixun.com\ngoufang.com\ngoufun8.com\ngoufw.com\ngougou.com\ngouhainan.com\ngouhao.com\ngoulew.com\ngoumin.com\ngoupuzi.com\ngouwuke.com\ngov86.com\ngowulong.com\ngpcxw.com\ngpinhui.com\ngprcw.com\ngpres.com\ngps688.com\ngpxz.com\ngq58.com\ngq66.com\ngqcsswj.com\ngqsoso.com\ngqt168.com\ngrchina.com\ngreatwuyi.com\ngree.com\ngreenbodhi.com\ngreening-china.com\ngreenlandsc.com\ngreenlem.com\ngreenxf.com\ngreenxiazai.com\ngrfyw.com\ngridsources.com\ngridsumdissector.com\ngrinm.com\ngronhi.com\ngrxxw.com\ngsdaquan.com\ngsdtarena.com\ngsdwhm.com\ngsflcp.com\ngsftw.com\ngsgrain.com\ngsheimeiren.com\ngsheitudou.com\ngsjb.com\ngskjcg.com\ngspst.com\ngsqiu.com\ngsrcw.com\ngsslu.com\ngstarcad.com\ngswhgl.com\ngsxpz.com\ngtfund.com\ngtgqw.com\ngtimg.com\ngtja.com\ngtjia.com\ngtobal.com\ngtuu.com\ngtxh.com\ngtxjob8001.com\ngtzyb.com\nguahao.com\nguaiguai.com\nguaixun.com\nguan5.com\nguanchengrc.com\nguandongphoto.com\nguanfang123.com\nguang.com\nguangdongrc.com\nguangdongshaiwang.com\nguangjiela.com\nguangshuishi.com\nguangxirc.com\nguangyidj.com\nguanjiatu.com\nguanlishi.com\nguanrencai.com\nguanzhongrc.com\nguanzhujia.com\nguatian.com\ngucheng.com\ngucn.com\ngudianwenxue.com\ngugubaby.com\nguhantai.com\nguidaye.com\nguidechem.com\nguiguanrc.com\nguiguanwater.com\nguijinshu.com\nguijirc.com\nguijj.com\nguijob.com\nguilinauto.com\nguilinbaobao.com\nguilincits.com\nguilinhd.com\nguilinlife.com\nguillot-wine.com\nguimi.com\nguiqianrc.com\nguiyinwang.com\nguizhouchine.com\ngulangyuzhusu.com\nguluyou.com\nguo7.com\nguocar.com\nguochengxin.com\nguodiy.com\nguodu.com\nguofenchaxun.com\nguofs.com\nguoji110.com\nguojixumu.com\nguolairen.com\nguoling.com\nguoluzhan.com\nguolv.com\nguolvol.com\nguoman8.com\nguomii.com\nguoshi.com\nguoxue.com\nguozhekou.com\nguozhen-health.com\ngupiaobaba.com\ngupzs.com\nguquanwang.com\nguquanzhuanrang.com\ngushibaike.com\ngushici5.com\ngushihui8.com\ngushq.com\ngusuwang.com\ngutx.com\nguuoo.com\nguwanw.com\nguzhiwang.com\ngw12580.com\ngwyoo.com\ngwyou.com\ngwyscs.com\ngx-job.com\ngx123.com\ngx12301.com\ngx211.com\ngxacw.com\ngxajj.com\ngxbd.com\ngxbstv.com\ngxbys.com\ngxcity.com\ngxdqw.com\ngxfcgedu.com\ngxfdcw.com\ngxfpw.com\ngxfsqm.com\ngxgrain.com\ngxgzf.com\ngxhczw.com\ngxhouse.com\ngxhzxw.com\ngxidc.com\ngxielts.com\ngxingw.com\ngxjbsj.com\ngxjcjj.com\ngxjlrc.com\ngxjpjy.com\ngxjtaq.com\ngxlottery.com\ngxorg.com\ngxpx114.com\ngxqcw.com\ngxrc.com\ngxrcw.com\ngxsell.com\ngxsky.com\ngxswnews.com\ngxtcmhw.com\ngxworker.com\ngxylnews.com\ngxzjy.com\ngy007.com\ngy365.com\ngyfcxx.com\ngyfff.com\ngyhqys.com\ngymama.com\ngymsj.com\ngysou.com\ngytxjx.com\ngyxuan.com\ngyzy.com\ngyzyfw.com\ngz-zikao.com\ngz0797.com\ngz12301.com\ngz300.com\ngz5168.com\ngzbaozhilin.com\ngzbdqn.com\ngzcofc.com\ngzcol.com\ngzcpc.com\ngzcsly.com\ngzcyxw.com\ngzcyxww.com\ngzdsw.com\ngzeic.com\ngzgczj.com\ngzh.com\ngzhtzy.com\ngzjcw.com\ngzjunkai.com\ngzjunyu.com\ngzjy360.com\ngzlight.com\ngzlrck.com\ngzmama.com\ngzmeilin.com\ngzml56.com\ngzmtr.com\ngzmzb.com\ngznet.com\ngznsny.com\ngznw.com\ngzpds.com\ngzpoly.com\ngzport.com\ngzpx360.com\ngzqnzyz.com\ngzqxn.com\ngzqzlx.com\ngzrck.com\ngzrcw.com\ngzrczpw.com\ngzre.com\ngzrencai.com\ngzrinm.com\ngzsalt.com\ngzsedu.com\ngzsggj.com\ngzsjyzx.com\ngzstv.com\ngzsy.com\ngzszfgjj.com\ngzszk.com\ngztarena.com\ngztcdj.com\ngzto.com\ngztv.com\ngzwanmeikongjian.com\ngzweilanhaian.com\ngzweix.com\ngzxishui.com\ngzxxw.com\ngzyeah.com\ngzyes.com\ngzzfzx.com\ngzzkzsw.com\ngzzoc.com\nh0591.com\nh0838.com\nh2o-china.com\nh6969.com\nha597.com\nha91.com\nhabctv.com\nhackdos.com\nhackhome.com\nhackp.com\nhaebinnews.com\nhagjj.com\nhahaertong.com\nhahait.com\nhahazaojiao.com\nhaianw.com\nhaibao.com\nhaidaiwan.com\nhaidian123.com\nhaier.com\nhaifangzj.com\nhaihr.com\nhaiis.com\nhaijiaonet.com\nhaijingfangcn.com\nhaijun360.com\nhaikele.com\nhaimanfeisi.com\nhaimenhr.com\nhainancoop.com\nhainanese.com\nhainanfz.com\nhainanhr.com\nhaining.com\nhaiqintech.com\nhaiqq.com\nhaishen.com\nhaisheninfo.com\nhaishenjia.com\nhaitian.com\nhaiwaisheying.com\nhaixiachina.com\nhaixiyin.com\nhaixuan12.com\nhaljl.com\nhancheng.com\nhandanjob.com\nhandsbrain.com\nhandu.com\nhangkong.com\nhanmaidj.com\nhantinghotels.com\nhanvontouch.com\nhanweb.com\nhanyouwang.com\nhanzhibing.com\nhanzhong123.com\nhao-sheng-yi.com\nhao123.com\nhao123img.com\nhao224.com\nhao315.com\nhaobashi.com\nhaochehui.com\nhaochi123.com\nhaochimei.com\nhaochu.com\nhaocw.com\nhaodai.com\nhaodf.com\nhaodingdan.com\nhaodou.com\nhaoduoge.com\nhaoeyou.com\nhaofanben.com\nhaofgo.com\nhaofjj.com\nhaofung.com\nhaofz.com\nhaogeqiang.com\nhaogongzhang.com\nhaohaizi.com\nhaohetao.com\nhaohuiyi.com\nhaohuoyuan.com\nhaojieyue.com\nhaojufang.com\nhaokan5.com\nhaokecheng.com\nhaole.com\nhaoleyou.com\nhaolietou.com\nhaoliv.com\nhaoloubang.com\nhaomahaoba.com\nhaonongzi.com\nhaopoo.com\nhaorc.com\nhaorennet.com\nhaoshangjia.com\nhaosilu.com\nhaotaotuan.com\nhaote.com\nhaott.com\nhaotui.com\nhaowangpu.com\nhaowm.com\nhaowywz.com\nhaoxuee.com\nhaoxx.com\nhaoyiz.com\nhaoyouyinxiang.com\nhaoyunbb.com\nhaoyunmom.com\nhaoyuyuan.com\nhaoyy114.com\nhaozhanhui.com\nhaozhuodao.com\nhaozu.com\nhaozu163.com\nhaozu168.com\nhaozuojia.com\nhappy3399.com\nhappyqiao.com\nhaxiu.com\nhazxqyw.com\nhb-csc.com\nhb0376.com\nhb0561.com\nhb12333.com\nhb261.com\nhb30.com\nhbaas.com\nhbaes.com\nhbcl-car.com\nhbcljyc.com\nhbclwqzc.com\nhbcoal.com\nhbcpre.com\nhbdangyang.com\nhbeol.com\nhbfy.com\nhbfzb.com\nhbgajg.com\nhbglky.com\nhbgrain.com\nhbgsl.com\nhbh520.com\nhbhbhb.com\nhbhro.com\nhbjnzyqc.com\nhbjob88.com\nhbjzlm.com\nhbksw.com\nhbnyw.com\nhbqnb.com\nhbrc.com\nhbrcw.com\nhbs0561.com\nhbshgzx.com\nhbsjz110.com\nhbsztv.com\nhbtcw.com\nhbtlz.com\nhbtycp.com\nhbwenshi.com\nhbxfmp.com\nhbxfzs.com\nhbxmad.com\nhbyczk.com\nhbyidu.com\nhbzaix.com\nhbzhan.com\nhbzkw.com\nhbzyfc.com\nhc360.com\nhc433.com\nhc699.com\nhc918.com\nhcdgzz.com\nhcdmy.com\nhche.com\nhcl100.com\nhctvnet.com\nhcwexpo.com\nhcxww.com\nhdabc.com\nhdavchina.com\nhdcmr.com\nhddcw.com\nhdeso.com\nhdletv.com\nhdmjdec.com\nhdmnw.com\nhdpfans.com\nhdslb.com\nhdtlxx.com\nhdzp.com\nhdzxw.com\nhdzyhm.com\nhe-nan.com\nheadstour.com\nhealthoo.com\nhealthr.com\nheartconn.com\nheb-huaqiang.com\nhebauto.com\nhebcar.com\nhebcoop.com\nhebdx.com\nhebeijiaoyu.com\nhebgtjt.com\nhebikuoda.com\nhebircw.com\nhebiw.com\nhebjxw.com\nhebnc.com\nhebnky.com\nhebpi.com\nhebradio.com\nhebtv.com\nhedaoxuan.com\nhefei58.com\nhefeizhaopin.com\nhehu.com\nhehuigj.com\nhehuit.com\nheiguang.com\nheiheiwan.com\nheima.com\nheima8.com\nheimashop.com\nheimaying.com\nheixo.com\nheiyan.com\nheiyanimg.com\nheiyc.com\nhejiang.com\nhello-code.com\nhellozx.com\nhemei120.com\nhenan-edu.com\nhenan-zikao.com\nhenan100.com\nhenanci.com\nhenandingsheng.com\nhenanfucai.com\nhenanqiuxue.com\nhenanrc.com\nhenantiyu.com\nhengqian.com\nhengqijy.com\nhengtonggroup.com\nhengyan.com\nhengyuandianlu.com\nhepan.com\nhepost.com\nhepuercha.com\nherbalife-health.com\nhercity.com\nherostart.com\nherschina.com\nhetaitea.com\nhetda.com\nheungkong.com\nhewei-china.com\nhexianbbs.com\nhexieshaanxi.com\nhexindai.com\nhexun.com\nhexuncn.com\nheze369.com\nhezedc.com\nhezefc.com\nhezejk.com\nhezejob.com\nhezeribao.com\nhf365.com\nhf777.com\nhf99.com\nhfairport.com\nhfbowei.com\nhfbtv.com\nhfcjl.com\nhfgjj.com\nhfhouse.com\nhfjcbs.com\nhfjfcm.com\nhfjieneng.com\nhfmama.com\nhftogo.com\nhfwenshi.com\nhg-z.com\nhg707.com\nhgitv.com\nhgjob.com\nhglaser.com\nhgrencai.com\nhgtvu.com\nhgzrc.com\nhh-w.com\nhh010.com\nhhbwjsc.com\nhhczy.com\nhhfcw.com\nhhgjj.com\nhhhtnews.com\nhhhtrx.com\nhhk365.com\nhhkao.com\nhhlepin.com\nhhsyjzs.com\nhhtravel.com\nhhzfgjj.com\nhhzhaoming.com\nhi-chic.com\nhi0574.com\nhi1718.com\nhi2000.com\nhi772.com\nhiao.com\nhiapk.com\nhicang.com\nhichina.com\nhicloud.com\nhicosmo.com\nhiesquire.com\nhifabric.com\nhihandan.com\nhihey.com\nhihifang.com\nhijiangxi.com\nhikvision.com\nhilizi.com\nhippoanimation.com\nhiputian.com\nhirede.com\nhisense.com\nhisensehitachi.com\nhisupplier.com\nhitao.com\nhivjob.com\nhiwemeet.com\nhiyeyou.com\nhjcun.com\nhjeee.com\nhjenglish.com\nhjglo.com\nhjplw.com\nhjyc.com\nhjyqw.com\nhkcts.com\nhke123.com\nhkhgo.com\nhkproperty.com\nhktdc.com\nhktdc-img.com\nhkxfb.com\nhl1314.com\nhlass.com\nhlcxy.com\nhldbtv.com\nhldgajjzd.com\nhldnews.com\nhldtop.com\nhlfdw.com\nhlhkys.com\nhljcq.com\nhljforest.com\nhljjjb.com\nhljnw.com\nhljpost.com\nhljradio.com\nhljsunwu.com\nhljtcp.com\nhljtv.com\nhlx99.com\nhly.com\nhlybar.com\nhlzpw.com\nhm5988.com\nhm8848.com\nhme01.com\nhmecw.com\nhmeonline.com\nhminvestment.com\nhmqqw.com\nhmting.com\nhmw365.com\nhmxuexiao.com\nhn-cts.com\nhn-pc.com\nhn12333.com\nhn481.com\nhn873.com\nhnaee.com\nhnagri.com\nhnair.com\nhnbaihua.com\nhnccgc.com\nhnccpm.com\nhnchj.com\nhncjh.com\nhncoop.com\nhncost.com\nhncsmjzs.com\nhnctw.com\nhncyfc.com\nhndeaho.com\nhndiancheng.com\nhnditu.com\nhnemap.com\nhnflcp.com\nhngfjy.com\nhnghw.com\nhnhjq.com\nhnhjw.com\nhnhm.com\nhnhyit.com\nhnhyrc.com\nhnielts.com\nhnjbwh.com\nhnjol.com\nhnjuran.com\nhnldgz.com\nhnloushi.com\nhnltw.com\nhnluxury.com\nhnlyxww.com\nhnmama.com\nhnmsw.com\nhnpost.com\nhnprec.com\nhnqcw.com\nhnqyfw.com\nhnradio.com\nhnrcsc.com\nhnrczpw.com\nhnrencai.com\nhnrsks.com\nhnrxw.com\nhnshangwu.com\nhnshj.com\nhnsjxn.com\nhnsncb.com\nhnsnnews.com\nhnsss.com\nhnsyfdc.com\nhntf8.com\nhnticai.com\nhntuanfun.com\nhnwenming.com\nhnwmw.com\nhnxhnews.com\nhnxnews.com\nhnxwcb.com\nhnxxw666.com\nhnxxwzz.com\nhnxysteel.com\nhnyc-edu.com\nhnyyjg.com\nhnzfgjj.com\nhnzhaoshan.com\nhnzhzz.com\nhnzmedia.com\nhnzpsc.com\nhnzresearch.com\nhogesoft.com\nhold168.com\nholdhr.com\nhome0538.com\nhome310.com\nhome77.com\nhome898.com\nhomedf.com\nhomedg.com\nhomekoo.com\nhomekoocdn.com\nhometex114.com\nhometexjoin.com\nhometexnet.com\nhometextilesworld.com\nhomeun.com\nhommk.com\nhongbeijob.com\nhongen.com\nhonggushi.com\nhonghuowang.com\nhongjingedu.com\nhongniang.com\nhongshu.com\nhongtu.com\nhongxiantuan.com\nhongxiu.com\nhongyaxuan.com\nhongyuanqh.com\nhongzerc.com\nhongzhoukan.com\nhookbase.com\nhoopchina.com\nhorise.com\nhorsehr.com\nhosap.com\nhostelcn.com\nhot178.com\nhot78.com\nhotds.com\nhotel525.com\nhotfcw.com\nhottui.com\nhoudao.com\nhouse0596.com\nhouse10000.com\nhouse365.com\nhouse577.com\nhousecq.com\nhousehy.com\nhouseqilu.com\nhouseyw.com\nhousoo.com\nhouxue.com\nhowbuy.com\nhowjia.com\nhowzhi.com\nhozhai.com\nhpimg.com\nhq-ielts.com\nhq-mart.com\nhq0451.com\nhq0564.com\nhq1h.com\nhq88.com\nhqbcdn.com\nhqbpc.com\nhqclass.com\nhqcr.com\nhqdly.com\nhqenorth.com\nhqepay.com\nhqew.com\nhqewimg.com\nhqhot.com\nhqhqw.com\nhqiye.com\nhqjhw.com\nhqlednews.com\nhqlsw.com\nhqmianshou.com\nhqpcb.com\nhqqrc.com\nhqshouji.com\nhqwy.com\nhqxly.com\nhqyj.com\nhqyl.com\nhqyyrc.com\nhr-sd.com\nhr025.com\nhr0571.com\nhr0596.com\nhr0660.com\nhr0662.com\nhr0751.com\nhr0752.com\nhr0753.com\nhr0755.com\nhr0759.com\nhr0766.com\nhr0773.com\nhr0898.com\nhr1000.com\nhr1288.com\nhr1898.com\nhr191.com\nhr33.com\nhr369.com\nhr5156.com\nhr762.com\nhr763.com\nhr777.com\nhr951.com\nhrbanlv.com\nhrbar.com\nhrbdqqz.com\nhrbit.com\nhrbmama.com\nhrhorse.com\nhrloo.com\nhroot.com\nhrpin.com\nhrrcw.com\nhrtx.com\nhrwind.com\nhs818.com\nhscbw.com\nhsdcw.com\nhsgjj.com\nhsgjjw.com\nhshan.com\nhsjas.com\nhsjjob.com\nhsnewsn.com\nhsrcw.com\nhssdzw.com\nhsspw.com\nhstmc.com\nht516.com\nht9000.com\nhtattoo.com\nhtderen.com\nhtexam.com\nhtfutures.com\nhthxm.com\nhtinns.com\nhtmianshi.com\nhtscw.com\nhtsec.com\nhttpcn.com\nhtyuqi.com\nhua.com\nhuaban.com\nhuabangfushi.com\nhuabei1.com\nhuabian.com\nhuacolor.com\nhuadachem.com\nhuadaofengye.com\nhuagu.com\nhuahuanet.com\nhuaian.com\nhuaian100.com\nhuaibei163.com\nhuaibin88.com\nhuaibinrc.com\nhuainet.com\nhuaiyangnews.com\nhuajian-al.com\nhuajianvalve.com\nhuajiashengdian.com\nhuajin100.com\nhuajx.com\nhualang001.com\nhualang123.com\nhualangnet.com\nhualepx.com\nhualongxiang.com\nhuamanche.com\nhuamanlou.com\nhuameibb.com\nhuanancoal.com\nhuanbao.com\nhuanbaoshi.com\nhuanbaoyc.com\nhuanbohaijob.com\nhuangjinlian.com\nhuangru.com\nhuangshanzjy.com\nhuangye88.com\nhuanhr.com\nhuanpingshi.com\nhuanqiu.com\nhuanqiu6.com\nhuanqiuw.com\nhuantu.com\nhuanwen.com\nhuanxia.com\nhuapaojob.com\nhuapinwang.com\nhuaqiphoto.com\nhuash.com\nhuashen-edu.com\nhuatai-serv.com\nhuatu.com\nhuaue.com\nhuawei.com\nhuaxcy.com\nhuaxi100.com\nhuaxia.com\nhuaxiaci.com\nhuaxirc.com\nhuaxunnsw.com\nhuayansi.com\nhuayiming.com\nhuayin520.com\nhuayuan520.com\nhuayuejob.com\nhuazhile.com\nhuazhongh.com\nhuazhu.com\nhubai.com\nhubeici.com\nhubeirc.com\nhudieji.com\nhudong.com\nhudou.com\nhugao8.com\nhugd.com\nhughjs.com\nhui800.com\nhuibo.com\nhuibojob.com\nhuiche.com\nhuidafx.com\nhuijucn.com\nhuilai88.com\nhuilan.com\nhuimaiche.com\nhuimingjia.com\nhuiminrencai.com\nhuishangbao.com\nhuishi365.com\nhuishoushang.com\nhuitouyu.com\nhuitu.com\nhuixiaodai.com\nhuixinyt.com\nhuiyanw.com\nhuiyi8.com\nhuizhuang.com\nhujiang.com\nhuliankm.com\nhuluxia.com\nhumen.com\nhunanfy.com\nhunanheicha.com\nhunanpta.com\nhunantv.com\nhunanzhibo.com\nhunchunnet.com\nhundsun.com\nhunlibar.com\nhunlimama.com\nhunt007.com\nhunter5156.com\nhunuo.com\nhuobar.com\nhuobi.com\nhuoche.com\nhuochepiao.com\nhuochepu.com\nhuodaixiamen.com\nhuodongjia.com\nhuodongxing.com\nhuohou.com\nhuohu123.com\nhuolawan.com\nhuolibaobao.com\nhuolinhe.com\nhuopao.com\nhuoqiuw.com\nhuore8.com\nhuoshannews.com\nhuowan.com\nhuoxue.com\nhuoying.com\nhuoyuanzhijia.com\nhupu.com\nhushi114.com\nhushiwin.com\nhuuyaa.com\nhuway.com\nhuweishen.com\nhuxiu.com\nhuzs.com\nhvac8.com\nhvacrex.com\nhvtong.com\nhw5d.com\nhwtop.com\nhwtrip.com\nhx-car.com\nhx-my.com\nhx116.com\nhx2car.com\nhx95.com\nhxcjdb.com\nhxdatian.com\nhxdctz.com\nhxdsrc.com\nhxen.com\nhxfilm.com\nhxfzjxw.com\nhxfzzx.com\nhxlsw.com\nhxqw.com\nhxrc.com\nhxrcsc.com\nhxsd.com\nhxsh365.com\nhxtk.com\nhxtxt.com\nhxyjw.com\nhxzb.com\nhy-steel.com\nhy123.com\nhy163.com\nhy588.com\nhydcd.com\nhydst.com\nhyedu.com\nhyfss.com\nhyjwz.com\nhyjzw.com\nhylrc.com\nhyqcw.com\nhysbw.com\nhysgjj.com\nhywit.com\nhyxnews.com\nhyxww.com\nhyzfgjj.com\nhz-delixi.com\nhz321.com\nhz66.com\nhzaee.com\nhzagro.com\nhzairport.com\nhzbj.com\nhzbx.com\nhzcbd.com\nhzcnb.com\nhzcnc.com\nhzcoop.com\nhzcy.com\nhzdaikuan8.com\nhzeduask.com\nhzfgj.com\nhzgjj.com\nhzhanbo.com\nhzhike.com\nhzhqyy.com\nhzhr.com\nhzhuman.com\nhzhuti.com\nhzins.com\nhzjs56.com\nhzjzwy.com\nhzland.com\nhzlongre.com\nhzlp.com\nhzlsg.com\nhzlw.com\nhzmnls.com\nhzmotv.com\nhznews.com\nhznzcn.com\nhzqiuxue.com\nhzqx.com\nhzrc.com\nhzshw.com\nhzsjgpx.com\nhzsk.com\nhzsmesc.com\nhztarena.com\nhztbc.com\nhztd56.com\nhzti.com\nhzvivi.com\nhzwestlake.com\nhzwmw.com\nhzwxq.com\nhzzays.com\nhzzp.com\ni-css.com\ni-jiaxing.com\ni-jjj.com\ni027.com\ni1758.com\ni1766.com\ni2ya.com\ni3kan.com\ni52088.com\ni8i8i8.com\niask.com\nib-china.com\nibamaol.com\nibangkf.com\nibayue.com\nibbdd.com\nibeifeng.com\nibgbuy.com\nibicn.com\nibooyi.com\nic37.com\nic72.com\nic98.com\nicafe8.com\nicaile.com\nicandata.com\nicarzoo.com\nicbuy.com\niceasy.com\nichengyang.com\nichengzi.com\niciba.com\nicifit.com\nicis-china.com\nicjyw.com\nicpcw.com\nicpdf.com\nicson.com\nictsiyantai.com\nicxo.com\nicycn.com\nidc123.com\nidchz.com\nidcps.com\nidcquan.com\nidcspy.com\nidcun.com\nidea-tops.com\nideahn.com\nidealroyal.com\nidealshanghai.com\nideatom.com\nidfay.com\nidler-et.com\nidongzhi.com\nidouu.com\nidqqimg.com\nidting.com\nidtui.com\niduola.com\nieche.com\niecity.com\niecnews.com\niecworld.com\nieduw.com\niefang.com\nieforex.com\nielts999.com\nifahao.com\nifanr.com\nifcwr.com\nifeng.com\nifeng-nb.com\nifenghui.com\nifengimg.com\nifensi.com\niflying.com\nigao7.com\nigaosheng.com\nigeak.com\nigo180.com\nigoldhk.com\nigome.com\nigoodgame.com\nigoodsc.com\niguso.com\nihaiyan.com\nihanhua.com\nihaveu.com\nihddy.com\niheima.com\nihome361.com\nihome927.com\nihome99.com\nihomeshow.com\nihoome.com\nihualun.com\nihuatong.com\nihuqu.com\nii010.com\niianews.com\niidns.com\niiiyooo.com\niiqee.com\niitpx.com\niiyi.com\niiyibbs.com\nijia360.com\nijiatv.com\nijie.com\nijinbu.com\nijinhuo.com\nijinshan.com\nijjnews.com\nijstv.com\nijxjj.com\nik123.com\nik3cloud.com\nikaka.com\nikanchai.com\nikandian.com\nikang.com\nikbqn.com\nikuyy.com\nilangwen.com\nilaw360.com\nileehoo.com\nilelu.com\nilishi.com\niliyu.com\nilongre.com\nilongterm.com\nilope-expo.com\nilovezuan.com\niluoshen.com\nilvping.com\nim286.com\nim533.com\nimages-amazon.com\nimaifang.com\nimaijia.com\nimakecollege.com\nimanhua.com\nimanshi.com\nimcdma.com\nimcoal.com\nimdiandao.com\nime19.com\nimeimama.com\nimfirewall.com\nimg-space.com\nimg4399.com\nimglafaso.com\nimglefeng.com\nimgshangman.com\nimmivip.com\nimooc.com\nimop.com\nimosi.com\nimportfoodfair.com\nin-en.com\nin189.com\ninabr.com\ninanle.com\nincensechina.com\ninchedao.com\nindexedu.com\nindiacn.com\nindiums.com\nindustrycome.com\ninengyuan.com\ninewoffice.com\ninfohc.com\ninfolz.com\ninfomorning.com\ninfzm.com\ning2ing.com\ningping.com\ninhe.com\ninimc.com\ninlishui.com\ninmachine.com\ninnyo.com\ninshion.com\ninsightwar.com\ninsigmaedu.com\ninsooo.com\ninspur.com\nintel.com\nintertid.com\nintple.com\ninuobi.com\ninvestjilin.com\ninwayedu.com\nios114.com\niot-online.com\niot1bbs.com\nip138.com\nipa001.com\nipanda.com\nipchina.com\niphonetrain.com\nipmph.com\nipr123.com\nipugou.com\niqilu.com\niqinbao.com\niqingdao.com\niqingren.com\niqiyi.com\niresearchad.com\niresearchchina.com\nirs09.com\nis97.com\nisanmen.com\nishaanxi.com\nishangman.com\nishangtoutiao.com\nishegou.com\nishenyou.com\nishibk.com\nishowx.com\nisoucai.com\nissns.com\nistartrade.com\nistreamsche.com\nisuzupowertrain.com\nisying.com\nit168.com\nit224.com\nitangyuan.com\nitaozhu.com\nitavcn.com\nitbulo.com\nitceo.com\nitchaguan.com\nitdcw.com\niterduo.com\niteye.com\nitfeed.com\nitheima.com\nithlj.com\nithome.com\nithov.com\nitingwa.com\nitjds.com\nitjol.com\nitjutou.com\nitjuzi.com\nitmale.com\nitmop.com\nitnxs.com\nitokit.com\nitouchchina.com\nitouxian.com\nitpar.com\nitravelqq.com\nitshai.com\nitsofun.com\nitt168.com\nittribalwo.com\nitugo.com\nitwaibaow.com\nitxinwen.com\nitxsw.com\niuicity.com\niuvision.com\nivsky.com\niwebchoice.com\niwencai.com\niwhr.com\niwjia.com\niwpai.com\niwugu.com\niwuyin.com\nixiapu.com\nixiawan.com\nixinda.com\nixinwei.com\nixiumei.com\nixumu.com\nixywy.com\niyaxin.com\niyaya.com\niyingji.com\niyiou.com\niyiyun.com\niyouman.com\niyxwzx.com\niyzx.com\nizaojiao.com\nizhikang.com\nizhuanr.com\nizhufu.com\nizhukao.com\nizhuti.com\nizizhucan.com\nizmzg.com\nj1.com\nj3bbs.com\njaadee.com\njaifang.com\njandou.com\njanxing.com\njarczpw.com\njarencai.com\njarhu.com\njbdown.com\njbzyw.com\njc0553.com\njc35.com\njc85.com\njcbao.com\njcbctv.com\njcc1.com\njccoal.com\njcjj365.com\njcjzs.com\njcku.com\njclzw.com\njcmeh.com\njcoal.com\njcqcw.com\njcqzw.com\njcrb.com\njcrcw.com\njcshi.com\njctrans.com\njcwcn.com\njcwuhan.com\njcz001.com\njczao.com\njczxb.com\njd.com\njd-88.com\njd-bbs.com\njd-cg.com\njd100.com\njd37.com\njdbaw.com\njdbbx.com\njdcheng.com\njdcjsr.com\njdemba.com\njdfhq.com\njdgod.com\njdjob88.com\njdlhw.com\njdnettv.com\njdunion.com\njdw001.com\njdwxs.com\njdxfw.com\njdxzwzx.com\njdygchina.com\njdyou.com\njdypgxw.com\njdysw.com\njdzj.com\njdzldtc.com\njdzol.com\njdzrcw.com\njdzrczpw.com\njdzrencai.com\njdzx365.com\njdzycw.com\njeixun.com\njelsty.com\njerei.com\njewelchina.com\njf1898.com\njfdaily.com\njfdown.com\njfgphzs.com\njfinfo.com\njfm668.com\njfpfw.com\njfrcw.com\njgaoxiao.com\njgfcw.com\njgjob88.com\njgscta.com\njgsdaily.com\njgstudy.com\njh597.com\njha118.com\njhcxl.com\njhdxyy.com\njhnyxx.com\njhpx.com\njhqzw.com\njhrcsc.com\njhrcw.com\njhsssy.com\njhusd.com\njhwcw.com\njhyc.com\njhzwed.com\njia.com\njia123.com\njia360.com\njia400.com\njia99.com\njiabk.com\njiaboohui.com\njiadefu168.com\njiadingtgw.com\njiafang168.com\njiafangyun.com\njiageshi.com\njiahesj.com\njiahesuji.com\njiaji.com\njiajiakt.com\njiajiao114.com\njiajiao400.com\njiajiaoban.com\njiajiashuo.com\njiaju.com\njiajumi.com\njiajuol.com\njialiphoto.com\njiamei188.com\njiameng.com\njiameng001.com\njiameng8.com\njiamisoft.com\njian123.com\njiancai.com\njiancai789.com\njiancaimy.com\njiancaizhanhui.com\njiandanwan.com\njiane86.com\njianfc.com\njianfei.com\njiang7.com\njiangduoduo.com\njiangdurencai.com\njiangduw.com\njianghairc.com\njianghuaipump.com\njianghuairc.com\njiangjiama.com\njiangshi.com\njiangshi99.com\njiangsurc.com\njiangxilvyou.com\njianhucheng.com\njianhuw.com\njianianle.com\njianianya.com\njiankang.com\njiankangcloud.com\njiankangzu.com\njianke.com\njiankongbao.com\njianli-sky.com\njianlip.com\njianlishi.com\njianpu8.com\njianshe001.com\njianshe99.com\njianshen78.com\njianshen8.com\njianshu.com\njianso.com\njianyangjob.com\njianzhi8.com\njianzhiba.com\njianzhijia.com\njianzhiku.com\njiao15.com\njiaodamba.com\njiaomai.com\njiaotanqihuo.com\njiaowolf.com\njiaoyanshi.com\njiaoyimao.com\njiaquan360.com\njiasule.com\njiathis.com\njiatx.com\njiayejob.com\njiayuan.com\njiazhao.com\njiazhaokaoshi.com\njiazhuang.com\njiazhuang6.com\njiazhuoedu.com\njibingnet.com\njichumei.com\njide123.com\njideli.com\njidi.com\njidian365.com\njidianmy.com\njidongrc.com\njiduola.com\njie08.com\njiebohui.com\njiegoushi.com\njiemeng8.com\njieshoujob.com\njietusoft.com\njieu.com\njif419.com\njifang360.com\njihai-edu.com\njiiaa.com\njijidi.com\njijinzige.com\njike.com\njikeu.com\njikexueyuan.com\njilaibao.com\njilaidai.com\njilinfc.com\njilinzhaopin.com\njiluai.com\njimi168.com\njimifashion.com\njimischool.com\njimubox.com\njimuyou.com\njin14.com\njinandazhaxie.com\njinanjuyi.com\njinbangqm.com\njinbaobeiqiming.com\njinbaonet.com\njinbifun.com\njincai1688.com\njindidq.com\njinfengtv.com\njinfuren100.com\njinfuzi.com\njingchurc.com\njingdake.com\njingdianwan.com\njingjishi.com\njingoffice.com\njingpinke.com\njingwei.com\njingyangchun.com\njingyouxi.com\njingzheng.com\njingzhengu.com\njinhantang.com\njinhejs.com\njinhou.com\njinhuang.com\njinhuatv.com\njinhurc.com\njining.com\njinkaixiang.com\njinkaoedu.com\njinku.com\njinlaoshi.com\njinliheng365.com\njinlingdry.com\njinmajia.com\njinmalvyou.com\njinmenrc.com\njinpu.com\njinqijian.com\njinqijian188.com\njinriningxiang.com\njinriwujin.com\njinshangrc.com\njintanwang.com\njinti.com\njintoutiao.com\njintuedu.com\njinxiexpo.com\njinxing-beer.com\njinying365.com\njinyingjie.com\njinzhe.com\njiqimao.com\njisibar.com\njisuxz.com\njita520.com\njitongtianxia.com\njiu30.com\njiu6.com\njiudianzhaopin.com\njiugang.com\njiukuaiwu.com\njiukuaiyou.com\njiushanglianmeng.com\njiutw.com\njiuxian.com\njiuxinxiushen.com\njiuyezhinan.com\njiuzhai.com\njiwu.com\njixielianmeng.com\njixinet.com\njiyidc.com\njiyifa.com\njiyun360.com\njj0833.com\njj20.com\njj59.com\njj597.com\njj831.com\njjbang.com\njjcdn.com\njjckb.com\njjedu.com\njjhh.com\njjhxhb.com\njjjgame.com\njjlxpz.com\njjmmw.com\njjqcw.com\njjrcsc.com\njjshipin.com\njjsrcw.com\njjvcd.com\njjxxk.com\njjzg365.com\njjzyzg.com\njk0760.com\njk51.com\njkbcw.com\njkdown.com\njklxl.com\njkmeishi.com\njkpj.com\njkshhao.com\njkshw.com\njkxdt.com\njkypx.com\njladi.com\njlbaobao.com\njlccpit.com\njlds110.com\njlhighway.com\njlhtcm.com\njlhxjt.com\njlit365.com\njljob88.com\njljsw.com\njlkangda.com\njllib.com\njllnzz.com\njlmhk.com\njlnku.com\njlonline.com\njlsgjt.com\njlshumei.com\njlsmm.com\njlszyy.com\njlthj.com\njly001.com\njlzkb.com\njm-tour.com\njm84.com\njmbao.com\njmdedu.com\njmgczj.com\njmkszx.com\njmmoxiang.com\njmrb.com\njmsdpzx.com\njmsjs.com\njmstatic.com\njmwjm.com\njmy-99.com\njmymh.com\njn001.com\njn025.com\njnbaobao.com\njnbenteng.com\njnbjemba.com\njnesc.com\njngrain.com\njnhouse.com\njnjj.com\njnlc.com\njnlongre.com\njnmaimai.com\njnmama.com\njnmc.com\njnnc.com\njnopfun.com\njnqb.com\njnqche.com\njnqpsh.com\njnticai.com\njnwmw.com\njnxindemei.com\njnzdgk.com\njnzs.com\njob-sky.com\njob0519.com\njob0523.com\njob0663.com\njob0722.com\njob0728.com\njob0768.com\njob0795.com\njob0917.com\njob100.com\njob10000.com\njob1001.com\njob120.com\njob128.com\njob1288.com\njob13580.com\njob168.com\njob1688.com\njob2003.com\njob222.com\njob2299.com\njob250.com\njob256.com\njob263.com\njob335.com\njob36.com\njob369.com\njob51.com\njob5156.com\njob5199.com\njob5588.com\njob592.com\njob5959.com\njob598.com\njob616.com\njob8001.com\njob868.com\njob910.com\njob9151.com\njob916.com\njob98.com\njob9981.com\njob9988.com\njobbaidu.com\njobbw.com\njobcn.com\njobdogame.com\njobeast.com\njobems.com\njobgojob.com\njobhb.com\njobjm.com\njoblc.com\njobpin.com\njobtong.com\njobui.com\njobuy.com\njobxa.com\njobyc.com\njobyp.com\njohnsdier.com\njoingoo.com\njoke01.com\njollaqiyu.com\njoobbe.com\njoroow.com\njovision.com\njowinpen.com\njowong.com\njoy-kids.com\njoy1996.com\njoy76.com\njoyboom.com\njoyes.com\njoyme.com\njoyo.com\njoystech.com\njoytrav.com\njoyyang.com\njpmanga.com\njpskb.com\njpwind.com\njpxm.com\njq-school.com\njqbyby.com\njqw.com\njqzy.com\njr18.com\njrhcw.com\njrj.com\njrlhmm.com\njrrsq.com\njrshx.com\njrsmw.com\njrxjnet.com\njryaw.com\njryghq.com\njs-jinhua.com\njs-lottery.com\njs11183.com\njs118114.com\njs178.com\njs811.com\njs95598.com\njsbc.com\njscj.com\njscsedu.com\njscseea.com\njsenews.com\njsgc168.com\njsjcsmart.com\njsjjgt.com\njsjjx.com\njsjob360.com\njskanghui.com\njslegal.com\njslit.com\njslottery.com\njsly001.com\njsmsg.com\njsmuseum.com\njsnxs.com\njsose.com\njsqdqc.com\njsqnews.com\njsqw.com\njsrcsc.com\njsrsrc.com\njsrugao.com\njsrxny.com\njsrzx.com\njssdfz.com\njssyxx.com\njstianzhuo.com\njstour.com\njstv.com\njswdj.com\njswmw.com\njsxhrcw.com\njsxiaoguo.com\njsxlkaoyan.com\njsxlmed.com\njsxmws.com\njsyjkz.com\njsyks.com\njsymyjs.com\njsyrzz.com\njszg.com\njszhaobiao.com\njszksw.com\njt111.com\njt2car.com\njtbole.com\njtdaw.com\njthysh.com\njtimg.com\njtjiaoyu.com\njtkyw.com\njtlhome.com\njtrmyy.com\njtsz.com\njtxxol.com\njtyou.com\njuanlaoda.com\njuanpi.com\njubaopu.com\njuben108.com\njuboyue.com\njuchang.com\njuchangan.com\njuesheng.com\njuexiang.com\njufanli.com\njufengshang.com\njuhaof.com\njuhuisuan.com\njuimg.com\njujiaonet.com\njule365.com\njuluren.com\njumei.com\njuming.com\njumingwang.com\njunbaike.com\njunjiajob.com\njunph.com\njunpin360.com\njunpinhui.com\njunpinzhi.com\njunqing123.com\njunqing7.com\njunshi.com\njunshi81.com\njunshier.com\njunshijia.com\njunshijidi.com\njunshiqu.com\njunshis.com\njunshishu.com\njunzilian.com\njunzimen.com\njuooo.com\njuren.com\njurenxly.com\njutuw.com\njuwai.com\njuxia.com\njuxian.com\njuxianxinxi.com\njuyanoo.com\njuyaohe.com\njuyouedu.com\njuyouqu.com\njuyouxi.com\njvrong.com\njwgou.com\njx09.com\njx612345.com\njxaas.com\njxbsl.com\njxc-tea.com\njxcc.com\njxcnt.com\njxdasz.com\njxdcw.com\njxdiguo.com\njxdyf.com\njxedt.com\njxepw.com\njxfc365.com\njxfcbbs.com\njxfdcrcw.com\njxfxgy.com\njxgdw.com\njxgjj.com\njxgydc.com\njxgztv.com\njxhcw.com\njxhi.com\njxhjxy.com\njxhyhr.com\njxiz.com\njxjatv.com\njxjiuye.com\njxjls.com\njxjyfw.com\njxjyzy.com\njxjz5.com\njxjzrcw.com\njxkp.com\njxlib.com\njxloufang.com\njxltw.com\njxpf.com\njxpp.com\njxpta.com\njxqcw.com\njxqiche.com\njxrcw.com\njxrczp.com\njxrencai.com\njxrsrc.com\njxrtv.com\njxsalt.com\njxsfybjy.com\njxshangyou.com\njxsrhy.com\njxtourism.com\njxtzw.com\njxxdf.com\njxxyrc.com\njxycw.com\njxydt.com\njxysnews.com\njxzcw.com\njxzwgk.com\njxzyx.com\njy1898.com\njy391.com\njy70.com\njyh007.com\njyhbxg.com\njyimg.com\njyinns.com\njyjsbxg.com\njyqcw.com\njyrcjl.com\njyrck.com\njysns.com\njytongmen.com\njytuangou.com\njyxyyxy.com\njyyuan.com\njz100.com\njz265.com\njz51.com\njz5u.com\njz6.com\njzaq.com\njzb.com\njzcool.com\njzfcol.com\njzgcoal.com\njzggcm.com\njzgjj.com\njzgxlm.com\njzhchr.com\njzhongmu.com\njzjob007.com\njzjzxh.com\njznj.com\njzpt.com\njzqikan.com\njzqnet.com\njzqyw.com\njzrb.com\njzsbs.com\njzszyw.com\njztedu.com\njzwcom.com\njzxgtd.com\njzxq.com\njzxyw.com\njzyx.com\nk0912.com\nk18.com\nk366.com\nk369.com\nk73.com\nk76.com\nk8008.com\nk8k9.com\nka163.com\nkaicent.com\nkaiche100.com\nkaichengschool.com\nkaifu.com\nkaifu100.com\nkaifu7.com\nkaifubiao.com\nkaifuji.com\nkaijianghao.com\nkaiwind.com\nkaixianrc.com\nkaixin001.com\nkaixin7.com\nkaixinbao.com\nkaixinlu.com\nkakaba.com\nkakuedu.com\nkama-classics.com\nkameng.com\nkan300.com\nkan3721.com\nkan98.com\nkandao.com\nkanglu.com\nkangpaiqi.com\nkangq.com\nkanimg.com\nkankan.com\nkankanews.com\nkanny88.com\nkanshaa.com\nkanshu.com\nkantc.com\nkanzg.com\nkanzhun.com\nkao66.com\nkaofudan.com\nkaoguo8.com\nkaogwy.com\nkaojuan.com\nkaolawan.com\nkaopu001.com\nkaoshi110.com\nkaoshidian.com\nkaosuda.com\nkaoup.com\nkaoyan.com\nkaoyan001.com\nkaoyanmeng.com\nkaoyans.com\nkaoyanw.com\nkaoyee.com\nkaozc.com\nkarryhome.com\nkashirc.com\nkaslyju.com\nkazakcnr.com\nkbcool.com\nkbl-jf.com\nkc81.com\nkc86.com\nkchsw.com\nkdcnu.com\nkds100.com\nkdslife.com\nkdweibo.com\nke-sen.com\nkeaidian.com\nkeaiq.com\nkedacom.com\nkedou.com\nkeede.com\nkeepc.com\nkehou.com\nkejianhome.com\nkejiatong.com\nkejihai.com\nkejik.com\nkejiqi.com\nkejixun.com\nkekejp.com\nkekenet.com\nkelanseal.com\nkelon.com\nkelrc.com\nkelwm.com\nkenfor.com\nkengwan.com\nkeqiaojob.com\nkeqii.com\nkeshuaiseo.com\nkesion.com\nketangwu.com\nkeyibao.com\nkeyunzhan.com\nkfcdn.com\nkfcrm.com\nkfrcw.com\nkfrsrcw.com\nkfw001.com\nkgrcw.com\nkhzzm.com\nkidsdown.com\nkidulty.com\nkiiik.com\nkimiss.com\nkin8.com\nkingboard.com\nkingdee.com\nkingriches.com\nkingsoft.com\nkingsun-china.com\nkinhom.com\nkinpan.com\nkj-hr.com\nkjfcw.com\nkk22.com\nkkcapture.com\nkkcoo.com\nkkdkk.com\nkkeju.com\nkkeye.com\nkkk5.com\nkkkmh.com\nkkmami.com\nkksmg.com\nklchao.com\nkllvx.com\nklmyrc.com\nklxuexi.com\nklzuowen.com\nkm100zs.com\nkmcct.com\nkmgfebh.com\nkmguolv.com\nkmmama.com\nkms88.com\nkmszfz.com\nkmvenus.com\nkmy100.com\nkmzp.com\nknowsky.com\nko499.com\nko99.com\nkongfz.com\nkongjie.com\nkongjun.com\nkongzhong.com\nkonka.com\nkooaoo.com\nkoofang.com\nkoolearn.com\nkoowo.com\nkoppers-china.com\nkorirl.com\nkoubei.com\nkoudai.com\nkoudaipe.com\nkoudaitong.com\nkpzs.com\nkq81.com\nkqmr120.com\nkqzp.com\nkrwz.com\nks-lxjy.com\nks116.com\nks5u.com\nksbao.com\nksbbs.com\nksdown.com\nkshot.com\nkslwed.com\nksokjob.com\nksren.com\nkssbw.com\nkt250.com\nkt51.com\nktkkt.com\nktxp.com\nktzpx.com\nku25.com\nku6.com\nku6cdn.com\nku6img.com\nku6vms.com\nkuachen.com\nkuai8.com\nkuaibo.com\nkuaichushou.com\nkuaidadi.com\nkuaidi100.com\nkuaidihelp.com\nkuaiji.com\nkuaijieair.com\nkuaijizheng.com\nkuaikaifu.com\nkuailezu.com\nkuailiyu.com\nkuaiwin.com\nkuaiyong.com\nkuaiyoujia.com\nkuakao.com\nkuche.com\nkuchechina.com\nkuchexiaozhen.com\nkufa88.com\nkugou.com\nkuguanyi.com\nkugz.com\nkuhao360.com\nkujiale.com\nkukahome.com\nkuku123.com\nkukuplay.com\nkukuspeak.com\nkulv.com\nkumanju.com\nkunjuke.com\nkunlun.com\nkunlunxuejucha.com\nkunmingkanghui.com\nkuotu.com\nkuparts.com\nkuqi.com\nkuqyu.com\nkutianxia.com\nkutj.com\nkutongji.com\nkuurl.com\nkuwan8.com\nkuxue.com\nkuyiso.com\nkwxs.com\nkx173.com\nkx43.com\nkxue.com\nkxyik.com\nky007.com\nky0873.com\nky81.com\nkyjxy.com\nkyjyw.com\nkyk8.com\nkyomh.com\nkyp.com\nkypbuy.com\nkytl.com\nkywcdn.com\nkywmall.com\nkz928.com\nkzbigu.com\nkzenglish.com\nkzhuang.com\nkzj365.com\nl-longview.com\nl-wed.com\nl-zzz.com\nlady8844.com\nladyhf.com\nladynest.com\nladysq.com\nladyyu.com\nlafaso.com\nlagou.com\nlagsw.com\nlaianbbs.com\nlaidingba.com\nlaifeng.com\nlaifudao.com\nlaigang.com\nlaijiuye.com\nlaiwang.com\nlaiwu.com\nlaiwumedia.com\nlaiyang58.com\nlamahui.com\nlamaison-arting.com\nlan1001.com\nlanapartments.com\nlanchijituan.com\nlandai.com\nlandbond.com\nlandchina.com\nlandjs.com\nlandks.com\nlandscapecn.com\nlandscapehr.com\nlandtu.com\nlandui.com\nlandzestate.com\nlandzhuhai.com\nlanfcw.com\nlanfw.com\nlange360.com\nlangfly.com\nlanglangjiajiao.com\nlangshanhong.com\nlanguang.com\nlangxudz.com\nlangyache.com\nlanhii.com\nlanhua8.com\nlaniqu.com\nlanjing-lijia.com\nlanou3g.com\nlanpowang.com\nlanrentuku.com\nlanrenyuan.com\nlanrenzhaofang.com\nlanrenzhijia.com\nlantian360.com\nlanxingzhuji.com\nlanyanwan.com\nlanyurz.com\nlaobiao.com\nlaobingmi.com\nlaogu.com\nlaohe5.com\nlaohu.com\nlaohucaijing.com\nlaoke.com\nlaomoo.com\nlaonanren.com\nlaoqianzhuang.com\nlaoren.com\nlaoshitv.com\nlaosizhou.com\nlaoyangchenghu.com\nlaoyindian.com\nlaoyuegou.com\nlashou.com\nlashouimg.com\nlavago.com\nlaw-lib.com\nlaw-star.com\nlaw1818.com\nlawtimeimg.com\nlawyerwq.com\nlazyren.com\nlbgoo.com\nlbrcw.com\nlbx777.com\nlc-rc.com\nlcbtv.com\nlcd88.com\nlcfcw.com\nlchssy.com\nlclabor.com\nlcpop.com\nlcwto.com\nlcxwfc.com\nlcyx.com\nld001.com\nld365.com\nldbj.com\nldgjj.com\nldlx.com\nldmet.com\nldmetals.com\nldrczpw.com\nle3x.com\nleadfutures.com\nleadge.com\nleadoor.com\nleatherhr.com\nlebeibei.com\nlecai.com\nleche.com\nled234.com\nled889.com\nledanji.com\nledbao.com\nledcax.com\nlede.com\nledgb.com\nledth.com\nledu.com\nledugame.com\nledwn.com\nleejiaju.com\nlefanghn.com\nlefeng.com\nleftdays.com\nlegu168.com\nlehecai.com\nlehihi.com\nleho.com\nleho100.com\nlehuozaixian.com\nleidian.com\nleiphone.com\nleixundr.com\nleixunkf.com\nlejiaoyun.com\nlejj.com\nleju.com\nlejuwh.com\nleleketang.com\nleleyx.com\nlelife.com\nlemanchina.com\nlemuzhi.com\nlengcang6.com\nlengxiaohua.com\nlenovo.com\nlenovomm.com\nlenovomobile.com\nlenovosj.com\nlentour.com\nlepinw.com\nleqian.com\nleqiyou.com\nlequ.com\nletao.com\nletfind.com\nletv.com\nletvcdn.com\nletvimg.com\nlewan100.com\nlewaos.com\nlewatek.com\nlexiang365.com\nlexiangrencai.com\nlexueke.com\nlexun.com\nleyoo.com\nleyou.com\nleyueke.com\nlezhi.com\nlezhiweilai.com\nlfang.com\nlfbole.com\nlffdcw.com\nlfgjj.com\nlfrtv.com\nlfsanjiu.com\nlfxww.com\nlg188.com\nlgbzj.com\nlgfang.com\nlgmi.com\nlgo100.com\nlgpic.com\nlgrcsc.com\nlgsou.com\nlh987.com\nlhave.com\nlhjol.com\nlhk110.com\nlhtz.com\nlhxfc.com\nli-ke.com\nli63.com\nli70.com\nliang360.com\nliangjian.com\nliangshixian.com\nliangxunwang.com\nliankebio.com\nlianm.com\nlianshuiren.com\nliansuo.com\nliansuovip.com\nliantu.com\nlianwifi.com\nliao1.com\nliaoing.com\nliaoshenrc.com\nliaozhuangxiu.com\nliazu.com\nliba.com\nlibvideo.com\nlicai18.com\nlicaike.com\nliche365.com\nlidodo.com\nlidroid.com\nliebiao.com\nliebo.com\nliehucn.com\nlieju.com\nlieou.com\nliepin.com\nlietou.com\nlietou-static.com\nliexiaow.com\nlieyou.com\nlieyunwang.com\nlife5000.com\nlifeyoyo.com\nlightget.com\nlighting163.com\nlightingchina.com\nlijiangtv.com\nlijiwan.com\nlijunwang.com\nlikelic.com\nlilingnews.com\nliminghe.com\nlinduren.com\nlinecg.com\nlinekong.com\nlinewow.com\nlinezing.com\nlinfangwang.com\nlinfen365.com\nlingauto.com\nlingkaba.com\nlingnanrc.com\nlingshi.com\nlingtiao.com\nlingtuan.com\nlink-run.com\nlinkbasic.com\nlinkchic.com\nlinkvans.com\nlinkwan.com\nlinlin.com\nlinqingtex.com\nlinqujob.com\nlinuxdiyf.com\nlinwa5678.com\nlinyimama.com\nlinyiren.com\nlinzhourc.com\nlipip.com\nliqu.com\nliqucn.com\nlisanxing.com\nlishi5.com\nlishichunqiu.com\nliuannews.com\nliubj.com\nliudu.com\nliugong.com\nliuhe.com\nliuliangche.com\nliumeinet.com\nliuwanlin.com\nliuxue114.com\nliuxue86.com\nliuxuejie.com\nliuyangjob.com\nliuyuanxing.com\nliuzhousteel.com\nlive0311.com\nlive754.com\nlive800.com\nlivnj.com\nliwai.com\nliwuyou.com\nliyangrc.com\nliyezhongzhi.com\nliyi99.com\nlizhidaren.com\nlizi.com\nlj168.com\nlj597.com\nljcjw.com\nljforest.com\nljgjj.com\nljmeeting.com\nljyongfu.com\nlke100.com\nlkgame.com\nll086.com\nllbtv.com\nllcbbs.com\nllfang.com\nlltqc.com\nllxue.com\nlm111.com\nlmedu100.com\nlmlove.com\nlmtw.com\nln-job.com\nln-rc.com\nln2car.com\nln632.com\nlncci.com\nlndzz.com\nlng123.com\nlngongmu.com\nlnlib.com\nlnlotto.com\nlnptm.com\nlnrcsc.com\nlnrsks.com\nlnspaq.com\nlntycp.com\nlnylfw.com\nlnzhyyjt.com\nlnzsks.com\nlnzzsm.com\nlobotou.com\nlocojoy.com\nlocowan.com\nlocoy.com\nlofter.com\nlogclub.com\nlogo33.com\nlogoai.com\nlogonc.com\nlogopay.com\nlogoquan.com\nlogozhizuowang.com\nloho88.com\nlolitabox.com\nloljieshuo.com\nlolqu.com\nlolxiu.com\nlomge.com\nlomoslife.com\nlong-photo.com\nlongau.com\nlongbasz.com\nlongchengrc.com\nlongchuan5.com\nlongdian.com\nlongfeng.com\nlongfor.com\nlongkangmiaomu.com\nlongkouhaijingfang.com\nlongre.com\nlongshangrc.com\nlongtengcn.com\nlongtugame.com\nlongwenedu.com\nlongyangjj.com\nlongyuebxg.com\nlooedu.com\nloogoo.com\nlookvin.com\nloongzone.com\nlooquan.com\nloorin.com\nlooxiang.com\nlooyu.com\nlooyuoms.com\nlotaoke.com\nlotour.com\nloukou.com\nloulanwang.com\nloupan.com\nlove169.com\nlove616.com\nlovebaoji.com\nlovelian.com\nloveliao.com\nlover88.com\nlovev.com\nlovingjob.com\nlowcn.com\nlp023.com\nlp91.com\nlpc8.com\nlpdyz.com\nlpsrc.com\nlqjob88.com\nlqjy.com\nlqrc028.com\nlqxww.com\nlqzcw.com\nlqzp.com\nlrswl.com\nls0376.com\nls666.com\nlscy18.com\nlsdag.com\nlsgzn.com\nlshangjiu.com\nlshappy.com\nlshui.com\nlsjxww.com\nlsnetlib.com\nlspjy.com\nlsqss.com\nlsqx.com\nlsrczpw.com\nlssdjt.com\nlssen.com\nlstest.com\nlsxt.com\nlszhaopin.com\nlt0769.com\nlt1000.com\nltaaa.com\nltcbase.com\nltcheku.com\nlua99.com\nluan163.com\nluaninfo.com\nluanren.com\nlubanlu.com\nlubansoft.com\nlubanu.com\nlubesale.com\nlubiao.com\nluchengnet.com\nludashi.com\nlufthansa.com\nluguowang.com\nlujiangjob.com\nlujuncn.com\nlukaegg.com\nlunanjob.com\nlundang.com\nlunwenstudy.com\nlunwentianxia.com\nlunwenup.com\nluo8.com\nluobo360.com\nluoherc.com\nluomeifeng.com\nluoohu.com\nluosi.com\nluoyuan597.com\nluozhongxu.com\nlupanshui.com\nlupaworld.com\nlusen.com\nlusongsong.com\nluv66.com\nluwenwang.com\nluxee.com\nluxtarget.com\nluyanbrand.com\nlv3w.com\nlvdichan.com\nlvhezi.com\nlvmama.com\nlvren.com\nlvse.com\nlvseba.com\nlvshou.com\nlvtu.com\nlvtu100.com\nlvye.com\nlvyebx.com\nlvyou114.com\nlvyou1778.com\nlwcj.com\nlwgcw.com\nlwhouse.com\nlwlm.com\nlxroto.com\nlxxnews.com\nlxydoor.com\nlxyes.com\nly.com\nly10000.com\nly234.com\nly333.com\nlyaccp.com\nlyauto.com\nlydhzs.com\nlyemb.com\nlyfcw.com\nlyfeiliao.com\nlyfff.com\nlyg1.com\nlyg188.com\nlygbole.com\nlygczj.com\nlygexpo.com\nlygfish.com\nlygjj.com\nlygmedia.com\nlygnews.com\nlygrc.com\nlyguihua.com\nlygyjs.com\nlyhengyue.com\nlyhero.com\nlyielts.com\nlyjjzd.com\nlymffyjd.com\nlymonalisa.com\nlyqcw.com\nlyqiche.com\nlyrcw.com\nlyredstar.com\nlysteel.com\nlytoday.com\nlytpw.com\nlywww.com\nlywxww.com\nlyxltv.com\nlyy99.com\nlyzhujia.com\nlz6.com\nlz669.com\nlzanju.com\nlzbd.com\nlzgjj.com\nlzhongdian.com\nlzhuba.com\nlzk99.com\nlztvnet.com\nlztxw.com\nlzxjyj.com\nlzyysd.com\nlzyysw.com\nlzzfgjj.com\nm10cdn.com\nm18.com\nm1905.com\nm3fc.com\nm3guo.com\nm3guocdn.com\nm598.com\nm6699.com\nma35.com\nmacgg.com\nmacgood.com\nmachine35.com\nmachine365.com\nmacmicst.com\nmacromedia.com\nmade-in-china.com\nmaercn.com\nmahua.com\nmaichawang.com\nmaidong100.com\nmaifang.com\nmaijipu.com\nmaijiuwang.com\nmainone.com\nmaishushi.com\nmaituan.com\nmaiwaiwai.com\nmaiyadi.com\nmaizhixiu.com\nmake365.com\nmakepolo.com\nmalait.com\nmalataedu.com\nmalmam.com\nmama100.com\nmama999.com\nmamabaobao.com\nmamacn.com\nmamecn.com\nmamimp3.com\nman189.com\nmanagershare.com\nmandarinmorning.com\nmangocity.com\nmanhuadao.com\nmanhuawan.com\nmanmankan.com\nmanpianyi.com\nmansuno.com\nmanxiangyi.com\nmanyart.com\nmanyou.com\nmanzhan.com\nmanzuo.com\nmaodou.com\nmaomingbao.com\nmaoocoffee.com\nmaopuyouxi.com\nmaoren8.com\nmaotaifamily.com\nmaoyidi.com\nmaoyigu.com\nmaoyiw.com\nmaoyl.com\nmaozhiwang.com\nmapabc.com\nmapbar.com\nmarieclairechina.com\nmarketreportchina.com\nmarry52.com\nmartell.com\nmasamaso.com\nmasej.com\nmasfy.com\nmasgl.com\nmasgq.com\nmasjia.com\nmaszs.com\nmaxpda.com\nmayangnews.com\nmayi.com\nmayiw.com\nmayiyy.com\nmazuworld.com\nmb5u.com\nmbachina.com\nmbajyz.com\nmbalib.com\nmbaobao.com\nmbatrip.com\nmbscss.com\nmbsimg.com\nmbsky.com\nmc-test.com\nmc0513.com\nmc1314.com\nmc361.com\nmccet.com\nmcchina.com\nmcmbaobao.com\nmcmqyc.com\nmcshe.com\nmd379.com\nmdjiaqi.com\nmdjmzj.com\nmdvoo.com\nmeadin.com\nmechr.com\nmecjob.com\nmed126.com\nmed518.com\nmed66.com\nmedejob.com\nmediaplex.com\nmediav.com\nmeerlove.com\nmeet99.com\nmefun.com\nmegong.com\nmei-pan.com\nmeidebi.com\nmeidianwang.com\nmeiguoshenpo.com\nmeijing.com\nmeijitea.com\nmeijugou.com\nmeijw.com\nmeilele.com\nmeilijia.com\nmeiling.com\nmeilishi.com\nmeilishuo.com\nmeiliy.com\nmeimeidu.com\nmeimingteng.com\nmeinv.com\nmeinvpo.com\nmeipai.com\nmeipo360.com\nmeishanjob.com\nmeishanren.com\nmeishichina.com\nmeishimeike.com\nmeishitui.com\nmeishurencai.com\nmeitantong.com\nmeitanwang.com\nmeitu.com\nmeituan.com\nmeitudata.com\nmeituyuan.com\nmeiwei123.com\nmeiwenting.com\nmeiyanqiangyi.com\nmeizhan.com\nmeizhou.com\nmeizu.com\nmeizuhui.com\nmellk.com\nmemall360.com\nmengpakezhan.com\nmengyoo.com\nmengzhou.com\nmenkou.com\nmenred.com\nmenwww.com\nmenye.com\nmepfair.com\nmepprice.com\nmetal35.com\nmetalchina.com\nmeyol.com\nmf08s.com\nmf528.com\nmfcad.com\nmffanwen.com\nmfjzs.com\nmfmf100.com\nmfqyw.com\nmfunz.com\nmfw365.com\nmg886.com\nmggzw.com\nmgyapp.com\nmgyun.com\nmh163k.com\nmhdenglish.com\nmhimg.com\nmi.com\nmi-img.com\nmi700.com\nmian4.com\nmianbao.com\nmianfeiic.com\nmiantuanwang.com\nmianyangauto.com\nmiaogu.com\nmiaokenet.com\nmiaomudi.com\nmiaomuzhan.com\nmiaopai.com\nmiaotiao.com\nmiaozhen.com\nmicamika.com\nmicrosci.com\nmidea.com\nmier123.com\nmiercn.com\nmikecrm.com\nmilan-bride.com\nmilankezhan.com\nmilanvip.com\nmilchina.com\nmiliao.com\nmilnews.com\nmilnews2.com\nmilzx.com\nmimajs.com\nmimimama.com\nmimiwan.com\nmine168.com\nminesjob.com\nmingdejx.com\nminggou.com\nminghong88.com\nmingjian.com\nmingluji.com\nmingong123.com\nmingshiedu.com\nmingshitang.com\nmingxing.com\nmingxingku.com\nmingyue.com\nmingyuege.com\nmingzhurc.com\nminhang.com\nmining120.com\nmininghr.com\nminjiangrc.com\nminnandianshang.com\nminshengart.com\nminshenglife.com\nminzhujie.com\nmipang.com\nmirautomation.com\nmirosoundvision.com\nmisall.com\nmissku.com\nmissyuan.com\nmituku.com\nmiui.com\nmiyucun.com\nmizhe.com\nmj37.com\nmjceo.com\nmjdec.com\nmjmjm.com\nmjoys.com\nmjqy.com\nmjrcw.com\nmkxk.com\nmkzhan.com\nmlbuy.com\nmlctsrq.com\nmlm114.com\nmlt01.com\nmmall.com\nmmarket.com\nmmbang.com\nmmfj.com\nmmgogo.com\nmmimm.com\nmmjyw.com\nmmrcw.com\nmmsfw.com\nmmstat.com\nmmstw.com\nmmwan.com\nmmyouxi.com\nmmyuer.com\nmmzh.com\nmnkyy.com\nmnlsbj.com\nmnsfh.com\nmnwww.com\nmob.com\nmobanku.com\nmobanwang.com\nmobao.com\nmobile-dad.com\nmobiletalkclub.com\nmodian.com\nmoejam.com\nmofang.com\nmofangge.com\nmogujie.com\nmojichina.com\nmokaxiu.com\nmoke8.com\nmokylin.com\nmoliuxiang.com\nmoloong.com\nmolychina.com\nmomachina.com\nmomihouse.com\nmomo35.com\nmomolili.com\nmonhr.com\nmonteamor.com\nmonternet.com\nmontesea.com\nmoobuu.com\nmoofor.com\nmoon777.com\nmoonbasa.com\nmop.com\nmoshou.com\nmosopower.com\nmostrend.com\nmotherbuy.com\nmotie.com\nmotieimg.com\nmotnt.com\nmotorchina.com\nmoukao.com\nmouldbbs.com\nmouldintl.com\nmouldjob.com\nmouldu.com\nmoutaichina.com\nmoveredu.com\nmowuhe.com\nmoyoutang.com\nmoyoyo.com\nmozillaonline.com\nmpbang.com\nmpdsj.com\nmplife.com\nmppmpp.com\nmquanquan.com\nmrgushi.com\nmrmfzp.com\nmrrencai.com\nmrwpx.com\nmrzpw.com\nmrzswang.com\nms0538.com\nms315.com\nms6666111.com\nmscbsc.com\nmsddp.com\nmsddt.com\nmsgjj.com\nmsn.com\nmsq86.com\nmsrfc.com\nmssqw.com\nmstxx.com\nmsw86.com\nmszxyh.com\nmtime.com\nmtjk.com\nmtklw.com\nmtnets.com\nmttang.com\nmtv123.com\nmtw001.com\nmtzkz.com\nmuch001.com\nmudanpin.com\nmumayi.com\nmuniao.com\nmusicchina-expo.com\nmuyang.com\nmuyee.com\nmuying.com\nmuyingjie.com\nmuyingzhijia.com\nmuyuqq.com\nmuzhibus.com\nmuzhiwan.com\nmuzisoft.com\nmvomvo.com\nmw1950.com\nmx175.com\nmxhichina.com\nmxpcp.com\nmxwz.com\nmy-zz.com\nmy0511.com\nmy0538.com\nmy0768.com\nmy0792.com\nmy0813.com\nmy12345.com\nmy399.com\nmy4399.com\nmy71.com\nmyantu.com\nmyapp.com\nmybulkstock.com\nmybuxiu.com\nmybwu.com\nmybxg.com\nmycar168.com\nmycarbbs.com\nmychefang.com\nmychemjob.com\nmyclub2.com\nmyclubmall.com\nmydiyclub.com\nmydrivers.com\nmyepjob.com\nmyf6.com\nmyfule.com\nmyfun7.com\nmygame66.com\nmygymchina.com\nmyhack58.com\nmyinsbroker.com\nmyir-tech.com\nmyjianzhu.com\nmyjiaxiang.com\nmyjmw.com\nmyjob.com\nmyluban.com\nmynfd.com\nmyoneone.com\nmypake.com\nmypethome.com\nmypharma.com\nmypxb.com\nmyqcloud.com\nmyqtyy.com\nmyra2.com\nmyshipjob.com\nmysjtu.com\nmysodao.com\nmysteel.com\nmysteelcdn.com\nmysteelcms.com\nmysteelresearch.com\nmysteelweekly.com\nmysvw.com\nmytaofang.com\nmytaofun.com\nmytophome.com\nmyubbs.com\nmyverydz.com\nmyyouse.com\nmyyule.com\nmyzaker.com\nmyzcm.com\nmyzhidao.com\nmyzx365.com\nmz001.com\nmzche.com\nmzhw.com\nmzjia.com\nmzklg.com\nmzrcw.com\nmzstatic.com\nmzwok.com\nmzyfz.com\nn371.com\nna597.com\nnahuo.com\nnai2.com\nnaitang.com\nnalichi.com\nnaliwan.com\nnanbeiyou.com\nnandu.com\nnanhunnvjia.com\nnanjob.com\nnanlue.com\nnanningjie.com\nnanpw.com\nnansha365.com\nnanshikaoyan.com\nnanshiw.com\nnantaihu.com\nnanyuenews.com\nnanzhao1.com\nnanzhaohm.com\nnarkii.com\nnarutom.com\nnaxue.com\nnaxww.com\nnayao.com\nnazhengshu.com\nnb-rcw.com\nnb-water.com\nnb119.com\nnb160.com\nnba.com\nnbark.com\nnbbltv.com\nnbbus.com\nnbccts.com\nnbcei.com\nnbch2sc.com\nnbchem.com\nnbcoop.com\nnbctsg.com\nnbcyy.com\nnbebi.com\nnbedi.com\nnbfce.com\nnbgjj.com\nnbgy.com\nnbhky.com\nnbidea.com\nnbjczx.com\nnbjmrc.com\nnbmovie.com\nnbmtw.com\nnbmyhome.com\nnbqcrl.com\nnbqfc.com\nnbradio.com\nnbrcw.com\nnbrczp.com\nnbsz.com\nnbtarena.com\nnbtelecom.com\nnbtjzx.com\nnbwater.com\nnbweekly.com\nnbxsrc.com\nnbyouth.com\nnbzhrc.com\nncdiy.com\nncfz.com\nncghj.com\nnchdz.com\nnchqw.com\nncielts.com\nnciyuan.com\nncoto.com\nncpqh.com\nncqiche.com\nncrczpw.com\nnctudi.com\nncxb.com\nncxww.com\nnczl.com\nnczx8.com\nnd090.com\nnd597.com\nnddaily.com\nndfang.com\nndgjj.com\nndjczx.com\nndrcw.com\nndt88.com\nnduoa.com\nnduotuan.com\nne21.com\nne365.com\nne51.com\nne56.com\nnecoal.com\nnectar-farm.com\nneeu.com\nnei-mao.com\nneiee.com\nneihan8.com\nneikupp.com\nneimengrc.com\nnengyuan.com\nnenqiu.com\nneo-neon.com\nneonan.com\nnerjob.com\nnet114.com\nnetandtv.com\nnetbai.com\nnetbian.com\nnetease.com\nnetecweb.com\nnetentsec.com\nnetsun.com\nnetworkbrand.com\nneupioneer.com\nnew-ci.com\nnew-motherhood.com\nnew123.com\nnew7.com\nnewacer.com\nnewaq.com\nnewcger.com\nnewexpo.com\nnewft.com\nnewhua.com\nnews-chtf.com\nnews0635.com\nnews18a.com\nnewsccn.com\nnewscv.com\nnewseasoft.com\nnewshainan.com\nnewshs.com\nnewsmy.com\nnewsxc.com\nnewsxy.com\nnewsyc.com\nnewtonghua.com\nnewzealand.com\nnewzgc.com\nnewzhongyuan.com\nnextsee.com\nnfcmag.com\nnfcnw.com\nnffair.com\nnfinv.com\nnfmedia.com\nnfpeople.com\nnfrencai.com\nnftec.com\nnfwin.com\nnfypw.com\nngbbs.com\nngfang.com\nngotcm.com\nnhaidu.com\nnhcsw.com\nnhnw.com\nnhvisit.com\nnhxxg.com\nnhzj.com\nniangyuan.com\nnianw.com\nniaogebiji.com\nnicai.com\nniceloo.com\nnicocn.com\nniczy.com\nnight9.com\nnihaowang.com\nnike.com\nnikefans.com\nnimtt.com\nningbo-airport.com\nningbobb.com\nningbochina.com\nningxiangrc.com\nninicat.com\nninxun.com\nnipic.com\nniuchengnews.com\nniuchengrc.com\nniuchengwang.com\nniutrip.com\nniutuku.com\nniuwan.com\nniuyang98.com\nniwodai.com\nnixiba.com\nnj110.com\nnj127.com\nnjcgs.com\nnjcqjy.com\nnjcw.com\nnjd1.com\nnjdfwb.com\nnjgqzs.com\nnjhaiwai.com\nnjiairport.com\nnjjsyy.com\nnjlongre.com\nnjltmp.com\nnjmama.com\nnjmuseum.com\nnjprice.com\nnjrsks.com\nnjrsrc.com\nnjsdy.com\nnjtarena.com\nnjtctg.com\nnjutcie.com\nnjxg.com\nnjxzcy.com\nnjycyj.com\nnk96728.com\nnksjjxh.com\nnlypx.com\nnmcqjy.com\nnmgexpo.com\nnmgfic.com\nnmgjdxy.com\nnmgjrw.com\nnmglabs.com\nnmgrc.com\nnmgwww.com\nnmgzkj.com\nnmhbj.com\nnmrcw.com\nnmsti.com\nnn600.com\nnndme.com\nnnfxcs.com\nnngjj.com\nnnhdqm.com\nnnjob.com\nnnmama.com\nnnn666.com\nnntlj.com\nnnwb.com\nnnzgz.com\nnnzp.com\nno1w.com\nnoblepen.com\nnongchengws.com\nnongcun5.com\nnongji1688.com\nnongji360.com\nnongjitong.com\nnongjx.com\nnongli.com\nnongmiao.com\nnongmintv.com\nnongminzhuanye.com\nnongrisheng.com\nnongyao001.com\nnongyerc.com\nnongzi100.com\nnongzi360.com\nnongzihr.com\nnonobank.com\nnowec.com\nnowscore.com\nnowxue.com\nnp5.com\nnp597.com\nnpcka.com\nnpckk.com\nnpcoop.com\nnpgjj.com\nnpicp.com\nnpjt.com\nnpjy.com\nnpxzb.com\nnrparking.com\nnst666.com\nnsw88.com\nnsxia.com\nnsy6.com\nntalker.com\nntgjj.com\nnthfw.com\nntjob88.com\nntjoy.com\nntjxj.com\nntrc.com\nntrgrcw.com\nntvimg.com\nntwenming.com\nnuandao.com\nnuansou.com\nnubb.com\nnuomi.com\nnuozhan.com\nnusrc.com\nnuxue.com\nnv43.com\nnvrenfang.com\nnvsheng.com\nnvxing163.com\nnwyhw.com\nnx28.com\nnxass.com\nnxcoop.com\nnxdzkj.com\nnxedu.com\nnxfang.com\nnxflcp.com\nnxfwz.com\nnxgcw.com\nnxgsl.com\nnxkongtiao.com\nnxnba.com\nnxnk.com\nnxsks.com\nnxycedu.com\nnxzgh.com\nnxzpt.com\nnxzyk.com\nny0538.com\nny1988.com\nny3721.com\nny8888.com\nnyato.com\nnyipcn.com\nnyjjchina.com\nnyljw.com\nnypxw.com\nnyrencai.com\nnysjw.com\nnyxzp.com\nnyycw.com\nnyyintong.com\nnz165.com\nnz86.com\nnzczq.com\nnzjsw.com\nnzstatic.com\nnzw-china.com\noa8000.com\noacio.com\noadz.com\nob1000.com\nobolee.com\noceanchina.com\noceanol.com\nocoal.com\noctc.com\nodourchina.com\noeeee.com\noem17.com\noemol.com\noemresource.com\noeofo.com\noephp.com\nofcard.com\noffcn.com\nofficeask.com\nofficebc.com\nofficese.com\nofpay.com\nofuns.com\nofweek.com\nofzx.com\nogoqz.com\noh100.com\noho168.com\nohqly.com\noi22.com\noicq88.com\noilequipcn.com\noilhr.com\noiwm.com\nok0559.com\nok0737.com\nok11.com\nok165.com\nok87.com\nokbao.com\nokbuy.com\nokbuycdn.com\nokeycar.com\nokfh.com\nokgj.com\nokhqb.com\noklx.com\nokmaidan.com\nokmeeting.com\nokmessi.com\nokmk.com\nokooo.com\nokoooimg.com\nokwanwan.com\nokzhuhai.com\nokzjj.com\nol-img.com\nolcdn.com\noldcp.com\nolder99.com\noledw.com\nolyun.com\nom-f.com\nometal.com\nonccc.com\none101.com\none79.com\nonekao.com\nonekeyrom.com\nonepiecer.com\noneplusbbs.com\nonjobedu.com\nonlinesjtu.com\nonlylady.com\noo6s.com\noocheoo.com\noodii.com\nooomm.com\nooopic.com\nooqiu.com\noosyoo.com\nopda.com\nopen-open.com\nopenwbs.com\noperachina.com\noppein.com\nopplandcorp.com\nopple.com\noptaim.com\noralpractice.com\noranpage.com\norgcc.com\norggx.com\norgnitu.com\noriginclean.com\norsoon.com\nostudytour.com\not51.com\nou99.com\noubohao.com\noujiangrc.com\noupeng.com\nourgame.com\nourpanda.com\nourtra.com\nourxun.com\nouryao.com\noussko.com\noutlets365.com\nouwan.com\nouyaagri.com\nouyaoxiazai.com\nouyicg.com\novupre.com\noyehi.com\noynkyy.com\nozhibao.com\np-e-china.com\np44.com\npache.com\npackceo.com\npackrc.com\npadsj.com\npadtt.com\npahaoche.com\npahou.com\npaidai.com\npaidui.com\npaihang360.com\npaileduo.com\npainb.com\npaiorg.com\npaipai.com\npaipaiimg.com\npaishoes.com\npaljw.com\npanduola.com\npanelook.com\npanguso.com\npanjiayuan.com\npanjk.com\npansino-solutions.com\npanzz.com\npaochefang.com\npaojiao.com\npaokoo.com\npaopaoku.com\npaoxue.com\npaperopen.com\nparalworld.com\nparatong.com\nparis-bride.com\npartinchina.com\npassportmanagement.com\npassxmu.com\npazx888.com\npc3w.com\npc4s.com\npc6.com\npc811.com\npc841.com\npcb818.com\npcbchinanet.com\npcbeta.com\npcbokjob.com\npcpc521.com\npcpop.com\npctowap.com\npdfangchan.com\npdshouse.com\npdsqcw.com\npdsxww.com\npe-fund.com\npe168.com\npe51.com\npe898.com\npegjj.com\npeixun22.com\npeixunfei.com\npeixuntong.com\npeixuntop.com\npengchengrc.com\npengfu.com\npengfuw.com\npenglaiu.com\npengpeng.com\npengrc.com\npengyou.com\npengzerencai.com\npeople258.com\npeoplephoto.com\npeoplerail.com\npethr.com\npetzp.com\npf178.com\npfwang.com\npg369.com\nph-fc.com\nph2009.com\nph66.com\npharm1718.com\npharmjx.com\nphb123.com\nphilips.com\nphoenixtv.com\nphotops.com\nphotoshopcn.com\nphotosichuan.com\nphp100.com\nphp186.com\nphpchina.com\nphpcoo.com\nphpwind.com\nphpyun.com\nphzfw.com\nphzp.com\npianyifun.com\npiao.com\npiao88.com\npiaojia.com\npiaojin.com\npiaoliang.com\npibaihui.com\npicchealth.com\npiedia.com\npifuyy.com\npig66.com\npigehr.com\npigerencai.com\npigpignet.com\npikadd.com\npimei.com\npin5i.com\npinbg.com\npincai.com\npinfengws.com\npingan.com\npingguo7.com\npingguolv.com\npingshu8.com\npingtan597.com\npingtan66.com\npingtandao.com\npingwest.com\npinjiao.com\npinkecity.com\npinker365.com\npinla.com\npinpai-qq.com\npinpai37.com\npinpaibaike.com\npinpaidongli.com\npinpaihudong.com\npinpinwang.com\npinshan.com\npintour.com\npinyouc.com\npipa.com\npipaw.com\npjhku.com\npjtime.com\npk350.com\npk38.com\npk66.com\npkpkpk.com\npkufi.com\npkulaws.com\npkurc.com\npkzx.com\npl520.com\nplateno.com\nplayacg.com\nplxww.com\npmcaff.com\npmdoudou.com\npmxsd.com\npnzpw.com\npocosite.com\npodinns.com\npogare.com\npolocai.com\npoluoluo.com\npolycn.com\npomoho.com\npooher.com\npop-bags.com\npop-fashion.com\npop-shoe.com\npop136.com\npop800.com\npopdalian.com\npopoho.com\npoppur.com\npopwan.com\nport-m.com\npostsc.com\nposuijianzhulaji.com\npotevio.com\npowercdn.com\npowerde.com\npowerfoo.com\npozjzz.com\npozzm.com\npp250.com\nppa18.com\nppaaol.com\nppdai.com\nppgoo.com\nppgys.com\npphgjx.com\nppkao.com\npplive.com\nppmarket.com\npppoo.com\nppsimg.com\nppstream.com\nppswan.com\npptbz.com\npptv.com\nppwan.com\nppxmw.com\nppzhan.com\nppzhangui.com\nppzsw.com\nppzuowen.com\npradafashionstore.com\nprcedu.com\nprinthr.com\nprnasia.com\nprocesson.com\nproject-oa.com\npsahz.com\npsbc.com\npsjia.com\npsmoban.com\npstatp.com\npsychcn.com\npsycofe.com\npt163.com\npt597.com\npt791.com\nptacn.com\nptbus.com\nptdao.com\nptfcxx.com\nptfdc.com\nptgxs.com\nptjy.com\nptmfrc.com\nptotour.com\nptpcp.com\nptrcw.com\nptsqjy.com\nptzpqz.com\nptztb.com\npuahome.com\npubchn.com\npuepu.com\npuercn.com\npuerlife.com\npuertea8.com\npujia.com\npump999.com\npumpzc.com\npunai.com\npupuwang.com\npusa123.com\nputaomiaomu.com\nputclub.com\nputschool.com\npuxinjingshe.com\npv-ledzm.com\npvall.com\npvc-sujiao-diban.com\npvc123.com\npvcpu.com\npvcqihuo.com\npx0769.com\npx33.com\npx8.com\npxcn168.com\npxmfw.com\npxrczpw.com\npxrencai.com\npxsww.com\npxtew.com\npy168.com\npybxfc.com\npybxrc.com\npycars.com\npygbw.com\npyinfo.com\npyjia.com\npylove.com\npytogo.com\npyxww.com\npyzhufang.com\npzfcw.com\npzgt.com\npzhgjj.com\npzhls.com\npzhr.com\npzjyw.com\npzoom.com\npzsh.com\npzsns.com\npztuan.com\nq-ce.com\nq0580.com\nq1.com\nq68.com\nqalex.com\nqbaobei.com\nqbdjjw.com\nqbjtour.com\nqc1818.com\nqc188.com\nqc6.com\nqc99.com\nqcloud.com\nqcplay.com\nqcqcw.com\nqcrencai.com\nqctsw.com\nqcwe.com\nqcwp.com\nqdairport.com\nqdbeian.com\nqdcaijing.com\nqdcars.com\nqdcdn.com\nqdcuishi.com\nqdfdc.com\nqdgjg.com\nqdgjj.com\nqdhibi.com\nqdit.com\nqdjiazheng.com\nqdlongre.com\nqdmm.com\nqdnrc.com\nqdnrm.com\nqdoulu.com\nqdqiche.com\nqdtianzhen.com\nqdwenxue.com\nqdxumu.com\nqdyjjh.com\nqdzkb.com\nqdzqs.com\nqeecn.com\nqeeka.com\nqegee.com\nqeqeqe.com\nqf521.com\nqfang.com\nqfcmr.com\nqffc8.com\nqfwzw.com\nqfzp.com\nqg597.com\nqglish.com\nqgpx.com\nqgrcsc.com\nqh12301.com\nqhcitc.com\nqhcmw.com\nqhcqjy.com\nqhdnews.com\nqhdrc.com\nqhdxw.com\nqhfcw.com\nqhflh.com\nqhgate.com\nqhhbly.com\nqhimg.com\nqhjiaye.com\nqhkxw.com\nqhlly.com\nqhmed.com\nqhnews.com\nqhpta.com\nqhradio.com\nqhrcsc.com\nqhsrcw.com\nqhstv.com\nqhswdx.com\nqhttw.com\nqhwriter.com\nqhwsjd.com\nqhzk.com\nqi-che.com\nqiancheng100.com\nqianchengriben.com\nqiandao.com\nqianggen.com\nqiangmi.com\nqiangpiao.com\nqianhuaweb.com\nqianinfo.com\nqianjia.com\nqianjiangjob.com\nqiankunlt.com\nqianlijob.com\nqianlima.com\nqianlong.com\nqianlongnews.com\nqianqian.com\nqianshanren.com\nqianweb.com\nqianxs.com\nqianyan001.com\nqianyecao.com\nqianyuangx.com\nqianzhan.com\nqianzhan123.com\nqianzheng88.com\nqianzhengdaiban.com\nqiaob2b.com\nqiaobutang.com\nqiaohule.com\nqiaowazi.com\nqiaxing.com\nqibosoft.com\nqicaispace.com\nqicaiwan.com\nqichecailiao.com\nqichelian.com\nqichengwang.com\nqichepeijian.com\nqichepinpai.com\nqichetong.com\nqicheyouqi.com\nqicou.com\nqidian.com\nqidou.com\nqieta.com\nqifabao.com\nqihaowh.com\nqihihi.com\nqihoo.com\nqihuituan.com\nqihuiwang.com\nqihuozige.com\nqijiangjob.com\nqijuib.com\nqikan.com\nqilibali.com\nqiligift.com\nqilindao.com\nqilooo.com\nqiluauto.com\nqilumovie.com\nqinbei.com\nqincai.com\nqindaohr.com\nqing5.com\nqingdao163.com\nqingdaochina.com\nqingdaoertong.com\nqingdaoielts.com\nqingdaomedia.com\nqingdaonews.com\nqingdaosailingworldcup.com\nqingfenggu.com\nqingguo.com\nqinghua211.com\nqinghuaonline.com\nqingju.com\nqingrenw.com\nqingsongwan.com\nqingweilou.com\nqingyout.com\nqingyy.com\nqingzhou365.com\nqiniu.com\nqiniudn.com\nqinlianwang.com\nqinmiaofuhua.com\nqinqin.com\nqinqiner.com\nqinrun.com\nqinseo.com\nqinxue365.com\nqionghaif.com\nqionghaifc.com\nqiongzhourc.com\nqipaiyouxi.com\nqipaoxian.com\nqipei001.com\nqipeipin.com\nqipeiren.com\nqipeizhan.com\nqiqi168.com\nqiqi6688.com\nqiqibudy.com\nqiqihaenews.com\nqiremv.com\nqiucinews.com\nqiuxian.com\nqiwuliulanqi.com\nqixing365.com\nqixingtang.com\nqixiujie.com\nqiye56.com\nqiyefalvguwen.com\nqiyegu.com\nqiyexxw.com\nqiyi.com\nqiyipic.com\nqiyouwang.com\nqiyue.com\nqizhongji.com\nqjdrying.com\nqjeda.com\nqjfang.com\nqjfdcw.com\nqjherb.com\nqjhte.com\nqjis.com\nqjrc.com\nqjren.com\nqjsxtz.com\nqjw99.com\nqjxzsp.com\nqjy168.com\nqjz.com\nqk365.com\nqkankan.com\nqkfang.com\nqlbchina.com\nqljgw.com\nqljr.com\nqlrc.com\nqlrc114.com\nqltarena.com\nqlwbshy.com\nqm120.com\nqmango.com\nqmingw.com\nqn71.com\nqnsb.com\nqp1001.com\nqp110.com\nqp966.com\nqplus.com\nqpzx.com\nqq.com\nqq-wan.com\nqq163.com\nqq190.com\nqq295925172.com\nqq373.com\nqq745.com\nqq8877.com\nqq990.com\nqqbaobao.com\nqqbiaoqing.com\nqqbifen.com\nqqbody.com\nqqcyl.com\nqqdcw.com\nqqdm.com\nqqershou.com\nqqfb.com\nqqfenzu.com\nqqgexingqianming.com\nqqhot.com\nqqhrnews.com\nqqjay.com\nqqjia.com\nqqjswang.com\nqqkqw.com\nqqma.com\nqqmail.com\nqqmcc.com\nqqpao.com\nqqpifu.com\nqqshuoshuo.com\nqqsort.com\nqqssn.com\nqqtbw.com\nqqthj.com\nqqtn.com\nqqtouxiang.com\nqqtu8.com\nqqtz.com\nqqu360.com\nqqwkids.com\nqqwm2014.com\nqqwuhan.com\nqqwwr.com\nqqxoo.com\nqqxxzx.com\nqqya.com\nqqyou.com\nqqyy.com\nqqzbz.com\nqqzl.com\nqqzssl.com\nqqzyw.com\nqqzywang.com\nqqzzhh.com\nqshang.com\nqsn365.com\nqstatic.com\nqtaidu.com\nqth8.com\nqthdaily.com\nqthnews.com\nqthtv.com\nqtour.com\nqtpep.com\nqtulou.com\nqu114.com\nqu247.com\nqu97.com\nquanhuaoffice.com\nquanji.com\nquanjiamei.com\nquanjing.com\nquanjingke.com\nquanjinglian.com\nquanlaoda.com\nquanmama.com\nquanshunjiazheng.com\nquanzhi.com\nqubaihuo.com\nqudao.com\nqudao168.com\nqudong.com\nqueshao.com\nquhua.com\nqujianglou.com\nqule8.com\nqulishi.com\nqulv.com\nqumaishu.com\nqumei.com\nqumenhu.com\nquna.com\nqunachi.com\nqunar.com\nqunarzz.com\nqunhaowang.com\nqunxianart.com\nqupingche.com\nqupk.com\nqutuly.com\nquwan.com\nquwanwan.com\nquxia.com\nquxiu.com\nquzhao.com\nqvod.com\nqw168.com\nqwjian.com\nqwqtw.com\nqwsy.com\nqx-pump.com\nqx121.com\nqx162.com\nqx818.com\nqx960.com\nqxmesh.com\nqxnic.com\nqxw18.com\nqxyou.com\nqy139.com\nqy6.com\nqybc.com\nqyceo.com\nqycn.com\nqyer.com\nqyjpzx.com\nqymssc.com\nqyrb.com\nqyt.com\nqyucn.com\nqyxyw.com\nqyzyw.com\nqz123.com\nqz597.com\nqz828.com\nqzbbs.com\nqzce.com\nqzfood.com\nqzfznews.com\nqzgb.com\nqzgjj.com\nqzhi5.com\nqzlcxww.com\nqzone.com\nqzrcw.com\nqzrczpw.com\nqzrls.com\nqzrtvu.com\nqztour.com\nqzwb.com\nqzwhcy.com\nqzyb.com\nr018.com\nr021.com\nr0580.com\nra10000.com\nrabook.com\nracecareer.com\nracing001.com\nradiohz.com\nradiotj.com\nrain8.com\nranshao.com\nraorao.com\nrapidppt.com\nraresd.com\nratuo.com\nrayp.com\nrb139.com\nrbtmm.com\nrc0722.com\nrc0732.com\nrc0817.com\nrc1001.com\nrc114.com\nrc365.com\nrc3721.com\nrc392.com\nrc536.com\nrc595.com\nrc775.com\nrc916.com\nrca8.com\nrcdang.com\nrcdio.com\nrceee.com\nrctong.com\nrcuu.com\nrcw0375.com\nrcw0391.com\nrcw395.com\nrcxx.com\nrdqh.com\nrdyjs.com\nreadlishi.com\nreadmeok.com\nreadnovel.com\nrecycle366.com\nrecyclechina.com\nredcrossol.com\nredidai.com\nredocn.com\nredstonevilla.com\nreedhuabo.com\nregishome.com\nrencai5.com\nrencaiabc.com\nrencaijob.com\nrencailu.com\nrenren.com\nrenren-inc.com\nrenrensucai.com\nrenrentou.com\nrenrenzhe.com\nrenrzx.com\nrensoo.com\nrenwen.com\nreporthb.com\nreportrc.com\nreportway.com\nrexuedongman.com\nrexuemil.com\nrfchina.com\nrfidm2m.com\nrfthr.com\nrg50.com\nrgfcw.com\nrgrc365.com\nrgzpw.com\nrichagri.com\nrihanyu.com\nrijigu.com\nrilajoy.com\nriliw.com\nrisfond.com\nrj0514.com\nrjzxw.com\nrkzdh.com\nrlzygl.com\nrmburl.com\nrmhospital.com\nrmzt.com\nroadexam.com\nroadoor.com\nroadqu.com\nrobam.com\nroboo.com\nrobot-china.com\nrobot-home.com\nrockszh.com\nrockyenglish.com\nrogi-stric.com\nromanka.com\nromantic214.com\nromjd.com\nromschina.com\nromzj.com\nroncua.com\nrong360.com\nrongbiz.com\nrongchao.com\nrongeasy.com\nrongshidai.com\nrongshuxia.com\nrongxingroup.com\nrongzicn.com\nrongzizulin.com\nrootinhenan.com\nrootzhushou.com\nrooyx.com\nross999.com\nrr-sc.com\nrr258.com\nrrfmn.com\nrrs.com\nrs66.com\nrsqhome.com\nrsqzs.com\nruan8.com\nruanmei.com\nrubberhr.com\nrubcn.com\nruczzy.com\nrugao35.com\nrugaojob.com\nrugaozs.com\nruian.com\nruian86.com\nruifox.com\nruigongye.com\nruimami.com\nruiwen.com\nruixinlong.com\nruizhiqi.com\nrunsky.com\nruochu.com\nruoshui.com\nrutisher.com\nruyi.com\nrw-cn.com\nrxhb110.com\nrxjy.com\nrz0375.com\nrz520.com\nrzauto.com\nrzdgtour.com\nrzfdc.com\nrzgdfc.com\nrzport.com\nrzrc.com\nrzrsrc.com\nrzta.com\nrzwenlan.com\nrzwww.com\nrzxwwang.com\nrzxx.com\nrzxyfc.com\nrzzg.com\ns-msn.com\ns1979.com\nsa26.com\nsaayaa.com\nsafe10000.com\nsafehoo.com\nsafetyw.com\nsaibeinews.com\nsaicgroup.com\nsaier360.com\nsaiermedia.com\nsaike.com\nsaloonrv.com\nsamboc.com\nsamsung.com\nsanan-e.com\nsanbeiguoshu.com\nsanfo.com\nsangame.com\nsanguosha.com\nsanhaostreet.com\nsanjinci.com\nsanjun.com\nsanlichem.com\nsanmaophoto.com\nsanqan.com\nsanqin.com\nsanqinche.com\nsanqindaily.com\nsanrenwo.com\nsanwenqu.com\nsanwenzx.com\nsanyahunshasheying.com\nsanyatour.com\nsanyecao.com\nsanyijishou.com\nsanyujixie.com\nsanzhijiao.com\nsaodijq.com\nsasa123.com\nsasacn.com\nsatog.com\nsbiao360.com\nsbo8.com\nsc115.com\nsc157.com\nsc2car.com\nsc2p.com\nsc518.com\nscanv.com\nscbid.com\nscbsm.com\nsccin.com\nsccnn.com\nscco-op.com\nsccts.com\nsceea.com\nscflcp.com\nscfzbs.com\nscgaosheng.com\nscgckj.com\nscgrain.com\nschongyuan.com\nschool51.com\nschtrust.com\nschylawyer.com\nsci99.com\nsciimg.com\nscjtg.com\nsclongfa.com\nscly168.com\nsclyzq.com\nscmingliu.com\nscmixin.com\nscnjnews.com\nscnjtv.com\nscnol.com\nscntv.com\nscqcp.com\nscqsng.com\nscrc168.com\nscrxw.com\nsctarena.com\nsctv.com\nsctvf.com\nsctvgo.com\nscw98.com\nscwcgz.com\nscweixiao.com\nscwxzk.com\nscyahua.com\nscypzs.com\nscyts.com\nsczfcg.com\nsczscd.com\nsczshz.com\nsczssz.com\nsczycj.com\nsczytv.com\nsczyw.com\nsd-china.com\nsd001.com\nsd11185.com\nsdalevel.com\nsdbdhy.com\nsdbdtc.com\nsdbear.com\nsdchina.com\nsdchn.com\nsdcoop.com\nsdcqjy.com\nsdcrj.com\nsddashi.com\nsddcp.com\nsddigua.com\nsddjw.com\nsddxyy.com\nsddzz.com\nsdenews.com\nsdfdc.com\nsdg-china.com\nsdgw.com\nsditol.com\nsdjjw.com\nsdjob.com\nsdjtcx.com\nsdjy001.com\nsdkcs.com\nsdkxyq.com\nsdlib.com\nsdlycts.com\nsdmtjy.com\nsdmuseum.com\nsdnxs.com\nsdo.com\nsdrc315.com\nsdrclm.com\nsdsgwy.com\nsdt360.com\nsdticai.com\nsdtuomei.com\nsdtxsc.com\nsdwenbo.com\nsdwenhua.com\nsdxhce.com\nsdzhan.com\nsdzqrc.com\nseadragonedu.com\nseaman-cn.com\nseccw.com\nsecn.com\nsecoo.com\nsecutimes.com\nsee-say.com\nseedit.com\nseekxiu.com\nsegahome.com\nsegmentfault.com\nsehand.com\nsemdn.com\nsendong.com\nsensor86.com\nsensorshome.com\nseowhy.com\nseptwolves.com\nseqtc.com\nserving-sys.com\nsexorz.com\nsf-auto.com\nsf-express.com\nsfacg.com\nsfbest.com\nsffdj.com\nsfmianhua.com\nsfzkw.com\nsfzmn.com\nsfzpw.com\nsg-rc.com\nsg120.com\nsgamer.com\nsgfcw.com\nsgjuzi.com\nsgrb.com\nsgrcw.com\nsgtz.com\nsguo.com\nsgyz.com\nsh-ielts.com\nsh-peixun.com\nsh-zhaopinhui.com\nsh112.com\nsh1188.com\nsh361.com\nsh51766.com\nsh528.com\nsh7.com\nsh91.com\nsha-steel.com\nshaanxigrain.com\nshaanxijky.com\nshafa.com\nshanchengrc.com\nshandalu.com\nshandongrc.com\nshandongsannong.com\nshandongtarena.com\nshang360.com\nshangcaifanyi.com\nshangdu.com\nshanghai-electric.com\nshanghaiairport.com\nshanghaiamts.com\nshanghaibaomu.com\nshanghaidz.com\nshanghaigm.com\nshanghaijiaodakaoyan.com\nshanghaining.com\nshanghairc.com\nshangjisou.com\nshangliutatler.com\nshangpin.com\nshangpusou.com\nshangqiurencaiwang.com\nshangshang.com\nshangxiang.com\nshangxueba.com\nshangyurencai.com\nshanhuwang.com\nshanke001.com\nshanshan360.com\nshantoumama.com\nshantui.com\nshanximuseum.com\nshanxiql.com\nshanxishizheng.com\nshanxw.com\nshaoer.com\nshaolinedu.com\nshaolinjidi.com\nshaolinsiyuan.com\nshaoyang51.com\nshaoyoo.com\nshaqing.com\nsharewithu.com\nshashapark.com\nshaxzs.com\nshbkqs.com\nshbtob.com\nshbyg.com\nshbyw.com\nshcaoan.com\nshcce.com\nshccig.com\nshcifco.com\nshcnws.com\nshcoop.com\nshctzh.com\nshcxaa.com\nshdazao.com\nshdbjy.com\nshdxhd.com\nshebao8.com\nshebaoyi.com\nshebeijianli.com\nshedunews.com\nsheencity.com\nsheepet.com\nsheidao.com\nsheji777.com\nshejiben.com\nshejiqun.com\nshejis.com\nshen1d.com\nshenbinghang.com\nshenchuang.com\nshendu.com\nshengdh123.com\nshengfang.com\nshengjoy.com\nshenglinyuan.com\nshengpay.com\nshengphoto.com\nshenguang.com\nshengyibao.com\nshengyidi.com\nshengzhujiage.com\nshenlumf.com\nshenmanhua.com\nshenmayouxi.com\nshennong.com\nshenyouyou.com\nshenzhenair.com\nshenzhenjiaoshi.com\nshexiannet.com\nsheying8.com\nsheyingtg.com\nshfff.com\nshfinancialnews.com\nshgao.com\nshgjj.com\nshhbm.com\nshhkws.com\nshhswed.com\nshhuo.com\nshichang.com\nshichangbu.com\nshichengxian.com\nshicimingju.com\nshiciw.com\nshidz.com\nshigong114.com\nshiguangjiaoluo.com\nshiguche88.com\nshihuahr.com\nshijiebang.com\nshijiemil.com\nshijieyouxi.com\nshijuew.com\nshikee.com\nshilehui.com\nshiliunet.com\nshimaogroup.com\nshionry.com\nshipinzhuchi.com\nshisu-edu.com\nshiwan.com\nshixi1980.com\nshixi8.com\nshiyanhospital.com\nshiyouhr.com\nshjdpx.com\nshjiugong.com\nshjmnc.com\nshjtaq.com\nshjyxxg.com\nshkingchem.com\nshmcws.com\nshmet.com\nshmetro.com\nshnn.com\nshoeshr.com\nshoucw.com\nshoudurc.com\nshoudurx.com\nshougongke.com\nshouji.com\nshouji56.com\nshouliwang.com\nshouy120.com\nshouyao8.com\nshouyihuo.com\nshouyou.com\nshouyou520.com\nshouyoubus.com\nshouyoucdn.com\nshouyoutv.com\nshowcang.com\nshowji.com\nshowjob.com\nshowmesse.com\nshpho.com\nshphome.com\nshphouse.com\nshpzzh.com\nshq-pump.com\nshqigan.com\nshrail.com\nshsjs.com\nshsof.com\nshsongjiang.com\nshsunedu.com\nshtimg.com\nshtl120.com\nshtuoba.com\nshuaijiao.com\nshuajizhijia.com\nshuame.com\nshuangliang.com\nshuanglongyuanyi.com\nshuangtao.com\nshuangtuan.com\nshuangzhengwang.com\nshucai001.com\nshucai123.com\nshucar.com\nshufa.com\nshufa001.com\nshufadajia.com\nshufawu.com\nshufe-cec.com\nshuhai.com\nshuhua.com\nshuhuapifa.com\nshuhuazy.com\nshuichan.com\nshuichan51.com\nshuifei168.com\nshuigongye.com\nshuiguo.com\nshuiliyc.com\nshuimotv.com\nshuitou001.com\nshulife.com\nshumiao.com\nshumx.com\nshundehr.com\nshunderen.com\nshunwang.com\nshuobao.com\nshuocar.com\nshuoshuokong.com\nshuren100.com\nshushi100.com\nshuxueba.com\nshuyangba.com\nshuzan.com\nshuzitielu.com\nshuzixiaoyuan.com\nshwsdp.com\nshxbe.com\nshxcoal.com\nshxdx.com\nshxingsen.com\nshyrcw.com\nshzaojiao.com\nshztdxyy.com\nsi114.com\nsiaholidays-beijing.com\nsiandian.com\nsichina.com\nsiciciyu.com\nsickcn.com\nsidajiaoyu.com\nsidri.com\nsifa365.com\nsigiscarf.com\nsihaidiaoyu.com\nsihaishuyuan.com\nsihe.com\nsihemy.com\nsihey.com\nsihongbbs.com\nsiilu.com\nsijieqinmiao.com\nsijinjiaju.com\nsijiquan.com\nsijitiemo.com\nsikenet.com\nsiliaojixie.com\nsiliaoycw.com\nsilingge.com\nsilucg.com\nsimingshan.com\nsimochem.com\nsimuwang.com\nsina.com\nsinaapp.com\nsinashow.com\nsingbon.com\nsingse.com\nsinioa.com\nsinmert.com\nsino-manager.com\nsinocars.com\nsinoef.com\nsinoergy.com\nsinohydro.com\nsinolub.com\nsinomep.com\nsinopec.com\nsinopecgroup.com\nsinopipenet.com\nsinosig.com\nsinosteel.com\nsinoteanet.com\nsinotechline.com\nsinotf.com\nsinotrans-csc.com\nsinovel.com\nsinzhu.com\nsiphrd.com\nsirenji.com\nsiriopharm.com\nsissiok.com\nsitongbxg.com\nsiweiw.com\nsixiangchina.com\nsixiju.com\nsiyjob.com\nsiyrcw.com\nsiyuquanyun.com\nsizuo.com\nsj5d.com\nsj998.com\nsjapk.com\nsjdfgl.com\nsjfsy.com\nsjfzxm.com\nsjgou.com\nsjjob88.com\nsjkoo.com\nsjvip.com\nsjway.com\nsjwg.com\nsjwj.com\nsjwyx.com\nsjxww.com\nsjxyx.com\nsjyyt.com\nsjzcity.com\nsjzjiajiaow.com\nsjzlongre.com\nsjzmama.com\nsjznews.com\nsjzonline.com\nsjzsheji.com\nsjztjob.com\nsjzyxh.com\nsjzzsw.com\nskg.com\nskgskg.com\nskinpp.com\nskjcsc.com\nskxox.com\nsky-fire.com\nskycn.com\nskyworth.com\nslanissue.com\nslemb.com\nsljjw.com\nsljob88.com\nsllssrq.com\nslrbs.com\nslstm.com\nslsttc.com\nslszs.com\nslzb.com\nslzyjsxy.com\nsm597.com\nsm598.com\nsmarthomecn.com\nsmarthu.com\nsmartjx.com\nsmcjw.com\nsmecq.com\nsmecqpt.com\nsmefj.com\nsmegx.com\nsmegz.com\nsmejs.com\nsmelx.com\nsmeok.com\nsmestar.com\nsmforestry.com\nsmggw.com\nsmgjj.com\nsmhzs.com\nsmszq.com\nsmudc.com\nsmvtc.com\nsmwrc.com\nsmxgjj.com\nsmxyz.com\nsmxzs.com\nsmyuan.com\nsmzdm.com\nsmzwzx.com\nsmzy.com\nsn110.com\nsnail.com\nsnda.com\nsndhr.com\nsneac.com\nsnedu.com\nsnjob.com\nsnow021.com\nsnrtv.com\nsnsece.com\nsnsnb.com\nsnsqw.com\nsnsyx.com\nsnwugong.com\nsnxiaowai.com\nsnxw.com\nsnyu.com\nsnzhao.com\nso.com\nsoautos.com\nsocang.com\nsoche8.com\nsocialtok.com\nsociw.com\nsocksb2b.com\nsodao.com\nsoe-soe.com\nsoershou.com\nsoft568.com\nsoft6.com\nsoft711.com\nsoftbar.com\nsoftparkinfo.com\nsofu580.com\nsogou.com\nsogoucdn.com\nsogoupc.com\nsogua.com\nsohochina.com\nsohu.com\nsohucs.com\nsohusce.com\nsohutuan.com\nsojump.com\nsokongyaji.com\nsoku.com\nsola123.com\nsolar001.com\nsolar588.com\nsolarbe.com\nsolarchn.com\nsolargard.com\nsolarsupporting.com\nsolarzoom.com\nsomaiwang.com\nsomenmian.com\nsongbaixiang.com\nsongyuanrc.com\nsongzhuang365.com\nsongzi100.com\nsonhoo.com\nsoo56.com\nsoocang.com\nsooker.com\nsooshong.com\nsootoo.com\nsooxue.com\nsooyuu.com\nsoozhu.com\nsoperson.com\nsortdoor.com\nsoshoo.com\nsoso.com\nsososteel.com\nsosoti.com\nsosucai.com\nsotcbb.com\nsouacg.com\nsoubaoad.com\nsoucai.com\nsoucaigroup.com\nsouche.com\nsouchebang.com\nsoucheke.com\nsoucke.com\nsoucm.com\nsoudai360.com\nsoufang58.com\nsouff.com\nsoufun.com\nsoufunimg.com\nsouloo.com\nsoulou365.com\nsoulou8.com\nsoulvone.com\nsoupei360.com\nsoupingguo.com\nsoupu.com\nsouqian.com\nsouthcn.com\nsouthmoney.com\nsouxuexiao.com\nsoweather.com\nsoxsok.com\nsoyouxi.com\nsoyuli.com\nsozhen.com\nsp910.com\nspacechina.com\nspasvo.com\nspcce.com\nspcywang.com\nspdl.com\nspeiyou.com\nspgykj.com\nspiiker.com\nspinlt.com\nspjobhr.com\nspjxcn.com\nspo1973.com\nspointdesign.com\nsportscn.com\nsporttery.com\nspringre.com\nspringtour.com\nsprtc.com\nspsb114.com\nspzlwz.com\nspzs.com\nspzyw.com\nsq1996.com\nsq597.com\nsqanju.com\nsqbdt.com\nsqcjw.com\nsqfc.com\nsqfcw.com\nsqkk.com\nsqrcw.com\nsqs373.com\nsqsjr.com\nsqyc.com\nsqzhaopin.com\nsqzhonghuan.com\nsrcdd.com\nsrhcw.com\nsrrczpw.com\nsrtong.com\nsrxww.com\nss256.com\nss597.com\nssbgzzs.com\nsscbw.com\nsseinfo.com\nssfcw.com\nssfun.com\nssjzw.com\nssl-images-amazon.com\nsslibrary.com\nssnrw.com\nssofair.com\nssqzj.com\nssrcsc.com\nssswh.com\nsstjtest.com\nsswoo.com\nssydt.com\nst5.com\nstar365.com\nstar65.com\nstarbaby.com\nstarlott.com\nstartos.com\nstatickksmg.com\nstcn.com\nstdaily.com\nsteelkx.com\nsteelphone.com\nsteelwin.com\nsteelyou.com\nstjohnsau.com\nstjunshi.com\nstjzxx.com\nstnts.com\nstny369.com\nstockstar.com\nstockyc.com\nstone365.com\nstonesm.com\nstonexp.com\nstqq.com\nstrawberrynet.com\nstrong-imm.com\nstrong-study.com\nsttcw.com\nstudentboss.com\nstudydao.com\nstudyems.com\nstudyez.com\nstudyget.com\nstuhack.com\nstutrip.com\nstylemode.com\nsu-long.com\nsuaee.com\nsuanpi.com\nsubaonet.com\nsucaifengbao.com\nsucaitianxia.com\nsucaiw.com\nsudasuta.com\nsudupan.com\nsuduxx.com\nsufeinet.com\nsuifw.com\nsuiningwang.com\nsuiyiju.com\nsuiyueart.com\nsuizhoushi.com\nsuizhoutg.com\nsukeju.com\nsuloon.com\nsumavision.com\nsumcl.com\nsumec.com\nsumiaohua.com\nsumiaowang.com\nsummall.com\nsun-cy.com\nsun0575.com\nsun0769.com\nsunbo.com\nsunchn.com\nsungrowpower.com\nsunhouse2002.com\nsuning.com\nsunnychina.com\nsunplusedu.com\nsunrain.com\nsunsirs.com\nsunstu.com\nsunvim.com\nsunyuanxx.com\nsuorang.com\nsupdri.com\nsupercrm.com\nsupu8.com\nsupuw.com\nsupuy.com\nsuqiantuan.com\nsushuo8.com\nsusongbbs.com\nsuv-trip.com\nsuvcm.com\nsuwurc.com\nsuxiazai.com\nsuxuewang.com\nsuyifbt.com\nsuzhounewswang.com\nsvw-volkswagen.com\nswarow.com\nswccw.com\nswimbb.com\nswjoy.com\nswkong.com\nswotbbs.com\nswuee.com\nswwenshi.com\nswxchina.com\nsx597.com\nsxac.com\nsxbjedu.com\nsxc2255.com\nsxcntv.com\nsxcoal.com\nsxcse.com\nsxdygbjy.com\nsxdzs.com\nsxejgfyxgs.com\nsxfic.com\nsxfsw.com\nsxgdtv.com\nsxjdmh.com\nsxjzwb.com\nsxkp.com\nsxlib.com\nsxlychina.com\nsxmtxs.com\nsxmzc.com\nsxncb.com\nsxol.com\nsxpmg.com\nsxpre.com\nsxpta.com\nsxpxks.com\nsxqc.com\nsxqiche.com\nsxrb.com\nsxrcw.com\nsxrtv.com\nsxsanwei.com\nsxshangjie.com\nsxshu.com\nsxsznews.com\nsxtdrn.com\nsxtour.com\nsxtvs.com\nsxtwedu.com\nsxw100.com\nsxwhty.com\nsxworker.com\nsxxsp.com\nsxxynews.com\nsxxzxy.com\nsxycpc.com\nsxycrb.com\nsxyhq.com\nsxzcjyw.com\nsxzjcoop.com\nsy128.com\nsy456.com\nsydang.com\nsydaxxw.com\nsyedugroup.com\nsyfff.com\nsygjj.com\nsygz1945.com\nsyhfw.com\nsyhhidc.com\nsyhmw.com\nsying.com\nsyiptv.com\nsyjiancai.com\nsyjzjc.com\nsykong.com\nsymama.com\nsymtc.com\nsynacast.com\nsynochip.com\nsypf.com\nsypglass.com\nsyqnr.com\nsyrczpw.com\nsysczn.com\nsysese.com\nsysuyz.com\nsyswin.com\nsytxxzsp.com\nsytzw.com\nsywsnet.com\nsyxwnet.com\nsyyx.com\nsyzol.com\nsyzxyz.com\nsz-3a.com\nsz-english.com\nsz-qb.com\nsz-yugong.com\nsz1w.com\nsz61.com\nsz68.com\nsz7h.com\nsz910.com\nszaee.com\nszaeia.com\nszai.com\nszass.com\nszcec.com\nszceo.com\nszcfxx.com\nszdlkt.com\nszects.com\nszeds.com\nszedu.com\nszehs.com\nszewhm.com\nszfa.com\nszfcol.com\nszfutong.com\nszgamfe.com\nszgla.com\nszguanai.com\nszgujian.com\nszhk.com\nszhome.com\nszhomeimg.com\nszhongmu.com\nszhr.com\nszhrzp.com\nszhufu.com\nszjianguo.com\nszjiaz.com\nszjjedu.com\nszjjzlh.com\nszkz.com\nszlab17.com\nszlyw12306.com\nszlyzx.com\nszmama.com\nszmj.com\nszmonalisa.com\nsznews.com\nsznmd.com\nszooo.com\nszphoto.com\nszpku-edu.com\nszpxe.com\nszqcw.com\nszrc88.com\nszredstone.com\nszsfwzx.com\nszsh.com\nsztaofang.com\nsztian.com\nszutek.com\nszvenushs.com\nszwudao.com\nszwwxn.com\nszxdcc.com\nszxnews.com\nszyc.com\nszyyx.com\nszzfgjj.com\nt0001.com\nt0376.com\nt0888.com\nt139.com\nt262.com\nt3nclick.com\nt3nlink.com\nt978.com\ntadercn.com\ntadiao168.com\ntadu.com\ntahota-lawyer.com\ntai87.com\ntaian.com\ntaicanghr.com\ntaihainet.com\ntaikang.com\ntaiweifeng.com\ntaizhou.com\ntakungpao.com\ntalentsmag.com\ntalicai.com\ntalkforex.com\ntalkyun.com\ntan8.com\ntangdou.com\ntangdouban.com\ntangjiu.com\ntangjiu001.com\ntangongye.com\ntanjiaoyi.com\ntanpaifang.com\ntansuonet.com\ntantuw.com\ntanx.com\ntao123.com\ntao15.com\ntao775.com\ntaoban.com\ntaobao.com\ntaobaocdn.com\ntaoche.com\ntaoche100.com\ntaoche8.com\ntaoci.com\ntaoci365.com\ntaocici.com\ntaocijiaju.com\ntaocijob.com\ntaocz.com\ntaodake.com\ntaodanyang.com\ntaoducity.com\ntaofang.com\ntaofen8.com\ntaogula.com\ntaohuren.com\ntaojindi.com\ntaojinyi.com\ntaoke.com\ntaolv365.com\ntaomee.com\ntaonb.com\ntaoneimeng.com\ntaoniu.com\ntaood.com\ntaopic.com\ntaoren100.com\ntaose98.com\ntaoshouyou.com\ntaoshu.com\ntaotaocar.com\ntaoxie.com\ntaoyunet.com\ntarenacn.com\ntarenasz.com\ntarkett1872.com\ntartsmy.com\ntaskcn.com\ntattoo77.com\ntayasaf.com\ntb-apps.com\ntb520.com\ntbnimg.com\ntbs-china.com\ntbscache.com\ntbtsps.com\ntbxt.com\ntc550.com\ntcaccp.com\ntcdushi.com\ntcl.com\ntcl-lighting.com\ntcm361.com\ntcrcsc.com\ntcrczpw.com\ntctzby.com\ntd776.com\ntdbnw.com\ntdfcw.com\ntdimg.com\ntdsyj.com\ntdzyw.com\nte6.com\ntea-shexpo.com\ntea160.com\ntea846.com\ntea8848.com\nteachercn.com\nteacherzp.com\nteapic.com\nteauo.com\ntech-ex.com\ntech-food.com\ntech2ipo.com\ntechan.com\ntechannet.com\ntechanzs.com\ntechxue.com\ntedianwang.com\ntejia01.com\ntelecomhr.com\ntelojob.com\ntemaiku.com\ntencent.com\ntencentmind.com\ntengfun.com\ntengzhourcw.com\ntenpay.com\ntesehunan.com\ntest-edu.com\ntest3g.com\ntestrust.com\ntex68.com\ntex688.com\ntexu1.com\nteyoutuan.com\ntezgc.com\ntffcw.com\ntfx888.com\ntfysw.com\ntg0123.com\ntgbus.com\ntghezuoshe.com\nthcha.com\nthe9.com\nthebeijingnews.com\nthechinawatch.com\nthethirdmedia.com\nthetianfu.com\nthjunshi.com\nthmall.com\nthmz.com\nthshengda.com\nthsware.com\nthxdbj.com\nthyoo.com\ntiancity.com\ntiancitycdn.com\ntiandaoedu.com\ntianditu.com\ntianinfo.com\ntianji.com\ntianjihr.com\ntianjimedia.com\ntianjinrc.com\ntianjinwe.com\ntiannv.com\ntianpingxian.com\ntianqi.com\ntianshangrenjian123.com\ntianshannet.com\ntianshanrc.com\ntiantian.com\ntiantianhr.com\ntiantianjob.com\ntiantianxuexi.com\ntiantianyj.com\ntianyaclub.com\ntianyangjx869.com\ntianyaui.com\ntiaomou.com\ntibet-g.com\ntibet3.com\ntibetcn.com\ntibetinfor.com\ntibetpic.com\ntiebaimg.com\ntiebaobei.com\ntiebaojiao.com\ntiedelao.com\ntiekuangshi.com\ntielingcn.com\ntietuku.com\ntieyou.com\ntigtag.com\ntihengjian.com\ntihuedu.com\ntimberland-china.com\ntime-weekly.com\ntimedg.com\ntimeep.com\ntimeoutcn.com\nting30.com\nting56.com\nting89.com\ntingbook.com\ntingchina.com\ntingfree.com\ntingge123.com\ntingroom.com\ntingshuge.com\ntingvoa.com\ntisahome.com\ntitan24.com\ntiyubisai.com\ntjaee.com\ntjbb.com\ntjchildrenshospital.com\ntjcoop.com\ntjfic.com\ntjflcpw.com\ntjinfo.com\ntjj.com\ntjkpzx.com\ntjkx.com\ntjkximg.com\ntjmama.com\ntjmylike.com\ntjshangceng.com\ntjsjx.com\ntjzjbbs.com\ntjzxfc.com\ntl100.com\ntl111.com\ntlb2b.com\ntlbaobao.com\ntlfrc.com\ntljob8001.com\ntlpsr.com\ntlpump.com\ntlrc.com\ntltesoft.com\ntm51.com\ntm9999.com\ntmall.com\ntmbbs.com\ntmfang.com\ntmhtour.com\ntmjob88.com\ntmjyw.com\ntmrcw.com\ntmsf.com\ntmtforum.com\ntmtpost.com\ntmwcn.com\ntnbxw.com\nto360.com\nto61.com\nto8to.com\ntobaccochina.com\ntoberp.com\ntobosu.com\ntodayartmuseum.com\ntodayidc.com\ntodaynic.com\ntodayonhistory.com\ntoefljuniorchina.com\ntogoo.com\ntoidea.com\ntokung.com\ntom.com\ntom61.com\ntomatolei.com\ntomdurrie.com\ntompda.com\ntomx.com\ntong12.com\ntongbu.com\ntonghaigroup.com\ntonghuanet.com\ntongjishi.com\ntongkong.com\ntonglian1998.com\ntongliaowang.com\ntonglingjob.com\ntonglukuaijian.com\ntongluren.com\ntongpiao.com\ntongqu.com\ntongqz.com\ntongxue8.com\ntongyouku.com\ntonymary.com\ntooben.com\ntoobiao.com\ntoobm.com\ntoocle.com\ntoocrystal.com\ntoofloor.com\ntoojj.com\ntooopen.com\ntootour.com\ntop100summit.com\ntopbm.com\ntopbrandunion.com\ntopdtv.com\ntopfo.com\ntopfreebiz.com\ntopielts.com\ntopjt.com\ntopnews9.com\ntopqikan.com\ntopsage.com\ntopsj.com\ntopthink.com\ntopu.com\ntopzj.com\ntorozi.com\ntotob.com\ntouchchinaexpo.com\ntouchf.com\ntouclick.com\ntouding.com\ntour17.com\ntourcool.com\ntourdz.com\ntours010.com\ntoursforfun.com\ntourzj.com\ntoutiao.com\ntoutouwan.com\ntouzhijia.com\ntouzhuzhan.com\ntouzishi.com\ntoxihu.com\ntoybaba.com\ntoyclubcn.com\ntoys365.com\ntoysbao.com\ntoysgu.com\ntpooo.com\ntprtc.com\ntpu-ptfe.com\ntpzj.com\ntqedu.com\ntqh168.com\ntqkaoyan.com\ntqlsgroup.com\ntqmba.com\ntrade2cn.com\ntradesns.com\ntranbbs.com\ntravelhuzhou.com\ntravellingscope.com\ntravelsky.com\ntrdcafes.com\ntreerly.com\ntrfcw.com\ntrhos.com\ntrip8080.com\ntripbaba.com\ntripdv.com\ntripear.com\ntrjcn.com\ntrustexporter.com\ntrylist.com\ntscanyin.com\ntscndd.com\ntshcf.com\ntsichuan.com\ntsinghua-sz.com\ntsinghuapxb.com\ntsjiuyeba.com\ntskjzs.com\ntsrcw.com\ntt-ly.com\ntt0760.com\ntt803.com\ntt919.com\ntt98.com\nttb2b.com\nttche.com\ntteb.com\nttgood.com\ntthcw.com\ntthhw.com\ntthonghuo.com\nttkdex.com\nttmeishi.com\nttmn.com\nttpet.com\nttpod.com\nttqmw.com\nttrencai.com\nttslsd.com\ntttz.com\nttufo.com\nttyl5.com\nttys5.com\nttzcw.com\nttzhaogong.com\ntu50.com\ntuan800.com\ntuanche.com\ntuanhuopu.com\ntuanimg.com\ntuanjiebao.com\ntuanjw.com\ntuanping.com\ntuanweihui.com\ntuboshu.com\ntuchw.com\ntucoo.com\ntudidaili.com\ntudigujia.com\ntudou.com\ntudouui.com\ntuhaonet.com\ntui18.com\ntui18edu.com\ntuicool.com\ntuidc.com\ntuifeiapi.com\ntuike888.com\ntuilie.com\ntuitui99.com\ntuituifang.com\ntujia.com\ntukeq.com\ntuku.com\ntulaoshi.com\ntuliao86.com\ntuliaotuyao.com\ntuliu.com\ntulvzu.com\ntumanduo.com\ntumukeji.com\ntuniu.com\ntuniucdn.com\ntuozhe8.com\ntupian114.com\ntupianzj.com\ntuquu.com\nturbocms.com\nturenscape.com\ntusiliao.com\ntuwan.com\ntuxiaobei.com\ntuyexinxi.com\ntuzi8.com\ntv0714.com\ntv189.com\ntv373.com\ntvhf.com\ntvhome.com\ntvhuan.com\ntvlicai.com\ntvmining.com\ntvptv.com\ntvscn.com\ntvsou.com\ntwl123.com\ntx365.com\ntx96345.com\ntxdai.com\ntxdzw.com\ntxooo.com\ntxrz.com\ntxsec.com\ntxssw.com\ntxtbbs.com\ntxuuu.com\ntxw.com\ntxwm.com\ntxxxb.com\ntxyes.com\ntxysyy.com\nty360.com\ntybaba.com\ntybus.com\ntycqjy.com\ntygjj.com\ntyjzk.com\ntyn100.com\ntyncar.com\ntyread.com\ntytarena.com\ntyueo.com\ntyuyan.com\ntyxrc.com\ntz-job.com\ntz0852.com\ntz121.com\ntz2100.com\ntz911.com\ntz94.com\ntzcz.com\ntzeju.com\ntzesf.com\ntzfdc.com\ntzhaoma.com\ntzhr.com\ntzhuan.com\ntzhzh.com\ntzjob.com\ntzkd.com\ntzlink.com\ntzmaimai.com\ntzmarry.com\ntzrc.com\ntzrcg.com\ntzrl.com\ntzshenxin.com\ntzsnw.com\ntzswdx.com\ntztjfc.com\ntztlt.com\ntzxctz.com\ntzxcw.com\ntzyouth.com\ntzzgz.com\ntzzp.com\ntzzufang.com\nu0.com\nu009.com\nu0351.com\nu0762.com\nu17.com\nu1733.com\nu17i.com\nu1d1.com\nu3399.com\nu4123.com\nu5450.com\nu69cn.com\nu77u.com\nu78.com\nu7u7.com\nu88.com\nu88job.com\nu8k8.com\nu966.com\nu9766.com\nu9time.com\nu9yoyo.com\nubicdn.com\nuc129.com\nucai123.com\nucbug.com\nucdao.com\nucjoy.com\nuctrac.com\nudashi.com\nuehtml.com\nufang.com\nufangw.com\nufenghuang.com\nufojia.com\nufojoy.com\nufstone.com\nuftong.com\nuggd.com\nugojp.com\nuhaidao.com\nuhenan.com\nuibao.com\nuimaker.com\nuinicall.com\nuisdc.com\nuisheji.com\nujintan.com\nujob138.com\nujob360.com\nukejisong.com\nukhorsman.com\nulbiz.com\nule.com\nulenp.com\nulzsw.com\numetal.com\numinsky.com\numiwi.com\numkid.com\nun188.com\nuncars.com\nuninf.com\nuninforun.com\nunion178.com\nunionli.com\nunionpay.com\nunisachina.com\nunitymanual.com\nunjs.com\nunn114.com\nunpcn.com\nuns114.com\nunsuv.com\nuntvchina.com\nuntx.com\nuoko.com\nuooyoo.com\nup71.com\nupaidui.com\nupaiyun.com\nupanboot.com\nupantool.com\nupdrv.com\nupfdc.com\nupshenghuo.com\nupuphr.com\nupyun.com\nuqidong.com\nuseso.com\nusfang.com\nushunde.com\nusportnews.com\nusteel.com\nusvisapass.com\nutan.com\nutanbaby.com\nutourworld.com\nutsteel.com\nuu1.com\nuu1758.com\nuu178.com\nuu2car.com\nuu38.com\nuu50.com\nuu7c.com\nuu898.com\nuucall.com\nuunt.com\nuuqj.com\nuusee.com\nuuu9.com\nuuufun.com\nuuxoo.com\nuuyoyo.com\nuuzhufu.com\nuuzu.com\nuvdeng.com\nuwan.com\nux87.com\nux98.com\nuxin.com\nuzai.com\nuzaicdn.com\nuzaituan.com\nuzise.com\nuzzf.com\nv-tio2.com\nv056.com\nv17go.com\nv1pin.com\nvaecn.com\nvalue500.com\nvancl.com\nvanclimg.com\nvanke.com\nvanward.com\nvapee.com\nvartcn.com\nvautou.com\nvcimg.com\nvcinchina.com\nvdfly.com\nvdolady.com\nvedeng.com\nveeqi.com\nveerchina.com\nvenfang.com\nverycd.com\nverydz.com\nveryhome.com\nveryhuo.com\nveryol.com\nveryzhun.com\nvfl123.com\nvhostgo.com\nvicovico.com\nvidarsoft.com\nviewones.com\nvikecn.com\nvillazx.com\nvinehoo.com\nvinux.com\nvip.com\nvip120.com\nvip121.com\nvip7758.com\nvip800.com\nvipcareer.com\nvipcn.com\nvipmtb.com\nvipshare.com\nvipshop.com\nvipsinaapp.com\nvipstatic.com\nviptijian.com\nvipyl.com\nvisa800.com\nvisabuilders.com\nvisionunion.com\nvisitgd.com\nvisitxm.com\nvista123.com\nvistastory.com\nvivijk.com\nvj100.com\nvjia.com\nvmall.com\nvmeti.com\nvnasi.com\nvoa365.com\nvobao.com\nvodehr.com\nvodjk.com\nvodone.com\nvoguechinese.com\nvolstock.com\nvonibo.com\nvotwo.com\nvpimg1.com\nvpimg2.com\nvpimg3.com\nvpimg4.com\nvrdam.com\nvrvkt.com\nvsharing.com\nvst88.com\nvsuch.com\nvvjob.com\nvvvdj.com\nvvwan.com\nw0517.com\nw1wan.com\nw5211.com\nw707.com\nw856.com\nwa3.com\nwa8688.com\nwaaku.com\nwabuw.com\nwacai.com\nwadongxi.com\nwaerfa.com\nwaheaven.com\nwaihuifanyongwang.com\nwaihuo.com\nwaimao6.com\nwaipoxin.com\nwaiwaitu.com\nwaixiaoyuan.com\nwajueji.com\nwallcoo.com\nwallstreetcn.com\nwalvyou.com\nwan.com\nwan25.com\nwan51.com\nwanbiansz.com\nwanchaow.com\nwanche100.com\nwanche168.com\nwandafilm.com\nwandaihao.com\nwandodo.com\nwandoujia.com\nwanfangdata.com\nwang1314.com\nwangdaitiandi.com\nwangdaizhidao.com\nwangdaizhijia.com\nwanggou.com\nwanggouchao.com\nwangjiaoba.com\nwangjiu.com\nwangtu.com\nwanguan.com\nwangxianhui.com\nwangxiaotong.com\nwangxiaowang.com\nwangxing.com\nwangxingroup.com\nwangyeba.com\nwangyi120.com\nwangyin.com\nwanhu888.com\nwanhuole.com\nwanhupo.com\nwanjidao.com\nwanjingchina.com\nwanjuhe.com\nwanlibo.com\nwanlitong.com\nwanlongjituan.com\nwanmagu.com\nwanmei.com\nwanshuba.com\nwantfeel.com\nwantuhao.com\nwanweixin.com\nwanwen99.com\nwanxf.com\nwanxuantong.com\nwanyeji.com\nwanyiwang.com\nwanyou365.com\nwanyouxi7.com\nwanyx.com\nwanzhouche.com\nwanzhoujob.com\nwanzui.com\nwaouji.com\nwaptw.com\nwarchina.com\nwarcraftchina.com\nwarting.com\nwasu.com\nwasu-umedia.com\nwatchstor.com\nwaterhr.com\nwatertu.com\nwawangluo.com\nwbtrans.com\nwbtt315.com\nwcjbb.com\nwcnimg.com\nwcsrcw.com\nwcwone.com\nwdjimg.com\nwdjslm.com\nwdlpump.com\nwdptj.com\nwdres.com\nwds369.com\nwdsdq.com\nwdsjz.com\nwdstq.com\nwe54.com\nwealink.com\nwealinkcdn.com\nweand.com\nweathercn.com\nweathertj.com\nweb198.com\nweb3389.com\nweb4008.com\nwebche.com\nwebciss.com\nwebdiyer.com\nwebgame163.com\nwebgameurl.com\nwebjx.com\nwebkaka.com\nwebkindu.com\nwebpowerchina.com\nwebscache.com\nwebterren.com\nwecenter.com\nwechatnet.com\nwed0512.com\nwed2008.com\nwed9.com\nwedohome.com\nweentech.com\nwehefei.com\nwei2008.com\nweibo.com\nweibopay.com\nweicaifu.com\nweichai.com\nweichaishi.com\nweifengke.com\nweifren.com\nweigz.com\nweihaifc.com\nweiheshidai.com\nweijiuxin.com\nweikeimg.com\nweilanhaian.com\nweilanliuxue.com\nweimeicun.com\nweimeixi.com\nweimob.com\nweiningnews.com\nweiphone.com\nweisheng.com\nweishengzige.com\nweishi.com\nweitiyan.com\nweiwenyi.com\nweixianwang.com\nweiyunke.com\nweizhangwang.com\nwelan.com\nweldec.com\nwelife100.com\nwell8.com\nwellhope-ag.com\nwelltrend-edu.com\nwellyn.com\nwemvp.com\nwenchangfc.com\nwenda60.com\nwendu.com\nwenduedu.com\nwendumba.com\nwenjuan.com\nwenlingrc.com\nwenmingzs.com\nwenrenpu.com\nwenshen520.com\nwenshen8.com\nwenshenxiu.com\nwenshitiandi.com\nwenwanhome.com\nwenwo.com\nwenwuchina.com\nwenxue24.com\nwenyifengxiang.com\nwenyoutai.com\nwenzhousx.com\nwenzifanyi.com\nweshequ.com\nwesmp.com\nwest-rtv.com\nwest263.com\nwestholiday.com\nwestking.com\nweyou360.com\nwf121.com\nwf777.com\nwfbbs.com\nwfcgs.com\nwfdpjm.com\nwff168.com\nwfftz.com\nwfits.com\nwfjyxxg.com\nwflgj.com\nwflzw.com\nwfrcsc.com\nwfrsks.com\nwgimg.com\nwh-motorshow.com\nwh3351.com\nwhankj.com\nwhbear.com\nwhblct.com\nwhbws.com\nwhctv.com\nwhedu21.com\nwhgogo.com\nwhhouse.com\nwhjlw.com\nwhjm.com\nwhjmyz.com\nwhjuren.com\nwhlongre.com\nwhmama.com\nwhmetroad.com\nwhnewnet.com\nwhpcschool.com\nwhqmcg.com\nwhrhkj.com\nwhsgj.com\nwhshangceng.com\nwhtarena.com\nwhunf.com\nwhwater.com\nwhwed.com\nwhzph.com\nwifigx.com\nwiki8.com\nwildrhino8.com\nwin007.com\nwin4000.com\nwin7china.com\nwin8china.com\nwin8e.com\nwincn.com\nwindchn.com\nwinddesktop.com\nwindin.com\nwindosi.com\nwindows7en.com\nwine-world.com\nwine9.com\nwinechina.com\nwinekee.com\nwinenice.com\nwines-info.com\nwinfang.com\nwinfreeinfo.com\nwingwit.com\nwinshang.com\nwintang.com\nwinvod.com\nwinwindai.com\nwinxw.com\nwishdown.com\nwj-hospital.com\nwj001.com\nwj0556.com\nwjclpx.com\nwjdaily.com\nwjfcw.com\nwjnin.com\nwjqcw.com\nwjshw.com\nwjsw.com\nwjyanghu.com\nwkdty.com\nwkimg.com\nwlc1618.com\nwldsb.com\nwlfce.com\nwlgy.com\nwlhagz.com\nwljysw.com\nwlkst.com\nwlmq.com\nwlmqgjj.com\nwlmqwb.com\nwlshw.com\nwlstock.com\nwlxyw.com\nwlyht.com\nwm090.com\nwm927.com\nwmb2b.com\nwmordos.com\nwmzhe.com\nwn51.com\nwndhr.com\nwndhw.com\nwnfdc.com\nwnrcw.com\nwnrczpw.com\nwnwb.com\nwo116114.com\nwoaipu.com\nwodai.com\nwodeyouhuigou.com\nwodingche.com\nwofang.com\nwofangwang.com\nwoiyu.com\nwojubl.com\nwokan.com\nwokanfang.com\nwokeji.com\nwolai.com\nwolaigo.com\nwomai.com\nwoman91.com\nwomenofchina.com\nwoniu.com\nwood168.com\nwoodworking365.com\nwool3.com\nwordlm.com\nworkpcb.com\nworkyi.com\nworld-metal.com\nworldal.com\nworldhots.com\nworldscrap.com\nworldwayhk.com\nwoshipm.com\nwosign.com\nwowoyou.com\nwowsai.com\nwoxiu.com\nwoyaogexing.com\nwoyaojiaju.com\nwoyewan.com\nwoying.com\nwoyo365.com\nwoyouguanjia.com\nwozhongla.com\nwp28.com\nwper.com\nwpwan.com\nwrating.com\nwsbgt.com\nwsche.com\nwsd114.com\nwsfjh.com\nwsgjj.com\nwshang.com\nwshangyun.com\nwshzg.com\nwsqsgo.com\nwsrc999.com\nwstdw.com\nwstea.com\nwszg8.com\nwszw.com\nwtobag.com\nwtsteel.com\nwtwan.com\nwudage.com\nwudang04.com\nwudang3.com\nwudang360.com\nwudangmuseum.com\nwudao.com\nwudaotv.com\nwudig.com\nwudihan.com\nwuguanling.com\nwuhan4.com\nwuhanbus.com\nwuhaninvest.com\nwuhulife.com\nwujianghr.com\nwujintool.com\nwujitl.com\nwujue.com\nwuliantour.com\nwuliaosi.com\nwulingxw.com\nwuliok.com\nwumii.com\nwuqunshuye.com\nwushen.com\nwuweijob.com\nwuxijob.com\nwuxinghuayuan.com\nwuxiph.com\nwuxjob.com\nwuyiguide.com\nwuyishan.com\nwuyitravel.com\nwuyuan168.com\nwuyueit.com\nwuzhe.com\nwwbxw.com\nwwenglish.com\nwx920.com\nwxbnbxg.com\nwxbtlbxg.com\nwxctkq.com\nwxctzx.com\nwxehs.com\nwxfuyou.com\nwxhouse.com\nwxhtlxj.com\nwxjbbxg.com\nwxjcgy.com\nwxjob.com\nwxlongre.com\nwxlottery.com\nwxmama.com\nwxmlbb.com\nwxqcw.com\nwxrb.com\nwxsbbs.com\nwxsjxn.com\nwxthw.com\nwxuse.com\nwxw120.com\nwxwmw.com\nwxxqlib.com\nwybbao.com\nwydxjzw.com\nwyhnn.com\nwyjiuyuanheiji.com\nwysap.com\nwysjob.com\nwyuyao.com\nwyzc.com\nwz121.com\nwz12333.com\nwz50.com\nwzcbd.com\nwzcheshi.com\nwzclxx.com\nwzdjy.com\nwzdlyw.com\nwzea.com\nwzfg.com\nwzfnykj.com\nwzgjj.com\nwzhd.com\nwzi9.com\nwzjob.com\nwzk.com\nwzrc.com\nwzrclt.com\nwzsee.com\nwzszp.com\nwztyj.com\nwzwh.com\nwzyds.com\nwzzbtb.com\nx-sing.com\nx0750.com\nx1616.com\nx3cn.com\nx888v.com\nxa999.com\nxabbs.com\nxacars.com\nxadmgjc.com\nxafc.com\nxahhw.com\nxajjzh.com\nxajob.com\nxajobw.com\nxanet110.com\nxaonline.com\nxapcn.com\nxaprice.com\nxarc8.com\nxarchi.com\nxaronline.com\nxatianzhou.com\nxatrm.com\nxatvs.com\nxawan.com\nxawb.com\nxaxzl.com\nxazmkm.com\nxazxw.com\nxb234.com\nxbaixing.com\nxbauto.com\nxbdb2b.com\nxbfzb.com\nxbgk.com\nxbiao.com\nxbjob.com\nxblaw.com\nxblyy.com\nxbmiaomu.com\nxbxxb.com\nxbzgold.com\nxc666.com\nxcabc.com\nxcarimg.com\nxcetv.com\nxcfc999.com\nxchelp.com\nxcjob.com\nxcljs.com\nxcmg.com\nxcmh.com\nxcrc999.com\nxcrj.com\nxcsztb.com\nxctour.com\nxcwenming.com\nxcy8.com\nxd.com\nxd57.com\nxdcharger.com\nxdf666.com\nxdfdly.com\nxdfxly.com\nxdnice.com\nxdowns.com\nxdwan.com\nxdxiazai.com\nxdxmw.com\nxdz.com\nxdzinfo.com\nxemh.com\nxenbo.com\nxesimg.com\nxeyjj.com\nxf-td.com\nxf0797.com\nxf88.com\nxfbst.com\nxfdq123.com\nxffcol.com\nxfgjj.com\nxfgx.com\nxfhqw.com\nxfj100.com\nxfqcol.com\nxftgrx.com\nxfun001.com\nxfwed.com\nxfydyt.com\nxgcw.com\nxglyy.com\nxgxedu.com\nxgzpw.com\nxgzrc.com\nxh-expo.com\nxh003.com\nxh925.com\nxhafz.com\nxhbhr.com\nxhcce.com\nxhengshui.com\nxhstv.com\nxhuaian.com\nxhume.com\nxiachufang.com\nxiadele.com\nxiadu.com\nxiagong.com\nxialv.com\nxiamenair.com\nxiameninvest.com\nxiamentour.com\nxiamenwater.com\nxiami.com\nxian-tourism.com\nxianbey.com\nxianbx.com\nxiancn.com\nxiandaishoucang.com\nxiang2012.com\nxiang5.com\nxiangauto.com\nxiangcunyou.com\nxiangguohe.com\nxianghe.com\nxianghunet.com\nxiangjiangyw.com\nxiangmu.com\nxiangqinyw.com\nxiangrikui.com\nxiangshanart.com\nxiangshengw.com\nxiangshu.com\nxianguo.com\nxiangyinxw.com\nxianjj.com\nxianlan315.com\nxianning.com\nxianoo.com\nxianpp.com\nxiansp.com\nxianyuange.com\nxianyuwang.com\nxianzhilou.com\nxiao-che.com\nxiao84.com\nxiaobaixitong.com\nxiaobao8.com\nxiaochangxian.com\nxiaoche5.com\nxiaofantian.com\nxiaogan.com\nxiaoguot.com\nxiaogushi.com\nxiaohei.com\nxiaohuangji.com\nxiaojiangguo123.com\nxiaojiulou.com\nxiaolebar.com\nxiaoliangkou.com\nxiaoma.com\nxiaomi.com\nxiaomi001.com\nxiaomishu.com\nxiaomizha.com\nxiaonaodai.com\nxiaonei.com\nxiaopi.com\nxiaopin5.com\nxiaopin8.com\nxiaot.com\nxiaoxiangrc.com\nxiaoxiaw.com\nxiaoxinwan.com\nxiaoyeren.com\nxiaoyu.com\nxiaoyuanfeng.com\nxiaozhishi.com\nxiaozhu.com\nxiaozhustatic1.com\nxiaozhustatic2.com\nxiaozhustatic3.com\nxiashanet.com\nxiayixian.com\nxiazaiba.com\nxiazaijidi.com\nxiazaizhijia.com\nxibakou.com\nxicai.com\nxiche168.com\nxicheji1.com\nxichengrc.com\nxichujob.com\nxiezilou.com\nxifengniao.com\nxifuquan.com\nxiggua.com\nxigu.com\nxigushi.com\nxihabang.com\nxihaiannews.com\nxihairc.com\nxihawan8.com\nxikoutourism.com\nxilituan.com\nxilu.com\nximalaya.com\nximenwai.com\nximij.com\nxin3721.com\nxinancaipiao.com\nxinancoal.com\nxincaijing.com\nxincainet.com\nxincheping.com\nxinchou114.com\nxinddy.com\nxinego.com\nxinfafloor.com\nxinfei.com\nxinfeihu.com\nxinfengit.com\nxinfenlei.com\nxinfuwan.com\nxingbanke.com\nxingchenmanhua.com\nxingjiesj.com\nxingjiezs.com\nxingkong.com\nxingming.com\nxingmucaoye.com\nxingshu.com\nxingtaishi.com\nxingtaitong.com\nxingxiangzg.com\nxingyang114.com\nxingyoucn.com\nxingyunba.com\nxingzuo123.com\nxingzuowu.com\nxinhe99.com\nxinhua08.com\nxinhuacang.com\nxinhuacnc.com\nxinhuame.com\nxinhuanet.com\nxinhuanteng.com\nxinhuatone.com\nxinjianghu.com\nxinjie88.com\nxinjiren.com\nxinju100.com\nxinjunshi.com\nxinkuaituan.com\nxinkz.com\nxinlexie.com\nxinluobo.com\nxinm123.com\nxinmanyuan.com\nxinmengzl.com\nxinnet.com\nxinnong.com\nxinpg.com\nxinpian.com\nxinpianimg.com\nxinpiaowang.com\nxinqianjiang.com\nxinquanedu.com\nxinshoucun.com\nxinshuozhou.com\nxinsilu.com\nxinsinong.com\nxinsixue.com\nxinsuixian.com\nxinsuwang.com\nxintairen.com\nxintairencai.com\nxintaizhou.com\nxintuan.com\nxinwangjing.com\nxinwo.com\nxinxiwo.com\nxinxunwang.com\nxinxunwei.com\nxinyeedu.com\nxinyi.com\nxinyiglass.com\nxinyou.com\nxinyubt.com\nxinyurc.com\nxiongying.com\nxipingbar.com\nxishanyihaoyuan.com\nxishiqu.com\nxishiwang.com\nxishu365.com\nxitek.com\nxitongcheng.com\nxitongcity.com\nxituan.com\nxiu.com\nxiu8.com\nxiuai.com\nxiugei.com\nxiuhome.com\nxiumei.com\nxiushuang.com\nxiwenquan.com\nxixiarc.com\nxixik.com\nxiyuit.com\nxizangshop.com\nxizhezhe.com\nxizhi.com\nxizhou.com\nxizi.com\nxj-zp.com\nxj169.com\nxj5u.com\nxj71.com\nxj96566.com\nxjass.com\nxjbzjj.com\nxjche365.com\nxjdaily.com\nxjdwx.com\nxjflcp.com\nxjfzb.com\nxjhj.com\nxjhjsd.com\nxjhr.com\nxjjjb.com\nxjjmw.com\nxjktarena.com\nxjlnwh.com\nxjrb.com\nxjtaobao.com\nxjtctv.com\nxjtonglan.com\nxjtour.com\nxjtrcw.com\nxjxnw.com\nxjxy.com\nxjz.com\nxjzj.com\nxjzsjc.com\nxkhouse.com\nxkseo.com\nxkwx.com\nxkxm.com\nxl699.com\nxlglsybl.com\nxlp8.com\nxlxjy.com\nxlys1904.com\nxlysauc.com\nxm-cs.com\nxm12333.com\nxm51.com\nxm597.com\nxm766.com\nxm7c.com\nxm96.com\nxmc325.com\nxmcdn.com\nxmculture.com\nxmdj123.com\nxmdtsh.com\nxmecc.com\nxmfc.com\nxmfish.com\nxmhougu.com\nxmhouse.com\nxmhunter.com\nxmibi.com\nxmjim.com\nxmjobs.com\nxmjxzx.com\nxmjydj.com\nxmmama.com\nxmnorns.com\nxmpig.com\nxmqilian.com\nxmsegu.com\nxmsjob.com\nxmsme.com\nxmsmjk.com\nxmtarc.com\nxmtsjq.com\nxmuky.com\nxmvivi.com\nxmwj.com\nxmwsjd.com\nxmzrc.com\nxmzyrc.com\nxn121.com\nxnfw.com\nxnguke.com\nxnhaofang.com\nxnjhome.com\nxnjjob.com\nxnkao.com\nxnmei.com\nxnmtd.com\nxnpad.com\nxns315.com\nxnwsc.com\nxnyauto.com\nxnyfd.com\nxnynews.com\nxoyin.com\nxoyo.com\nxp14.com\nxp3366.com\nxp510.com\nxp597.com\nxp74.com\nxp85.com\nxp911.com\nxpenyou.com\nxpgod.com\nxplus.com\nxpxww.com\nxrkcdn.com\nxs9999.com\nxsbhjt.com\nxsfc.com\nxsjob.com\nxskhome.com\nxsledu.com\nxsme.com\nxsmnews.com\nxsool.com\nxsqw.com\nxstour.com\nxsyjn.com\nxszrcw.com\nxt12333.com\nxt512.com\nxt866.com\nxtcheche.com\nxtdtzc.com\nxtedu.com\nxtjc.com\nxtjdcjsr.com\nxtkjp.com\nxtsou.com\nxtuan.com\nxtx6.com\nxtyhbz.com\nxu.com\nxuanchuanyi.com\nxuanke.com\nxuanke114.com\nxuanruanjian.com\nxuanwww.com\nxuanxuan.com\nxuanxue.com\nxuanyi.com\nxuanzequan.com\nxuchangbbs.com\nxue163.com\nxue2you.com\nxue5156.com\nxuebuyuan.com\nxuechela.com\nxuechenghr.com\nxuechengkaoyan.com\nxueda.com\nxueersi.com\nxueeu.com\nxuefengwuji.com\nxuefofa.com\nxueid.com\nxuejutea.com\nxuekeedu.com\nxueshandai.com\nxueshanrc.com\nxuex123.com\nxuexi111.com\nxuexiaodaquan.com\nxuexifangfa.com\nxuexila.com\nxueyiyun.com\nxumulc.com\nxumurc.com\nxumuren.com\nxumutongshi.com\nxun-yi.com\nxun8.com\nxunche.com\nxungou.com\nxunlei.com\nxunleimil.com\nxunxianrc.com\nxunzai.com\nxuzhouc.com\nxuzhoujob.com\nxw365.com\nxwcsj.com\nxwen.com\nxwham.com\nxwhb.com\nxwhrcw.com\nxwimg.com\nxwpx.com\nxx028.com\nxxcig.com\nxxcmw.com\nxxcxw.com\nxxdm.com\nxxfang.com\nxxgcw.com\nxxgjj.com\nxxhh.com\nxxia.com\nxxluo.com\nxxplzx.com\nxxs8.com\nxxsc.com\nxxsp518.com\nxxtef.com\nxxtg.com\nxxtlw.com\nxxxye.com\nxxzhaopin.com\nxxzq.com\nxxzzm.com\nxy.com\nxy280.com\nxy3nw.com\nxy597.com\nxy9981.com\nxyanjia.com\nxyb100.com\nxydhl.com\nxyfc.com\nxyfcw.com\nxyfnw.com\nxyg100.com\nxygjy.com\nxygmed.com\nxyjrw.com\nxypht.com\nxyppzx.com\nxyrczpw.com\nxyrtv.com\nxyshu8.com\nxywy.com\nxyxww.com\nxyxxg.com\nxyxy01.com\nxyyao.com\nxyybxg.com\nxyyintong.com\nxyzfgjj.com\nxyzs.com\nxyzwin.com\nxz323.com\nxz5u.com\nxz91.com\nxzbu.com\nxzfamily.com\nxzfashion.com\nxzgjj.com\nxzhichang.com\nxzhiliao.com\nxzjyh.com\nxzl571.com\nxzloo.com\nxzlres.com\nxzrbw.com\nxzt9.com\nxzuan.com\nxzxx.com\nxzyuhui.com\ny13255262618.com\ny261.com\ny3600.com\ny999.com\nya247.com\nya597.com\nyaanrcw.com\nyaantv.com\nyacely.com\nyacol.com\nyafengwu.com\nyaheen.com\nyahqq.com\nyakolux.com\nyala517.com\nyamszs.com\nyanchang.com\nyandongjixie.com\nyanfabu.com\nyanfang12365.com\nyangche51.com\nyangchenghuxie.com\nyangfenzi.com\nyangguangbao.com\nyangji.com\nyangjiajiao.com\nyangjihu.com\nyanglao120.com\nyanglihui.com\nyanglingwang.com\nyangnai100.com\nyangshenglife.com\nyangshitianqi.com\nyangsousou.com\nyangsukj.com\nyangtse.com\nyanjiao.com\nyanjiaorexian.com\nyanjob.com\nyankon.com\nyanlutong.com\nyanmo360.com\nyanmoxuan.com\nyantai-chuanpiao.com\nyantuchina.com\nyantushi.com\nyanxiaoni.com\nyanzhaorc.com\nyanzheng.com\nyanzhoujob.com\nyanzixiang.com\nyaochufa.com\nyaofangwang.com\nyaojingweiba.com\nyaojobs.com\nyaolan.com\nyaosai.com\nyaoshiduo.com\nyaowan.com\nyaoxinfu.com\nyaozh.com\nyaozs.com\nyappygo.com\nyarczp.com\nyasn.com\nyatai.com\nyaya888.com\nyayawan.com\nyb983.com\nybaixin.com\nybbbs.com\nybdu.com\nybgjj.com\nybhzs.com\nybk001.com\nyblysy.com\nybvv.com\nybxww.com\nyc-cq.com\nyc-yujia.com\nyc123.com\nyc597.com\nyc9y.com\nycbole.com\nyccar.com\nyccdn.com\nycfczc.com\nycgjj.com\nychr.com\nyckuoda.com\nyclunwen.com\nycpai.com\nycrczpw.com\nycrusher.com\nycseaman.com\nycshequ.com\nycsrcsc.com\nyctarena.com\nycwb.com\nycxc.com\nycxinxi.com\nyczihua.com\nydcast.com\nydcbw.com\nyddyw.com\nydjy.com\nydstatic.com\nydsteel.com\nye40.com\nyeepay.com\nyeesha.com\nyefeilvshi.com\nyejinye.com\nyejinzg.com\nyemaozi.com\nyes515.com\nyesfr.com\nyeshanpo.com\nyeshj.com\nyesky.com\nyesmywine.com\nyespearl.com\nyesshou.com\nyeyou.com\nyeyoucdn.com\nyeyoudaquan.com\nyeyoujia.com\nyeyouw.com\nyeyouwo.com\nyf116.com\nyf12365.com\nyf133.com\nyfdyf.com\nyfgg.com\nyg188.com\nygits.com\nygjj.com\nygqiantu.com\nyh2002.com\nyhd.com\nyhdali.com\nyhganggou.com\nyhh668.com\nyhjj.com\nyhouse.com\nyi-z.com\nyi6.com\nyi7.com\nyiase.com\nyibiaojob.com\nyibinfen.com\nyibu.com\nyibuyibu.com\nyicai.com\nyicars.com\nyichangly.com\nyiche.com\nyichemall.com\nyicheshi.com\nyichun0795.com\nyichuntv.com\nyicp.com\nyida0760.com\nyidaba.com\nyidianchina.com\nyidujia.com\nyiecha.com\nyifen.com\nyifone.com\nyifu.com\nyigao.com\nyigaokao.com\nyihaodian.com\nyihaodianimg.com\nyihu.com\nyihubaiying.com\nyihuimg.com\nyiihuu.com\nyijiaqin.com\nyijie.com\nyijiuweilan.com\nyijjj.com\nyikedou.com\nyikeer.com\nyikuaiqu.com\nyikuaiyou.com\nyiledao.com\nyili.com\nyilianit.com\nyilin.com\nyiliu88.com\nyilu365.com\nyimanman.com\nyimenchuang.com\nyimianmian.com\nyiminjiayuan.com\nyinar.com\nyingbishufa.com\nyingchuang.com\nyinghuangzs.com\nyingjia360.com\nyingjiesheng.com\nyingkelawyer.com\nyingmoo.com\nyingsheng.com\nyingsoft.com\nyingtaoai.com\nyingxiao360.com\nyingxiongji.com\nyingyonghui.com\nyingyu.com\nyingyu360.com\nyingyugaofen.com\nyinhang.com\nyinjucn.com\nyinlianbang.com\nyinlingyounao.com\nyinongdai.com\nyinsha.com\nyinshihui.com\nyintai.com\nyinuowl.com\nyinxingshu.com\nyinyuegf.com\nyinyuetai.com\nyinzuojiaju.com\nyipihuo.com\nyiqibazi.com\nyiqifa.com\nyiqijixiang.com\nyiqike.com\nyiqisoo.com\nyiren198.com\nyirendai.com\nyishu.com\nyishujie.com\nyisoche.com\nyisou.com\nyisou5.com\nyitiaogen8.com\nyiwan.com\nyiwubuy.com\nyiwufair.com\nyiwugou.com\nyixianjob.com\nyixiaoba.com\nyixieshi.com\nyixingpx.com\nyixue001.com\nyixue99.com\nyixuewang.com\nyixuezp.com\nyixun.com\nyiyaolietou.com\nyiyibuy.com\nyiyu.com\nyiyyy.com\nyizhaopin.com\nyizimg.com\nyj-job.com\nyj0577.com\nyj518.com\nyjbctv.com\nyjbys.com\nyjcom.com\nyjdj.com\nyjh321.com\nyjlxauto.com\nyjpdf.com\nyjsyu.com\nyk0579.com\nykimg.com\nykrx.com\nyktchina.com\nyktworld.com\nykw18.com\nykwin.com\nyl007.com\nyl1001.com\nyldt.com\nylimg.com\nylpcs.com\nylsw.com\nylting.com\nyltvb.com\nylw0813.com\nylw168.com\nylwltv.com\nylxwzzb.com\nylxxg.com\nylzmhzs.com\nymapp.com\nymars.com\nymfile.com\nymkjpx.com\nymlaser.com\nymt360.com\nyn1234.com\nyn16.com\nynchj.com\nyncie.com\nyncits08.com\nyncoop.com\nyndaily.com\nyndtjj.com\nynet.com\nynfjw.com\nyngkseed.com\nyngod.com\nynhmw.com\nynhouse.com\nynhr.com\nynihao.com\nyninfo.com\nynit580.com\nynithr.com\nynjtt.com\nynju.com\nynkcw.com\nynnm.com\nynpost.com\nynpxrz.com\nynradio.com\nynshangji.com\nynsugar.com\nyntrip88.com\nynwangli.com\nynxxb.com\nynyes.com\nynyh.com\nynyj.com\nynzol.com\nynzp.com\nyodao.com\nyofond.com\nyofus.com\nyoger01.com\nyoher.com\nyohobuy.com\nyoka.com\nyokacdn.com\nyongchengren.com\nyongjiangrc.com\nyongjiwooden.com\nyonglijh.com\nyooduo.com\nyoofh.com\nyoohouse.com\nyooli.com\nyoosure.com\nyorkinstrument.com\nyou178.com\nyou89.com\nyouba.com\nyouban.com\nyoubian.com\nyoubianku.com\nyoubibi.com\nyouboy.com\nyouc.com\nyouchepin.com\nyoudao.com\nyoudu5.com\nyoufangw.com\nyougou.com\nyouguow.com\nyouhaotravel.com\nyouhuaaa.com\nyouhuas.com\nyoujiao.com\nyoujiaxiao.com\nyoujindi.com\nyoujobit.com\nyoukecn.com\nyoukee.com\nyoukelai.com\nyouku.com\nyoule55.com\nyoulunzhaopin.com\nyoumogu.com\nyouneng.com\nyouqudao.com\nyousergroup.com\nyousesky.com\nyoushang.com\nyoushanjiayuan.com\nyoushige.com\nyoutiy.com\nyoutulou.com\nyoutx.com\nyouwo.com\nyouxi.com\nyouxi369.com\nyouxi86.com\nyouxiake.com\nyouxibe.com\nyouxiduo.com\nyouxigonglue8.com\nyouxigt.com\nyouxigu.com\nyouxihuoban.com\nyouxike.com\nyouxilao.com\nyouxile.com\nyouxinan.com\nyouxiniao.com\nyouxiping.com\nyouxiputao.com\nyouxiqun.com\nyouxituoluo.com\nyouxiuhui.com\nyouxiwangguo.com\nyouxiweixun.com\nyouxjia.com\nyouyou234.com\nyouyuan.com\nyouyy.com\nyouzhiqin.com\nyouzhuan.com\nyouzu.com\nyoyobaby.com\nyoyojie.com\nyoyou.com\nyp10000.com\nyp900.com\nypgair.com\nypian.com\nypwjob.com\nyq919.com\nyqbdt.com\nyqdown.com\nyqjiehun.com\nyqrc.com\nyqrtv.com\nyr1818.com\nys137.com\nys168.com\nys1688.com\nys7.com\nys7828.com\nysali.com\nyscbook.com\nyshlawyer.com\nysjvip.com\nysrencai.com\nysw365.com\nyswxcn.com\nyt160.com\nytbbs.com\nytbxw.com\nytcutv.com\nytdwhyjzs.com\nythouse.com\nytinstrument.com\nytjob.com\nytloushi.com\nytrczpw.com\nytrlzyw.com\nytscd.com\nytszg.com\nytwrc.com\nytxww.com\nyu-dian.com\nyuadmin.com\nyuai.com\nyuananren.com\nyuanlin.com\nyuanlin001.com\nyuanlin365.com\nyuanlin8.com\nyuanliner.com\nyuanlinyc.com\nyuanyetrip.com\nyublue.com\nyubooa.com\nyucde.com\nyuchai.com\nyudujob.com\nyuduzi.com\nyue365.com\nyuecheng.com\nyuedutong.com\nyueduwen.com\nyuejianglou.com\nyuejob.com\nyueloo.com\nyuemei.com\nyuerzaixian.com\nyuewo.com\nyuexiren.com\nyueyuzhushou.com\nyufolunchan.com\nyugunet.com\nyuhuijob.com\nyujia.com\nyujia99.com\nyukuai.com\nyulehezi.com\nyulindayday.com\nyulipump.com\nyuloo.com\nyulua.com\nyun61.com\nyunanjgs.com\nyunbangwang.com\nyunbei.com\nyunceng.com\nyuncheng.com\nyunchenghr.com\nyunci4.com\nyundaex.com\nyundangan.com\nyundianrc.com\nyunfudaily.com\nyunhepan.com\nyunli.com\nyunmaotong.com\nyunnanrc.com\nyunnao.com\nyunos.com\nyunshipei.com\nyunshow.com\nyuntaodu.com\nyunust.com\nyunuu.com\nyunwenxue.com\nyunyangrc.com\nyupoo.com\nyuqinge.com\nyurun.com\nyusuan.com\nyutai100.com\nyuu1.com\nyuxinews.com\nyuyingchina.com\nyuzhepeixun.com\nyw11.com\nyw2005.com\nyw597.com\nywbb.com\nywcec.com\nywcq.com\nywefood.com\nywmeexpo.com\nywxue.com\nywzz.com\nyx-s.com\nyx007.com\nyx136.com\nyx99.com\nyxacw.com\nyxad.com\nyxbao.com\nyxdaily.com\nyxdown.com\nyxgjj.com\nyxi5.com\nyxi8.com\nyxlady.com\nyxm.com\nyxph.com\nyxqnews.com\nyxsanhu.com\nyxtvg.com\nyxzoo.com\nyy.com\nyy138.com\nyy960.com\nyybbs.com\nyycqc.com\nyydm.com\nyyfad.com\nyyfdcw.com\nyyfensi.com\nyygjj.com\nyyhao.com\nyyhh.com\nyyhospital.com\nyyhqys.com\nyyjia.com\nyyjol.com\nyykc.com\nyymjx.com\nyyqc.com\nyyqx.com\nyyrc.com\nyyrtv.com\nyysweb.com\nyyt360.com\nyytcdn.com\nyytou.com\nyytzx.com\nyyxggjm.com\nyyxinqing.com\nyyxj8.com\nyyxnews.com\nyyxt.com\nyyxxcc.com\nyz-china.com\nyz2shou.com\nyz2y.com\nyz355.com\nyzcts.com\nyzdjbh.com\nyzdsb.com\nyzfcd.com\nyzfcw.com\nyzforex.com\nyzhyw.com\nyzjdc.com\nyzqcw.com\nyzrc.com\nyzsfcw.com\nyzxw.com\nyzzaoxing.com\nz4bbs.com\nzafk120.com\nzahuishi.com\nzaihuangshi.com\nzaisd.com\nzaiyunbian.com\nzaizai5.com\nzan800.com\nzanba.com\nzanzw.com\nzaoche168.com\nzaojia.com\nzaojiao.com\nzaojiashi.com\nzaojob.com\nzaopang.com\nzaozhichu.com\nzaozhuangfangchan.com\nzastatic.com\nzazhipu.com\nzb31.com\nzbcars.com\nzbfjsj.com\nzbgjpx.com\nzbhouse.com\nzbii.com\nzbintel.com\nzbird.com\nzbjimg.com\nzbjinchen.com\nzbjjrcw.com\nzbmiao.com\nzbradio.com\nzbsme.com\nzbzfgjj.com\nzcfun.com\nzcheer.com\nzchospital.com\nzcom.com\nzcqiche.com\nzcrcw.com\nzcrczp.com\nzctcar.com\nzctt.com\nzcwz.com\nzcxn.com\nzcyy8.com\nzd360.com\nzddmall.com\nzdface.com\nzdhnjd.com\nzdhtjx.com\nzdhyb.com\nzdrcw.com\nzei6.com\nzei8.com\nzenque.com\nzepao.com\nzero-orez.com\nzero2ipovc.com\nzf3d.com\nzf875.com\nzf9918.com\nzfang.com\nzfn8.com\nzft.com\nzg-ld.com\nzg-xbwh.com\nzg0543.com\nzg17.com\nzg1929.com\nzgb365.com\nzgbfw.com\nzgbigart.com\nzgbm.com\nzgchangfang.com\nzgchawang.com\nzgcmlm.com\nzgcsgd.com\nzgcyfz.com\nzgcyly.com\nzgcylymh.com\nzgczxzx.com\nzgdjyj.com\nzgdls.com\nzgdrive.com\nzgfcn.com\nzgftjg.com\nzgfxnews.com\nzgfznews.com\nzgg35.com\nzggdjj.com\nzggwyw.com\nzggyp.com\nzghbsw.com\nzghjjlm.com\nzgjcjs.com\nzgjczzw.com\nzgjf168.com\nzgjfs.com\nzgjhjy.com\nzgjlxww.com\nzgjn365.com\nzgjnzx.com\nzgjrcw.com\nzgjrjw.com\nzgjrzk.com\nzgjsks.com\nzgjtb.com\nzgjy111.com\nzgjzlw.com\nzgkjzx.com\nzgkspx.com\nzglcppt.com\nzgltgj.com\nzglxw.com\nzgmcxw.com\nzgmdbw.com\nzgmklt.com\nzgmtkj.com\nzgmxzx.com\nzgnfcphy.com\nzgnfcpjx.com\nzgnhzx.com\nzgnyqss.com\nzgong.com\nzgppny.com\nzgqczj.com\nzgqdrc.com\nzgqpc.com\nzgqsc.com\nzgqw.com\nzgrcjyw.com\nzgrdcy.com\nzgsbzlcy.com\nzgsc123.com\nzgsccd.com\nzgscpcy.com\nzgsdsmh.com\nzgshengsi.com\nzgshoes.com\nzgsjylhy.com\nzgsjyxzx.com\nzgsjzxxx.com\nzgslylw.com\nzgsof.com\nzgspgq.com\nzgswcn.com\nzgsxzs.com\nzgsyb.com\nzgsydw.com\nzgsynews.com\nzgtcha.com\nzgtjh.com\nzgtnzx.com\nzgxbmjw.com\nzgxf88.com\nzgxnyzx.com\nzgxzw.com\nzgycrc.com\nzgyey.com\nzgyspp.com\nzgyushiwang.com\nzgyz001.com\nzgzcw.com\nzgznh.com\nzgzsp.com\nzgzsw.com\nzgzsys.com\nzgzx114.com\nzh-365.com\nzh-hr.com\nzh-hz.com\nzh28.com\nzh5000.com\nzh51home.com\nzh853.com\nzhaif.com\nzhaigirl.com\nzhaihei.com\nzhainanwan.com\nzhairport.com\nzhanggame.com\nzhangjk.com\nzhangle.com\nzhangniu.com\nzhangpu597.com\nzhangyoushijie.com\nzhankua.com\nzhantai.com\nzhaoapple.com\nzhaocaihr.com\nzhaochafa.com\nzhaodanji.com\nzhaofangtong.com\nzhaogejia.com\nzhaoiphone.com\nzhaojiaxiao.com\nzhaoming123.com\nzhaomingwjj.com\nzhaopin.com\nzhaopin2.com\nzhaopinxitong.com\nzhaopuw.com\nzhaoqiweb.com\nzhaoshang-sh.com\nzhaoshang01.com\nzhaoshang100.com\nzhaoshang800.com\nzhaoshangbao.com\nzhaosheng.com\nzhaotie.com\nzhaoxiaoshuo.com\nzhaoyuan365.com\nzhayoule.com\nzhazhi.com\nzhbiao.com\nzhcoo.com\nzhcpic.com\nzhcw.com\nzhdzw.com\nzhe800.com\nzhedakaoyan.com\nzhelun.com\nzhenai.com\nzhenfangyuan.com\nzhengfayingjie.com\nzhengjin99.com\nzhengquanzige.com\nzhengwutong.com\nzhengzhoubus.com\nzhenimg.com\nzhenjianghr.com\nzhenpin.com\nzhenren.com\nzhenweiexpo.com\nzheyangai.com\nzheyibu.com\nzhgczj.com\nzhgl.com\nzhgnews.com\nzhhbi.com\nzhhbw.com\nzhhdq.com\nzhibio.com\nzhibitouzi.com\nzhiboba.com\nzhibowu.com\nzhicg.com\nzhicheng.com\nzhidantour.com\nzhiding8.com\nzhidiy.com\nzhifang.com\nzhigame.com\nzhigou.com\nzhihelou.com\nzhihongchazhuang.com\nzhihu.com\nzhihuilv.com\nzhihuimami.com\nzhiji.com\nzhijia.com\nzhijinsteel.com\nzhijintuan.com\nzhijinwang.com\nzhileng.com\nzhileng8.com\nzhiliangshi.com\nzhimantian.com\nzhinei.com\nzhineikaixin.com\nzhinengjiaotong.com\nzhinews.com\nzhishagongyi.com\nzhitechan.com\nzhituad.com\nzhitui.com\nzhiweiwenshi.com\nzhiwenyl.com\nzhixuan.com\nzhiye.com\nzhiyeyaoshi.com\nzhiyeyishi.com\nzhiyinmanhua.com\nzhiyuanfuwu.com\nzhiyuanyun.com\nzhiziyun.com\nzhjiameng.com\nzhjunshi.com\nzhjzmh.com\nzhld.com\nzhnjw.com\nzhongbuauto.com\nzhongdaonet.com\nzhongdeng.com\nzhongdingw.com\nzhongguodali.com\nzhongguokanghui.com\nzhongguolaoqu.com\nzhongguonongziwang.com\nzhongguosyzs.com\nzhongguowangshi.com\nzhonghuacar.com\nzhongji8.com\nzhongkao.com\nzhongkao5.com\nzhonglianyian.com\nzhongman.com\nzhongp.com\nzhongshanbus.com\nzhongso.com\nzhongsou.com\nzhongyalyw.com\nzhongyuanauto.com\nzhongzhourc.com\nzhoujijl.com\nzhousipump.com\nzhqxj.com\nzhsh5000.com\nzhsho.com\nzhtdshy.com\nzhtmw.com\nzhtool.com\nzhtv.com\nzhuang100.com\nzhuangjiba.com\nzhuangku.com\nzhuangpin.com\nzhuangxiu315.com\nzhuannet.com\nzhuanseo.com\nzhuantiku.com\nzhuanyewanjia.com\nzhuapo.com\nzhuaxia.com\nzhuayoukong.com\nzhubajie.com\nzhubao.com\nzhubing120.com\nzhuchengrc.com\nzhuego.com\nzhuhaia.com\nzhuhaifc.com\nzhuhaily.com\nzhuhaimy.com\nzhuinvsheng.com\nzhujia360.com\nzhujia86.com\nzhujiaba.com\nzhujiange.com\nzhujiangrc.com\nzhujiangroad.com\nzhujiankang.com\nzhuke.com\nzhulang.com\nzhulink.com\nzhulisy.com\nzhulong.com\nzhuo.com\nzhuodingedu.com\nzhuoji.com\nzhuokearts.com\nzhuoku.com\nzhuoyueenglish.com\nzhuozhoufangchan.com\nzhuozhourencai.com\nzhuqu.com\nzhuqunqing.com\nzhuzao.com\nzhuzaochina.com\nzhuzaohr.com\nzhuzhouwang.com\nzhuzhudao.com\nzhwsjd.com\nzhxjyw.com\nzhxwang.com\nzhzfc.com\nzibocn.com\nzibomama.com\nziborc.com\nzibosky.com\nzidiantong.com\nzidianwang.com\nzihua01.com\nzijiayoucn.com\nzijinyin.com\nzikao1688.com\nzikao365.com\nziling.com\nzimilan.com\nziranzhibao.com\nziroom.com\nziroomapartment.com\nzisha.com\nzisha360.com\nzisha8090.com\nzishayx.com\nzishayy.com\nzitichina.com\nziwoniu.com\nzixia.com\nzixuexi.com\nzixuntop.com\nziyuan5.com\nzj.com\nzj-alevel.com\nzj005.com\nzj121.com\nzj123.com\nzj186.com\nzj9.com\nzjadgroup.com\nzjbar.com\nzjcaoban.com\nzjcb.com\nzjcheshi.com\nzjchuguo.com\nzjcoal.com\nzjcoop.com\nzjebbs.com\nzjg12345.com\nzjgdrc.com\nzjghfw.com\nzjghot.com\nzjgjj.com\nzjgrrb.com\nzjgsmwy.com\nzjhep.com\nzjhq.com\nzjhr.com\nzjhzart.com\nzjic.com\nzjincubator.com\nzjits.com\nzjj-hc.com\nzjjcts.com\nzjjcy.com\nzjjhaodi.com\nzjjk365.com\nzjjrc.com\nzjjta.com\nzjjvip.com\nzjjxs.com\nzjjybkzs.com\nzjjyzx.com\nzjjzzp.com\nzjketv.com\nzjkgz.com\nzjknews.com\nzjkonline.com\nzjkrbsnews.com\nzjks.com\nzjkwang.com\nzjllw.com\nzjlottery.com\nzjlqw.com\nzjlscourt.com\nzjmoney.com\nzjnhaf.com\nzjningbo.com\nzjolcdn.com\nzjpark.com\nzjphis.com\nzjpost.com\nzjpse.com\nzjpxzx.com\nzjrail.com\nzjrc.com\nzjrxz.com\nzjscdb.com\nzjsmap.com\nzjsr.com\nzjstv.com\nzjszrc.com\nzjtcn.com\nzjtree.com\nzjtxrc.com\nzjwater.com\nzjwchc.com\nzjwmw.com\nzjxf119.com\nzjxjrc.com\nzjxww.com\nzjzcj.com\nzk21.com\nzk3158.com\nzk71.com\nzkcrm.com\nzkjkgc.com\nzkxww.com\nzkzp.com\nzlhome.com\nzlmfcw.com\nzlook.com\nzlpumps.com\nzls365.com\nzlwq.com\nzmd5.com\nzmdfcw.com\nzmdfdc.com\nzmdjzw.com\nzmgov.com\nzmnedu.com\nzmyjy.com\nzmzhw.com\nznds.com\nznhr.com\nznimg.com\nznxkw.com\nzocai.com\nzol.com\nzongheng.com\nzonglai.com\nzongsifang.com\nzoomlion.com\nzoossoft.com\nzopomobile.com\nzotye.com\nzouquwan.com\nzoutu.com\nzp0370.com\nzp0372.com\nzp0517.com\nzp365.com\nzp512.com\nzp515.com\nzp597.com\nzp666.com\nzpb365.com\nzpfdc.com\nzph-sh.com\nzph58.com\nzplm.com\nzprc.com\nzpydt.com\nzpzj.com\nzpzpw.com\nzq84.com\nzqgame.com\nzqlqt.com\nzqnksw.com\nzqrsrc.com\nzqzhibo.com\nzr597.com\nzr98.com\nzrexam.com\nzritn.com\nzrtg.com\nzs-coop.com\nzs-hospital.com\nzs-jyx.com\nzs27.com\nzs310.com\nzsbicycle.com\nzsbwg.com\nzsby.com\nzschinese.com\nzsdinghai.com\nzsdonggang.com\nzsemail.com\nzsezt.com\nzsfybjy.com\nzsglj.com\nzsguilai.com\nzshl.com\nzshouyou.com\nzshyqx.com\nzsi68.com\nzsjjob.com\nzskxg.com\nzslz.com\nzsmama.com\nzsmls.com\nzsnet.com\nzsnets.com\nzsnl.com\nzspt-hospital.com\nzsputuo.com\nzsqx.com\nzssalt.com\nzsscoop.com\nzssns.com\nzssou.com\nzst365.com\nzsw-qd.com\nzswcn.com\nzsxnts.com\nzsysdiy.com\nzszgh.com\nzszk.com\nzszxt.com\nzt5.com\nztcadx.com\nztcrc.com\nztems.com\nztgame.com\nztsfc.com\nztsfcw.com\nztv-5.com\nztyxkj.com\nztzftc.com\nzubunet.com\nzuche.com\nzuchecdn.com\nzuciwang.com\nzudemi.com\nzudong.com\nzufang.com\nzufang8.com\nzufangbao.com\nzugame.com\nzugou.com\nzui74.com\nzuifengyun.com\nzuigexing.com\nzuitech.com\nzuiyouxi.com\nzujuan.com\nzulinnet.com\nzunjuehuangjia.com\nzunlongweiyu.com\nzunyiol.com\nzunyiyizhuan.com\nzuoanlong.com\nzuodia.com\nzuojiang.com\nzuojiawang.com\nzuowen.com\nzuowenren.com\nzuoye88.com\nzupuk.com\nzupulu.com\nzuulee.com\nzuyaya.com\nzuzhirenshi.com\nzuzuche.com\nzwcad.com\nzwhz.com\nzwlwrc.com\nzwye.com\nzx163k.com\nzx98.com\nzxdrying.com\nzxdyw.com\nzxhro.com\nzxhsd.com\nzxip.com\nzxiu.com\nzxiubbs.com\nzxking.com\nzxqss.com\nzxrcw.com\nzxtang.com\nzxwh.com\nzxwygzs.com\nzxxk.com\nzxxww.com\nzxxxkj.com\nzxzhijia.com\nzy.com\nzy12580.com\nzy91.com\nzyautoe.com\nzybus.com\nzycits.com\nzycmmt.com\nzyctd.com\nzyflipin.com\nzygk.com\nzygyy.com\nzyjgkj.com\nzynews.com\nzyoulun.com\nzyptm.com\nzyqczz.com\nzyshr.com\nzysj360.com\nzytxs.com\nzyue.com\nzyuexc.com\nzyxjz.com\nzyxuan.com\nzyzhan.com\nzyzhaopin.com\nzyzhjt.com\nzz597.com\nzz91.com\nzzb58.com\nzzbaike.com\nzzbbs.com\nzzbk.com\nzzbtv.com\nzzccjsj.com\nzzccs.com\nzzdjw.com\nzzdxyc.com\nzzeol.com\nzzfcw.com\nzzfxj.com\nzzfzjob.com\nzzgjj.com\nzzhcz.com\nzzhpkj.com\nzzidc.com\nzzielts.com\nzzjidi.com\nzzjob88.com\nzzjol.com\nzzjsjy.com\nzzleju.com\nzzloushi.com\nzzmnls.com\nzzol360.com\nzzpgm.com\nzzqc.com\nzzqcw.com\nzzqiche.com\nzzrsks.com\nzzsfybjy.com\nzzsgjj.com\nzzsglj.com\nzzshl.com\nzzsr.com\nzzstep.com\nzzta.com\nzztengda.com\nzztlj.com\nzzwljc.com\nzzxmjx.com\nzzxsjswkj.com\nzzyjs.com\nzzyycc.com\nzzyyss.com\nzzz4.com\nzzzj.com\nzzzlll.com\nchina-botschaft.de\nceibs.edu\neurasia.edu\n637.fm\ndouban.fm\nlvxing.fm\nbehome.hk\nbluestacks.hk\nbmd.hk\nctrip.com.hk\ntakungpao.com.hk\ngap.hk\nfmcoprc.gov.hk\nitools.hk\nlocpg.hk\ntimall.hk\nbxr.im\ncli.im\niapps.im\nyixin.im\naushome.info\nchinasteel.info\ncnzx.info\nhaiguan.info\njdwx.info\njiuyan.info\nlaishui.info\nmeihua.info\nmmbang.info\nseheli.info\nsemidata.info\ntaicang.info\nwilliamlong.info\nzhenkong.info\njianshu.io\nctrip.co.kr\n0827.la\n17wan.la\n33.la\n35.la\n36.la\n51.la\n51wan.la\n55.la\n900.la\ndehua.la\ndns.la\nmeiju.la\nqzone.la\nruanwen.la\ntiaowu.la\ntool.la\nwordpress.la\nyky.la\n21me.me\naips.me\nbole.me\ngall.me\nhaining.me\nhaopic.me\nlovewith.me\nneitui.me\npcpc.me\nqbox.me\nshijue.me\nsodao.me\ntopit.me\ntvb.me\nurl7.me\nweimi.me\nwmpic.me\nyo6.me\nzhangjiajie.me\ncnswys.mobi\nnewman.mobi\nnmgmt.mobi\nsouyue.mobi\nvnet.mobi\nzgyss.mobi\nzonglai.mobi\nccuc.name\nsosuo.name\nzhuangxiu.name\n001sj.net\n00615.net\n021766.net\n021shangyuan.net\n0261.net\n027.net\n0312zp.net\n0376.net\n0513.net\n0517.net\n0519car.net\n0533.net\n0537fc.net\n0566cn.net\n0573zp.net\n0577home.net\n0738fdc.net\n0755.net\n0758fc.net\n0759home.net\n0771ch.net\n0797live.net\n0871job.net\n0875job.net\n0891job.net\n0898.net\n0898hn.net\n0937.net\n10050.net\n100jiaoyu.net\n100t1.net\n111cn.net\n114hr.net\n11pk.net\n121121.net\n123juzi.net\n125cn.net\n126.net\n126job.net\n127.net\n1556.net\n157300.net\n1616.net\n163.net\n163yy.net\n1688e.net\n17173ie.net\n1718china.net\n177dj.net\n17lu.net\n17u.net\n18838.net\n18dao.net\n198526.net\n1qj.net\n200.net\n21-sun.net\n21ccom.net\n21cn.net\n21cp.net\n21ks.net\n21page.net\n230la.net\n2345.net\n238000.net\n24jq.net\n24pay.net\n25pp.net\n263.net\n269.net\n288jc.net\n2dx.net\n2liang.net\n2rich.net\n2scc.net\n312000.net\n3158.net\n317600.net\n325802.net\n3265.net\n3304399.net\n33378.net\n360guakao.net\n3650310.net\n365kl.net\n36kr.net\n371.net\n37wan.net\n39.net\n3banfu.net\n3cjob.net\n3conline.net\n3derp.net\n3edu.net\n3g210.net\n3sjob.net\n3snews.net\n3u5.net\n41717.net\n419600.net\n434300.net\n4399api.net\n461000.net\n4fang.net\n4gdh.net\n4yt.net\n512g.net\n51education.net\n51fanli.net\n51gaokao.net\n51hunter.net\n51la.net\n51psy.net\n51qc.net\n51room.net\n51ss.net\n51test.net\n51yuming.net\n51zd.net\n51zxw.net\n520.net\n520f.net\n520ok.net\n520zg.net\n5219.net\n5251.net\n52cake.net\n52car.net\n52ch.net\n52db.net\n52hotel.net\n52jj.net\n52kl.net\n52njl.net\n52op.net\n52pcgame.net\n52sales.net\n52th.net\n52tian.net\n530312.net\n53999.net\n5460.net\n54cn.net\n54kefu.net\n5566.net\n557.net\n56885.net\n56888.net\n56ye.net\n57315.net\n58728.net\n58abc.net\n5d6d.net\n5haoxue.net\n5i9u.net\n5ips.net\n5ixuexi.net\n5qv.net\n6259114.net\n6300.net\n66one.net\n68design.net\n69js.net\n6down.net\n71p.net\n722300.net\n788job.net\n78dm.net\n7do.net\n7u7.net\n800400.net\n8080.net\n80data.net\n80dyy.net\n818chuguo.net\n81un.net\n850505.net\n860714.net\n8671.net\n91tea.net\n94117.net\n9600169.net\n962.net\n97616.net\n999120.net\n99edu.net\na963.net\nacftu.net\nactoys.net\nadmin5.net\nadpolestar.net\nagjob.net\nah163.net\nahage.net\nahhy.net\nahjs.net\nahtarena.net\najfcw.net\najiang.net\naladd.net\nali213.net\nali37.net\nanbingsoft.net\nandroidonline.net\nanshunjob.net\nanyv.net\naotrip.net\napidc.net\nartbeijing.net\nartimg.net\nartintern.net\nartmotions.net\nartoto.net\nartron.net\narttz.net\nautoobserver.net\nawotuan.net\naycw.net\nayqc.net\nayrc.net\nb2bvip.net\nbaigou.net\nbailinsi.net\nbaixing.net\nbaiy.net\nbanhuajia.net\nbaoman.net\nbaoye.net\nbashang.net\nbawu.net\nbbsls.net\nbcy.net\nbd365.net\nbdche.net\nbdinfo.net\nbdtm.net\nbeianchaxun.net\nbeifang.net\nbejoin.net\nbianji.net\nbianjibu.net\nbillwang.net\nbinzhou.net\nbj-binbin.net\nbjhytc.net\nbjiae.net\nbjlz.net\nbjmama.net\nbjmxw.net\nbjyzyz.net\nbjzj.net\nbmjob.net\nboilerinfo.net\nbokee.net\nbokon.net\nbook51.net\nbtjy.net\nbuger.net\nbuildjob.net\nbupu.net\nbushome.net\nbuxiugangban.net\nbwie.net\nbwlc.net\nbxrcw.net\nbxxh.net\nbyqsc.net\nbyzp.net\nbzcm.net\nbznj.net\nc-ps.net\nc114.net\ncaihao.net\ncaipuchina.net\ncarbang.net\ncbbn.net\ncbi360.net\ncc163.net\ncccbs.net\nccedin.net\nccen.net\nccfcc.net\nccgas.net\ncctb.net\ncd-auto.net\ncdcgames.net\ncdn-files.net\ncdqcw.net\ncdqss.net\ncdweekly.net\ncdyou.net\nce02.net\ncechem.net\ncementchina.net\ncfanclub.net\ncfedu.net\ncfej.net\ncffw.net\nchadianhua.net\nchangdedj.net\nchaoliu1.net\nchda.net\nchebiao.net\nchengdechina.net\nchenglou.net\nchetuanwang.net\ncheweixiu.net\nchexun.net\nchina-cba.net\nchina-changjiang.net\nchina-english.net\nchina-landscape.net\nchina-led.net\nchina-lottery.net\nchina-power.net\nchina-train.net\nchina95.net\nchina98.net\nchinaauto.net\nchinabinzhou.net\nchinachina.net\nchinacity.net\nchinack.net\nchinacloud.net\nchinaeea.net\nchinaefu.net\nchinaeic.net\nchinaeol.net\nchinafengji.net\nchinafpd.net\nchinagames.net\nchinagb.net\nchinahrd.net\nchinajoy.net\nchinamost.net\nchinamr.net\nchinanap.net\nchinapipe.net\nchinasage.net\nchinaschool.net\nchinaseed.net\nchinasfa.net\nchinashishi.net\nchinatextile.net\nchinauma.net\nchinaunix.net\nchinavalue.net\nchinawestnews.net\nchinawutong.net\nchinawznews.net\nchinayoung.net\nchinayzxx.net\nchinazg.net\nchint.net\nchnmus.net\nchubanzige.net\nchuncui.net\ncifco.net\ncio360.net\nciture.net\ncixiedu.net\ncjdby.net\ncjk3d.net\nclw8.net\ncmda.net\ncmzj.net\ncn.net\ncn2car.net\ncnbaowen.net\ncnbg.net\ncnbook.net\ncnbxfc.net\ncncgw.net\ncnchache.net\ncncn.net\ncncsj.net\ncndianlu.net\ncndiaosu.net\ncneln.net\ncneol.net\ncnfabric.net\ncnfirst.net\ncngdw.net\ncngrain.net\ncngsda.net\ncnhbsb.net\ncnhbw.net\ncnhengqi.net\ncnhm.net\ncnhuadong.net\ncnhyw.net\ncninfo.net\ncnjdz.net\ncnjnw.net\ncnjskc.net\ncnjyzb.net\ncnki.net\ncnkssb.net\ncnky.net\ncnlinfo.net\ncnmd.net\ncnmf.net\ncnmsw.net\ncnnb.net\ncnnyjx.net\ncnool.net\ncnpec.net\ncnphotos.net\ncnpsy.net\ncnqipei.net\ncnread.net\ncnshicai.net\ncnssh.net\ncnsyyq.net\ncnszw.net\ncntaotax.net\ncnwen.net\ncnwenshi.net\ncnworld.net\ncnxishui.net\ncnyw.net\ncnzhutan.net\ncnzz.net\ncodefans.net\ncodesky.net\ncomicfans.net\ncoolling.net\ncoolsc.net\ncopperhome.net\ncp3d.net\ncp520.net\ncpecc.net\ncphoto.net\ncpplay.net\ncqcp.net\ncqgj.net\ncqkjwx.net\ncqmama.net\ncqme.net\ncqnews.net\ncqqnb.net\ncqrc.net\ncqshebao.net\ncqwxnews.net\ncqxszx.net\ncqyc.net\ncsbaidu.net\ncsdn.net\ncsgia.net\ncsmama.net\ncsstoday.net\ncszlyy.net\nctdsb.net\nctiec.net\nctjy.net\nctma.net\ncttm.net\ncxedu.net\ncynee.net\ncyol.net\nczgs.net\nczinfo.net\nczonline.net\nczyts.net\nd1xz.net\nd9read.net\ndalian-gov.net\ndanzhoujob.net\ndaodongart.net\ndaomin.net\ndaoxila.net\ndbh123.net\ndd001.net\nddahr.net\nddjob.net\ndeemstone.net\ndehua.net\ndehuata.net\ndfysw.net\ndfzpw.net\ndgjy.net\ndgmama.net\ndhabc.net\ndheart.net\ndianmi.net\ndiaochapai.net\ndiaokeji.net\ndiaosujia.net\ndimeng.net\ndiscuz.net\nditiewang.net\ndiwei.net\ndj3721.net\ndjlsoft.net\ndljs.net\ndmjob.net\ndocin.net\ndongdao.net\ndongliaogov.net\ndongpeng.net\ndongpo.net\ndotodo.net\ndoubleclick.net\ndouguo.net\ndoyoo.net\ndqlyw.net\ndragon-guide.net\ndsjunshi.net\ndt123.net\ndtrcw.net\nduba.net\ndushe.net\ndv37.net\ndvbbs.net\ndwrh.net\ndyfc.net\ndylw.net\ndynong.net\ndyqez.net\ndyqjy.net\ndytt.net\ndz169.net\ndz19.net\ndzwork.net\ndzxw.net\neamn.net\neasyicon.net\nebadu.net\nec168.net\necgoo.net\nechache.net\necmao.net\necp888.net\necwan77.net\nedowning.net\nedudown.net\nehuanbao.net\neistudy.net\nejinshan.net\nemland.net\nemu999.net\nename.net\nenbar.net\neq-xz.net\nerpworld.net\nesilk.net\nex-cp.net\nexambook.net\nexbuy.net\nexzk.net\nf2cn.net\nface100.net\nfangce.net\nfangfa.net\nfangfang.net\nfangpei.net\nfastapi.net\nfcii.net\nfd365.net\nfdlt.net\nfecn.net\nfeigang.net\nfeijiu.net\nfeiwan.net\nfeng6.net\nfengj.net\nfengone.net\nfjfs.net\nfjjl.net\nfjlib.net\nfjlt.net\nfjlx.net\nfjmap.net\nfjmb.net\nfjsy.net\nfjtp.net\nfjtv.net\nfjwh.net\nfjxw.net\nfjyj.net\nflash8.net\nflashwing.net\nfm918.net\nfmq10.net\nfoodmate.net\nfoodvip.net\nfps365.net\nfqjob.net\nfreepcware.net\nfsjy.net\nftnews.net\nftutj.net\nfuturescn.net\nfuyangjob.net\nfx120.net\nfynews.net\nfzmama.net\nfzqsng.net\nfzzpw.net\ngame247.net\nganzhong.net\ngaoan.net\ngcimg.net\ngdcct.net\ngdcg.net\ngdcic.net\ngdscse.net\ngdsin.net\ngeekpark.net\ngelinlan.net\ngentags.net\ngg114.net\ngjgwy.net\ngl114.net\nglobalimporter.net\ngm178.net\ngmacsaic.net\ngmseb.net\ngod520.net\ngojiaju.net\ngomeart.net\ngoodacc.net\ngotozjj.net\ngouhuasuan.net\ngqsoso.net\ngrfy.net\ngt120.net\ngtags.net\ngtjg.net\ngtobal.net\nguimobile.net\nguohuajia.net\nguqu.net\ngusuan.net\ngxaas.net\ngxb2b.net\ngxcic.net\ngxipo.net\ngxjk.net\ngxmengshan.net\ngxphoto.net\ngxst.net\ngxsti.net\ngycc.net\ngyjob.net\ngyxww.net\ngz-travel.net\ngz007.net\ngzhstars.net\ngzjtzy.net\ngzstv.net\nhafcw.net\nhaha56.net\nhai126.net\nhaier.net\nhainan.net\nhainan0898.net\nhainanpc.net\nhairuolawyer.net\nhanhai.net\nhanjialan.net\nhao60.net\nhaocf.net\nhaofang.net\nhaoqu.net\nhaorencai.net\nhaotc.net\nhaoyingyong.net\nhaoyuwang.net\nhazp.net\nhb12369.net\nhbgrb.net\nhbnews.net\nhbpx.net\nhbrd.net\nhbsky58.net\nhbycw.net\nhbzj.net\nhdzc.net\nheacn.net\nheiguang.net\nhenau.net\nhfgdfz.net\nhgnc.net\nhhsq.net\nhifidiy.net\nhiyouth.net\nhk3318.net\nhkdq.net\nhkwb.net\nhledu.net\nhlj.net\nhlje.net\nhljgwy.net\nhlsports.net\nhm-3223.net\nhnbys.net\nhncic.net\nhncoop.net\nhner.net\nhnfz.net\nhngawj.net\nhngjj.net\nhnjkw.net\nhnkjonline.net\nhnltw.net\nhnlzw.net\nhnol.net\nhnpi.net\nhnskl.net\nhnw.net\nhomomo.net\nhongze.net\nhopebook.net\nhqew.net\nhqyj.net\nhrbtv.net\nhse365.net\nhtbenet.net\nhtcbbs.net\nhteacher.net\nhtexam.net\nhtwx.net\nhuantai.net\nhuaxiajiayuan.net\nhubeibbs.net\nhuedu.net\nhuichexiang.net\nhuiyitang.net\nhunanedu.net\nhunau.net\nhuoche.net\nhuochepiao.net\nhustonline.net\nhwit.net\nhx-my.net\nhxcdn.net\nhxck.net\nhxpxw.net\nhxsx.net\nhxzg.net\nhyk123.net\nhynews.net\nhyxw.net\nhzedu.net\nhzlib.net\nhzmama.net\nhzpzs.net\nhztarena.net\nicgoo.net\nichacha.net\nicycn.net\niejob.net\nifasion.net\nihaveu.net\nihuikou.net\niincn.net\nijinbu.net\nilighting.net\nilinyi.net\nimg168.net\nimgshao123.net\nimp3.net\nimportfood.net\nindexedu.net\ninhe.net\ninmes.net\nirs01.net\nishang.net\nitcpn.net\nitiexue.net\nitpub.net\nitsogo.net\nitunion.net\nivcode.net\niwms.net\nixbren.net\nixpub.net\nixxss.net\nja168.net\njb51.net\njbedu.net\njc88.net\njcjy.net\njctrans.net\njdedu.net\njdzol.net\njemcc.net\njfjmw.net\njhjyj.net\njhtong.net\njhxww.net\njiadinglife.net\njiajushichang.net\njiangsuedu.net\njianke.net\njianzhiba.net\njianzhujia.net\njiaodong.net\njiaoshizhaopin.net\njiaoshui.net\njibi.net\njichuang.net\njieyue.net\njinduoduo.net\njinghou.net\njingnei.net\njinrongren.net\njinshuju.net\njishigou.net\njius.net\njiusi.net\njiyili.net\njjlg.net\njjwxc.net\njjyf.net\njk520.net\njkimg.net\njlqf.net\njlstnet.net\njltiet.net\njob0575.net\njobinhe.net\njqcn.net\njrjob.net\njsche.net\njsgx.net\njsinfo.net\njsqq.net\njsrencai.net\njszzc.net\njtyx.net\njuexing.net\njulu.net\njupai.net\njwedit.net\njxagri.net\njxjj.net\njxjjw.net\njxjsxx.net\njxjw.net\njxqx.net\njxzpw.net\njy163.net\njy1898.net\njynews.net\njyrcw.net\njyrw.net\njzcn.net\njzrc.net\nk666.net\nkandongman.net\nkanghu.net\nkantao.net\nkaoben.net\nkaocool.net\nkaoshijie.net\nkdnet.net\nkejet.net\nkfsy.net\nkhgd.net\nkimiss.net\nkjpt.net\nkmcz.net\nkmeb.net\nkmzj.net\nkofbobo.net\nks56.net\nksldesign.net\nksyx.net\nkuaijishi.net\nkuaitv.net\nkuakao.net\nkugz.net\nla-bbs.net\nlabbase.net\nlameng.net\nlampbrother.net\nlaohe360.net\nlaohuangli.net\nlarcw.net\nlc123.net\nlczb.net\nledanji.net\nledche.net\nlenosoft.net\nletian.net\nlftour.net\nlh168.net\nlhjy.net\nli63.net\nliangchan.net\nlianzhuang.net\nliaoyangwater.net\nlicang.net\nlilv8.net\nlingb.net\nlingnan.net\nliuxue51.net\nliveuc.net\nlizhi123.net\nljia.net\nljzc.net\nlkong.net\nlmjx.net\nlnast.net\nlngsm.net\nlnok.net\nlofficielchina.net\nlogo123.net\nlogo2008.net\nlongcity.net\nlonghoo.net\nlongjiang.net\nlongyin.net\nlonlife.net\nlotour.net\nlouti.net\nlpnews.net\nls520.net\nlsjyw.net\nlsnews.net\nlssx.net\nlstjj.net\nltcdn.net\nltesting.net\nluckyair.net\nluckyxp.net\nluohuedu.net\nlvguo.net\nlwjy.net\nlwnews.net\nlxyk.net\nlxzc.net\nlyg01.net\nlygjg.net\nlygrc.net\nlyjob.net\nlylxs.net\nlyqj.net\nlyrce.net\nlywj.net\nlywww.net\nlyyz.net\nlz520.net\nlzedu.net\nlzgd.net\nlzqss.net\nlzrc.net\nlzsq.net\nma4.net\nmafengwo.net\nmahoupao.net\nmakepolo.net\nmallchina.net\nmandarinmorning.net\nmaoren8.net\nmaquan.net\nmbaun.net\nmedrc.net\nmeilishuo.net\nmeishij.net\nmeishuwang.net\nmeituan.net\nmgbm.net\nmian4.net\nmingyihui.net\nminjianyishu.net\nmissyuan.net\nmjcl.net\nmllj.net\nmm111.net\nmmhn.net\nmmxq.net\nmnrb.net\nmouldfair.net\nmshw.net\nmsxf.net\nmusestudio.net\nmvxz.net\nmwrf.net\nmxwz.net\nmy0575.net\nmybjx.net\nmycar168.net\nmycollect.net\nmydns114.net\nmyhostadmin.net\nmyjob123.net\nmypm.net\nmyrb.net\nmysteel.net\nmz6.net\nname321.net\nnanrenwo.net\nnanrenzhuang.net\nnb7000.net\nnbcredit.net\nnbgj.net\nnbip.net\nnbks.net\nnbol.net\nnbow.net\nnbptweb.net\nncvt.net\nnengyuan.net\nnet-eye.net\nnetat.net\nnewasp.net\nnewsmth.net\nnewyx.net\nng114.net\nngocn.net\nniubb.net\nnj110.net\nnjtarena.net\nnnnews.net\nnongli.net\nnongyezhan.net\nnowamagic.net\nnp163.net\nnphoto.net\nntjy.net\nntxx.net\nnxnews.net\nnxng.net\nnxskl.net\nnxzwnews.net\nnyedu.net\nnyist.net\nnz99.net\nob1000.net\nofficecd.net\noilchem.net\nokhan.net\nokhere.net\nonebuild.net\nonegreen.net\nonfun.net\nonlinedown.net\nonlyonly.net\nonlyred.net\nopbbs.net\noralcollege.net\norgnitu.net\noschina.net\nourseo.net\np5w.net\npadh.net\npafj.net\npagechoice.net\npaixie.net\npaizihao.net\npamss.net\npaopaoche.net\npaperrater.net\npc360.net\npcdown.net\npch-img.net\npchome.net\npcomic.net\npcrcw.net\npczp.net\npdxx.net\npeixun.net\nperyi.net\nphp168.net\nphpstat.net\nphpwind.net\npipaw.net\npjob.net\npkedu.net\nplaaf.net\npm168.net\npobaby.net\npolyv.net\npopub.net\npost183.net\npowereasy.net\npowerpigs.net\nppt123.net\npptstore.net\nppys.net\nprechina.net\nproperty-bid.net\nps123.net\npthl.net\npxems.net\npyinfo.net\npyrc.net\npzzc.net\nqctl.net\nqcyf.net\nqdedu.net\nqdhr.net\nqdmama.net\nqdmw.net\nqfyf.net\nqgnews.net\nqgny.net\nqgyyzs.net\nqihuokaihu.net\nqikao.net\nqinb.net\nqincai.net\nqingdou.net\nqinghe8.net\nqixid.net\nqj99.net\nqjhm.net\nqjkc.net\nqkzxw.net\nqlcars.net\nqp365.net\nqq-online.net\nqs56.net\nqszpw.net\nqtimg.net\nquanjiamei.net\nqwqt.net\nqxyc.net\nqyoy.net\nqysxy.net\nqz828.net\nqzedu.net\nqzjw.net\nqzkj.net\nqztour.net\nqzxxg.net\nqzzpw.net\nrailcn.net\nraoke.net\nrar8.net\nrayhoo.net\nrcpx.net\nrencai.net\nreplays.net\nreyoo.net\nrhrl.net\nroadexam.net\nromzhijia.net\nrqbx.net\nrrting.net\nrrxk.net\nrspx.net\nruanman.net\nrushu.net\nrz169.net\nrzinfo.net\nsandai.net\nsanwen.net\nsarft.net\nsbrj.net\nsc-overseasinfo.net\nscdxs.net\nsceci.net\nscedu.net\nscgc.net\nscgis.net\nscxsj.net\nsdcw.net\nsdinfo.net\nsdtyjixie.net\nseecmedia.net\nseosrx.net\nsepu.net\nsg91.net\nsgqcw.net\nshangc.net\nshanghaimuseum.net\nshanghaitour.net\nshaoyangnews.net\nshejiguan.net\nshengyijie.net\nsherc.net\nshfuyu.net\nshmama.net\nshopin.net\nshopqc.net\nshouyouzhijia.net\nshowbb.net\nshuaji.net\nshuajizhijia.net\nshuangcheng.net\nshuanghui.net\nshuhuacun.net\nshuiwushi.net\nshuoping.net\nshuoshuodaquan.net\nshxb.net\nshynws.net\nshyouth.net\nshzfzz.net\nshzh.net\nsilversand.net\nsina.net\nsingcere.net\nsino-web.net\nsinodtv.net\nsinoec.net\nsinofarm.net\nsinoss.net\nsiteloop.net\nsjqw.net\nsjyzc.net\nsjzdd.net\nskybig.net\nsmchangan.net\nsms9.net\nsmxrcw.net\nsofthy.net\nsoftxp.net\nsohu.net\nsolarf.net\nsongshuhui.net\nsoo56.net\nsosg.net\nsosol.net\nsosoo.net\nsosw.net\nsoubao.net\nspforum.net\nsqcar.net\nsqjg.net\nsqtv.net\nssart.net\nsshscom.net\nssnn.net\nssxf.net\nssxw.net\nstedu.net\nstre.net\nsuerda.net\nsugarinfo.net\nsuixinews.net\nsumiao.net\nsunkf.net\nsuperarmy.net\nswsm.net\nsxcm.net\nsxcnw.net\nsxinfo.net\nsxlottery.net\nsxlove.net\nsxny.net\nsxqx.net\nsxsedu.net\nsxxcy.net\nsxxw.net\nsxzj.net\nsycu.net\nsyhr.net\nsynedu.net\nsyogame.net\nsyqcw.net\nsyrcw.net\nsyszyl.net\nsyuan.net\nsz100.net\nsz1001.net\nsz1w.net\nszcj.net\nszeat.net\nszedu.net\nszmama.net\nsznewworld.net\nszol.net\nszonline.net\nszsti.net\nsztaoche.net\nszykj.net\nt56.net\ntainfo.net\ntangrenju.net\ntaobao.net\ntax-edu.net\ntb888.net\ntbkf.net\ntcl37.net\ntczp.net\ntech110.net\ntengfang.net\ntexrc.net\ntfauto.net\ntffood.net\ntfrl.net\ntfyou.net\nthhome.net\ntianqizhubo.net\ntianxiazhi.net\ntianya.net\ntianya168.net\ntibetculture.net\ntibetmagazine.net\ntiexue.net\ntingclass.net\ntingyuxuan.net\ntirechina.net\ntjwang.net\ntlfw.net\ntlhr.net\ntmcdn.net\ntmtbib.net\ntobaccochina.net\ntobosu.net\ntongxiang.net\ntop17.net\ntopcfo.net\ntoppk.net\ntourjob.net\ntripc.net\ntszlx.net\ntt65.net\nttacc.net\nttszy.net\ntttuangou.net\nttxuexi.net\ntuan800.net\ntuiq.net\ntulaomao.net\ntuojin.net\ntuoliji.net\ntuoxian.net\ntvapk.net\ntxzpw.net\ntyguomiao.net\ntyzn.net\ntz-rc.net\ntz55.net\ntzgjj.net\ntzhcz.net\ntzinfo.net\ntzks.net\nu148.net\nu1city.net\nu520.net\nucdrs.net\nufstone.net\nujiao.net\nuker.net\numivi.net\nusaedu.net\nuutrip.net\nv007.net\nvbooking.net\nvi21.net\nvicp.net\nwadongxi.net\nwaihuigu.net\nwangxiao.net\nwanhutong.net\nwanshouyou.net\nwanyiwang.net\nwanzui.net\nwaterculture.net\nwdjl.net\nwdphoto.net\nwdqh.net\nwebshu.net\nwed020.net\nweigi.net\nweihz.net\nweilai.net\nweiot.net\nweiphone.net\nweizhang.net\nweste.net\nwgszq.net\nwhedu.net\nwhgjj.net\nwhir.net\nwhjy.net\nwhjzw.net\nwhlawyer.net\nwhpx.net\nwhqss.net\nwhzhaopin.net\nwindhr.net\nwjjob.net\nwlgd.net\nwmtp.net\nwoitea.net\nwoja.net\nwokaw.net\nwopeng.net\nworldmr.net\nwowody.net\nwpeu.net\nwrsa.net\nwshoes.net\nwto168.net\nwuca.net\nwufun.net\nwx920.net\nwzdsb.net\nwzer.net\nwzfx.net\nwzhan.net\nwzrc.net\nwzsky.net\nxamama.net\nxarc.net\nxb124.net\nxbsh.net\nxcqc.net\nxcs168.net\nxczpw.net\nxdcdn.net\nxdedu.net\nxdkb.net\nxeeee.net\nxfsljk.net\nxhby.net\nxiangdang.net\nxiangyang.net\nxiaojiulou.net\nxiaomayi.net\nxiaomi.net\nxiaotongxing.net\nxichu.net\nxici.net\nxihawan8.net\nxiusheji.net\nxiziwang.net\nxjaas.net\nxjauto.net\nxjtour.net\nxmlib.net\nxpsy.net\nxrecovery.net\nxsjk.net\nxsmp.net\nxtauto.net\nxthg.net\nxtjob.net\nxtrc.net\nxtwj.net\nxue.net\nxuyi365.net\nxwcm.net\nxwhb.net\nxxsd.net\nxxsy.net\nxyimg.net\nxyrc.net\nxz5u.net\nxzjob.net\nxzsw.net\nxzzp.net\nyanmo.net\nyaofangwang.net\nyaoxie.net\nybmz.net\nycbbs.net\nycfang.net\nycgjj.net\nydpsz.net\nyeah.net\nyesnb.net\nyetu.net\nyhfd.net\nyhqh.net\nyhtzx.net\nyiliaozhan.net\nyingqian.net\nyinhang123.net\nyirong.net\nyjbbs.net\nylmf.net\nylqxs.net\nylsw.net\nylxw.net\nynbz.net\nynedu.net\nynhl.net\nynkcw.net\nynradio.net\nynzpw.net\nyodak.net\nyofond.net\nyooan.net\nyopin.net\nyoucha.net\nyoudaili.net\nyoulu.net\nyouquba.net\nyouxi5.net\nyouxiake.net\nyouxihezi.net\nyp360.net\nyqfcw.net\nyqpt.net\nyshc.net\nytcnc.net\nyuantengfei.net\nyueduge.net\nyule360.net\nyuntaishan.net\nyuwenba.net\nyuzhou.net\nywec.net\nywexpo.net\nyxjiaoyu.net\nyxzp.net\nyy21.net\nyy99.net\nyyfdc.net\nyyly.net\nyyzs.net\nyzedu.net\nyzfcjy.net\nyzrsrc.net\nyzsc.net\nyzwb.net\nyzwh.net\nz888.net\nzauu.net\nzb2b.net\nzbedu.net\nzbgl.net\nzbinfo.net\nzblz.net\nzbnews.net\nzcbgxx.net\nzcgd.net\nzdic.net\nzei6.net\nzgdkj.net\nzgfxnews.net\nzggzn.net\nzgjhjy.net\nzgmt.net\nzgnt.net\nzgnykj.net\nzgrb.net\nzgsee.net\nzgthj.net\nzgys.net\nzgzzs.net\nzhangjiang.net\nzhanzhang.net\nzhaobiaoshi.net\nzhaofangtong.net\nzhaokao.net\nzhaoshang.net\nzhaoxi.net\nzhige.net\nzhixiangji.net\nzhiyehushi.net\nzhizaoye.net\nzhjy.net\nzhmmw.net\nzhnews.net\nzhong-yao.net\nzhongjiao.net\nzhongshantong.net\nzhongsou.net\nzhsti.net\nzhunbaba.net\nzhushouwang.net\nzhxww.net\nzhyw.net\nzibo.net\nzikaos.net\nziuziu.net\nzixuekaoshi.net\nzjgjj.net\nzjinvest.net\nzjk169.net\nzjks.net\nzjnw.net\nzjwu.net\nzjzj.net\nzjzs.net\nzkzsb.net\nzljob.net\nzmdzs.net\nzoglo.net\nzongsifang.net\nzoosnet.net\nzoossoft.net\nzq8.net\nzsedu.net\nzslib.net\nzsrc.net\nzsrd.net\nzstj.net\nzswoman.net\nzsxd.net\nzsyfzy.net\nzszxbj.net\nztsfc.net\nztv-8.net\nzuijh.net\nzwzsh.net\nzxjsq.net\nzybb.net\nzyrc.net\nzyscw.net\nzzmama.net\nzzrc.net\n0513.org\n0739fdc.org\n1000plan.org\n100che.org\n1139.org\n11wang.org\n1203.org\n18xiang.org\n1zhao.org\n21gold.org\n21js.org\n21sb.org\n21sq.org\n315sc.org\n3322.org\n3g-edu.org\n4thmedia.org\n50bang.org\n518baidu.org\n51cma.org\n51honest.org\n51lunwen.org\n52114.org\n56beijing.org\n5i81.org\n5icool.org\n8800.org\n8855.org\n8hy.org\n8ke.org\n8lw.org\n91lx.org\n96399.org\n96785.org\n99oushi.org\nacfechina.org\nacftu.org\nahnews.org\nambafrance-cn.org\namchamchina.org\nankang06.org\nanquan.org\nantong.org\napec-ecba.org\naplmf.org\napp111.org\naqbz.org\naqzbcg.org\nasean-china-center.org\nautohr.org\nbaijiajiangtan.org\nbaiquean.org\nbaiteng.org\nbanyuetan.org\nbaowenxiehui.org\nbczgx.org\nbeidaqingniao.org\nbiaoyu.org\nbj148.org\nbj315.org\nbjcdc.org\nbjcsyg.org\nbjfyw.org\nbjjubao.org\nbjpts.org\nbjtuxyqyj.org\nbjzgh.org\nbmippa.org\nbtv.org\nbublue.org\nbznews.org\nca-sme.org\ncaeexpo.org\ncaexpo.org\ncaiep.org\ncangchu.org\nccade.org\nccpit.org\nccpit-henan.org\nccpitbj.org\nccpitbm.org\nccpitgs.org\nccpitjinan.org\nccpitjs.org\nccpitnb.org\nccpitqd.org\nccpitxiamen.org\ncdyjs.org\nceiaec.org\nceiec.org\ncementtech.org\ncerambath.org\ncfachina.org\ncfbchina.org\ncfsdc.org\nchahua.org\ncheaa.org\nchina-consulate.org\nchina-cotton.org\nchina-embassy.org\nchina10.org\nchinaasc.org\nchinacampus.org\nchinacct.org\nchinacehui.org\nchinacg.org\nchinachild.org\nchinacitywater.org\nchinacno.org\nchinacourt.org\nchinacraa.org\nchinacses.org\nchinaculture.org\nchinadmoz.org\nchinadriver.org\nchinaeda.org\nchinafairs.org\nchinagwyw.org\nchinaielts.org\nchinairr.org\nchinakongzi.org\nchinaleather.org\nchinamining-expo.org\nchinanotary.org\nchinaparking.org\nchinapm.org\nchinaprint.org\nchinaql.org\nchinaskills.org\nchinastor.org\nchinasus.org\nchinataiwan.org\nchinatimber.org\nchinatruck.org\nchinaumu.org\nchinawin.org\nchinazy.org\nchinca.org\nchineseconsulate.org\nchineseembassy.org\nchnbook.org\ncicheng.org\nciftis.org\ncityup.org\ncjfj.org\ncltt.org\ncms1924.org\ncn-ny.org\ncn12365.org\ncnbrand.org\ncncgw.org\ncncma.org\ncncnc.org\ncnenergy.org\ncnern.org\ncnfxj.org\ncngold.org\ncnhcg.org\ncnips.org\ncnispunion.org\ncnky.org\ncnlist.org\ncnqr.org\ncnsb.org\ncnxk.org\ncocos2d-x.org\ncomra.org\ncottonchina.org\ncpaedu.org\ncphoto.org\ncpifa.org\ncq315.org\ncqgh.org\ncqhc.org\ncqsy.org\ncqzx.org\ncsacc.org\ncscdf.org\ncufeyk.org\ncwen.org\ncweun.org\ncwun.org\ncxwz.org\ncyedu.org\nczlawyer.org\ndabiaoji.org\ndajiangsai.org\nddfddf.org\ndifangzhi.org\ndl-hr.org\ndongliao.org\ndtjy.org\ne-bices.org\neccpitbj.org\neccsp.org\necnia.org\nedry.org\neguilin.org\nembedu.org\nenvinnovators.org\nershouyi.org\nexam66.org\nextmail.org\nfcpachina.org\nfercc.org\nfhfcw.org\nfjcyl.org\nfjgs.org\nfjkx.org\nfjsdfz.org\nfjsq.org\nfjwh.org\nfodian.org\nfreescaleic.org\nfs315.org\nfzrc.org\nganchang.org\ngaoling.org\ngazx.org\ngdafxh.org\ngdagri.org\ngdgkw.org\ngdql.org\ngedu.org\ngelun.org\ngeren-jianli.org\ngieaa.org\ngjgwy.org\nglobalbook.org\ngming.org\ngreenfood.org\ngsean.org\ngteachers.org\nguigu.org\nguihuashi.org\ngx315.org\ngxftu.org\ngxjubao.org\ngxzs.org\ngyart.org\ngyxuan.org\ngzast.org\ngzlib.org\ngzredcross.org\nhainanredcross.org\nhainei.org\nhanguoyou.org\nhanzify.org\nhaopeixun.org\nhazpw.org\nhbcourt.org\nhbrchina.org\nhbredcross.org\nhbww.org\nhcsindex.org\nhdgch.org\nhebgcc.org\nhebgh.org\nhebredcross.org\nhenanredcross.org\nhengqian.org\nhepan.org\nhfib.org\nhljgh.org\nhljgsl.org\nhljys.org\nhlnmg.org\nhncourt.org\nhndpf.org\nhngcc.org\nhngh.org\nhngwy.org\nhnid.org\nhnql.org\nhnskl.org\nhnswtzb.org\nhnszgh.org\nhongfen.org\nhoseaworldwide.org\nhqeast.org\nhqfb.org\nhrcshp.org\nhscbbs.org\nhtml5cn.org\nhtzx.org\nhuigezi.org\nhumanrights-china.org\nhuocheshikebiao.org\nhxlt.org\nhynews.org\nhyxyw.org\nhzabl.org\nhzgh.org\nhztarena.org\ni0898.org\nibspecial.org\nicourse163.org\nidacn.org\ninfineon-power-rf.org\ninfineonic.org\ninterfranchise.org\nintsst.org\ninvestteda.org\nit-home.org\nitppi.org\njcnews.org\njianbihua.org\njiangshi.org\njiankang.org\njiansuji.org\njiaoshizige.org\njiaotou.org\njinandpf.org\njingjia.org\njingshu.org\njixiezhan.org\njjkk.org\njjsedu.org\njjxj.org\njl315.org\njl54.org\njljgdj.org\njlredcross.org\njlzf.org\njlzp.org\njnjpw.org\njsfxh.org\njsgh.org\njsls.org\njsnotary.org\njszf.org\njszsf.org\njxcq.org\njxtyzx.org\njzsedu.org\nkeywin.org\nklxuexi.org\nkmhouse.org\nkooke.org\nkouyu.org\nkudou.org\nkxchina.org\nlangxi.org\nlepingfoundation.org\nliaotuo.org\nlinecg.org\nliquan.org\nljjgdj.org\nlngb.org\nlnszgh.org\nlnwomen.org\nlsphoto.org\nlsrcw.org\nluliang.org\nlvsecn.org\nma-china.org\nmandaringarden.org\nmeixun.org\nmkaq.org\nmmscsw.org\nmobiletrain.org\nmwrfchina.org\nmyhm.org\nnamoc.org\nnanjing2014.org\nnaradafoundation.org\nnbcqjy.org\nnbcsbb.org\nnbgy.org\nncacg.org\nnctzb.org\nneiscn.org\nnewchannel.org\nneworiental.org\nneworiental-k12.org\nneworientalgroup.org\nnewssc.org\nnmgcoop.org\nnongjiayuan.org\nnssd.org\nnuli.org\noksat.org\nopenhw.org\nopfun.org\nourfreesky.org\novkj.org\noxbridgedu.org\npatachina.org\npdsjob.org\npeac-conf.org\nphvalue.org\nphxzzx.org\npigai.org\npinggu.org\npoyanglake.org\npsachina.org\npuresky.org\nqdepi.org\nqdsailing.org\nqhass.org\nqhcl.org\nqhfx.org\nqingdaochina.org\nqingdaoexpo2014.org\nqinglian.org\nqjjy.org\nqq2013.org\nqqmcc.org\nqqwangming.org\nqusu.org\nquyouxue.org\nqzpc.org\nrachina.org\nrczp.org\nredcross-sha.org\nreformdata.org\nreportway.org\nrfidchina.org\nrrhjz.org\nsae-china.org\nsaict.org\nscgh.org\nsclf.org\nscu-edu.org\nscwmw.org\nsdas.org\nsfcdn.org\nsgfy.org\nshanghaiconcerthall.org\nshechuang.org\nshidi.org\nshodr.org\nshowchina.org\nshtour.org\nshufa.org\nshuoshuodaquan.org\nshusongji.org\nshuzixiaoyuan.org\nshwomen.org\nshxgh.org\nshxsy.org\nshzgd.org\nshzgh.org\nshzq.org\nsiliconchina.org\nsiling.org\nslkj.org\nslyy.org\nsolidot.org\nsqzx.org\nssjy.org\nstaticfile.org\nsungoal.org\nsunwy.org\nsunyat-sen.org\nsxjx.org\nsysu-edu.org\nsz2011.org\nszbbs.org\nszfw.org\nszlottery.org\nszsolar.org\nszsta.org\nsztalent.org\nszzgh.org\ntaaas.org\ntaisha.org\nthxy.org\ntianhan.org\ntielu.org\ntjredcross.org\ntoefl-edu.org\ntopenergy.org\ntrustutn.org\ntui8.org\ntuozhanzhe.org\ntzcdc.org\ntzedu.org\ntzsf.org\nu1000.org\nveryen.org\nvnexpo.org\nw3.org\nwanjia.org\nweijiu.org\nweinan.org\nwenyue.org\nwesternchinafair.org\nwhgh.org\nwhgyw.org\nwhsy.org\nwmgm.org\nwqby.org\nws8.org\nwwfchina.org\nwwwcn.org\nwx6.org\nwxlongre.org\nwxsme.org\nxdth.org\nxf12356.org\nxfzx.org\nxhd.org\nxiaochang.org\nxiaoxiaotong.org\nxiaozhan.org\nxinhua.org\nxinkb.org\nxinzhou.org\nxippe.org\nxisuedu.org\nxjedu.org\nxjlib.org\nxmccc.org\nxmim.org\nxmzgh.org\nxtfj.org\nxuancheng.org\nxuanfang.org\nxueyiwang.org\nxzass.org\nyctzw.org\nyczjda.org\nyeluedu.org\nyezhuwang.org\nyiedu.org\nyjsjl.org\nyoucheng.org\nysedu.org\nysnews.org\nyuqingtong.org\nyygsl.org\nyykx.org\nyylm.org\nyyxh.org\nyzcl.org\nzaoyang.org\nzaxsw.org\nzbyz.org\nzgc-bigdata.org\nzget.org\nzgghw.org\nzgjm.org\nzgjzy.org\nzgnmg.org\nzgshjy.org\nzhaopinhui.org\nzhibo8.org\nzhifujing.org\nzhnc.org\nzhzyw.org\nzj315.org\nzjchina.org\nzjdh.org\nzjedu.org\nzjftu.org\nzjjys.org\nzjlsedu.org\nzjmj.org\nzjphoto.org\nzjscedu.org\nzlzx.org\nzmyg.org\nzoomeye.org\nzpedu.org\nzpxzzx.org\nzqgongyi.org\nzsfuer.org\nzsql.org\nzsyxw.org\nzugou.org\nzwbk.org\nzx110.org\nzyxuan.org\nzzbm.org\nzzbs.org\nsge.sh\n0471.so\nccp.so\ndongtai.so\nhaorenyuan.so\nhcw.so\nledao.so\nlishang.so\nnoni.so\nqingsong.so\nsmm.so\nsoutudi.so\ntuu.so\nwangxiao.so\nyongcheng.so\nstone.tm\nwe.tm\nputuoshan.travel\n005.tv\n0438.tv\n0515yc.tv\n0916.tv\n1006.tv\n1189.tv\n1288.tv\n1588.tv\n1819.tv\n1866.tv\n1988.tv\n19888.tv\n2588.tv\n3328.tv\n3456.tv\n5588.tv\n5666.tv\n5888.tv\n59277.tv\n5999.tv\n666888.tv\n7666.tv\n7999.tv\n8090.tv\n9111.tv\n9928.tv\n9998.tv\nacfun.tv\nacg.tv\nahsz.tv\nbeiwo.tv\nbilibili.tv\nboyin.tv\nccin.tv\ncditv.tv\nchinaacc.tv\nchinaielts.tv\nciehi.tv\ncnacc.tv\ncnsb.tv\ncztv.tv\ndd13.tv\ndengzhou.tv\ndocuchina.tv\ndydh.tv\ndztv.tv\nefang.tv\nfun.tv\ngamehome.tv\ngntv.tv\ngreenchina.tv\nhao315.tv\nhejia.tv\nhntv.tv\nhoolo.tv\nhuaihai.tv\nhznet.tv\nicntv.tv\nimgo.tv\njinshi.tv\njiyou.tv\njnnews.tv\nkaku.tv\nliaozhai.tv\nlunan.tv\nlztv.tv\nmiomio.tv\nocar.tv\nok123.tv\npeopleart.tv\npps.tv\nscnj.tv\nshenqing.tv\nsosol.tv\ntangxia.tv\ntttv.tv\nwasu.tv\nweihai.tv\nwmwz.tv\nxiaoxiang.tv\nxigo.tv\nxntv.tv\nxwei.tv\nyatu.tv\nyouni.tv\nyoyi.tv\nyy.tv\nzb580.tv\nzhanqi.tv\nzhufu.tv\nzjedu.tv\nzjmc.tv\nzohi.tv\nzztv.tv\nhexun.com.tw\nyuelian.com.tw\ntaiwandao.tw\nshijihao.wang\nzx580.wang\nchinese-embassy.org.za\n\"\"\"\n return set(liststr.splitlines(False))\n" }, { "alpha_fraction": 0.4704190492630005, "alphanum_fraction": 0.5688658952713013, "avg_line_length": 17.620378494262695, "blob_id": "e5c5114e1efbd66e44642a9f3e0cd916b3d038a1", "content_id": "ec064229753384c9e705fb834057db78a5d0a254", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 338985, "license_type": "permissive", "max_line_length": 47, "num_lines": 18205, "path": "/whitelist.pac", "repo_name": "yaehei/gfw_whitelist-1", "src_encoding": "UTF-8", "text": "var domains = {\n\t\"0-100s.com\": 1,\n\t\"0-6.com\": 1,\n\t\"0001688.com\": 1,\n\t\"0001k.com\": 1,\n\t\"0001wan.com\": 1,\n\t\"00042.com\": 1,\n\t\"000dn.com\": 1,\n\t\"001ce.com\": 1,\n\t\"001cndc.com\": 1,\n\t\"001en.com\": 1,\n\t\"001hr.com\": 1,\n\t\"001job.com\": 1,\n\t\"001pp.com\": 1,\n\t\"001sj.net\": 1,\n\t\"001sxy.com\": 1,\n\t\"001zhe.com\": 1,\n\t\"003job.com\": 1,\n\t\"005.tv\": 1,\n\t\"00615.net\": 1,\n\t\"007258.com\": 1,\n\t\"007dp.com\": 1,\n\t\"007swz.com\": 1,\n\t\"007yx.com\": 1,\n\t\"008wan.com\": 1,\n\t\"009hr.com\": 1,\n\t\"010.cc\": 1,\n\t\"010bjzs.com\": 1,\n\t\"010hr.com\": 1,\n\t\"010jiaoshi.com\": 1,\n\t\"010lf.com\": 1,\n\t\"010lyzg.com\": 1,\n\t\"010zihua.com\": 1,\n\t\"011job.com\": 1,\n\t\"01hr.com\": 1,\n\t\"01teacher.com\": 1,\n\t\"01yo.com\": 1,\n\t\"020.com\": 1,\n\t\"020h.com\": 1,\n\t\"020job.com\": 1,\n\t\"020k.com\": 1,\n\t\"0214.com\": 1,\n\t\"021766.net\": 1,\n\t\"021cai.com\": 1,\n\t\"021shangyuan.net\": 1,\n\t\"021wy.com\": 1,\n\t\"022ee.com\": 1,\n\t\"022net.com\": 1,\n\t\"022sy.com\": 1,\n\t\"022v.com\": 1,\n\t\"0233.com\": 1,\n\t\"02342.com\": 1,\n\t\"023aq.com\": 1,\n\t\"023v.com\": 1,\n\t\"023yts.com\": 1,\n\t\"023zjj.com\": 1,\n\t\"023zp.com\": 1,\n\t\"024zol.com\": 1,\n\t\"024zxw.com\": 1,\n\t\"025.com\": 1,\n\t\"025ct.com\": 1,\n\t\"025kd.com\": 1,\n\t\"025syedu.com\": 1,\n\t\"025xl.com\": 1,\n\t\"025zp.com\": 1,\n\t\"025zph.com\": 1,\n\t\"0261.net\": 1,\n\t\"027.net\": 1,\n\t\"02751766.com\": 1,\n\t\"027art.com\": 1,\n\t\"027deru.com\": 1,\n\t\"027hpedu.com\": 1,\n\t\"027hpit.com\": 1,\n\t\"028-56.com\": 1,\n\t\"028668.com\": 1,\n\t\"028aide.com\": 1,\n\t\"028cbd.com\": 1,\n\t\"028ccx.com\": 1,\n\t\"028f.com\": 1,\n\t\"028gcw.com\": 1,\n\t\"028jiajiao.com\": 1,\n\t\"028kj.com\": 1,\n\t\"028office.com\": 1,\n\t\"028sp.com\": 1,\n\t\"028town.com\": 1,\n\t\"029-88810000.com\": 1,\n\t\"029558.com\": 1,\n\t\"029k.com\": 1,\n\t\"029yoyo.com\": 1,\n\t\"029zp.com\": 1,\n\t\"02edu.com\": 1,\n\t\"02yc.com\": 1,\n\t\"031086.com\": 1,\n\t\"0311.cc\": 1,\n\t\"0312zp.net\": 1,\n\t\"0314job.com\": 1,\n\t\"0316fdc.com\": 1,\n\t\"031924.com\": 1,\n\t\"031rc.com\": 1,\n\t\"0335qc.com\": 1,\n\t\"0335travel.com\": 1,\n\t\"0350tv.com\": 1,\n\t\"035166.com\": 1,\n\t\"0352fang.com\": 1,\n\t\"0355wxr.com\": 1,\n\t\"0356.com\": 1,\n\t\"0356f.com\": 1,\n\t\"0357hz.com\": 1,\n\t\"0358lvl.com\": 1,\n\t\"0359fdc.com\": 1,\n\t\"0359rencai.com\": 1,\n\t\"0359tv.com\": 1,\n\t\"0370home.com\": 1,\n\t\"0370zp.com\": 1,\n\t\"0371job.com\": 1,\n\t\"0371www.com\": 1,\n\t\"0371zm.com\": 1,\n\t\"0372job.com\": 1,\n\t\"0373job.com\": 1,\n\t\"0375jk.com\": 1,\n\t\"0376.net\": 1,\n\t\"0377auto.com\": 1,\n\t\"0377jobs.com\": 1,\n\t\"0378job.com\": 1,\n\t\"0379house.com\": 1,\n\t\"0379jk.com\": 1,\n\t\"037g.com\": 1,\n\t\"0384.com\": 1,\n\t\"0391job.com\": 1,\n\t\"0392job.com\": 1,\n\t\"0393fcw.com\": 1,\n\t\"0393job.com\": 1,\n\t\"0396e.com\": 1,\n\t\"0398job.com\": 1,\n\t\"03th.com\": 1,\n\t\"0411921.com\": 1,\n\t\"0411hd.com\": 1,\n\t\"0417u.com\": 1,\n\t\"0418hr.com\": 1,\n\t\"0419car.com\": 1,\n\t\"0427qcw.com\": 1,\n\t\"0431jia.com\": 1,\n\t\"0434w.com\": 1,\n\t\"0438.tv\": 1,\n\t\"0438news.com\": 1,\n\t\"0452e.com\": 1,\n\t\"0452zhaopin.com\": 1,\n\t\"0454.com\": 1,\n\t\"0460.com\": 1,\n\t\"0464.cm\": 1,\n\t\"0471.so\": 1,\n\t\"0471fcw.com\": 1,\n\t\"0472.com\": 1,\n\t\"0510.com\": 1,\n\t\"051000.com\": 1,\n\t\"0510syedu.com\": 1,\n\t\"0510yx.com\": 1,\n\t\"0511qcw.com\": 1,\n\t\"0511y.com\": 1,\n\t\"051291.com\": 1,\n\t\"0512a.com\": 1,\n\t\"0512dz.com\": 1,\n\t\"0512rx.com\": 1,\n\t\"0512uu.com\": 1,\n\t\"0512yy.com\": 1,\n\t\"0512zp.com\": 1,\n\t\"0513.cc\": 1,\n\t\"0513.net\": 1,\n\t\"0513.org\": 1,\n\t\"0513info8.com\": 1,\n\t\"0513nttc.com\": 1,\n\t\"0513syedu.com\": 1,\n\t\"0514.com\": 1,\n\t\"0514dq.com\": 1,\n\t\"051591.com\": 1,\n\t\"0515auto.com\": 1,\n\t\"0515cw.com\": 1,\n\t\"0515yc.tv\": 1,\n\t\"051661.com\": 1,\n\t\"0516zpw.com\": 1,\n\t\"0517.net\": 1,\n\t\"0517cw.com\": 1,\n\t\"0517mall.com\": 1,\n\t\"0517offer.com\": 1,\n\t\"0517w.com\": 1,\n\t\"05188.com\": 1,\n\t\"0518cw.com\": 1,\n\t\"0518hj.com\": 1,\n\t\"0518rcw.com\": 1,\n\t\"0519.com\": 1,\n\t\"0519car.net\": 1,\n\t\"0519net.com\": 1,\n\t\"0519syedu.com\": 1,\n\t\"051jk.com\": 1,\n\t\"051wc.com\": 1,\n\t\"0523gg.com\": 1,\n\t\"0523tv.com\": 1,\n\t\"0523zp.com\": 1,\n\t\"0527c.com\": 1,\n\t\"0527car.com\": 1,\n\t\"0527city.com\": 1,\n\t\"0527lsw.com\": 1,\n\t\"0527tao.com\": 1,\n\t\"0527zp.com\": 1,\n\t\"0530fangchan.com\": 1,\n\t\"0531.com\": 1,\n\t\"0531wt.com\": 1,\n\t\"0532cate.com\": 1,\n\t\"0532hq.com\": 1,\n\t\"0532jiaozhou.com\": 1,\n\t\"0533.net\": 1,\n\t\"0534.com\": 1,\n\t\"0535-0411.com\": 1,\n\t\"0536home.com\": 1,\n\t\"0536qiche.com\": 1,\n\t\"0536qz.com\": 1,\n\t\"0537fc.net\": 1,\n\t\"0537qcw.com\": 1,\n\t\"0537yz.com\": 1,\n\t\"0537zp.com\": 1,\n\t\"0538fc.com\": 1,\n\t\"0538taian.com\": 1,\n\t\"0543bbs.com\": 1,\n\t\"0543fcw.com\": 1,\n\t\"0543house.com\": 1,\n\t\"0543hr.com\": 1,\n\t\"0543jobs.com\": 1,\n\t\"0543sem.com\": 1,\n\t\"0543zxw.com\": 1,\n\t\"054400.com\": 1,\n\t\"0546fdc.com\": 1,\n\t\"0550cw.com\": 1,\n\t\"0550qcw.com\": 1,\n\t\"055178.com\": 1,\n\t\"0551fangchan.com\": 1,\n\t\"0551ren.com\": 1,\n\t\"0551up.com\": 1,\n\t\"0551zhuang.com\": 1,\n\t\"0552jie.com\": 1,\n\t\"0553qcw.com\": 1,\n\t\"0554coal.com\": 1,\n\t\"0554news.com\": 1,\n\t\"0554x.com\": 1,\n\t\"0554zp.com\": 1,\n\t\"0555cw.com\": 1,\n\t\"0555fc.com\": 1,\n\t\"0555qcw.com\": 1,\n\t\"0555rcw.com\": 1,\n\t\"0555yi.com\": 1,\n\t\"0557100.com\": 1,\n\t\"0557che.com\": 1,\n\t\"0558.com\": 1,\n\t\"0558t.com\": 1,\n\t\"0559fc.com\": 1,\n\t\"0561house.com\": 1,\n\t\"0561life.com\": 1,\n\t\"0562auto.com\": 1,\n\t\"0563job.com\": 1,\n\t\"0564abc.com\": 1,\n\t\"0564job.com\": 1,\n\t\"0564luan.com\": 1,\n\t\"0564shw.com\": 1,\n\t\"0565fc.com\": 1,\n\t\"0566car.com\": 1,\n\t\"0566cn.net\": 1,\n\t\"0566fc.cc\": 1,\n\t\"0566fc.com\": 1,\n\t\"0566fw.com\": 1,\n\t\"0566job.com\": 1,\n\t\"0567.com\": 1,\n\t\"0570.cc\": 1,\n\t\"05701234.com\": 1,\n\t\"057191.com\": 1,\n\t\"0571car.com\": 1,\n\t\"0571lkhs.com\": 1,\n\t\"0572gb.com\": 1,\n\t\"0572home.com\": 1,\n\t\"0573rcw.com\": 1,\n\t\"0573ren.com\": 1,\n\t\"0573syedu.com\": 1,\n\t\"0573zp.net\": 1,\n\t\"0574bbs.com\": 1,\n\t\"0574byedu.com\": 1,\n\t\"0574yye.com\": 1,\n\t\"0575.com\": 1,\n\t\"0575bbs.com\": 1,\n\t\"0575eshop.com\": 1,\n\t\"0575j.com\": 1,\n\t\"0575jzw.com\": 1,\n\t\"0575lt.com\": 1,\n\t\"0575rl.com\": 1,\n\t\"0576fang.com\": 1,\n\t\"0577home.net\": 1,\n\t\"0577hr.com\": 1,\n\t\"0577job.com\": 1,\n\t\"0577wzlf.com\": 1,\n\t\"0578rencai.com\": 1,\n\t\"0579818.com\": 1,\n\t\"0579com.com\": 1,\n\t\"0579fdc.com\": 1,\n\t\"057yx.com\": 1,\n\t\"0591job.com\": 1,\n\t\"05927.com\": 1,\n\t\"0593r.com\": 1,\n\t\"0594.com\": 1,\n\t\"0595rc.com\": 1,\n\t\"0596cs.com\": 1,\n\t\"0596fc.com\": 1,\n\t\"0596lh.com\": 1,\n\t\"0597.com\": 1,\n\t\"0597car.com\": 1,\n\t\"0597ok.com\": 1,\n\t\"0597yd.com\": 1,\n\t\"0598777.com\": 1,\n\t\"0598rc.com\": 1,\n\t\"0598yu.com\": 1,\n\t\"05job.com\": 1,\n\t\"05sun.com\": 1,\n\t\"05wan.com\": 1,\n\t\"05youxi.com\": 1,\n\t\"0600.com\": 1,\n\t\"063.com\": 1,\n\t\"0631rc.com\": 1,\n\t\"0634.com\": 1,\n\t\"0635jia.com\": 1,\n\t\"063yy.com\": 1,\n\t\"0663auto.com\": 1,\n\t\"0663job.com\": 1,\n\t\"0671.com\": 1,\n\t\"0685.com\": 1,\n\t\"06game.com\": 1,\n\t\"0701.com\": 1,\n\t\"07073.com\": 1,\n\t\"07073sy.com\": 1,\n\t\"0710.com\": 1,\n\t\"0710520.com\": 1,\n\t\"0710fz.com\": 1,\n\t\"0710hf.com\": 1,\n\t\"0710rcw.com\": 1,\n\t\"0710rencai.com\": 1,\n\t\"0712f.com\": 1,\n\t\"0712fang.com\": 1,\n\t\"0713hb.com\": 1,\n\t\"0713rcw.com\": 1,\n\t\"0714.com\": 1,\n\t\"0714job.com\": 1,\n\t\"0715fc.com\": 1,\n\t\"0716fw.com\": 1,\n\t\"0716jl.com\": 1,\n\t\"07177.com\": 1,\n\t\"0719house.com\": 1,\n\t\"0722fc.com\": 1,\n\t\"0722fw.com\": 1,\n\t\"0722h.com\": 1,\n\t\"0724tx.com\": 1,\n\t\"0725.com\": 1,\n\t\"0728f.com\": 1,\n\t\"0728h.com\": 1,\n\t\"0728i.com\": 1,\n\t\"0728zpw.com\": 1,\n\t\"073.cc\": 1,\n\t\"0730news.com\": 1,\n\t\"0730qc.com\": 1,\n\t\"0731520.com\": 1,\n\t\"0731esf.com\": 1,\n\t\"0731fdc.com\": 1,\n\t\"0731jiaju.com\": 1,\n\t\"0731job.com\": 1,\n\t\"0731tg.com\": 1,\n\t\"0732fc.com\": 1,\n\t\"0734.com\": 1,\n\t\"0734zpw.com\": 1,\n\t\"0735.com\": 1,\n\t\"07356.com\": 1,\n\t\"07358.com\": 1,\n\t\"0735jz.com\": 1,\n\t\"0736.com\": 1,\n\t\"0736fdc.com\": 1,\n\t\"0736house.com\": 1,\n\t\"0736rencai.com\": 1,\n\t\"0737job.com\": 1,\n\t\"0738fdc.com\": 1,\n\t\"0738fdc.net\": 1,\n\t\"0738ld.com\": 1,\n\t\"0738rc.com\": 1,\n\t\"0739bbs.com\": 1,\n\t\"0739fdc.org\": 1,\n\t\"0739fz.com\": 1,\n\t\"073img.com\": 1,\n\t\"073uu.com\": 1,\n\t\"073wan.com\": 1,\n\t\"073yx.com\": 1,\n\t\"0745job.com\": 1,\n\t\"0746yc.com\": 1,\n\t\"0750f.com\": 1,\n\t\"0750rc.com\": 1,\n\t\"0752qc.com\": 1,\n\t\"0754cars.com\": 1,\n\t\"0754ok.com\": 1,\n\t\"0755.net\": 1,\n\t\"0755bzf.com\": 1,\n\t\"0755car.com\": 1,\n\t\"0755cits.com\": 1,\n\t\"0755rc.com\": 1,\n\t\"0756zx.com\": 1,\n\t\"0757cfw.com\": 1,\n\t\"0757chongkong.com\": 1,\n\t\"0757fc.com\": 1,\n\t\"0757rc.com\": 1,\n\t\"0757zhaopin.com\": 1,\n\t\"0758fc.net\": 1,\n\t\"0759h.com\": 1,\n\t\"0759home.com\": 1,\n\t\"0759home.net\": 1,\n\t\"0759job.com\": 1,\n\t\"0759lt.com\": 1,\n\t\"0759u.com\": 1,\n\t\"0759zhiye.com\": 1,\n\t\"0760.com\": 1,\n\t\"0760js.com\": 1,\n\t\"0760jz.com\": 1,\n\t\"0760rc.com\": 1,\n\t\"076299.com\": 1,\n\t\"0762home.com\": 1,\n\t\"0762r.com\": 1,\n\t\"076999.com\": 1,\n\t\"0769auto.com\": 1,\n\t\"0769che.com\": 1,\n\t\"0769rc.com\": 1,\n\t\"0769xw.com\": 1,\n\t\"0771bc.com\": 1,\n\t\"0771ch.net\": 1,\n\t\"0771rc.com\": 1,\n\t\"0772fang.com\": 1,\n\t\"0772job.com\": 1,\n\t\"0773web.com\": 1,\n\t\"0774.cc\": 1,\n\t\"0775fcw.com\": 1,\n\t\"0775fw.com\": 1,\n\t\"0775jzw.com\": 1,\n\t\"0775qc.com\": 1,\n\t\"0776rc.com\": 1,\n\t\"0791abc.com\": 1,\n\t\"0791look.com\": 1,\n\t\"0791quanquan.com\": 1,\n\t\"0792c.com\": 1,\n\t\"0792job.com\": 1,\n\t\"0792rs.com\": 1,\n\t\"0793.com\": 1,\n\t\"0793p.com\": 1,\n\t\"0794work.com\": 1,\n\t\"0795gaoan.com\": 1,\n\t\"0795rc.com\": 1,\n\t\"0797live.net\": 1,\n\t\"0797rs.com\": 1,\n\t\"07jm.com\": 1,\n\t\"07ka.com\": 1,\n\t\"07ly.com\": 1,\n\t\"07ux.com\": 1,\n\t\"0817ch.com\": 1,\n\t\"0817f.com\": 1,\n\t\"0817rc.com\": 1,\n\t\"0818hr.com\": 1,\n\t\"0818jy.com\": 1,\n\t\"0818work.com\": 1,\n\t\"0824.com\": 1,\n\t\"0827.la\": 1,\n\t\"0830e.com\": 1,\n\t\"0830qc.com\": 1,\n\t\"0831che.com\": 1,\n\t\"0831home.com\": 1,\n\t\"0832h.com\": 1,\n\t\"0832mh.com\": 1,\n\t\"0838.com\": 1,\n\t\"0839fc.com\": 1,\n\t\"0839zp.com\": 1,\n\t\"0851gx.com\": 1,\n\t\"0852job.com\": 1,\n\t\"0852zpw.com\": 1,\n\t\"0853fdc.com\": 1,\n\t\"0853news.com\": 1,\n\t\"0853rc.com\": 1,\n\t\"0854job.com\": 1,\n\t\"0855job.com\": 1,\n\t\"0856job.com\": 1,\n\t\"0857job.com\": 1,\n\t\"0859job.com\": 1,\n\t\"0871job.net\": 1,\n\t\"0875job.net\": 1,\n\t\"0891job.net\": 1,\n\t\"0891zp.com\": 1,\n\t\"0898.net\": 1,\n\t\"0898cx.com\": 1,\n\t\"0898dichan.com\": 1,\n\t\"0898f.com\": 1,\n\t\"0898hn.net\": 1,\n\t\"0898hq.com\": 1,\n\t\"08cms.com\": 1,\n\t\"08fang.com\": 1,\n\t\"08px.com\": 1,\n\t\"08zfw.com\": 1,\n\t\"0902rc.com\": 1,\n\t\"0909wan.com\": 1,\n\t\"090job.com\": 1,\n\t\"0912job.com\": 1,\n\t\"0913car.com\": 1,\n\t\"0914bbs.com\": 1,\n\t\"0914cn.com\": 1,\n\t\"0915auto.com\": 1,\n\t\"0915home.com\": 1,\n\t\"0915rc.com\": 1,\n\t\"0916.tv\": 1,\n\t\"0916auto.com\": 1,\n\t\"0916i.com\": 1,\n\t\"0916rencai.com\": 1,\n\t\"0916tea.com\": 1,\n\t\"0917888.com\": 1,\n\t\"0937.net\": 1,\n\t\"094wan.com\": 1,\n\t\"0951job.com\": 1,\n\t\"09635.com\": 1,\n\t\"0979news.com\": 1,\n\t\"0991dj.com\": 1,\n\t\"0991fc.com\": 1,\n\t\"0997job.com\": 1,\n\t\"099sky.com\": 1,\n\t\"09ge.com\": 1,\n\t\"0car0.com\": 1,\n\t\"0duw.com\": 1,\n\t\"0x110.com\": 1,\n\t\"1-l.cc\": 1,\n\t\"100.com\": 1,\n\t\"10000job.com\": 1,\n\t\"10000link.com\": 1,\n\t\"10000yao.com\": 1,\n\t\"10000zy.com\": 1,\n\t\"1000islandlake.com\": 1,\n\t\"1000kan.cc\": 1,\n\t\"1000plan.org\": 1,\n\t\"1000tuan.com\": 1,\n\t\"1000z.com\": 1,\n\t\"10010.com\": 1,\n\t\"1001p.com\": 1,\n\t\"100365.com\": 1,\n\t\"10050.net\": 1,\n\t\"100580.com\": 1,\n\t\"1006.tv\": 1,\n\t\"10086gouji.com\": 1,\n\t\"100autoshow.com\": 1,\n\t\"100bt.com\": 1,\n\t\"100che.org\": 1,\n\t\"100chee.com\": 1,\n\t\"100cs.com\": 1,\n\t\"100fsc.com\": 1,\n\t\"100jiaoyu.net\": 1,\n\t\"100jn.com\": 1,\n\t\"100jnled.com\": 1,\n\t\"100kk.com\": 1,\n\t\"100ksw.com\": 1,\n\t\"100lunwen.com\": 1,\n\t\"100njz.com\": 1,\n\t\"100ppi.com\": 1,\n\t\"100shuai.com\": 1,\n\t\"100t.com\": 1,\n\t\"100t1.net\": 1,\n\t\"100tal.com\": 1,\n\t\"100tjs.com\": 1,\n\t\"100xhs.com\": 1,\n\t\"100xiao.com\": 1,\n\t\"100xuexi.com\": 1,\n\t\"100yangsheng.com\": 1,\n\t\"100ye.com\": 1,\n\t\"100yiyao.com\": 1,\n\t\"100yue.com\": 1,\n\t\"100zhuang.com\": 1,\n\t\"1010jz.com\": 1,\n\t\"10155.com\": 1,\n\t\"101jiajiao.com\": 1,\n\t\"101wo.com\": 1,\n\t\"10333.com\": 1,\n\t\"10339.com\": 1,\n\t\"103wx.com\": 1,\n\t\"105zx.com\": 1,\n\t\"10628789.com\": 1,\n\t\"1073.com\": 1,\n\t\"1080t.com\": 1,\n\t\"108jj.com\": 1,\n\t\"10and9.com\": 1,\n\t\"10fang.com\": 1,\n\t\"10oa.com\": 1,\n\t\"10s1.com\": 1,\n\t\"10yan.com\": 1,\n\t\"110.com\": 1,\n\t\"1111.com\": 1,\n\t\"11124.com\": 1,\n\t\"11157.com\": 1,\n\t\"11186.com\": 1,\n\t\"1118yx.com\": 1,\n\t\"111cn.net\": 1,\n\t\"111jz.com\": 1,\n\t\"111ttt.com\": 1,\n\t\"1122.com\": 1,\n\t\"1122xyx.com\": 1,\n\t\"1133.cc\": 1,\n\t\"1139.org\": 1,\n\t\"114-0510.com\": 1,\n\t\"1144.cc\": 1,\n\t\"11467.com\": 1,\n\t\"114best.com\": 1,\n\t\"114cbd.com\": 1,\n\t\"114chn.com\": 1,\n\t\"114hr.net\": 1,\n\t\"114huoche.com\": 1,\n\t\"114ic.com\": 1,\n\t\"114la.com\": 1,\n\t\"114nba.com\": 1,\n\t\"114nz.com\": 1,\n\t\"114piaowu.com\": 1,\n\t\"114px.com\": 1,\n\t\"114study.com\": 1,\n\t\"114xialingying.com\": 1,\n\t\"114xueche.com\": 1,\n\t\"114zhibo.com\": 1,\n\t\"115.com\": 1,\n\t\"11584.com\": 1,\n\t\"115bc.com\": 1,\n\t\"115img.com\": 1,\n\t\"115kf.com\": 1,\n\t\"116.com\": 1,\n\t\"1166.com\": 1,\n\t\"11665.com\": 1,\n\t\"116yx.com\": 1,\n\t\"11773.com\": 1,\n\t\"1177you.com\": 1,\n\t\"1179house.com\": 1,\n\t\"1188.com\": 1,\n\t\"1189.tv\": 1,\n\t\"118jiancai.com\": 1,\n\t\"11919.com\": 1,\n\t\"119g.com\": 1,\n\t\"119hn.com\": 1,\n\t\"119tx.com\": 1,\n\t\"11chuangye.com\": 1,\n\t\"11pk.net\": 1,\n\t\"11wang.org\": 1,\n\t\"11yeyou.com\": 1,\n\t\"120-job.com\": 1,\n\t\"1203.org\": 1,\n\t\"120ask.com\": 1,\n\t\"120askimages.com\": 1,\n\t\"120gubing.com\": 1,\n\t\"121121.net\": 1,\n\t\"12114job.com\": 1,\n\t\"12114rc.com\": 1,\n\t\"1212wan.com\": 1,\n\t\"121314.com\": 1,\n\t\"121tianqi.com\": 1,\n\t\"122park.com\": 1,\n\t\"12306pk.com\": 1,\n\t\"12333.com\": 1,\n\t\"12333sb.com\": 1,\n\t\"123456dj.com\": 1,\n\t\"1234h.com\": 1,\n\t\"1234kan.com\": 1,\n\t\"1234wu.com\": 1,\n\t\"1234xw.com\": 1,\n\t\"12365auto.com\": 1,\n\t\"123cha.com\": 1,\n\t\"123du.cc\": 1,\n\t\"123huijia.com\": 1,\n\t\"123ido.com\": 1,\n\t\"123juzi.net\": 1,\n\t\"123langlang.com\": 1,\n\t\"123lvxing.com\": 1,\n\t\"123tsg.com\": 1,\n\t\"123yingyu.com\": 1,\n\t\"123youhuo.com\": 1,\n\t\"123ypw.com\": 1,\n\t\"123zcyy.com\": 1,\n\t\"12530.com\": 1,\n\t\"12580.com\": 1,\n\t\"12580xy.com\": 1,\n\t\"125cn.net\": 1,\n\t\"125job.com\": 1,\n\t\"126.am\": 1,\n\t\"126.com\": 1,\n\t\"126.net\": 1,\n\t\"126job.net\": 1,\n\t\"127.net\": 1,\n\t\"127q.com\": 1,\n\t\"1288.tv\": 1,\n\t\"128rc.com\": 1,\n\t\"128uu.com\": 1,\n\t\"12999.com\": 1,\n\t\"12chai.com\": 1,\n\t\"12gang.com\": 1,\n\t\"12ky.com\": 1,\n\t\"12yao.com\": 1,\n\t\"130wan.com\": 1,\n\t\"1314gz.com\": 1,\n\t\"131cc.com\": 1,\n\t\"1322.com\": 1,\n\t\"133998.com\": 1,\n\t\"133jz.com\": 1,\n\t\"1350135.com\": 1,\n\t\"1360.com\": 1,\n\t\"13688854328.com\": 1,\n\t\"1377.cc\": 1,\n\t\"1377.com\": 1,\n\t\"137home.com\": 1,\n\t\"137wan.com\": 1,\n\t\"138edu.com\": 1,\n\t\"138jm.com\": 1,\n\t\"138job.com\": 1,\n\t\"138mr.com\": 1,\n\t\"139.com\": 1,\n\t\"1390130.com\": 1,\n\t\"139931.com\": 1,\n\t\"139cai.com\": 1,\n\t\"139js.com\": 1,\n\t\"139life.com\": 1,\n\t\"139shop.com\": 1,\n\t\"139yd.com\": 1,\n\t\"139zhuti.com\": 1,\n\t\"13cr.com\": 1,\n\t\"13ddd.com\": 1,\n\t\"13ejob.com\": 1,\n\t\"13ie.com\": 1,\n\t\"144yx.com\": 1,\n\t\"1488.com\": 1,\n\t\"148com.com\": 1,\n\t\"14xf.com\": 1,\n\t\"150z.com\": 1,\n\t\"15153.com\": 1,\n\t\"1518.com\": 1,\n\t\"1518wan.com\": 1,\n\t\"151wan.com\": 1,\n\t\"1545ts.com\": 1,\n\t\"1556.net\": 1,\n\t\"156580.com\": 1,\n\t\"15666.com\": 1,\n\t\"157300.net\": 1,\n\t\"1588.tv\": 1,\n\t\"15880.com\": 1,\n\t\"1588yx.com\": 1,\n\t\"159.com\": 1,\n\t\"159cai.com\": 1,\n\t\"15bl.com\": 1,\n\t\"15gg.com\": 1,\n\t\"15gift.com\": 1,\n\t\"15hr.com\": 1,\n\t\"15iacc.com\": 1,\n\t\"15lu.com\": 1,\n\t\"15sjw.com\": 1,\n\t\"15too.com\": 1,\n\t\"15ux.com\": 1,\n\t\"15w.com\": 1,\n\t\"160.com\": 1,\n\t\"1616.net\": 1,\n\t\"1617k.com\": 1,\n\t\"161gg.com\": 1,\n\t\"1626.com\": 1,\n\t\"163.com\": 1,\n\t\"163.net\": 1,\n\t\"1633.com\": 1,\n\t\"1637.com\": 1,\n\t\"163disk.com\": 1,\n\t\"163gov.com\": 1,\n\t\"163k.cc\": 1,\n\t\"163k.com\": 1,\n\t\"163ns.com\": 1,\n\t\"163yu.com\": 1,\n\t\"163yy.net\": 1,\n\t\"164580.com\": 1,\n\t\"1651ky.com\": 1,\n\t\"1666.com\": 1,\n\t\"166wan.com\": 1,\n\t\"1688.com\": 1,\n\t\"16888.com\": 1,\n\t\"1688e.net\": 1,\n\t\"1688wan.com\": 1,\n\t\"168cb.com\": 1,\n\t\"168dc.com\": 1,\n\t\"168hm.com\": 1,\n\t\"168hs.com\": 1,\n\t\"168job.com\": 1,\n\t\"168liuxue.com\": 1,\n\t\"168pd.com\": 1,\n\t\"168xd.com\": 1,\n\t\"168xiezi.com\": 1,\n\t\"168yinhe.com\": 1,\n\t\"169369.com\": 1,\n\t\"16999.com\": 1,\n\t\"169gold.com\": 1,\n\t\"16cp.com\": 1,\n\t\"16fan.com\": 1,\n\t\"16good.com\": 1,\n\t\"16house.com\": 1,\n\t\"16kang.com\": 1,\n\t\"16p.com\": 1,\n\t\"16sucai.com\": 1,\n\t\"16tz.com\": 1,\n\t\"16u.com\": 1,\n\t\"170u.com\": 1,\n\t\"17173.com\": 1,\n\t\"1717388.com\": 1,\n\t\"17173cdn.com\": 1,\n\t\"17173ie.com\": 1,\n\t\"17173ie.net\": 1,\n\t\"1717kf.com\": 1,\n\t\"1717pk.com\": 1,\n\t\"1718001.com\": 1,\n\t\"1718006.com\": 1,\n\t\"1718china.com\": 1,\n\t\"1718china.net\": 1,\n\t\"1718world.com\": 1,\n\t\"171ju.com\": 1,\n\t\"172xiaoyuan.com\": 1,\n\t\"173.com\": 1,\n\t\"1737game.com\": 1,\n\t\"173daxue.com\": 1,\n\t\"173eg.com\": 1,\n\t\"173kt.com\": 1,\n\t\"173pk.com\": 1,\n\t\"173zsw.com\": 1,\n\t\"17446.com\": 1,\n\t\"175game.com\": 1,\n\t\"175ha.com\": 1,\n\t\"175kh.com\": 1,\n\t\"175pt.com\": 1,\n\t\"175wan.com\": 1,\n\t\"176.com\": 1,\n\t\"17611.com\": 1,\n\t\"17673.com\": 1,\n\t\"1773.com\": 1,\n\t\"1773y.com\": 1,\n\t\"1778.com\": 1,\n\t\"177dj.net\": 1,\n\t\"178.com\": 1,\n\t\"178178qp.com\": 1,\n\t\"17888.com\": 1,\n\t\"178good.com\": 1,\n\t\"178yy.com\": 1,\n\t\"178zmy.com\": 1,\n\t\"179179.com\": 1,\n\t\"1797wan.com\": 1,\n\t\"179v.com\": 1,\n\t\"179xizang.com\": 1,\n\t\"17caifu.com\": 1,\n\t\"17cdn.com\": 1,\n\t\"17cma.com\": 1,\n\t\"17coolz.com\": 1,\n\t\"17daili.com\": 1,\n\t\"17dm.com\": 1,\n\t\"17fangte.com\": 1,\n\t\"17fee.com\": 1,\n\t\"17gai.com\": 1,\n\t\"17guagua.com\": 1,\n\t\"17heli.com\": 1,\n\t\"17hihi.com\": 1,\n\t\"17house.com\": 1,\n\t\"17jita.com\": 1,\n\t\"17k.com\": 1,\n\t\"17kapai.com\": 1,\n\t\"17kuxun.com\": 1,\n\t\"17liuxue.com\": 1,\n\t\"17lu.net\": 1,\n\t\"17m3.com\": 1,\n\t\"17maoyi.com\": 1,\n\t\"17mcp.com\": 1,\n\t\"17miyou.com\": 1,\n\t\"17ms.com\": 1,\n\t\"17oh.com\": 1,\n\t\"17ps8.com\": 1,\n\t\"17qzx.com\": 1,\n\t\"17sucai.com\": 1,\n\t\"17u.com\": 1,\n\t\"17u.net\": 1,\n\t\"17ugo.com\": 1,\n\t\"17usoft.com\": 1,\n\t\"17utt.com\": 1,\n\t\"17wan.la\": 1,\n\t\"17wendao.com\": 1,\n\t\"17xinghun.com\": 1,\n\t\"17yy.com\": 1,\n\t\"17zhuang.com\": 1,\n\t\"17zwd.com\": 1,\n\t\"180img.com\": 1,\n\t\"180kids.com\": 1,\n\t\"180mi.com\": 1,\n\t\"181.cc\": 1,\n\t\"18108.com\": 1,\n\t\"18183.com\": 1,\n\t\"1818hm.com\": 1,\n\t\"1819.tv\": 1,\n\t\"183read.com\": 1,\n\t\"1851688.com\": 1,\n\t\"1866.tv\": 1,\n\t\"186it.com\": 1,\n\t\"188.com\": 1,\n\t\"18838.net\": 1,\n\t\"188cyw.com\": 1,\n\t\"188dm.com\": 1,\n\t\"188fu.com\": 1,\n\t\"189house.com\": 1,\n\t\"189rc.com\": 1,\n\t\"189share.com\": 1,\n\t\"189store.com\": 1,\n\t\"189yo.com\": 1,\n\t\"18dao.net\": 1,\n\t\"18heyou.com\": 1,\n\t\"18ladys.com\": 1,\n\t\"18ph.com\": 1,\n\t\"18qiang.com\": 1,\n\t\"18report.com\": 1,\n\t\"18touch.com\": 1,\n\t\"18xiang.org\": 1,\n\t\"18yl.com\": 1,\n\t\"1905.com\": 1,\n\t\"192job.com\": 1,\n\t\"19687.com\": 1,\n\t\"197c.com\": 1,\n\t\"198526.com\": 1,\n\t\"198526.net\": 1,\n\t\"1988.tv\": 1,\n\t\"19888.tv\": 1,\n\t\"198du.com\": 1,\n\t\"198game.com\": 1,\n\t\"199it.com\": 1,\n\t\"199youxi.com\": 1,\n\t\"19lou.com\": 1,\n\t\"19wan.com\": 1,\n\t\"19yxw.com\": 1,\n\t\"19zhan.com\": 1,\n\t\"19zu.com\": 1,\n\t\"1b2g.com\": 1,\n\t\"1bd1.com\": 1,\n\t\"1beng.com\": 1,\n\t\"1d11.com\": 1,\n\t\"1dancong.com\": 1,\n\t\"1diaocha.com\": 1,\n\t\"1f11.com\": 1,\n\t\"1fabric.com\": 1,\n\t\"1g31.com\": 1,\n\t\"1gjh.com\": 1,\n\t\"1haomeng.com\": 1,\n\t\"1kejian.com\": 1,\n\t\"1kepu.com\": 1,\n\t\"1kkk.com\": 1,\n\t\"1koreannews.com\": 1,\n\t\"1linli.com\": 1,\n\t\"1m3d.com\": 1,\n\t\"1mall.com\": 1,\n\t\"1mishu.com\": 1,\n\t\"1n11.com\": 1,\n\t\"1news.cc\": 1,\n\t\"1nongjing.com\": 1,\n\t\"1nsou.com\": 1,\n\t\"1o26.com\": 1,\n\t\"1oo2.com\": 1,\n\t\"1p1g.com\": 1,\n\t\"1p365.com\": 1,\n\t\"1peizai.com\": 1,\n\t\"1ppt.com\": 1,\n\t\"1qj.net\": 1,\n\t\"1qwe3r.com\": 1,\n\t\"1shoucang.com\": 1,\n\t\"1ting.com\": 1,\n\t\"1ty.com\": 1,\n\t\"1uuc.com\": 1,\n\t\"1v1offcn.com\": 1,\n\t\"1wwtx.com\": 1,\n\t\"1y2y.com\": 1,\n\t\"1youxi.com\": 1,\n\t\"1zhao.org\": 1,\n\t\"1zihua.com\": 1,\n\t\"1zjob.com\": 1,\n\t\"1zw.com\": 1,\n\t\"200.net\": 1,\n\t\"2000888.com\": 1,\n\t\"2001com.com\": 1,\n\t\"200dy.com\": 1,\n\t\"2016kaoyan.com\": 1,\n\t\"201980.com\": 1,\n\t\"202wan.com\": 1,\n\t\"2046sheying.com\": 1,\n\t\"2095114.com\": 1,\n\t\"20uk.com\": 1,\n\t\"21-cmjob.com\": 1,\n\t\"21-part.com\": 1,\n\t\"21-rent.com\": 1,\n\t\"21-sun.com\": 1,\n\t\"21-sun.net\": 1,\n\t\"21-used.com\": 1,\n\t\"2100book.com\": 1,\n\t\"2114.com\": 1,\n\t\"211600.com\": 1,\n\t\"211lx.com\": 1,\n\t\"212300.com\": 1,\n\t\"2125.com\": 1,\n\t\"21253.com\": 1,\n\t\"2144.cc\": 1,\n\t\"2160.com\": 1,\n\t\"2197079.com\": 1,\n\t\"21af.com\": 1,\n\t\"21c168.com\": 1,\n\t\"21caas.com\": 1,\n\t\"21cbh.com\": 1,\n\t\"21cbr.com\": 1,\n\t\"21ccnn.com\": 1,\n\t\"21ccom.net\": 1,\n\t\"21ce.cc\": 1,\n\t\"21cn.com\": 1,\n\t\"21cn.net\": 1,\n\t\"21cnimg.com\": 1,\n\t\"21cnjy.com\": 1,\n\t\"21cnlunwen.com\": 1,\n\t\"21cp.com\": 1,\n\t\"21cp.net\": 1,\n\t\"21dagong.com\": 1,\n\t\"21dcw.com\": 1,\n\t\"21dianchi.com\": 1,\n\t\"21dianyuan.com\": 1,\n\t\"21dnn.com\": 1,\n\t\"21edu8.com\": 1,\n\t\"21fengchao.com\": 1,\n\t\"21food.com\": 1,\n\t\"21gold.org\": 1,\n\t\"21hgjx.com\": 1,\n\t\"21hh.com\": 1,\n\t\"21hospital.com\": 1,\n\t\"21hubei.com\": 1,\n\t\"21hulian.com\": 1,\n\t\"21ic.com\": 1,\n\t\"21itjob.com\": 1,\n\t\"21its.com\": 1,\n\t\"21jrr.com\": 1,\n\t\"21js.com\": 1,\n\t\"21js.org\": 1,\n\t\"21ks.net\": 1,\n\t\"21me.me\": 1,\n\t\"21nowart.com\": 1,\n\t\"21our.com\": 1,\n\t\"21page.net\": 1,\n\t\"21part.com\": 1,\n\t\"21peitao.com\": 1,\n\t\"21pw.com\": 1,\n\t\"21rcw.com\": 1,\n\t\"21rv.com\": 1,\n\t\"21sb.com\": 1,\n\t\"21sb.org\": 1,\n\t\"21sea.com\": 1,\n\t\"21sew.com\": 1,\n\t\"21shipin.com\": 1,\n\t\"21so.com\": 1,\n\t\"21spv.com\": 1,\n\t\"21sq.org\": 1,\n\t\"21taiyang.com\": 1,\n\t\"21tb.com\": 1,\n\t\"21tyn.com\": 1,\n\t\"21wanwan.com\": 1,\n\t\"21wecan.com\": 1,\n\t\"21xc.com\": 1,\n\t\"21xsl.com\": 1,\n\t\"21yod.com\": 1,\n\t\"21yq.com\": 1,\n\t\"2200book.com\": 1,\n\t\"22086.com\": 1,\n\t\"221400job.com\": 1,\n\t\"22157.com\": 1,\n\t\"221600job.com\": 1,\n\t\"221700.com\": 1,\n\t\"22197.com\": 1,\n\t\"223you.com\": 1,\n\t\"224200.com\": 1,\n\t\"2243.com\": 1,\n\t\"224600.com\": 1,\n\t\"2258.com\": 1,\n\t\"225s.com\": 1,\n\t\"2265.com\": 1,\n\t\"226531.com\": 1,\n\t\"226y.com\": 1,\n\t\"2280.com\": 1,\n\t\"228cai.com\": 1,\n\t\"2295.com\": 1,\n\t\"2298.com\": 1,\n\t\"22bw.com\": 1,\n\t\"22edu.com\": 1,\n\t\"22w.com\": 1,\n\t\"2300sjz.com\": 1,\n\t\"230jc.com\": 1,\n\t\"230la.net\": 1,\n\t\"2323u.com\": 1,\n\t\"2323wan.com\": 1,\n\t\"23255555.com\": 1,\n\t\"233.com\": 1,\n\t\"233000.com\": 1,\n\t\"2344.cc\": 1,\n\t\"2344.com\": 1,\n\t\"2345.com\": 1,\n\t\"2345.net\": 1,\n\t\"2345a.com\": 1,\n\t\"2366.com\": 1,\n\t\"237.cc\": 1,\n\t\"238000.net\": 1,\n\t\"23class.com\": 1,\n\t\"23du.com\": 1,\n\t\"23ks.com\": 1,\n\t\"23ps.com\": 1,\n\t\"23qcw.com\": 1,\n\t\"23rencai.com\": 1,\n\t\"246ys.com\": 1,\n\t\"24jq.net\": 1,\n\t\"24k.com\": 1,\n\t\"24k99.com\": 1,\n\t\"24pay.net\": 1,\n\t\"24quan.com\": 1,\n\t\"25000li.com\": 1,\n\t\"2500che.com\": 1,\n\t\"2500sz.com\": 1,\n\t\"253u.com\": 1,\n\t\"255star.com\": 1,\n\t\"256.cc\": 1,\n\t\"25622.com\": 1,\n\t\"25788.com\": 1,\n\t\"2588.tv\": 1,\n\t\"258en.com\": 1,\n\t\"25az.com\": 1,\n\t\"25game.com\": 1,\n\t\"25nc.com\": 1,\n\t\"25pp.com\": 1,\n\t\"25pp.net\": 1,\n\t\"25xz.com\": 1,\n\t\"25yz.com\": 1,\n\t\"263.cc\": 1,\n\t\"263.com\": 1,\n\t\"263.net\": 1,\n\t\"264006.com\": 1,\n\t\"264g.com\": 1,\n\t\"265.com\": 1,\n\t\"265588.com\": 1,\n\t\"2657.com\": 1,\n\t\"26595.com\": 1,\n\t\"265g.com\": 1,\n\t\"265vv.com\": 1,\n\t\"266wan.com\": 1,\n\t\"2676.com\": 1,\n\t\"269.net\": 1,\n\t\"26923.com\": 1,\n\t\"26abc.com\": 1,\n\t\"26lady.com\": 1,\n\t\"271you.com\": 1,\n\t\"2720668.com\": 1,\n\t\"274500.com\": 1,\n\t\"279wo.com\": 1,\n\t\"27qq.com\": 1,\n\t\"27xs.com\": 1,\n\t\"28.com\": 1,\n\t\"280.com\": 1,\n\t\"285868.com\": 1,\n\t\"2881.com\": 1,\n\t\"288jc.net\": 1,\n\t\"288job.com\": 1,\n\t\"289.com\": 1,\n\t\"28jmw.com\": 1,\n\t\"28ktv.com\": 1,\n\t\"28sn.com\": 1,\n\t\"28tui.com\": 1,\n\t\"28y.com\": 1,\n\t\"28yun.com\": 1,\n\t\"293.net\": 1,\n\t\"2cto.com\": 1,\n\t\"2danji.com\": 1,\n\t\"2dianban.com\": 1,\n\t\"2dx.net\": 1,\n\t\"2ge8.com\": 1,\n\t\"2hua.com\": 1,\n\t\"2liang.net\": 1,\n\t\"2m2j.com\": 1,\n\t\"2m3m.com\": 1,\n\t\"2mdn.net\": 1,\n\t\"2mjob.com\": 1,\n\t\"2mould.com\": 1,\n\t\"2pjob.com\": 1,\n\t\"2rich.net\": 1,\n\t\"2scc.net\": 1,\n\t\"2uuzs.com\": 1,\n\t\"3000f.com\": 1,\n\t\"300cleaners.com\": 1,\n\t\"301688.com\": 1,\n\t\"302wan.com\": 1,\n\t\"304t.com\": 1,\n\t\"30556.com\": 1,\n\t\"30buy.com\": 1,\n\t\"30edu.com\": 1,\n\t\"30gov.com\": 1,\n\t\"30kp.com\": 1,\n\t\"310tv.com\": 1,\n\t\"310win.com\": 1,\n\t\"311wan.com\": 1,\n\t\"312000.net\": 1,\n\t\"312168.com\": 1,\n\t\"312tree.com\": 1,\n\t\"313.com\": 1,\n\t\"3131job.com\": 1,\n\t\"313job.com\": 1,\n\t\"3145.com\": 1,\n\t\"3155.com\": 1,\n\t\"315700.com\": 1,\n\t\"3158.com\": 1,\n\t\"3158.net\": 1,\n\t\"3158yww.com\": 1,\n\t\"315ad.com\": 1,\n\t\"315che.com\": 1,\n\t\"315city.com\": 1,\n\t\"315hyw.com\": 1,\n\t\"315img.com\": 1,\n\t\"315mro.com\": 1,\n\t\"315ok.com\": 1,\n\t\"315sc.org\": 1,\n\t\"317600.net\": 1,\n\t\"318918.com\": 1,\n\t\"318yishu.com\": 1,\n\t\"31alu.com\": 1,\n\t\"31bag.com\": 1,\n\t\"31bear.com\": 1,\n\t\"31bee.com\": 1,\n\t\"31boiler.com\": 1,\n\t\"31bxg.com\": 1,\n\t\"31byq.com\": 1,\n\t\"31bzjx.com\": 1,\n\t\"31cable.com\": 1,\n\t\"31cf.com\": 1,\n\t\"31cgw.com\": 1,\n\t\"31chair.com\": 1,\n\t\"31ddc.com\": 1,\n\t\"31ddgj.com\": 1,\n\t\"31dry.com\": 1,\n\t\"31dt.com\": 1,\n\t\"31expo.com\": 1,\n\t\"31feed.com\": 1,\n\t\"31fg.com\": 1,\n\t\"31fish.com\": 1,\n\t\"31fj.com\": 1,\n\t\"31fluid.com\": 1,\n\t\"31food.com\": 1,\n\t\"31fsbw.com\": 1,\n\t\"31gcjx.com\": 1,\n\t\"31gear.com\": 1,\n\t\"31glass.com\": 1,\n\t\"31glasses.com\": 1,\n\t\"31hgyq.com\": 1,\n\t\"31hqyp.com\": 1,\n\t\"31hrq.com\": 1,\n\t\"31huiyi.com\": 1,\n\t\"31hwyp.com\": 1,\n\t\"31hzp.com\": 1,\n\t\"31jc.com\": 1,\n\t\"31jf.com\": 1,\n\t\"31jgj.com\": 1,\n\t\"31jhsb.com\": 1,\n\t\"31jiaju.com\": 1,\n\t\"31jmw.com\": 1,\n\t\"31jxw.com\": 1,\n\t\"31light.com\": 1,\n\t\"31lp.com\": 1,\n\t\"31mada.com\": 1,\n\t\"31md.com\": 1,\n\t\"31metals.com\": 1,\n\t\"31mjg.com\": 1,\n\t\"31mold.com\": 1,\n\t\"31myhome.com\": 1,\n\t\"31nk.com\": 1,\n\t\"31oil.com\": 1,\n\t\"31print.com\": 1,\n\t\"31pump.com\": 1,\n\t\"31rcw.com\": 1,\n\t\"31rzp.com\": 1,\n\t\"31seal.com\": 1,\n\t\"31shipin.com\": 1,\n\t\"31shoes.com\": 1,\n\t\"31sjjx.com\": 1,\n\t\"31spcar.com\": 1,\n\t\"31spjx.com\": 1,\n\t\"31taoci.com\": 1,\n\t\"31tjj.com\": 1,\n\t\"31toy.com\": 1,\n\t\"31tqw.com\": 1,\n\t\"31weld.com\": 1,\n\t\"31wenju.com\": 1,\n\t\"31wj.com\": 1,\n\t\"31wood.com\": 1,\n\t\"31xf.com\": 1,\n\t\"31xjd.com\": 1,\n\t\"31xm.com\": 1,\n\t\"31yj.com\": 1,\n\t\"31yr.com\": 1,\n\t\"31yrhg.com\": 1,\n\t\"31ysj.com\": 1,\n\t\"31yyqd.com\": 1,\n\t\"31zj.com\": 1,\n\t\"31zscl.com\": 1,\n\t\"31zzw.com\": 1,\n\t\"320106.com\": 1,\n\t\"320921.com\": 1,\n\t\"3216.cc\": 1,\n\t\"3234.com\": 1,\n\t\"323g.com\": 1,\n\t\"325802.net\": 1,\n\t\"3265.net\": 1,\n\t\"32ka.com\": 1,\n\t\"32wan.com\": 1,\n\t\"33.la\": 1,\n\t\"3304399.net\": 1,\n\t\"3310.com\": 1,\n\t\"3322.org\": 1,\n\t\"3323.com\": 1,\n\t\"3328.tv\": 1,\n\t\"33378.net\": 1,\n\t\"33383338.com\": 1,\n\t\"333xin.com\": 1,\n\t\"33456.com\": 1,\n\t\"33519.com\": 1,\n\t\"3366.com\": 1,\n\t\"3366img.com\": 1,\n\t\"337g.com\": 1,\n\t\"337y.com\": 1,\n\t\"3393.com\": 1,\n\t\"3399.com\": 1,\n\t\"33dvd.com\": 1,\n\t\"33erwo.com\": 1,\n\t\"33lc.com\": 1,\n\t\"33ly.com\": 1,\n\t\"33trip.com\": 1,\n\t\"340.cc\": 1,\n\t\"342225.com\": 1,\n\t\"3454.com\": 1,\n\t\"3456.cc\": 1,\n\t\"3456.tv\": 1,\n\t\"34job.com\": 1,\n\t\"35.com\": 1,\n\t\"35.la\": 1,\n\t\"35313.com\": 1,\n\t\"3533.com\": 1,\n\t\"356ys.com\": 1,\n\t\"358wan.com\": 1,\n\t\"35941.com\": 1,\n\t\"35metal.com\": 1,\n\t\"35pic.com\": 1,\n\t\"35q.com\": 1,\n\t\"35tool.com\": 1,\n\t\"35wl.com\": 1,\n\t\"35yao.com\": 1,\n\t\"35you.com\": 1,\n\t\"35zhe.com\": 1,\n\t\"36.la\": 1,\n\t\"3600t.com\": 1,\n\t\"360aiyi.com\": 1,\n\t\"360buy.com\": 1,\n\t\"360buyimg.com\": 1,\n\t\"360changshi.com\": 1,\n\t\"360che.com\": 1,\n\t\"360doc.com\": 1,\n\t\"360doo.com\": 1,\n\t\"360eol.com\": 1,\n\t\"360gann.com\": 1,\n\t\"360guakao.net\": 1,\n\t\"360gxi.com\": 1,\n\t\"360js.com\": 1,\n\t\"360junshi.com\": 1,\n\t\"360kad.com\": 1,\n\t\"360kan.com\": 1,\n\t\"360kxr.com\": 1,\n\t\"360mobao.com\": 1,\n\t\"360qc.com\": 1,\n\t\"360qikan.com\": 1,\n\t\"360safe.com\": 1,\n\t\"360sky.com\": 1,\n\t\"360tl.com\": 1,\n\t\"360top.com\": 1,\n\t\"360tpcdn.com\": 1,\n\t\"360uu.com\": 1,\n\t\"360wyw.com\": 1,\n\t\"360xzl.com\": 1,\n\t\"360youtu.com\": 1,\n\t\"3618med.com\": 1,\n\t\"361games.com\": 1,\n\t\"361sport.com\": 1,\n\t\"364000.com\": 1,\n\t\"3650310.net\": 1,\n\t\"365500.com\": 1,\n\t\"365724.com\": 1,\n\t\"36578.com\": 1,\n\t\"36588zs.com\": 1,\n\t\"365a8.com\": 1,\n\t\"365ajw.com\": 1,\n\t\"365anfang.com\": 1,\n\t\"365art.com\": 1,\n\t\"365auto.com\": 1,\n\t\"365azw.com\": 1,\n\t\"365bj.com\": 1,\n\t\"365cgw.com\": 1,\n\t\"365exam.com\": 1,\n\t\"365groups.com\": 1,\n\t\"365guipian.com\": 1,\n\t\"365haofang.com\": 1,\n\t\"365hf.com\": 1,\n\t\"365jilin.com\": 1,\n\t\"365kl.net\": 1,\n\t\"365mo.com\": 1,\n\t\"365pk.com\": 1,\n\t\"365qilu.com\": 1,\n\t\"365rili.com\": 1,\n\t\"365soso.com\": 1,\n\t\"365ta.com\": 1,\n\t\"365tkt.com\": 1,\n\t\"365tlf.com\": 1,\n\t\"365url.cc\": 1,\n\t\"365webcall.com\": 1,\n\t\"365wj.com\": 1,\n\t\"365zhanlan.com\": 1,\n\t\"365zhaosheng.com\": 1,\n\t\"365zhongzi.com\": 1,\n\t\"365zl.com\": 1,\n\t\"3661.com\": 1,\n\t\"36683.com\": 1,\n\t\"366health.com\": 1,\n\t\"368tea.com\": 1,\n\t\"369.com\": 1,\n\t\"36dj.com\": 1,\n\t\"36dsj.com\": 1,\n\t\"36kr.com\": 1,\n\t\"36kr.net\": 1,\n\t\"36krcnd.com\": 1,\n\t\"36sfw.com\": 1,\n\t\"36tr.com\": 1,\n\t\"36zm.com\": 1,\n\t\"37.com\": 1,\n\t\"371.com\": 1,\n\t\"371.net\": 1,\n\t\"37168.com\": 1,\n\t\"371love.com\": 1,\n\t\"371weiyi.com\": 1,\n\t\"37201.com\": 1,\n\t\"3737.com\": 1,\n\t\"3737k.com\": 1,\n\t\"373f.com\": 1,\n\t\"373house.com\": 1,\n\t\"373w.com\": 1,\n\t\"375ba.com\": 1,\n\t\"3761.com\": 1,\n\t\"376che.com\": 1,\n\t\"3777w.com\": 1,\n\t\"37937.com\": 1,\n\t\"3798.com\": 1,\n\t\"37cs.com\": 1,\n\t\"37cu.com\": 1,\n\t\"37cy.com\": 1,\n\t\"37k.com\": 1,\n\t\"37nixi.com\": 1,\n\t\"37pk49.com\": 1,\n\t\"37see.com\": 1,\n\t\"37wan.com\": 1,\n\t\"37wan.net\": 1,\n\t\"37wanimg.com\": 1,\n\t\"37wanwan.com\": 1,\n\t\"37youwan.com\": 1,\n\t\"37youyou.com\": 1,\n\t\"3839.com\": 1,\n\t\"383yx.com\": 1,\n\t\"387a.com\": 1,\n\t\"38xf.com\": 1,\n\t\"39.net\": 1,\n\t\"3911.com\": 1,\n\t\"391k.com\": 1,\n\t\"39269222.com\": 1,\n\t\"3937.com\": 1,\n\t\"3949000.com\": 1,\n\t\"3987.com\": 1,\n\t\"39kf.com\": 1,\n\t\"39txt.com\": 1,\n\t\"39yss.com\": 1,\n\t\"39yst.com\": 1,\n\t\"39ysw.com\": 1,\n\t\"3apaint.com\": 1,\n\t\"3b2o.com\": 1,\n\t\"3banfu.net\": 1,\n\t\"3bwx.com\": 1,\n\t\"3chao.com\": 1,\n\t\"3cjob.com\": 1,\n\t\"3cjob.net\": 1,\n\t\"3conline.com\": 1,\n\t\"3conline.net\": 1,\n\t\"3d66.com\": 1,\n\t\"3ddmjob.com\": 1,\n\t\"3derp.net\": 1,\n\t\"3dfc.com\": 1,\n\t\"3dkezhan.com\": 1,\n\t\"3dmgame.com\": 1,\n\t\"3dtaiyuan.com\": 1,\n\t\"3dtaomo.com\": 1,\n\t\"3edu.net\": 1,\n\t\"3etravel.com\": 1,\n\t\"3fantizi.com\": 1,\n\t\"3g-edu.org\": 1,\n\t\"3g210.com\": 1,\n\t\"3g210.net\": 1,\n\t\"3g2y.com\": 1,\n\t\"3ghuashang.com\": 1,\n\t\"3h3.com\": 1,\n\t\"3hrc.com\": 1,\n\t\"3hsh.com\": 1,\n\t\"3j3f.com\": 1,\n\t\"3jgo.com\": 1,\n\t\"3jrx.com\": 1,\n\t\"3jy.com\": 1,\n\t\"3kfw.com\": 1,\n\t\"3lian.com\": 1,\n\t\"3lsc.com\": 1,\n\t\"3need.com\": 1,\n\t\"3nong.com\": 1,\n\t\"3qhouse.com\": 1,\n\t\"3s001.com\": 1,\n\t\"3sjob.net\": 1,\n\t\"3snews.net\": 1,\n\t\"3u5.net\": 1,\n\t\"3visual3.com\": 1,\n\t\"3wmas.com\": 1,\n\t\"3wmm.cc\": 1,\n\t\"3wmm.com\": 1,\n\t\"3xgd.com\": 1,\n\t\"3yx.com\": 1,\n\t\"4.cm\": 1,\n\t\"400516.com\": 1,\n\t\"4006666688.com\": 1,\n\t\"4006713114.com\": 1,\n\t\"4006777711.com\": 1,\n\t\"4006787252.com\": 1,\n\t\"4006888808.com\": 1,\n\t\"4006hr.com\": 1,\n\t\"4008000000.com\": 1,\n\t\"4008208040.com\": 1,\n\t\"4008885166.com\": 1,\n\t\"400job.com\": 1,\n\t\"400jz.com\": 1,\n\t\"40407.com\": 1,\n\t\"404wan.com\": 1,\n\t\"405400.com\": 1,\n\t\"4065.com\": 1,\n\t\"411au.com\": 1,\n\t\"4124.com\": 1,\n\t\"4136.com\": 1,\n\t\"414.cc\": 1,\n\t\"41717.com\": 1,\n\t\"41717.net\": 1,\n\t\"419600.net\": 1,\n\t\"41cs.com\": 1,\n\t\"42144.com\": 1,\n\t\"4299.cc\": 1,\n\t\"432520.com\": 1,\n\t\"434300.net\": 1,\n\t\"4355.com\": 1,\n\t\"4362.com\": 1,\n\t\"4366.cc\": 1,\n\t\"437900.com\": 1,\n\t\"438g.com\": 1,\n\t\"4399.com\": 1,\n\t\"43999yx.com\": 1,\n\t\"4399api.net\": 1,\n\t\"4399dmw.com\": 1,\n\t\"4399er.com\": 1,\n\t\"4399j.com\": 1,\n\t\"4399pk.com\": 1,\n\t\"4399vv.com\": 1,\n\t\"43house.com\": 1,\n\t\"43nv.com\": 1,\n\t\"44755.com\": 1,\n\t\"44957.com\": 1,\n\t\"44hr.com\": 1,\n\t\"44pq.com\": 1,\n\t\"45451.com\": 1,\n\t\"45575.com\": 1,\n\t\"457000.com\": 1,\n\t\"458000.com\": 1,\n\t\"45fan.com\": 1,\n\t\"461000.net\": 1,\n\t\"46sj.com\": 1,\n\t\"4738.com\": 1,\n\t\"4765.com\": 1,\n\t\"47yun.com\": 1,\n\t\"4806549.com\": 1,\n\t\"488u.com\": 1,\n\t\"4891111.com\": 1,\n\t\"4908.com\": 1,\n\t\"49358.com\": 1,\n\t\"49369.com\": 1,\n\t\"4997.com\": 1,\n\t\"49you.com\": 1,\n\t\"4aqq.com\": 1,\n\t\"4dmil.com\": 1,\n\t\"4dtime.com\": 1,\n\t\"4edy.com\": 1,\n\t\"4fang.net\": 1,\n\t\"4gdh.net\": 1,\n\t\"4gfang.com\": 1,\n\t\"4gfy.com\": 1,\n\t\"4ggamer.com\": 1,\n\t\"4jxl.com\": 1,\n\t\"4lou.com\": 1,\n\t\"4lzx.com\": 1,\n\t\"4plmarket.com\": 1,\n\t\"4sjob.com\": 1,\n\t\"4thmedia.org\": 1,\n\t\"4wan.cc\": 1,\n\t\"4yt.net\": 1,\n\t\"4zhe.com\": 1,\n\t\"500.com\": 1,\n\t\"5000pk.com\": 1,\n\t\"500365.com\": 1,\n\t\"5004.com\": 1,\n\t\"500cache.com\": 1,\n\t\"500wan.com\": 1,\n\t\"502pk.com\": 1,\n\t\"5054399.com\": 1,\n\t\"5055.cc\": 1,\n\t\"505wan.com\": 1,\n\t\"5068.com\": 1,\n\t\"50769.com\": 1,\n\t\"508job.com\": 1,\n\t\"509.cc\": 1,\n\t\"50bang.org\": 1,\n\t\"51-cf.com\": 1,\n\t\"51.com\": 1,\n\t\"51.la\": 1,\n\t\"510.com\": 1,\n\t\"510560.com\": 1,\n\t\"5105wan.com\": 1,\n\t\"5113178.com\": 1,\n\t\"5118114.com\": 1,\n\t\"5118wan.com\": 1,\n\t\"511wan.com\": 1,\n\t\"5120.com\": 1,\n\t\"51240.com\": 1,\n\t\"512auto.com\": 1,\n\t\"512g.net\": 1,\n\t\"512ms.com\": 1,\n\t\"512pk.com\": 1,\n\t\"512play.com\": 1,\n\t\"512test.com\": 1,\n\t\"512zp.com\": 1,\n\t\"51314.cc\": 1,\n\t\"5137.cc\": 1,\n\t\"513cc.com\": 1,\n\t\"514193.com\": 1,\n\t\"514200.com\": 1,\n\t\"5151home.com\": 1,\n\t\"5151sc.com\": 1,\n\t\"5151xqg.com\": 1,\n\t\"5155wan.com\": 1,\n\t\"5156edu.com\": 1,\n\t\"5156yuwen.com\": 1,\n\t\"51595.com\": 1,\n\t\"51643.com\": 1,\n\t\"516lyw.com\": 1,\n\t\"5173.com\": 1,\n\t\"5173766.com\": 1,\n\t\"5173cdn.com\": 1,\n\t\"51766.com\": 1,\n\t\"5179.com\": 1,\n\t\"517best.com\": 1,\n\t\"517dv.com\": 1,\n\t\"517ee.com\": 1,\n\t\"517gf.com\": 1,\n\t\"517huwai.com\": 1,\n\t\"517japan.com\": 1,\n\t\"517sc.com\": 1,\n\t\"517wjw.com\": 1,\n\t\"517zzw.com\": 1,\n\t\"5184.com\": 1,\n\t\"5188b2b.com\": 1,\n\t\"518ad.com\": 1,\n\t\"518baidu.org\": 1,\n\t\"518fang.com\": 1,\n\t\"519d.com\": 1,\n\t\"51able.com\": 1,\n\t\"51anf.com\": 1,\n\t\"51app.com\": 1,\n\t\"51aspx.com\": 1,\n\t\"51atgc.com\": 1,\n\t\"51auto.com\": 1,\n\t\"51aya.com\": 1,\n\t\"51bafu.com\": 1,\n\t\"51banban.com\": 1,\n\t\"51baocai.com\": 1,\n\t\"51bdks.com\": 1,\n\t\"51bi.com\": 1,\n\t\"51buy.com\": 1,\n\t\"51bxg.com\": 1,\n\t\"51cacg.com\": 1,\n\t\"51charge.com\": 1,\n\t\"51chudui.com\": 1,\n\t\"51chuji.com\": 1,\n\t\"51chuli.com\": 1,\n\t\"51ci.com\": 1,\n\t\"51cm.com\": 1,\n\t\"51cma.org\": 1,\n\t\"51cnhr.com\": 1,\n\t\"51coma.com\": 1,\n\t\"51comp.com\": 1,\n\t\"51credit.com\": 1,\n\t\"51cto.com\": 1,\n\t\"51dc.com\": 1,\n\t\"51dianlan.com\": 1,\n\t\"51ditu.com\": 1,\n\t\"51duide.com\": 1,\n\t\"51duoying.com\": 1,\n\t\"51dzw.com\": 1,\n\t\"51e-online.com\": 1,\n\t\"51edu.com\": 1,\n\t\"51education.net\": 1,\n\t\"51etong.com\": 1,\n\t\"51ey.com\": 1,\n\t\"51f.com\": 1,\n\t\"51fanli.com\": 1,\n\t\"51fanli.net\": 1,\n\t\"51fdc.com\": 1,\n\t\"51fzflw.com\": 1,\n\t\"51fzh.com\": 1,\n\t\"51g3.com\": 1,\n\t\"51gaifang.com\": 1,\n\t\"51gaokao.net\": 1,\n\t\"51garlic.com\": 1,\n\t\"51gdrc.com\": 1,\n\t\"51ggwu.com\": 1,\n\t\"51grb.com\": 1,\n\t\"51hanhua.com\": 1,\n\t\"51haojob.com\": 1,\n\t\"51hbjob.com\": 1,\n\t\"51hcw.com\": 1,\n\t\"51hejia.com\": 1,\n\t\"51honest.org\": 1,\n\t\"51htxw.com\": 1,\n\t\"51hunter.net\": 1,\n\t\"51huoche.com\": 1,\n\t\"51idc.com\": 1,\n\t\"51iec.com\": 1,\n\t\"51ielts.com\": 1,\n\t\"51img1.com\": 1,\n\t\"51img3.com\": 1,\n\t\"51jam.com\": 1,\n\t\"51jb.com\": 1,\n\t\"51jiameng.com\": 1,\n\t\"51jiaxiao.com\": 1,\n\t\"51jiemeng.com\": 1,\n\t\"51jishu.com\": 1,\n\t\"51job.com\": 1,\n\t\"51jobcdn.com\": 1,\n\t\"51jrjob.com\": 1,\n\t\"51junshi.com\": 1,\n\t\"51kaihui.com\": 1,\n\t\"51kaishan.com\": 1,\n\t\"51kids.com\": 1,\n\t\"51kiosk.com\": 1,\n\t\"51kqn.com\": 1,\n\t\"51kybg.com\": 1,\n\t\"51la.net\": 1,\n\t\"51labour.com\": 1,\n\t\"51lama.com\": 1,\n\t\"51lenovo.com\": 1,\n\t\"51lieyou.com\": 1,\n\t\"51liucheng.com\": 1,\n\t\"51live.com\": 1,\n\t\"51lunwen.com\": 1,\n\t\"51lunwen.org\": 1,\n\t\"51lvsewang.com\": 1,\n\t\"51lxrc.com\": 1,\n\t\"51meishu.com\": 1,\n\t\"51mingche.com\": 1,\n\t\"51mingren.com\": 1,\n\t\"51mobilejob.com\": 1,\n\t\"51mole.com\": 1,\n\t\"51nacs.com\": 1,\n\t\"51nb.com\": 1,\n\t\"51neixun.com\": 1,\n\t\"51netu.com\": 1,\n\t\"51nianheji.com\": 1,\n\t\"51nuoqi.com\": 1,\n\t\"51offer.com\": 1,\n\t\"51office.com\": 1,\n\t\"51pigai.com\": 1,\n\t\"51pinwei.com\": 1,\n\t\"51pla.com\": 1,\n\t\"51pot.com\": 1,\n\t\"51ps.com\": 1,\n\t\"51psy.net\": 1,\n\t\"51qc.com\": 1,\n\t\"51qc.net\": 1,\n\t\"51qingjiao.com\": 1,\n\t\"51qinxue.com\": 1,\n\t\"51rattan.com\": 1,\n\t\"51rc.com\": 1,\n\t\"51rencai.com\": 1,\n\t\"51report.com\": 1,\n\t\"51room.net\": 1,\n\t\"51rrp.com\": 1,\n\t\"51scb.com\": 1,\n\t\"51sdjob.com\": 1,\n\t\"51seer.com\": 1,\n\t\"51shengyue.com\": 1,\n\t\"51sheyuan.com\": 1,\n\t\"51shiyan.com\": 1,\n\t\"51shoushi.com\": 1,\n\t\"51shworkshops.com\": 1,\n\t\"51sjyx.com\": 1,\n\t\"51sole.com\": 1,\n\t\"51soma.com\": 1,\n\t\"51ss.net\": 1,\n\t\"51stujob.com\": 1,\n\t\"51sxue.com\": 1,\n\t\"51sya.com\": 1,\n\t\"51t.com\": 1,\n\t\"51talk.com\": 1,\n\t\"51talkenglish.com\": 1,\n\t\"51taonan.com\": 1,\n\t\"51taoshi.com\": 1,\n\t\"51taoyang.com\": 1,\n\t\"51tbl.com\": 1,\n\t\"51test.net\": 1,\n\t\"51testbook.com\": 1,\n\t\"51tie.com\": 1,\n\t\"51toefl.com\": 1,\n\t\"51touch.com\": 1,\n\t\"51tujia.com\": 1,\n\t\"51tuzhi.com\": 1,\n\t\"51tz.com\": 1,\n\t\"51uuo.com\": 1,\n\t\"51value.com\": 1,\n\t\"51vv.com\": 1,\n\t\"51wan.com\": 1,\n\t\"51wan.la\": 1,\n\t\"51wf.com\": 1,\n\t\"51wp.com\": 1,\n\t\"51xly.com\": 1,\n\t\"51xuesheji.com\": 1,\n\t\"51yala.com\": 1,\n\t\"51ych.com\": 1,\n\t\"51yes.com\": 1,\n\t\"51yey.com\": 1,\n\t\"51yilu.com\": 1,\n\t\"51yoho.com\": 1,\n\t\"51you.com\": 1,\n\t\"51youcai.com\": 1,\n\t\"51yougo.com\": 1,\n\t\"51yuding.com\": 1,\n\t\"51yuming.net\": 1,\n\t\"51yys.com\": 1,\n\t\"51zd.net\": 1,\n\t\"51zhijia.com\": 1,\n\t\"51zhu.com\": 1,\n\t\"51zhucai.com\": 1,\n\t\"51zjob.com\": 1,\n\t\"51zjxm.com\": 1,\n\t\"51zlwx.com\": 1,\n\t\"51znt.com\": 1,\n\t\"51zr.com\": 1,\n\t\"51zsjc.com\": 1,\n\t\"51zsrcw.com\": 1,\n\t\"51ztzj.com\": 1,\n\t\"51zuoche.com\": 1,\n\t\"51zupu.com\": 1,\n\t\"51zx.com\": 1,\n\t\"51zxw.net\": 1,\n\t\"52.com\": 1,\n\t\"520.net\": 1,\n\t\"520apk.com\": 1,\n\t\"520bn.com\": 1,\n\t\"520cpw.com\": 1,\n\t\"520e3e4.com\": 1,\n\t\"520f.net\": 1,\n\t\"520ok.net\": 1,\n\t\"520tianmei.com\": 1,\n\t\"520ux.com\": 1,\n\t\"520wawa.com\": 1,\n\t\"520xy8.com\": 1,\n\t\"520zg.net\": 1,\n\t\"52114.org\": 1,\n\t\"52173.com\": 1,\n\t\"5219.net\": 1,\n\t\"521auto.com\": 1,\n\t\"521che.com\": 1,\n\t\"521g.com\": 1,\n\t\"522g.com\": 1,\n\t\"52372.com\": 1,\n\t\"52396.com\": 1,\n\t\"523che.com\": 1,\n\t\"523fang.com\": 1,\n\t\"5251.net\": 1,\n\t\"5253.com\": 1,\n\t\"525jmall.com\": 1,\n\t\"525zb.com\": 1,\n\t\"526wan.com\": 1,\n\t\"527k.com\": 1,\n\t\"527pk.com\": 1,\n\t\"5281.cc\": 1,\n\t\"5281.com\": 1,\n\t\"52954.com\": 1,\n\t\"52article.com\": 1,\n\t\"52bar.com\": 1,\n\t\"52bmw.com\": 1,\n\t\"52cake.net\": 1,\n\t\"52car.net\": 1,\n\t\"52ch.net\": 1,\n\t\"52che.com\": 1,\n\t\"52chizhou.com\": 1,\n\t\"52ciqi.com\": 1,\n\t\"52db.net\": 1,\n\t\"52design.com\": 1,\n\t\"52djq.com\": 1,\n\t\"52dopod.com\": 1,\n\t\"52e-mail.com\": 1,\n\t\"52ezx.com\": 1,\n\t\"52fangzi.com\": 1,\n\t\"52foto.com\": 1,\n\t\"52funs.com\": 1,\n\t\"52fuqing.com\": 1,\n\t\"52game.com\": 1,\n\t\"52guoman.com\": 1,\n\t\"52hardware.com\": 1,\n\t\"52hc.com\": 1,\n\t\"52hotel.net\": 1,\n\t\"52huapai.com\": 1,\n\t\"52huaqiao.com\": 1,\n\t\"52hxw.com\": 1,\n\t\"52ij.com\": 1,\n\t\"52jj.net\": 1,\n\t\"52kaoyan.com\": 1,\n\t\"52kl.net\": 1,\n\t\"52kmh.com\": 1,\n\t\"52liezheng.com\": 1,\n\t\"52liuzhou.com\": 1,\n\t\"52mh.cc\": 1,\n\t\"52miji.com\": 1,\n\t\"52njl.com\": 1,\n\t\"52njl.net\": 1,\n\t\"52op.net\": 1,\n\t\"52pcgame.net\": 1,\n\t\"52ph.com\": 1,\n\t\"52pk.com\": 1,\n\t\"52pk.net\": 1,\n\t\"52player.com\": 1,\n\t\"52psxt.com\": 1,\n\t\"52rd.com\": 1,\n\t\"52sales.net\": 1,\n\t\"52shehua.com\": 1,\n\t\"52solution.com\": 1,\n\t\"52steel.com\": 1,\n\t\"52suda.com\": 1,\n\t\"52swine.com\": 1,\n\t\"52th.net\": 1,\n\t\"52tian.net\": 1,\n\t\"52tlbb.com\": 1,\n\t\"52udl.com\": 1,\n\t\"52waha.com\": 1,\n\t\"52wubi.com\": 1,\n\t\"52wuhan.com\": 1,\n\t\"52wuling.com\": 1,\n\t\"52xiangyou.com\": 1,\n\t\"52xiaohuahui.com\": 1,\n\t\"52xsj.com\": 1,\n\t\"52xyz.com\": 1,\n\t\"52ykjob.com\": 1,\n\t\"52youju.com\": 1,\n\t\"52youxue.com\": 1,\n\t\"52z.com\": 1,\n\t\"52zhushan.com\": 1,\n\t\"52zikao.com\": 1,\n\t\"530312.net\": 1,\n\t\"531springs.com\": 1,\n\t\"533.com\": 1,\n\t\"5336.com\": 1,\n\t\"538538.com\": 1,\n\t\"5399.com\": 1,\n\t\"53999.net\": 1,\n\t\"53gou.com\": 1,\n\t\"53info.com\": 1,\n\t\"53kf.com\": 1,\n\t\"54086.com\": 1,\n\t\"54114.com\": 1,\n\t\"5433.com\": 1,\n\t\"54535.com\": 1,\n\t\"5460.net\": 1,\n\t\"54cn.net\": 1,\n\t\"54game.com\": 1,\n\t\"54hcz.com\": 1,\n\t\"54heb.com\": 1,\n\t\"54jj.com\": 1,\n\t\"54job.com\": 1,\n\t\"54kefu.net\": 1,\n\t\"54op.com\": 1,\n\t\"54paike.com\": 1,\n\t\"54pc.com\": 1,\n\t\"54qnr.com\": 1,\n\t\"54xsr.com\": 1,\n\t\"54yo.com\": 1,\n\t\"54youshi.com\": 1,\n\t\"55.cc\": 1,\n\t\"55.com\": 1,\n\t\"55.la\": 1,\n\t\"55167.com\": 1,\n\t\"55188.com\": 1,\n\t\"5523.com\": 1,\n\t\"55255.com\": 1,\n\t\"553.com\": 1,\n\t\"553000.com\": 1,\n\t\"553you.com\": 1,\n\t\"5555d.com\": 1,\n\t\"55577.com\": 1,\n\t\"5566.net\": 1,\n\t\"5566wan.com\": 1,\n\t\"556wan.com\": 1,\n\t\"557.net\": 1,\n\t\"5577.com\": 1,\n\t\"5588.tv\": 1,\n\t\"5588yx.com\": 1,\n\t\"5599.com\": 1,\n\t\"55bbs.com\": 1,\n\t\"55g.cc\": 1,\n\t\"55gps.com\": 1,\n\t\"55it.com\": 1,\n\t\"55la.com\": 1,\n\t\"55tuan.com\": 1,\n\t\"55tuanimg.com\": 1,\n\t\"55usedcar.com\": 1,\n\t\"55you.com\": 1,\n\t\"55zm.com\": 1,\n\t\"56.com\": 1,\n\t\"560731.com\": 1,\n\t\"56135.com\": 1,\n\t\"56156.com\": 1,\n\t\"5617.com\": 1,\n\t\"561hr.com\": 1,\n\t\"562wan.com\": 1,\n\t\"56360.com\": 1,\n\t\"56380.com\": 1,\n\t\"563wan.com\": 1,\n\t\"5648.cc\": 1,\n\t\"5652.com\": 1,\n\t\"566.com\": 1,\n\t\"5666.tv\": 1,\n\t\"566855.com\": 1,\n\t\"5669.com\": 1,\n\t\"566job.com\": 1,\n\t\"5676.com\": 1,\n\t\"5678job.com\": 1,\n\t\"567go.com\": 1,\n\t\"567job.com\": 1,\n\t\"56885.net\": 1,\n\t\"56888.net\": 1,\n\t\"569.com\": 1,\n\t\"5694.com\": 1,\n\t\"56bbw.com\": 1,\n\t\"56beijing.org\": 1,\n\t\"56golf.com\": 1,\n\t\"56img.com\": 1,\n\t\"56iq.com\": 1,\n\t\"56uu.com\": 1,\n\t\"56ye.net\": 1,\n\t\"57023.com\": 1,\n\t\"57315.com\": 1,\n\t\"57315.net\": 1,\n\t\"5757wan.com\": 1,\n\t\"576.com\": 1,\n\t\"57616.com\": 1,\n\t\"576rcw.com\": 1,\n\t\"576tv.com\": 1,\n\t\"5778.com\": 1,\n\t\"577fang.com\": 1,\n\t\"57821.com\": 1,\n\t\"57go.com\": 1,\n\t\"57nepal.com\": 1,\n\t\"57px.com\": 1,\n\t\"57tbs.com\": 1,\n\t\"57tibet.com\": 1,\n\t\"58.com\": 1,\n\t\"581518.com\": 1,\n\t\"582hr.com\": 1,\n\t\"585.com\": 1,\n\t\"5858.com\": 1,\n\t\"586jz.com\": 1,\n\t\"58728.net\": 1,\n\t\"5874.com\": 1,\n\t\"587766.com\": 1,\n\t\"5888.tv\": 1,\n\t\"588qh.com\": 1,\n\t\"58abc.net\": 1,\n\t\"58bama.com\": 1,\n\t\"58cyjm.com\": 1,\n\t\"58dm.com\": 1,\n\t\"58fenlei.com\": 1,\n\t\"58food.com\": 1,\n\t\"58game.com\": 1,\n\t\"58guakao.com\": 1,\n\t\"58gzw.com\": 1,\n\t\"58hukou.com\": 1,\n\t\"58pem.com\": 1,\n\t\"58pic.com\": 1,\n\t\"58player.com\": 1,\n\t\"58spx.com\": 1,\n\t\"58wan.com\": 1,\n\t\"58xzz.com\": 1,\n\t\"5911.com\": 1,\n\t\"591hx.com\": 1,\n\t\"591wed.com\": 1,\n\t\"591wy.com\": 1,\n\t\"5925car.com\": 1,\n\t\"59277.tv\": 1,\n\t\"592wg.cc\": 1,\n\t\"592xyx.com\": 1,\n\t\"593yx.com\": 1,\n\t\"5959.com\": 1,\n\t\"595wan.com\": 1,\n\t\"596fc.com\": 1,\n\t\"597.com\": 1,\n\t\"5973.com\": 1,\n\t\"597mm.com\": 1,\n\t\"597rcw.com\": 1,\n\t\"598rc.com\": 1,\n\t\"5999.tv\": 1,\n\t\"599z.com\": 1,\n\t\"59hq.com\": 1,\n\t\"59wujin.com\": 1,\n\t\"5aaa.com\": 1,\n\t\"5acbd.com\": 1,\n\t\"5aicp.com\": 1,\n\t\"5aipai.com\": 1,\n\t\"5ajob.com\": 1,\n\t\"5alz.com\": 1,\n\t\"5article.com\": 1,\n\t\"5aspx.com\": 1,\n\t\"5biying.com\": 1,\n\t\"5booking.com\": 1,\n\t\"5bzx.com\": 1,\n\t\"5d6d.com\": 1,\n\t\"5d6d.net\": 1,\n\t\"5dmx.com\": 1,\n\t\"5douy.com\": 1,\n\t\"5ds.com\": 1,\n\t\"5est.com\": 1,\n\t\"5etv.com\": 1,\n\t\"5fen.com\": 1,\n\t\"5fwan.com\": 1,\n\t\"5g.com\": 1,\n\t\"5haoxue.net\": 1,\n\t\"5hoom.com\": 1,\n\t\"5i5aj.com\": 1,\n\t\"5i5j.com\": 1,\n\t\"5i81.org\": 1,\n\t\"5i9u.com\": 1,\n\t\"5i9u.net\": 1,\n\t\"5icbs.com\": 1,\n\t\"5icool.org\": 1,\n\t\"5ijr.com\": 1,\n\t\"5ikfc.com\": 1,\n\t\"5ipatent.com\": 1,\n\t\"5ips.net\": 1,\n\t\"5its.com\": 1,\n\t\"5itx.com\": 1,\n\t\"5iucn.com\": 1,\n\t\"5iwl.com\": 1,\n\t\"5ixuexi.net\": 1,\n\t\"5iyq.com\": 1,\n\t\"5izhuangban.com\": 1,\n\t\"5jcao.com\": 1,\n\t\"5jss.com\": 1,\n\t\"5jzp.com\": 1,\n\t\"5kbox.com\": 1,\n\t\"5khouse.com\": 1,\n\t\"5ktd.com\": 1,\n\t\"5lux.com\": 1,\n\t\"5muu.com\": 1,\n\t\"5nd.com\": 1,\n\t\"5nexus.com\": 1,\n\t\"5o5k.com\": 1,\n\t\"5qv.net\": 1,\n\t\"5qwan.com\": 1,\n\t\"5sai.com\": 1,\n\t\"5u588.com\": 1,\n\t\"5ucom.com\": 1,\n\t\"5utaoke.com\": 1,\n\t\"5w.com\": 1,\n\t\"5wenxue.com\": 1,\n\t\"5x1job.com\": 1,\n\t\"5xueba.com\": 1,\n\t\"5ydj.com\": 1,\n\t\"5ygame.com\": 1,\n\t\"5yi.com\": 1,\n\t\"5zrc.com\": 1,\n\t\"60.cm\": 1,\n\t\"6000job.com\": 1,\n\t\"600258.com\": 1,\n\t\"600hr.com\": 1,\n\t\"600jp.com\": 1,\n\t\"602.com\": 1,\n\t\"606job.com\": 1,\n\t\"60886666.com\": 1,\n\t\"60junshi.com\": 1,\n\t\"60malaysia.com\": 1,\n\t\"61.com\": 1,\n\t\"6103.com\": 1,\n\t\"6111cq.com\": 1,\n\t\"61166.com\": 1,\n\t\"611wan.com\": 1,\n\t\"612.com\": 1,\n\t\"612345.com\": 1,\n\t\"6164.com\": 1,\n\t\"61658.com\": 1,\n\t\"616wan.com\": 1,\n\t\"6175.com\": 1,\n\t\"6188.com\": 1,\n\t\"6188cp.com\": 1,\n\t\"618hr.com\": 1,\n\t\"61baobao.com\": 1,\n\t\"61bbw.com\": 1,\n\t\"61bus.com\": 1,\n\t\"61diy.com\": 1,\n\t\"61duocai.com\": 1,\n\t\"61ertong.com\": 1,\n\t\"61f.com\": 1,\n\t\"61flash.com\": 1,\n\t\"61hr.com\": 1,\n\t\"61mami.com\": 1,\n\t\"61meiwen.com\": 1,\n\t\"61new.com\": 1,\n\t\"61tg.com\": 1,\n\t\"61un.com\": 1,\n\t\"61ux.com\": 1,\n\t\"61xue.com\": 1,\n\t\"6259114.net\": 1,\n\t\"628.com\": 1,\n\t\"628go.com\": 1,\n\t\"62b2b.com\": 1,\n\t\"6300.net\": 1,\n\t\"63063.com\": 1,\n\t\"637.fm\": 1,\n\t\"63hr.com\": 1,\n\t\"63wan.com\": 1,\n\t\"64365.com\": 1,\n\t\"65.com\": 1,\n\t\"6528.com\": 1,\n\t\"654buy.com\": 1,\n\t\"655u.com\": 1,\n\t\"655wan.com\": 1,\n\t\"65gz.com\": 1,\n\t\"65singapore.com\": 1,\n\t\"65wan.com\": 1,\n\t\"660wan.com\": 1,\n\t\"66163.com\": 1,\n\t\"6617.com\": 1,\n\t\"661d.com\": 1,\n\t\"6637.com\": 1,\n\t\"66378.com\": 1,\n\t\"6655.com\": 1,\n\t\"6665.com\": 1,\n\t\"666888.tv\": 1,\n\t\"666ccc.com\": 1,\n\t\"6676.com\": 1,\n\t\"6677bank.com\": 1,\n\t\"6681.com\": 1,\n\t\"66880.com\": 1,\n\t\"6688wan.com\": 1,\n\t\"668news.com\": 1,\n\t\"669art.com\": 1,\n\t\"66diqiu.com\": 1,\n\t\"66hao315.com\": 1,\n\t\"66house.com\": 1,\n\t\"66lv.com\": 1,\n\t\"66one.net\": 1,\n\t\"66qhd.com\": 1,\n\t\"66rpg.com\": 1,\n\t\"66ruian.com\": 1,\n\t\"66tuzhi.com\": 1,\n\t\"66u.com\": 1,\n\t\"66wc.com\": 1,\n\t\"66weibo.com\": 1,\n\t\"66wl.com\": 1,\n\t\"66wz.com\": 1,\n\t\"66xue.com\": 1,\n\t\"66you.com\": 1,\n\t\"66zhuang.com\": 1,\n\t\"67.com\": 1,\n\t\"6711.com\": 1,\n\t\"6777111.com\": 1,\n\t\"677game.com\": 1,\n\t\"678114.com\": 1,\n\t\"6789123.com\": 1,\n\t\"6789g.com\": 1,\n\t\"6789uu.com\": 1,\n\t\"679wan.com\": 1,\n\t\"680.com\": 1,\n\t\"6816.com\": 1,\n\t\"68211.com\": 1,\n\t\"685.com\": 1,\n\t\"6868g.com\": 1,\n\t\"688n.com\": 1,\n\t\"68apk.com\": 1,\n\t\"68design.net\": 1,\n\t\"68flash.com\": 1,\n\t\"68wan.com\": 1,\n\t\"68zhuan.com\": 1,\n\t\"6949.com\": 1,\n\t\"6969g.com\": 1,\n\t\"69js.com\": 1,\n\t\"69js.net\": 1,\n\t\"69kan.com\": 1,\n\t\"69xiu.com\": 1,\n\t\"69zw.com\": 1,\n\t\"6c6.com\": 1,\n\t\"6dad.com\": 1,\n\t\"6ddd.com\": 1,\n\t\"6down.net\": 1,\n\t\"6eat.com\": 1,\n\t\"6guilin.com\": 1,\n\t\"6jk.com\": 1,\n\t\"6luling.com\": 1,\n\t\"6niu.com\": 1,\n\t\"6pingm.com\": 1,\n\t\"6renyou.com\": 1,\n\t\"6rooms.com\": 1,\n\t\"6wan.com\": 1,\n\t\"6wang.cc\": 1,\n\t\"6xiu.com\": 1,\n\t\"6zrc.com\": 1,\n\t\"7-hk.com\": 1,\n\t\"70.com\": 1,\n\t\"700yx.com\": 1,\n\t\"701sou.com\": 1,\n\t\"703804.com\": 1,\n\t\"7060.com\": 1,\n\t\"70e.com\": 1,\n\t\"70god.com\": 1,\n\t\"70yx.com\": 1,\n\t\"71096.com\": 1,\n\t\"711g.com\": 1,\n\t\"7127.com\": 1,\n\t\"7160.com\": 1,\n\t\"717199.com\": 1,\n\t\"718cfw.com\": 1,\n\t\"7190.cc\": 1,\n\t\"7192.com\": 1,\n\t\"71gq.com\": 1,\n\t\"71lady.com\": 1,\n\t\"71p.net\": 1,\n\t\"71peixun.com\": 1,\n\t\"71study.com\": 1,\n\t\"71zs.com\": 1,\n\t\"72177.com\": 1,\n\t\"722300.net\": 1,\n\t\"7230.com\": 1,\n\t\"726100.com\": 1,\n\t\"72622.com\": 1,\n\t\"726ux.com\": 1,\n\t\"727.com\": 1,\n\t\"7273.com\": 1,\n\t\"72ce.com\": 1,\n\t\"72dj.com\": 1,\n\t\"72g.com\": 1,\n\t\"72up.com\": 1,\n\t\"72xuan.com\": 1,\n\t\"731c.com\": 1,\n\t\"733dm.com\": 1,\n\t\"7360.cc\": 1,\n\t\"737.com\": 1,\n\t\"7374.com\": 1,\n\t\"7377.com\": 1,\n\t\"738car.com\": 1,\n\t\"7399.com\": 1,\n\t\"73994.com\": 1,\n\t\"739hr.com\": 1,\n\t\"7474.com\": 1,\n\t\"7476.com\": 1,\n\t\"747wan.com\": 1,\n\t\"74cms.com\": 1,\n\t\"7599.com\": 1,\n\t\"75pk.com\": 1,\n\t\"761.com\": 1,\n\t\"7614.com\": 1,\n\t\"762rc.com\": 1,\n\t\"7651.com\": 1,\n\t\"766.com\": 1,\n\t\"7666.tv\": 1,\n\t\"766cn.com\": 1,\n\t\"766z.com\": 1,\n\t\"7676.com\": 1,\n\t\"76hai.com\": 1,\n\t\"76ju.com\": 1,\n\t\"76yc.com\": 1,\n\t\"7706.com\": 1,\n\t\"771wan.com\": 1,\n\t\"7723.com\": 1,\n\t\"7729.com\": 1,\n\t\"77313.com\": 1,\n\t\"774g.com\": 1,\n\t\"7755.com\": 1,\n\t\"77745.com\": 1,\n\t\"777fly.com\": 1,\n\t\"777wyx.com\": 1,\n\t\"777zp.com\": 1,\n\t\"778669.com\": 1,\n\t\"77883.com\": 1,\n\t\"7789.com\": 1,\n\t\"7799520.com\": 1,\n\t\"779you.com\": 1,\n\t\"77hh.com\": 1,\n\t\"77hunjia.com\": 1,\n\t\"77jz.com\": 1,\n\t\"77l.com\": 1,\n\t\"77music.com\": 1,\n\t\"77nt.com\": 1,\n\t\"77pvp.com\": 1,\n\t\"77vcd.com\": 1,\n\t\"77wan.cc\": 1,\n\t\"77y8.com\": 1,\n\t\"77zp.com\": 1,\n\t\"77zxw.com\": 1,\n\t\"7808.com\": 1,\n\t\"78187.com\": 1,\n\t\"7878.com\": 1,\n\t\"78793.com\": 1,\n\t\"787y.com\": 1,\n\t\"7881.com\": 1,\n\t\"788hr.com\": 1,\n\t\"788job.net\": 1,\n\t\"7899.cc\": 1,\n\t\"789gg.com\": 1,\n\t\"789hi.com\": 1,\n\t\"78baby.com\": 1,\n\t\"78dm.net\": 1,\n\t\"78oa.com\": 1,\n\t\"78zph.com\": 1,\n\t\"79.com\": 1,\n\t\"7937.com\": 1,\n\t\"7940.com\": 1,\n\t\"7979la.com\": 1,\n\t\"7979u.com\": 1,\n\t\"797sun.com\": 1,\n\t\"798edu.com\": 1,\n\t\"798play.com\": 1,\n\t\"798yx.com\": 1,\n\t\"798zxw.com\": 1,\n\t\"7999.tv\": 1,\n\t\"7999wan.com\": 1,\n\t\"799job.com\": 1,\n\t\"79abc.com\": 1,\n\t\"79w.com\": 1,\n\t\"7acg.com\": 1,\n\t\"7ahr.com\": 1,\n\t\"7bei.cc\": 1,\n\t\"7c.com\": 1,\n\t\"7cha.com\": 1,\n\t\"7czw.com\": 1,\n\t\"7dajiao.com\": 1,\n\t\"7dapei.com\": 1,\n\t\"7daysinn.biz\": 1,\n\t\"7djob.com\": 1,\n\t\"7do.net\": 1,\n\t\"7edown.com\": 1,\n\t\"7fgame.com\": 1,\n\t\"7h365.com\": 1,\n\t\"7hcn.com\": 1,\n\t\"7hhome.com\": 1,\n\t\"7hon.com\": 1,\n\t\"7iaoshou.com\": 1,\n\t\"7k7k.com\": 1,\n\t\"7kcc.com\": 1,\n\t\"7l7l.com\": 1,\n\t\"7lean.com\": 1,\n\t\"7mato.com\": 1,\n\t\"7mgame.com\": 1,\n\t\"7mo.cc\": 1,\n\t\"7mok.com\": 1,\n\t\"7po.com\": 1,\n\t\"7sgsoft.com\": 1,\n\t\"7tyy.com\": 1,\n\t\"7u7.net\": 1,\n\t\"7uyn.com\": 1,\n\t\"7vk.com\": 1,\n\t\"7wenta.com\": 1,\n\t\"7xdown.com\": 1,\n\t\"7xz.com\": 1,\n\t\"7y7.com\": 1,\n\t\"7yueji.com\": 1,\n\t\"7zhan.com\": 1,\n\t\"7zzy.com\": 1,\n\t\"8000ad.com\": 1,\n\t\"800400.net\": 1,\n\t\"8008200958.com\": 1,\n\t\"800fc.com\": 1,\n\t\"800hr.com\": 1,\n\t\"800pai.com\": 1,\n\t\"800pharm.com\": 1,\n\t\"8014.com\": 1,\n\t\"8020rc.com\": 1,\n\t\"802wan.com\": 1,\n\t\"804.com\": 1,\n\t\"80710.com\": 1,\n\t\"8080.net\": 1,\n\t\"8080wan.com\": 1,\n\t\"808707.com\": 1,\n\t\"8090.com\": 1,\n\t\"8090.tv\": 1,\n\t\"8090kk.com\": 1,\n\t\"8090vision.com\": 1,\n\t\"8090xx.com\": 1,\n\t\"8090yx.com\": 1,\n\t\"8090yxs.com\": 1,\n\t\"80data.net\": 1,\n\t\"80dyy.net\": 1,\n\t\"80tian.com\": 1,\n\t\"80xb.com\": 1,\n\t\"81256.com\": 1,\n\t\"81499.com\": 1,\n\t\"8158.com\": 1,\n\t\"8161.cc\": 1,\n\t\"818.com\": 1,\n\t\"818222.com\": 1,\n\t\"81874.com\": 1,\n\t\"818chuguo.net\": 1,\n\t\"81junhun.com\": 1,\n\t\"81tech.com\": 1,\n\t\"81un.net\": 1,\n\t\"82222919.com\": 1,\n\t\"82341.com\": 1,\n\t\"8234567.com\": 1,\n\t\"826.com\": 1,\n\t\"8264.com\": 1,\n\t\"8265.com\": 1,\n\t\"826wan.com\": 1,\n\t\"828g.com\": 1,\n\t\"82b2b.com\": 1,\n\t\"82yx.com\": 1,\n\t\"830836.com\": 1,\n\t\"83133.com\": 1,\n\t\"83480900.com\": 1,\n\t\"83838.com\": 1,\n\t\"83923888.com\": 1,\n\t\"844a.com\": 1,\n\t\"8477.com\": 1,\n\t\"84g.com\": 1,\n\t\"84ju.com\": 1,\n\t\"84ny.com\": 1,\n\t\"850505.net\": 1,\n\t\"85118.com\": 1,\n\t\"85277777.com\": 1,\n\t\"852wan.com\": 1,\n\t\"8558.com\": 1,\n\t\"855you.com\": 1,\n\t\"85814.com\": 1,\n\t\"859652.com\": 1,\n\t\"860527.com\": 1,\n\t\"860714.net\": 1,\n\t\"862sc.com\": 1,\n\t\"86516.com\": 1,\n\t\"8671.net\": 1,\n\t\"8682.cc\": 1,\n\t\"86838683.com\": 1,\n\t\"8684.com\": 1,\n\t\"86angel.com\": 1,\n\t\"86auto.com\": 1,\n\t\"86che.com\": 1,\n\t\"86chemnet.com\": 1,\n\t\"86control.com\": 1,\n\t\"86djy.com\": 1,\n\t\"86echr.com\": 1,\n\t\"86fsp.com\": 1,\n\t\"86garden.com\": 1,\n\t\"86hh.com\": 1,\n\t\"86jnjp.com\": 1,\n\t\"86jobs.com\": 1,\n\t\"86jzjob.com\": 1,\n\t\"86kx.com\": 1,\n\t\"86kyjob.com\": 1,\n\t\"86mdo.com\": 1,\n\t\"86name.com\": 1,\n\t\"86nb.com\": 1,\n\t\"86office.com\": 1,\n\t\"86pla.com\": 1,\n\t\"86ps.com\": 1,\n\t\"86qc.com\": 1,\n\t\"86sb.com\": 1,\n\t\"86signs.com\": 1,\n\t\"86sme.com\": 1,\n\t\"86techan.com\": 1,\n\t\"86tree.com\": 1,\n\t\"86wan.com\": 1,\n\t\"86wind.com\": 1,\n\t\"86xinxi.com\": 1,\n\t\"87050.com\": 1,\n\t\"87188718.com\": 1,\n\t\"8721.com\": 1,\n\t\"8783.com\": 1,\n\t\"8787g.com\": 1,\n\t\"8791.com\": 1,\n\t\"87dailian.com\": 1,\n\t\"87money.com\": 1,\n\t\"87pk.com\": 1,\n\t\"88.com\": 1,\n\t\"8800.org\": 1,\n\t\"88055116.com\": 1,\n\t\"880735.com\": 1,\n\t\"88119966.com\": 1,\n\t\"8813yx.com\": 1,\n\t\"88152.com\": 1,\n\t\"8825.com\": 1,\n\t\"8855.org\": 1,\n\t\"8864.com\": 1,\n\t\"88680.com\": 1,\n\t\"887g.com\": 1,\n\t\"887you.com\": 1,\n\t\"8884321.com\": 1,\n\t\"889xp.com\": 1,\n\t\"88db.com\": 1,\n\t\"88dj.com\": 1,\n\t\"88gogo.com\": 1,\n\t\"88gs.com\": 1,\n\t\"88j84.com\": 1,\n\t\"88jh.com\": 1,\n\t\"88kuka.com\": 1,\n\t\"88lan.com\": 1,\n\t\"88mh.com\": 1,\n\t\"88order.com\": 1,\n\t\"88tc.com\": 1,\n\t\"88yn.com\": 1,\n\t\"88yoo.com\": 1,\n\t\"88yx.com\": 1,\n\t\"88yz.com\": 1,\n\t\"88zf.com\": 1,\n\t\"890pk.com\": 1,\n\t\"89178.com\": 1,\n\t\"893.cc\": 1,\n\t\"89902511.com\": 1,\n\t\"8999wan.com\": 1,\n\t\"89ws.com\": 1,\n\t\"89xd.com\": 1,\n\t\"8breed.com\": 1,\n\t\"8cheche.com\": 1,\n\t\"8dn.com\": 1,\n\t\"8edy.com\": 1,\n\t\"8fkd.com\": 1,\n\t\"8gl.com\": 1,\n\t\"8gongzi.com\": 1,\n\t\"8hy.org\": 1,\n\t\"8ke.org\": 1,\n\t\"8l8e.com\": 1,\n\t\"8le8le.com\": 1,\n\t\"8lnet.com\": 1,\n\t\"8lw.org\": 1,\n\t\"8mhh.com\": 1,\n\t\"8yee.com\": 1,\n\t\"8ztc.com\": 1,\n\t\"900.la\": 1,\n\t\"900gold.com\": 1,\n\t\"90576.com\": 1,\n\t\"90912.com\": 1,\n\t\"90fer.com\": 1,\n\t\"90he.com\": 1,\n\t\"90tiyu.com\": 1,\n\t\"91.com\": 1,\n\t\"9111.tv\": 1,\n\t\"91120.com\": 1,\n\t\"9117hi.com\": 1,\n\t\"911xs.com\": 1,\n\t\"911you.com\": 1,\n\t\"913u.com\": 1,\n\t\"915.com\": 1,\n\t\"9158.com\": 1,\n\t\"917.com\": 1,\n\t\"9188.com\": 1,\n\t\"9188wan.com\": 1,\n\t\"918jin.com\": 1,\n\t\"918s.com\": 1,\n\t\"9191mr.com\": 1,\n\t\"9199.com\": 1,\n\t\"91ac.com\": 1,\n\t\"91accp.com\": 1,\n\t\"91aiyx.com\": 1,\n\t\"91b2b.com\": 1,\n\t\"91baiju.com\": 1,\n\t\"91cha.com\": 1,\n\t\"91cps.com\": 1,\n\t\"91cye.com\": 1,\n\t\"91danji.com\": 1,\n\t\"91feizhuliu.com\": 1,\n\t\"91goodschool.com\": 1,\n\t\"91haojob.com\": 1,\n\t\"91ielts.com\": 1,\n\t\"91jiafang.com\": 1,\n\t\"91jm.com\": 1,\n\t\"91jmw.com\": 1,\n\t\"91job.com\": 1,\n\t\"91jsj.com\": 1,\n\t\"91lx.com\": 1,\n\t\"91lx.org\": 1,\n\t\"91metal.com\": 1,\n\t\"91office.com\": 1,\n\t\"91px.com\": 1,\n\t\"91rb.com\": 1,\n\t\"91rencai.com\": 1,\n\t\"91spj.com\": 1,\n\t\"91student.com\": 1,\n\t\"91tea.net\": 1,\n\t\"91toefl.com\": 1,\n\t\"91town.com\": 1,\n\t\"91wan.com\": 1,\n\t\"91weile.com\": 1,\n\t\"91xbkm.com\": 1,\n\t\"91zhongkao.com\": 1,\n\t\"9211.com\": 1,\n\t\"921rc.com\": 1,\n\t\"92296.com\": 1,\n\t\"925pk.com\": 1,\n\t\"927953.com\": 1,\n\t\"927vip.com\": 1,\n\t\"92913.com\": 1,\n\t\"92ay.com\": 1,\n\t\"92gzc.com\": 1,\n\t\"92ha.com\": 1,\n\t\"92mp.com\": 1,\n\t\"92sns.com\": 1,\n\t\"92wudao.com\": 1,\n\t\"92wy.com\": 1,\n\t\"92you.com\": 1,\n\t\"92zc.com\": 1,\n\t\"9351.com\": 1,\n\t\"9355.com\": 1,\n\t\"9377.com\": 1,\n\t\"93pk.com\": 1,\n\t\"93rc.com\": 1,\n\t\"93tyy.com\": 1,\n\t\"94117.net\": 1,\n\t\"94176.com\": 1,\n\t\"9453job.com\": 1,\n\t\"94656.com\": 1,\n\t\"9466.com\": 1,\n\t\"9487.com\": 1,\n\t\"94rc.com\": 1,\n\t\"95095.com\": 1,\n\t\"95191.com\": 1,\n\t\"951it.com\": 1,\n\t\"9527baby.com\": 1,\n\t\"9527lady.com\": 1,\n\t\"955113.com\": 1,\n\t\"9553.com\": 1,\n\t\"95572.com\": 1,\n\t\"9564.com\": 1,\n\t\"9588.com\": 1,\n\t\"958shop.com\": 1,\n\t\"959.cc\": 1,\n\t\"9595wan.com\": 1,\n\t\"95gq.com\": 1,\n\t\"95px.com\": 1,\n\t\"9600169.net\": 1,\n\t\"960755.com\": 1,\n\t\"960rc.com\": 1,\n\t\"962.net\": 1,\n\t\"962013.com\": 1,\n\t\"9637.com\": 1,\n\t\"96399.org\": 1,\n\t\"96520.com\": 1,\n\t\"96555.cc\": 1,\n\t\"96567.com\": 1,\n\t\"96580.com\": 1,\n\t\"966.com\": 1,\n\t\"9666sr.com\": 1,\n\t\"966733.com\": 1,\n\t\"9669.com\": 1,\n\t\"96785.org\": 1,\n\t\"968tl.com\": 1,\n\t\"969g.com\": 1,\n\t\"96ak.com\": 1,\n\t\"96hq.com\": 1,\n\t\"96pk.com\": 1,\n\t\"96scsh.com\": 1,\n\t\"96u.com\": 1,\n\t\"9724.com\": 1,\n\t\"973.com\": 1,\n\t\"97616.net\": 1,\n\t\"9777wan.com\": 1,\n\t\"9787.com\": 1,\n\t\"97973.com\": 1,\n\t\"9797ly.com\": 1,\n\t\"97ba.com\": 1,\n\t\"97ic.com\": 1,\n\t\"97jz.com\": 1,\n\t\"97ls.com\": 1,\n\t\"97wanle.com\": 1,\n\t\"97zm.com\": 1,\n\t\"9844.cc\": 1,\n\t\"98523.com\": 1,\n\t\"98654.com\": 1,\n\t\"987.cc\": 1,\n\t\"987jy.com\": 1,\n\t\"987k.com\": 1,\n\t\"98892.com\": 1,\n\t\"988yx.com\": 1,\n\t\"9891.com\": 1,\n\t\"98nba.com\": 1,\n\t\"98player.com\": 1,\n\t\"98ps.com\": 1,\n\t\"98wine.com\": 1,\n\t\"98znz.com\": 1,\n\t\"99.com\": 1,\n\t\"99114.com\": 1,\n\t\"99166.com\": 1,\n\t\"9928.tv\": 1,\n\t\"992you.com\": 1,\n\t\"9939.com\": 1,\n\t\"99425.com\": 1,\n\t\"99447.com\": 1,\n\t\"9949.com\": 1,\n\t\"996.com\": 1,\n\t\"9966333.com\": 1,\n\t\"99809.com\": 1,\n\t\"999.com\": 1,\n\t\"9991.com\": 1,\n\t\"999120.com\": 1,\n\t\"999120.net\": 1,\n\t\"9998.tv\": 1,\n\t\"999ask.com\": 1,\n\t\"999lyk.com\": 1,\n\t\"999wan.com\": 1,\n\t\"99ashw.com\": 1,\n\t\"99bill.com\": 1,\n\t\"99cad.com\": 1,\n\t\"99cfw.com\": 1,\n\t\"99danji.com\": 1,\n\t\"99edu.net\": 1,\n\t\"99fang.com\": 1,\n\t\"99fund.com\": 1,\n\t\"99hots.com\": 1,\n\t\"99inf.com\": 1,\n\t\"99jee.com\": 1,\n\t\"99jianzhu.com\": 1,\n\t\"99jxw.com\": 1,\n\t\"99leba.com\": 1,\n\t\"99mc.com\": 1,\n\t\"99oushi.org\": 1,\n\t\"99qh.com\": 1,\n\t\"99qumingzi.com\": 1,\n\t\"99rfid.com\": 1,\n\t\"99sjyx.com\": 1,\n\t\"99sushe.com\": 1,\n\t\"99wed.com\": 1,\n\t\"99xcs.com\": 1,\n\t\"99xr.com\": 1,\n\t\"99xyx.com\": 1,\n\t\"99ys.com\": 1,\n\t\"99yx.com\": 1,\n\t\"99zihua.com\": 1,\n\t\"99zuowen.com\": 1,\n\t\"9aoduo.com\": 1,\n\t\"9ask.com\": 1,\n\t\"9ban.com\": 1,\n\t\"9buys.com\": 1,\n\t\"9che.com\": 1,\n\t\"9chew.com\": 1,\n\t\"9chun.com\": 1,\n\t\"9cka.com\": 1,\n\t\"9ddf.com\": 1,\n\t\"9fbank.com\": 1,\n\t\"9fzs.com\": 1,\n\t\"9hello.com\": 1,\n\t\"9hiwan.com\": 1,\n\t\"9ht.com\": 1,\n\t\"9hyou.com\": 1,\n\t\"9i2s.com\": 1,\n\t\"9ihome.com\": 1,\n\t\"9ijia.com\": 1,\n\t\"9ijm.com\": 1,\n\t\"9ijr.com\": 1,\n\t\"9ist.com\": 1,\n\t\"9jcw.com\": 1,\n\t\"9juren.com\": 1,\n\t\"9jut.com\": 1,\n\t\"9jwan.com\": 1,\n\t\"9k9k.com\": 1,\n\t\"9k9k99k.com\": 1,\n\t\"9ku.com\": 1,\n\t\"9miao.com\": 1,\n\t\"9ria.com\": 1,\n\t\"9sky.com\": 1,\n\t\"9suv.com\": 1,\n\t\"9to.com\": 1,\n\t\"9tu.cc\": 1,\n\t\"9twan.com\": 1,\n\t\"9u.com\": 1,\n\t\"9u8u.com\": 1,\n\t\"9upk.com\": 1,\n\t\"9v8v.com\": 1,\n\t\"9vwan.com\": 1,\n\t\"9wan.com\": 1,\n\t\"9xiqi.com\": 1,\n\t\"9xwang.com\": 1,\n\t\"9yaocn.com\": 1,\n\t\"9ye.com\": 1,\n\t\"9you.com\": 1,\n\t\"9zhen.com\": 1,\n\t\"9zsb.com\": 1,\n\t\"a0598.com\": 1,\n\t\"a0816.com\": 1,\n\t\"a0bi.com\": 1,\n\t\"a135.net\": 1,\n\t\"a21yishion.com\": 1,\n\t\"a22.com\": 1,\n\t\"a5588.com\": 1,\n\t\"a67.com\": 1,\n\t\"a688888.com\": 1,\n\t\"a8888.com\": 1,\n\t\"a9188.com\": 1,\n\t\"a963.com\": 1,\n\t\"a963.net\": 1,\n\t\"a9jj.com\": 1,\n\t\"a9soft.com\": 1,\n\t\"a9vg.com\": 1,\n\t\"aan5.com\": 1,\n\t\"aatuzhi.com\": 1,\n\t\"abab.com\": 1,\n\t\"abang.com\": 1,\n\t\"abc788.com\": 1,\n\t\"abcache.com\": 1,\n\t\"abcdao.com\": 1,\n\t\"abchina.com\": 1,\n\t\"abiz.com\": 1,\n\t\"ablesky.com\": 1,\n\t\"accgame.com\": 1,\n\t\"accorhotels.com\": 1,\n\t\"acdorm.com\": 1,\n\t\"acfechina.org\": 1,\n\t\"acftu.net\": 1,\n\t\"acftu.org\": 1,\n\t\"acfun.com\": 1,\n\t\"acfun.tv\": 1,\n\t\"acg.tv\": 1,\n\t\"acgmall.com\": 1,\n\t\"acgwan.com\": 1,\n\t\"acs86.com\": 1,\n\t\"actoys.net\": 1,\n\t\"ad1111.com\": 1,\n\t\"ad189.com\": 1,\n\t\"ad63.com\": 1,\n\t\"addpv.com\": 1,\n\t\"adhhouse.com\": 1,\n\t\"adjol.com\": 1,\n\t\"adjyc.com\": 1,\n\t\"admaimai.com\": 1,\n\t\"admin10000.com\": 1,\n\t\"admin5.com\": 1,\n\t\"admin5.net\": 1,\n\t\"admin6.com\": 1,\n\t\"adminxy.com\": 1,\n\t\"adnxs.com\": 1,\n\t\"adobe.com\": 1,\n\t\"adpolestar.net\": 1,\n\t\"adquan.com\": 1,\n\t\"adroll.com\": 1,\n\t\"ads8.com\": 1,\n\t\"adsage.com\": 1,\n\t\"adsame.com\": 1,\n\t\"adsonar.com\": 1,\n\t\"adtchrome.com\": 1,\n\t\"adtechus.com\": 1,\n\t\"adunioncode.com\": 1,\n\t\"adyun.com\": 1,\n\t\"aeenets.com\": 1,\n\t\"af360.com\": 1,\n\t\"afjk.com\": 1,\n\t\"afjob88.com\": 1,\n\t\"afnhk.com\": 1,\n\t\"aft888.com\": 1,\n\t\"afuchina.com\": 1,\n\t\"afuzg.com\": 1,\n\t\"afwing.com\": 1,\n\t\"afz.cc\": 1,\n\t\"afzhan.com\": 1,\n\t\"ag365.com\": 1,\n\t\"agjob.net\": 1,\n\t\"agrisg.com\": 1,\n\t\"agrodt.com\": 1,\n\t\"agrofairs.com\": 1,\n\t\"agrofed.com\": 1,\n\t\"agronf.com\": 1,\n\t\"agronj.com\": 1,\n\t\"agrorc.com\": 1,\n\t\"agrosc.com\": 1,\n\t\"agrosg.com\": 1,\n\t\"agrowsw.com\": 1,\n\t\"agroxq.com\": 1,\n\t\"agroyl.com\": 1,\n\t\"agui.cc\": 1,\n\t\"ah163.net\": 1,\n\t\"ah3nong.com\": 1,\n\t\"ahage.net\": 1,\n\t\"ahauto.com\": 1,\n\t\"ahbb.cc\": 1,\n\t\"ahbzfdc.com\": 1,\n\t\"ahbztv.com\": 1,\n\t\"ahcar.com\": 1,\n\t\"ahchanyi.com\": 1,\n\t\"ahctc.com\": 1,\n\t\"ahdznews.com\": 1,\n\t\"ahfeixi.com\": 1,\n\t\"ahgame.com\": 1,\n\t\"ahglj.com\": 1,\n\t\"ahhntz.com\": 1,\n\t\"ahhome.com\": 1,\n\t\"ahhouse.com\": 1,\n\t\"ahhy.net\": 1,\n\t\"ahhzl.com\": 1,\n\t\"ahjdq.com\": 1,\n\t\"ahjia.com\": 1,\n\t\"ahjiaju.com\": 1,\n\t\"ahjs.net\": 1,\n\t\"ahjtxx.com\": 1,\n\t\"ahlife.com\": 1,\n\t\"ahljnews.com\": 1,\n\t\"ahlongre.com\": 1,\n\t\"ahlottery.com\": 1,\n\t\"ahlsg.com\": 1,\n\t\"ahly.cc\": 1,\n\t\"ahlydc.com\": 1,\n\t\"ahnews.org\": 1,\n\t\"ahnxs.com\": 1,\n\t\"ahsalt.com\": 1,\n\t\"ahscb.com\": 1,\n\t\"ahsjxjy.com\": 1,\n\t\"ahsouche.com\": 1,\n\t\"ahss168.com\": 1,\n\t\"ahssnews.com\": 1,\n\t\"ahswine.com\": 1,\n\t\"ahsz.tv\": 1,\n\t\"ahszjob.com\": 1,\n\t\"ahtarena.com\": 1,\n\t\"ahtarena.net\": 1,\n\t\"ahtrader.com\": 1,\n\t\"ahwjnews.com\": 1,\n\t\"ahzp.com\": 1,\n\t\"ai0513.com\": 1,\n\t\"aibala.com\": 1,\n\t\"aibang.com\": 1,\n\t\"aibangjuxin.com\": 1,\n\t\"aibeiwang.com\": 1,\n\t\"aibo123.com\": 1,\n\t\"aicai.com\": 1,\n\t\"aicaicdn.com\": 1,\n\t\"aicairen.com\": 1,\n\t\"aicarzu.com\": 1,\n\t\"aicdn.com\": 1,\n\t\"aicunfu.com\": 1,\n\t\"aidigong.com\": 1,\n\t\"aidonghai.com\": 1,\n\t\"aifang.com\": 1,\n\t\"aifanggou.com\": 1,\n\t\"aifangke.com\": 1,\n\t\"aifcdn.com\": 1,\n\t\"aifeipin.com\": 1,\n\t\"aifengjie.com\": 1,\n\t\"aifmb.com\": 1,\n\t\"aigexing.com\": 1,\n\t\"aigo.com\": 1,\n\t\"aigounet.com\": 1,\n\t\"aihami.com\": 1,\n\t\"aihuaan.com\": 1,\n\t\"aihuaju.com\": 1,\n\t\"aiimg.com\": 1,\n\t\"aijunwang.com\": 1,\n\t\"aik120.com\": 1,\n\t\"aiketour.com\": 1,\n\t\"aikuirui.com\": 1,\n\t\"aili.com\": 1,\n\t\"ailiuwa.com\": 1,\n\t\"ailushan.com\": 1,\n\t\"ailvxing.com\": 1,\n\t\"aimuju.com\": 1,\n\t\"aipai.com\": 1,\n\t\"aipiaoke.com\": 1,\n\t\"aipingxiang.com\": 1,\n\t\"aipintuan.com\": 1,\n\t\"aips.me\": 1,\n\t\"aiqin88.com\": 1,\n\t\"airchinagroup.com\": 1,\n\t\"airjipiao.com\": 1,\n\t\"airmate-china.com\": 1,\n\t\"airmb.com\": 1,\n\t\"aisbeijing.com\": 1,\n\t\"aishengri.com\": 1,\n\t\"aisy.com\": 1,\n\t\"ait123.com\": 1,\n\t\"aitaoad.com\": 1,\n\t\"aitingwang.com\": 1,\n\t\"aituan.com\": 1,\n\t\"aituwo.com\": 1,\n\t\"aiutrip.com\": 1,\n\t\"aiwanyizu.com\": 1,\n\t\"aiwou.com\": 1,\n\t\"aixingpin.com\": 1,\n\t\"aixueche.com\": 1,\n\t\"aiyeyou.com\": 1,\n\t\"aiyidu.com\": 1,\n\t\"aiyijob.com\": 1,\n\t\"aiyingli.com\": 1,\n\t\"aiyiqu.com\": 1,\n\t\"aiyouxi.com\": 1,\n\t\"aiyuncheng.com\": 1,\n\t\"aizhan.com\": 1,\n\t\"aizhishang.com\": 1,\n\t\"aizongyi.com\": 1,\n\t\"ajbox.com\": 1,\n\t\"ajbtv.com\": 1,\n\t\"ajfcw.net\": 1,\n\t\"ajiang.net\": 1,\n\t\"ajkcdn.com\": 1,\n\t\"ajkimg.com\": 1,\n\t\"ajwang.com\": 1,\n\t\"akangdi.com\": 1,\n\t\"akdanji.com\": 1,\n\t\"akjunshi.com\": 1,\n\t\"aksrc.com\": 1,\n\t\"aksxw.com\": 1,\n\t\"al93.com\": 1,\n\t\"aladd.net\": 1,\n\t\"aladingyidong.com\": 1,\n\t\"ali213.com\": 1,\n\t\"ali213.net\": 1,\n\t\"ali37.net\": 1,\n\t\"alibaba.com\": 1,\n\t\"alibado.com\": 1,\n\t\"alibbw.com\": 1,\n\t\"alibole.com\": 1,\n\t\"alibuybuy.com\": 1,\n\t\"alicdn.com\": 1,\n\t\"alidanji.com\": 1,\n\t\"aliexpress.com\": 1,\n\t\"alihuahua.com\": 1,\n\t\"alihz.com\": 1,\n\t\"aliimg.com\": 1,\n\t\"aliloan.com\": 1,\n\t\"alimama.com\": 1,\n\t\"alipay.com\": 1,\n\t\"alipayobjects.com\": 1,\n\t\"aliresearch.com\": 1,\n\t\"alisoft.com\": 1,\n\t\"aliunicorn.com\": 1,\n\t\"alivv.com\": 1,\n\t\"alixixi.com\": 1,\n\t\"aliyiba.com\": 1,\n\t\"aliyun.com\": 1,\n\t\"aliyuncdn.com\": 1,\n\t\"aliyuncs.com\": 1,\n\t\"allallyes.com\": 1,\n\t\"allbrightlaw.com\": 1,\n\t\"allcates.com\": 1,\n\t\"allfang.com\": 1,\n\t\"alltriple.com\": 1,\n\t\"allyes.com\": 1,\n\t\"altxw.com\": 1,\n\t\"alu1886.com\": 1,\n\t\"alwindoor.com\": 1,\n\t\"alwooo.com\": 1,\n\t\"alxw.com\": 1,\n\t\"alyisheng.com\": 1,\n\t\"amannisha.com\": 1,\n\t\"amaomb.com\": 1,\n\t\"amap.com\": 1,\n\t\"amazon.com\": 1,\n\t\"ambafrance-cn.org\": 1,\n\t\"ambchina.com\": 1,\n\t\"amchamchina.org\": 1,\n\t\"amerealtygroup.com\": 1,\n\t\"ami001.com\": 1,\n\t\"ampcn.com\": 1,\n\t\"amutong.com\": 1,\n\t\"anbingsoft.net\": 1,\n\t\"andaike.com\": 1,\n\t\"androidonline.net\": 1,\n\t\"anfan.com\": 1,\n\t\"anfensi.com\": 1,\n\t\"angeeks.com\": 1,\n\t\"angelyeast.com\": 1,\n\t\"anguanjia.com\": 1,\n\t\"anhuaw.com\": 1,\n\t\"anhui.cc\": 1,\n\t\"anhuinews.com\": 1,\n\t\"anjia.com\": 1,\n\t\"anjiala.com\": 1,\n\t\"anjian.com\": 1,\n\t\"anjirencai.com\": 1,\n\t\"anjuke.com\": 1,\n\t\"anjukestatic.com\": 1,\n\t\"ankang.biz\": 1,\n\t\"ankang06.org\": 1,\n\t\"ankangs.com\": 1,\n\t\"ankangwang.com\": 1,\n\t\"anqingonline.com\": 1,\n\t\"anqu.com\": 1,\n\t\"anquan.org\": 1,\n\t\"anquan365.com\": 1,\n\t\"anquanbao.com\": 1,\n\t\"anquanren.com\": 1,\n\t\"anquanshi.com\": 1,\n\t\"anquye123.com\": 1,\n\t\"anruan.com\": 1,\n\t\"anshunjob.net\": 1,\n\t\"ansteelgroup.com\": 1,\n\t\"anting.com\": 1,\n\t\"antong.org\": 1,\n\t\"anxi.com\": 1,\n\t\"anxin.com\": 1,\n\t\"anxinews.com\": 1,\n\t\"anxinwh.com\": 1,\n\t\"anxiw.com\": 1,\n\t\"any2000.com\": 1,\n\t\"anyangedu.com\": 1,\n\t\"anychem.com\": 1,\n\t\"anyisheng.com\": 1,\n\t\"anymacro.com\": 1,\n\t\"anyv.net\": 1,\n\t\"anzbc.com\": 1,\n\t\"anzhi.com\": 1,\n\t\"anzhuo2.com\": 1,\n\t\"anzhuostore.com\": 1,\n\t\"anzow.com\": 1,\n\t\"anzuche.com\": 1,\n\t\"aoaob.com\": 1,\n\t\"aobi.com\": 1,\n\t\"aobosoft.com\": 1,\n\t\"aodi.com\": 1,\n\t\"aodiango.com\": 1,\n\t\"aofenglu.com\": 1,\n\t\"aojiyouxue.com\": 1,\n\t\"aojiyuke.com\": 1,\n\t\"aokang.com\": 1,\n\t\"aol.com\": 1,\n\t\"aolaituan.com\": 1,\n\t\"aoliday.com\": 1,\n\t\"aooshe.com\": 1,\n\t\"aoqi168.com\": 1,\n\t\"aoshitang.com\": 1,\n\t\"aoshu.com\": 1,\n\t\"aosoo.com\": 1,\n\t\"aotian.com\": 1,\n\t\"aotrip.net\": 1,\n\t\"aotudq.com\": 1,\n\t\"aowin.com\": 1,\n\t\"aoya-hk.com\": 1,\n\t\"aoyou.cc\": 1,\n\t\"aoyou.com\": 1,\n\t\"aoyuyj.com\": 1,\n\t\"ap88.com\": 1,\n\t\"apec-ecba.org\": 1,\n\t\"apendi.com\": 1,\n\t\"apetdog.com\": 1,\n\t\"apidc.net\": 1,\n\t\"apinpai.com\": 1,\n\t\"apk3g.com\": 1,\n\t\"apk90.com\": 1,\n\t\"apkbus.com\": 1,\n\t\"apkol.com\": 1,\n\t\"apkyx.com\": 1,\n\t\"apkzu.com\": 1,\n\t\"aplmf.org\": 1,\n\t\"apoints.com\": 1,\n\t\"app111.com\": 1,\n\t\"app111.org\": 1,\n\t\"app17.com\": 1,\n\t\"apparelsos.com\": 1,\n\t\"appchina.com\": 1,\n\t\"appcms.cc\": 1,\n\t\"appdp.com\": 1,\n\t\"apper8.com\": 1,\n\t\"appgame.com\": 1,\n\t\"appinn.com\": 1,\n\t\"appjzy.com\": 1,\n\t\"apple.com\": 1,\n\t\"appvv.com\": 1,\n\t\"appying.com\": 1,\n\t\"aptchina.com\": 1,\n\t\"apusic.com\": 1,\n\t\"aq365.com\": 1,\n\t\"aqapk.com\": 1,\n\t\"aqbbw.com\": 1,\n\t\"aqbz.org\": 1,\n\t\"aqioo.com\": 1,\n\t\"aqqiche.com\": 1,\n\t\"aqqx.com\": 1,\n\t\"aqrczp.com\": 1,\n\t\"aqrenren.com\": 1,\n\t\"aqtg.com\": 1,\n\t\"aqtour.com\": 1,\n\t\"aqw.cc\": 1,\n\t\"aqwblm.com\": 1,\n\t\"aqzbcg.org\": 1,\n\t\"aqzpw.com\": 1,\n\t\"aqzyzx.com\": 1,\n\t\"aringhb.com\": 1,\n\t\"arkoo.com\": 1,\n\t\"armystar.com\": 1,\n\t\"arpg2.com\": 1,\n\t\"arpun.com\": 1,\n\t\"art-ba-ba.com\": 1,\n\t\"art-child.com\": 1,\n\t\"art-liuxue.com\": 1,\n\t\"art-zj.com\": 1,\n\t\"art139.com\": 1,\n\t\"art456.com\": 1,\n\t\"artbeijing.net\": 1,\n\t\"artddu.com\": 1,\n\t\"artebuy.com\": 1,\n\t\"artgoin.com\": 1,\n\t\"artguangxi.com\": 1,\n\t\"arthoop.com\": 1,\n\t\"artimg.net\": 1,\n\t\"arting365.com\": 1,\n\t\"artintern.net\": 1,\n\t\"artjingya.com\": 1,\n\t\"artmotions.net\": 1,\n\t\"artohe.com\": 1,\n\t\"artohes.com\": 1,\n\t\"artoto.net\": 1,\n\t\"artrade.com\": 1,\n\t\"artron.net\": 1,\n\t\"artsbuy.com\": 1,\n\t\"arttz.net\": 1,\n\t\"artweekip.com\": 1,\n\t\"artxun.com\": 1,\n\t\"asdf37.com\": 1,\n\t\"asean-china-center.org\": 1,\n\t\"aseantradecenter.com\": 1,\n\t\"asgajj.com\": 1,\n\t\"ashsh.com\": 1,\n\t\"asiabt.com\": 1,\n\t\"asiachinachina.com\": 1,\n\t\"askci.com\": 1,\n\t\"askt7.com\": 1,\n\t\"aslzw.com\": 1,\n\t\"asp168.com\": 1,\n\t\"asp300.com\": 1,\n\t\"aspirecn.com\": 1,\n\t\"aspjzy.com\": 1,\n\t\"aspoo.com\": 1,\n\t\"asqql.com\": 1,\n\t\"asscb.com\": 1,\n\t\"asuswork.com\": 1,\n\t\"at188.com\": 1,\n\t\"ataozx.com\": 1,\n\t\"ataw-art.com\": 1,\n\t\"atdmt.com\": 1,\n\t\"atobo.com\": 1,\n\t\"atpanel.com\": 1,\n\t\"auak.com\": 1,\n\t\"audio160.com\": 1,\n\t\"auditcn.com\": 1,\n\t\"aushome.info\": 1,\n\t\"ausingroup.com\": 1,\n\t\"ausinvisa.com\": 1,\n\t\"austargroup.com\": 1,\n\t\"auto-made.com\": 1,\n\t\"auto0722.com\": 1,\n\t\"auto0754.com\": 1,\n\t\"auto0760.com\": 1,\n\t\"auto0768.com\": 1,\n\t\"auto18.com\": 1,\n\t\"auto318.com\": 1,\n\t\"auto328.com\": 1,\n\t\"auto373.com\": 1,\n\t\"autobaidu.com\": 1,\n\t\"autobaojun.com\": 1,\n\t\"autochina360.com\": 1,\n\t\"autodg.com\": 1,\n\t\"autoho.com\": 1,\n\t\"autohr.org\": 1,\n\t\"autohunan.com\": 1,\n\t\"autono1.com\": 1,\n\t\"autoobserver.net\": 1,\n\t\"autosup.com\": 1,\n\t\"autowj.com\": 1,\n\t\"auugame.com\": 1,\n\t\"auyou.com\": 1,\n\t\"av-window.com\": 1,\n\t\"av001.com\": 1,\n\t\"av010.com\": 1,\n\t\"av118.com\": 1,\n\t\"avzq.com\": 1,\n\t\"aw99.com\": 1,\n\t\"awotuan.com\": 1,\n\t\"awotuan.net\": 1,\n\t\"ax597.com\": 1,\n\t\"axatp.com\": 1,\n\t\"axjlxh.com\": 1,\n\t\"axmro.com\": 1,\n\t\"axmw.com\": 1,\n\t\"aycw.net\": 1,\n\t\"aygjj.com\": 1,\n\t\"ayhsnm.com\": 1,\n\t\"ayican.com\": 1,\n\t\"ayijx.com\": 1,\n\t\"ayjewelry.com\": 1,\n\t\"ayqc.net\": 1,\n\t\"ayrbs.com\": 1,\n\t\"ayrc.cc\": 1,\n\t\"ayrc.com\": 1,\n\t\"ayrc.net\": 1,\n\t\"ayu100.com\": 1,\n\t\"ayyx.com\": 1,\n\t\"b-tea.com\": 1,\n\t\"b2005.com\": 1,\n\t\"b2b-1.com\": 1,\n\t\"b2b110.com\": 1,\n\t\"b2b168.com\": 1,\n\t\"b2b179.com\": 1,\n\t\"b2bfenlei.com\": 1,\n\t\"b2bgujian.com\": 1,\n\t\"b2bhs.com\": 1,\n\t\"b2bic.com\": 1,\n\t\"b2bkk.com\": 1,\n\t\"b2bmy.com\": 1,\n\t\"b2bvip.com\": 1,\n\t\"b2bvip.net\": 1,\n\t\"b2tong.com\": 1,\n\t\"b5m.com\": 1,\n\t\"ba1314.com\": 1,\n\t\"bab720.com\": 1,\n\t\"bababaike.com\": 1,\n\t\"bababian.com\": 1,\n\t\"babai.com\": 1,\n\t\"babakk.com\": 1,\n\t\"babapi.com\": 1,\n\t\"babeltime.com\": 1,\n\t\"baby-edu.com\": 1,\n\t\"baby0515.com\": 1,\n\t\"baby611.com\": 1,\n\t\"baby868.com\": 1,\n\t\"babydao.com\": 1,\n\t\"babytoo.com\": 1,\n\t\"babytree.com\": 1,\n\t\"babytreeimg.com\": 1,\n\t\"bacic5i5j.com\": 1,\n\t\"badao37.com\": 1,\n\t\"bag-hr.com\": 1,\n\t\"bagsnet.com\": 1,\n\t\"bai58.com\": 1,\n\t\"baibaidu.com\": 1,\n\t\"baicai.com\": 1,\n\t\"baicaolu.com\": 1,\n\t\"baicheng.com\": 1,\n\t\"baicheng360.com\": 1,\n\t\"baicmotor.com\": 1,\n\t\"baidajob.com\": 1,\n\t\"baidu.com\": 1,\n\t\"baiducontent.com\": 1,\n\t\"baiduhm.com\": 1,\n\t\"baidustatic.com\": 1,\n\t\"baiduyy.com\": 1,\n\t\"baietu.com\": 1,\n\t\"baifendian.com\": 1,\n\t\"baifubao.com\": 1,\n\t\"baigou.net\": 1,\n\t\"baihe.com\": 1,\n\t\"baiherc.com\": 1,\n\t\"baihuabaiyou.com\": 1,\n\t\"baijia520.com\": 1,\n\t\"baijiajiangtan.org\": 1,\n\t\"baike.com\": 1,\n\t\"baike126.com\": 1,\n\t\"bailinsi.net\": 1,\n\t\"bailitop.com\": 1,\n\t\"baima.com\": 1,\n\t\"baimao.com\": 1,\n\t\"baimei.com\": 1,\n\t\"baimin.com\": 1,\n\t\"bainawang.com\": 1,\n\t\"baipaopao.com\": 1,\n\t\"baipu365.com\": 1,\n\t\"baiquean.org\": 1,\n\t\"baise.cc\": 1,\n\t\"baishan.com\": 1,\n\t\"baishibaike.com\": 1,\n\t\"baishuiapple.com\": 1,\n\t\"baiteng.org\": 1,\n\t\"baitianinfo.com\": 1,\n\t\"baitugu.com\": 1,\n\t\"baiwanzhan.com\": 1,\n\t\"baixing.com\": 1,\n\t\"baixing.net\": 1,\n\t\"baixinger.com\": 1,\n\t\"baixingjd.com\": 1,\n\t\"baixingjob.com\": 1,\n\t\"baiy.net\": 1,\n\t\"baiyinjg.com\": 1,\n\t\"baiyintouzi.com\": 1,\n\t\"baiyjk.com\": 1,\n\t\"baiyou100.com\": 1,\n\t\"baiyunpiaopiao.com\": 1,\n\t\"baizhuwang.com\": 1,\n\t\"bamaol.cc\": 1,\n\t\"bamaol.com\": 1,\n\t\"bamatea.com\": 1,\n\t\"bamboo18.com\": 1,\n\t\"bamboochar.com\": 1,\n\t\"bamuyu.com\": 1,\n\t\"banbaowang.com\": 1,\n\t\"banbijiang.com\": 1,\n\t\"bangboer.com\": 1,\n\t\"bangexam.com\": 1,\n\t\"banggo.com\": 1,\n\t\"bangongzs.com\": 1,\n\t\"bangzaizai.com\": 1,\n\t\"bangzhu123.com\": 1,\n\t\"banhuajia.net\": 1,\n\t\"banjiajia.com\": 1,\n\t\"bank-of-china.com\": 1,\n\t\"bankcomm.com\": 1,\n\t\"bankhr.com\": 1,\n\t\"banklilv.com\": 1,\n\t\"banknotestudy.com\": 1,\n\t\"bankofchina.com\": 1,\n\t\"bankofshanghai.com\": 1,\n\t\"banksteel.com\": 1,\n\t\"banma.com\": 1,\n\t\"banwojia.com\": 1,\n\t\"banyouguoji.com\": 1,\n\t\"banyuetan.org\": 1,\n\t\"banzhu.co\": 1,\n\t\"bao21.com\": 1,\n\t\"baobao001.com\": 1,\n\t\"baobao18.com\": 1,\n\t\"baobao88.com\": 1,\n\t\"baobaohua.com\": 1,\n\t\"baobaomm.com\": 1,\n\t\"baobei360.com\": 1,\n\t\"baobeigou.com\": 1,\n\t\"baobeihr.com\": 1,\n\t\"baobeihuijia.com\": 1,\n\t\"baoerle.com\": 1,\n\t\"baofeng.com\": 1,\n\t\"baogao.com\": 1,\n\t\"baogaoku.com\": 1,\n\t\"baoji168.com\": 1,\n\t\"baojia.com\": 1,\n\t\"baojiaba.com\": 1,\n\t\"baojidaily.com\": 1,\n\t\"baojijob.com\": 1,\n\t\"baojiphoto.com\": 1,\n\t\"baojizx.com\": 1,\n\t\"baojk.com\": 1,\n\t\"baolubxg.com\": 1,\n\t\"baoman.net\": 1,\n\t\"baomihua.com\": 1,\n\t\"baoming.com\": 1,\n\t\"baomiye.com\": 1,\n\t\"baoruan.com\": 1,\n\t\"baoshanhui.com\": 1,\n\t\"baoshanjie.com\": 1,\n\t\"baosteel.com\": 1,\n\t\"baotang5.com\": 1,\n\t\"baotime.com\": 1,\n\t\"baotu.com\": 1,\n\t\"baowenxiehui.org\": 1,\n\t\"baoxian.com\": 1,\n\t\"baoye.net\": 1,\n\t\"baoyeah.com\": 1,\n\t\"baoyi100.com\": 1,\n\t\"baoyilego.com\": 1,\n\t\"baoyuntong.com\": 1,\n\t\"baozang.com\": 1,\n\t\"baozoudawang.com\": 1,\n\t\"baronchina.com\": 1,\n\t\"base888.com\": 1,\n\t\"bashang.net\": 1,\n\t\"batteryhr.com\": 1,\n\t\"bavlo.com\": 1,\n\t\"bawu.net\": 1,\n\t\"baxue.com\": 1,\n\t\"bayecao.com\": 1,\n\t\"bayuche.com\": 1,\n\t\"bayueju.com\": 1,\n\t\"bbhun.com\": 1,\n\t\"bbicn.com\": 1,\n\t\"bbioo.com\": 1,\n\t\"bblfloor.com\": 1,\n\t\"bblft.com\": 1,\n\t\"bbmalls.com\": 1,\n\t\"bbready.com\": 1,\n\t\"bbs0370.com\": 1,\n\t\"bbs0556.com\": 1,\n\t\"bbskaoyan.com\": 1,\n\t\"bbsls.net\": 1,\n\t\"bbstoday.com\": 1,\n\t\"bbszjj.com\": 1,\n\t\"bbwcq.com\": 1,\n\t\"bbwfish.com\": 1,\n\t\"bbwmw.com\": 1,\n\t\"bcactc.com\": 1,\n\t\"bcgjob.com\": 1,\n\t\"bcjy123.com\": 1,\n\t\"bcpcn.com\": 1,\n\t\"bcy.net\": 1,\n\t\"bcyimg.com\": 1,\n\t\"bczgx.org\": 1,\n\t\"bczph.com\": 1,\n\t\"bd365.net\": 1,\n\t\"bdall.com\": 1,\n\t\"bdche.net\": 1,\n\t\"bdchina.com\": 1,\n\t\"bdgbw.com\": 1,\n\t\"bdimg.com\": 1,\n\t\"bdinfo.net\": 1,\n\t\"bdjtd.com\": 1,\n\t\"bdqnht.com\": 1,\n\t\"bdqnxh.com\": 1,\n\t\"bdr114.com\": 1,\n\t\"bds-tech.com\": 1,\n\t\"bdstatic.com\": 1,\n\t\"bdtm.net\": 1,\n\t\"bead-diy.com\": 1,\n\t\"beat11.com\": 1,\n\t\"becod.com\": 1,\n\t\"beelineser.com\": 1,\n\t\"beelink.com\": 1,\n\t\"behome.hk\": 1,\n\t\"beianbeian.com\": 1,\n\t\"beianchaxun.net\": 1,\n\t\"beibaotu.com\": 1,\n\t\"beibeico.com\": 1,\n\t\"beibeidai.com\": 1,\n\t\"beidajj.com\": 1,\n\t\"beidaqingniao.org\": 1,\n\t\"beidaxueshihou.com\": 1,\n\t\"beidoulian.com\": 1,\n\t\"beifang.net\": 1,\n\t\"beifangdianlan.com\": 1,\n\t\"beifangfoshifen.com\": 1,\n\t\"beifangguolv.com\": 1,\n\t\"beiguorc.com\": 1,\n\t\"beihai365.com\": 1,\n\t\"beihaidc.com\": 1,\n\t\"beijing-office.com\": 1,\n\t\"beijingbang.com\": 1,\n\t\"beijingbaomu.com\": 1,\n\t\"beijingnongjiayuan.com\": 1,\n\t\"beijingrc.com\": 1,\n\t\"beijingshots.com\": 1,\n\t\"beijingxa.com\": 1,\n\t\"beingmate.com\": 1,\n\t\"beisen.com\": 1,\n\t\"beitanews.com\": 1,\n\t\"beitiao.com\": 1,\n\t\"beitu.cc\": 1,\n\t\"beiwaibest.com\": 1,\n\t\"beiwaiclass.com\": 1,\n\t\"beiwaionline.com\": 1,\n\t\"beiwaiqingshao.com\": 1,\n\t\"beiwo.tv\": 1,\n\t\"beiww.com\": 1,\n\t\"beiyistar.com\": 1,\n\t\"beiyupeixun.com\": 1,\n\t\"bejoin.net\": 1,\n\t\"benber.com\": 1,\n\t\"bendibao.com\": 1,\n\t\"bengbeng.com\": 1,\n\t\"bengou.cm\": 1,\n\t\"bengou.com\": 1,\n\t\"beniao.com\": 1,\n\t\"benimg.com\": 1,\n\t\"benmaz.com\": 1,\n\t\"benniaocn.com\": 1,\n\t\"benshouji.com\": 1,\n\t\"bensino.com\": 1,\n\t\"benxiaoqu.com\": 1,\n\t\"benyouhui.com\": 1,\n\t\"berqin.com\": 1,\n\t\"berui.com\": 1,\n\t\"best73.com\": 1,\n\t\"bestb2b.com\": 1,\n\t\"bestopview.com\": 1,\n\t\"bet500.com\": 1,\n\t\"betrad.com\": 1,\n\t\"beva.com\": 1,\n\t\"bf35.com\": 1,\n\t\"bfjr.com\": 1,\n\t\"bfyx.com\": 1,\n\t\"bgl88.com\": 1,\n\t\"bgrimm.com\": 1,\n\t\"bgsdyz.com\": 1,\n\t\"bgyedu.com\": 1,\n\t\"bgyks.com\": 1,\n\t\"bh-hotel.com\": 1,\n\t\"bh111.com\": 1,\n\t\"bh5.com\": 1,\n\t\"bhdlw.com\": 1,\n\t\"bhtv.cc\": 1,\n\t\"bhwzd.com\": 1,\n\t\"bhxww.com\": 1,\n\t\"biancui.com\": 1,\n\t\"bianews.com\": 1,\n\t\"bianfeng.com\": 1,\n\t\"bianji.net\": 1,\n\t\"bianjibu.net\": 1,\n\t\"bianmincn.com\": 1,\n\t\"bianwanjia.com\": 1,\n\t\"bianzhirensheng.com\": 1,\n\t\"biaonews.com\": 1,\n\t\"biaoyu.org\": 1,\n\t\"biaoyu114.com\": 1,\n\t\"biaoyu168.com\": 1,\n\t\"bibitie.com\": 1,\n\t\"bicpaedu.com\": 1,\n\t\"bidchance.com\": 1,\n\t\"bieshu.com\": 1,\n\t\"bifen520.com\": 1,\n\t\"bifengxia.com\": 1,\n\t\"biftedu.com\": 1,\n\t\"big-bit.com\": 1,\n\t\"bigzhu.com\": 1,\n\t\"bihannet.com\": 1,\n\t\"bijiafloor.com\": 1,\n\t\"bilibili.com\": 1,\n\t\"bilibili.tv\": 1,\n\t\"biligame.com\": 1,\n\t\"bilinstar.com\": 1,\n\t\"billwang.net\": 1,\n\t\"bimawen.com\": 1,\n\t\"bincailiuxue.com\": 1,\n\t\"binfang.com\": 1,\n\t\"bing.com\": 1,\n\t\"bingchengwang.com\": 1,\n\t\"binglanggu.com\": 1,\n\t\"bingtuannet.com\": 1,\n\t\"binguanzs.com\": 1,\n\t\"binhai100.com\": 1,\n\t\"binvor.com\": 1,\n\t\"binxian.cc\": 1,\n\t\"binzhou.net\": 1,\n\t\"binzhoumama.com\": 1,\n\t\"bio1000.com\": 1,\n\t\"bioon.com\": 1,\n\t\"bisenet.com\": 1,\n\t\"bitauto.com\": 1,\n\t\"bitautoimg.com\": 1,\n\t\"bitautotech.com\": 1,\n\t\"bitscn.com\": 1,\n\t\"biwo.com\": 1,\n\t\"biyong007.com\": 1,\n\t\"biz178.com\": 1,\n\t\"biz72.com\": 1,\n\t\"bizcn.com\": 1,\n\t\"biznewscn.com\": 1,\n\t\"bj-binbin.net\": 1,\n\t\"bj-cl.com\": 1,\n\t\"bj-gzjlb.com\": 1,\n\t\"bj-lexus.com\": 1,\n\t\"bj-mobiletv.com\": 1,\n\t\"bj-sihemy.com\": 1,\n\t\"bj148.org\": 1,\n\t\"bj1777.com\": 1,\n\t\"bj315.org\": 1,\n\t\"bj597.com\": 1,\n\t\"bjaccp.com\": 1,\n\t\"bjbenet.com\": 1,\n\t\"bjbkws.com\": 1,\n\t\"bjbus.com\": 1,\n\t\"bjcankao.com\": 1,\n\t\"bjcdc.org\": 1,\n\t\"bjcf.com\": 1,\n\t\"bjcn.cc\": 1,\n\t\"bjcshy.com\": 1,\n\t\"bjcsyg.org\": 1,\n\t\"bjdskgl.com\": 1,\n\t\"bjdtv.com\": 1,\n\t\"bjdushu.com\": 1,\n\t\"bjedu.com\": 1,\n\t\"bjfair.com\": 1,\n\t\"bjfyw.org\": 1,\n\t\"bjgxs.com\": 1,\n\t\"bjhhlv.com\": 1,\n\t\"bjhonglu.com\": 1,\n\t\"bjhoutai.com\": 1,\n\t\"bjhuaboyy.com\": 1,\n\t\"bjhuiyou.com\": 1,\n\t\"bjhxjz.com\": 1,\n\t\"bjhypx.com\": 1,\n\t\"bjhytc.net\": 1,\n\t\"bjiae.net\": 1,\n\t\"bjjubao.org\": 1,\n\t\"bjlmfq.com\": 1,\n\t\"bjlot.com\": 1,\n\t\"bjlyjszx.com\": 1,\n\t\"bjlz.net\": 1,\n\t\"bjmama.com\": 1,\n\t\"bjmama.net\": 1,\n\t\"bjmanyuan.com\": 1,\n\t\"bjmmhh.com\": 1,\n\t\"bjmtv.com\": 1,\n\t\"bjmxw.net\": 1,\n\t\"bjp321.com\": 1,\n\t\"bjpts.org\": 1,\n\t\"bjpzs.com\": 1,\n\t\"bjrc.com\": 1,\n\t\"bjrcb.com\": 1,\n\t\"bjrzx.com\": 1,\n\t\"bjsdkj.com\": 1,\n\t\"bjsoyo.com\": 1,\n\t\"bjspw.com\": 1,\n\t\"bjsqgy.com\": 1,\n\t\"bjsubway.com\": 1,\n\t\"bjsyqw.com\": 1,\n\t\"bjtarena.com\": 1,\n\t\"bjtjd.com\": 1,\n\t\"bjtopli.com\": 1,\n\t\"bjtptk.com\": 1,\n\t\"bjtuxyqyj.org\": 1,\n\t\"bjtxc.com\": 1,\n\t\"bjwmys.com\": 1,\n\t\"bjxatq.com\": 1,\n\t\"bjxfpp.com\": 1,\n\t\"bjxiangda.com\": 1,\n\t\"bjxinniang.com\": 1,\n\t\"bjxinyou.com\": 1,\n\t\"bjxyxd.com\": 1,\n\t\"bjypw.com\": 1,\n\t\"bjyxl.com\": 1,\n\t\"bjyzyz.net\": 1,\n\t\"bjzgh.org\": 1,\n\t\"bjzj.net\": 1,\n\t\"bjzs.com\": 1,\n\t\"bjzyhs.com\": 1,\n\t\"bk010.com\": 1,\n\t\"bkill.com\": 1,\n\t\"bkpcn.com\": 1,\n\t\"bl81890.com\": 1,\n\t\"blctwed.com\": 1,\n\t\"bleju.com\": 1,\n\t\"blnjw.com\": 1,\n\t\"blog.163.com\": 1,\n\t\"blogbus.com\": 1,\n\t\"blogchina.com\": 1,\n\t\"bloomgamer.com\": 1,\n\t\"bloves.com\": 1,\n\t\"blqx.com\": 1,\n\t\"blshe.com\": 1,\n\t\"bluehn.com\": 1,\n\t\"blueidea.com\": 1,\n\t\"bluekai.com\": 1,\n\t\"bluestacks.hk\": 1,\n\t\"blyol.com\": 1,\n\t\"bmd.hk\": 1,\n\t\"bmindex.com\": 1,\n\t\"bmippa.org\": 1,\n\t\"bmjob.net\": 1,\n\t\"bmlink.com\": 1,\n\t\"bmymtz.com\": 1,\n\t\"bnapp.com\": 1,\n\t\"bndaily.com\": 1,\n\t\"bnncn.com\": 1,\n\t\"bnpower.com\": 1,\n\t\"boai.com\": 1,\n\t\"boaigx.com\": 1,\n\t\"boairc.com\": 1,\n\t\"bobo.com\": 1,\n\t\"bohaitoday.com\": 1,\n\t\"boheshop.com\": 1,\n\t\"boilerinfo.net\": 1,\n\t\"boke001.com\": 1,\n\t\"bokecc.com\": 1,\n\t\"bokeccimg.com\": 1,\n\t\"bokee.com\": 1,\n\t\"bokee.net\": 1,\n\t\"bokon.net\": 1,\n\t\"bole.me\": 1,\n\t\"bole766.com\": 1,\n\t\"bolijob.com\": 1,\n\t\"bon-top.com\": 1,\n\t\"book51.net\": 1,\n\t\"bookben.com\": 1,\n\t\"bookdao.com\": 1,\n\t\"bookschina.com\": 1,\n\t\"booksky.org\": 1,\n\t\"bookuu.com\": 1,\n\t\"boosj.com\": 1,\n\t\"bootcss.com\": 1,\n\t\"boqee.com\": 1,\n\t\"boqii.com\": 1,\n\t\"borlonclan.com\": 1,\n\t\"borpor.com\": 1,\n\t\"bosafe.com\": 1,\n\t\"bosera.com\": 1,\n\t\"bosidata.com\": 1,\n\t\"bosideng.com\": 1,\n\t\"bosnn.com\": 1,\n\t\"bosshr.com\": 1,\n\t\"bostpx.com\": 1,\n\t\"boxuu.com\": 1,\n\t\"boyin.tv\": 1,\n\t\"bozhong.com\": 1,\n\t\"boznews.com\": 1,\n\t\"bqqm.com\": 1,\n\t\"brandcn.com\": 1,\n\t\"brandjs.com\": 1,\n\t\"broadks.com\": 1,\n\t\"brothersoft.com\": 1,\n\t\"bs-car.com\": 1,\n\t\"bs2005.com\": 1,\n\t\"bsjhhzs.com\": 1,\n\t\"bsmhw.com\": 1,\n\t\"bsqc.com\": 1,\n\t\"bsrczpw.com\": 1,\n\t\"bssfc.com\": 1,\n\t\"bssmm.com\": 1,\n\t\"bswxw.com\": 1,\n\t\"bsyjrb.com\": 1,\n\t\"btbsm.com\": 1,\n\t\"btc114.com\": 1,\n\t\"btcha.com\": 1,\n\t\"btcman.com\": 1,\n\t\"btctrade.com\": 1,\n\t\"btesi.com\": 1,\n\t\"btgms.com\": 1,\n\t\"btjy.net\": 1,\n\t\"btophr.com\": 1,\n\t\"btrcsc.com\": 1,\n\t\"btsteel.com\": 1,\n\t\"btv.org\": 1,\n\t\"btwmb.com\": 1,\n\t\"bublue.org\": 1,\n\t\"bubukua.com\": 1,\n\t\"bufan.com\": 1,\n\t\"buger.net\": 1,\n\t\"build365.com\": 1,\n\t\"buildhr.com\": 1,\n\t\"buildjob.net\": 1,\n\t\"bukade.com\": 1,\n\t\"bumiu.com\": 1,\n\t\"bundpic.com\": 1,\n\t\"bunyn.com\": 1,\n\t\"bupu.net\": 1,\n\t\"bus84.com\": 1,\n\t\"bushome.net\": 1,\n\t\"busyan.com\": 1,\n\t\"busyouxi.com\": 1,\n\t\"butao.com\": 1,\n\t\"buxiugangban.net\": 1,\n\t\"buycarcn.com\": 1,\n\t\"buyiju.com\": 1,\n\t\"buzzopt.com\": 1,\n\t\"bwchinese.com\": 1,\n\t\"bwie.net\": 1,\n\t\"bwlc.net\": 1,\n\t\"bx169.com\": 1,\n\t\"bxd365.com\": 1,\n\t\"bxdyt.com\": 1,\n\t\"bxgfw.com\": 1,\n\t\"bxgtd.com\": 1,\n\t\"bxhq.com\": 1,\n\t\"bxi8.com\": 1,\n\t\"bxkxw.com\": 1,\n\t\"bxr.im\": 1,\n\t\"bxrcw.com\": 1,\n\t\"bxrcw.net\": 1,\n\t\"bxxh.net\": 1,\n\t\"bxycw.com\": 1,\n\t\"bxynzz.com\": 1,\n\t\"bxzxw.com\": 1,\n\t\"by-bbs.com\": 1,\n\t\"byandon.com\": 1,\n\t\"bycmw.com\": 1,\n\t\"byecity.com\": 1,\n\t\"byf.com\": 1,\n\t\"bykjhb.com\": 1,\n\t\"bynmc.com\": 1,\n\t\"byqsc.net\": 1,\n\t\"byywee.com\": 1,\n\t\"byzc.com\": 1,\n\t\"byzp.net\": 1,\n\t\"bz169.com\": 1,\n\t\"bz800.com\": 1,\n\t\"bzcars.com\": 1,\n\t\"bzcm.net\": 1,\n\t\"bzfccs.com\": 1,\n\t\"bzfxw.com\": 1,\n\t\"bzgd.com\": 1,\n\t\"bzhan.cc\": 1,\n\t\"bzjw.com\": 1,\n\t\"bznews.org\": 1,\n\t\"bznj.net\": 1,\n\t\"bzonl.com\": 1,\n\t\"bzqcw.com\": 1,\n\t\"bzshw.com\": 1,\n\t\"bzsj.com\": 1,\n\t\"bztdxxl.com\": 1,\n\t\"bzw315.com\": 1,\n\t\"bzwscgs.com\": 1,\n\t\"bzys001.com\": 1,\n\t\"bzzpw.com\": 1,\n\t\"c-bm.com\": 1,\n\t\"c-c.com\": 1,\n\t\"c-ctrip.com\": 1,\n\t\"c-ly.com\": 1,\n\t\"c-ps.net\": 1,\n\t\"c029.com\": 1,\n\t\"c100.cc\": 1,\n\t\"c114.net\": 1,\n\t\"c168c.com\": 1,\n\t\"c2000.cc\": 1,\n\t\"c21ax.com\": 1,\n\t\"c2qz.com\": 1,\n\t\"c393.com\": 1,\n\t\"c3crm.com\": 1,\n\t\"c969.com\": 1,\n\t\"ca-maimai.com\": 1,\n\t\"ca-sme.org\": 1,\n\t\"ca168.com\": 1,\n\t\"ca39.com\": 1,\n\t\"ca800.com\": 1,\n\t\"caa1949.com\": 1,\n\t\"caaad.com\": 1,\n\t\"caamei.com\": 1,\n\t\"caanb.com\": 1,\n\t\"cabhr.com\": 1,\n\t\"cable-ex.com\": 1,\n\t\"cableabc.com\": 1,\n\t\"cableex.com\": 1,\n\t\"cabling-system.com\": 1,\n\t\"cacgame.com\": 1,\n\t\"cache.netease.com\": 1,\n\t\"cacos.com\": 1,\n\t\"cadmm.com\": 1,\n\t\"caeexpo.org\": 1,\n\t\"caexpo.com\": 1,\n\t\"caexpo.org\": 1,\n\t\"cafacds.com\": 1,\n\t\"caffeenglish.com\": 1,\n\t\"cago365.com\": 1,\n\t\"caiep.org\": 1,\n\t\"caifx.com\": 1,\n\t\"caigou2003.com\": 1,\n\t\"caigu.com\": 1,\n\t\"caiguu.com\": 1,\n\t\"caihao.com\": 1,\n\t\"caihao.net\": 1,\n\t\"caijj.com\": 1,\n\t\"caiku.com\": 1,\n\t\"caikuu.com\": 1,\n\t\"cailele.com\": 1,\n\t\"cailiao.com\": 1,\n\t\"cailizhong.com\": 1,\n\t\"caing.com\": 1,\n\t\"caipiao365.com\": 1,\n\t\"caipiaogu.com\": 1,\n\t\"caipiaokong.com\": 1,\n\t\"caipuchina.net\": 1,\n\t\"caishijie.com\": 1,\n\t\"caitoo.com\": 1,\n\t\"caixin.com\": 1,\n\t\"caixinhui.com\": 1,\n\t\"caiyun.com\": 1,\n\t\"caizhuang.com\": 1,\n\t\"cake400.com\": 1,\n\t\"cali-light.com\": 1,\n\t\"callwan.com\": 1,\n\t\"calusy.com\": 1,\n\t\"can-goldlink.com\": 1,\n\t\"cando100.com\": 1,\n\t\"candou.com\": 1,\n\t\"canenglish.com\": 1,\n\t\"cang.com\": 1,\n\t\"cangbao.com\": 1,\n\t\"cangchu.org\": 1,\n\t\"cangjinbao.com\": 1,\n\t\"cangvip.com\": 1,\n\t\"cangworld.com\": 1,\n\t\"canju114.com\": 1,\n\t\"cankaoxiaoxi.com\": 1,\n\t\"canyin88.com\": 1,\n\t\"canyouhn.com\": 1,\n\t\"caomeipai.com\": 1,\n\t\"caoyuanfeng.com\": 1,\n\t\"car0575.com\": 1,\n\t\"car0596.com\": 1,\n\t\"car885.com\": 1,\n\t\"carbang.net\": 1,\n\t\"cardbaobao.com\": 1,\n\t\"carimg.com\": 1,\n\t\"carixy.com\": 1,\n\t\"carjol.com\": 1,\n\t\"carnoc.com\": 1,\n\t\"cars178.com\": 1,\n\t\"carschina.com\": 1,\n\t\"cartoonb2b.com\": 1,\n\t\"cartooncentury.com\": 1,\n\t\"cartoonhr.com\": 1,\n\t\"carword.com\": 1,\n\t\"carxoo.com\": 1,\n\t\"caspm.com\": 1,\n\t\"casshr.com\": 1,\n\t\"cat898.com\": 1,\n\t\"catwaji.com\": 1,\n\t\"caupd.com\": 1,\n\t\"cazpw.com\": 1,\n\t\"cb-h.com\": 1,\n\t\"cb310.com\": 1,\n\t\"cbbn.net\": 1,\n\t\"cbd-china.com\": 1,\n\t\"cbe21.com\": 1,\n\t\"cbex.com\": 1,\n\t\"cbh-jj.com\": 1,\n\t\"cbi360.net\": 1,\n\t\"cbice.com\": 1,\n\t\"cbiec.com\": 1,\n\t\"cbinews.com\": 1,\n\t\"cbminfo.com\": 1,\n\t\"cbrx.com\": 1,\n\t\"cbs86.com\": 1,\n\t\"cbsbw.com\": 1,\n\t\"cbskc.com\": 1,\n\t\"cbsrc.com\": 1,\n\t\"cbt9.com\": 1,\n\t\"cbtia.com\": 1,\n\t\"cbw365.com\": 1,\n\t\"cc-office.com\": 1,\n\t\"cc0595.com\": 1,\n\t\"cc11.cc\": 1,\n\t\"cc148.com\": 1,\n\t\"cc163.net\": 1,\n\t\"cc520.com\": 1,\n\t\"cc9d.com\": 1,\n\t\"ccaabb.com\": 1,\n\t\"ccade.org\": 1,\n\t\"ccapress.com\": 1,\n\t\"ccartd.com\": 1,\n\t\"ccav5.com\": 1,\n\t\"ccb.com\": 1,\n\t\"ccbfutures.com\": 1,\n\t\"ccbookfair.com\": 1,\n\t\"ccc333.com\": 1,\n\t\"cccacc.com\": 1,\n\t\"cccbs.net\": 1,\n\t\"cccdzxw.com\": 1,\n\t\"ccceedu.com\": 1,\n\t\"ccdol.com\": 1,\n\t\"ccedin.net\": 1,\n\t\"ccedip.com\": 1,\n\t\"ccedisp.com\": 1,\n\t\"ccedpw.com\": 1,\n\t\"ccedu24.com\": 1,\n\t\"cceep.com\": 1,\n\t\"ccement.com\": 1,\n\t\"ccen.net\": 1,\n\t\"ccenn.com\": 1,\n\t\"ccfcc.net\": 1,\n\t\"ccfdw.com\": 1,\n\t\"ccfei.com\": 1,\n\t\"ccgaa.com\": 1,\n\t\"ccgas.net\": 1,\n\t\"ccic.com\": 1,\n\t\"ccidcom.com\": 1,\n\t\"ccidconsulting.com\": 1,\n\t\"ccidedu.com\": 1,\n\t\"ccidgroup.com\": 1,\n\t\"ccidjl.com\": 1,\n\t\"ccidnet.com\": 1,\n\t\"ccidreport.com\": 1,\n\t\"ccidthinktank.com\": 1,\n\t\"ccig.co\": 1,\n\t\"ccin.tv\": 1,\n\t\"ccits618.com\": 1,\n\t\"ccjex.com\": 1,\n\t\"ccjoy.com\": 1,\n\t\"cclcn.com\": 1,\n\t\"ccm-1.com\": 1,\n\t\"ccmama.com\": 1,\n\t\"ccmedu.com\": 1,\n\t\"ccmetro.com\": 1,\n\t\"ccn360.com\": 1,\n\t\"cco100.com\": 1,\n\t\"ccoalnews.com\": 1,\n\t\"ccost.com\": 1,\n\t\"ccp.so\": 1,\n\t\"ccpc360.com\": 1,\n\t\"ccpit-ah.com\": 1,\n\t\"ccpit-henan.org\": 1,\n\t\"ccpit.org\": 1,\n\t\"ccpitbj.org\": 1,\n\t\"ccpitbm.org\": 1,\n\t\"ccpitgs.org\": 1,\n\t\"ccpitjinan.org\": 1,\n\t\"ccpitjs.org\": 1,\n\t\"ccpitnb.org\": 1,\n\t\"ccpitqd.org\": 1,\n\t\"ccpittex.com\": 1,\n\t\"ccpitxiamen.org\": 1,\n\t\"ccpitzs.com\": 1,\n\t\"ccpm168.com\": 1,\n\t\"ccprec.com\": 1,\n\t\"ccrjia.com\": 1,\n\t\"ccsph.com\": 1,\n\t\"cct88588.com\": 1,\n\t\"cctalk.com\": 1,\n\t\"cctb.net\": 1,\n\t\"cctccb.com\": 1,\n\t\"cctcct.com\": 1,\n\t\"cctime.com\": 1,\n\t\"cctourcollege.com\": 1,\n\t\"cctv-19.com\": 1,\n\t\"cctv.com\": 1,\n\t\"cctv1-15.com\": 1,\n\t\"cctvcaizhi.com\": 1,\n\t\"cctvcj.com\": 1,\n\t\"cctvmall.com\": 1,\n\t\"cctvpic.com\": 1,\n\t\"cctvxf.com\": 1,\n\t\"ccuc.name\": 1,\n\t\"ccutchi.com\": 1,\n\t\"ccutu.com\": 1,\n\t\"ccv160.com\": 1,\n\t\"ccv5.com\": 1,\n\t\"ccvita.com\": 1,\n\t\"ccwcw.com\": 1,\n\t\"ccxcn.com\": 1,\n\t\"ccxinkezhan.com\": 1,\n\t\"ccyts.com\": 1,\n\t\"cd-auto.net\": 1,\n\t\"cd-lotton.com\": 1,\n\t\"cd-motorshow.com\": 1,\n\t\"cd-pa.com\": 1,\n\t\"cdbdks.com\": 1,\n\t\"cdcgames.net\": 1,\n\t\"cdcmzx.com\": 1,\n\t\"cdculture.com\": 1,\n\t\"cddtz.com\": 1,\n\t\"cdeaa.com\": 1,\n\t\"cdedu.com\": 1,\n\t\"cdeledu.com\": 1,\n\t\"cdfds.com\": 1,\n\t\"cdgjbus.com\": 1,\n\t\"cdgjlxs.com\": 1,\n\t\"cditv.tv\": 1,\n\t\"cdjzs.com\": 1,\n\t\"cdknj.com\": 1,\n\t\"cdn-apple.com\": 1,\n\t\"cdn-files.net\": 1,\n\t\"cdn20.com\": 1,\n\t\"cdndm.com\": 1,\n\t\"cdndm5.com\": 1,\n\t\"cdnet110.com\": 1,\n\t\"cdpta.com\": 1,\n\t\"cdqcp.com\": 1,\n\t\"cdqcw.net\": 1,\n\t\"cdqss.com\": 1,\n\t\"cdqss.net\": 1,\n\t\"cdsb.com\": 1,\n\t\"cdsjjy.com\": 1,\n\t\"cdsme.com\": 1,\n\t\"cdspld.com\": 1,\n\t\"cdvns.com\": 1,\n\t\"cdweekly.net\": 1,\n\t\"cdxuntu.com\": 1,\n\t\"cdyee.com\": 1,\n\t\"cdyjs.org\": 1,\n\t\"cdyou.net\": 1,\n\t\"cdysxx.com\": 1,\n\t\"cdzjj.com\": 1,\n\t\"cdzmkm.com\": 1,\n\t\"cdzxyy.com\": 1,\n\t\"ce-air.com\": 1,\n\t\"ce-idc.com\": 1,\n\t\"ce02.net\": 1,\n\t\"ceair.com\": 1,\n\t\"cebbank.com\": 1,\n\t\"cecb2b.com\": 1,\n\t\"ceccen.com\": 1,\n\t\"cechem.net\": 1,\n\t\"ceeia.com\": 1,\n\t\"cehome.com\": 1,\n\t\"cehui8.com\": 1,\n\t\"cehuiyc.com\": 1,\n\t\"cehuizizhi.com\": 1,\n\t\"ceiaec.org\": 1,\n\t\"ceibs.edu\": 1,\n\t\"ceiea.com\": 1,\n\t\"ceiec.org\": 1,\n\t\"cement365.com\": 1,\n\t\"cementchina.net\": 1,\n\t\"cementren.com\": 1,\n\t\"cementtech.org\": 1,\n\t\"centanet.com\": 1,\n\t\"century21cn.com\": 1,\n\t\"cenwor.com\": 1,\n\t\"cenxiao.com\": 1,\n\t\"ceoba.com\": 1,\n\t\"ceoedu.com\": 1,\n\t\"ceolearn.com\": 1,\n\t\"ceowan.com\": 1,\n\t\"ceping114.com\": 1,\n\t\"cerambath.org\": 1,\n\t\"ceramicschina.com\": 1,\n\t\"cernet.com\": 1,\n\t\"cersp.com\": 1,\n\t\"cespc.com\": 1,\n\t\"cet-46.com\": 1,\n\t\"cetc.cc\": 1,\n\t\"cetcit.com\": 1,\n\t\"cetimes.com\": 1,\n\t\"cetv.com\": 1,\n\t\"cf086.com\": 1,\n\t\"cf5156.com\": 1,\n\t\"cf571.com\": 1,\n\t\"cfachina.org\": 1,\n\t\"cfanclub.net\": 1,\n\t\"cfbchina.org\": 1,\n\t\"cfcyb.com\": 1,\n\t\"cfd163.com\": 1,\n\t\"cfedu.net\": 1,\n\t\"cfej.net\": 1,\n\t\"cffw.net\": 1,\n\t\"cfhot.com\": 1,\n\t\"cfiin.com\": 1,\n\t\"cfmmc.com\": 1,\n\t\"cfsbcn.com\": 1,\n\t\"cfscrm.com\": 1,\n\t\"cfsdc.org\": 1,\n\t\"cftjob.com\": 1,\n\t\"cfvin.com\": 1,\n\t\"cfwjob.com\": 1,\n\t\"cfyd168.com\": 1,\n\t\"cfzpw.com\": 1,\n\t\"cg009.com\": 1,\n\t\"cg1993.com\": 1,\n\t\"cg577.com\": 1,\n\t\"cg98.com\": 1,\n\t\"cgbolo.com\": 1,\n\t\"cgebook.com\": 1,\n\t\"cgjoy.com\": 1,\n\t\"cgmol.com\": 1,\n\t\"cgtz.com\": 1,\n\t\"cguardian.com\": 1,\n\t\"cguwan.com\": 1,\n\t\"ch-em.com\": 1,\n\t\"ch7w.com\": 1,\n\t\"ch9888.com\": 1,\n\t\"ch999.com\": 1,\n\t\"ch999img.com\": 1,\n\t\"chachaba.com\": 1,\n\t\"chadao.cc\": 1,\n\t\"chadianhua.net\": 1,\n\t\"chaduo.com\": 1,\n\t\"chaej.com\": 1,\n\t\"chahaoba.com\": 1,\n\t\"chahaotai.com\": 1,\n\t\"chahua.org\": 1,\n\t\"chajie.com\": 1,\n\t\"chakd.com\": 1,\n\t\"chamei.com\": 1,\n\t\"chamenhu.com\": 1,\n\t\"chanel.com\": 1,\n\t\"changan.biz\": 1,\n\t\"changdedj.net\": 1,\n\t\"changhong.com\": 1,\n\t\"changjiangtimes.com\": 1,\n\t\"changshannews.com\": 1,\n\t\"changshuhr.com\": 1,\n\t\"changyou.com\": 1,\n\t\"changzhinews.com\": 1,\n\t\"chaohu.cc\": 1,\n\t\"chaoji.com\": 1,\n\t\"chaoji007.com\": 1,\n\t\"chaojupai.com\": 1,\n\t\"chaoliu1.net\": 1,\n\t\"chaorenwang.com\": 1,\n\t\"chaoshanren.com\": 1,\n\t\"chaoxing.com\": 1,\n\t\"chaozhoudaily.com\": 1,\n\t\"chasfz.com\": 1,\n\t\"chashebao.com\": 1,\n\t\"chashui.cc\": 1,\n\t\"chawenyi.com\": 1,\n\t\"chaxiao.com\": 1,\n\t\"chaxunbang.com\": 1,\n\t\"chayou365.com\": 1,\n\t\"chazidian.com\": 1,\n\t\"chbcnet.com\": 1,\n\t\"chbds.com\": 1,\n\t\"chcpmc.com\": 1,\n\t\"chczz.com\": 1,\n\t\"chda.net\": 1,\n\t\"chdajob.com\": 1,\n\t\"chdbits.org\": 1,\n\t\"che12.com\": 1,\n\t\"che127.com\": 1,\n\t\"che168.com\": 1,\n\t\"che2.com\": 1,\n\t\"che310.com\": 1,\n\t\"che777.com\": 1,\n\t\"cheaa.com\": 1,\n\t\"cheaa.org\": 1,\n\t\"cheari.com\": 1,\n\t\"chebadu.com\": 1,\n\t\"chebiao.net\": 1,\n\t\"chebiaow.com\": 1,\n\t\"chechong.com\": 1,\n\t\"chechuan.com\": 1,\n\t\"cheduoshao.com\": 1,\n\t\"cheertea.com\": 1,\n\t\"chefans.com\": 1,\n\t\"chejl.com\": 1,\n\t\"chekb.com\": 1,\n\t\"chelink.com\": 1,\n\t\"chem-men.com\": 1,\n\t\"chem17.com\": 1,\n\t\"chem234.com\": 1,\n\t\"chem31.com\": 1,\n\t\"chem960.com\": 1,\n\t\"chem99.com\": 1,\n\t\"chemayi.com\": 1,\n\t\"chemcp.com\": 1,\n\t\"chemdrug.com\": 1,\n\t\"chemishu.com\": 1,\n\t\"chemmade.com\": 1,\n\t\"chemn.com\": 1,\n\t\"chemnet.com\": 1,\n\t\"chemrp.com\": 1,\n\t\"chemsb.com\": 1,\n\t\"chemstar.cc\": 1,\n\t\"chenair.com\": 1,\n\t\"chengbaoo.com\": 1,\n\t\"chengche.cc\": 1,\n\t\"chengdechina.com\": 1,\n\t\"chengdechina.net\": 1,\n\t\"chengdetv.com\": 1,\n\t\"chengdujjw.com\": 1,\n\t\"chengguw.com\": 1,\n\t\"chenghai.cc\": 1,\n\t\"chengkao365.com\": 1,\n\t\"chenglou.net\": 1,\n\t\"chengruide.com\": 1,\n\t\"chengshiw.com\": 1,\n\t\"chengtu.com\": 1,\n\t\"chengw.com\": 1,\n\t\"chengyiju.com\": 1,\n\t\"chenhr.com\": 1,\n\t\"chenpeipei.com\": 1,\n\t\"chepin88.com\": 1,\n\t\"chepuer.com\": 1,\n\t\"cherriespie.com\": 1,\n\t\"cheshi-img.com\": 1,\n\t\"cheshi.com\": 1,\n\t\"cheshitv.com\": 1,\n\t\"chetuanwang.net\": 1,\n\t\"chetx.com\": 1,\n\t\"chetxia.com\": 1,\n\t\"cheweixiu.com\": 1,\n\t\"cheweixiu.net\": 1,\n\t\"chewen.com\": 1,\n\t\"chexiang.com\": 1,\n\t\"chexianinfo.com\": 1,\n\t\"chexinwen.com\": 1,\n\t\"chexiu.com\": 1,\n\t\"chexun.com\": 1,\n\t\"chexun.net\": 1,\n\t\"cheyes.com\": 1,\n\t\"cheyian.com\": 1,\n\t\"cheyipai.com\": 1,\n\t\"cheyisou.com\": 1,\n\t\"cheyou123.com\": 1,\n\t\"cheyou360.com\": 1,\n\t\"cheyuan.com\": 1,\n\t\"cheyun.com\": 1,\n\t\"chgjjzx.com\": 1,\n\t\"chihao.com\": 1,\n\t\"china-315.com\": 1,\n\t\"china-ah.com\": 1,\n\t\"china-anjian.com\": 1,\n\t\"china-asahi.com\": 1,\n\t\"china-b.com\": 1,\n\t\"china-botschaft.de\": 1,\n\t\"china-cba.net\": 1,\n\t\"china-cdt.com\": 1,\n\t\"china-changjiang.net\": 1,\n\t\"china-chigo.com\": 1,\n\t\"china-chuwei.com\": 1,\n\t\"china-cloud.com\": 1,\n\t\"china-consulate.org\": 1,\n\t\"china-cotton.org\": 1,\n\t\"china-cpp.com\": 1,\n\t\"china-dalian.com\": 1,\n\t\"china-designer.com\": 1,\n\t\"china-ef.com\": 1,\n\t\"china-eia.com\": 1,\n\t\"china-embassy.org\": 1,\n\t\"china-english.net\": 1,\n\t\"china-esi.com\": 1,\n\t\"china-fire-retardant.com\": 1,\n\t\"china-flower.com\": 1,\n\t\"china-guiyuan.com\": 1,\n\t\"china-house.com\": 1,\n\t\"china-huaxue.com\": 1,\n\t\"china-insurance.com\": 1,\n\t\"china-landscape.net\": 1,\n\t\"china-lawfirm.com\": 1,\n\t\"china-led.net\": 1,\n\t\"china-lottery.net\": 1,\n\t\"china-lushan.com\": 1,\n\t\"china-moutai.com\": 1,\n\t\"china-nengyuan.com\": 1,\n\t\"china-papernet.com\": 1,\n\t\"china-pec.com\": 1,\n\t\"china-power.net\": 1,\n\t\"china-pub.com\": 1,\n\t\"china-qg.com\": 1,\n\t\"china-ssp.com\": 1,\n\t\"china-sss.com\": 1,\n\t\"china-tin.com\": 1,\n\t\"china-train.net\": 1,\n\t\"china-up.com\": 1,\n\t\"china-zibo.com\": 1,\n\t\"china.com\": 1,\n\t\"china001.com\": 1,\n\t\"china10.org\": 1,\n\t\"china114net.com\": 1,\n\t\"china183.com\": 1,\n\t\"china2car.com\": 1,\n\t\"china3-d.com\": 1,\n\t\"china35.com\": 1,\n\t\"china3608.com\": 1,\n\t\"china5e.com\": 1,\n\t\"china91.com\": 1,\n\t\"china95.net\": 1,\n\t\"china98.net\": 1,\n\t\"china9986.com\": 1,\n\t\"chinaacademyofart.com\": 1,\n\t\"chinaacc.com\": 1,\n\t\"chinaacc.tv\": 1,\n\t\"chinaacn.com\": 1,\n\t\"chinaadec.com\": 1,\n\t\"chinaadren.com\": 1,\n\t\"chinaaet.com\": 1,\n\t\"chinaamc.com\": 1,\n\t\"chinaaqnews.com\": 1,\n\t\"chinaart-eye.com\": 1,\n\t\"chinaasc.org\": 1,\n\t\"chinaasnews.com\": 1,\n\t\"chinaauto.net\": 1,\n\t\"chinaautolighting.com\": 1,\n\t\"chinaautosupplier.com\": 1,\n\t\"chinababy365.com\": 1,\n\t\"chinabaifukang.com\": 1,\n\t\"chinabancai.com\": 1,\n\t\"chinabathware.com\": 1,\n\t\"chinabatteryonline.com\": 1,\n\t\"chinabbnews.com\": 1,\n\t\"chinabcnews.com\": 1,\n\t\"chinabdh.com\": 1,\n\t\"chinabdnews.com\": 1,\n\t\"chinabei.com\": 1,\n\t\"chinabgao.com\": 1,\n\t\"chinabidding.com\": 1,\n\t\"chinabim.com\": 1,\n\t\"chinabinzhou.net\": 1,\n\t\"chinabmi.com\": 1,\n\t\"chinaboxi.com\": 1,\n\t\"chinabreed.com\": 1,\n\t\"chinabsnews.com\": 1,\n\t\"chinabuses.com\": 1,\n\t\"chinabx.com\": 1,\n\t\"chinabxnews.com\": 1,\n\t\"chinabyte.com\": 1,\n\t\"chinabznews.com\": 1,\n\t\"chinabzp.com\": 1,\n\t\"chinac.com\": 1,\n\t\"chinacaipu.com\": 1,\n\t\"chinacampus.org\": 1,\n\t\"chinacars.com\": 1,\n\t\"chinacbe.com\": 1,\n\t\"chinaccm.com\": 1,\n\t\"chinaccnet.com\": 1,\n\t\"chinaccnews.com\": 1,\n\t\"chinacct.org\": 1,\n\t\"chinacdnews.com\": 1,\n\t\"chinacehui.org\": 1,\n\t\"chinaceot.com\": 1,\n\t\"chinacg.org\": 1,\n\t\"chinachangzhinews.com\": 1,\n\t\"chinachangzhounews.com\": 1,\n\t\"chinachemnet.com\": 1,\n\t\"chinachild.org\": 1,\n\t\"chinachina.net\": 1,\n\t\"chinachizhounews.com\": 1,\n\t\"chinachnews.com\": 1,\n\t\"chinachugui.com\": 1,\n\t\"chinachuzhounews.com\": 1,\n\t\"chinacity.net\": 1,\n\t\"chinacitywater.org\": 1,\n\t\"chinack.net\": 1,\n\t\"chinacloud.net\": 1,\n\t\"chinacno.org\": 1,\n\t\"chinacnr.com\": 1,\n\t\"chinacoal.com\": 1,\n\t\"chinacoop.com\": 1,\n\t\"chinacourt.org\": 1,\n\t\"chinacpx.com\": 1,\n\t\"chinacqsb.com\": 1,\n\t\"chinacraa.org\": 1,\n\t\"chinacses.org\": 1,\n\t\"chinactv.com\": 1,\n\t\"chinaculture.org\": 1,\n\t\"chinacutv.com\": 1,\n\t\"chinacynews.com\": 1,\n\t\"chinacznews.com\": 1,\n\t\"chinadance.com\": 1,\n\t\"chinadandongnews.com\": 1,\n\t\"chinadarktea.com\": 1,\n\t\"chinadazhaxie.com\": 1,\n\t\"chinadeda.com\": 1,\n\t\"chinadengshi.com\": 1,\n\t\"chinadlh.com\": 1,\n\t\"chinadlnews.com\": 1,\n\t\"chinadmoz.org\": 1,\n\t\"chinadqnews.com\": 1,\n\t\"chinadriver.org\": 1,\n\t\"chinadrtv.com\": 1,\n\t\"chinadtnews.com\": 1,\n\t\"chinae.com\": 1,\n\t\"chinaecec.com\": 1,\n\t\"chinaeda.org\": 1,\n\t\"chinaedu.com\": 1,\n\t\"chinaedunet.com\": 1,\n\t\"chinaeea.com\": 1,\n\t\"chinaeea.net\": 1,\n\t\"chinaefu.net\": 1,\n\t\"chinaeic.net\": 1,\n\t\"chinaeinet.com\": 1,\n\t\"chinaeku.com\": 1,\n\t\"chinaenvironment.com\": 1,\n\t\"chinaeol.net\": 1,\n\t\"chinaepe.com\": 1,\n\t\"chinafairs.org\": 1,\n\t\"chinafarming.com\": 1,\n\t\"chinafastener.biz\": 1,\n\t\"chinafeedonline.com\": 1,\n\t\"chinafengji.net\": 1,\n\t\"chinafife.com\": 1,\n\t\"chinafix.com\": 1,\n\t\"chinaforklift.com\": 1,\n\t\"chinaforkliftpart.com\": 1,\n\t\"chinafpd.net\": 1,\n\t\"chinafranchiseexpo.com\": 1,\n\t\"chinafsnews.com\": 1,\n\t\"chinafudaoban.com\": 1,\n\t\"chinafxnews.com\": 1,\n\t\"chinafynews.com\": 1,\n\t\"chinafznews.com\": 1,\n\t\"chinagames.net\": 1,\n\t\"chinagayles.com\": 1,\n\t\"chinagb.net\": 1,\n\t\"chinagba.com\": 1,\n\t\"chinagdda.com\": 1,\n\t\"chinagiftsfair.com\": 1,\n\t\"chinagne.com\": 1,\n\t\"chinagocar.com\": 1,\n\t\"chinagoldgroup.com\": 1,\n\t\"chinagreentown.com\": 1,\n\t\"chinagwxz.com\": 1,\n\t\"chinagwy.com\": 1,\n\t\"chinagwyw.org\": 1,\n\t\"chinagynews.com\": 1,\n\t\"chinagzn.com\": 1,\n\t\"chinahanews.com\": 1,\n\t\"chinahazelnut.com\": 1,\n\t\"chinahbi.com\": 1,\n\t\"chinahdnews.com\": 1,\n\t\"chinahfnews.com\": 1,\n\t\"chinahgnews.com\": 1,\n\t\"chinahhnews.com\": 1,\n\t\"chinahightech.com\": 1,\n\t\"chinahjbh.com\": 1,\n\t\"chinahldnews.com\": 1,\n\t\"chinahobypaper.com\": 1,\n\t\"chinahome.cc\": 1,\n\t\"chinahr.com\": 1,\n\t\"chinahrd.net\": 1,\n\t\"chinahsnews.com\": 1,\n\t\"chinahti.com\": 1,\n\t\"chinahuainannews.com\": 1,\n\t\"chinahuangshannews.com\": 1,\n\t\"chinahvacr.com\": 1,\n\t\"chinahyyj.com\": 1,\n\t\"chinaidp.com\": 1,\n\t\"chinaidr.com\": 1,\n\t\"chinaielts.org\": 1,\n\t\"chinaielts.tv\": 1,\n\t\"chinaigbt.com\": 1,\n\t\"chinaiiss.com\": 1,\n\t\"chinaimnet.com\": 1,\n\t\"chinainfoseek.com\": 1,\n\t\"chinaiol.com\": 1,\n\t\"chinaios.com\": 1,\n\t\"chinairn.com\": 1,\n\t\"chinairr.org\": 1,\n\t\"chinaitlab.com\": 1,\n\t\"chinajcnews.com\": 1,\n\t\"chinajiuquan.com\": 1,\n\t\"chinajixinews.com\": 1,\n\t\"chinajlnews.com\": 1,\n\t\"chinajmsnews.com\": 1,\n\t\"chinajnhb.com\": 1,\n\t\"chinajnzz.com\": 1,\n\t\"chinajob.com\": 1,\n\t\"chinajoy.net\": 1,\n\t\"chinajsxx.com\": 1,\n\t\"chinajznews.com\": 1,\n\t\"chinakaoyan.com\": 1,\n\t\"chinakehai.com\": 1,\n\t\"chinakingo.com\": 1,\n\t\"chinakongzi.org\": 1,\n\t\"chinakyxx.com\": 1,\n\t\"chinalao.com\": 1,\n\t\"chinalaobao.com\": 1,\n\t\"chinalawedu.com\": 1,\n\t\"chinalawinfo.com\": 1,\n\t\"chinalawyeryn.com\": 1,\n\t\"chinaleather.org\": 1,\n\t\"chinaled114.com\": 1,\n\t\"chinalfnews.com\": 1,\n\t\"chinaliaoyangnews.com\": 1,\n\t\"chinaliaoyuannews.com\": 1,\n\t\"chinalinfennews.com\": 1,\n\t\"chinalishi.com\": 1,\n\t\"chinallnews.com\": 1,\n\t\"chinalongyannews.com\": 1,\n\t\"chinaluan.com\": 1,\n\t\"chinaluju.com\": 1,\n\t\"chinaluxehome.com\": 1,\n\t\"chinaluxus.com\": 1,\n\t\"chinalygnews.com\": 1,\n\t\"chinamaho.com\": 1,\n\t\"chinamasnews.com\": 1,\n\t\"chinamdjnews.com\": 1,\n\t\"chinamedevice.com\": 1,\n\t\"chinamendu.com\": 1,\n\t\"chinamenwang.com\": 1,\n\t\"chinamingci.com\": 1,\n\t\"chinamining-expo.org\": 1,\n\t\"chinamining.com\": 1,\n\t\"chinamobile.com\": 1,\n\t\"chinamost.net\": 1,\n\t\"chinamr.net\": 1,\n\t\"chinamsr.com\": 1,\n\t\"chinamypp.com\": 1,\n\t\"chinanap.net\": 1,\n\t\"chinandnews.com\": 1,\n\t\"chinanet-online.com\": 1,\n\t\"chinanetcenter.com\": 1,\n\t\"chinanetsun.com\": 1,\n\t\"chinanews.com\": 1,\n\t\"chinanjnews.com\": 1,\n\t\"chinanotary.org\": 1,\n\t\"chinanpnews.com\": 1,\n\t\"chinantnews.com\": 1,\n\t\"chinaoct.com\": 1,\n\t\"chinaore.com\": 1,\n\t\"chinaparking.org\": 1,\n\t\"chinapay.com\": 1,\n\t\"chinape168.com\": 1,\n\t\"chinapet.com\": 1,\n\t\"chinapipe.net\": 1,\n\t\"chinapjnews.com\": 1,\n\t\"chinaplasm.com\": 1,\n\t\"chinapm.org\": 1,\n\t\"chinaports.com\": 1,\n\t\"chinapost-life.com\": 1,\n\t\"chinapp.com\": 1,\n\t\"chinaprint.org\": 1,\n\t\"chinaptnews.com\": 1,\n\t\"chinaqbw.com\": 1,\n\t\"chinaqhdnews.com\": 1,\n\t\"chinaql.org\": 1,\n\t\"chinaqthnews.com\": 1,\n\t\"chinaqw.com\": 1,\n\t\"chinaqznews.com\": 1,\n\t\"chinaredstar.com\": 1,\n\t\"chinaren.com\": 1,\n\t\"chinarjw.com\": 1,\n\t\"chinasage.net\": 1,\n\t\"chinaschool.net\": 1,\n\t\"chinascsmh.com\": 1,\n\t\"chinaseed.net\": 1,\n\t\"chinasfa.net\": 1,\n\t\"chinashaodong.com\": 1,\n\t\"chinashishi.net\": 1,\n\t\"chinashj.com\": 1,\n\t\"chinashoes.com\": 1,\n\t\"chinashoujipp.com\": 1,\n\t\"chinashuozhounews.com\": 1,\n\t\"chinasilk.com\": 1,\n\t\"chinasipingnews.com\": 1,\n\t\"chinasjznews.com\": 1,\n\t\"chinaskills.org\": 1,\n\t\"chinasmnews.com\": 1,\n\t\"chinaso.com\": 1,\n\t\"chinasongyuannews.com\": 1,\n\t\"chinasqbg.com\": 1,\n\t\"chinasqnews.com\": 1,\n\t\"chinasspp.com\": 1,\n\t\"chinasteel.info\": 1,\n\t\"chinastor.org\": 1,\n\t\"chinasus.org\": 1,\n\t\"chinasuzhounews.com\": 1,\n\t\"chinaswitch.com\": 1,\n\t\"chinasych.com\": 1,\n\t\"chinasynews.com\": 1,\n\t\"chinasysnews.com\": 1,\n\t\"chinataitan.com\": 1,\n\t\"chinataiwan.org\": 1,\n\t\"chinataizhounews.com\": 1,\n\t\"chinatarena.com\": 1,\n\t\"chinatat.com\": 1,\n\t\"chinatcw.com\": 1,\n\t\"chinatelecom-ec.com\": 1,\n\t\"chinatelecomiot.com\": 1,\n\t\"chinatet.com\": 1,\n\t\"chinatex.com\": 1,\n\t\"chinatextile.net\": 1,\n\t\"chinathnews.com\": 1,\n\t\"chinatibetnews.com\": 1,\n\t\"chinatimber.org\": 1,\n\t\"chinatimes.cc\": 1,\n\t\"chinatlnews.com\": 1,\n\t\"chinatonglingnews.com\": 1,\n\t\"chinatour-net.com\": 1,\n\t\"chinatpg.com\": 1,\n\t\"chinatpm.com\": 1,\n\t\"chinatruck.org\": 1,\n\t\"chinatsi.com\": 1,\n\t\"chinatsnews.com\": 1,\n\t\"chinatynews.com\": 1,\n\t\"chinaui.com\": 1,\n\t\"chinauma.com\": 1,\n\t\"chinauma.net\": 1,\n\t\"chinaumu.org\": 1,\n\t\"chinaunicom.com\": 1,\n\t\"chinaunionpay.com\": 1,\n\t\"chinaunix.net\": 1,\n\t\"chinaups.com\": 1,\n\t\"chinavalue.net\": 1,\n\t\"chinavanward.com\": 1,\n\t\"chinavegnet.com\": 1,\n\t\"chinavisual.com\": 1,\n\t\"chinavnet.com\": 1,\n\t\"chinavoa.com\": 1,\n\t\"chinaw3.com\": 1,\n\t\"chinawaternet.com\": 1,\n\t\"chinawaternews.com\": 1,\n\t\"chinawbsyxh.com\": 1,\n\t\"chinawebmap.com\": 1,\n\t\"chinaweiyu.com\": 1,\n\t\"chinawestagr.com\": 1,\n\t\"chinawestnews.net\": 1,\n\t\"chinawhnews.com\": 1,\n\t\"chinawin.org\": 1,\n\t\"chinawin2000.com\": 1,\n\t\"chinawoodnet.com\": 1,\n\t\"chinawudang.com\": 1,\n\t\"chinawutong.com\": 1,\n\t\"chinawutong.net\": 1,\n\t\"chinawxnews.com\": 1,\n\t\"chinawyx.com\": 1,\n\t\"chinawznews.net\": 1,\n\t\"chinaxcnews.com\": 1,\n\t\"chinaxiamennews.com\": 1,\n\t\"chinaxiaokang.com\": 1,\n\t\"chinaxnnews.com\": 1,\n\t\"chinaxuzhounews.com\": 1,\n\t\"chinaxwcb.com\": 1,\n\t\"chinaxznews.com\": 1,\n\t\"chinayanchengnews.com\": 1,\n\t\"chinayanghe.com\": 1,\n\t\"chinayichunnews.com\": 1,\n\t\"chinayigou.com\": 1,\n\t\"chinayigui.com\": 1,\n\t\"chinayknews.com\": 1,\n\t\"chinaymqg.com\": 1,\n\t\"chinayoubang.com\": 1,\n\t\"chinayouji.com\": 1,\n\t\"chinayoung.net\": 1,\n\t\"chinayqnews.com\": 1,\n\t\"chinayucinews.com\": 1,\n\t\"chinayunchengnews.com\": 1,\n\t\"chinayyjx.com\": 1,\n\t\"chinayzxx.net\": 1,\n\t\"chinaz.com\": 1,\n\t\"chinazg.net\": 1,\n\t\"chinazhoukou.com\": 1,\n\t\"chinazichan.com\": 1,\n\t\"chinazikao.com\": 1,\n\t\"chinazjknews.com\": 1,\n\t\"chinazjnews.com\": 1,\n\t\"chinazy.org\": 1,\n\t\"chinazznews.com\": 1,\n\t\"chinca.org\": 1,\n\t\"chinese-embassy.org.za\": 1,\n\t\"chinese-luxury.com\": 1,\n\t\"chinese-no1.com\": 1,\n\t\"chinese-os.com\": 1,\n\t\"chineseall.com\": 1,\n\t\"chineseconsulate.org\": 1,\n\t\"chineseembassy.org\": 1,\n\t\"chinesejy.com\": 1,\n\t\"chint.net\": 1,\n\t\"chiphell.com\": 1,\n\t\"chivast.com\": 1,\n\t\"chizhou007.com\": 1,\n\t\"chizhoujob.com\": 1,\n\t\"chizhouren.com\": 1,\n\t\"chizhouxueyuan.com\": 1,\n\t\"chiznews.com\": 1,\n\t\"chlngg.com\": 1,\n\t\"chn0769.com\": 1,\n\t\"chnart.com\": 1,\n\t\"chnbook.org\": 1,\n\t\"chnci.com\": 1,\n\t\"chncomic.com\": 1,\n\t\"chndesign.com\": 1,\n\t\"chnir.com\": 1,\n\t\"chnjet.com\": 1,\n\t\"chnlung.com\": 1,\n\t\"chnmilitary.com\": 1,\n\t\"chnmus.net\": 1,\n\t\"chnrailway.com\": 1,\n\t\"chnroad.com\": 1,\n\t\"chnsuv.com\": 1,\n\t\"chnvc.com\": 1,\n\t\"chnweiyu.com\": 1,\n\t\"chnwp.com\": 1,\n\t\"chnyhg.com\": 1,\n\t\"chnyin.com\": 1,\n\t\"chofn.com\": 1,\n\t\"chongwujiaoyi.com\": 1,\n\t\"chouti.com\": 1,\n\t\"chris-tina.com\": 1,\n\t\"chrunsoft.com\": 1,\n\t\"chtangyao.com\": 1,\n\t\"chtf.com\": 1,\n\t\"chtgc.com\": 1,\n\t\"chtpe.com\": 1,\n\t\"chuandakaoyan.com\": 1,\n\t\"chuandong.com\": 1,\n\t\"chuangdian114.com\": 1,\n\t\"chuangelm.com\": 1,\n\t\"chuangshachang.com\": 1,\n\t\"chuangye.com\": 1,\n\t\"chuanke.com\": 1,\n\t\"chuanmeicn.com\": 1,\n\t\"chuban.cc\": 1,\n\t\"chubanzige.net\": 1,\n\t\"chuchuwan.com\": 1,\n\t\"chufw.com\": 1,\n\t\"chuguo78.com\": 1,\n\t\"chuguohome.com\": 1,\n\t\"chuguoqu.com\": 1,\n\t\"chuji8.com\": 1,\n\t\"chuncui.net\": 1,\n\t\"chunqiuwang.com\": 1,\n\t\"chunshuitang.com\": 1,\n\t\"chushan.com\": 1,\n\t\"chushixx.com\": 1,\n\t\"chuxiong.cc\": 1,\n\t\"chuyouke.com\": 1,\n\t\"chvacuum.com\": 1,\n\t\"chyee.com\": 1,\n\t\"chyxx.com\": 1,\n\t\"chzhw.com\": 1,\n\t\"chzpw.com\": 1,\n\t\"ci123.com\": 1,\n\t\"ci800.com\": 1,\n\t\"cibohui.com\": 1,\n\t\"cicaf.com\": 1,\n\t\"ciceme.com\": 1,\n\t\"cicgf.com\": 1,\n\t\"cicheng.org\": 1,\n\t\"cidianwang.com\": 1,\n\t\"ciehi.tv\": 1,\n\t\"cifco.net\": 1,\n\t\"ciftis.org\": 1,\n\t\"cigna-cmc.com\": 1,\n\t\"cignacmb.com\": 1,\n\t\"ciid.cc\": 1,\n\t\"ciid09.com\": 1,\n\t\"ciidoo.com\": 1,\n\t\"ciidsh.com\": 1,\n\t\"ciif-expo.com\": 1,\n\t\"ciku5.com\": 1,\n\t\"cilanie.com\": 1,\n\t\"cilogo.com\": 1,\n\t\"cio360.net\": 1,\n\t\"cioage.com\": 1,\n\t\"ciotimes.com\": 1,\n\t\"ciotour.com\": 1,\n\t\"cirmall.com\": 1,\n\t\"cis-expo.com\": 1,\n\t\"cisregister.com\": 1,\n\t\"cisskwt.com\": 1,\n\t\"citic.com\": 1,\n\t\"citicsf.com\": 1,\n\t\"citscq.com\": 1,\n\t\"citshlj.com\": 1,\n\t\"citsnj.com\": 1,\n\t\"citswx.com\": 1,\n\t\"citure.net\": 1,\n\t\"citvc.com\": 1,\n\t\"city8.com\": 1,\n\t\"citygaga.com\": 1,\n\t\"citygf.com\": 1,\n\t\"cityn.com\": 1,\n\t\"citysbs.com\": 1,\n\t\"cityup.org\": 1,\n\t\"cityy.com\": 1,\n\t\"civilness.com\": 1,\n\t\"ciweek.com\": 1,\n\t\"ciweekforum.com\": 1,\n\t\"cixiedu.net\": 1,\n\t\"ciyuan.co\": 1,\n\t\"cjdby.com\": 1,\n\t\"cjdby.net\": 1,\n\t\"cjfcw.com\": 1,\n\t\"cjfj.org\": 1,\n\t\"cjk3d.net\": 1,\n\t\"cjlap.com\": 1,\n\t\"cjol.com\": 1,\n\t\"cjolimg.com\": 1,\n\t\"cjrcsc.com\": 1,\n\t\"cjt1996.com\": 1,\n\t\"cjtzlss.com\": 1,\n\t\"cjxtv.com\": 1,\n\t\"cjzww.com\": 1,\n\t\"ckimg.com\": 1,\n\t\"ckplayer.com\": 1,\n\t\"cl2000.com\": 1,\n\t\"cl597.com\": 1,\n\t\"class01.com\": 1,\n\t\"classic023.com\": 1,\n\t\"clcjob.com\": 1,\n\t\"clcmw.com\": 1,\n\t\"cldol.com\": 1,\n\t\"cleanbird.com\": 1,\n\t\"clemf.com\": 1,\n\t\"clfg.com\": 1,\n\t\"clhweb.com\": 1,\n\t\"cli.im\": 1,\n\t\"cljmmm123.com\": 1,\n\t\"cljob.com\": 1,\n\t\"clner.com\": 1,\n\t\"clothr.com\": 1,\n\t\"clothw.com\": 1,\n\t\"cloudapply.com\": 1,\n\t\"cloverhostel.com\": 1,\n\t\"clpifa.com\": 1,\n\t\"clssn.com\": 1,\n\t\"cltt.org\": 1,\n\t\"clw8.net\": 1,\n\t\"clxww.com\": 1,\n\t\"clysolar.com\": 1,\n\t\"clzqdf.com\": 1,\n\t\"cm188.com\": 1,\n\t\"cmaaicpa.com\": 1,\n\t\"cmbchina.com\": 1,\n\t\"cmda.net\": 1,\n\t\"cmejob.com\": 1,\n\t\"cmfchina.com\": 1,\n\t\"cmfu.com\": 1,\n\t\"cmgame.com\": 1,\n\t\"cmhk.com\": 1,\n\t\"cmingde.com\": 1,\n\t\"cminin.com\": 1,\n\t\"cmiy.com\": 1,\n\t\"cmiyu.com\": 1,\n\t\"cmmri.com\": 1,\n\t\"cmol.com\": 1,\n\t\"cmpay.com\": 1,\n\t\"cmpbook.com\": 1,\n\t\"cmread.com\": 1,\n\t\"cms1924.org\": 1,\n\t\"cmstop.com\": 1,\n\t\"cmwb.com\": 1,\n\t\"cmxrcw.com\": 1,\n\t\"cmzd.com\": 1,\n\t\"cmzj.net\": 1,\n\t\"cmzz100.com\": 1,\n\t\"cn-edu.com\": 1,\n\t\"cn-em.com\": 1,\n\t\"cn-healthcare.com\": 1,\n\t\"cn-java.com\": 1,\n\t\"cn-jnrc.com\": 1,\n\t\"cn-ny.org\": 1,\n\t\"cn-truck.com\": 1,\n\t\"cn-tyn.com\": 1,\n\t\"cn.net\": 1,\n\t\"cn0-6.com\": 1,\n\t\"cn0556.com\": 1,\n\t\"cn0851.com\": 1,\n\t\"cn0874.com\": 1,\n\t\"cn0917.com\": 1,\n\t\"cn12365.org\": 1,\n\t\"cn21edu.com\": 1,\n\t\"cn2car.net\": 1,\n\t\"cn2che.com\": 1,\n\t\"cn357.com\": 1,\n\t\"cn5135.com\": 1,\n\t\"cn716.com\": 1,\n\t\"cn939.com\": 1,\n\t\"cnacc.tv\": 1,\n\t\"cnaction.com\": 1,\n\t\"cnad.com\": 1,\n\t\"cnadtop.com\": 1,\n\t\"cnaf.com\": 1,\n\t\"cnagri.com\": 1,\n\t\"cnair.com\": 1,\n\t\"cnal.com\": 1,\n\t\"cnalu.cc\": 1,\n\t\"cnanzhi.com\": 1,\n\t\"cnapt.com\": 1,\n\t\"cnautonews.com\": 1,\n\t\"cnbagnet.com\": 1,\n\t\"cnbaowen.net\": 1,\n\t\"cnbdw.com\": 1,\n\t\"cnbeta.com\": 1,\n\t\"cnbg.net\": 1,\n\t\"cnbidding.com\": 1,\n\t\"cnblogs.com\": 1,\n\t\"cnbmys.com\": 1,\n\t\"cnbook.net\": 1,\n\t\"cnbrand.org\": 1,\n\t\"cnbxfc.net\": 1,\n\t\"cnccar.com\": 1,\n\t\"cncelab.com\": 1,\n\t\"cncgw.net\": 1,\n\t\"cncgw.org\": 1,\n\t\"cnchache.net\": 1,\n\t\"cnchainnet.com\": 1,\n\t\"cnchu.com\": 1,\n\t\"cncma.org\": 1,\n\t\"cncn.com\": 1,\n\t\"cncn.net\": 1,\n\t\"cncnc.org\": 1,\n\t\"cncoke.com\": 1,\n\t\"cncookernet.com\": 1,\n\t\"cncotton.com\": 1,\n\t\"cncproduct.com\": 1,\n\t\"cncraftinfo.com\": 1,\n\t\"cncrk.com\": 1,\n\t\"cncsj.net\": 1,\n\t\"cncxhw.com\": 1,\n\t\"cnd8.com\": 1,\n\t\"cndbscw.com\": 1,\n\t\"cndds.com\": 1,\n\t\"cndeaf.com\": 1,\n\t\"cndesign.com\": 1,\n\t\"cndewei.com\": 1,\n\t\"cndianlu.net\": 1,\n\t\"cndiaosu.net\": 1,\n\t\"cndingxi.com\": 1,\n\t\"cndlsh.com\": 1,\n\t\"cndns.com\": 1,\n\t\"cndoornet.com\": 1,\n\t\"cndoors.com\": 1,\n\t\"cndrsq.com\": 1,\n\t\"cndrynet.com\": 1,\n\t\"cndsi.com\": 1,\n\t\"cndw.com\": 1,\n\t\"cndwine.com\": 1,\n\t\"cndzys.com\": 1,\n\t\"cndzz.com\": 1,\n\t\"cne163.com\": 1,\n\t\"cnelc.com\": 1,\n\t\"cnele.com\": 1,\n\t\"cneln.net\": 1,\n\t\"cnena.com\": 1,\n\t\"cnenergy.org\": 1,\n\t\"cnenzyme.com\": 1,\n\t\"cneol.net\": 1,\n\t\"cnep001.com\": 1,\n\t\"cnepaper.com\": 1,\n\t\"cnepub.com\": 1,\n\t\"cnern.org\": 1,\n\t\"cnestate.com\": 1,\n\t\"cnfabric.net\": 1,\n\t\"cnfda.com\": 1,\n\t\"cnfdnet.com\": 1,\n\t\"cnfeol.com\": 1,\n\t\"cnffi.com\": 1,\n\t\"cnfilternet.com\": 1,\n\t\"cnfirst.net\": 1,\n\t\"cnfla.com\": 1,\n\t\"cnfluidnet.com\": 1,\n\t\"cnfol.com\": 1,\n\t\"cnfolimg.com\": 1,\n\t\"cnfoodsafety.com\": 1,\n\t\"cnforex.com\": 1,\n\t\"cnfruit.com\": 1,\n\t\"cnfxj.org\": 1,\n\t\"cnfzflw.com\": 1,\n\t\"cngaosu.com\": 1,\n\t\"cngba.com\": 1,\n\t\"cngbbs.com\": 1,\n\t\"cngdw.net\": 1,\n\t\"cngold.org\": 1,\n\t\"cngoldres.com\": 1,\n\t\"cngoto.com\": 1,\n\t\"cngpc.com\": 1,\n\t\"cngrain.com\": 1,\n\t\"cngrain.net\": 1,\n\t\"cngsda.net\": 1,\n\t\"cngulu.com\": 1,\n\t\"cngzbj.com\": 1,\n\t\"cnhan.com\": 1,\n\t\"cnhangyun.com\": 1,\n\t\"cnhaomen.com\": 1,\n\t\"cnhbsb.net\": 1,\n\t\"cnhbw.net\": 1,\n\t\"cnhcg.org\": 1,\n\t\"cnhengqi.net\": 1,\n\t\"cnhetianyu.com\": 1,\n\t\"cnhm.net\": 1,\n\t\"cnhmsq.com\": 1,\n\t\"cnhouse.com\": 1,\n\t\"cnhuadong.net\": 1,\n\t\"cnhubei.com\": 1,\n\t\"cnhvacr.com\": 1,\n\t\"cnhvacrnet.com\": 1,\n\t\"cnhyc.com\": 1,\n\t\"cnhyw.net\": 1,\n\t\"cnhzpjy.com\": 1,\n\t\"cnicif.com\": 1,\n\t\"cnijoy.com\": 1,\n\t\"cnimba.com\": 1,\n\t\"cnin-net.com\": 1,\n\t\"cninfo.net\": 1,\n\t\"cninsp.com\": 1,\n\t\"cnipr.com\": 1,\n\t\"cnips.org\": 1,\n\t\"cnispunion.org\": 1,\n\t\"cnitblog.com\": 1,\n\t\"cnitdc.com\": 1,\n\t\"cnjdyp.com\": 1,\n\t\"cnjdz.net\": 1,\n\t\"cnjiaju.com\": 1,\n\t\"cnjiajun.com\": 1,\n\t\"cnjiaren.com\": 1,\n\t\"cnjidan.com\": 1,\n\t\"cnjj.com\": 1,\n\t\"cnjjbc.com\": 1,\n\t\"cnjly.com\": 1,\n\t\"cnjnsb.com\": 1,\n\t\"cnjnw.net\": 1,\n\t\"cnjob.com\": 1,\n\t\"cnjobedu.com\": 1,\n\t\"cnjskc.net\": 1,\n\t\"cnjsqw.com\": 1,\n\t\"cnjutiao.com\": 1,\n\t\"cnjxol.com\": 1,\n\t\"cnjy99.com\": 1,\n\t\"cnjyzb.net\": 1,\n\t\"cnjzjj.com\": 1,\n\t\"cnkang.com\": 1,\n\t\"cnkfjob.com\": 1,\n\t\"cnki.net\": 1,\n\t\"cnkjz.com\": 1,\n\t\"cnkssb.net\": 1,\n\t\"cnky.net\": 1,\n\t\"cnky.org\": 1,\n\t\"cnlacenet.com\": 1,\n\t\"cnlai.com\": 1,\n\t\"cnled114.com\": 1,\n\t\"cnledw.com\": 1,\n\t\"cnlight.com\": 1,\n\t\"cnlightnet.com\": 1,\n\t\"cnlinfo.net\": 1,\n\t\"cnlist.org\": 1,\n\t\"cnliti.com\": 1,\n\t\"cnlive.com\": 1,\n\t\"cnlogo8.com\": 1,\n\t\"cnlsqy.com\": 1,\n\t\"cnlsspxx.com\": 1,\n\t\"cnluan.com\": 1,\n\t\"cnluye.com\": 1,\n\t\"cnlyrcw.com\": 1,\n\t\"cnmcg-expo.com\": 1,\n\t\"cnmd.net\": 1,\n\t\"cnmeiw.com\": 1,\n\t\"cnmet.com\": 1,\n\t\"cnmf.net\": 1,\n\t\"cnmmhh.com\": 1,\n\t\"cnmo.com\": 1,\n\t\"cnmsw.net\": 1,\n\t\"cnnaihuo.com\": 1,\n\t\"cnnauto.com\": 1,\n\t\"cnnb.com\": 1,\n\t\"cnnb.net\": 1,\n\t\"cnnbfdc.com\": 1,\n\t\"cnnbpi.com\": 1,\n\t\"cnnbzj.com\": 1,\n\t\"cnnfhy.com\": 1,\n\t\"cnnyjx.net\": 1,\n\t\"cnnzxx.com\": 1,\n\t\"cnoa360.com\": 1,\n\t\"cnobol.com\": 1,\n\t\"cnoee.com\": 1,\n\t\"cnool.net\": 1,\n\t\"cnpatent.com\": 1,\n\t\"cnpcjob.com\": 1,\n\t\"cnpeak.com\": 1,\n\t\"cnpec.net\": 1,\n\t\"cnpenjing.com\": 1,\n\t\"cnphotos.net\": 1,\n\t\"cnpickups.com\": 1,\n\t\"cnpignet.com\": 1,\n\t\"cnpmetal.com\": 1,\n\t\"cnpowdernet.com\": 1,\n\t\"cnpre.com\": 1,\n\t\"cnprophoto.com\": 1,\n\t\"cnpsy.net\": 1,\n\t\"cnpubg.com\": 1,\n\t\"cnput.com\": 1,\n\t\"cnpv.com\": 1,\n\t\"cnqipei.net\": 1,\n\t\"cnqjc.com\": 1,\n\t\"cnqjw.com\": 1,\n\t\"cnqr.org\": 1,\n\t\"cnradio.com\": 1,\n\t\"cnrdn.com\": 1,\n\t\"cnread.net\": 1,\n\t\"cnree.com\": 1,\n\t\"cnrencai.com\": 1,\n\t\"cnrepark.com\": 1,\n\t\"cnrexue.com\": 1,\n\t\"cnrmobile.com\": 1,\n\t\"cnsaw.com\": 1,\n\t\"cnsb.org\": 1,\n\t\"cnsb.tv\": 1,\n\t\"cnscdc.com\": 1,\n\t\"cnscore.com\": 1,\n\t\"cnsdjxw.com\": 1,\n\t\"cnsea-pump.com\": 1,\n\t\"cnsepu.com\": 1,\n\t\"cnshicai.net\": 1,\n\t\"cnshipnet.com\": 1,\n\t\"cnshipping.com\": 1,\n\t\"cnsikao.com\": 1,\n\t\"cnsilver.com\": 1,\n\t\"cnslfp.com\": 1,\n\t\"cnsnpj.com\": 1,\n\t\"cnsoftnews.com\": 1,\n\t\"cnsphoto.com\": 1,\n\t\"cnsppl.com\": 1,\n\t\"cnssh.net\": 1,\n\t\"cnstm.com\": 1,\n\t\"cnstock.com\": 1,\n\t\"cnsuning.com\": 1,\n\t\"cnsuv.com\": 1,\n\t\"cnswys.mobi\": 1,\n\t\"cnsynews.com\": 1,\n\t\"cnsyyq.net\": 1,\n\t\"cnszw.net\": 1,\n\t\"cnta.com\": 1,\n\t\"cntaijiquan.com\": 1,\n\t\"cntaiping.com\": 1,\n\t\"cntaotax.net\": 1,\n\t\"cntc.com\": 1,\n\t\"cntexjob.com\": 1,\n\t\"cntff.com\": 1,\n\t\"cntheory.com\": 1,\n\t\"cntianliao.com\": 1,\n\t\"cntizi.com\": 1,\n\t\"cntour2.com\": 1,\n\t\"cntour365.com\": 1,\n\t\"cntrades.com\": 1,\n\t\"cntronics.com\": 1,\n\t\"cntsmr.com\": 1,\n\t\"cntv.net\": 1,\n\t\"cntvchina.com\": 1,\n\t\"cntxw.com\": 1,\n\t\"cnutg.com\": 1,\n\t\"cnv168.com\": 1,\n\t\"cnvdf.com\": 1,\n\t\"cnwav.com\": 1,\n\t\"cnwear.com\": 1,\n\t\"cnwebshow.com\": 1,\n\t\"cnwee.com\": 1,\n\t\"cnwen.net\": 1,\n\t\"cnwenshi.net\": 1,\n\t\"cnwep.com\": 1,\n\t\"cnwest.com\": 1,\n\t\"cnwest88.com\": 1,\n\t\"cnwinenews.com\": 1,\n\t\"cnwlkj.com\": 1,\n\t\"cnwlxxw.com\": 1,\n\t\"cnwnews.com\": 1,\n\t\"cnworld.net\": 1,\n\t\"cnwpem.com\": 1,\n\t\"cnwuhu.com\": 1,\n\t\"cnwuyun.com\": 1,\n\t\"cnwzcx.com\": 1,\n\t\"cnxad.com\": 1,\n\t\"cnxds.com\": 1,\n\t\"cnxiantao.com\": 1,\n\t\"cnxianzai.com\": 1,\n\t\"cnxibu.com\": 1,\n\t\"cnxishui.net\": 1,\n\t\"cnxk.org\": 1,\n\t\"cnxnyw.com\": 1,\n\t\"cnycedu.com\": 1,\n\t\"cnyigui.com\": 1,\n\t\"cnync.com\": 1,\n\t\"cnys.com\": 1,\n\t\"cnyu.com\": 1,\n\t\"cnyw.net\": 1,\n\t\"cnzhantuan.com\": 1,\n\t\"cnzhengmu.com\": 1,\n\t\"cnzhixiang.com\": 1,\n\t\"cnzhutan.net\": 1,\n\t\"cnzicai.com\": 1,\n\t\"cnzjgc.com\": 1,\n\t\"cnzjnet.com\": 1,\n\t\"cnzjqi.com\": 1,\n\t\"cnzpxx.com\": 1,\n\t\"cnzsyz.com\": 1,\n\t\"cnztjx.com\": 1,\n\t\"cnzx.info\": 1,\n\t\"cnzxsoft.com\": 1,\n\t\"cnzyjc.com\": 1,\n\t\"cnzz.com\": 1,\n\t\"cnzz.net\": 1,\n\t\"co188.com\": 1,\n\t\"coal-link.com\": 1,\n\t\"coalcn.com\": 1,\n\t\"coalstudy.com\": 1,\n\t\"coating-cn.com\": 1,\n\t\"coatingol.com\": 1,\n\t\"coco90.com\": 1,\n\t\"cocoachina.com\": 1,\n\t\"cocodiy.com\": 1,\n\t\"cocoren.com\": 1,\n\t\"cocos2d-x.org\": 1,\n\t\"codefans.net\": 1,\n\t\"codesky.net\": 1,\n\t\"cofco.com\": 1,\n\t\"cofeed.com\": 1,\n\t\"cofool.com\": 1,\n\t\"coinabc.com\": 1,\n\t\"cokeic.com\": 1,\n\t\"coli688.com\": 1,\n\t\"comac.cc\": 1,\n\t\"combadc.com\": 1,\n\t\"comenb.com\": 1,\n\t\"comeshang.com\": 1,\n\t\"comicdd.com\": 1,\n\t\"comicer.com\": 1,\n\t\"comicfans.net\": 1,\n\t\"comicyu.com\": 1,\n\t\"comingchina.com\": 1,\n\t\"companycn.com\": 1,\n\t\"compete.com\": 1,\n\t\"componentcn.com\": 1,\n\t\"comra.org\": 1,\n\t\"comsenz.com\": 1,\n\t\"comuu.com\": 1,\n\t\"concrete365.com\": 1,\n\t\"coo8.com\": 1,\n\t\"coocaa.com\": 1,\n\t\"coodir.com\": 1,\n\t\"cooflower.com\": 1,\n\t\"cooguo.com\": 1,\n\t\"cool-de.com\": 1,\n\t\"cool999.com\": 1,\n\t\"coolchuan.com\": 1,\n\t\"cooldock.com\": 1,\n\t\"coolgy.com\": 1,\n\t\"coolling.net\": 1,\n\t\"coolool.com\": 1,\n\t\"coolsc.net\": 1,\n\t\"cooltuku.com\": 1,\n\t\"coolxap.com\": 1,\n\t\"copperhome.net\": 1,\n\t\"cosco.com\": 1,\n\t\"cosdiv.com\": 1,\n\t\"cosplay8.com\": 1,\n\t\"cost168.com\": 1,\n\t\"cottonchina.org\": 1,\n\t\"coubei.com\": 1,\n\t\"cp2y.com\": 1,\n\t\"cp3d.net\": 1,\n\t\"cp520.com\": 1,\n\t\"cp520.net\": 1,\n\t\"cpa800.com\": 1,\n\t\"cpaedu.org\": 1,\n\t\"cpato.com\": 1,\n\t\"cpbay.com\": 1,\n\t\"cpc-ex.com\": 1,\n\t\"cpdyj.com\": 1,\n\t\"cpecc.net\": 1,\n\t\"cphoto.net\": 1,\n\t\"cphoto.org\": 1,\n\t\"cpifa.org\": 1,\n\t\"cppc360.com\": 1,\n\t\"cppccnews.com\": 1,\n\t\"cppfoto.com\": 1,\n\t\"cpplay.com\": 1,\n\t\"cpplay.net\": 1,\n\t\"cps800.com\": 1,\n\t\"cpspew.com\": 1,\n\t\"cpspt.com\": 1,\n\t\"cptjob.com\": 1,\n\t\"cq.cm\": 1,\n\t\"cq315.org\": 1,\n\t\"cq315house.com\": 1,\n\t\"cq6.com\": 1,\n\t\"cqacmm.com\": 1,\n\t\"cqcoal.com\": 1,\n\t\"cqcp.net\": 1,\n\t\"cqcsrc.com\": 1,\n\t\"cqdnet.com\": 1,\n\t\"cqdxy.com\": 1,\n\t\"cqfire.com\": 1,\n\t\"cqfygzfw.com\": 1,\n\t\"cqgh.org\": 1,\n\t\"cqgj.net\": 1,\n\t\"cqgtjt.com\": 1,\n\t\"cqhc.org\": 1,\n\t\"cqism.com\": 1,\n\t\"cqjbly.com\": 1,\n\t\"cqjiaz.com\": 1,\n\t\"cqjjnet.com\": 1,\n\t\"cqjjrcw.com\": 1,\n\t\"cqjob.com\": 1,\n\t\"cqjsrc.com\": 1,\n\t\"cqjsxx.com\": 1,\n\t\"cqjxjp.com\": 1,\n\t\"cqkjwx.net\": 1,\n\t\"cqkx.com\": 1,\n\t\"cqleaders.com\": 1,\n\t\"cqlozz.com\": 1,\n\t\"cqlp.com\": 1,\n\t\"cqmama.net\": 1,\n\t\"cqmap.com\": 1,\n\t\"cqme.net\": 1,\n\t\"cqmmgo.com\": 1,\n\t\"cqnews.net\": 1,\n\t\"cqour.com\": 1,\n\t\"cqph.com\": 1,\n\t\"cqqnb.net\": 1,\n\t\"cqrc.net\": 1,\n\t\"cqsalt.com\": 1,\n\t\"cqshangceng.com\": 1,\n\t\"cqshebao.net\": 1,\n\t\"cqshipping.com\": 1,\n\t\"cqskl.com\": 1,\n\t\"cqspbxz.com\": 1,\n\t\"cqsq.com\": 1,\n\t\"cqswyq.com\": 1,\n\t\"cqsy.org\": 1,\n\t\"cqtiyu.com\": 1,\n\t\"cqtlrc.com\": 1,\n\t\"cqtn.com\": 1,\n\t\"cquae.com\": 1,\n\t\"cqueap.com\": 1,\n\t\"cqvip.com\": 1,\n\t\"cqwaitan.com\": 1,\n\t\"cqwin.com\": 1,\n\t\"cqwsrc.com\": 1,\n\t\"cqwxnews.net\": 1,\n\t\"cqxszx.net\": 1,\n\t\"cqxyw.com\": 1,\n\t\"cqyc.net\": 1,\n\t\"cqyznews.com\": 1,\n\t\"cqzls.com\": 1,\n\t\"cqzol.com\": 1,\n\t\"cqzprc.com\": 1,\n\t\"cqzql.com\": 1,\n\t\"cqzx.org\": 1,\n\t\"cr-expo.com\": 1,\n\t\"cr-nielsen.com\": 1,\n\t\"cr173.com\": 1,\n\t\"crecg.com\": 1,\n\t\"cric.com\": 1,\n\t\"crm1001.com\": 1,\n\t\"crmgz.com\": 1,\n\t\"crossmo.com\": 1,\n\t\"crsky.com\": 1,\n\t\"crystaledu.com\": 1,\n\t\"cs090.com\": 1,\n\t\"cs53.com\": 1,\n\t\"cs6s.com\": 1,\n\t\"cs81.com\": 1,\n\t\"csacc.org\": 1,\n\t\"csadec.com\": 1,\n\t\"csair.com\": 1,\n\t\"csau.com\": 1,\n\t\"csbaidu.net\": 1,\n\t\"csbew.com\": 1,\n\t\"csc86.com\": 1,\n\t\"cscb2b.com\": 1,\n\t\"cscdf.org\": 1,\n\t\"cscec.com\": 1,\n\t\"cscoal.com\": 1,\n\t\"cscse-germany.com\": 1,\n\t\"cscsf.com\": 1,\n\t\"csdn.net\": 1,\n\t\"cseac.com\": 1,\n\t\"csfcw.com\": 1,\n\t\"csgholding.com\": 1,\n\t\"csgia.net\": 1,\n\t\"csgm168.com\": 1,\n\t\"cshaojob.com\": 1,\n\t\"cskaoyan.com\": 1,\n\t\"cslleather.com\": 1,\n\t\"cslygs.com\": 1,\n\t\"csmama.net\": 1,\n\t\"csnaxin.com\": 1,\n\t\"csoei.com\": 1,\n\t\"csoly.com\": 1,\n\t\"csqc.com\": 1,\n\t\"csrcsc.com\": 1,\n\t\"cssmoban.com\": 1,\n\t\"cssponline.com\": 1,\n\t\"cssqt.com\": 1,\n\t\"csstoday.net\": 1,\n\t\"csteelnews.com\": 1,\n\t\"cstif.com\": 1,\n\t\"csueus.com\": 1,\n\t\"csvw.com\": 1,\n\t\"csxb.com\": 1,\n\t\"csxnews.com\": 1,\n\t\"csxww.com\": 1,\n\t\"csyamei.com\": 1,\n\t\"csyjx.com\": 1,\n\t\"csytv.com\": 1,\n\t\"cszhan.com\": 1,\n\t\"cszhibei.com\": 1,\n\t\"cszlyy.net\": 1,\n\t\"cszpw.com\": 1,\n\t\"csztv.com\": 1,\n\t\"ct-xz.com\": 1,\n\t\"ct10000.com\": 1,\n\t\"ct165.com\": 1,\n\t\"ct597.com\": 1,\n\t\"ctaoci.com\": 1,\n\t\"ctcnn.com\": 1,\n\t\"ctctc.com\": 1,\n\t\"ctcte.com\": 1,\n\t\"ctdsb.net\": 1,\n\t\"cteaw.com\": 1,\n\t\"cthnet.com\": 1,\n\t\"cthy.com\": 1,\n\t\"ctiec.net\": 1,\n\t\"ctiforum.com\": 1,\n\t\"ctjy.net\": 1,\n\t\"ctma.net\": 1,\n\t\"ctn1986.com\": 1,\n\t\"ctocio.com\": 1,\n\t\"ctppumps.com\": 1,\n\t\"ctqcp.com\": 1,\n\t\"ctraining365.com\": 1,\n\t\"ctrip.co.kr\": 1,\n\t\"ctrip.com\": 1,\n\t\"ctrip.com.hk\": 1,\n\t\"ctsdc.com\": 1,\n\t\"ctsho.com\": 1,\n\t\"ctsmice.com\": 1,\n\t\"ctsscs.com\": 1,\n\t\"ctsto.com\": 1,\n\t\"cttm.net\": 1,\n\t\"ctxyw.com\": 1,\n\t\"cubead.com\": 1,\n\t\"cuctv.com\": 1,\n\t\"cuew.com\": 1,\n\t\"cufeyk.org\": 1,\n\t\"cug2313.com\": 1,\n\t\"cuilai.com\": 1,\n\t\"cunan.com\": 1,\n\t\"cuncun8.com\": 1,\n\t\"cuncunle.com\": 1,\n\t\"cunlie.com\": 1,\n\t\"cuntuba.com\": 1,\n\t\"cuplayer.com\": 1,\n\t\"custeel.com\": 1,\n\t\"cut35.com\": 1,\n\t\"cutv.com\": 1,\n\t\"cuwell.com\": 1,\n\t\"cv-nz.com\": 1,\n\t\"cv51.com\": 1,\n\t\"cvcri.com\": 1,\n\t\"cw100.com\": 1,\n\t\"cwan.com\": 1,\n\t\"cwddd.com\": 1,\n\t\"cwen.org\": 1,\n\t\"cwestc.com\": 1,\n\t\"cweun.org\": 1,\n\t\"cwmaya.com\": 1,\n\t\"cwmining.com\": 1,\n\t\"cwroom.com\": 1,\n\t\"cwun.org\": 1,\n\t\"cwyan.com\": 1,\n\t\"cwyx.com\": 1,\n\t\"cxcyds.com\": 1,\n\t\"cxdpsp.com\": 1,\n\t\"cxedu.net\": 1,\n\t\"cxfish.com\": 1,\n\t\"cxh99.com\": 1,\n\t\"cxhr.com\": 1,\n\t\"cxt8.com\": 1,\n\t\"cxtuku.com\": 1,\n\t\"cxw.com\": 1,\n\t\"cxwz.org\": 1,\n\t\"cxzw.com\": 1,\n\t\"cy.com\": 1,\n\t\"cy580.com\": 1,\n\t\"cycnet.com\": 1,\n\t\"cyedu.org\": 1,\n\t\"cyegushi.com\": 1,\n\t\"cyguilin.com\": 1,\n\t\"cyheb.com\": 1,\n\t\"cyikao.com\": 1,\n\t\"cyipu.com\": 1,\n\t\"cynee.net\": 1,\n\t\"cyol.com\": 1,\n\t\"cyol.net\": 1,\n\t\"cyw100.com\": 1,\n\t\"cyz7.com\": 1,\n\t\"cyzypm.com\": 1,\n\t\"cz0355.com\": 1,\n\t\"cz121.com\": 1,\n\t\"cz365.com\": 1,\n\t\"czairport.com\": 1,\n\t\"czbank.com\": 1,\n\t\"czbfw.com\": 1,\n\t\"czcaizi.com\": 1,\n\t\"czcits.com\": 1,\n\t\"czcqw.com\": 1,\n\t\"czepb.com\": 1,\n\t\"czfcw.com\": 1,\n\t\"czflcp.com\": 1,\n\t\"czgjj.com\": 1,\n\t\"czgm.com\": 1,\n\t\"czgongzuo.com\": 1,\n\t\"czgs.net\": 1,\n\t\"czhr.com\": 1,\n\t\"czinfo.net\": 1,\n\t\"czlawyer.org\": 1,\n\t\"czlook.com\": 1,\n\t\"czmei.com\": 1,\n\t\"czmuseum.com\": 1,\n\t\"czonline.net\": 1,\n\t\"czqcw.com\": 1,\n\t\"czrc114.com\": 1,\n\t\"czrcw.com\": 1,\n\t\"czrxw.com\": 1,\n\t\"czsgjj.com\": 1,\n\t\"czsnlw.com\": 1,\n\t\"czsrc.com\": 1,\n\t\"cztaole.com\": 1,\n\t\"cztour.com\": 1,\n\t\"cztv.com\": 1,\n\t\"cztv.tv\": 1,\n\t\"cztv6.com\": 1,\n\t\"cztzy.com\": 1,\n\t\"czwljyw.com\": 1,\n\t\"czwlzx.com\": 1,\n\t\"czxiu.com\": 1,\n\t\"czxls.com\": 1,\n\t\"czxnews.com\": 1,\n\t\"czyts.net\": 1,\n\t\"czzp.com\": 1,\n\t\"czzsw.com\": 1,\n\t\"d-edu.com\": 1,\n\t\"d0818.com\": 1,\n\t\"d17.cc\": 1,\n\t\"d1cm.com\": 1,\n\t\"d1com.com\": 1,\n\t\"d1net.com\": 1,\n\t\"d1xz.net\": 1,\n\t\"d399.com\": 1,\n\t\"d586.com\": 1,\n\t\"d7ol.com\": 1,\n\t\"d8360.com\": 1,\n\t\"d8wed.com\": 1,\n\t\"d9read.net\": 1,\n\t\"d9soft.com\": 1,\n\t\"daba.com\": 1,\n\t\"dabandichan.com\": 1,\n\t\"dabaoku.com\": 1,\n\t\"dabiaoji.org\": 1,\n\t\"dacai.com\": 1,\n\t\"dachangtex.com\": 1,\n\t\"dachenglaw.com\": 1,\n\t\"dachengnet.com\": 1,\n\t\"dada360.com\": 1,\n\t\"dadou.com\": 1,\n\t\"daeee.com\": 1,\n\t\"dafengso.com\": 1,\n\t\"daflw.com\": 1,\n\t\"dagangcheng.com\": 1,\n\t\"dagong.com\": 1,\n\t\"daguantao.com\": 1,\n\t\"daguirc.com\": 1,\n\t\"daguozhenzimiao.com\": 1,\n\t\"dahainan.com\": 1,\n\t\"dahangzhou.com\": 1,\n\t\"dahecc.com\": 1,\n\t\"dahecw.com\": 1,\n\t\"dahei.com\": 1,\n\t\"daheshui.com\": 1,\n\t\"dahew.com\": 1,\n\t\"dahuaping.com\": 1,\n\t\"dahuatech.com\": 1,\n\t\"dahuawang.com\": 1,\n\t\"daihr.com\": 1,\n\t\"dailiba.com\": 1,\n\t\"dailyqd.com\": 1,\n\t\"daimg.com\": 1,\n\t\"dairy123.com\": 1,\n\t\"dairyexpo.com\": 1,\n\t\"daishan.com\": 1,\n\t\"daishu.com\": 1,\n\t\"daixiaomi.com\": 1,\n\t\"daixiwan.com\": 1,\n\t\"dajiabao.com\": 1,\n\t\"dajianet.com\": 1,\n\t\"dajiangsai.org\": 1,\n\t\"dajiawan.com\": 1,\n\t\"dajiazhao.com\": 1,\n\t\"dajie.com\": 1,\n\t\"dajieimg.com\": 1,\n\t\"dajunshi.com\": 1,\n\t\"dakawang.com\": 1,\n\t\"dalian-gov.net\": 1,\n\t\"dalianjob.com\": 1,\n\t\"dalianxueche.com\": 1,\n\t\"dalidaily.com\": 1,\n\t\"dalings.com\": 1,\n\t\"dalooss.com\": 1,\n\t\"daman.cc\": 1,\n\t\"damuzzz.com\": 1,\n\t\"dance365.com\": 1,\n\t\"danding.com\": 1,\n\t\"dandongjob.com\": 1,\n\t\"dangbei.com\": 1,\n\t\"dangdaiyishu.com\": 1,\n\t\"dangdang.com\": 1,\n\t\"dangjian.com\": 1,\n\t\"danhuang.cc\": 1,\n\t\"danji6.com\": 1,\n\t\"danji8.com\": 1,\n\t\"danpinku.com\": 1,\n\t\"danyang.com\": 1,\n\t\"danyanghr.com\": 1,\n\t\"danyrc.com\": 1,\n\t\"danzhengyuan.com\": 1,\n\t\"danzhoujob.net\": 1,\n\t\"dao50.com\": 1,\n\t\"daodao.com\": 1,\n\t\"daodongart.net\": 1,\n\t\"daogoubang.com\": 1,\n\t\"daoguo.com\": 1,\n\t\"daoguqihuo.com\": 1,\n\t\"daomin.net\": 1,\n\t\"daoxila.com\": 1,\n\t\"daoxila.net\": 1,\n\t\"dapu.com\": 1,\n\t\"dapuimg.com\": 1,\n\t\"daqi.com\": 1,\n\t\"daqin029.com\": 1,\n\t\"darczpw.com\": 1,\n\t\"darryring.com\": 1,\n\t\"dashi.com\": 1,\n\t\"dashilike.com\": 1,\n\t\"dashipin.com\": 1,\n\t\"dasuanwang.com\": 1,\n\t\"data68.com\": 1,\n\t\"datang5.com\": 1,\n\t\"dataodu.com\": 1,\n\t\"datatang.com\": 1,\n\t\"datianmen.com\": 1,\n\t\"datihu.com\": 1,\n\t\"datouyouxi.com\": 1,\n\t\"davinfo.com\": 1,\n\t\"dawanghui.com\": 1,\n\t\"daxi.com\": 1,\n\t\"daxiangkeji.com\": 1,\n\t\"daxiangnews.com\": 1,\n\t\"daxiangrc.com\": 1,\n\t\"daxiangwang.com\": 1,\n\t\"daxin360.com\": 1,\n\t\"daxue52.com\": 1,\n\t\"daxuecn.com\": 1,\n\t\"daxuewa.com\": 1,\n\t\"dayanzhu.com\": 1,\n\t\"dayirc.com\": 1,\n\t\"dayiwang.com\": 1,\n\t\"dayiwangluo.com\": 1,\n\t\"dayoo.com\": 1,\n\t\"dayou123.com\": 1,\n\t\"dayouwooden.com\": 1,\n\t\"dayuchang.com\": 1,\n\t\"dayunmotor.com\": 1,\n\t\"dayuonline.com\": 1,\n\t\"dazhangqiu.com\": 1,\n\t\"dazhe5.com\": 1,\n\t\"dazhenzimiao.com\": 1,\n\t\"dazhicm.com\": 1,\n\t\"dazhongemiao.com\": 1,\n\t\"dazhonghr.com\": 1,\n\t\"dazhongzhou.com\": 1,\n\t\"dazhoushan.com\": 1,\n\t\"dazhuangwang.com\": 1,\n\t\"dazhurc.com\": 1,\n\t\"dazibo.com\": 1,\n\t\"dazpin.com\": 1,\n\t\"db-nw.com\": 1,\n\t\"db2car.com\": 1,\n\t\"dbafmh.com\": 1,\n\t\"dbank.com\": 1,\n\t\"dbh123.net\": 1,\n\t\"dcdjt.com\": 1,\n\t\"dcdrcw.com\": 1,\n\t\"dcement.com\": 1,\n\t\"dcfjw.com\": 1,\n\t\"dchpv.com\": 1,\n\t\"dcjianghu.com\": 1,\n\t\"dcjol.com\": 1,\n\t\"dcn88.com\": 1,\n\t\"dcwzg.com\": 1,\n\t\"dd001.net\": 1,\n\t\"dd13.tv\": 1,\n\t\"dd188.com\": 1,\n\t\"dd288.com\": 1,\n\t\"dd373.com\": 1,\n\t\"ddahr.net\": 1,\n\t\"ddc999.com\": 1,\n\t\"ddeng.com\": 1,\n\t\"ddfchina.com\": 1,\n\t\"ddfddf.org\": 1,\n\t\"ddjob.net\": 1,\n\t\"ddkspdt.com\": 1,\n\t\"ddmap.com\": 1,\n\t\"ddmapimg.com\": 1,\n\t\"ddmeishi.com\": 1,\n\t\"ddoo.cc\": 1,\n\t\"ddooo.com\": 1,\n\t\"ddove.com\": 1,\n\t\"ddport.com\": 1,\n\t\"ddqcw.com\": 1,\n\t\"ddttn.com\": 1,\n\t\"ddvip.com\": 1,\n\t\"ddxia.com\": 1,\n\t\"decorcn.com\": 1,\n\t\"decwhy.com\": 1,\n\t\"dedecms.com\": 1,\n\t\"dedewan.com\": 1,\n\t\"deemstone.net\": 1,\n\t\"defensecn.com\": 1,\n\t\"dehua.la\": 1,\n\t\"dehua.net\": 1,\n\t\"dehuaca.com\": 1,\n\t\"dehuata.net\": 1,\n\t\"demage.com\": 1,\n\t\"demaxiya.com\": 1,\n\t\"demingtang.com\": 1,\n\t\"deng6.com\": 1,\n\t\"denghuo.com\": 1,\n\t\"denglu.cc\": 1,\n\t\"dengzhou.tv\": 1,\n\t\"deppon.com\": 1,\n\t\"derenbs.com\": 1,\n\t\"design521.com\": 1,\n\t\"desktopsky.com\": 1,\n\t\"desktx.com\": 1,\n\t\"destoon.com\": 1,\n\t\"deyetown.com\": 1,\n\t\"deyi.com\": 1,\n\t\"deyiso.com\": 1,\n\t\"dezhi.com\": 1,\n\t\"dezhong365.com\": 1,\n\t\"dezhoudaily.com\": 1,\n\t\"df-118.com\": 1,\n\t\"df818.com\": 1,\n\t\"dfcfw.com\": 1,\n\t\"dffsj.com\": 1,\n\t\"dfhon.com\": 1,\n\t\"dfjyhome.com\": 1,\n\t\"dflgnc.com\": 1,\n\t\"dfsrcw.com\": 1,\n\t\"dfstw.com\": 1,\n\t\"dfysw.net\": 1,\n\t\"dfyuan.com\": 1,\n\t\"dfzpw.net\": 1,\n\t\"dg-dx.com\": 1,\n\t\"dg121.com\": 1,\n\t\"dg699.com\": 1,\n\t\"dgaccpx.com\": 1,\n\t\"dgcaomei.com\": 1,\n\t\"dggcc.com\": 1,\n\t\"dginfo.com\": 1,\n\t\"dgjt.com\": 1,\n\t\"dgjy.net\": 1,\n\t\"dgmama.net\": 1,\n\t\"dgpx88.com\": 1,\n\t\"dgqjj.com\": 1,\n\t\"dgrcpq.com\": 1,\n\t\"dgs6.com\": 1,\n\t\"dgsme.com\": 1,\n\t\"dgwxys.com\": 1,\n\t\"dgzstx.com\": 1,\n\t\"dgzzm.com\": 1,\n\t\"dh597.com\": 1,\n\t\"dh818.com\": 1,\n\t\"dhabc.net\": 1,\n\t\"dhang123.com\": 1,\n\t\"dhcmzs.com\": 1,\n\t\"dheart.net\": 1,\n\t\"dhgate.com\": 1,\n\t\"dhifi.com\": 1,\n\t\"dhrczx.com\": 1,\n\t\"dhteach.com\": 1,\n\t\"dian5000.com\": 1,\n\t\"diandian.com\": 1,\n\t\"diandong.com\": 1,\n\t\"dianhangjia.com\": 1,\n\t\"dianji007.com\": 1,\n\t\"dianli114.com\": 1,\n\t\"dianmi.net\": 1,\n\t\"diannaoban.com\": 1,\n\t\"diannaojishu.com\": 1,\n\t\"dianping.com\": 1,\n\t\"dianrong.com\": 1,\n\t\"dianshifu.com\": 1,\n\t\"diantijob.com\": 1,\n\t\"dianxian999.com\": 1,\n\t\"dianxin.com\": 1,\n\t\"dianxinnews.com\": 1,\n\t\"dianyuan.com\": 1,\n\t\"dianzp.com\": 1,\n\t\"dianzubuluo.com\": 1,\n\t\"diaochapai.net\": 1,\n\t\"diaokeji.net\": 1,\n\t\"diaosujia.net\": 1,\n\t\"diaoyanbao.com\": 1,\n\t\"diaoyu.com\": 1,\n\t\"diaoyu123.com\": 1,\n\t\"dicaiwang.com\": 1,\n\t\"dichan.com\": 1,\n\t\"didatuan.com\": 1,\n\t\"didipai.com\": 1,\n\t\"didown.com\": 1,\n\t\"didunews.com\": 1,\n\t\"difangzhi.org\": 1,\n\t\"dihuasen.com\": 1,\n\t\"dili360.com\": 1,\n\t\"dimeng.net\": 1,\n\t\"dinbon.com\": 1,\n\t\"dinghuaren.com\": 1,\n\t\"dingniugu.com\": 1,\n\t\"dingyuannews.com\": 1,\n\t\"dingyx.com\": 1,\n\t\"dinju.com\": 1,\n\t\"dionly.com\": 1,\n\t\"dipan.com\": 1,\n\t\"diqiuw.com\": 1,\n\t\"discoversources.com\": 1,\n\t\"discuz.com\": 1,\n\t\"discuz.net\": 1,\n\t\"disoso.com\": 1,\n\t\"ditan360.com\": 1,\n\t\"ditan500.com\": 1,\n\t\"ditiewang.net\": 1,\n\t\"divcss5.com\": 1,\n\t\"diwei.net\": 1,\n\t\"diwuji.cc\": 1,\n\t\"diyiapp.com\": 1,\n\t\"diyicai.com\": 1,\n\t\"diyiche8.com\": 1,\n\t\"diyiyou.com\": 1,\n\t\"diyizby.com\": 1,\n\t\"diypda.com\": 1,\n\t\"diytrade.com\": 1,\n\t\"dj020.com\": 1,\n\t\"dj114.cc\": 1,\n\t\"dj19.com\": 1,\n\t\"dj3721.net\": 1,\n\t\"dj520.com\": 1,\n\t\"dj7.com\": 1,\n\t\"dj97.com\": 1,\n\t\"djbozi.com\": 1,\n\t\"djbstatic.com\": 1,\n\t\"djkk.com\": 1,\n\t\"djlsoft.net\": 1,\n\t\"djob.com\": 1,\n\t\"dju8.com\": 1,\n\t\"djwma.com\": 1,\n\t\"djxww.com\": 1,\n\t\"djye.com\": 1,\n\t\"djyjob.com\": 1,\n\t\"dker.cc\": 1,\n\t\"dl-hr.org\": 1,\n\t\"dlairport.com\": 1,\n\t\"dlaitc.com\": 1,\n\t\"dlbyg.com\": 1,\n\t\"dld.com\": 1,\n\t\"dldcdn.com\": 1,\n\t\"dledu.com\": 1,\n\t\"dlgaoji.com\": 1,\n\t\"dlgxw.com\": 1,\n\t\"dlhmjw.com\": 1,\n\t\"dlhnews.com\": 1,\n\t\"dlicw.com\": 1,\n\t\"dljs.net\": 1,\n\t\"dlkhgl.com\": 1,\n\t\"dlmonita.com\": 1,\n\t\"dlpuwan.com\": 1,\n\t\"dlqh.com\": 1,\n\t\"dlqinzi.com\": 1,\n\t\"dlsysy.com\": 1,\n\t\"dlxp.com\": 1,\n\t\"dlxww.com\": 1,\n\t\"dlxxsd.com\": 1,\n\t\"dlysgh.com\": 1,\n\t\"dlzfgjj.com\": 1,\n\t\"dlzzm.com\": 1,\n\t\"dm-rc.com\": 1,\n\t\"dm300.com\": 1,\n\t\"dm456.com\": 1,\n\t\"dm5.com\": 1,\n\t\"dm591.com\": 1,\n\t\"dm76.com\": 1,\n\t\"dmcbd.com\": 1,\n\t\"dmdfchina.com\": 1,\n\t\"dmjob.net\": 1,\n\t\"dmkor.com\": 1,\n\t\"dmshu.com\": 1,\n\t\"dmsxxw.com\": 1,\n\t\"dmtrck.com\": 1,\n\t\"dmwhj.com\": 1,\n\t\"dmzj.com\": 1,\n\t\"dmzx.com\": 1,\n\t\"dn1234.com\": 1,\n\t\"dnake.com\": 1,\n\t\"dnbbs.com\": 1,\n\t\"dnc21.com\": 1,\n\t\"dnfwan.com\": 1,\n\t\"dnheimuer.com\": 1,\n\t\"dns.la\": 1,\n\t\"dnwx.com\": 1,\n\t\"dnxf.com\": 1,\n\t\"do93.com\": 1,\n\t\"doc88.com\": 1,\n\t\"docer.com\": 1,\n\t\"docin.com\": 1,\n\t\"docin.net\": 1,\n\t\"docuchina.tv\": 1,\n\t\"dodo8.com\": 1,\n\t\"dodonew.com\": 1,\n\t\"doershow.com\": 1,\n\t\"dog126.com\": 1,\n\t\"doguo.com\": 1,\n\t\"doido.com\": 1,\n\t\"doname.com\": 1,\n\t\"donews.com\": 1,\n\t\"dongannews.com\": 1,\n\t\"dongao.com\": 1,\n\t\"dongbei8.com\": 1,\n\t\"dongdao.net\": 1,\n\t\"dongfang.com\": 1,\n\t\"dongfang8.com\": 1,\n\t\"dongjidao.com\": 1,\n\t\"dongjinyu.com\": 1,\n\t\"dongkounews.com\": 1,\n\t\"dongliao.org\": 1,\n\t\"dongliaogov.net\": 1,\n\t\"donglingying.cc\": 1,\n\t\"dongnanshan.com\": 1,\n\t\"dongpeng.net\": 1,\n\t\"dongpingren.com\": 1,\n\t\"dongpo.net\": 1,\n\t\"dongqiudi.com\": 1,\n\t\"dongsheng2010.com\": 1,\n\t\"dongtai.so\": 1,\n\t\"dooland.com\": 1,\n\t\"doooor.com\": 1,\n\t\"door-expo.com\": 1,\n\t\"dooreb.com\": 1,\n\t\"doorhr.com\": 1,\n\t\"doserv.com\": 1,\n\t\"dospy.com\": 1,\n\t\"dostor.com\": 1,\n\t\"dotamax.com\": 1,\n\t\"dotodo.net\": 1,\n\t\"douanju.com\": 1,\n\t\"douban.com\": 1,\n\t\"douban.fm\": 1,\n\t\"doubleclick.com\": 1,\n\t\"doubleclick.net\": 1,\n\t\"douguo.com\": 1,\n\t\"douguo.net\": 1,\n\t\"doulai.com\": 1,\n\t\"doulewu.com\": 1,\n\t\"douluodalu123.com\": 1,\n\t\"douni.com\": 1,\n\t\"doupobook.com\": 1,\n\t\"douxie.com\": 1,\n\t\"douyutv.com\": 1,\n\t\"dowater.com\": 1,\n\t\"down.cc\": 1,\n\t\"downcc.com\": 1,\n\t\"downdownz.com\": 1,\n\t\"downg.com\": 1,\n\t\"downhot.com\": 1,\n\t\"downkr.com\": 1,\n\t\"downxia.com\": 1,\n\t\"doyoo.net\": 1,\n\t\"doyor.com\": 1,\n\t\"dozedu.com\": 1,\n\t\"dpfile.com\": 1,\n\t\"dpin100.com\": 1,\n\t\"dpm360.com\": 1,\n\t\"dq-fx.com\": 1,\n\t\"dq247.com\": 1,\n\t\"dqccc.com\": 1,\n\t\"dqdaily.com\": 1,\n\t\"dqdm.com\": 1,\n\t\"dqjob88.com\": 1,\n\t\"dqlyw.net\": 1,\n\t\"dqpump.com\": 1,\n\t\"dqxxw.com\": 1,\n\t\"dragon-guide.net\": 1,\n\t\"dragonmil.com\": 1,\n\t\"draw-more.com\": 1,\n\t\"drcnet.com\": 1,\n\t\"dream4ever.org\": 1,\n\t\"dreams-travel.com\": 1,\n\t\"drivergenius.com\": 1,\n\t\"driversdown.com\": 1,\n\t\"drugadmin.com\": 1,\n\t\"drughuloo.com\": 1,\n\t\"ds-360.com\": 1,\n\t\"ds-is.com\": 1,\n\t\"ds123456.com\": 1,\n\t\"ds599.com\": 1,\n\t\"dsbjq.com\": 1,\n\t\"dsfauto.com\": 1,\n\t\"dsfunds.com\": 1,\n\t\"dsgkt.com\": 1,\n\t\"dshigao.com\": 1,\n\t\"dshmama.com\": 1,\n\t\"dshrc.com\": 1,\n\t\"dsjunshi.net\": 1,\n\t\"dslpool.com\": 1,\n\t\"dsrczp.com\": 1,\n\t\"dswjob.com\": 1,\n\t\"dt123.net\": 1,\n\t\"dt12318.com\": 1,\n\t\"dt511.com\": 1,\n\t\"dtcoalmine.com\": 1,\n\t\"dthr.com\": 1,\n\t\"dthuawei.com\": 1,\n\t\"dtjy.org\": 1,\n\t\"dtlsw.com\": 1,\n\t\"dtrcw.net\": 1,\n\t\"duanwenxue.com\": 1,\n\t\"duapp.com\": 1,\n\t\"duba.com\": 1,\n\t\"duba.net\": 1,\n\t\"duhub.com\": 1,\n\t\"duidea.com\": 1,\n\t\"duitang.com\": 1,\n\t\"dukuai.com\": 1,\n\t\"duobei.com\": 1,\n\t\"duohaode.com\": 1,\n\t\"duoic.com\": 1,\n\t\"duokan.com\": 1,\n\t\"duomai.com\": 1,\n\t\"duomi.com\": 1,\n\t\"duorou42.com\": 1,\n\t\"duoshuo.com\": 1,\n\t\"duote.com\": 1,\n\t\"duotegame.com\": 1,\n\t\"duouoo.com\": 1,\n\t\"duowan.com\": 1,\n\t\"duoww.com\": 1,\n\t\"duoxinqi.com\": 1,\n\t\"duoyi.com\": 1,\n\t\"dushe.net\": 1,\n\t\"dushi118.com\": 1,\n\t\"dushifang.com\": 1,\n\t\"dushiline.com\": 1,\n\t\"dutbbs.com\": 1,\n\t\"dute520.com\": 1,\n\t\"duwenz.com\": 1,\n\t\"duwenzhang.com\": 1,\n\t\"duxiu.com\": 1,\n\t\"duzhebao.com\": 1,\n\t\"duzhihai.com\": 1,\n\t\"dv37.com\": 1,\n\t\"dv37.net\": 1,\n\t\"dvbbs.net\": 1,\n\t\"dvbcn.com\": 1,\n\t\"dvwu.com\": 1,\n\t\"dw20.com\": 1,\n\t\"dwgou.com\": 1,\n\t\"dwrh.net\": 1,\n\t\"dwstatic.com\": 1,\n\t\"dwywooden.com\": 1,\n\t\"dx-job.com\": 1,\n\t\"dxb2b.com\": 1,\n\t\"dxbei.com\": 1,\n\t\"dxcang.com\": 1,\n\t\"dxcjjzx.com\": 1,\n\t\"dxlfile.com\": 1,\n\t\"dxsbb.com\": 1,\n\t\"dxsheng.com\": 1,\n\t\"dxsjz.com\": 1,\n\t\"dxszxy.com\": 1,\n\t\"dxxnews.com\": 1,\n\t\"dxycdn.com\": 1,\n\t\"dxyy91.com\": 1,\n\t\"dxzx.com\": 1,\n\t\"dy-bus.com\": 1,\n\t\"dy2018.com\": 1,\n\t\"dy369.com\": 1,\n\t\"dy8.com\": 1,\n\t\"dy86.com\": 1,\n\t\"dycars.com\": 1,\n\t\"dydh.tv\": 1,\n\t\"dyfc.net\": 1,\n\t\"dyfcw.com\": 1,\n\t\"dyhjw.com\": 1,\n\t\"dylw.net\": 1,\n\t\"dynong.net\": 1,\n\t\"dyp2p.com\": 1,\n\t\"dyqc.com\": 1,\n\t\"dyqez.net\": 1,\n\t\"dyqjy.net\": 1,\n\t\"dyrbw.com\": 1,\n\t\"dytdc.com\": 1,\n\t\"dyteam.com\": 1,\n\t\"dytfw.com\": 1,\n\t\"dytjj.com\": 1,\n\t\"dytt.net\": 1,\n\t\"dytt8.net\": 1,\n\t\"dyxtw.com\": 1,\n\t\"dyxw.com\": 1,\n\t\"dz-z.com\": 1,\n\t\"dz090.com\": 1,\n\t\"dz169.net\": 1,\n\t\"dz19.net\": 1,\n\t\"dz1982.com\": 1,\n\t\"dz211.com\": 1,\n\t\"dz600.com\": 1,\n\t\"dzcnc.com\": 1,\n\t\"dzfang.com\": 1,\n\t\"dzfc.com\": 1,\n\t\"dzgjj.com\": 1,\n\t\"dzhaoj.com\": 1,\n\t\"dzkfq.com\": 1,\n\t\"dzmall.com\": 1,\n\t\"dzqiche.com\": 1,\n\t\"dzqxj.com\": 1,\n\t\"dzrbs.com\": 1,\n\t\"dzrc8.com\": 1,\n\t\"dzrtv.com\": 1,\n\t\"dzsc.com\": 1,\n\t\"dzsm.com\": 1,\n\t\"dzso.com\": 1,\n\t\"dzsrcw.com\": 1,\n\t\"dzszb.com\": 1,\n\t\"dztv.tv\": 1,\n\t\"dzwcity.com\": 1,\n\t\"dzwindows.com\": 1,\n\t\"dzwork.net\": 1,\n\t\"dzwww.com\": 1,\n\t\"dzxw.net\": 1,\n\t\"dzztgw.com\": 1,\n\t\"e-bices.org\": 1,\n\t\"e-dyer.com\": 1,\n\t\"e-jjj.com\": 1,\n\t\"e-qdpm.com\": 1,\n\t\"e0453.com\": 1,\n\t\"e0514.com\": 1,\n\t\"e0570.com\": 1,\n\t\"e0575.cc\": 1,\n\t\"e0575.com\": 1,\n\t\"e0734.com\": 1,\n\t\"e0756.com\": 1,\n\t\"e0838.com\": 1,\n\t\"e118114.com\": 1,\n\t\"e1617.com\": 1,\n\t\"e1988.com\": 1,\n\t\"e21cn.com\": 1,\n\t\"e2say.com\": 1,\n\t\"e51home.com\": 1,\n\t\"e521.com\": 1,\n\t\"e6w6.com\": 1,\n\t\"e7uu.com\": 1,\n\t\"e8online.com\": 1,\n\t\"e974.com\": 1,\n\t\"ea-china.com\": 1,\n\t\"ea3w.com\": 1,\n\t\"each9.com\": 1,\n\t\"eachnet.com\": 1,\n\t\"eachnic.com\": 1,\n\t\"eagtop.com\": 1,\n\t\"eahot.com\": 1,\n\t\"eamn.net\": 1,\n\t\"ean98.com\": 1,\n\t\"earthedu.com\": 1,\n\t\"easdo.com\": 1,\n\t\"easeeyes.com\": 1,\n\t\"easiu.com\": 1,\n\t\"easou.com\": 1,\n\t\"eastcang.com\": 1,\n\t\"eastday.com\": 1,\n\t\"easteat.com\": 1,\n\t\"eastfair.com\": 1,\n\t\"eastib.com\": 1,\n\t\"eastmoney.com\": 1,\n\t\"eastradio.com\": 1,\n\t\"eastshepin.com\": 1,\n\t\"eastsilver.com\": 1,\n\t\"eastsoo.com\": 1,\n\t\"eastts.com\": 1,\n\t\"eastups.com\": 1,\n\t\"easyicon.net\": 1,\n\t\"easysino.com\": 1,\n\t\"easyvoa.com\": 1,\n\t\"eb80.com\": 1,\n\t\"ebadu.net\": 1,\n\t\"ebaocheng.com\": 1,\n\t\"ebatong.com\": 1,\n\t\"ebay.com\": 1,\n\t\"ebdoor.com\": 1,\n\t\"ebiaoegou.com\": 1,\n\t\"ebieshu.com\": 1,\n\t\"ebigear.com\": 1,\n\t\"eblockschina.com\": 1,\n\t\"ebnew.com\": 1,\n\t\"eboce.com\": 1,\n\t\"ebrun.com\": 1,\n\t\"ebscn.com\": 1,\n\t\"ebseek.com\": 1,\n\t\"ec168.net\": 1,\n\t\"ec2ec.com\": 1,\n\t\"ec517.com\": 1,\n\t\"ecaihr.com\": 1,\n\t\"ecang.cc\": 1,\n\t\"ecasee.com\": 1,\n\t\"ecbaby.com\": 1,\n\t\"eccn.com\": 1,\n\t\"eccnmall.com\": 1,\n\t\"eccpitbj.org\": 1,\n\t\"eccsp.org\": 1,\n\t\"eceeg.com\": 1,\n\t\"eceibs.com\": 1,\n\t\"ecgoo.net\": 1,\n\t\"echache.net\": 1,\n\t\"echangye.com\": 1,\n\t\"echinagov.com\": 1,\n\t\"echinajob.com\": 1,\n\t\"echocontrol.com\": 1,\n\t\"ecidi.com\": 1,\n\t\"ecitic.com\": 1,\n\t\"ecmao.com\": 1,\n\t\"ecmao.net\": 1,\n\t\"ecnia.org\": 1,\n\t\"ecp888.com\": 1,\n\t\"ecp888.net\": 1,\n\t\"ecppn.com\": 1,\n\t\"ecqun.com\": 1,\n\t\"ecshop.com\": 1,\n\t\"ecstv.com\": 1,\n\t\"ecvvby.com\": 1,\n\t\"ecwan77.net\": 1,\n\t\"eczn.com\": 1,\n\t\"edai.com\": 1,\n\t\"edaocha.com\": 1,\n\t\"edazhang.com\": 1,\n\t\"edianchi.com\": 1,\n\t\"edianyou.com\": 1,\n\t\"edowning.net\": 1,\n\t\"edry.org\": 1,\n\t\"edtqy.com\": 1,\n\t\"edu-010.com\": 1,\n\t\"edu-hb.com\": 1,\n\t\"edu-nw.com\": 1,\n\t\"edu03.com\": 1,\n\t\"edu1488.com\": 1,\n\t\"edu201.com\": 1,\n\t\"edu24ol.com\": 1,\n\t\"edu5a.com\": 1,\n\t\"edu63.com\": 1,\n\t\"edu80.com\": 1,\n\t\"edu84.com\": 1,\n\t\"educaizhi.com\": 1,\n\t\"edudo.com\": 1,\n\t\"edudown.net\": 1,\n\t\"eduease.com\": 1,\n\t\"eduego.com\": 1,\n\t\"eduei.com\": 1,\n\t\"edufang.com\": 1,\n\t\"eduglobal.com\": 1,\n\t\"edulida.com\": 1,\n\t\"eduour.com\": 1,\n\t\"edushi.com\": 1,\n\t\"edutt.com\": 1,\n\t\"eduu.com\": 1,\n\t\"eduuu.com\": 1,\n\t\"eduvv.com\": 1,\n\t\"eduwo.com\": 1,\n\t\"eeboard.com\": 1,\n\t\"eec-sh.com\": 1,\n\t\"eechina.com\": 1,\n\t\"eecnt.com\": 1,\n\t\"eeeen.com\": 1,\n\t\"eeeff.com\": 1,\n\t\"eefocus.com\": 1,\n\t\"eehu.com\": 1,\n\t\"eeju.com\": 1,\n\t\"eelly.com\": 1,\n\t\"eenzo.com\": 1,\n\t\"eetrend.com\": 1,\n\t\"eeyy.com\": 1,\n\t\"ef168.com\": 1,\n\t\"ef360.com\": 1,\n\t\"ef75.com\": 1,\n\t\"efang.tv\": 1,\n\t\"efubo.com\": 1,\n\t\"efuhr.com\": 1,\n\t\"efuyang.com\": 1,\n\t\"egoedu.com\": 1,\n\t\"egou.com\": 1,\n\t\"egouz.com\": 1,\n\t\"eguanzhu.com\": 1,\n\t\"eguilin.org\": 1,\n\t\"ehaier.com\": 1,\n\t\"ehaoyao.com\": 1,\n\t\"ehomeday.com\": 1,\n\t\"ehometu.com\": 1,\n\t\"ehsy.com\": 1,\n\t\"ehualang.com\": 1,\n\t\"ehuanbao.net\": 1,\n\t\"ehuatai.com\": 1,\n\t\"ehvacr.com\": 1,\n\t\"eiacn.com\": 1,\n\t\"eiafans.com\": 1,\n\t\"eiiq.com\": 1,\n\t\"eis100.com\": 1,\n\t\"eisdl.com\": 1,\n\t\"eistudy.com\": 1,\n\t\"eistudy.net\": 1,\n\t\"eit0571.com\": 1,\n\t\"ejee.com\": 1,\n\t\"ejeegroup.com\": 1,\n\t\"ejeepay.com\": 1,\n\t\"ejiaju.cc\": 1,\n\t\"ejinshan.net\": 1,\n\t\"eju.com\": 1,\n\t\"ek6.com\": 1,\n\t\"ekan123.com\": 1,\n\t\"ekingo.com\": 1,\n\t\"ekoooo.com\": 1,\n\t\"elanw.com\": 1,\n\t\"ele001.com\": 1,\n\t\"elecfans.com\": 1,\n\t\"elecinfo.com\": 1,\n\t\"elexcon.com\": 1,\n\t\"elht.com\": 1,\n\t\"ellechina.com\": 1,\n\t\"elong.com\": 1,\n\t\"elongstatic.com\": 1,\n\t\"els88.com\": 1,\n\t\"elvyo.com\": 1,\n\t\"emai360.com\": 1,\n\t\"emalljs.com\": 1,\n\t\"emaozi.com\": 1,\n\t\"emarbox.com\": 1,\n\t\"embatimes.com\": 1,\n\t\"embedu.org\": 1,\n\t\"emcsino.com\": 1,\n\t\"eme2000.com\": 1,\n\t\"emeixian.com\": 1,\n\t\"emland.net\": 1,\n\t\"emmacn.com\": 1,\n\t\"ems517.com\": 1,\n\t\"emtx.com\": 1,\n\t\"emu618.com\": 1,\n\t\"emu999.net\": 1,\n\t\"emui.com\": 1,\n\t\"en51.com\": 1,\n\t\"en84.com\": 1,\n\t\"ename.com\": 1,\n\t\"ename.net\": 1,\n\t\"enbar.net\": 1,\n\t\"enboedu.com\": 1,\n\t\"enbowang.com\": 1,\n\t\"enetedu.com\": 1,\n\t\"enetsz.com\": 1,\n\t\"enfodesk.com\": 1,\n\t\"eng24.com\": 1,\n\t\"englishtown.com\": 1,\n\t\"englishvip.com\": 1,\n\t\"enguo.com\": 1,\n\t\"enkj.com\": 1,\n\t\"enmuo.com\": 1,\n\t\"enshi9e.com\": 1,\n\t\"enshifdc.com\": 1,\n\t\"enshijob.com\": 1,\n\t\"enshisport.com\": 1,\n\t\"enterdesk.com\": 1,\n\t\"envinnovators.org\": 1,\n\t\"envirofortune.com\": 1,\n\t\"eoeandroid.com\": 1,\n\t\"eoemarket.com\": 1,\n\t\"eoffcn.com\": 1,\n\t\"eoledu.com\": 1,\n\t\"eotour.com\": 1,\n\t\"epaidai.com\": 1,\n\t\"epanshi.com\": 1,\n\t\"epchina.com\": 1,\n\t\"epday.com\": 1,\n\t\"epi88.com\": 1,\n\t\"epiaogo.com\": 1,\n\t\"epinv.com\": 1,\n\t\"epjob88.com\": 1,\n\t\"eptrc.com\": 1,\n\t\"eptxw.com\": 1,\n\t\"epweike.com\": 1,\n\t\"epzpw.com\": 1,\n\t\"eq-gc1.com\": 1,\n\t\"eq-hl.com\": 1,\n\t\"eq-xz.net\": 1,\n\t\"eqinrun.com\": 1,\n\t\"eqyn.com\": 1,\n\t\"ercac.com\": 1,\n\t\"ereneben.com\": 1,\n\t\"erongtu.com\": 1,\n\t\"erpchn.com\": 1,\n\t\"erpworld.net\": 1,\n\t\"errenzhuan.cc\": 1,\n\t\"ershouyi.org\": 1,\n\t\"ersoso.com\": 1,\n\t\"eryoutang.com\": 1,\n\t\"es370.com\": 1,\n\t\"escdn.com\": 1,\n\t\"eserexpo.com\": 1,\n\t\"esfimg.com\": 1,\n\t\"esfxx.com\": 1,\n\t\"eshiyan.com\": 1,\n\t\"eshouyao.com\": 1,\n\t\"eshow365.com\": 1,\n\t\"eshowgo.com\": 1,\n\t\"esilk.net\": 1,\n\t\"esnai.com\": 1,\n\t\"esoche.com\": 1,\n\t\"esqimg.com\": 1,\n\t\"essaycn.com\": 1,\n\t\"estc8.com\": 1,\n\t\"esuliao.com\": 1,\n\t\"eswine.com\": 1,\n\t\"et8.org\": 1,\n\t\"etaicang.com\": 1,\n\t\"etaiyang.com\": 1,\n\t\"etao.com\": 1,\n\t\"etc-sbc.com\": 1,\n\t\"etest8.com\": 1,\n\t\"etf88.com\": 1,\n\t\"etfjijin.com\": 1,\n\t\"ethainan.com\": 1,\n\t\"etiantian.com\": 1,\n\t\"etlong.com\": 1,\n\t\"etonkids.com\": 1,\n\t\"etowz.com\": 1,\n\t\"etpass.com\": 1,\n\t\"ett-cn.com\": 1,\n\t\"etuan.com\": 1,\n\t\"euibe.com\": 1,\n\t\"eurasia.edu\": 1,\n\t\"ev123.com\": 1,\n\t\"evaad.com\": 1,\n\t\"evdays.com\": 1,\n\t\"evergrande.com\": 1,\n\t\"everychina.com\": 1,\n\t\"evlook.com\": 1,\n\t\"evpartner.com\": 1,\n\t\"evsou.com\": 1,\n\t\"ewang.com\": 1,\n\t\"ewangpai.com\": 1,\n\t\"ewjar.com\": 1,\n\t\"ewkimg.com\": 1,\n\t\"ewoka.com\": 1,\n\t\"eworksglobal.com\": 1,\n\t\"eworldship.com\": 1,\n\t\"ewsos.com\": 1,\n\t\"ewstudy.com\": 1,\n\t\"ewteacher.com\": 1,\n\t\"ex-cp.com\": 1,\n\t\"ex-cp.net\": 1,\n\t\"exam001.com\": 1,\n\t\"exam66.org\": 1,\n\t\"exam76.com\": 1,\n\t\"exam8.com\": 1,\n\t\"exambook.net\": 1,\n\t\"examda.com\": 1,\n\t\"examw.com\": 1,\n\t\"examzz.com\": 1,\n\t\"exbulk.com\": 1,\n\t\"exbuy.net\": 1,\n\t\"exbxg.com\": 1,\n\t\"exiaba.com\": 1,\n\t\"exiaoba.com\": 1,\n\t\"expai.com\": 1,\n\t\"expeak.com\": 1,\n\t\"expo-china.com\": 1,\n\t\"expo-cn.com\": 1,\n\t\"expo-yy.com\": 1,\n\t\"expowindow.com\": 1,\n\t\"exrtz.com\": 1,\n\t\"extmail.org\": 1,\n\t\"exw360.com\": 1,\n\t\"exzk.net\": 1,\n\t\"eye.rs\": 1,\n\t\"eyou.com\": 1,\n\t\"eyoudi.com\": 1,\n\t\"eyuyao.com\": 1,\n\t\"ezhiol.com\": 1,\n\t\"eztxw.com\": 1,\n\t\"f0580.com\": 1,\n\t\"f139.com\": 1,\n\t\"f139content.com\": 1,\n\t\"f1688.com\": 1,\n\t\"f2cn.net\": 1,\n\t\"f537.com\": 1,\n\t\"f61.com\": 1,\n\t\"f737.com\": 1,\n\t\"fa-today.com\": 1,\n\t\"fa597.com\": 1,\n\t\"fabao365.com\": 1,\n\t\"fabric114.com\": 1,\n\t\"fabu114.com\": 1,\n\t\"facang.com\": 1,\n\t\"face100.net\": 1,\n\t\"face321.com\": 1,\n\t\"fad123.com\": 1,\n\t\"fadianxitong.com\": 1,\n\t\"fadui.com\": 1,\n\t\"fahao.cc\": 1,\n\t\"fahaola.com\": 1,\n\t\"fahaole.com\": 1,\n\t\"faidns.com\": 1,\n\t\"fajiaowang.com\": 1,\n\t\"falongfa.com\": 1,\n\t\"faloo.com\": 1,\n\t\"famenbao.com\": 1,\n\t\"famens.com\": 1,\n\t\"famensy.com\": 1,\n\t\"fancai.com\": 1,\n\t\"fanfou.com\": 1,\n\t\"fang.com\": 1,\n\t\"fang33.com\": 1,\n\t\"fang86.com\": 1,\n\t\"fang99.com\": 1,\n\t\"fangbx.com\": 1,\n\t\"fangce.net\": 1,\n\t\"fangchan.com\": 1,\n\t\"fangchankaoshi.com\": 1,\n\t\"fangdr.com\": 1,\n\t\"fangedai.com\": 1,\n\t\"fangfa.net\": 1,\n\t\"fangfang.net\": 1,\n\t\"fanging.com\": 1,\n\t\"fangjia.com\": 1,\n\t\"fangjiadp.com\": 1,\n\t\"fangjiaw.com\": 1,\n\t\"fangke.cc\": 1,\n\t\"fangle.com\": 1,\n\t\"fanglincar.com\": 1,\n\t\"fangpei.net\": 1,\n\t\"fangtan007.com\": 1,\n\t\"fangte.com\": 1,\n\t\"fangtoo.com\": 1,\n\t\"fangtuwang.com\": 1,\n\t\"fangtw.com\": 1,\n\t\"fangtx.com\": 1,\n\t\"fangxiaoer.com\": 1,\n\t\"fangxinbao.com\": 1,\n\t\"fangxinmai.com\": 1,\n\t\"fangyou.com\": 1,\n\t\"fangyuan365.com\": 1,\n\t\"fangyuanglass.com\": 1,\n\t\"fangzhanhui.com\": 1,\n\t\"fangzhi-china.com\": 1,\n\t\"fangzhur.com\": 1,\n\t\"fanhuan.com\": 1,\n\t\"fanqun.com\": 1,\n\t\"fansimg.com\": 1,\n\t\"fansjw.com\": 1,\n\t\"fantizi5.com\": 1,\n\t\"fantong.com\": 1,\n\t\"fanxian.com\": 1,\n\t\"fanxuefei.com\": 1,\n\t\"fanyizhijia.com\": 1,\n\t\"far2000.com\": 1,\n\t\"farc.cc\": 1,\n\t\"fashangji.com\": 1,\n\t\"fashiontrenddigest.com\": 1,\n\t\"fastapi.net\": 1,\n\t\"fastcdn.com\": 1,\n\t\"fastener500.com\": 1,\n\t\"fastif.net\": 1,\n\t\"fat999.com\": 1,\n\t\"favolist.com\": 1,\n\t\"faw-mazda.com\": 1,\n\t\"faw-vw.com\": 1,\n\t\"fawan.com\": 1,\n\t\"faxingzhan.com\": 1,\n\t\"fayifa.com\": 1,\n\t\"fblife.com\": 1,\n\t\"fboos.com\": 1,\n\t\"fc0531.com\": 1,\n\t\"fc0575.com\": 1,\n\t\"fc0592.com\": 1,\n\t\"fc0595.com\": 1,\n\t\"fc0596.com\": 1,\n\t\"fc0597.com\": 1,\n\t\"fc0633.com\": 1,\n\t\"fc571.com\": 1,\n\t\"fc593.com\": 1,\n\t\"fc85.com\": 1,\n\t\"fccs.com\": 1,\n\t\"fccscar.com\": 1,\n\t\"fcdbz.com\": 1,\n\t\"fcfcg.com\": 1,\n\t\"fcfxb.com\": 1,\n\t\"fcg360.com\": 1,\n\t\"fcgic.com\": 1,\n\t\"fcgsnews.com\": 1,\n\t\"fcgyc.com\": 1,\n\t\"fcii.net\": 1,\n\t\"fcjob88.com\": 1,\n\t\"fclubimg.com\": 1,\n\t\"fcpachina.org\": 1,\n\t\"fcrc114.com\": 1,\n\t\"fcsc517.com\": 1,\n\t\"fcxlib.com\": 1,\n\t\"fcxnews.com\": 1,\n\t\"fcyhw.com\": 1,\n\t\"fd365.net\": 1,\n\t\"fd597.com\": 1,\n\t\"fdc0737.com\": 1,\n\t\"fdc0746.com\": 1,\n\t\"fdc315.com\": 1,\n\t\"fdcew.com\": 1,\n\t\"fdckj.com\": 1,\n\t\"fdfang.com\": 1,\n\t\"fdgzw.com\": 1,\n\t\"fdlt.net\": 1,\n\t\"fdxww.com\": 1,\n\t\"fecn.net\": 1,\n\t\"feedsky.com\": 1,\n\t\"feelcars.com\": 1,\n\t\"feeliu.com\": 1,\n\t\"feeyo.com\": 1,\n\t\"fei580.com\": 1,\n\t\"feichengjob.com\": 1,\n\t\"feicuiedu.com\": 1,\n\t\"feicuiwuyu.com\": 1,\n\t\"feidm.com\": 1,\n\t\"feigang.net\": 1,\n\t\"feihucg.com\": 1,\n\t\"feijiu.net\": 1,\n\t\"feijs.com\": 1,\n\t\"feiku.com\": 1,\n\t\"feiliu.com\": 1,\n\t\"feipin.com\": 1,\n\t\"feiwan.net\": 1,\n\t\"feixi.cc\": 1,\n\t\"feixue.com\": 1,\n\t\"feizl.com\": 1,\n\t\"fenfen.com\": 1,\n\t\"feng.com\": 1,\n\t\"feng6.net\": 1,\n\t\"feng91.com\": 1,\n\t\"fengbao.com\": 1,\n\t\"fengbuy.com\": 1,\n\t\"fengdu100.com\": 1,\n\t\"fengfeng.cc\": 1,\n\t\"fenggang.cc\": 1,\n\t\"fengj.com\": 1,\n\t\"fengj.net\": 1,\n\t\"fengjierc.com\": 1,\n\t\"fengjing.com\": 1,\n\t\"fenglu-alu.com\": 1,\n\t\"fengmu6.com\": 1,\n\t\"fengniao.com\": 1,\n\t\"fengone.com\": 1,\n\t\"fengone.net\": 1,\n\t\"fengrun.cc\": 1,\n\t\"fengsung.com\": 1,\n\t\"fengyunlive.com\": 1,\n\t\"fengyunzhibo.com\": 1,\n\t\"fenlei168.com\": 1,\n\t\"fenleidao.com\": 1,\n\t\"fentishebei.com\": 1,\n\t\"fenzhi.com\": 1,\n\t\"fercc.org\": 1,\n\t\"ferrygame.com\": 1,\n\t\"fetionpic.com\": 1,\n\t\"ffdy.cc\": 1,\n\t\"ffdyk.com\": 1,\n\t\"ffpic.com\": 1,\n\t\"ffwan.com\": 1,\n\t\"fhfcw.org\": 1,\n\t\"fhgame.com\": 1,\n\t\"fhlczy.com\": 1,\n\t\"fhlyou.com\": 1,\n\t\"fhmob.com\": 1,\n\t\"filterhz.com\": 1,\n\t\"financeun.com\": 1,\n\t\"findzd.com\": 1,\n\t\"fireflytrip.com\": 1,\n\t\"firstgood.com\": 1,\n\t\"fish-photo.com\": 1,\n\t\"fishrc.com\": 1,\n\t\"fit120.com\": 1,\n\t\"fj007.com\": 1,\n\t\"fj3091.com\": 1,\n\t\"fjber.com\": 1,\n\t\"fjcet.com\": 1,\n\t\"fjcha.com\": 1,\n\t\"fjcoop.com\": 1,\n\t\"fjcyl.org\": 1,\n\t\"fjdaily.com\": 1,\n\t\"fjdh.com\": 1,\n\t\"fjfdi.com\": 1,\n\t\"fjfs.net\": 1,\n\t\"fjgb.com\": 1,\n\t\"fjgczj.com\": 1,\n\t\"fjgczl.com\": 1,\n\t\"fjgrain.com\": 1,\n\t\"fjgs.org\": 1,\n\t\"fjgzjy.com\": 1,\n\t\"fjhrss.com\": 1,\n\t\"fjhun.com\": 1,\n\t\"fjhzrc.com\": 1,\n\t\"fjii.com\": 1,\n\t\"fjjcjy.com\": 1,\n\t\"fjjdrcw.com\": 1,\n\t\"fjjgxy.com\": 1,\n\t\"fjjl.net\": 1,\n\t\"fjjyxy.com\": 1,\n\t\"fjkx.org\": 1,\n\t\"fjlcnews.com\": 1,\n\t\"fjlearning.com\": 1,\n\t\"fjlh.com\": 1,\n\t\"fjlib.net\": 1,\n\t\"fjlt.net\": 1,\n\t\"fjlx.net\": 1,\n\t\"fjlyta.com\": 1,\n\t\"fjmap.net\": 1,\n\t\"fjmb.net\": 1,\n\t\"fjmwjx.com\": 1,\n\t\"fjnet.com\": 1,\n\t\"fjprxx.com\": 1,\n\t\"fjpta.com\": 1,\n\t\"fjqlw.com\": 1,\n\t\"fjsalt.com\": 1,\n\t\"fjsdfz.org\": 1,\n\t\"fjsen.com\": 1,\n\t\"fjsq.org\": 1,\n\t\"fjsy.net\": 1,\n\t\"fjsyxww.com\": 1,\n\t\"fjszgjj.com\": 1,\n\t\"fjta.com\": 1,\n\t\"fjteanews.com\": 1,\n\t\"fjtj.com\": 1,\n\t\"fjtp.net\": 1,\n\t\"fjtv.net\": 1,\n\t\"fjtvnews.com\": 1,\n\t\"fjwh.net\": 1,\n\t\"fjwh.org\": 1,\n\t\"fjwuzi.com\": 1,\n\t\"fjxmw.com\": 1,\n\t\"fjxw.net\": 1,\n\t\"fjydnews.com\": 1,\n\t\"fjyj.net\": 1,\n\t\"fjzlym.com\": 1,\n\t\"fjzol.com\": 1,\n\t\"fjzsjy.com\": 1,\n\t\"fkbxg.com\": 1,\n\t\"fkyycl.com\": 1,\n\t\"fl928.com\": 1,\n\t\"flash1890.com\": 1,\n\t\"flash8.net\": 1,\n\t\"flashget.com\": 1,\n\t\"flashwing.net\": 1,\n\t\"flickr.com\": 1,\n\t\"flingba.com\": 1,\n\t\"flrcw.com\": 1,\n\t\"fltrp.com\": 1,\n\t\"fm-job.com\": 1,\n\t\"fm1036.com\": 1,\n\t\"fm1039.com\": 1,\n\t\"fm1054.com\": 1,\n\t\"fm914.com\": 1,\n\t\"fm918.net\": 1,\n\t\"fm936.com\": 1,\n\t\"fmbimg.com\": 1,\n\t\"fmcoprc.gov.hk\": 1,\n\t\"fmq10.net\": 1,\n\t\"fnrcw.com\": 1,\n\t\"fobshanghai.com\": 1,\n\t\"focussend.com\": 1,\n\t\"focustt.com\": 1,\n\t\"fodian.org\": 1,\n\t\"fojiaoyongpin.com\": 1,\n\t\"foloda.com\": 1,\n\t\"fondcool.com\": 1,\n\t\"foodjol.com\": 1,\n\t\"foodjx.com\": 1,\n\t\"foodmate.net\": 1,\n\t\"foods1.com\": 1,\n\t\"foodspl.com\": 1,\n\t\"foodszs.com\": 1,\n\t\"foodvip.net\": 1,\n\t\"foolcars.com\": 1,\n\t\"foooooot.com\": 1,\n\t\"for68.com\": 1,\n\t\"forbeschina.com\": 1,\n\t\"foresky.com\": 1,\n\t\"forestryfair.com\": 1,\n\t\"forkliftnet.com\": 1,\n\t\"fornature.com\": 1,\n\t\"fortunevc.com\": 1,\n\t\"fotile.com\": 1,\n\t\"fotosay.com\": 1,\n\t\"foundersc.com\": 1,\n\t\"fpdisplay.com\": 1,\n\t\"fphs5.com\": 1,\n\t\"fpky188.com\": 1,\n\t\"fps365.net\": 1,\n\t\"fpwap.com\": 1,\n\t\"fq597.com\": 1,\n\t\"fqjob.net\": 1,\n\t\"fqpai.com\": 1,\n\t\"fqrsw.com\": 1,\n\t\"fqwh.com\": 1,\n\t\"freepcware.net\": 1,\n\t\"freescaleic.org\": 1,\n\t\"freezph.com\": 1,\n\t\"frjie.com\": 1,\n\t\"frpjh.com\": 1,\n\t\"frsky.com\": 1,\n\t\"fruitday.com\": 1,\n\t\"fs024.com\": 1,\n\t\"fs121.com\": 1,\n\t\"fs31.com\": 1,\n\t\"fs315.org\": 1,\n\t\"fs7000.com\": 1,\n\t\"fscfrc.com\": 1,\n\t\"fsclzs.com\": 1,\n\t\"fsjy.net\": 1,\n\t\"fskzpw.com\": 1,\n\t\"fsmama.com\": 1,\n\t\"fsmeeting.com\": 1,\n\t\"fspcdn.com\": 1,\n\t\"fssgjj.com\": 1,\n\t\"fsshyd.com\": 1,\n\t\"fstcb.com\": 1,\n\t\"fstta.com\": 1,\n\t\"fswanlei.com\": 1,\n\t\"fswchina.com\": 1,\n\t\"ft22.com\": 1,\n\t\"ftchinese.com\": 1,\n\t\"ftgsct.com\": 1,\n\t\"ftnews.net\": 1,\n\t\"ftuan.com\": 1,\n\t\"ftutj.net\": 1,\n\t\"ftxgame.com\": 1,\n\t\"fu08.com\": 1,\n\t\"fuanjob.com\": 1,\n\t\"fuanrc.com\": 1,\n\t\"fubaore.com\": 1,\n\t\"fuchan024.com\": 1,\n\t\"fudankao.com\": 1,\n\t\"fudaonet.com\": 1,\n\t\"fuguangchina.com\": 1,\n\t\"fuhaodq.com\": 1,\n\t\"fujian-window.com\": 1,\n\t\"fujianrc.com\": 1,\n\t\"fujiantulou.com\": 1,\n\t\"fuliansheng.com\": 1,\n\t\"fuliao.com\": 1,\n\t\"fuling.com\": 1,\n\t\"fuliyuwang.com\": 1,\n\t\"fumanhua.com\": 1,\n\t\"fumin.com\": 1,\n\t\"fumu.com\": 1,\n\t\"fumubang.com\": 1,\n\t\"fumuhui.com\": 1,\n\t\"fun.tv\": 1,\n\t\"funing114.com\": 1,\n\t\"funshion.com\": 1,\n\t\"funuo.com\": 1,\n\t\"funxoo.com\": 1,\n\t\"funxun.com\": 1,\n\t\"fupiaopifa.com\": 1,\n\t\"fupingjiazheng.com\": 1,\n\t\"fuqiangw.com\": 1,\n\t\"furielec.com\": 1,\n\t\"fushenshop.com\": 1,\n\t\"fushr.com\": 1,\n\t\"futurescn.net\": 1,\n\t\"fututa.com\": 1,\n\t\"fuxianren.com\": 1,\n\t\"fuyang.com\": 1,\n\t\"fuyangjob.net\": 1,\n\t\"fuyin365.com\": 1,\n\t\"fuzhuanghome.com\": 1,\n\t\"fw3721.com\": 1,\n\t\"fw55555.com\": 1,\n\t\"fwsir.com\": 1,\n\t\"fx120.net\": 1,\n\t\"fx168.com\": 1,\n\t\"fx1718.com\": 1,\n\t\"fx678.com\": 1,\n\t\"fx898.com\": 1,\n\t\"fx963.com\": 1,\n\t\"fxfk4.com\": 1,\n\t\"fxingw.com\": 1,\n\t\"fxsol-uk.com\": 1,\n\t\"fxtiyu.com\": 1,\n\t\"fxxz.com\": 1,\n\t\"fxyqw.com\": 1,\n\t\"fxytzz.com\": 1,\n\t\"fy14.com\": 1,\n\t\"fy168.cc\": 1,\n\t\"fy22.com\": 1,\n\t\"fyapw.com\": 1,\n\t\"fygjj.com\": 1,\n\t\"fynews.net\": 1,\n\t\"fysns.com\": 1,\n\t\"fytcw.com\": 1,\n\t\"fytest.com\": 1,\n\t\"fz12358.com\": 1,\n\t\"fz597.com\": 1,\n\t\"fzbbw.com\": 1,\n\t\"fzbm.com\": 1,\n\t\"fzcj.com\": 1,\n\t\"fzengine.com\": 1,\n\t\"fzfu.com\": 1,\n\t\"fzfzjx.com\": 1,\n\t\"fzg360.com\": 1,\n\t\"fzhitech.com\": 1,\n\t\"fzjol.com\": 1,\n\t\"fzlol.com\": 1,\n\t\"fzlu.com\": 1,\n\t\"fzlwc.com\": 1,\n\t\"fzmama.net\": 1,\n\t\"fzpchome.com\": 1,\n\t\"fzpig.com\": 1,\n\t\"fzpp.com\": 1,\n\t\"fzqnrc.com\": 1,\n\t\"fzqsng.net\": 1,\n\t\"fzrc.org\": 1,\n\t\"fzrczpw.com\": 1,\n\t\"fzrsrc.com\": 1,\n\t\"fzsjob.com\": 1,\n\t\"fzsme.com\": 1,\n\t\"fzwnjjw.com\": 1,\n\t\"fzzfgjj.com\": 1,\n\t\"fzzpw.net\": 1,\n\t\"fzzxbbs.com\": 1,\n\t\"g1080.com\": 1,\n\t\"g12e.com\": 1,\n\t\"g207.com\": 1,\n\t\"g2b2b.com\": 1,\n\t\"g312.com\": 1,\n\t\"g361.com\": 1,\n\t\"g855.com\": 1,\n\t\"ga-me.com\": 1,\n\t\"gacmotor.com\": 1,\n\t\"gai001.com\": 1,\n\t\"gaibar.com\": 1,\n\t\"gaitu.com\": 1,\n\t\"galaxyinfo.com\": 1,\n\t\"gall.me\": 1,\n\t\"galshi.com\": 1,\n\t\"game012.com\": 1,\n\t\"game080.com\": 1,\n\t\"game166.com\": 1,\n\t\"game247.net\": 1,\n\t\"game28.com\": 1,\n\t\"game3737.com\": 1,\n\t\"game3896.com\": 1,\n\t\"game3939.com\": 1,\n\t\"game511.com\": 1,\n\t\"game798.com\": 1,\n\t\"gamebbq.com\": 1,\n\t\"gamecomb.com\": 1,\n\t\"gamedg.com\": 1,\n\t\"gamehome.tv\": 1,\n\t\"gameres.com\": 1,\n\t\"gamerlol.com\": 1,\n\t\"gamersky.com\": 1,\n\t\"gamestlbb.com\": 1,\n\t\"gamesville.com\": 1,\n\t\"gamewan.net\": 1,\n\t\"gamfe.com\": 1,\n\t\"ganayinxiang.com\": 1,\n\t\"ganchang.org\": 1,\n\t\"ganggg.com\": 1,\n\t\"ganhuoche.com\": 1,\n\t\"ganji.com\": 1,\n\t\"ganjiangrc.com\": 1,\n\t\"ganjistatic1.com\": 1,\n\t\"gannanw.com\": 1,\n\t\"ganniu.com\": 1,\n\t\"ganpen.com\": 1,\n\t\"gansuci.com\": 1,\n\t\"gansupost.com\": 1,\n\t\"ganttcn.com\": 1,\n\t\"gantuan.com\": 1,\n\t\"ganwan.com\": 1,\n\t\"ganyu.com\": 1,\n\t\"ganzhe.com\": 1,\n\t\"ganzhong.net\": 1,\n\t\"ganzhouw.com\": 1,\n\t\"gao7.com\": 1,\n\t\"gao8dou.com\": 1,\n\t\"gaoan.com\": 1,\n\t\"gaoan.net\": 1,\n\t\"gaobohr.com\": 1,\n\t\"gaodun.com\": 1,\n\t\"gaofen.com\": 1,\n\t\"gaojieya.com\": 1,\n\t\"gaokao.com\": 1,\n\t\"gaokao789.com\": 1,\n\t\"gaokaopai.com\": 1,\n\t\"gaokw.com\": 1,\n\t\"gaolehui.com\": 1,\n\t\"gaoling.org\": 1,\n\t\"gaoloumi.com\": 1,\n\t\"gaopeng.com\": 1,\n\t\"gaosheng520.com\": 1,\n\t\"gaoshipf.com\": 1,\n\t\"gaosiedu.com\": 1,\n\t\"gaosivip.com\": 1,\n\t\"gaosubao.com\": 1,\n\t\"gaotieshike.com\": 1,\n\t\"gaotiewang.com\": 1,\n\t\"gaoxiaobaitai.com\": 1,\n\t\"gaoxiaojob.com\": 1,\n\t\"gaoxiaola.com\": 1,\n\t\"gaoxinkeji.com\": 1,\n\t\"gaoyizaixian.com\": 1,\n\t\"gaoyoujob.com\": 1,\n\t\"gaoyouzhaopin.com\": 1,\n\t\"gap.hk\": 1,\n\t\"garefu.com\": 1,\n\t\"garmentoffice.com\": 1,\n\t\"gasgoo.com\": 1,\n\t\"gashw.com\": 1,\n\t\"gasshow.com\": 1,\n\t\"gaszx.com\": 1,\n\t\"gatewang.com\": 1,\n\t\"gayleshome.com\": 1,\n\t\"gazx.org\": 1,\n\t\"gb87.com\": 1,\n\t\"gbdfang.com\": 1,\n\t\"gbeqo.com\": 1,\n\t\"gcb56.com\": 1,\n\t\"gcchina.com\": 1,\n\t\"gcimg.net\": 1,\n\t\"gcjc.com\": 1,\n\t\"gctezw.com\": 1,\n\t\"gcw.cm\": 1,\n\t\"gcwdq.com\": 1,\n\t\"gcwzj.com\": 1,\n\t\"gczx.cc\": 1,\n\t\"gd-china.com\": 1,\n\t\"gd-donglong.com\": 1,\n\t\"gd-e.com\": 1,\n\t\"gd-jiaoyu.com\": 1,\n\t\"gdafxh.org\": 1,\n\t\"gdagri.org\": 1,\n\t\"gdalpha.com\": 1,\n\t\"gdart.com\": 1,\n\t\"gdcct.com\": 1,\n\t\"gdcct.net\": 1,\n\t\"gdcg.net\": 1,\n\t\"gdcic.net\": 1,\n\t\"gdcoop.com\": 1,\n\t\"gdcost.com\": 1,\n\t\"gdcostzx.com\": 1,\n\t\"gdcrj.com\": 1,\n\t\"gddvb.com\": 1,\n\t\"gdedu123.com\": 1,\n\t\"gdeea.com\": 1,\n\t\"gdepi.com\": 1,\n\t\"gdgkw.org\": 1,\n\t\"gdglc.com\": 1,\n\t\"gdgpo.com\": 1,\n\t\"gdjrw.com\": 1,\n\t\"gdjxzs.com\": 1,\n\t\"gdkepu.com\": 1,\n\t\"gdlands.com\": 1,\n\t\"gdmxjy.com\": 1,\n\t\"gdongw.com\": 1,\n\t\"gdonlyedu.com\": 1,\n\t\"gdpp.com\": 1,\n\t\"gdql.org\": 1,\n\t\"gdrc.com\": 1,\n\t\"gdrc360.com\": 1,\n\t\"gdsalt.com\": 1,\n\t\"gdscse.net\": 1,\n\t\"gdshafa.com\": 1,\n\t\"gdsin.net\": 1,\n\t\"gdsrcw.com\": 1,\n\t\"gdstc.com\": 1,\n\t\"gdswine.com\": 1,\n\t\"gdsxxw.com\": 1,\n\t\"gdtarena.com\": 1,\n\t\"gdtoption.com\": 1,\n\t\"gdxxb.com\": 1,\n\t\"gdyctour.com\": 1,\n\t\"gdyjs.com\": 1,\n\t\"gdzhaojiao.com\": 1,\n\t\"gdzijin.com\": 1,\n\t\"gdzj8.com\": 1,\n\t\"geautos.com\": 1,\n\t\"gedu.org\": 1,\n\t\"geedu.com\": 1,\n\t\"geekpark.net\": 1,\n\t\"geely.com\": 1,\n\t\"geetest.com\": 1,\n\t\"geilidaquan.com\": 1,\n\t\"geilidjy.com\": 1,\n\t\"geilirc.com\": 1,\n\t\"gelinlan.net\": 1,\n\t\"gelun.org\": 1,\n\t\"gemdale.com\": 1,\n\t\"generalichina.com\": 1,\n\t\"gensee.com\": 1,\n\t\"gentags.net\": 1,\n\t\"genvict.com\": 1,\n\t\"geo-show.com\": 1,\n\t\"geo2k.com\": 1,\n\t\"geochina.com\": 1,\n\t\"geren-jianli.com\": 1,\n\t\"geren-jianli.org\": 1,\n\t\"gesep.com\": 1,\n\t\"getfirebug.com\": 1,\n\t\"gewara.com\": 1,\n\t\"gexing.com\": 1,\n\t\"gexings.com\": 1,\n\t\"geyanw.com\": 1,\n\t\"gezila.com\": 1,\n\t\"gfan.com\": 1,\n\t\"gfcang.com\": 1,\n\t\"gfgt.com\": 1,\n\t\"gfw.io\": 1,\n\t\"gfw0898.com\": 1,\n\t\"gfwz100.com\": 1,\n\t\"gfzihua.com\": 1,\n\t\"gg-art.com\": 1,\n\t\"gg-led.com\": 1,\n\t\"gg114.net\": 1,\n\t\"gg1z.com\": 1,\n\t\"ggact.com\": 1,\n\t\"ggcj.com\": 1,\n\t\"ggd5.com\": 1,\n\t\"gggjs.com\": 1,\n\t\"gghappy.com\": 1,\n\t\"ggmm777.com\": 1,\n\t\"ggsafe.com\": 1,\n\t\"ggsgg.com\": 1,\n\t\"ghjie.com\": 1,\n\t\"ghjmz.com\": 1,\n\t\"ghzpw.com\": 1,\n\t\"giabbs.com\": 1,\n\t\"gialen.com\": 1,\n\t\"gieaa.org\": 1,\n\t\"gifore.com\": 1,\n\t\"gift12345.com\": 1,\n\t\"giftjie.com\": 1,\n\t\"giftsbeijing.com\": 1,\n\t\"gjgwy.net\": 1,\n\t\"gjgwy.org\": 1,\n\t\"gjgzpw.com\": 1,\n\t\"gjjnhb.com\": 1,\n\t\"gk-z.com\": 1,\n\t\"gk505.com\": 1,\n\t\"gk99.com\": 1,\n\t\"gkcity.com\": 1,\n\t\"gkfree.com\": 1,\n\t\"gkong.com\": 1,\n\t\"gkstk.com\": 1,\n\t\"gkzhan.com\": 1,\n\t\"gkzy100.com\": 1,\n\t\"gl110.com\": 1,\n\t\"gl114.net\": 1,\n\t\"glasshr.com\": 1,\n\t\"glassinchina.com\": 1,\n\t\"glinfo.com\": 1,\n\t\"glituan.com\": 1,\n\t\"glmama.com\": 1,\n\t\"global-trade-center.com\": 1,\n\t\"globalbook.org\": 1,\n\t\"globalbuy.cc\": 1,\n\t\"globalchemmade.com\": 1,\n\t\"globalcompressor.com\": 1,\n\t\"globalfabric.com\": 1,\n\t\"globalhardwares.com\": 1,\n\t\"globalimporter.net\": 1,\n\t\"globeedu.com\": 1,\n\t\"globeimmi.com\": 1,\n\t\"globepv.com\": 1,\n\t\"globrand.com\": 1,\n\t\"gloryre.com\": 1,\n\t\"glosspp.com\": 1,\n\t\"glpx.com\": 1,\n\t\"glrcw.com\": 1,\n\t\"glwmw.com\": 1,\n\t\"gly360.com\": 1,\n\t\"glyrc.com\": 1,\n\t\"glzy8.com\": 1,\n\t\"gm178.net\": 1,\n\t\"gm263.com\": 1,\n\t\"gm86.com\": 1,\n\t\"gmacsaic.net\": 1,\n\t\"gming.org\": 1,\n\t\"gmseb.net\": 1,\n\t\"gmtv.cc\": 1,\n\t\"gn00.com\": 1,\n\t\"gndaily.com\": 1,\n\t\"gntv.tv\": 1,\n\t\"go007.com\": 1,\n\t\"go24k.com\": 1,\n\t\"go2map.com\": 1,\n\t\"go823.com\": 1,\n\t\"go9939.com\": 1,\n\t\"goart100.com\": 1,\n\t\"god520.net\": 1,\n\t\"godsignal.com\": 1,\n\t\"goepe.com\": 1,\n\t\"goes123.com\": 1,\n\t\"gogohome.com\": 1,\n\t\"goheee.com\": 1,\n\t\"gohku.com\": 1,\n\t\"gohoedu.com\": 1,\n\t\"gojiaju.com\": 1,\n\t\"gojiaju.net\": 1,\n\t\"gold186.com\": 1,\n\t\"gold58.com\": 1,\n\t\"gold678.com\": 1,\n\t\"goldenagri.com\": 1,\n\t\"goldenholiday.com\": 1,\n\t\"golue.com\": 1,\n\t\"gomeart.com\": 1,\n\t\"gomeart.net\": 1,\n\t\"gong123.com\": 1,\n\t\"gong7jun.com\": 1,\n\t\"gongchang.com\": 1,\n\t\"gongjiao.com\": 1,\n\t\"gongjiaomi.com\": 1,\n\t\"gongjing880.com\": 1,\n\t\"gongkong.com\": 1,\n\t\"gongpingjia.com\": 1,\n\t\"gongshunews.com\": 1,\n\t\"gongyequan.com\": 1,\n\t\"gongyishibao.com\": 1,\n\t\"gongzuo365.com\": 1,\n\t\"goo2sc.com\": 1,\n\t\"goodacc.net\": 1,\n\t\"goodbaby.com\": 1,\n\t\"goodbabygroup.com\": 1,\n\t\"goodjd.com\": 1,\n\t\"goodjob100.com\": 1,\n\t\"goodkejian.com\": 1,\n\t\"goodtea.cc\": 1,\n\t\"google-analytics.com\": 1,\n\t\"googleadservices.com\": 1,\n\t\"googlesyndication.com\": 1,\n\t\"gooniu.com\": 1,\n\t\"gooooal.com\": 1,\n\t\"goootech.com\": 1,\n\t\"gopuu.com\": 1,\n\t\"gotohz.com\": 1,\n\t\"gotoip1.com\": 1,\n\t\"gotoip2.com\": 1,\n\t\"gotoip4.com\": 1,\n\t\"gotoip55.com\": 1,\n\t\"gotoningbo.com\": 1,\n\t\"gotoread.com\": 1,\n\t\"gotosd.com\": 1,\n\t\"gotozjj.net\": 1,\n\t\"gou3618.com\": 1,\n\t\"goubuy.com\": 1,\n\t\"gouchezixun.com\": 1,\n\t\"goufang.com\": 1,\n\t\"goufun8.com\": 1,\n\t\"goufw.com\": 1,\n\t\"gougou.com\": 1,\n\t\"gouhainan.com\": 1,\n\t\"gouhao.com\": 1,\n\t\"gouhuasuan.net\": 1,\n\t\"goulew.com\": 1,\n\t\"goumin.com\": 1,\n\t\"goupuzi.com\": 1,\n\t\"gouwuke.com\": 1,\n\t\"gov86.com\": 1,\n\t\"gowulong.com\": 1,\n\t\"gpcxw.com\": 1,\n\t\"gpinhui.com\": 1,\n\t\"gprcw.com\": 1,\n\t\"gpres.com\": 1,\n\t\"gps688.com\": 1,\n\t\"gpxz.com\": 1,\n\t\"gq58.com\": 1,\n\t\"gq66.com\": 1,\n\t\"gqcsswj.com\": 1,\n\t\"gqsoso.com\": 1,\n\t\"gqsoso.net\": 1,\n\t\"gqt168.com\": 1,\n\t\"gqw.cc\": 1,\n\t\"grchina.com\": 1,\n\t\"greatwuyi.com\": 1,\n\t\"gree.com\": 1,\n\t\"greenbodhi.com\": 1,\n\t\"greenchina.tv\": 1,\n\t\"greenfood.org\": 1,\n\t\"greening-china.com\": 1,\n\t\"greenlandsc.com\": 1,\n\t\"greenlem.com\": 1,\n\t\"greenxf.com\": 1,\n\t\"greenxiazai.com\": 1,\n\t\"grfy.net\": 1,\n\t\"grfyw.com\": 1,\n\t\"gridsources.com\": 1,\n\t\"gridsumdissector.com\": 1,\n\t\"grinm.com\": 1,\n\t\"gronhi.com\": 1,\n\t\"grxxw.com\": 1,\n\t\"gsdaquan.com\": 1,\n\t\"gsdtarena.com\": 1,\n\t\"gsdwhm.com\": 1,\n\t\"gsean.org\": 1,\n\t\"gsflcp.com\": 1,\n\t\"gsftw.com\": 1,\n\t\"gsgrain.com\": 1,\n\t\"gsheimeiren.com\": 1,\n\t\"gsheitudou.com\": 1,\n\t\"gsjb.com\": 1,\n\t\"gskjcg.com\": 1,\n\t\"gspst.com\": 1,\n\t\"gsqiu.com\": 1,\n\t\"gsrcw.com\": 1,\n\t\"gsslu.com\": 1,\n\t\"gstarcad.com\": 1,\n\t\"gswhgl.com\": 1,\n\t\"gsxpz.com\": 1,\n\t\"gt120.net\": 1,\n\t\"gtags.net\": 1,\n\t\"gteachers.org\": 1,\n\t\"gtfund.com\": 1,\n\t\"gtgqw.com\": 1,\n\t\"gtimg.com\": 1,\n\t\"gtja.com\": 1,\n\t\"gtjg.net\": 1,\n\t\"gtjia.com\": 1,\n\t\"gtobal.com\": 1,\n\t\"gtobal.net\": 1,\n\t\"gtuu.com\": 1,\n\t\"gtxh.com\": 1,\n\t\"gtxjob8001.com\": 1,\n\t\"gtzyb.com\": 1,\n\t\"guahao.com\": 1,\n\t\"guaiguai.com\": 1,\n\t\"guaixun.com\": 1,\n\t\"guan5.com\": 1,\n\t\"guanchengrc.com\": 1,\n\t\"guandongphoto.com\": 1,\n\t\"guanfang123.com\": 1,\n\t\"guang.com\": 1,\n\t\"guangdongrc.com\": 1,\n\t\"guangdongshaiwang.com\": 1,\n\t\"guangjiela.com\": 1,\n\t\"guangshuishi.com\": 1,\n\t\"guangxirc.com\": 1,\n\t\"guangyidj.com\": 1,\n\t\"guanjiatu.com\": 1,\n\t\"guanlishi.com\": 1,\n\t\"guanrencai.com\": 1,\n\t\"guanshangyu.cc\": 1,\n\t\"guanzhongrc.com\": 1,\n\t\"guanzhujia.com\": 1,\n\t\"guatian.com\": 1,\n\t\"gucheng.com\": 1,\n\t\"gucn.com\": 1,\n\t\"gudianwenxue.com\": 1,\n\t\"gugubaby.com\": 1,\n\t\"guhantai.com\": 1,\n\t\"guidaye.com\": 1,\n\t\"guidechem.com\": 1,\n\t\"guigu.org\": 1,\n\t\"guiguanrc.com\": 1,\n\t\"guiguanwater.com\": 1,\n\t\"guihuashi.org\": 1,\n\t\"guijinshu.com\": 1,\n\t\"guijirc.com\": 1,\n\t\"guijj.com\": 1,\n\t\"guijob.com\": 1,\n\t\"guilin.cm\": 1,\n\t\"guilinauto.com\": 1,\n\t\"guilinbaobao.com\": 1,\n\t\"guilincits.com\": 1,\n\t\"guilinhd.com\": 1,\n\t\"guilinlife.com\": 1,\n\t\"guillot-wine.com\": 1,\n\t\"guimi.com\": 1,\n\t\"guimobile.net\": 1,\n\t\"guiqianrc.com\": 1,\n\t\"guiyinwang.com\": 1,\n\t\"guizhouchine.com\": 1,\n\t\"gulangyuzhusu.com\": 1,\n\t\"guluyou.com\": 1,\n\t\"guo7.com\": 1,\n\t\"guocar.com\": 1,\n\t\"guochengxin.com\": 1,\n\t\"guodiy.com\": 1,\n\t\"guodu.com\": 1,\n\t\"guofenchaxun.com\": 1,\n\t\"guofs.com\": 1,\n\t\"guohuajia.net\": 1,\n\t\"guoji110.com\": 1,\n\t\"guojixumu.com\": 1,\n\t\"guolairen.com\": 1,\n\t\"guoling.com\": 1,\n\t\"guoluzhan.com\": 1,\n\t\"guolv.com\": 1,\n\t\"guolvol.com\": 1,\n\t\"guoman8.com\": 1,\n\t\"guomii.com\": 1,\n\t\"guoshi.com\": 1,\n\t\"guoxue.com\": 1,\n\t\"guoyang.cc\": 1,\n\t\"guozhekou.com\": 1,\n\t\"guozhen-health.com\": 1,\n\t\"gupiaobaba.com\": 1,\n\t\"gupzs.com\": 1,\n\t\"guqu.net\": 1,\n\t\"guquanwang.com\": 1,\n\t\"guquanzhuanrang.com\": 1,\n\t\"gushibaike.com\": 1,\n\t\"gushici5.com\": 1,\n\t\"gushihui8.com\": 1,\n\t\"gushq.com\": 1,\n\t\"gusu.cc\": 1,\n\t\"gusuan.net\": 1,\n\t\"gusuwang.com\": 1,\n\t\"gutx.com\": 1,\n\t\"guuoo.com\": 1,\n\t\"guwanw.com\": 1,\n\t\"guyi.cc\": 1,\n\t\"guzhiwang.com\": 1,\n\t\"gw12580.com\": 1,\n\t\"gwyoo.com\": 1,\n\t\"gwyou.com\": 1,\n\t\"gwyscs.com\": 1,\n\t\"gx-job.com\": 1,\n\t\"gx123.com\": 1,\n\t\"gx12301.com\": 1,\n\t\"gx211.com\": 1,\n\t\"gx315.org\": 1,\n\t\"gxaas.net\": 1,\n\t\"gxacw.com\": 1,\n\t\"gxajj.com\": 1,\n\t\"gxb2b.net\": 1,\n\t\"gxbd.com\": 1,\n\t\"gxbstv.com\": 1,\n\t\"gxbys.com\": 1,\n\t\"gxcic.net\": 1,\n\t\"gxcity.com\": 1,\n\t\"gxdqw.com\": 1,\n\t\"gxfcgedu.com\": 1,\n\t\"gxfdcw.com\": 1,\n\t\"gxfpw.com\": 1,\n\t\"gxfsqm.com\": 1,\n\t\"gxftu.org\": 1,\n\t\"gxgrain.com\": 1,\n\t\"gxgzf.com\": 1,\n\t\"gxhczw.com\": 1,\n\t\"gxhouse.com\": 1,\n\t\"gxhzxw.com\": 1,\n\t\"gxidc.com\": 1,\n\t\"gxielts.com\": 1,\n\t\"gxingw.com\": 1,\n\t\"gxipo.net\": 1,\n\t\"gxjbsj.com\": 1,\n\t\"gxjcjj.com\": 1,\n\t\"gxjk.net\": 1,\n\t\"gxjlrc.com\": 1,\n\t\"gxjpjy.com\": 1,\n\t\"gxjtaq.com\": 1,\n\t\"gxjubao.org\": 1,\n\t\"gxlottery.com\": 1,\n\t\"gxmengshan.net\": 1,\n\t\"gxorg.com\": 1,\n\t\"gxphoto.net\": 1,\n\t\"gxpx114.com\": 1,\n\t\"gxqcw.com\": 1,\n\t\"gxrc.com\": 1,\n\t\"gxrcw.com\": 1,\n\t\"gxsell.com\": 1,\n\t\"gxsky.com\": 1,\n\t\"gxst.net\": 1,\n\t\"gxsti.net\": 1,\n\t\"gxswnews.com\": 1,\n\t\"gxtcmhw.com\": 1,\n\t\"gxworker.com\": 1,\n\t\"gxylnews.com\": 1,\n\t\"gxzjy.com\": 1,\n\t\"gxzs.org\": 1,\n\t\"gy007.com\": 1,\n\t\"gy365.com\": 1,\n\t\"gy9y.com\": 1,\n\t\"gyart.org\": 1,\n\t\"gycc.net\": 1,\n\t\"gyfcxx.com\": 1,\n\t\"gyfff.com\": 1,\n\t\"gyhqys.com\": 1,\n\t\"gyjob.net\": 1,\n\t\"gymama.com\": 1,\n\t\"gymsj.com\": 1,\n\t\"gysou.com\": 1,\n\t\"gytxjx.com\": 1,\n\t\"gyxuan.com\": 1,\n\t\"gyxuan.org\": 1,\n\t\"gyxww.net\": 1,\n\t\"gyzy.com\": 1,\n\t\"gyzyfw.com\": 1,\n\t\"gz-travel.net\": 1,\n\t\"gz-zikao.com\": 1,\n\t\"gz007.net\": 1,\n\t\"gz0797.com\": 1,\n\t\"gz12301.com\": 1,\n\t\"gz300.com\": 1,\n\t\"gz5168.com\": 1,\n\t\"gzast.org\": 1,\n\t\"gzbaozhilin.com\": 1,\n\t\"gzbdqn.com\": 1,\n\t\"gzcofc.com\": 1,\n\t\"gzcol.com\": 1,\n\t\"gzcpc.com\": 1,\n\t\"gzcsly.com\": 1,\n\t\"gzcyxw.com\": 1,\n\t\"gzcyxww.com\": 1,\n\t\"gzdsw.com\": 1,\n\t\"gzeic.com\": 1,\n\t\"gzgczj.com\": 1,\n\t\"gzh.com\": 1,\n\t\"gzhstars.net\": 1,\n\t\"gzhtzy.com\": 1,\n\t\"gzjcw.com\": 1,\n\t\"gzjtzy.net\": 1,\n\t\"gzjunkai.com\": 1,\n\t\"gzjunyu.com\": 1,\n\t\"gzjy360.com\": 1,\n\t\"gzlib.org\": 1,\n\t\"gzlight.com\": 1,\n\t\"gzlrck.com\": 1,\n\t\"gzmama.com\": 1,\n\t\"gzmeilin.com\": 1,\n\t\"gzml56.com\": 1,\n\t\"gzmtr.com\": 1,\n\t\"gzmzb.com\": 1,\n\t\"gznet.com\": 1,\n\t\"gznsny.com\": 1,\n\t\"gznw.com\": 1,\n\t\"gzpds.com\": 1,\n\t\"gzpoly.com\": 1,\n\t\"gzport.com\": 1,\n\t\"gzpx360.com\": 1,\n\t\"gzqnzyz.com\": 1,\n\t\"gzqxn.com\": 1,\n\t\"gzqzlx.com\": 1,\n\t\"gzrck.com\": 1,\n\t\"gzrcw.com\": 1,\n\t\"gzrczpw.com\": 1,\n\t\"gzre.com\": 1,\n\t\"gzredcross.org\": 1,\n\t\"gzrencai.com\": 1,\n\t\"gzrinm.com\": 1,\n\t\"gzsalt.com\": 1,\n\t\"gzsedu.com\": 1,\n\t\"gzsggj.com\": 1,\n\t\"gzsjyzx.com\": 1,\n\t\"gzstv.com\": 1,\n\t\"gzstv.net\": 1,\n\t\"gzsy.com\": 1,\n\t\"gzszfgjj.com\": 1,\n\t\"gzszk.com\": 1,\n\t\"gztarena.com\": 1,\n\t\"gztcdj.com\": 1,\n\t\"gzto.com\": 1,\n\t\"gztv.com\": 1,\n\t\"gzwanmeikongjian.com\": 1,\n\t\"gzweilanhaian.com\": 1,\n\t\"gzweix.com\": 1,\n\t\"gzxishui.com\": 1,\n\t\"gzxxw.com\": 1,\n\t\"gzyeah.com\": 1,\n\t\"gzyes.com\": 1,\n\t\"gzzfzx.com\": 1,\n\t\"gzzkzsw.com\": 1,\n\t\"gzzoc.com\": 1,\n\t\"h0591.com\": 1,\n\t\"h0838.com\": 1,\n\t\"h2o-china.com\": 1,\n\t\"h6969.com\": 1,\n\t\"ha597.com\": 1,\n\t\"ha91.com\": 1,\n\t\"habctv.com\": 1,\n\t\"hackdos.com\": 1,\n\t\"hackhome.com\": 1,\n\t\"hackp.com\": 1,\n\t\"haebinnews.com\": 1,\n\t\"hafcw.net\": 1,\n\t\"hagjj.com\": 1,\n\t\"haha56.net\": 1,\n\t\"hahaertong.com\": 1,\n\t\"hahait.com\": 1,\n\t\"hahazaojiao.com\": 1,\n\t\"hai126.net\": 1,\n\t\"haianw.com\": 1,\n\t\"haibao.com\": 1,\n\t\"haidaiwan.com\": 1,\n\t\"haidian123.com\": 1,\n\t\"haier.com\": 1,\n\t\"haier.net\": 1,\n\t\"haifangzj.com\": 1,\n\t\"haiguan.info\": 1,\n\t\"haihr.com\": 1,\n\t\"haiis.com\": 1,\n\t\"haijiaonet.com\": 1,\n\t\"haijingfang.cc\": 1,\n\t\"haijingfangcn.com\": 1,\n\t\"haijun360.com\": 1,\n\t\"haikele.com\": 1,\n\t\"haimanfeisi.com\": 1,\n\t\"haimenhr.com\": 1,\n\t\"hainan.net\": 1,\n\t\"hainan0898.net\": 1,\n\t\"hainancoop.com\": 1,\n\t\"hainanese.com\": 1,\n\t\"hainanfz.com\": 1,\n\t\"hainanhr.com\": 1,\n\t\"hainanpc.net\": 1,\n\t\"hainanredcross.org\": 1,\n\t\"hainei.org\": 1,\n\t\"haining.com\": 1,\n\t\"haining.me\": 1,\n\t\"haiqintech.com\": 1,\n\t\"haiqq.com\": 1,\n\t\"hairuolawyer.net\": 1,\n\t\"haishen.com\": 1,\n\t\"haisheninfo.com\": 1,\n\t\"haishenjia.com\": 1,\n\t\"haishui.cc\": 1,\n\t\"haitian.com\": 1,\n\t\"haiwaisheying.com\": 1,\n\t\"haixiachina.com\": 1,\n\t\"haixiyin.com\": 1,\n\t\"haixuan12.com\": 1,\n\t\"haliyuya.com\": 1,\n\t\"haljl.com\": 1,\n\t\"han-tang.cc\": 1,\n\t\"hancheng.com\": 1,\n\t\"handanjob.com\": 1,\n\t\"handsbrain.com\": 1,\n\t\"handu.com\": 1,\n\t\"hangkong.com\": 1,\n\t\"hanguoyou.org\": 1,\n\t\"hanhai.net\": 1,\n\t\"hanjialan.net\": 1,\n\t\"hanmaidj.com\": 1,\n\t\"hantinghotels.com\": 1,\n\t\"hanvontouch.com\": 1,\n\t\"hanweb.com\": 1,\n\t\"hanyouwang.com\": 1,\n\t\"hanzhibing.com\": 1,\n\t\"hanzhong123.com\": 1,\n\t\"hanzify.org\": 1,\n\t\"hao-sheng-yi.com\": 1,\n\t\"hao123.com\": 1,\n\t\"hao123img.com\": 1,\n\t\"hao224.com\": 1,\n\t\"hao315.cc\": 1,\n\t\"hao315.com\": 1,\n\t\"hao315.tv\": 1,\n\t\"hao60.net\": 1,\n\t\"haobashi.com\": 1,\n\t\"haocf.net\": 1,\n\t\"haochehui.com\": 1,\n\t\"haochi123.com\": 1,\n\t\"haochimei.com\": 1,\n\t\"haochu.com\": 1,\n\t\"haocw.com\": 1,\n\t\"haodai.com\": 1,\n\t\"haodf.com\": 1,\n\t\"haodingdan.com\": 1,\n\t\"haodir.cc\": 1,\n\t\"haodou.com\": 1,\n\t\"haoduoge.com\": 1,\n\t\"haoeyou.com\": 1,\n\t\"haofanben.com\": 1,\n\t\"haofang.net\": 1,\n\t\"haofgo.com\": 1,\n\t\"haofjj.com\": 1,\n\t\"haofung.com\": 1,\n\t\"haofz.com\": 1,\n\t\"haogeqiang.com\": 1,\n\t\"haogongzhang.com\": 1,\n\t\"haohaizi.com\": 1,\n\t\"haohetao.com\": 1,\n\t\"haohuiyi.com\": 1,\n\t\"haohuoyuan.com\": 1,\n\t\"haojieyue.com\": 1,\n\t\"haojufang.com\": 1,\n\t\"haokan5.com\": 1,\n\t\"haokecheng.com\": 1,\n\t\"haole.com\": 1,\n\t\"haoleyou.com\": 1,\n\t\"haolietou.com\": 1,\n\t\"haoliv.com\": 1,\n\t\"haoloubang.com\": 1,\n\t\"haomahaoba.com\": 1,\n\t\"haonongzi.com\": 1,\n\t\"haopeixun.org\": 1,\n\t\"haopic.me\": 1,\n\t\"haopoo.com\": 1,\n\t\"haoqu.net\": 1,\n\t\"haorc.com\": 1,\n\t\"haorencai.net\": 1,\n\t\"haorennet.com\": 1,\n\t\"haorenyuan.so\": 1,\n\t\"haoshangjia.com\": 1,\n\t\"haosilu.com\": 1,\n\t\"haotaotuan.com\": 1,\n\t\"haotc.net\": 1,\n\t\"haote.com\": 1,\n\t\"haott.com\": 1,\n\t\"haotui.com\": 1,\n\t\"haowangpu.com\": 1,\n\t\"haowm.com\": 1,\n\t\"haowywz.com\": 1,\n\t\"haoxuee.com\": 1,\n\t\"haoxuexiao.cc\": 1,\n\t\"haoxx.com\": 1,\n\t\"haoyingshi.cc\": 1,\n\t\"haoyingyong.net\": 1,\n\t\"haoyiz.com\": 1,\n\t\"haoyouyinxiang.com\": 1,\n\t\"haoyunbb.com\": 1,\n\t\"haoyunmom.com\": 1,\n\t\"haoyuwang.net\": 1,\n\t\"haoyuyuan.com\": 1,\n\t\"haoyy114.com\": 1,\n\t\"haozhanhui.com\": 1,\n\t\"haozhuodao.com\": 1,\n\t\"haozu.com\": 1,\n\t\"haozu163.com\": 1,\n\t\"haozu168.com\": 1,\n\t\"haozuojia.com\": 1,\n\t\"happy3399.com\": 1,\n\t\"happyqiao.com\": 1,\n\t\"harrenmedianetwork.com\": 1,\n\t\"haxiu.com\": 1,\n\t\"hazp.net\": 1,\n\t\"hazpw.org\": 1,\n\t\"hazxqyw.com\": 1,\n\t\"hb-csc.com\": 1,\n\t\"hb0376.com\": 1,\n\t\"hb0561.com\": 1,\n\t\"hb114.cc\": 1,\n\t\"hb12333.com\": 1,\n\t\"hb12369.net\": 1,\n\t\"hb261.com\": 1,\n\t\"hb30.com\": 1,\n\t\"hbaas.com\": 1,\n\t\"hbaes.com\": 1,\n\t\"hbcl-car.com\": 1,\n\t\"hbcljyc.com\": 1,\n\t\"hbclwqzc.com\": 1,\n\t\"hbcoal.com\": 1,\n\t\"hbcourt.org\": 1,\n\t\"hbcpre.com\": 1,\n\t\"hbdangyang.com\": 1,\n\t\"hbeol.com\": 1,\n\t\"hbfcw.cc\": 1,\n\t\"hbfy.com\": 1,\n\t\"hbfzb.com\": 1,\n\t\"hbgajg.com\": 1,\n\t\"hbglky.com\": 1,\n\t\"hbgrain.com\": 1,\n\t\"hbgrb.net\": 1,\n\t\"hbgsl.com\": 1,\n\t\"hbh520.com\": 1,\n\t\"hbhbhb.com\": 1,\n\t\"hbhro.com\": 1,\n\t\"hbjnzyqc.com\": 1,\n\t\"hbjob88.com\": 1,\n\t\"hbjzlm.com\": 1,\n\t\"hbksw.com\": 1,\n\t\"hbnews.net\": 1,\n\t\"hbnyw.com\": 1,\n\t\"hbpx.net\": 1,\n\t\"hbqnb.com\": 1,\n\t\"hbrc.com\": 1,\n\t\"hbrchina.org\": 1,\n\t\"hbrcw.com\": 1,\n\t\"hbrd.net\": 1,\n\t\"hbredcross.org\": 1,\n\t\"hbs0561.com\": 1,\n\t\"hbshgzx.com\": 1,\n\t\"hbsjz110.com\": 1,\n\t\"hbsky58.net\": 1,\n\t\"hbsztv.com\": 1,\n\t\"hbtcw.com\": 1,\n\t\"hbtlz.com\": 1,\n\t\"hbtycp.com\": 1,\n\t\"hbw.cc\": 1,\n\t\"hbwenshi.com\": 1,\n\t\"hbww.org\": 1,\n\t\"hbxfmp.com\": 1,\n\t\"hbxfzs.com\": 1,\n\t\"hbxmad.com\": 1,\n\t\"hbycw.net\": 1,\n\t\"hbyczk.com\": 1,\n\t\"hbyidu.com\": 1,\n\t\"hbzaix.com\": 1,\n\t\"hbzhan.com\": 1,\n\t\"hbzj.net\": 1,\n\t\"hbzkw.com\": 1,\n\t\"hbzp.cc\": 1,\n\t\"hbzyfc.com\": 1,\n\t\"hc360.com\": 1,\n\t\"hc433.com\": 1,\n\t\"hc699.com\": 1,\n\t\"hc918.com\": 1,\n\t\"hcdgzz.com\": 1,\n\t\"hcdmy.com\": 1,\n\t\"hche.com\": 1,\n\t\"hcl100.com\": 1,\n\t\"hcms.cc\": 1,\n\t\"hcsindex.org\": 1,\n\t\"hctvnet.com\": 1,\n\t\"hcw.so\": 1,\n\t\"hcwexpo.com\": 1,\n\t\"hcxww.com\": 1,\n\t\"hdabc.com\": 1,\n\t\"hdavchina.com\": 1,\n\t\"hdcmr.com\": 1,\n\t\"hddcw.com\": 1,\n\t\"hdeso.com\": 1,\n\t\"hdgch.org\": 1,\n\t\"hdletv.com\": 1,\n\t\"hdmjdec.com\": 1,\n\t\"hdmnw.com\": 1,\n\t\"hdpfans.com\": 1,\n\t\"hdslb.com\": 1,\n\t\"hdtlxx.com\": 1,\n\t\"hdzc.net\": 1,\n\t\"hdzp.com\": 1,\n\t\"hdzxw.com\": 1,\n\t\"hdzyhm.com\": 1,\n\t\"he-nan.com\": 1,\n\t\"heacn.net\": 1,\n\t\"headstour.com\": 1,\n\t\"healthoo.com\": 1,\n\t\"healthr.com\": 1,\n\t\"heartconn.com\": 1,\n\t\"heb-huaqiang.com\": 1,\n\t\"hebauto.com\": 1,\n\t\"hebcar.com\": 1,\n\t\"hebcoop.com\": 1,\n\t\"hebdx.com\": 1,\n\t\"hebeijiaoyu.com\": 1,\n\t\"hebgcc.org\": 1,\n\t\"hebgh.org\": 1,\n\t\"hebgtjt.com\": 1,\n\t\"hebikuoda.com\": 1,\n\t\"hebircw.com\": 1,\n\t\"hebiw.com\": 1,\n\t\"hebjxw.com\": 1,\n\t\"hebnc.com\": 1,\n\t\"hebnky.com\": 1,\n\t\"hebpi.com\": 1,\n\t\"hebradio.com\": 1,\n\t\"hebredcross.org\": 1,\n\t\"hebtv.com\": 1,\n\t\"hedaoxuan.com\": 1,\n\t\"hefei.cc\": 1,\n\t\"hefei58.com\": 1,\n\t\"hefeizhaopin.com\": 1,\n\t\"hehu.com\": 1,\n\t\"hehuigj.com\": 1,\n\t\"hehuit.com\": 1,\n\t\"heiguang.com\": 1,\n\t\"heiguang.net\": 1,\n\t\"heiheiwan.com\": 1,\n\t\"heima.com\": 1,\n\t\"heima8.com\": 1,\n\t\"heimashop.com\": 1,\n\t\"heimaying.com\": 1,\n\t\"heixo.com\": 1,\n\t\"heiyan.com\": 1,\n\t\"heiyanimg.com\": 1,\n\t\"heiyc.com\": 1,\n\t\"heiye.cc\": 1,\n\t\"hejia.tv\": 1,\n\t\"hejiang.com\": 1,\n\t\"hello-code.com\": 1,\n\t\"hellozx.com\": 1,\n\t\"help.apple.com\": 1,\n\t\"hemei120.com\": 1,\n\t\"henan-edu.com\": 1,\n\t\"henan-zikao.com\": 1,\n\t\"henan100.com\": 1,\n\t\"henanci.com\": 1,\n\t\"henandingsheng.com\": 1,\n\t\"henanfucai.com\": 1,\n\t\"henanqiuxue.com\": 1,\n\t\"henanrc.com\": 1,\n\t\"henanredcross.org\": 1,\n\t\"henantiyu.com\": 1,\n\t\"henau.net\": 1,\n\t\"hengqian.co\": 1,\n\t\"hengqian.com\": 1,\n\t\"hengqian.org\": 1,\n\t\"hengqijy.com\": 1,\n\t\"hengtonggroup.com\": 1,\n\t\"hengyan.com\": 1,\n\t\"hengyuandianlu.com\": 1,\n\t\"hepan.com\": 1,\n\t\"hepan.org\": 1,\n\t\"hepost.com\": 1,\n\t\"hepuercha.com\": 1,\n\t\"herbalife-health.com\": 1,\n\t\"hercity.com\": 1,\n\t\"herostart.com\": 1,\n\t\"herschina.com\": 1,\n\t\"hetaitea.com\": 1,\n\t\"hetda.com\": 1,\n\t\"heungkong.com\": 1,\n\t\"hewei-china.com\": 1,\n\t\"hexianbbs.com\": 1,\n\t\"hexieshaanxi.com\": 1,\n\t\"hexindai.com\": 1,\n\t\"hexun.com\": 1,\n\t\"hexun.com.tw\": 1,\n\t\"hexuncn.com\": 1,\n\t\"heyang.cc\": 1,\n\t\"heze.cc\": 1,\n\t\"heze369.com\": 1,\n\t\"hezedc.com\": 1,\n\t\"hezefangchan.cc\": 1,\n\t\"hezefc.cc\": 1,\n\t\"hezefc.com\": 1,\n\t\"hezejk.com\": 1,\n\t\"hezejob.com\": 1,\n\t\"hezeqc.cc\": 1,\n\t\"hezeqiche.cc\": 1,\n\t\"hezerencai.cc\": 1,\n\t\"hezeribao.com\": 1,\n\t\"hf365.com\": 1,\n\t\"hf777.com\": 1,\n\t\"hf99.com\": 1,\n\t\"hfairport.com\": 1,\n\t\"hfbowei.com\": 1,\n\t\"hfbtv.com\": 1,\n\t\"hfcjl.com\": 1,\n\t\"hfgdfz.net\": 1,\n\t\"hfgjj.com\": 1,\n\t\"hfhouse.com\": 1,\n\t\"hfib.org\": 1,\n\t\"hfjcbs.com\": 1,\n\t\"hfjfcm.com\": 1,\n\t\"hfjieneng.com\": 1,\n\t\"hfmama.com\": 1,\n\t\"hftogo.com\": 1,\n\t\"hfw.cc\": 1,\n\t\"hfwenshi.com\": 1,\n\t\"hg-z.com\": 1,\n\t\"hg707.com\": 1,\n\t\"hgitv.com\": 1,\n\t\"hgjob.com\": 1,\n\t\"hglaser.com\": 1,\n\t\"hgnc.net\": 1,\n\t\"hgrencai.com\": 1,\n\t\"hgtvu.com\": 1,\n\t\"hgzrc.com\": 1,\n\t\"hh-w.com\": 1,\n\t\"hh010.com\": 1,\n\t\"hhbwjsc.com\": 1,\n\t\"hhczy.com\": 1,\n\t\"hhfcw.com\": 1,\n\t\"hhgjj.com\": 1,\n\t\"hhhtnews.com\": 1,\n\t\"hhhtrx.com\": 1,\n\t\"hhk365.com\": 1,\n\t\"hhkao.com\": 1,\n\t\"hhlepin.com\": 1,\n\t\"hhsq.net\": 1,\n\t\"hhsyjzs.com\": 1,\n\t\"hhtravel.com\": 1,\n\t\"hhzfgjj.com\": 1,\n\t\"hhzhaoming.com\": 1,\n\t\"hi-chic.com\": 1,\n\t\"hi-pda.com\": 1,\n\t\"hi0574.com\": 1,\n\t\"hi1718.com\": 1,\n\t\"hi2000.com\": 1,\n\t\"hi772.com\": 1,\n\t\"hiao.com\": 1,\n\t\"hiapk.com\": 1,\n\t\"hicang.com\": 1,\n\t\"hichina.com\": 1,\n\t\"hicloud.com\": 1,\n\t\"hicosmo.com\": 1,\n\t\"hiesquire.com\": 1,\n\t\"hifabric.com\": 1,\n\t\"hifidiy.net\": 1,\n\t\"hihandan.com\": 1,\n\t\"hihey.com\": 1,\n\t\"hihifang.com\": 1,\n\t\"hijiangxi.com\": 1,\n\t\"hikvision.com\": 1,\n\t\"hilizi.com\": 1,\n\t\"hippoanimation.com\": 1,\n\t\"hiputian.com\": 1,\n\t\"hirede.com\": 1,\n\t\"hisense.com\": 1,\n\t\"hisensehitachi.com\": 1,\n\t\"hisupplier.com\": 1,\n\t\"hitao.com\": 1,\n\t\"hivjob.com\": 1,\n\t\"hiwemeet.com\": 1,\n\t\"hiyeyou.com\": 1,\n\t\"hiyouth.net\": 1,\n\t\"hjcun.com\": 1,\n\t\"hjeee.com\": 1,\n\t\"hjenglish.com\": 1,\n\t\"hjglo.com\": 1,\n\t\"hjplw.com\": 1,\n\t\"hjyc.com\": 1,\n\t\"hjyqw.com\": 1,\n\t\"hk3318.net\": 1,\n\t\"hk5.cc\": 1,\n\t\"hkcts.com\": 1,\n\t\"hkdq.net\": 1,\n\t\"hke123.com\": 1,\n\t\"hkhgo.com\": 1,\n\t\"hkproperty.com\": 1,\n\t\"hktdc-img.com\": 1,\n\t\"hktdc.com\": 1,\n\t\"hkwb.net\": 1,\n\t\"hkxfb.com\": 1,\n\t\"hl1314.com\": 1,\n\t\"hlass.com\": 1,\n\t\"hlcxy.com\": 1,\n\t\"hldbtv.com\": 1,\n\t\"hldgajjzd.com\": 1,\n\t\"hldnews.com\": 1,\n\t\"hldtop.com\": 1,\n\t\"hledu.net\": 1,\n\t\"hlfdw.com\": 1,\n\t\"hlhkys.com\": 1,\n\t\"hlj.net\": 1,\n\t\"hljcq.com\": 1,\n\t\"hlje.net\": 1,\n\t\"hljforest.com\": 1,\n\t\"hljgh.org\": 1,\n\t\"hljgsl.org\": 1,\n\t\"hljgwy.net\": 1,\n\t\"hljjjb.com\": 1,\n\t\"hljnw.com\": 1,\n\t\"hljpost.com\": 1,\n\t\"hljradio.com\": 1,\n\t\"hljsunwu.com\": 1,\n\t\"hljtcp.com\": 1,\n\t\"hljtv.com\": 1,\n\t\"hljys.org\": 1,\n\t\"hlnmg.org\": 1,\n\t\"hlsports.net\": 1,\n\t\"hltm.cc\": 1,\n\t\"hlwan.net\": 1,\n\t\"hlx99.com\": 1,\n\t\"hly.com\": 1,\n\t\"hlybar.com\": 1,\n\t\"hlzpw.com\": 1,\n\t\"hm-3223.net\": 1,\n\t\"hm5988.com\": 1,\n\t\"hm8848.com\": 1,\n\t\"hme01.com\": 1,\n\t\"hmecw.com\": 1,\n\t\"hmeonline.com\": 1,\n\t\"hminvestment.com\": 1,\n\t\"hmqqw.com\": 1,\n\t\"hmting.com\": 1,\n\t\"hmw365.com\": 1,\n\t\"hmxuexiao.com\": 1,\n\t\"hn-cts.com\": 1,\n\t\"hn-pc.com\": 1,\n\t\"hn12333.com\": 1,\n\t\"hn481.com\": 1,\n\t\"hn873.com\": 1,\n\t\"hnaee.com\": 1,\n\t\"hnagri.com\": 1,\n\t\"hnair.com\": 1,\n\t\"hnbaihua.com\": 1,\n\t\"hnbys.net\": 1,\n\t\"hnccgc.com\": 1,\n\t\"hnccpm.com\": 1,\n\t\"hnchj.com\": 1,\n\t\"hncic.net\": 1,\n\t\"hncjh.com\": 1,\n\t\"hncoop.com\": 1,\n\t\"hncoop.net\": 1,\n\t\"hncost.com\": 1,\n\t\"hncourt.org\": 1,\n\t\"hncsmjzs.com\": 1,\n\t\"hnctw.com\": 1,\n\t\"hncyfc.com\": 1,\n\t\"hndeaho.com\": 1,\n\t\"hndiancheng.com\": 1,\n\t\"hnditu.com\": 1,\n\t\"hndpf.org\": 1,\n\t\"hnemap.com\": 1,\n\t\"hner.net\": 1,\n\t\"hnflcp.com\": 1,\n\t\"hnfz.net\": 1,\n\t\"hngawj.net\": 1,\n\t\"hngcc.org\": 1,\n\t\"hngfjy.com\": 1,\n\t\"hngh.org\": 1,\n\t\"hnghw.com\": 1,\n\t\"hngjj.net\": 1,\n\t\"hngwy.org\": 1,\n\t\"hnh.cc\": 1,\n\t\"hnhjq.com\": 1,\n\t\"hnhjw.com\": 1,\n\t\"hnhm.com\": 1,\n\t\"hnhyit.com\": 1,\n\t\"hnhyrc.com\": 1,\n\t\"hnid.org\": 1,\n\t\"hnielts.com\": 1,\n\t\"hnjbwh.com\": 1,\n\t\"hnjkw.net\": 1,\n\t\"hnjol.com\": 1,\n\t\"hnjuran.com\": 1,\n\t\"hnkjonline.net\": 1,\n\t\"hnldgz.com\": 1,\n\t\"hnloushi.com\": 1,\n\t\"hnltw.com\": 1,\n\t\"hnltw.net\": 1,\n\t\"hnluxury.com\": 1,\n\t\"hnlyxww.com\": 1,\n\t\"hnlzw.net\": 1,\n\t\"hnmama.com\": 1,\n\t\"hnmsw.com\": 1,\n\t\"hnnews.cc\": 1,\n\t\"hnol.net\": 1,\n\t\"hnpi.net\": 1,\n\t\"hnpost.com\": 1,\n\t\"hnprec.com\": 1,\n\t\"hnqcw.com\": 1,\n\t\"hnql.org\": 1,\n\t\"hnqyfw.com\": 1,\n\t\"hnradio.com\": 1,\n\t\"hnrcsc.com\": 1,\n\t\"hnrczpw.com\": 1,\n\t\"hnrencai.com\": 1,\n\t\"hnrsks.com\": 1,\n\t\"hnrxw.com\": 1,\n\t\"hnshangwu.com\": 1,\n\t\"hnshj.com\": 1,\n\t\"hnsjxn.com\": 1,\n\t\"hnskl.net\": 1,\n\t\"hnskl.org\": 1,\n\t\"hnsncb.com\": 1,\n\t\"hnsnnews.com\": 1,\n\t\"hnsss.com\": 1,\n\t\"hnswtzb.org\": 1,\n\t\"hnsyfdc.com\": 1,\n\t\"hnszgh.org\": 1,\n\t\"hntf8.com\": 1,\n\t\"hnticai.com\": 1,\n\t\"hntuanfun.com\": 1,\n\t\"hntv.tv\": 1,\n\t\"hnw.net\": 1,\n\t\"hnwenming.com\": 1,\n\t\"hnwmw.com\": 1,\n\t\"hnxhnews.com\": 1,\n\t\"hnxnews.com\": 1,\n\t\"hnxwcb.com\": 1,\n\t\"hnxxw666.com\": 1,\n\t\"hnxxwzz.com\": 1,\n\t\"hnxysteel.com\": 1,\n\t\"hnyc-edu.com\": 1,\n\t\"hnyyjg.com\": 1,\n\t\"hnzfgjj.com\": 1,\n\t\"hnzhaoshan.com\": 1,\n\t\"hnzhzz.com\": 1,\n\t\"hnzmedia.com\": 1,\n\t\"hnzpsc.com\": 1,\n\t\"hnzresearch.com\": 1,\n\t\"hnzz.cc\": 1,\n\t\"hogesoft.com\": 1,\n\t\"hold168.com\": 1,\n\t\"holdhr.com\": 1,\n\t\"home0538.com\": 1,\n\t\"home310.com\": 1,\n\t\"home77.com\": 1,\n\t\"home898.com\": 1,\n\t\"homedf.com\": 1,\n\t\"homedg.com\": 1,\n\t\"homeinns.com\": 1,\n\t\"homekoo.com\": 1,\n\t\"homekoocdn.com\": 1,\n\t\"hometex114.com\": 1,\n\t\"hometexjoin.com\": 1,\n\t\"hometexnet.com\": 1,\n\t\"hometextilesworld.com\": 1,\n\t\"homeun.com\": 1,\n\t\"hommk.com\": 1,\n\t\"homomo.net\": 1,\n\t\"hongbeijob.com\": 1,\n\t\"hongen.com\": 1,\n\t\"hongfen.org\": 1,\n\t\"honggushi.com\": 1,\n\t\"honghuowang.com\": 1,\n\t\"hongjingedu.com\": 1,\n\t\"hongniang.com\": 1,\n\t\"hongshu.com\": 1,\n\t\"hongsui.biz\": 1,\n\t\"hongtu.com\": 1,\n\t\"hongxiantuan.com\": 1,\n\t\"hongxiu.com\": 1,\n\t\"hongyaxuan.com\": 1,\n\t\"hongyuanqh.com\": 1,\n\t\"hongze.net\": 1,\n\t\"hongzerc.com\": 1,\n\t\"hongzhoukan.com\": 1,\n\t\"hookbase.com\": 1,\n\t\"hoolo.tv\": 1,\n\t\"hoopchina.com\": 1,\n\t\"hopebook.net\": 1,\n\t\"horise.com\": 1,\n\t\"horsehr.com\": 1,\n\t\"hosap.com\": 1,\n\t\"hoseaworldwide.org\": 1,\n\t\"hostelcn.com\": 1,\n\t\"hot178.com\": 1,\n\t\"hot78.com\": 1,\n\t\"hotds.com\": 1,\n\t\"hotel525.com\": 1,\n\t\"hotfcw.com\": 1,\n\t\"hotsales.net\": 1,\n\t\"hottui.com\": 1,\n\t\"houdao.com\": 1,\n\t\"house0596.com\": 1,\n\t\"house10000.com\": 1,\n\t\"house365.com\": 1,\n\t\"house577.com\": 1,\n\t\"housecq.com\": 1,\n\t\"househy.com\": 1,\n\t\"houseqilu.com\": 1,\n\t\"houseyw.com\": 1,\n\t\"housoo.com\": 1,\n\t\"houxue.com\": 1,\n\t\"howbuy.com\": 1,\n\t\"howjia.com\": 1,\n\t\"howzhi.com\": 1,\n\t\"hozhai.com\": 1,\n\t\"hpimg.com\": 1,\n\t\"hq-ielts.com\": 1,\n\t\"hq-mart.com\": 1,\n\t\"hq0451.com\": 1,\n\t\"hq0564.com\": 1,\n\t\"hq1h.com\": 1,\n\t\"hq88.com\": 1,\n\t\"hqbcdn.com\": 1,\n\t\"hqbpc.com\": 1,\n\t\"hqclass.com\": 1,\n\t\"hqcr.com\": 1,\n\t\"hqdly.com\": 1,\n\t\"hqeast.org\": 1,\n\t\"hqenorth.com\": 1,\n\t\"hqepay.com\": 1,\n\t\"hqew.com\": 1,\n\t\"hqew.net\": 1,\n\t\"hqewimg.com\": 1,\n\t\"hqfb.org\": 1,\n\t\"hqhot.com\": 1,\n\t\"hqhqw.com\": 1,\n\t\"hqiye.com\": 1,\n\t\"hqjhw.com\": 1,\n\t\"hqlednews.com\": 1,\n\t\"hqlsw.com\": 1,\n\t\"hqmianshou.com\": 1,\n\t\"hqpcb.com\": 1,\n\t\"hqqrc.com\": 1,\n\t\"hqshouji.com\": 1,\n\t\"hqwy.com\": 1,\n\t\"hqxly.com\": 1,\n\t\"hqyj.com\": 1,\n\t\"hqyj.net\": 1,\n\t\"hqyl.com\": 1,\n\t\"hqyyrc.com\": 1,\n\t\"hr-sd.com\": 1,\n\t\"hr025.com\": 1,\n\t\"hr0571.com\": 1,\n\t\"hr0596.com\": 1,\n\t\"hr0660.com\": 1,\n\t\"hr0662.com\": 1,\n\t\"hr0751.com\": 1,\n\t\"hr0752.com\": 1,\n\t\"hr0753.com\": 1,\n\t\"hr0755.com\": 1,\n\t\"hr0759.com\": 1,\n\t\"hr0766.com\": 1,\n\t\"hr0773.com\": 1,\n\t\"hr0898.com\": 1,\n\t\"hr1000.com\": 1,\n\t\"hr1288.com\": 1,\n\t\"hr1898.com\": 1,\n\t\"hr191.com\": 1,\n\t\"hr33.com\": 1,\n\t\"hr369.com\": 1,\n\t\"hr5156.com\": 1,\n\t\"hr762.com\": 1,\n\t\"hr763.com\": 1,\n\t\"hr777.com\": 1,\n\t\"hr951.com\": 1,\n\t\"hrbanlv.com\": 1,\n\t\"hrbar.com\": 1,\n\t\"hrbdqqz.com\": 1,\n\t\"hrbit.com\": 1,\n\t\"hrbmama.com\": 1,\n\t\"hrbtv.net\": 1,\n\t\"hrcshp.org\": 1,\n\t\"hrhorse.com\": 1,\n\t\"hrloo.com\": 1,\n\t\"hroot.com\": 1,\n\t\"hrpin.com\": 1,\n\t\"hrrcw.com\": 1,\n\t\"hrtx.com\": 1,\n\t\"hrwind.com\": 1,\n\t\"hs818.com\": 1,\n\t\"hscbbs.org\": 1,\n\t\"hscbw.com\": 1,\n\t\"hsdcw.com\": 1,\n\t\"hsds.cc\": 1,\n\t\"hse365.net\": 1,\n\t\"hsgjj.com\": 1,\n\t\"hsgjjw.com\": 1,\n\t\"hshan.com\": 1,\n\t\"hsjas.com\": 1,\n\t\"hsjjob.com\": 1,\n\t\"hsnewsn.com\": 1,\n\t\"hsrcw.com\": 1,\n\t\"hssdzw.com\": 1,\n\t\"hsspw.com\": 1,\n\t\"hstmc.com\": 1,\n\t\"ht516.com\": 1,\n\t\"ht9000.com\": 1,\n\t\"htattoo.com\": 1,\n\t\"htbenet.net\": 1,\n\t\"htcbbs.net\": 1,\n\t\"htderen.com\": 1,\n\t\"hteacher.net\": 1,\n\t\"htexam.com\": 1,\n\t\"htexam.net\": 1,\n\t\"htfutures.com\": 1,\n\t\"hthxm.com\": 1,\n\t\"htinns.com\": 1,\n\t\"htmianshi.com\": 1,\n\t\"html5cn.org\": 1,\n\t\"htscw.com\": 1,\n\t\"htsec.com\": 1,\n\t\"httpcn.com\": 1,\n\t\"htwx.net\": 1,\n\t\"hty.cc\": 1,\n\t\"htyuqi.com\": 1,\n\t\"htzx.org\": 1,\n\t\"hua.com\": 1,\n\t\"huaban.com\": 1,\n\t\"huabangfushi.com\": 1,\n\t\"huabei1.com\": 1,\n\t\"huabian.com\": 1,\n\t\"huacolor.com\": 1,\n\t\"huadachem.com\": 1,\n\t\"huadaofengye.com\": 1,\n\t\"huagu.com\": 1,\n\t\"huahuanet.com\": 1,\n\t\"huai.cc\": 1,\n\t\"huaian.com\": 1,\n\t\"huaian100.com\": 1,\n\t\"huaibei163.com\": 1,\n\t\"huaibin88.com\": 1,\n\t\"huaibinrc.com\": 1,\n\t\"huaihai.tv\": 1,\n\t\"huainet.com\": 1,\n\t\"huaiyangnews.com\": 1,\n\t\"huajian-al.com\": 1,\n\t\"huajianvalve.com\": 1,\n\t\"huajiashengdian.com\": 1,\n\t\"huajin100.com\": 1,\n\t\"huajx.com\": 1,\n\t\"hualang001.com\": 1,\n\t\"hualang123.com\": 1,\n\t\"hualangnet.com\": 1,\n\t\"hualepx.com\": 1,\n\t\"hualongxiang.com\": 1,\n\t\"huamanche.com\": 1,\n\t\"huamanlou.com\": 1,\n\t\"huameibb.com\": 1,\n\t\"huanancoal.com\": 1,\n\t\"huanbao.com\": 1,\n\t\"huanbaoshi.com\": 1,\n\t\"huanbaoyc.com\": 1,\n\t\"huanbohaijob.com\": 1,\n\t\"huangchuan.co\": 1,\n\t\"huanghelou.cc\": 1,\n\t\"huangjinlian.com\": 1,\n\t\"huangru.com\": 1,\n\t\"huangshanzjy.com\": 1,\n\t\"huangye88.com\": 1,\n\t\"huanhr.com\": 1,\n\t\"huanpingshi.com\": 1,\n\t\"huanqiu.com\": 1,\n\t\"huanqiu6.com\": 1,\n\t\"huanqiuw.com\": 1,\n\t\"huantai.net\": 1,\n\t\"huantu.com\": 1,\n\t\"huanwen.com\": 1,\n\t\"huanxia.com\": 1,\n\t\"huapaojob.com\": 1,\n\t\"huapinwang.com\": 1,\n\t\"huaqiphoto.com\": 1,\n\t\"huash.com\": 1,\n\t\"huashen-edu.com\": 1,\n\t\"huatai-serv.com\": 1,\n\t\"huatu.com\": 1,\n\t\"huaue.com\": 1,\n\t\"huawei.com\": 1,\n\t\"huaxcy.com\": 1,\n\t\"huaxi100.com\": 1,\n\t\"huaxia.com\": 1,\n\t\"huaxiaci.com\": 1,\n\t\"huaxiajiayuan.net\": 1,\n\t\"huaxirc.com\": 1,\n\t\"huaxunnsw.com\": 1,\n\t\"huayansi.com\": 1,\n\t\"huayiming.com\": 1,\n\t\"huayin520.com\": 1,\n\t\"huayuan520.com\": 1,\n\t\"huayuejob.com\": 1,\n\t\"huazhile.com\": 1,\n\t\"huazhongh.com\": 1,\n\t\"huazhu.com\": 1,\n\t\"hubai.com\": 1,\n\t\"hubeibbs.net\": 1,\n\t\"hubeici.com\": 1,\n\t\"hubeirc.com\": 1,\n\t\"hudieji.com\": 1,\n\t\"hudong.cc\": 1,\n\t\"hudong.com\": 1,\n\t\"hudou.com\": 1,\n\t\"huedu.net\": 1,\n\t\"hugao8.com\": 1,\n\t\"hugd.com\": 1,\n\t\"hughjs.com\": 1,\n\t\"hui800.com\": 1,\n\t\"huibo.com\": 1,\n\t\"huibojob.com\": 1,\n\t\"huiche.com\": 1,\n\t\"huichexiang.net\": 1,\n\t\"huidafx.com\": 1,\n\t\"huigezi.org\": 1,\n\t\"huijucn.com\": 1,\n\t\"huilai88.com\": 1,\n\t\"huilan.com\": 1,\n\t\"huimaiche.com\": 1,\n\t\"huimingjia.com\": 1,\n\t\"huiminrencai.com\": 1,\n\t\"huishangbao.com\": 1,\n\t\"huishi365.com\": 1,\n\t\"huishoushang.com\": 1,\n\t\"huitouyu.com\": 1,\n\t\"huitu.com\": 1,\n\t\"huixiaodai.com\": 1,\n\t\"huixinyt.com\": 1,\n\t\"huiyanw.com\": 1,\n\t\"huiyi8.com\": 1,\n\t\"huiyitang.net\": 1,\n\t\"huizhuang.com\": 1,\n\t\"hujiang.com\": 1,\n\t\"huliankm.com\": 1,\n\t\"huluxia.com\": 1,\n\t\"humanrights-china.org\": 1,\n\t\"humen.com\": 1,\n\t\"hunanedu.net\": 1,\n\t\"hunanfy.com\": 1,\n\t\"hunanheicha.com\": 1,\n\t\"hunanpta.com\": 1,\n\t\"hunantv.com\": 1,\n\t\"hunanzhibo.com\": 1,\n\t\"hunau.net\": 1,\n\t\"hunchunnet.com\": 1,\n\t\"hundsun.com\": 1,\n\t\"hunlibar.com\": 1,\n\t\"hunlimama.com\": 1,\n\t\"hunt007.com\": 1,\n\t\"hunter5156.com\": 1,\n\t\"hunuo.com\": 1,\n\t\"huobar.com\": 1,\n\t\"huobi.com\": 1,\n\t\"huoche.com\": 1,\n\t\"huoche.net\": 1,\n\t\"huochepiao.com\": 1,\n\t\"huochepiao.net\": 1,\n\t\"huochepu.com\": 1,\n\t\"huocheshikebiao.org\": 1,\n\t\"huodaixiamen.com\": 1,\n\t\"huodongjia.com\": 1,\n\t\"huodongxing.com\": 1,\n\t\"huohou.com\": 1,\n\t\"huohu123.com\": 1,\n\t\"huolawan.com\": 1,\n\t\"huolibaobao.com\": 1,\n\t\"huolinhe.com\": 1,\n\t\"huopao.com\": 1,\n\t\"huoqiuw.com\": 1,\n\t\"huore8.com\": 1,\n\t\"huoshan.cc\": 1,\n\t\"huoshannews.com\": 1,\n\t\"huowan.com\": 1,\n\t\"huoxue.com\": 1,\n\t\"huoying.com\": 1,\n\t\"huoyuanzhijia.com\": 1,\n\t\"hupu.com\": 1,\n\t\"hushi114.com\": 1,\n\t\"hushiwin.com\": 1,\n\t\"hustonline.net\": 1,\n\t\"huuyaa.com\": 1,\n\t\"huway.com\": 1,\n\t\"huweishen.com\": 1,\n\t\"huxiu.com\": 1,\n\t\"huzs.com\": 1,\n\t\"hvac8.com\": 1,\n\t\"hvacrex.com\": 1,\n\t\"hvtong.com\": 1,\n\t\"hw5d.com\": 1,\n\t\"hwit.net\": 1,\n\t\"hwtop.com\": 1,\n\t\"hwtrip.com\": 1,\n\t\"hx-car.com\": 1,\n\t\"hx-my.com\": 1,\n\t\"hx-my.net\": 1,\n\t\"hx116.com\": 1,\n\t\"hx2car.com\": 1,\n\t\"hx95.com\": 1,\n\t\"hxcdn.net\": 1,\n\t\"hxcjdb.com\": 1,\n\t\"hxck.net\": 1,\n\t\"hxdatian.com\": 1,\n\t\"hxdctz.com\": 1,\n\t\"hxdsrc.com\": 1,\n\t\"hxen.com\": 1,\n\t\"hxfilm.com\": 1,\n\t\"hxfzjxw.com\": 1,\n\t\"hxfzzx.com\": 1,\n\t\"hxlsw.com\": 1,\n\t\"hxlt.org\": 1,\n\t\"hxpxw.net\": 1,\n\t\"hxqw.com\": 1,\n\t\"hxrc.com\": 1,\n\t\"hxrcsc.com\": 1,\n\t\"hxsd.com\": 1,\n\t\"hxsh365.com\": 1,\n\t\"hxsx.net\": 1,\n\t\"hxtk.com\": 1,\n\t\"hxtxt.com\": 1,\n\t\"hxyjw.com\": 1,\n\t\"hxzb.com\": 1,\n\t\"hxzg.net\": 1,\n\t\"hy-steel.com\": 1,\n\t\"hy123.com\": 1,\n\t\"hy163.com\": 1,\n\t\"hy588.com\": 1,\n\t\"hydcd.com\": 1,\n\t\"hydst.com\": 1,\n\t\"hyedu.com\": 1,\n\t\"hyfss.com\": 1,\n\t\"hyjwz.com\": 1,\n\t\"hyjzw.com\": 1,\n\t\"hyk123.net\": 1,\n\t\"hylrc.com\": 1,\n\t\"hynews.net\": 1,\n\t\"hynews.org\": 1,\n\t\"hyqcw.com\": 1,\n\t\"hysbw.com\": 1,\n\t\"hysgjj.com\": 1,\n\t\"hyw.cc\": 1,\n\t\"hywit.com\": 1,\n\t\"hyxnews.com\": 1,\n\t\"hyxw.net\": 1,\n\t\"hyxww.com\": 1,\n\t\"hyxyw.org\": 1,\n\t\"hyzfgjj.com\": 1,\n\t\"hz-delixi.com\": 1,\n\t\"hz321.com\": 1,\n\t\"hz66.com\": 1,\n\t\"hzabl.org\": 1,\n\t\"hzaee.com\": 1,\n\t\"hzagro.com\": 1,\n\t\"hzairport.com\": 1,\n\t\"hzbj.com\": 1,\n\t\"hzbx.com\": 1,\n\t\"hzcbd.com\": 1,\n\t\"hzcnb.com\": 1,\n\t\"hzcnc.com\": 1,\n\t\"hzcoop.com\": 1,\n\t\"hzcy.com\": 1,\n\t\"hzdaikuan8.com\": 1,\n\t\"hzedu.cc\": 1,\n\t\"hzedu.net\": 1,\n\t\"hzeduask.com\": 1,\n\t\"hzfc.cc\": 1,\n\t\"hzfgj.com\": 1,\n\t\"hzgh.org\": 1,\n\t\"hzgjj.com\": 1,\n\t\"hzgz.cc\": 1,\n\t\"hzhanbo.com\": 1,\n\t\"hzhike.com\": 1,\n\t\"hzhqyy.com\": 1,\n\t\"hzhr.com\": 1,\n\t\"hzhuman.com\": 1,\n\t\"hzhuti.com\": 1,\n\t\"hzins.com\": 1,\n\t\"hzjs56.com\": 1,\n\t\"hzjzwy.com\": 1,\n\t\"hzland.com\": 1,\n\t\"hzlib.net\": 1,\n\t\"hzlongre.com\": 1,\n\t\"hzlp.com\": 1,\n\t\"hzlsg.com\": 1,\n\t\"hzlw.com\": 1,\n\t\"hzmama.net\": 1,\n\t\"hzmnls.com\": 1,\n\t\"hzmotv.com\": 1,\n\t\"hznet.tv\": 1,\n\t\"hznews.com\": 1,\n\t\"hznzcn.com\": 1,\n\t\"hzpzs.net\": 1,\n\t\"hzqiuxue.com\": 1,\n\t\"hzqx.com\": 1,\n\t\"hzrc.com\": 1,\n\t\"hzrcw.cc\": 1,\n\t\"hzshw.com\": 1,\n\t\"hzsjgpx.com\": 1,\n\t\"hzsk.com\": 1,\n\t\"hzsmesc.com\": 1,\n\t\"hztarena.com\": 1,\n\t\"hztarena.net\": 1,\n\t\"hztarena.org\": 1,\n\t\"hztbc.com\": 1,\n\t\"hztd56.com\": 1,\n\t\"hzti.com\": 1,\n\t\"hzvivi.com\": 1,\n\t\"hzwestlake.com\": 1,\n\t\"hzwmw.com\": 1,\n\t\"hzwxq.com\": 1,\n\t\"hzzays.com\": 1,\n\t\"hzzp.cc\": 1,\n\t\"hzzp.com\": 1,\n\t\"i-css.com\": 1,\n\t\"i-jiaxing.com\": 1,\n\t\"i-jjj.com\": 1,\n\t\"i027.com\": 1,\n\t\"i0898.org\": 1,\n\t\"i1758.com\": 1,\n\t\"i1766.com\": 1,\n\t\"i2ya.com\": 1,\n\t\"i3kan.com\": 1,\n\t\"i3v.cc\": 1,\n\t\"i52088.com\": 1,\n\t\"i8i8i8.com\": 1,\n\t\"iapps.im\": 1,\n\t\"iask.com\": 1,\n\t\"ib-china.com\": 1,\n\t\"ibamaol.com\": 1,\n\t\"ibangkf.com\": 1,\n\t\"ibayue.com\": 1,\n\t\"ibbdd.com\": 1,\n\t\"ibeifeng.com\": 1,\n\t\"ibgbuy.com\": 1,\n\t\"ibicn.com\": 1,\n\t\"ibm.com\": 1,\n\t\"ibooyi.com\": 1,\n\t\"ibspecial.org\": 1,\n\t\"ic37.com\": 1,\n\t\"ic72.com\": 1,\n\t\"ic98.com\": 1,\n\t\"icafe8.com\": 1,\n\t\"icaile.com\": 1,\n\t\"icandata.com\": 1,\n\t\"icarzoo.com\": 1,\n\t\"icbuy.com\": 1,\n\t\"iceasy.com\": 1,\n\t\"icgoo.net\": 1,\n\t\"ichacha.net\": 1,\n\t\"ichengyang.com\": 1,\n\t\"ichengzi.com\": 1,\n\t\"iciba.com\": 1,\n\t\"icifit.com\": 1,\n\t\"icis-china.com\": 1,\n\t\"icjyw.com\": 1,\n\t\"icntv.tv\": 1,\n\t\"icoat.cc\": 1,\n\t\"icourse163.org\": 1,\n\t\"icpcw.com\": 1,\n\t\"icpdf.com\": 1,\n\t\"icson.com\": 1,\n\t\"ictsiyantai.com\": 1,\n\t\"icxo.com\": 1,\n\t\"icycn.com\": 1,\n\t\"icycn.net\": 1,\n\t\"idacn.org\": 1,\n\t\"idailyapp.com\": 1,\n\t\"idarling.cc\": 1,\n\t\"idc123.com\": 1,\n\t\"idchz.com\": 1,\n\t\"idcps.com\": 1,\n\t\"idcquan.com\": 1,\n\t\"idcspy.com\": 1,\n\t\"idcun.com\": 1,\n\t\"idea-tops.com\": 1,\n\t\"ideahn.com\": 1,\n\t\"idealroyal.com\": 1,\n\t\"idealshanghai.com\": 1,\n\t\"ideatom.com\": 1,\n\t\"idfay.com\": 1,\n\t\"idler-et.com\": 1,\n\t\"idongzhi.com\": 1,\n\t\"idouu.com\": 1,\n\t\"idqqimg.com\": 1,\n\t\"idting.com\": 1,\n\t\"idtui.com\": 1,\n\t\"iduola.com\": 1,\n\t\"ieche.com\": 1,\n\t\"iecity.com\": 1,\n\t\"iecnews.com\": 1,\n\t\"iecworld.com\": 1,\n\t\"ieduw.com\": 1,\n\t\"iefang.com\": 1,\n\t\"ieforex.com\": 1,\n\t\"iejob.net\": 1,\n\t\"ielts999.com\": 1,\n\t\"iepz.cc\": 1,\n\t\"ifahao.com\": 1,\n\t\"ifanr.com\": 1,\n\t\"ifasion.net\": 1,\n\t\"ifcwr.com\": 1,\n\t\"ifeng-nb.com\": 1,\n\t\"ifeng.com\": 1,\n\t\"ifenghui.com\": 1,\n\t\"ifengimg.com\": 1,\n\t\"ifensi.com\": 1,\n\t\"iflying.com\": 1,\n\t\"igao7.com\": 1,\n\t\"igaosheng.com\": 1,\n\t\"igeak.com\": 1,\n\t\"igo180.com\": 1,\n\t\"igoldhk.com\": 1,\n\t\"igome.com\": 1,\n\t\"igoodgame.com\": 1,\n\t\"igoodsc.com\": 1,\n\t\"iguso.com\": 1,\n\t\"ihaiyan.com\": 1,\n\t\"ihanhua.com\": 1,\n\t\"ihaveu.com\": 1,\n\t\"ihaveu.net\": 1,\n\t\"ihddy.com\": 1,\n\t\"iheima.com\": 1,\n\t\"ihome361.com\": 1,\n\t\"ihome927.com\": 1,\n\t\"ihome99.com\": 1,\n\t\"ihomeshow.com\": 1,\n\t\"ihoome.com\": 1,\n\t\"ihualun.com\": 1,\n\t\"ihuatong.com\": 1,\n\t\"ihuikou.net\": 1,\n\t\"ihuqu.com\": 1,\n\t\"ii010.com\": 1,\n\t\"iianews.com\": 1,\n\t\"iidns.com\": 1,\n\t\"iiiyooo.com\": 1,\n\t\"iincn.net\": 1,\n\t\"iiqee.com\": 1,\n\t\"iitpx.com\": 1,\n\t\"iiyi.com\": 1,\n\t\"iiyibbs.com\": 1,\n\t\"ijia360.com\": 1,\n\t\"ijiatv.com\": 1,\n\t\"ijie.com\": 1,\n\t\"ijinbu.com\": 1,\n\t\"ijinbu.net\": 1,\n\t\"ijinhuo.com\": 1,\n\t\"ijinshan.com\": 1,\n\t\"ijjnews.com\": 1,\n\t\"ijstv.com\": 1,\n\t\"ijxjj.com\": 1,\n\t\"ik123.com\": 1,\n\t\"ik3cloud.com\": 1,\n\t\"ikaka.com\": 1,\n\t\"ikanchai.com\": 1,\n\t\"ikandian.com\": 1,\n\t\"ikang.com\": 1,\n\t\"ikbqn.com\": 1,\n\t\"ikuyy.com\": 1,\n\t\"ilangwen.com\": 1,\n\t\"ilaw360.com\": 1,\n\t\"ileehoo.com\": 1,\n\t\"ilelu.com\": 1,\n\t\"ilighting.net\": 1,\n\t\"ilinyi.net\": 1,\n\t\"ilishi.com\": 1,\n\t\"iliyu.com\": 1,\n\t\"ilongre.com\": 1,\n\t\"ilongterm.com\": 1,\n\t\"ilope-expo.com\": 1,\n\t\"iloveyouxi.com\": 1,\n\t\"ilovezuan.com\": 1,\n\t\"iluoshen.com\": 1,\n\t\"ilvping.com\": 1,\n\t\"im286.com\": 1,\n\t\"im533.com\": 1,\n\t\"images-amazon.com\": 1,\n\t\"imaifang.com\": 1,\n\t\"imaijia.com\": 1,\n\t\"imakecollege.com\": 1,\n\t\"imanhua.com\": 1,\n\t\"imanshi.com\": 1,\n\t\"imcdma.com\": 1,\n\t\"imcoal.com\": 1,\n\t\"imdiandao.com\": 1,\n\t\"ime19.com\": 1,\n\t\"imeimama.com\": 1,\n\t\"imfirewall.com\": 1,\n\t\"img-space.com\": 1,\n\t\"img.cctvpic.com\": 1,\n\t\"img168.net\": 1,\n\t\"img4399.com\": 1,\n\t\"imglafaso.com\": 1,\n\t\"imglefeng.com\": 1,\n\t\"imgo.tv\": 1,\n\t\"imgshangman.com\": 1,\n\t\"imgshao123.net\": 1,\n\t\"immivip.com\": 1,\n\t\"imooc.com\": 1,\n\t\"imop.com\": 1,\n\t\"imosi.com\": 1,\n\t\"imp3.net\": 1,\n\t\"importfood.net\": 1,\n\t\"importfoodfair.com\": 1,\n\t\"imqq.com\": 1,\n\t\"imrworldwide.com\": 1,\n\t\"in-en.com\": 1,\n\t\"in189.com\": 1,\n\t\"inabr.com\": 1,\n\t\"inanle.com\": 1,\n\t\"inc.gs\": 1,\n\t\"incensechina.com\": 1,\n\t\"inchedao.com\": 1,\n\t\"indexedu.com\": 1,\n\t\"indexedu.net\": 1,\n\t\"indiacn.com\": 1,\n\t\"indiums.com\": 1,\n\t\"industrycome.com\": 1,\n\t\"inengyuan.com\": 1,\n\t\"inewoffice.com\": 1,\n\t\"infineon-power-rf.org\": 1,\n\t\"infineonic.org\": 1,\n\t\"infohc.com\": 1,\n\t\"infolz.com\": 1,\n\t\"infomorning.com\": 1,\n\t\"infzm.com\": 1,\n\t\"ing2ing.com\": 1,\n\t\"ingping.com\": 1,\n\t\"inhe.com\": 1,\n\t\"inhe.net\": 1,\n\t\"inimc.com\": 1,\n\t\"inlishui.com\": 1,\n\t\"inmachine.com\": 1,\n\t\"inmes.net\": 1,\n\t\"innyo.com\": 1,\n\t\"inshion.com\": 1,\n\t\"insightwar.com\": 1,\n\t\"insigmaedu.com\": 1,\n\t\"insooo.com\": 1,\n\t\"inspur.com\": 1,\n\t\"intel.com\": 1,\n\t\"interfranchise.org\": 1,\n\t\"intertid.com\": 1,\n\t\"intple.com\": 1,\n\t\"intsst.org\": 1,\n\t\"inuobi.com\": 1,\n\t\"investjilin.com\": 1,\n\t\"investteda.org\": 1,\n\t\"invitemedia.com\": 1,\n\t\"inwayedu.com\": 1,\n\t\"ios114.com\": 1,\n\t\"iot-online.com\": 1,\n\t\"iot1bbs.com\": 1,\n\t\"ip138.com\": 1,\n\t\"ipa001.com\": 1,\n\t\"ipanda.com\": 1,\n\t\"ipchina.com\": 1,\n\t\"iphonetrain.com\": 1,\n\t\"ipinyou.com\": 1,\n\t\"ipmph.com\": 1,\n\t\"ipr123.com\": 1,\n\t\"ipugou.com\": 1,\n\t\"iqilu.com\": 1,\n\t\"iqinbao.com\": 1,\n\t\"iqingdao.com\": 1,\n\t\"iqingren.com\": 1,\n\t\"iqiyi.com\": 1,\n\t\"iresearchad.com\": 1,\n\t\"iresearchchina.com\": 1,\n\t\"irs01.com\": 1,\n\t\"irs01.net\": 1,\n\t\"irs09.com\": 1,\n\t\"is686.com\": 1,\n\t\"is97.com\": 1,\n\t\"isanmen.com\": 1,\n\t\"ishaanxi.com\": 1,\n\t\"ishang.net\": 1,\n\t\"ishangman.com\": 1,\n\t\"ishangtoutiao.com\": 1,\n\t\"ishegou.com\": 1,\n\t\"ishenyou.com\": 1,\n\t\"ishibk.com\": 1,\n\t\"ishowx.com\": 1,\n\t\"isoucai.com\": 1,\n\t\"issns.com\": 1,\n\t\"istartrade.com\": 1,\n\t\"istreamsche.com\": 1,\n\t\"isuzupowertrain.com\": 1,\n\t\"isying.com\": 1,\n\t\"it-home.org\": 1,\n\t\"it168.com\": 1,\n\t\"it224.com\": 1,\n\t\"itangyuan.com\": 1,\n\t\"itaozhu.com\": 1,\n\t\"itavcn.com\": 1,\n\t\"itbulo.com\": 1,\n\t\"itceo.com\": 1,\n\t\"itchaguan.com\": 1,\n\t\"itcpn.net\": 1,\n\t\"itdcw.com\": 1,\n\t\"iterduo.com\": 1,\n\t\"iteye.com\": 1,\n\t\"itfeed.com\": 1,\n\t\"itheima.com\": 1,\n\t\"ithlj.com\": 1,\n\t\"ithome.com\": 1,\n\t\"ithov.com\": 1,\n\t\"itiexue.net\": 1,\n\t\"itingwa.com\": 1,\n\t\"itjds.com\": 1,\n\t\"itjol.com\": 1,\n\t\"itjutou.com\": 1,\n\t\"itjuzi.com\": 1,\n\t\"itmale.com\": 1,\n\t\"itmop.com\": 1,\n\t\"itnxs.com\": 1,\n\t\"itokit.com\": 1,\n\t\"itools.hk\": 1,\n\t\"itouchchina.com\": 1,\n\t\"itouxian.com\": 1,\n\t\"itpar.com\": 1,\n\t\"itppi.org\": 1,\n\t\"itpub.net\": 1,\n\t\"itravelqq.com\": 1,\n\t\"itshai.com\": 1,\n\t\"itsofun.com\": 1,\n\t\"itsogo.net\": 1,\n\t\"itt168.com\": 1,\n\t\"ittribalwo.com\": 1,\n\t\"itudou.cc\": 1,\n\t\"itugo.com\": 1,\n\t\"itunion.net\": 1,\n\t\"itwaibaow.com\": 1,\n\t\"itxinwen.com\": 1,\n\t\"itxsw.com\": 1,\n\t\"iuicity.com\": 1,\n\t\"iuvision.com\": 1,\n\t\"ivcode.net\": 1,\n\t\"ivsky.com\": 1,\n\t\"iwebchoice.com\": 1,\n\t\"iweek.ly\": 1,\n\t\"iwencai.com\": 1,\n\t\"iwhr.com\": 1,\n\t\"iwjia.com\": 1,\n\t\"iwms.net\": 1,\n\t\"iwpai.com\": 1,\n\t\"iwugu.com\": 1,\n\t\"iwuyin.com\": 1,\n\t\"ixbren.net\": 1,\n\t\"ixiapu.com\": 1,\n\t\"ixiawan.com\": 1,\n\t\"ixinda.com\": 1,\n\t\"ixinwei.com\": 1,\n\t\"ixiumei.com\": 1,\n\t\"ixpub.net\": 1,\n\t\"ixumu.com\": 1,\n\t\"ixxss.net\": 1,\n\t\"ixywy.com\": 1,\n\t\"iyaxin.com\": 1,\n\t\"iyaya.com\": 1,\n\t\"iyd.cc\": 1,\n\t\"iyingji.com\": 1,\n\t\"iyiou.com\": 1,\n\t\"iyiyun.com\": 1,\n\t\"iyouman.com\": 1,\n\t\"iyxwzx.com\": 1,\n\t\"iyzx.com\": 1,\n\t\"izaojiao.com\": 1,\n\t\"izhikang.com\": 1,\n\t\"izhuanr.com\": 1,\n\t\"izhufu.com\": 1,\n\t\"izhukao.com\": 1,\n\t\"izhuti.com\": 1,\n\t\"izizhucan.com\": 1,\n\t\"izmzg.com\": 1,\n\t\"j1.com\": 1,\n\t\"j3bbs.com\": 1,\n\t\"ja168.net\": 1,\n\t\"jaadee.com\": 1,\n\t\"jaifang.com\": 1,\n\t\"james520.com\": 1,\n\t\"jandan.net\": 1,\n\t\"jandou.com\": 1,\n\t\"janxing.com\": 1,\n\t\"jarczpw.com\": 1,\n\t\"jarencai.com\": 1,\n\t\"jarhu.com\": 1,\n\t\"jb51.net\": 1,\n\t\"jbdown.com\": 1,\n\t\"jbedu.net\": 1,\n\t\"jbzyw.com\": 1,\n\t\"jc0553.com\": 1,\n\t\"jc35.com\": 1,\n\t\"jc85.com\": 1,\n\t\"jc88.net\": 1,\n\t\"jcbao.com\": 1,\n\t\"jcbctv.com\": 1,\n\t\"jcc1.com\": 1,\n\t\"jccoal.com\": 1,\n\t\"jcjj365.com\": 1,\n\t\"jcjy.net\": 1,\n\t\"jcjzs.com\": 1,\n\t\"jcku.com\": 1,\n\t\"jclzw.com\": 1,\n\t\"jcmeh.com\": 1,\n\t\"jcnews.org\": 1,\n\t\"jcoal.com\": 1,\n\t\"jcqcw.com\": 1,\n\t\"jcqzw.com\": 1,\n\t\"jcrb.com\": 1,\n\t\"jcrcw.com\": 1,\n\t\"jcshi.com\": 1,\n\t\"jctrans.com\": 1,\n\t\"jctrans.net\": 1,\n\t\"jcwcn.com\": 1,\n\t\"jcwuhan.com\": 1,\n\t\"jcz001.com\": 1,\n\t\"jczao.com\": 1,\n\t\"jczxb.com\": 1,\n\t\"jd-88.com\": 1,\n\t\"jd-bbs.com\": 1,\n\t\"jd-cg.com\": 1,\n\t\"jd.com\": 1,\n\t\"jd100.com\": 1,\n\t\"jd37.com\": 1,\n\t\"jdbaw.com\": 1,\n\t\"jdbbx.com\": 1,\n\t\"jdcheng.com\": 1,\n\t\"jdcjsr.com\": 1,\n\t\"jdedu.net\": 1,\n\t\"jdemba.com\": 1,\n\t\"jdfhq.com\": 1,\n\t\"jdgod.com\": 1,\n\t\"jdjob88.com\": 1,\n\t\"jdlhw.com\": 1,\n\t\"jdnettv.com\": 1,\n\t\"jdunion.com\": 1,\n\t\"jdw001.com\": 1,\n\t\"jdwx.info\": 1,\n\t\"jdwxs.com\": 1,\n\t\"jdxfw.com\": 1,\n\t\"jdxzwzx.com\": 1,\n\t\"jdygchina.com\": 1,\n\t\"jdyou.com\": 1,\n\t\"jdypgxw.com\": 1,\n\t\"jdysw.com\": 1,\n\t\"jdzj.com\": 1,\n\t\"jdzldtc.com\": 1,\n\t\"jdzol.com\": 1,\n\t\"jdzol.net\": 1,\n\t\"jdzrcw.com\": 1,\n\t\"jdzrczpw.com\": 1,\n\t\"jdzrencai.com\": 1,\n\t\"jdzx365.com\": 1,\n\t\"jdzycw.com\": 1,\n\t\"jeixun.com\": 1,\n\t\"jelsty.com\": 1,\n\t\"jemcc.net\": 1,\n\t\"jerei.com\": 1,\n\t\"jewelchina.com\": 1,\n\t\"jf1898.com\": 1,\n\t\"jfdaily.com\": 1,\n\t\"jfdown.com\": 1,\n\t\"jfgphzs.com\": 1,\n\t\"jfinfo.com\": 1,\n\t\"jfjmw.net\": 1,\n\t\"jfm668.com\": 1,\n\t\"jfpfw.com\": 1,\n\t\"jfrcw.com\": 1,\n\t\"jgaoxiao.com\": 1,\n\t\"jgfcw.com\": 1,\n\t\"jgjob88.com\": 1,\n\t\"jgscta.com\": 1,\n\t\"jgsdaily.com\": 1,\n\t\"jgstudy.com\": 1,\n\t\"jgzx.cc\": 1,\n\t\"jh597.com\": 1,\n\t\"jha118.com\": 1,\n\t\"jhcxl.com\": 1,\n\t\"jhdxyy.com\": 1,\n\t\"jhjyj.net\": 1,\n\t\"jhnyxx.com\": 1,\n\t\"jhpx.com\": 1,\n\t\"jhqzw.com\": 1,\n\t\"jhrcsc.com\": 1,\n\t\"jhrcw.com\": 1,\n\t\"jhsssy.com\": 1,\n\t\"jhtong.net\": 1,\n\t\"jhusd.com\": 1,\n\t\"jhwcw.com\": 1,\n\t\"jhxww.net\": 1,\n\t\"jhyc.com\": 1,\n\t\"jhzwed.com\": 1,\n\t\"jia.com\": 1,\n\t\"jia123.com\": 1,\n\t\"jia360.com\": 1,\n\t\"jia400.com\": 1,\n\t\"jia99.com\": 1,\n\t\"jiabk.com\": 1,\n\t\"jiaboohui.com\": 1,\n\t\"jiadefu168.com\": 1,\n\t\"jiadinglife.net\": 1,\n\t\"jiadingtgw.com\": 1,\n\t\"jiafang168.com\": 1,\n\t\"jiafangyun.com\": 1,\n\t\"jiageshi.com\": 1,\n\t\"jiahesj.com\": 1,\n\t\"jiahesuji.com\": 1,\n\t\"jiaji.com\": 1,\n\t\"jiajiakt.com\": 1,\n\t\"jiajiao114.com\": 1,\n\t\"jiajiao400.com\": 1,\n\t\"jiajiaoban.com\": 1,\n\t\"jiajiashuo.com\": 1,\n\t\"jiaju.cc\": 1,\n\t\"jiaju.com\": 1,\n\t\"jiajumi.com\": 1,\n\t\"jiajuol.com\": 1,\n\t\"jiajushichang.net\": 1,\n\t\"jialaxin.cc\": 1,\n\t\"jialiphoto.com\": 1,\n\t\"jiamei188.com\": 1,\n\t\"jiameng.com\": 1,\n\t\"jiameng001.com\": 1,\n\t\"jiameng8.com\": 1,\n\t\"jiamisoft.com\": 1,\n\t\"jian123.com\": 1,\n\t\"jianbihua.org\": 1,\n\t\"jiancai.com\": 1,\n\t\"jiancai789.com\": 1,\n\t\"jiancaimy.com\": 1,\n\t\"jiancaizhanhui.com\": 1,\n\t\"jiandanwan.com\": 1,\n\t\"jiane86.com\": 1,\n\t\"jianfc.com\": 1,\n\t\"jianfei.com\": 1,\n\t\"jiang7.com\": 1,\n\t\"jiangduoduo.com\": 1,\n\t\"jiangdurencai.com\": 1,\n\t\"jiangduw.com\": 1,\n\t\"jianghairc.com\": 1,\n\t\"jianghuaipump.com\": 1,\n\t\"jianghuairc.com\": 1,\n\t\"jiangjiama.com\": 1,\n\t\"jiangshi.com\": 1,\n\t\"jiangshi.org\": 1,\n\t\"jiangshi99.com\": 1,\n\t\"jiangsuedu.net\": 1,\n\t\"jiangsurc.com\": 1,\n\t\"jiangxia.cc\": 1,\n\t\"jiangxilvyou.com\": 1,\n\t\"jianhucheng.com\": 1,\n\t\"jianhuw.com\": 1,\n\t\"jianianle.com\": 1,\n\t\"jianianya.com\": 1,\n\t\"jiankang.com\": 1,\n\t\"jiankang.org\": 1,\n\t\"jiankangcloud.com\": 1,\n\t\"jiankangzu.com\": 1,\n\t\"jianke.com\": 1,\n\t\"jianke.net\": 1,\n\t\"jiankongbao.com\": 1,\n\t\"jianli-sky.com\": 1,\n\t\"jianlip.com\": 1,\n\t\"jianlishi.com\": 1,\n\t\"jianpu8.com\": 1,\n\t\"jianshe001.com\": 1,\n\t\"jianshe99.com\": 1,\n\t\"jianshen78.com\": 1,\n\t\"jianshen8.com\": 1,\n\t\"jianshu.com\": 1,\n\t\"jianshu.io\": 1,\n\t\"jianso.com\": 1,\n\t\"jiansuji.org\": 1,\n\t\"jianyangjob.com\": 1,\n\t\"jianzaoshi.cc\": 1,\n\t\"jianzhi8.com\": 1,\n\t\"jianzhiba.com\": 1,\n\t\"jianzhiba.net\": 1,\n\t\"jianzhijia.com\": 1,\n\t\"jianzhiku.com\": 1,\n\t\"jianzhujia.net\": 1,\n\t\"jiao15.com\": 1,\n\t\"jiaodamba.com\": 1,\n\t\"jiaodong.net\": 1,\n\t\"jiaomai.com\": 1,\n\t\"jiaoshizhaopin.net\": 1,\n\t\"jiaoshizige.org\": 1,\n\t\"jiaoshui.net\": 1,\n\t\"jiaotanqihuo.com\": 1,\n\t\"jiaotou.org\": 1,\n\t\"jiaowolf.com\": 1,\n\t\"jiaoyanshi.com\": 1,\n\t\"jiaoyimao.com\": 1,\n\t\"jiaquan360.com\": 1,\n\t\"jiasule.com\": 1,\n\t\"jiathis.com\": 1,\n\t\"jiatx.com\": 1,\n\t\"jiayejob.com\": 1,\n\t\"jiayuan.com\": 1,\n\t\"jiazhao.com\": 1,\n\t\"jiazhaokaoshi.com\": 1,\n\t\"jiazhuang.com\": 1,\n\t\"jiazhuang6.com\": 1,\n\t\"jiazhuoedu.com\": 1,\n\t\"jibi.net\": 1,\n\t\"jibingnet.com\": 1,\n\t\"jichuang.net\": 1,\n\t\"jichumei.com\": 1,\n\t\"jide123.cc\": 1,\n\t\"jide123.com\": 1,\n\t\"jideli.com\": 1,\n\t\"jidi.com\": 1,\n\t\"jidian365.com\": 1,\n\t\"jidianmy.com\": 1,\n\t\"jidongrc.com\": 1,\n\t\"jiduola.com\": 1,\n\t\"jie08.com\": 1,\n\t\"jiebohui.com\": 1,\n\t\"jiegoushi.com\": 1,\n\t\"jiemeng8.com\": 1,\n\t\"jiepang.com\": 1,\n\t\"jieshoujob.com\": 1,\n\t\"jietusoft.com\": 1,\n\t\"jieu.com\": 1,\n\t\"jieyue.net\": 1,\n\t\"jif419.com\": 1,\n\t\"jifang360.com\": 1,\n\t\"jihai-edu.com\": 1,\n\t\"jiiaa.com\": 1,\n\t\"jijidi.com\": 1,\n\t\"jijinzige.com\": 1,\n\t\"jike.com\": 1,\n\t\"jikeu.com\": 1,\n\t\"jikexueyuan.com\": 1,\n\t\"jilaibao.com\": 1,\n\t\"jilaidai.com\": 1,\n\t\"jilinfc.com\": 1,\n\t\"jilinzhaopin.com\": 1,\n\t\"jiluai.com\": 1,\n\t\"jimi168.com\": 1,\n\t\"jimifashion.com\": 1,\n\t\"jimischool.com\": 1,\n\t\"jimonet.cc\": 1,\n\t\"jimubox.com\": 1,\n\t\"jimuyou.com\": 1,\n\t\"jin14.com\": 1,\n\t\"jinandazhaxie.com\": 1,\n\t\"jinandpf.org\": 1,\n\t\"jinanjuyi.com\": 1,\n\t\"jinbangqm.com\": 1,\n\t\"jinbaobeiqiming.com\": 1,\n\t\"jinbaonet.com\": 1,\n\t\"jinbifun.com\": 1,\n\t\"jincai1688.com\": 1,\n\t\"jindidq.com\": 1,\n\t\"jinduoduo.net\": 1,\n\t\"jinfengtv.com\": 1,\n\t\"jinfuren100.com\": 1,\n\t\"jinfuzi.com\": 1,\n\t\"jing.fm\": 1,\n\t\"jingchurc.com\": 1,\n\t\"jingdake.com\": 1,\n\t\"jingdianwan.com\": 1,\n\t\"jinghou.net\": 1,\n\t\"jingjia.org\": 1,\n\t\"jingjishi.com\": 1,\n\t\"jingnei.net\": 1,\n\t\"jingoffice.com\": 1,\n\t\"jingpinke.com\": 1,\n\t\"jingshu.org\": 1,\n\t\"jingwei.com\": 1,\n\t\"jingyangchun.com\": 1,\n\t\"jingyouxi.com\": 1,\n\t\"jingzheng.com\": 1,\n\t\"jingzhengu.com\": 1,\n\t\"jinhantang.com\": 1,\n\t\"jinhejs.com\": 1,\n\t\"jinhou.com\": 1,\n\t\"jinhuang.com\": 1,\n\t\"jinhuatv.com\": 1,\n\t\"jinhurc.com\": 1,\n\t\"jining.com\": 1,\n\t\"jinkaixiang.com\": 1,\n\t\"jinkaoedu.com\": 1,\n\t\"jinku.com\": 1,\n\t\"jinlaoshi.com\": 1,\n\t\"jinliheng365.com\": 1,\n\t\"jinlingdry.com\": 1,\n\t\"jinliyu.cc\": 1,\n\t\"jinmajia.com\": 1,\n\t\"jinmalvyou.com\": 1,\n\t\"jinmenrc.com\": 1,\n\t\"jinnong.cc\": 1,\n\t\"jinpu.com\": 1,\n\t\"jinqijian.com\": 1,\n\t\"jinqijian188.com\": 1,\n\t\"jinriningxiang.com\": 1,\n\t\"jinriwujin.com\": 1,\n\t\"jinrongren.net\": 1,\n\t\"jinshangrc.com\": 1,\n\t\"jinshi.tv\": 1,\n\t\"jinshuju.net\": 1,\n\t\"jintanwang.com\": 1,\n\t\"jinti.com\": 1,\n\t\"jintoutiao.com\": 1,\n\t\"jintuedu.com\": 1,\n\t\"jinxiexpo.com\": 1,\n\t\"jinxing-beer.com\": 1,\n\t\"jinxun.cc\": 1,\n\t\"jinying365.com\": 1,\n\t\"jinyingjie.com\": 1,\n\t\"jinyuzd.cc\": 1,\n\t\"jinzhe.com\": 1,\n\t\"jiqimao.com\": 1,\n\t\"jishigou.net\": 1,\n\t\"jisibar.com\": 1,\n\t\"jisuxz.com\": 1,\n\t\"jita520.com\": 1,\n\t\"jitongtianxia.com\": 1,\n\t\"jiu30.com\": 1,\n\t\"jiu6.com\": 1,\n\t\"jiudianzhaopin.com\": 1,\n\t\"jiugang.com\": 1,\n\t\"jiukuaiwu.com\": 1,\n\t\"jiukuaiyou.com\": 1,\n\t\"jius.net\": 1,\n\t\"jiushanglianmeng.com\": 1,\n\t\"jiusi.net\": 1,\n\t\"jiutw.com\": 1,\n\t\"jiuxian.com\": 1,\n\t\"jiuxinxiushen.com\": 1,\n\t\"jiuyan.info\": 1,\n\t\"jiuyaoyouxi.com\": 1,\n\t\"jiuyezhinan.com\": 1,\n\t\"jiuzhai.com\": 1,\n\t\"jiuzi.cc\": 1,\n\t\"jiwu.com\": 1,\n\t\"jixielianmeng.com\": 1,\n\t\"jixiezhan.org\": 1,\n\t\"jixinet.com\": 1,\n\t\"jiyidc.com\": 1,\n\t\"jiyifa.com\": 1,\n\t\"jiyili.net\": 1,\n\t\"jiyou.tv\": 1,\n\t\"jiyun360.com\": 1,\n\t\"jj0833.com\": 1,\n\t\"jj20.com\": 1,\n\t\"jj59.com\": 1,\n\t\"jj597.com\": 1,\n\t\"jj831.com\": 1,\n\t\"jjbang.com\": 1,\n\t\"jjcdn.com\": 1,\n\t\"jjckb.com\": 1,\n\t\"jjedu.com\": 1,\n\t\"jjhh.com\": 1,\n\t\"jjhxhb.com\": 1,\n\t\"jjjg.co\": 1,\n\t\"jjjgame.com\": 1,\n\t\"jjkk.org\": 1,\n\t\"jjlg.net\": 1,\n\t\"jjlxpz.com\": 1,\n\t\"jjmmw.com\": 1,\n\t\"jjqcw.com\": 1,\n\t\"jjrcsc.com\": 1,\n\t\"jjsedu.org\": 1,\n\t\"jjshipin.com\": 1,\n\t\"jjsrcw.com\": 1,\n\t\"jjvcd.com\": 1,\n\t\"jjwxc.net\": 1,\n\t\"jjxj.org\": 1,\n\t\"jjxxk.com\": 1,\n\t\"jjyf.net\": 1,\n\t\"jjzg365.com\": 1,\n\t\"jjzyzg.com\": 1,\n\t\"jk0760.com\": 1,\n\t\"jk51.com\": 1,\n\t\"jk520.net\": 1,\n\t\"jkbcw.com\": 1,\n\t\"jkdb.cc\": 1,\n\t\"jkdown.com\": 1,\n\t\"jkimg.net\": 1,\n\t\"jklxl.com\": 1,\n\t\"jkmeishi.com\": 1,\n\t\"jkpj.com\": 1,\n\t\"jkshhao.com\": 1,\n\t\"jkshw.com\": 1,\n\t\"jkxdt.com\": 1,\n\t\"jkypx.com\": 1,\n\t\"jl315.org\": 1,\n\t\"jl54.org\": 1,\n\t\"jladi.com\": 1,\n\t\"jlbaobao.com\": 1,\n\t\"jlccpit.com\": 1,\n\t\"jlds110.com\": 1,\n\t\"jlhighway.com\": 1,\n\t\"jlhtcm.com\": 1,\n\t\"jlhxjt.com\": 1,\n\t\"jlit365.com\": 1,\n\t\"jljgdj.org\": 1,\n\t\"jljob88.com\": 1,\n\t\"jljsw.com\": 1,\n\t\"jlkangda.com\": 1,\n\t\"jllib.com\": 1,\n\t\"jllnzz.com\": 1,\n\t\"jlmhk.com\": 1,\n\t\"jlnku.com\": 1,\n\t\"jlonline.com\": 1,\n\t\"jlqf.net\": 1,\n\t\"jlredcross.org\": 1,\n\t\"jlsgjt.com\": 1,\n\t\"jlshumei.com\": 1,\n\t\"jlsmm.com\": 1,\n\t\"jlstnet.net\": 1,\n\t\"jlszyy.com\": 1,\n\t\"jlthj.com\": 1,\n\t\"jltiet.net\": 1,\n\t\"jly001.com\": 1,\n\t\"jlzf.org\": 1,\n\t\"jlzkb.com\": 1,\n\t\"jlzp.org\": 1,\n\t\"jlzx.cc\": 1,\n\t\"jm-tour.com\": 1,\n\t\"jm84.com\": 1,\n\t\"jmbao.com\": 1,\n\t\"jmdedu.com\": 1,\n\t\"jmgczj.com\": 1,\n\t\"jmkszx.com\": 1,\n\t\"jmmoxiang.com\": 1,\n\t\"jmrb.com\": 1,\n\t\"jmsdpzx.com\": 1,\n\t\"jmsjs.com\": 1,\n\t\"jmstatic.com\": 1,\n\t\"jmwjm.com\": 1,\n\t\"jmy-99.com\": 1,\n\t\"jmymh.com\": 1,\n\t\"jn001.com\": 1,\n\t\"jn025.com\": 1,\n\t\"jnbaobao.com\": 1,\n\t\"jnbenteng.com\": 1,\n\t\"jnbjemba.com\": 1,\n\t\"jnesc.com\": 1,\n\t\"jngrain.com\": 1,\n\t\"jnhouse.com\": 1,\n\t\"jnjj.com\": 1,\n\t\"jnjpw.org\": 1,\n\t\"jnlc.com\": 1,\n\t\"jnlongre.com\": 1,\n\t\"jnmaimai.com\": 1,\n\t\"jnmama.com\": 1,\n\t\"jnmc.com\": 1,\n\t\"jnnc.com\": 1,\n\t\"jnnews.tv\": 1,\n\t\"jnopfun.com\": 1,\n\t\"jnqb.com\": 1,\n\t\"jnqche.com\": 1,\n\t\"jnqpsh.com\": 1,\n\t\"jnticai.com\": 1,\n\t\"jnwmw.com\": 1,\n\t\"jnxindemei.com\": 1,\n\t\"jnzdgk.com\": 1,\n\t\"jnzs.com\": 1,\n\t\"jnzx.cc\": 1,\n\t\"job-sky.com\": 1,\n\t\"job0519.com\": 1,\n\t\"job0523.com\": 1,\n\t\"job0575.net\": 1,\n\t\"job0663.com\": 1,\n\t\"job0722.com\": 1,\n\t\"job0728.com\": 1,\n\t\"job0768.com\": 1,\n\t\"job0795.com\": 1,\n\t\"job0917.com\": 1,\n\t\"job100.com\": 1,\n\t\"job10000.com\": 1,\n\t\"job1001.com\": 1,\n\t\"job120.com\": 1,\n\t\"job128.com\": 1,\n\t\"job1288.com\": 1,\n\t\"job13580.com\": 1,\n\t\"job168.com\": 1,\n\t\"job1688.com\": 1,\n\t\"job2003.com\": 1,\n\t\"job222.com\": 1,\n\t\"job2299.com\": 1,\n\t\"job250.com\": 1,\n\t\"job256.com\": 1,\n\t\"job263.com\": 1,\n\t\"job335.com\": 1,\n\t\"job36.com\": 1,\n\t\"job369.com\": 1,\n\t\"job51.com\": 1,\n\t\"job5156.com\": 1,\n\t\"job5199.com\": 1,\n\t\"job5588.com\": 1,\n\t\"job592.com\": 1,\n\t\"job5959.com\": 1,\n\t\"job598.com\": 1,\n\t\"job616.com\": 1,\n\t\"job8001.com\": 1,\n\t\"job868.com\": 1,\n\t\"job910.com\": 1,\n\t\"job9151.com\": 1,\n\t\"job916.com\": 1,\n\t\"job98.com\": 1,\n\t\"job9981.com\": 1,\n\t\"job9988.com\": 1,\n\t\"jobbaidu.com\": 1,\n\t\"jobbw.com\": 1,\n\t\"jobcn.com\": 1,\n\t\"jobdogame.com\": 1,\n\t\"jobeast.com\": 1,\n\t\"jobems.com\": 1,\n\t\"jobgojob.com\": 1,\n\t\"jobhb.com\": 1,\n\t\"jobinhe.net\": 1,\n\t\"jobjm.com\": 1,\n\t\"joblc.com\": 1,\n\t\"jobpin.com\": 1,\n\t\"jobtong.com\": 1,\n\t\"jobui.com\": 1,\n\t\"jobuy.com\": 1,\n\t\"jobxa.com\": 1,\n\t\"jobyc.com\": 1,\n\t\"jobyp.com\": 1,\n\t\"johnsdier.com\": 1,\n\t\"joingoo.com\": 1,\n\t\"joke01.com\": 1,\n\t\"jollaqiyu.com\": 1,\n\t\"joobbe.com\": 1,\n\t\"joqoo.com\": 1,\n\t\"joroow.com\": 1,\n\t\"jovision.com\": 1,\n\t\"jowinpen.com\": 1,\n\t\"jowong.com\": 1,\n\t\"joy-kids.com\": 1,\n\t\"joy1996.com\": 1,\n\t\"joy76.com\": 1,\n\t\"joyboom.com\": 1,\n\t\"joyes.com\": 1,\n\t\"joyme.com\": 1,\n\t\"joyo.com\": 1,\n\t\"joystech.com\": 1,\n\t\"joytrav.com\": 1,\n\t\"joyyang.com\": 1,\n\t\"jpmanga.com\": 1,\n\t\"jpskb.com\": 1,\n\t\"jpwind.com\": 1,\n\t\"jpxm.com\": 1,\n\t\"jq-school.com\": 1,\n\t\"jqbyby.com\": 1,\n\t\"jqcn.net\": 1,\n\t\"jqw.com\": 1,\n\t\"jqzy.com\": 1,\n\t\"jr18.com\": 1,\n\t\"jrhcw.com\": 1,\n\t\"jrj.com\": 1,\n\t\"jrjob.net\": 1,\n\t\"jrlhmm.com\": 1,\n\t\"jrrsq.com\": 1,\n\t\"jrshx.com\": 1,\n\t\"jrsmw.com\": 1,\n\t\"jrxjnet.com\": 1,\n\t\"jryaw.com\": 1,\n\t\"jryghq.com\": 1,\n\t\"js-jinhua.com\": 1,\n\t\"js-lottery.com\": 1,\n\t\"js11183.com\": 1,\n\t\"js118114.com\": 1,\n\t\"js178.com\": 1,\n\t\"js811.com\": 1,\n\t\"js95598.com\": 1,\n\t\"jsbc.com\": 1,\n\t\"jsche.net\": 1,\n\t\"jscj.com\": 1,\n\t\"jscsedu.com\": 1,\n\t\"jscseea.com\": 1,\n\t\"jsenews.com\": 1,\n\t\"jsfxh.org\": 1,\n\t\"jsgc168.com\": 1,\n\t\"jsgh.org\": 1,\n\t\"jsgx.net\": 1,\n\t\"jsinfo.net\": 1,\n\t\"jsjcsmart.com\": 1,\n\t\"jsjjgt.com\": 1,\n\t\"jsjjx.com\": 1,\n\t\"jsjob360.com\": 1,\n\t\"jskanghui.com\": 1,\n\t\"jslegal.com\": 1,\n\t\"jslit.com\": 1,\n\t\"jslottery.com\": 1,\n\t\"jsls.org\": 1,\n\t\"jsly001.com\": 1,\n\t\"jsmsg.com\": 1,\n\t\"jsmuseum.com\": 1,\n\t\"jsnotary.org\": 1,\n\t\"jsnxs.com\": 1,\n\t\"jsose.com\": 1,\n\t\"jsqdqc.com\": 1,\n\t\"jsqnews.com\": 1,\n\t\"jsqq.net\": 1,\n\t\"jsqw.com\": 1,\n\t\"jsrcsc.com\": 1,\n\t\"jsrencai.net\": 1,\n\t\"jsrsrc.com\": 1,\n\t\"jsrugao.com\": 1,\n\t\"jsrxny.com\": 1,\n\t\"jsrzx.com\": 1,\n\t\"jssdfz.com\": 1,\n\t\"jssyxx.com\": 1,\n\t\"jstianzhuo.com\": 1,\n\t\"jstour.com\": 1,\n\t\"jstv.com\": 1,\n\t\"jswdj.com\": 1,\n\t\"jswmw.com\": 1,\n\t\"jsxhrcw.com\": 1,\n\t\"jsxiaoguo.com\": 1,\n\t\"jsxlkaoyan.com\": 1,\n\t\"jsxlmed.com\": 1,\n\t\"jsxmws.com\": 1,\n\t\"jsyjkz.com\": 1,\n\t\"jsyks.com\": 1,\n\t\"jsymyjs.com\": 1,\n\t\"jsyrzz.com\": 1,\n\t\"jszf.org\": 1,\n\t\"jszg.com\": 1,\n\t\"jszhaobiao.com\": 1,\n\t\"jszksw.com\": 1,\n\t\"jszsf.org\": 1,\n\t\"jszzc.net\": 1,\n\t\"jt111.com\": 1,\n\t\"jt2car.com\": 1,\n\t\"jtbole.com\": 1,\n\t\"jtdaw.com\": 1,\n\t\"jthysh.com\": 1,\n\t\"jtimg.com\": 1,\n\t\"jtjiaoyu.com\": 1,\n\t\"jtkyw.com\": 1,\n\t\"jtlhome.com\": 1,\n\t\"jtrmyy.com\": 1,\n\t\"jtsz.com\": 1,\n\t\"jtxxol.com\": 1,\n\t\"jtyou.com\": 1,\n\t\"jtyx.net\": 1,\n\t\"juanlaoda.com\": 1,\n\t\"juanpi.com\": 1,\n\t\"jubaopu.com\": 1,\n\t\"juben108.com\": 1,\n\t\"juboyue.com\": 1,\n\t\"juchang.com\": 1,\n\t\"juchangan.com\": 1,\n\t\"juesheng.com\": 1,\n\t\"juexiang.com\": 1,\n\t\"juexing.net\": 1,\n\t\"jufanli.com\": 1,\n\t\"jufengshang.com\": 1,\n\t\"juhaof.com\": 1,\n\t\"juhuisuan.com\": 1,\n\t\"juimg.com\": 1,\n\t\"jujiaonet.com\": 1,\n\t\"jule365.com\": 1,\n\t\"julu.net\": 1,\n\t\"juluren.com\": 1,\n\t\"jumei.com\": 1,\n\t\"jumin.cc\": 1,\n\t\"juming.com\": 1,\n\t\"jumingwang.com\": 1,\n\t\"junbaike.com\": 1,\n\t\"junjiajob.com\": 1,\n\t\"junph.com\": 1,\n\t\"junpin360.com\": 1,\n\t\"junpinhui.com\": 1,\n\t\"junpinzhi.com\": 1,\n\t\"junqing123.com\": 1,\n\t\"junqing7.com\": 1,\n\t\"junshi.com\": 1,\n\t\"junshi81.com\": 1,\n\t\"junshier.com\": 1,\n\t\"junshijia.com\": 1,\n\t\"junshijidi.com\": 1,\n\t\"junshiqu.com\": 1,\n\t\"junshis.com\": 1,\n\t\"junshishu.com\": 1,\n\t\"junzilian.com\": 1,\n\t\"junzimen.com\": 1,\n\t\"juooo.com\": 1,\n\t\"jupai.net\": 1,\n\t\"juren.com\": 1,\n\t\"jurenxly.com\": 1,\n\t\"jutuw.com\": 1,\n\t\"juwai.com\": 1,\n\t\"juxia.com\": 1,\n\t\"juxian.com\": 1,\n\t\"juxianxinxi.com\": 1,\n\t\"juyanoo.com\": 1,\n\t\"juyaohe.com\": 1,\n\t\"juyouedu.com\": 1,\n\t\"juyouqu.com\": 1,\n\t\"juyouxi.com\": 1,\n\t\"jvrong.com\": 1,\n\t\"jwedit.net\": 1,\n\t\"jwgou.com\": 1,\n\t\"jx09.com\": 1,\n\t\"jx612345.com\": 1,\n\t\"jxaas.com\": 1,\n\t\"jxagri.net\": 1,\n\t\"jxbsl.com\": 1,\n\t\"jxc-tea.com\": 1,\n\t\"jxcc.com\": 1,\n\t\"jxcnt.com\": 1,\n\t\"jxcq.org\": 1,\n\t\"jxdasz.com\": 1,\n\t\"jxdcw.com\": 1,\n\t\"jxdiguo.com\": 1,\n\t\"jxdyf.com\": 1,\n\t\"jxedt.com\": 1,\n\t\"jxepw.com\": 1,\n\t\"jxfc365.com\": 1,\n\t\"jxfcbbs.com\": 1,\n\t\"jxfdcrcw.com\": 1,\n\t\"jxfxgy.com\": 1,\n\t\"jxgdw.com\": 1,\n\t\"jxgjj.com\": 1,\n\t\"jxgydc.com\": 1,\n\t\"jxgztv.com\": 1,\n\t\"jxhcw.com\": 1,\n\t\"jxhi.com\": 1,\n\t\"jxhjxy.com\": 1,\n\t\"jxhyhr.com\": 1,\n\t\"jxiz.com\": 1,\n\t\"jxjatv.com\": 1,\n\t\"jxjiuye.com\": 1,\n\t\"jxjj.net\": 1,\n\t\"jxjjw.net\": 1,\n\t\"jxjls.com\": 1,\n\t\"jxjsxx.net\": 1,\n\t\"jxjw.net\": 1,\n\t\"jxjyfw.com\": 1,\n\t\"jxjyzy.com\": 1,\n\t\"jxjz5.com\": 1,\n\t\"jxjzrcw.com\": 1,\n\t\"jxkp.com\": 1,\n\t\"jxlib.com\": 1,\n\t\"jxloufang.com\": 1,\n\t\"jxltw.com\": 1,\n\t\"jxpf.com\": 1,\n\t\"jxpp.com\": 1,\n\t\"jxpta.com\": 1,\n\t\"jxqcw.com\": 1,\n\t\"jxqiche.com\": 1,\n\t\"jxqx.net\": 1,\n\t\"jxrcw.com\": 1,\n\t\"jxrczp.com\": 1,\n\t\"jxrencai.com\": 1,\n\t\"jxrsrc.com\": 1,\n\t\"jxrtv.com\": 1,\n\t\"jxsalt.com\": 1,\n\t\"jxsfybjy.com\": 1,\n\t\"jxshangyou.com\": 1,\n\t\"jxsrhy.com\": 1,\n\t\"jxtourism.com\": 1,\n\t\"jxtyzx.org\": 1,\n\t\"jxtzw.com\": 1,\n\t\"jxxdf.com\": 1,\n\t\"jxxyrc.com\": 1,\n\t\"jxycw.com\": 1,\n\t\"jxydt.com\": 1,\n\t\"jxysnews.com\": 1,\n\t\"jxzcw.com\": 1,\n\t\"jxzp.cc\": 1,\n\t\"jxzpw.net\": 1,\n\t\"jxzwgk.com\": 1,\n\t\"jxzyx.com\": 1,\n\t\"jy163.net\": 1,\n\t\"jy1898.com\": 1,\n\t\"jy1898.net\": 1,\n\t\"jy391.com\": 1,\n\t\"jy70.com\": 1,\n\t\"jyh007.com\": 1,\n\t\"jyhbxg.com\": 1,\n\t\"jyimg.com\": 1,\n\t\"jyinns.com\": 1,\n\t\"jyjsbxg.com\": 1,\n\t\"jynews.net\": 1,\n\t\"jyqcw.com\": 1,\n\t\"jyrcjl.com\": 1,\n\t\"jyrck.com\": 1,\n\t\"jyrcw.net\": 1,\n\t\"jyrw.net\": 1,\n\t\"jysns.com\": 1,\n\t\"jysq.net\": 1,\n\t\"jytongmen.com\": 1,\n\t\"jytuangou.com\": 1,\n\t\"jyxyyxy.com\": 1,\n\t\"jyyuan.com\": 1,\n\t\"jz.cc\": 1,\n\t\"jz100.com\": 1,\n\t\"jz265.com\": 1,\n\t\"jz51.com\": 1,\n\t\"jz5u.com\": 1,\n\t\"jz6.cc\": 1,\n\t\"jz6.com\": 1,\n\t\"jzaq.com\": 1,\n\t\"jzb.com\": 1,\n\t\"jzcn.net\": 1,\n\t\"jzcool.com\": 1,\n\t\"jzfcol.com\": 1,\n\t\"jzgcoal.com\": 1,\n\t\"jzggcm.com\": 1,\n\t\"jzgjj.com\": 1,\n\t\"jzgxlm.com\": 1,\n\t\"jzhchr.com\": 1,\n\t\"jzhongmu.com\": 1,\n\t\"jzjob007.com\": 1,\n\t\"jzjzxh.com\": 1,\n\t\"jznj.com\": 1,\n\t\"jzpt.com\": 1,\n\t\"jzqikan.com\": 1,\n\t\"jzqnet.com\": 1,\n\t\"jzqyw.com\": 1,\n\t\"jzrb.com\": 1,\n\t\"jzrc.net\": 1,\n\t\"jzsbs.com\": 1,\n\t\"jzsedu.org\": 1,\n\t\"jzszyw.com\": 1,\n\t\"jztedu.com\": 1,\n\t\"jzwcom.com\": 1,\n\t\"jzxgtd.com\": 1,\n\t\"jzxq.com\": 1,\n\t\"jzxyw.com\": 1,\n\t\"jzyx.com\": 1,\n\t\"k0912.com\": 1,\n\t\"k18.com\": 1,\n\t\"k366.com\": 1,\n\t\"k369.com\": 1,\n\t\"k666.net\": 1,\n\t\"k73.com\": 1,\n\t\"k76.com\": 1,\n\t\"k8008.com\": 1,\n\t\"k8k9.com\": 1,\n\t\"ka163.com\": 1,\n\t\"kaicent.com\": 1,\n\t\"kaiche100.com\": 1,\n\t\"kaichengschool.com\": 1,\n\t\"kaifu.com\": 1,\n\t\"kaifu100.com\": 1,\n\t\"kaifu7.com\": 1,\n\t\"kaifubiao.com\": 1,\n\t\"kaifuji.com\": 1,\n\t\"kaijianghao.com\": 1,\n\t\"kaiwind.com\": 1,\n\t\"kaixianrc.com\": 1,\n\t\"kaixin001.com\": 1,\n\t\"kaixin7.com\": 1,\n\t\"kaixinbao.com\": 1,\n\t\"kaixinlu.com\": 1,\n\t\"kakaba.com\": 1,\n\t\"kaku.tv\": 1,\n\t\"kakuedu.com\": 1,\n\t\"kama-classics.com\": 1,\n\t\"kameng.com\": 1,\n\t\"kan300.com\": 1,\n\t\"kan3721.com\": 1,\n\t\"kan98.com\": 1,\n\t\"kandao.com\": 1,\n\t\"kandian.com\": 1,\n\t\"kandian.net\": 1,\n\t\"kandongman.net\": 1,\n\t\"kanghu.net\": 1,\n\t\"kanglu.com\": 1,\n\t\"kangpaiqi.com\": 1,\n\t\"kangq.com\": 1,\n\t\"kanimg.com\": 1,\n\t\"kankan.com\": 1,\n\t\"kankanews.com\": 1,\n\t\"kanny88.com\": 1,\n\t\"kanshaa.com\": 1,\n\t\"kanshu.com\": 1,\n\t\"kantao.net\": 1,\n\t\"kantc.com\": 1,\n\t\"kanzg.com\": 1,\n\t\"kanzhun.com\": 1,\n\t\"kao66.com\": 1,\n\t\"kao8.cc\": 1,\n\t\"kaoben.net\": 1,\n\t\"kaocool.net\": 1,\n\t\"kaofudan.com\": 1,\n\t\"kaoguo8.com\": 1,\n\t\"kaogwy.com\": 1,\n\t\"kaojuan.com\": 1,\n\t\"kaolawan.com\": 1,\n\t\"kaopu001.com\": 1,\n\t\"kaoshi110.com\": 1,\n\t\"kaoshidian.com\": 1,\n\t\"kaoshijie.net\": 1,\n\t\"kaosuda.com\": 1,\n\t\"kaoup.com\": 1,\n\t\"kaoyan.com\": 1,\n\t\"kaoyan001.com\": 1,\n\t\"kaoyanmeng.com\": 1,\n\t\"kaoyans.com\": 1,\n\t\"kaoyanw.com\": 1,\n\t\"kaoyee.com\": 1,\n\t\"kaozc.com\": 1,\n\t\"karryhome.com\": 1,\n\t\"kashirc.com\": 1,\n\t\"kaslyju.com\": 1,\n\t\"kazakcnr.com\": 1,\n\t\"kb.cc\": 1,\n\t\"kbcool.com\": 1,\n\t\"kbl-jf.com\": 1,\n\t\"kc81.com\": 1,\n\t\"kc86.com\": 1,\n\t\"kchsw.com\": 1,\n\t\"kdcnu.com\": 1,\n\t\"kdnet.net\": 1,\n\t\"kds100.com\": 1,\n\t\"kdslife.com\": 1,\n\t\"kdweibo.com\": 1,\n\t\"ke-sen.com\": 1,\n\t\"keaidian.com\": 1,\n\t\"keaiq.com\": 1,\n\t\"kedacom.com\": 1,\n\t\"kedou.com\": 1,\n\t\"keede.com\": 1,\n\t\"keepc.com\": 1,\n\t\"kehou.com\": 1,\n\t\"kejet.net\": 1,\n\t\"kejianhome.com\": 1,\n\t\"kejiatong.com\": 1,\n\t\"kejihai.com\": 1,\n\t\"kejik.com\": 1,\n\t\"kejiqi.com\": 1,\n\t\"kejixun.com\": 1,\n\t\"kekejp.com\": 1,\n\t\"kekenet.com\": 1,\n\t\"kelanseal.com\": 1,\n\t\"kelon.com\": 1,\n\t\"kelrc.com\": 1,\n\t\"kelwm.com\": 1,\n\t\"kenfor.com\": 1,\n\t\"kengwan.com\": 1,\n\t\"keqiaojob.com\": 1,\n\t\"keqii.com\": 1,\n\t\"keshuaiseo.com\": 1,\n\t\"kesion.com\": 1,\n\t\"ketangwu.com\": 1,\n\t\"keyibao.com\": 1,\n\t\"keyunzhan.com\": 1,\n\t\"keywin.org\": 1,\n\t\"kfcdn.com\": 1,\n\t\"kfcrm.com\": 1,\n\t\"kfrcw.com\": 1,\n\t\"kfrsrcw.com\": 1,\n\t\"kfsy.net\": 1,\n\t\"kfw001.com\": 1,\n\t\"kgrcw.com\": 1,\n\t\"khgd.net\": 1,\n\t\"khzzm.com\": 1,\n\t\"kidsdown.com\": 1,\n\t\"kidulty.com\": 1,\n\t\"kiiik.com\": 1,\n\t\"kimiss.com\": 1,\n\t\"kimiss.net\": 1,\n\t\"kin8.com\": 1,\n\t\"kingboard.com\": 1,\n\t\"kingdee.com\": 1,\n\t\"kingriches.com\": 1,\n\t\"kingsoft.com\": 1,\n\t\"kingsun-china.com\": 1,\n\t\"kinhom.com\": 1,\n\t\"kinpan.com\": 1,\n\t\"kj-hr.com\": 1,\n\t\"kjfcw.com\": 1,\n\t\"kjpt.net\": 1,\n\t\"kjw.cc\": 1,\n\t\"kk22.com\": 1,\n\t\"kkcapture.com\": 1,\n\t\"kkcoo.com\": 1,\n\t\"kkdkk.com\": 1,\n\t\"kkeju.com\": 1,\n\t\"kkeye.com\": 1,\n\t\"kkk5.com\": 1,\n\t\"kkkmh.com\": 1,\n\t\"kkmami.com\": 1,\n\t\"kksmg.com\": 1,\n\t\"klchao.com\": 1,\n\t\"kllvx.com\": 1,\n\t\"klmyrc.com\": 1,\n\t\"klxuexi.com\": 1,\n\t\"klxuexi.org\": 1,\n\t\"klzuowen.com\": 1,\n\t\"km100zs.com\": 1,\n\t\"kmcct.com\": 1,\n\t\"kmcz.net\": 1,\n\t\"kmeb.net\": 1,\n\t\"kmgfebh.com\": 1,\n\t\"kmguolv.com\": 1,\n\t\"kmhouse.org\": 1,\n\t\"kmmama.com\": 1,\n\t\"kms88.com\": 1,\n\t\"kmszfz.com\": 1,\n\t\"kmvenus.com\": 1,\n\t\"kmw.cc\": 1,\n\t\"kmy100.com\": 1,\n\t\"kmzj.net\": 1,\n\t\"kmzp.com\": 1,\n\t\"knowsky.com\": 1,\n\t\"ko499.com\": 1,\n\t\"ko99.com\": 1,\n\t\"kofbobo.net\": 1,\n\t\"kongfz.com\": 1,\n\t\"kongjie.com\": 1,\n\t\"kongjun.com\": 1,\n\t\"kongqueyuzd.cc\": 1,\n\t\"kongyaji.cc\": 1,\n\t\"kongzhong.com\": 1,\n\t\"konka.com\": 1,\n\t\"kooaoo.com\": 1,\n\t\"koofang.com\": 1,\n\t\"kooke.org\": 1,\n\t\"koolearn.com\": 1,\n\t\"koowo.com\": 1,\n\t\"koppers-china.com\": 1,\n\t\"korirl.com\": 1,\n\t\"koubei.com\": 1,\n\t\"koudai.com\": 1,\n\t\"koudai8.com\": 1,\n\t\"koudaipe.com\": 1,\n\t\"koudaitong.com\": 1,\n\t\"kouyu.org\": 1,\n\t\"kp52.cc\": 1,\n\t\"kpzs.com\": 1,\n\t\"kq81.com\": 1,\n\t\"kqmr120.com\": 1,\n\t\"kqzp.com\": 1,\n\t\"krwz.com\": 1,\n\t\"ks-lxjy.com\": 1,\n\t\"ks116.com\": 1,\n\t\"ks56.net\": 1,\n\t\"ks5u.com\": 1,\n\t\"ksbao.com\": 1,\n\t\"ksbbs.com\": 1,\n\t\"ksdown.com\": 1,\n\t\"kshot.com\": 1,\n\t\"ksldesign.net\": 1,\n\t\"kslwed.com\": 1,\n\t\"ksokjob.com\": 1,\n\t\"ksren.com\": 1,\n\t\"kssbw.com\": 1,\n\t\"ksyx.net\": 1,\n\t\"kt250.com\": 1,\n\t\"kt51.com\": 1,\n\t\"ktkkt.com\": 1,\n\t\"ktxp.com\": 1,\n\t\"ktzpx.com\": 1,\n\t\"ku25.com\": 1,\n\t\"ku6.com\": 1,\n\t\"ku6cdn.com\": 1,\n\t\"ku6img.com\": 1,\n\t\"ku6vms.com\": 1,\n\t\"kuachen.com\": 1,\n\t\"kuai8.com\": 1,\n\t\"kuaibo.com\": 1,\n\t\"kuaichushou.com\": 1,\n\t\"kuaidadi.com\": 1,\n\t\"kuaidi100.com\": 1,\n\t\"kuaidihelp.com\": 1,\n\t\"kuaiji.com\": 1,\n\t\"kuaijieair.com\": 1,\n\t\"kuaijishi.net\": 1,\n\t\"kuaijizheng.com\": 1,\n\t\"kuaikaifu.com\": 1,\n\t\"kuailezu.com\": 1,\n\t\"kuailiyu.com\": 1,\n\t\"kuaitv.net\": 1,\n\t\"kuaiwan.com\": 1,\n\t\"kuaiwin.com\": 1,\n\t\"kuaiyong.com\": 1,\n\t\"kuaiyoujia.com\": 1,\n\t\"kuakao.com\": 1,\n\t\"kuakao.net\": 1,\n\t\"kuche.com\": 1,\n\t\"kuchechina.com\": 1,\n\t\"kuchexiaozhen.com\": 1,\n\t\"kudou.org\": 1,\n\t\"kufa88.com\": 1,\n\t\"kugou.com\": 1,\n\t\"kuguanyi.com\": 1,\n\t\"kugz.com\": 1,\n\t\"kugz.net\": 1,\n\t\"kuhao360.com\": 1,\n\t\"kuhema.cc\": 1,\n\t\"kujiale.com\": 1,\n\t\"kukahome.com\": 1,\n\t\"kuku123.com\": 1,\n\t\"kukuplay.com\": 1,\n\t\"kukuspeak.com\": 1,\n\t\"kulv.com\": 1,\n\t\"kumanju.com\": 1,\n\t\"kunjuke.com\": 1,\n\t\"kunlun.com\": 1,\n\t\"kunlunxuejucha.com\": 1,\n\t\"kunmingkanghui.com\": 1,\n\t\"kuotu.com\": 1,\n\t\"kuparts.com\": 1,\n\t\"kuqi.com\": 1,\n\t\"kuqyu.com\": 1,\n\t\"kutianxia.com\": 1,\n\t\"kutj.com\": 1,\n\t\"kutongji.com\": 1,\n\t\"kuurl.com\": 1,\n\t\"kuwan8.com\": 1,\n\t\"kuxue.com\": 1,\n\t\"kuyiso.com\": 1,\n\t\"kwxs.com\": 1,\n\t\"kx173.com\": 1,\n\t\"kx43.com\": 1,\n\t\"kxchina.org\": 1,\n\t\"kxue.com\": 1,\n\t\"kxyik.com\": 1,\n\t\"ky007.com\": 1,\n\t\"ky0873.com\": 1,\n\t\"ky81.com\": 1,\n\t\"kyjxy.com\": 1,\n\t\"kyjyw.com\": 1,\n\t\"kyk8.com\": 1,\n\t\"kyomh.com\": 1,\n\t\"kyp.com\": 1,\n\t\"kypbuy.com\": 1,\n\t\"kytl.com\": 1,\n\t\"kywcdn.com\": 1,\n\t\"kywmall.com\": 1,\n\t\"kz928.com\": 1,\n\t\"kzbigu.com\": 1,\n\t\"kzenglish.com\": 1,\n\t\"kzhuang.com\": 1,\n\t\"kzj365.com\": 1,\n\t\"l-longview.com\": 1,\n\t\"l-wed.com\": 1,\n\t\"l-zzz.com\": 1,\n\t\"l99.com\": 1,\n\t\"la-bbs.net\": 1,\n\t\"labbase.net\": 1,\n\t\"lady8844.com\": 1,\n\t\"ladyhf.com\": 1,\n\t\"ladynest.com\": 1,\n\t\"ladysq.com\": 1,\n\t\"ladyyu.com\": 1,\n\t\"lafaso.com\": 1,\n\t\"lagou.com\": 1,\n\t\"lagsw.com\": 1,\n\t\"laianbbs.com\": 1,\n\t\"laidingba.com\": 1,\n\t\"laifeng.com\": 1,\n\t\"laifudao.com\": 1,\n\t\"laigang.com\": 1,\n\t\"laijiuye.com\": 1,\n\t\"laishui.info\": 1,\n\t\"laiwang.com\": 1,\n\t\"laiwu.com\": 1,\n\t\"laiwumedia.com\": 1,\n\t\"laiyang58.com\": 1,\n\t\"lamahui.com\": 1,\n\t\"lamaison-arting.com\": 1,\n\t\"lameng.net\": 1,\n\t\"lampbrother.net\": 1,\n\t\"lampdrive.com\": 1,\n\t\"lan1001.com\": 1,\n\t\"lanapartments.com\": 1,\n\t\"lanchijituan.com\": 1,\n\t\"landai.com\": 1,\n\t\"landbond.com\": 1,\n\t\"landchina.com\": 1,\n\t\"landjs.com\": 1,\n\t\"landks.com\": 1,\n\t\"landscapecn.com\": 1,\n\t\"landscapehr.com\": 1,\n\t\"landtu.com\": 1,\n\t\"landui.com\": 1,\n\t\"landzestate.com\": 1,\n\t\"landzhuhai.com\": 1,\n\t\"lanfcw.com\": 1,\n\t\"lanfw.com\": 1,\n\t\"lange360.com\": 1,\n\t\"langfly.com\": 1,\n\t\"langlangjiajiao.com\": 1,\n\t\"langshanhong.com\": 1,\n\t\"languang.cc\": 1,\n\t\"languang.com\": 1,\n\t\"langxi.org\": 1,\n\t\"langxudz.com\": 1,\n\t\"langyache.com\": 1,\n\t\"lanhii.com\": 1,\n\t\"lanhua8.com\": 1,\n\t\"laniqu.com\": 1,\n\t\"lanjing-lijia.com\": 1,\n\t\"lanou3g.com\": 1,\n\t\"lanpowang.com\": 1,\n\t\"lanrentuku.com\": 1,\n\t\"lanrenyuan.com\": 1,\n\t\"lanrenzhaofang.com\": 1,\n\t\"lanrenzhijia.com\": 1,\n\t\"lantian360.com\": 1,\n\t\"lanxingzhuji.com\": 1,\n\t\"lanyanwan.com\": 1,\n\t\"lanyurz.com\": 1,\n\t\"laobiao.com\": 1,\n\t\"laobingmi.com\": 1,\n\t\"laogu.com\": 1,\n\t\"laohe360.net\": 1,\n\t\"laohe5.com\": 1,\n\t\"laohu.com\": 1,\n\t\"laohuangli.net\": 1,\n\t\"laohucaijing.com\": 1,\n\t\"laoke.com\": 1,\n\t\"laomoo.com\": 1,\n\t\"laonanren.com\": 1,\n\t\"laoqianzhuang.com\": 1,\n\t\"laoren.com\": 1,\n\t\"laoshitv.com\": 1,\n\t\"laosizhou.com\": 1,\n\t\"laoyangchenghu.com\": 1,\n\t\"laoyindian.com\": 1,\n\t\"laoyuegou.com\": 1,\n\t\"larcw.net\": 1,\n\t\"lashou.com\": 1,\n\t\"lashouimg.com\": 1,\n\t\"lavago.com\": 1,\n\t\"law-lib.com\": 1,\n\t\"law-star.com\": 1,\n\t\"law1818.com\": 1,\n\t\"lawtimeimg.com\": 1,\n\t\"lawyerwq.com\": 1,\n\t\"lazyren.com\": 1,\n\t\"lbgoo.com\": 1,\n\t\"lbrcw.com\": 1,\n\t\"lbx.cc\": 1,\n\t\"lbx777.com\": 1,\n\t\"lc-rc.com\": 1,\n\t\"lc123.net\": 1,\n\t\"lcbtv.com\": 1,\n\t\"lcd88.com\": 1,\n\t\"lcfcw.com\": 1,\n\t\"lchssy.com\": 1,\n\t\"lclabor.com\": 1,\n\t\"lcpop.com\": 1,\n\t\"lcwto.com\": 1,\n\t\"lcxwfc.com\": 1,\n\t\"lcyx.com\": 1,\n\t\"lczb.net\": 1,\n\t\"ld001.com\": 1,\n\t\"ld365.com\": 1,\n\t\"ldbj.com\": 1,\n\t\"ldgjj.com\": 1,\n\t\"ldlx.com\": 1,\n\t\"ldmet.com\": 1,\n\t\"ldmetals.com\": 1,\n\t\"ldrczpw.com\": 1,\n\t\"le3x.com\": 1,\n\t\"leadfutures.com\": 1,\n\t\"leadge.com\": 1,\n\t\"leadoor.com\": 1,\n\t\"leatherhr.com\": 1,\n\t\"lebeibei.com\": 1,\n\t\"lecai.com\": 1,\n\t\"leche.com\": 1,\n\t\"led234.com\": 1,\n\t\"led889.com\": 1,\n\t\"ledanji.com\": 1,\n\t\"ledanji.net\": 1,\n\t\"ledao.so\": 1,\n\t\"ledbao.com\": 1,\n\t\"ledcax.com\": 1,\n\t\"ledche.net\": 1,\n\t\"lede.com\": 1,\n\t\"ledgb.com\": 1,\n\t\"ledth.com\": 1,\n\t\"ledu.com\": 1,\n\t\"ledugame.com\": 1,\n\t\"ledwn.com\": 1,\n\t\"leejiaju.com\": 1,\n\t\"lefanghn.com\": 1,\n\t\"lefeng.com\": 1,\n\t\"leftdays.com\": 1,\n\t\"legolas-media.com\": 1,\n\t\"legu168.com\": 1,\n\t\"lehecai.com\": 1,\n\t\"lehihi.com\": 1,\n\t\"leho.com\": 1,\n\t\"leho100.com\": 1,\n\t\"lehuozaixian.com\": 1,\n\t\"leidian.com\": 1,\n\t\"leiphone.com\": 1,\n\t\"leixundr.com\": 1,\n\t\"leixunkf.com\": 1,\n\t\"lejiaoyun.com\": 1,\n\t\"lejj.com\": 1,\n\t\"leju.com\": 1,\n\t\"lejuwh.com\": 1,\n\t\"leleketang.com\": 1,\n\t\"leleyx.com\": 1,\n\t\"lelife.com\": 1,\n\t\"lemanchina.com\": 1,\n\t\"lemuzhi.com\": 1,\n\t\"lengcang6.com\": 1,\n\t\"lengxiaohua.com\": 1,\n\t\"lenosoft.net\": 1,\n\t\"lenovo.com\": 1,\n\t\"lenovomm.com\": 1,\n\t\"lenovomobile.com\": 1,\n\t\"lenovosj.com\": 1,\n\t\"lentour.com\": 1,\n\t\"lepingfoundation.org\": 1,\n\t\"lepinw.com\": 1,\n\t\"leqian.com\": 1,\n\t\"leqiyou.com\": 1,\n\t\"lequ.com\": 1,\n\t\"letao.com\": 1,\n\t\"letfind.com\": 1,\n\t\"letian.net\": 1,\n\t\"letv.com\": 1,\n\t\"letvcdn.com\": 1,\n\t\"letvimg.com\": 1,\n\t\"lewan100.com\": 1,\n\t\"lewaos.com\": 1,\n\t\"lewatek.com\": 1,\n\t\"lexiang365.com\": 1,\n\t\"lexiangrencai.com\": 1,\n\t\"lexueke.com\": 1,\n\t\"lexun.com\": 1,\n\t\"leyoo.com\": 1,\n\t\"leyou.com\": 1,\n\t\"leyueke.com\": 1,\n\t\"lezhi.com\": 1,\n\t\"lezhiweilai.com\": 1,\n\t\"lfang.com\": 1,\n\t\"lfbole.com\": 1,\n\t\"lffdcw.com\": 1,\n\t\"lfgjj.com\": 1,\n\t\"lfrtv.com\": 1,\n\t\"lfsanjiu.com\": 1,\n\t\"lftour.net\": 1,\n\t\"lfxww.com\": 1,\n\t\"lg188.com\": 1,\n\t\"lgbzj.com\": 1,\n\t\"lgfang.com\": 1,\n\t\"lgmi.com\": 1,\n\t\"lgo100.com\": 1,\n\t\"lgpic.com\": 1,\n\t\"lgrcsc.com\": 1,\n\t\"lgsou.com\": 1,\n\t\"lh168.net\": 1,\n\t\"lh987.com\": 1,\n\t\"lhave.com\": 1,\n\t\"lhjol.com\": 1,\n\t\"lhjy.net\": 1,\n\t\"lhk110.com\": 1,\n\t\"lhtz.com\": 1,\n\t\"lhxfc.com\": 1,\n\t\"li-ke.com\": 1,\n\t\"li63.com\": 1,\n\t\"li63.net\": 1,\n\t\"li70.com\": 1,\n\t\"liang360.com\": 1,\n\t\"liangchan.net\": 1,\n\t\"liangjian.com\": 1,\n\t\"liangshixian.com\": 1,\n\t\"liangxunwang.com\": 1,\n\t\"liankebio.com\": 1,\n\t\"lianm.com\": 1,\n\t\"lianshuiren.com\": 1,\n\t\"liansuo.com\": 1,\n\t\"liansuovip.com\": 1,\n\t\"liantu.com\": 1,\n\t\"lianwifi.com\": 1,\n\t\"lianzhuang.net\": 1,\n\t\"liao1.com\": 1,\n\t\"liaoing.com\": 1,\n\t\"liaoshenrc.com\": 1,\n\t\"liaotuo.org\": 1,\n\t\"liaoyangwater.net\": 1,\n\t\"liaozhai.tv\": 1,\n\t\"liaozhuangxiu.com\": 1,\n\t\"liazu.com\": 1,\n\t\"liba.com\": 1,\n\t\"libvideo.com\": 1,\n\t\"licai18.com\": 1,\n\t\"licaike.com\": 1,\n\t\"licang.net\": 1,\n\t\"liche365.com\": 1,\n\t\"lidodo.com\": 1,\n\t\"lidroid.com\": 1,\n\t\"liebiao.com\": 1,\n\t\"liebo.com\": 1,\n\t\"liehucn.com\": 1,\n\t\"lieju.com\": 1,\n\t\"lieou.com\": 1,\n\t\"liepin.com\": 1,\n\t\"lietou-static.com\": 1,\n\t\"lietou.com\": 1,\n\t\"liexiaow.com\": 1,\n\t\"lieyou.com\": 1,\n\t\"lieyunwang.com\": 1,\n\t\"life5000.com\": 1,\n\t\"lifeyoyo.com\": 1,\n\t\"lightget.com\": 1,\n\t\"lighting163.com\": 1,\n\t\"lightingchina.com\": 1,\n\t\"lijiangtv.com\": 1,\n\t\"lijiwan.com\": 1,\n\t\"lijunwang.com\": 1,\n\t\"likelic.com\": 1,\n\t\"lilingnews.com\": 1,\n\t\"lilv8.net\": 1,\n\t\"liminghe.com\": 1,\n\t\"linduren.com\": 1,\n\t\"linecg.com\": 1,\n\t\"linecg.org\": 1,\n\t\"linekong.com\": 1,\n\t\"linewow.com\": 1,\n\t\"linezing.com\": 1,\n\t\"linfangwang.com\": 1,\n\t\"linfen365.com\": 1,\n\t\"lingauto.com\": 1,\n\t\"lingb.net\": 1,\n\t\"lingdan.cc\": 1,\n\t\"lingkaba.com\": 1,\n\t\"lingnan.net\": 1,\n\t\"lingnanrc.com\": 1,\n\t\"lingshi.com\": 1,\n\t\"lingtiao.com\": 1,\n\t\"lingtuan.com\": 1,\n\t\"link-run.com\": 1,\n\t\"linkbasic.com\": 1,\n\t\"linkchic.com\": 1,\n\t\"linkedin.com\": 1,\n\t\"linkvans.com\": 1,\n\t\"linkwan.com\": 1,\n\t\"linlin.com\": 1,\n\t\"linqingtex.com\": 1,\n\t\"linqujob.com\": 1,\n\t\"linuxdiyf.com\": 1,\n\t\"linwa5678.com\": 1,\n\t\"linyimama.com\": 1,\n\t\"linyiren.com\": 1,\n\t\"linzhourc.com\": 1,\n\t\"lipip.com\": 1,\n\t\"liqu.com\": 1,\n\t\"liquan.org\": 1,\n\t\"liqucn.com\": 1,\n\t\"lisanxing.com\": 1,\n\t\"lishang.so\": 1,\n\t\"lishi5.com\": 1,\n\t\"lishichunqiu.com\": 1,\n\t\"liuannews.com\": 1,\n\t\"liubj.com\": 1,\n\t\"liudu.com\": 1,\n\t\"liugong.com\": 1,\n\t\"liuhe.com\": 1,\n\t\"liuliangche.com\": 1,\n\t\"liumeinet.com\": 1,\n\t\"liuwanlin.com\": 1,\n\t\"liuxue114.com\": 1,\n\t\"liuxue51.net\": 1,\n\t\"liuxue86.com\": 1,\n\t\"liuxuejie.com\": 1,\n\t\"liuyangjob.com\": 1,\n\t\"liuyuanxing.com\": 1,\n\t\"liuzhousteel.com\": 1,\n\t\"live.com\": 1,\n\t\"live0311.com\": 1,\n\t\"live754.com\": 1,\n\t\"live800.com\": 1,\n\t\"liveuc.net\": 1,\n\t\"livnj.com\": 1,\n\t\"liwai.com\": 1,\n\t\"liwuyou.com\": 1,\n\t\"lixin.co\": 1,\n\t\"liyangrc.com\": 1,\n\t\"liyezhongzhi.com\": 1,\n\t\"liyi99.com\": 1,\n\t\"lizhi123.net\": 1,\n\t\"lizhidaren.com\": 1,\n\t\"lizi.com\": 1,\n\t\"lj168.com\": 1,\n\t\"lj597.com\": 1,\n\t\"ljcjw.com\": 1,\n\t\"ljforest.com\": 1,\n\t\"ljgjj.com\": 1,\n\t\"ljia.net\": 1,\n\t\"ljjgdj.org\": 1,\n\t\"ljlj.cc\": 1,\n\t\"ljmeeting.com\": 1,\n\t\"ljyongfu.com\": 1,\n\t\"ljzc.net\": 1,\n\t\"lke100.com\": 1,\n\t\"lkgame.com\": 1,\n\t\"lkong.net\": 1,\n\t\"ll086.com\": 1,\n\t\"llbtv.com\": 1,\n\t\"llcbbs.com\": 1,\n\t\"llfang.com\": 1,\n\t\"lltqc.com\": 1,\n\t\"llxue.com\": 1,\n\t\"lm111.com\": 1,\n\t\"lmedu100.com\": 1,\n\t\"lmjx.net\": 1,\n\t\"lmlove.com\": 1,\n\t\"lmtw.com\": 1,\n\t\"ln-job.com\": 1,\n\t\"ln-rc.com\": 1,\n\t\"ln2car.com\": 1,\n\t\"ln632.com\": 1,\n\t\"lnast.net\": 1,\n\t\"lncci.com\": 1,\n\t\"lndzz.com\": 1,\n\t\"lng123.com\": 1,\n\t\"lngb.org\": 1,\n\t\"lngongmu.com\": 1,\n\t\"lngsm.net\": 1,\n\t\"lnlib.com\": 1,\n\t\"lnlotto.com\": 1,\n\t\"lnok.net\": 1,\n\t\"lnptm.com\": 1,\n\t\"lnrcsc.com\": 1,\n\t\"lnrsks.com\": 1,\n\t\"lnspaq.com\": 1,\n\t\"lnszgh.org\": 1,\n\t\"lntycp.com\": 1,\n\t\"lnwomen.org\": 1,\n\t\"lnylfw.com\": 1,\n\t\"lnzhyyjt.com\": 1,\n\t\"lnzsks.com\": 1,\n\t\"lnzzsm.com\": 1,\n\t\"lobotou.com\": 1,\n\t\"locojoy.com\": 1,\n\t\"locowan.com\": 1,\n\t\"locoy.com\": 1,\n\t\"locpg.hk\": 1,\n\t\"lofficielchina.net\": 1,\n\t\"lofter.com\": 1,\n\t\"logclub.com\": 1,\n\t\"logmein.com\": 1,\n\t\"logo123.net\": 1,\n\t\"logo2008.net\": 1,\n\t\"logo33.com\": 1,\n\t\"logoai.com\": 1,\n\t\"logonc.com\": 1,\n\t\"logopay.com\": 1,\n\t\"logoquan.com\": 1,\n\t\"logozhizuowang.com\": 1,\n\t\"lohas.ly\": 1,\n\t\"loho88.com\": 1,\n\t\"loli.mg\": 1,\n\t\"loli.vg\": 1,\n\t\"lolitabox.com\": 1,\n\t\"loljieshuo.com\": 1,\n\t\"lolqu.com\": 1,\n\t\"lolxiu.com\": 1,\n\t\"lomge.com\": 1,\n\t\"lomoslife.com\": 1,\n\t\"long-photo.com\": 1,\n\t\"longau.com\": 1,\n\t\"longbasz.com\": 1,\n\t\"longchengrc.com\": 1,\n\t\"longchuan5.com\": 1,\n\t\"longcity.net\": 1,\n\t\"longdian.com\": 1,\n\t\"longfeng.com\": 1,\n\t\"longfor.com\": 1,\n\t\"longhoo.net\": 1,\n\t\"longjiang.net\": 1,\n\t\"longkangmiaomu.com\": 1,\n\t\"longkouhaijingfang.com\": 1,\n\t\"longre.com\": 1,\n\t\"longshangrc.com\": 1,\n\t\"longtengcn.com\": 1,\n\t\"longtugame.com\": 1,\n\t\"longwenedu.com\": 1,\n\t\"longyangjj.com\": 1,\n\t\"longyin.net\": 1,\n\t\"longyu.cc\": 1,\n\t\"longyuebxg.com\": 1,\n\t\"lonlife.net\": 1,\n\t\"looedu.com\": 1,\n\t\"loogoo.com\": 1,\n\t\"lookvin.com\": 1,\n\t\"loongzone.com\": 1,\n\t\"looquan.com\": 1,\n\t\"loorin.com\": 1,\n\t\"looxiang.com\": 1,\n\t\"looyu.com\": 1,\n\t\"looyuoms.com\": 1,\n\t\"lotaoke.com\": 1,\n\t\"lotour.com\": 1,\n\t\"lotour.net\": 1,\n\t\"loukou.com\": 1,\n\t\"loulanwang.com\": 1,\n\t\"loupan.com\": 1,\n\t\"louti.net\": 1,\n\t\"love169.com\": 1,\n\t\"love21cn.com\": 1,\n\t\"love616.com\": 1,\n\t\"lovebaoji.com\": 1,\n\t\"lovelian.com\": 1,\n\t\"loveliao.com\": 1,\n\t\"lover88.com\": 1,\n\t\"lovev.com\": 1,\n\t\"lovewith.me\": 1,\n\t\"lovingjob.com\": 1,\n\t\"lowcn.com\": 1,\n\t\"lp023.com\": 1,\n\t\"lp91.com\": 1,\n\t\"lpc8.com\": 1,\n\t\"lpdyz.com\": 1,\n\t\"lpnews.net\": 1,\n\t\"lpsrc.com\": 1,\n\t\"lqjob88.com\": 1,\n\t\"lqjy.com\": 1,\n\t\"lqrc028.com\": 1,\n\t\"lqxww.com\": 1,\n\t\"lqzcw.com\": 1,\n\t\"lqzp.com\": 1,\n\t\"lrswl.com\": 1,\n\t\"ls0376.com\": 1,\n\t\"ls520.net\": 1,\n\t\"ls666.com\": 1,\n\t\"lscy18.com\": 1,\n\t\"lsdag.com\": 1,\n\t\"lsgzn.com\": 1,\n\t\"lshangjiu.com\": 1,\n\t\"lshappy.com\": 1,\n\t\"lshui.com\": 1,\n\t\"lsjxww.com\": 1,\n\t\"lsjyw.net\": 1,\n\t\"lsnetlib.com\": 1,\n\t\"lsnews.net\": 1,\n\t\"lsphoto.org\": 1,\n\t\"lspjy.com\": 1,\n\t\"lsqss.com\": 1,\n\t\"lsqx.com\": 1,\n\t\"lsrcw.org\": 1,\n\t\"lsrczpw.com\": 1,\n\t\"lssdjt.com\": 1,\n\t\"lssen.com\": 1,\n\t\"lssx.net\": 1,\n\t\"lstest.com\": 1,\n\t\"lstjj.net\": 1,\n\t\"lsxt.com\": 1,\n\t\"lszhaopin.com\": 1,\n\t\"lt0769.com\": 1,\n\t\"lt1000.com\": 1,\n\t\"ltaaa.com\": 1,\n\t\"ltcbase.com\": 1,\n\t\"ltcdn.net\": 1,\n\t\"ltcheku.com\": 1,\n\t\"ltesting.net\": 1,\n\t\"lua99.com\": 1,\n\t\"luan163.com\": 1,\n\t\"luaninfo.com\": 1,\n\t\"luanren.com\": 1,\n\t\"lubanlu.com\": 1,\n\t\"lubansoft.com\": 1,\n\t\"lubanu.com\": 1,\n\t\"lubesale.com\": 1,\n\t\"lubiao.com\": 1,\n\t\"luchengnet.com\": 1,\n\t\"luckyair.net\": 1,\n\t\"luckyxp.net\": 1,\n\t\"ludashi.com\": 1,\n\t\"lufthansa.com\": 1,\n\t\"luguowang.com\": 1,\n\t\"lujiangjob.com\": 1,\n\t\"lujuncn.com\": 1,\n\t\"lukaegg.com\": 1,\n\t\"luliang.org\": 1,\n\t\"lunan.tv\": 1,\n\t\"lunanjob.com\": 1,\n\t\"lundang.com\": 1,\n\t\"lunwenstudy.com\": 1,\n\t\"lunwentianxia.com\": 1,\n\t\"lunwenup.com\": 1,\n\t\"luo8.com\": 1,\n\t\"luobo360.com\": 1,\n\t\"luohanyu.cc\": 1,\n\t\"luoherc.com\": 1,\n\t\"luohuedu.net\": 1,\n\t\"luomeifeng.com\": 1,\n\t\"luoohu.com\": 1,\n\t\"luosi.com\": 1,\n\t\"luoyuan597.com\": 1,\n\t\"luozhongxu.com\": 1,\n\t\"lupanshui.com\": 1,\n\t\"lupaworld.com\": 1,\n\t\"lusen.com\": 1,\n\t\"lusongsong.com\": 1,\n\t\"luv66.com\": 1,\n\t\"luwenwang.com\": 1,\n\t\"luxee.com\": 1,\n\t\"luxtarget.com\": 1,\n\t\"luyanbrand.com\": 1,\n\t\"lv3w.com\": 1,\n\t\"lvdichan.com\": 1,\n\t\"lvguo.net\": 1,\n\t\"lvhezi.com\": 1,\n\t\"lvmama.com\": 1,\n\t\"lvping.com\": 1,\n\t\"lvren.com\": 1,\n\t\"lvse.com\": 1,\n\t\"lvseba.com\": 1,\n\t\"lvsecn.org\": 1,\n\t\"lvshou.com\": 1,\n\t\"lvtu.com\": 1,\n\t\"lvtu100.com\": 1,\n\t\"lvxing.fm\": 1,\n\t\"lvye.com\": 1,\n\t\"lvyebx.com\": 1,\n\t\"lvyou114.com\": 1,\n\t\"lvyou1778.com\": 1,\n\t\"lwcj.com\": 1,\n\t\"lwgcw.com\": 1,\n\t\"lwhouse.com\": 1,\n\t\"lwjy.net\": 1,\n\t\"lwlm.com\": 1,\n\t\"lwnews.net\": 1,\n\t\"lxdns.com\": 1,\n\t\"lxroto.com\": 1,\n\t\"lxxnews.com\": 1,\n\t\"lxydoor.com\": 1,\n\t\"lxyes.com\": 1,\n\t\"lxyk.net\": 1,\n\t\"lxzc.net\": 1,\n\t\"ly.com\": 1,\n\t\"ly10000.com\": 1,\n\t\"ly234.com\": 1,\n\t\"ly333.com\": 1,\n\t\"lyaccp.com\": 1,\n\t\"lyauto.com\": 1,\n\t\"lycos.com\": 1,\n\t\"lydhzs.com\": 1,\n\t\"lyemb.com\": 1,\n\t\"lyfcw.com\": 1,\n\t\"lyfeiliao.com\": 1,\n\t\"lyfff.com\": 1,\n\t\"lyg01.net\": 1,\n\t\"lyg1.com\": 1,\n\t\"lyg188.com\": 1,\n\t\"lygbole.com\": 1,\n\t\"lygczj.com\": 1,\n\t\"lygexpo.com\": 1,\n\t\"lygfish.com\": 1,\n\t\"lygjg.net\": 1,\n\t\"lygjj.com\": 1,\n\t\"lygmedia.com\": 1,\n\t\"lygnews.com\": 1,\n\t\"lygo.com\": 1,\n\t\"lygrc.com\": 1,\n\t\"lygrc.net\": 1,\n\t\"lyguihua.com\": 1,\n\t\"lygyjs.com\": 1,\n\t\"lyhengyue.com\": 1,\n\t\"lyhero.com\": 1,\n\t\"lyielts.com\": 1,\n\t\"lyjjzd.com\": 1,\n\t\"lyjob.net\": 1,\n\t\"lylxs.net\": 1,\n\t\"lymffyjd.com\": 1,\n\t\"lymonalisa.com\": 1,\n\t\"lyqcw.com\": 1,\n\t\"lyqiche.com\": 1,\n\t\"lyqj.net\": 1,\n\t\"lyrc.cc\": 1,\n\t\"lyrce.net\": 1,\n\t\"lyrcw.com\": 1,\n\t\"lyredstar.com\": 1,\n\t\"lysteel.com\": 1,\n\t\"lytoday.com\": 1,\n\t\"lytpw.com\": 1,\n\t\"lywj.net\": 1,\n\t\"lywww.com\": 1,\n\t\"lywww.net\": 1,\n\t\"lywxww.com\": 1,\n\t\"lyxltv.com\": 1,\n\t\"lyy99.com\": 1,\n\t\"lyyz.net\": 1,\n\t\"lyzhujia.com\": 1,\n\t\"lz520.net\": 1,\n\t\"lz6.com\": 1,\n\t\"lz669.com\": 1,\n\t\"lzanju.com\": 1,\n\t\"lzbd.com\": 1,\n\t\"lzedu.net\": 1,\n\t\"lzgd.net\": 1,\n\t\"lzgjj.com\": 1,\n\t\"lzhongdian.com\": 1,\n\t\"lzhuba.com\": 1,\n\t\"lzk99.com\": 1,\n\t\"lzqss.net\": 1,\n\t\"lzrc.net\": 1,\n\t\"lzsq.net\": 1,\n\t\"lztv.tv\": 1,\n\t\"lztvnet.com\": 1,\n\t\"lztxw.com\": 1,\n\t\"lzxjyj.com\": 1,\n\t\"lzyysd.com\": 1,\n\t\"lzyysw.com\": 1,\n\t\"lzzfgjj.com\": 1,\n\t\"m10cdn.com\": 1,\n\t\"m18.com\": 1,\n\t\"m1905.com\": 1,\n\t\"m3fc.com\": 1,\n\t\"m3guo.com\": 1,\n\t\"m3guocdn.com\": 1,\n\t\"m598.com\": 1,\n\t\"m6699.com\": 1,\n\t\"ma-china.org\": 1,\n\t\"ma35.com\": 1,\n\t\"ma4.net\": 1,\n\t\"macgg.com\": 1,\n\t\"macgood.com\": 1,\n\t\"machine35.com\": 1,\n\t\"machine365.com\": 1,\n\t\"macmicst.com\": 1,\n\t\"macromedia.com\": 1,\n\t\"made-in-china.com\": 1,\n\t\"maercn.com\": 1,\n\t\"mafengwo.net\": 1,\n\t\"mahoupao.net\": 1,\n\t\"mahua.com\": 1,\n\t\"maichawang.com\": 1,\n\t\"maidong100.com\": 1,\n\t\"maifang.com\": 1,\n\t\"maijipu.com\": 1,\n\t\"maijiuwang.com\": 1,\n\t\"mainone.com\": 1,\n\t\"maishushi.com\": 1,\n\t\"maituan.com\": 1,\n\t\"maiwaiwai.com\": 1,\n\t\"maiyadi.com\": 1,\n\t\"maizhixiu.com\": 1,\n\t\"make365.com\": 1,\n\t\"makepolo.com\": 1,\n\t\"makepolo.net\": 1,\n\t\"malait.com\": 1,\n\t\"malataedu.com\": 1,\n\t\"mallchina.net\": 1,\n\t\"mallcn.cc\": 1,\n\t\"malmam.com\": 1,\n\t\"mama100.com\": 1,\n\t\"mama999.com\": 1,\n\t\"mamabaobao.com\": 1,\n\t\"mamacn.com\": 1,\n\t\"mamecn.com\": 1,\n\t\"mamimp3.com\": 1,\n\t\"man189.com\": 1,\n\t\"managershare.com\": 1,\n\t\"mandaringarden.org\": 1,\n\t\"mandarinmorning.com\": 1,\n\t\"mandarinmorning.net\": 1,\n\t\"mangocity.com\": 1,\n\t\"manhuadao.com\": 1,\n\t\"manhuawan.com\": 1,\n\t\"manmankan.com\": 1,\n\t\"manpianyi.com\": 1,\n\t\"mansuno.com\": 1,\n\t\"manxiangyi.com\": 1,\n\t\"manyart.com\": 1,\n\t\"manyou.com\": 1,\n\t\"manzhan.com\": 1,\n\t\"manzuo.com\": 1,\n\t\"maodou.com\": 1,\n\t\"maomingbao.com\": 1,\n\t\"maoocoffee.com\": 1,\n\t\"maopuyouxi.com\": 1,\n\t\"maoren8.com\": 1,\n\t\"maoren8.net\": 1,\n\t\"maotaifamily.com\": 1,\n\t\"maoyidi.com\": 1,\n\t\"maoyigu.com\": 1,\n\t\"maoyiw.com\": 1,\n\t\"maoyl.com\": 1,\n\t\"maozhiwang.com\": 1,\n\t\"mapabc.com\": 1,\n\t\"mapbar.com\": 1,\n\t\"maquan.net\": 1,\n\t\"marieclairechina.com\": 1,\n\t\"marketreportchina.com\": 1,\n\t\"marry52.com\": 1,\n\t\"martell.com\": 1,\n\t\"masamaso.com\": 1,\n\t\"masej.com\": 1,\n\t\"masfy.com\": 1,\n\t\"masgl.com\": 1,\n\t\"masgq.com\": 1,\n\t\"masjia.com\": 1,\n\t\"maszs.com\": 1,\n\t\"mathtag.com\": 1,\n\t\"maxpda.com\": 1,\n\t\"mayangnews.com\": 1,\n\t\"mayi.com\": 1,\n\t\"mayiw.com\": 1,\n\t\"mayiyy.com\": 1,\n\t\"mazuworld.com\": 1,\n\t\"mb5u.com\": 1,\n\t\"mbachina.com\": 1,\n\t\"mbajyz.com\": 1,\n\t\"mbalib.com\": 1,\n\t\"mbaobao.com\": 1,\n\t\"mbatrip.com\": 1,\n\t\"mbaun.net\": 1,\n\t\"mbscss.com\": 1,\n\t\"mbsimg.com\": 1,\n\t\"mbsky.com\": 1,\n\t\"mc-test.com\": 1,\n\t\"mc0513.com\": 1,\n\t\"mc1314.com\": 1,\n\t\"mc361.com\": 1,\n\t\"mccet.com\": 1,\n\t\"mcchina.com\": 1,\n\t\"mcmbaobao.com\": 1,\n\t\"mcmqyc.com\": 1,\n\t\"mcshe.com\": 1,\n\t\"md379.com\": 1,\n\t\"mdjiaqi.com\": 1,\n\t\"mdjmzj.com\": 1,\n\t\"mdvoo.com\": 1,\n\t\"meadin.com\": 1,\n\t\"mechr.com\": 1,\n\t\"mecjob.com\": 1,\n\t\"med126.com\": 1,\n\t\"med518.com\": 1,\n\t\"med66.com\": 1,\n\t\"medejob.com\": 1,\n\t\"mediaplex.com\": 1,\n\t\"mediav.com\": 1,\n\t\"medrc.net\": 1,\n\t\"meerlove.com\": 1,\n\t\"meet99.com\": 1,\n\t\"mefun.com\": 1,\n\t\"megong.com\": 1,\n\t\"mei-pan.com\": 1,\n\t\"meidebi.com\": 1,\n\t\"meidianwang.com\": 1,\n\t\"meiguoshenpo.com\": 1,\n\t\"meihua.info\": 1,\n\t\"meijing.com\": 1,\n\t\"meijitea.com\": 1,\n\t\"meiju.la\": 1,\n\t\"meijugou.com\": 1,\n\t\"meijw.com\": 1,\n\t\"meilele.com\": 1,\n\t\"meilijia.com\": 1,\n\t\"meiling.com\": 1,\n\t\"meilishi.com\": 1,\n\t\"meilishuo.com\": 1,\n\t\"meilishuo.net\": 1,\n\t\"meiliy.com\": 1,\n\t\"meimeidu.com\": 1,\n\t\"meimingteng.com\": 1,\n\t\"meinv.com\": 1,\n\t\"meinvpo.com\": 1,\n\t\"meipai.com\": 1,\n\t\"meipo360.com\": 1,\n\t\"meishanjob.com\": 1,\n\t\"meishanren.com\": 1,\n\t\"meishi.cc\": 1,\n\t\"meishichina.com\": 1,\n\t\"meishij.net\": 1,\n\t\"meishimeike.com\": 1,\n\t\"meishitui.com\": 1,\n\t\"meishurencai.com\": 1,\n\t\"meishuwang.net\": 1,\n\t\"meitantong.com\": 1,\n\t\"meitanwang.com\": 1,\n\t\"meitu.com\": 1,\n\t\"meituan.com\": 1,\n\t\"meituan.net\": 1,\n\t\"meitudata.com\": 1,\n\t\"meituyuan.com\": 1,\n\t\"meiwei123.com\": 1,\n\t\"meiwenting.com\": 1,\n\t\"meixun.org\": 1,\n\t\"meiyanqiangyi.com\": 1,\n\t\"meizhan.com\": 1,\n\t\"meizhou.com\": 1,\n\t\"meizu.com\": 1,\n\t\"meizuhui.com\": 1,\n\t\"mellk.com\": 1,\n\t\"memall360.com\": 1,\n\t\"mengpakezhan.com\": 1,\n\t\"mengyoo.com\": 1,\n\t\"mengzhou.com\": 1,\n\t\"menkou.com\": 1,\n\t\"menred.com\": 1,\n\t\"menwww.com\": 1,\n\t\"menye.com\": 1,\n\t\"mepfair.com\": 1,\n\t\"mepprice.com\": 1,\n\t\"metal35.com\": 1,\n\t\"metalchina.com\": 1,\n\t\"meyol.com\": 1,\n\t\"mf08s.com\": 1,\n\t\"mf528.com\": 1,\n\t\"mfcad.com\": 1,\n\t\"mffanwen.com\": 1,\n\t\"mfjzs.com\": 1,\n\t\"mfmf100.com\": 1,\n\t\"mfqyw.com\": 1,\n\t\"mfunz.com\": 1,\n\t\"mfw365.com\": 1,\n\t\"mg886.com\": 1,\n\t\"mgbm.net\": 1,\n\t\"mggzw.com\": 1,\n\t\"mgyapp.com\": 1,\n\t\"mgyun.com\": 1,\n\t\"mh163k.com\": 1,\n\t\"mhdenglish.com\": 1,\n\t\"mhimg.com\": 1,\n\t\"mi-img.com\": 1,\n\t\"mi.com\": 1,\n\t\"mi700.com\": 1,\n\t\"mian4.com\": 1,\n\t\"mian4.net\": 1,\n\t\"mianbao.com\": 1,\n\t\"mianfeiic.com\": 1,\n\t\"mianhuatang.cc\": 1,\n\t\"miantuanwang.com\": 1,\n\t\"mianyangauto.com\": 1,\n\t\"miaogu.com\": 1,\n\t\"miaokenet.com\": 1,\n\t\"miaomudi.com\": 1,\n\t\"miaomuzhan.com\": 1,\n\t\"miaopai.com\": 1,\n\t\"miaotiao.com\": 1,\n\t\"miaozhen.com\": 1,\n\t\"micamika.com\": 1,\n\t\"microsci.com\": 1,\n\t\"microsoft.com\": 1,\n\t\"midea.com\": 1,\n\t\"mier123.com\": 1,\n\t\"miercn.com\": 1,\n\t\"miit.cc\": 1,\n\t\"mikecrm.com\": 1,\n\t\"milan-bride.com\": 1,\n\t\"milankezhan.com\": 1,\n\t\"milanvip.com\": 1,\n\t\"milchina.com\": 1,\n\t\"miliao.com\": 1,\n\t\"milnews.com\": 1,\n\t\"milnews2.com\": 1,\n\t\"milzx.com\": 1,\n\t\"mimajs.com\": 1,\n\t\"mimimama.com\": 1,\n\t\"mimiwan.com\": 1,\n\t\"mine168.com\": 1,\n\t\"minesjob.com\": 1,\n\t\"mingdejx.com\": 1,\n\t\"minggou.com\": 1,\n\t\"minghong88.com\": 1,\n\t\"mingjian.com\": 1,\n\t\"mingluji.com\": 1,\n\t\"mingong123.com\": 1,\n\t\"mingshiedu.com\": 1,\n\t\"mingshitang.com\": 1,\n\t\"mingxing.com\": 1,\n\t\"mingxingku.com\": 1,\n\t\"mingyihui.net\": 1,\n\t\"mingyue.com\": 1,\n\t\"mingyuege.com\": 1,\n\t\"mingzhurc.com\": 1,\n\t\"minhang.com\": 1,\n\t\"mining120.com\": 1,\n\t\"mininghr.com\": 1,\n\t\"minjiangrc.com\": 1,\n\t\"minjianyishu.net\": 1,\n\t\"minnandianshang.com\": 1,\n\t\"minshengart.com\": 1,\n\t\"minshenglife.com\": 1,\n\t\"minzhujie.com\": 1,\n\t\"miomio.tv\": 1,\n\t\"mipang.com\": 1,\n\t\"mirautomation.com\": 1,\n\t\"mirosoundvision.com\": 1,\n\t\"misall.com\": 1,\n\t\"missku.com\": 1,\n\t\"missyuan.com\": 1,\n\t\"missyuan.net\": 1,\n\t\"mituku.com\": 1,\n\t\"miui.com\": 1,\n\t\"miyucun.com\": 1,\n\t\"mizhe.com\": 1,\n\t\"mj37.com\": 1,\n\t\"mjceo.com\": 1,\n\t\"mjcl.net\": 1,\n\t\"mjdec.com\": 1,\n\t\"mjmjm.com\": 1,\n\t\"mjoys.com\": 1,\n\t\"mjqy.com\": 1,\n\t\"mjrcw.com\": 1,\n\t\"mkaq.org\": 1,\n\t\"mkxk.com\": 1,\n\t\"mkzhan.com\": 1,\n\t\"mlbuy.com\": 1,\n\t\"mlctsrq.com\": 1,\n\t\"mllj.net\": 1,\n\t\"mlm114.com\": 1,\n\t\"mlt01.com\": 1,\n\t\"mm111.net\": 1,\n\t\"mmall.com\": 1,\n\t\"mmarket.com\": 1,\n\t\"mmbang.com\": 1,\n\t\"mmbang.info\": 1,\n\t\"mmfj.com\": 1,\n\t\"mmgogo.com\": 1,\n\t\"mmhn.net\": 1,\n\t\"mmimm.com\": 1,\n\t\"mmjyw.com\": 1,\n\t\"mmrcw.com\": 1,\n\t\"mmscsw.org\": 1,\n\t\"mmsfw.com\": 1,\n\t\"mmstat.com\": 1,\n\t\"mmstw.com\": 1,\n\t\"mmwan.com\": 1,\n\t\"mmxq.net\": 1,\n\t\"mmyouxi.com\": 1,\n\t\"mmyuer.com\": 1,\n\t\"mmzh.com\": 1,\n\t\"mn520.cc\": 1,\n\t\"mnkyy.com\": 1,\n\t\"mnlsbj.com\": 1,\n\t\"mnrb.net\": 1,\n\t\"mnsfh.com\": 1,\n\t\"mnwan.com\": 1,\n\t\"mnwww.com\": 1,\n\t\"mob.com\": 1,\n\t\"mobanku.com\": 1,\n\t\"mobanwang.com\": 1,\n\t\"mobao.com\": 1,\n\t\"mobile-dad.com\": 1,\n\t\"mobiletalkclub.com\": 1,\n\t\"mobiletrain.org\": 1,\n\t\"modian.com\": 1,\n\t\"moejam.com\": 1,\n\t\"mofang.com\": 1,\n\t\"mofangge.com\": 1,\n\t\"mogujie.com\": 1,\n\t\"mohe.cc\": 1,\n\t\"mojichina.com\": 1,\n\t\"mokaxiu.com\": 1,\n\t\"moke8.com\": 1,\n\t\"moko.cc\": 1,\n\t\"mokylin.com\": 1,\n\t\"moliuxiang.com\": 1,\n\t\"moloong.com\": 1,\n\t\"molychina.com\": 1,\n\t\"momachina.com\": 1,\n\t\"momihouse.com\": 1,\n\t\"momo35.com\": 1,\n\t\"momolili.com\": 1,\n\t\"monhr.com\": 1,\n\t\"monteamor.com\": 1,\n\t\"monternet.com\": 1,\n\t\"montesea.com\": 1,\n\t\"moobuu.com\": 1,\n\t\"moofor.com\": 1,\n\t\"mookie1.com\": 1,\n\t\"moon777.com\": 1,\n\t\"moonbasa.com\": 1,\n\t\"mop.com\": 1,\n\t\"moshou.com\": 1,\n\t\"mosopower.com\": 1,\n\t\"mosso.com\": 1,\n\t\"mostrend.com\": 1,\n\t\"motherbuy.com\": 1,\n\t\"motie.com\": 1,\n\t\"motieimg.com\": 1,\n\t\"motnt.com\": 1,\n\t\"motorchina.com\": 1,\n\t\"moukao.com\": 1,\n\t\"mouldbbs.com\": 1,\n\t\"mouldfair.net\": 1,\n\t\"mouldintl.com\": 1,\n\t\"mouldjob.com\": 1,\n\t\"mouldu.com\": 1,\n\t\"moutaichina.com\": 1,\n\t\"moveredu.com\": 1,\n\t\"mowuhe.com\": 1,\n\t\"moyoutang.com\": 1,\n\t\"moyoyo.com\": 1,\n\t\"mozilla.org\": 1,\n\t\"mozillaonline.com\": 1,\n\t\"mpbang.com\": 1,\n\t\"mpdsj.com\": 1,\n\t\"mplife.com\": 1,\n\t\"mppmpp.com\": 1,\n\t\"mquanquan.com\": 1,\n\t\"mrgushi.com\": 1,\n\t\"mrmfzp.com\": 1,\n\t\"mrrencai.com\": 1,\n\t\"mrwpx.com\": 1,\n\t\"mrzpw.com\": 1,\n\t\"mrzswang.com\": 1,\n\t\"ms0538.com\": 1,\n\t\"ms315.com\": 1,\n\t\"ms6666111.com\": 1,\n\t\"mscbsc.com\": 1,\n\t\"msddp.com\": 1,\n\t\"msddt.com\": 1,\n\t\"msgjj.com\": 1,\n\t\"mshw.net\": 1,\n\t\"msn.com\": 1,\n\t\"msq86.com\": 1,\n\t\"msrfc.com\": 1,\n\t\"mssqw.com\": 1,\n\t\"mstxx.com\": 1,\n\t\"msw86.com\": 1,\n\t\"msxf.net\": 1,\n\t\"mszxyh.com\": 1,\n\t\"mtime.com\": 1,\n\t\"mtjk.com\": 1,\n\t\"mtklw.com\": 1,\n\t\"mtnets.com\": 1,\n\t\"mttang.com\": 1,\n\t\"mtv123.com\": 1,\n\t\"mtw001.com\": 1,\n\t\"mtzkz.com\": 1,\n\t\"much001.com\": 1,\n\t\"mudanpin.com\": 1,\n\t\"mumayi.com\": 1,\n\t\"muniao.com\": 1,\n\t\"musestudio.net\": 1,\n\t\"musicchina-expo.com\": 1,\n\t\"muyang.com\": 1,\n\t\"muyee.com\": 1,\n\t\"muying.com\": 1,\n\t\"muyingjie.com\": 1,\n\t\"muyingzhijia.com\": 1,\n\t\"muyuqq.com\": 1,\n\t\"muzhibus.com\": 1,\n\t\"muzhiwan.com\": 1,\n\t\"muzisoft.com\": 1,\n\t\"mvomvo.com\": 1,\n\t\"mvxz.net\": 1,\n\t\"mw1950.com\": 1,\n\t\"mwrf.net\": 1,\n\t\"mwrfchina.org\": 1,\n\t\"mx175.com\": 1,\n\t\"mxhichina.com\": 1,\n\t\"mxpcp.com\": 1,\n\t\"mxwz.com\": 1,\n\t\"mxwz.net\": 1,\n\t\"my-zz.com\": 1,\n\t\"my.cl.ly\": 1,\n\t\"my0511.com\": 1,\n\t\"my0538.com\": 1,\n\t\"my0575.net\": 1,\n\t\"my0768.com\": 1,\n\t\"my0792.com\": 1,\n\t\"my0813.com\": 1,\n\t\"my12345.com\": 1,\n\t\"my399.com\": 1,\n\t\"my4399.com\": 1,\n\t\"my71.com\": 1,\n\t\"myantu.com\": 1,\n\t\"myapp.com\": 1,\n\t\"mybjx.net\": 1,\n\t\"mybulkstock.com\": 1,\n\t\"mybuxiu.com\": 1,\n\t\"mybwu.com\": 1,\n\t\"mybxg.com\": 1,\n\t\"mycar168.com\": 1,\n\t\"mycar168.net\": 1,\n\t\"mycarbbs.com\": 1,\n\t\"mychefang.com\": 1,\n\t\"mychemjob.com\": 1,\n\t\"myclub2.com\": 1,\n\t\"myclubmall.com\": 1,\n\t\"mycollect.net\": 1,\n\t\"mydiyclub.com\": 1,\n\t\"mydns114.net\": 1,\n\t\"mydrivers.com\": 1,\n\t\"myepjob.com\": 1,\n\t\"myf6.com\": 1,\n\t\"myfule.com\": 1,\n\t\"myfun7.com\": 1,\n\t\"mygame66.com\": 1,\n\t\"mygymchina.com\": 1,\n\t\"myhack58.com\": 1,\n\t\"myhm.org\": 1,\n\t\"myhostadmin.net\": 1,\n\t\"myinsbroker.com\": 1,\n\t\"myir-tech.com\": 1,\n\t\"myjianzhu.com\": 1,\n\t\"myjiaxiang.com\": 1,\n\t\"myjmw.com\": 1,\n\t\"myjob.com\": 1,\n\t\"myjob123.net\": 1,\n\t\"myluban.com\": 1,\n\t\"mynfd.com\": 1,\n\t\"myoneone.com\": 1,\n\t\"mypake.com\": 1,\n\t\"mypethome.com\": 1,\n\t\"mypharma.com\": 1,\n\t\"mypm.net\": 1,\n\t\"mypxb.com\": 1,\n\t\"myqcloud.com\": 1,\n\t\"myqtyy.com\": 1,\n\t\"myra2.com\": 1,\n\t\"myrb.net\": 1,\n\t\"myshipjob.com\": 1,\n\t\"mysjtu.com\": 1,\n\t\"mysodao.com\": 1,\n\t\"mysteel.com\": 1,\n\t\"mysteel.net\": 1,\n\t\"mysteelcdn.com\": 1,\n\t\"mysteelcms.com\": 1,\n\t\"mysteelresearch.com\": 1,\n\t\"mysteelweekly.com\": 1,\n\t\"mysvw.com\": 1,\n\t\"mytaofang.com\": 1,\n\t\"mytaofun.com\": 1,\n\t\"mytophome.com\": 1,\n\t\"myubbs.com\": 1,\n\t\"myverydz.com\": 1,\n\t\"mywood.cc\": 1,\n\t\"myyouse.com\": 1,\n\t\"myyule.com\": 1,\n\t\"myzaker.com\": 1,\n\t\"myzcm.com\": 1,\n\t\"myzhidao.com\": 1,\n\t\"myzx365.com\": 1,\n\t\"mz001.com\": 1,\n\t\"mz6.net\": 1,\n\t\"mzche.com\": 1,\n\t\"mzhw.com\": 1,\n\t\"mzjia.com\": 1,\n\t\"mzklg.com\": 1,\n\t\"mzrcw.com\": 1,\n\t\"mzsky.cc\": 1,\n\t\"mzstatic.com\": 1,\n\t\"mzwok.com\": 1,\n\t\"mzyfz.com\": 1,\n\t\"n21.cc\": 1,\n\t\"n371.com\": 1,\n\t\"na597.com\": 1,\n\t\"nabel.cc\": 1,\n\t\"nahuo.com\": 1,\n\t\"nai2.com\": 1,\n\t\"naitang.com\": 1,\n\t\"nalichi.com\": 1,\n\t\"naliwan.com\": 1,\n\t\"name321.net\": 1,\n\t\"namoc.org\": 1,\n\t\"nanbeiyou.com\": 1,\n\t\"nandu.com\": 1,\n\t\"nanhunnvjia.com\": 1,\n\t\"nanjing2014.org\": 1,\n\t\"nanjob.com\": 1,\n\t\"nanlue.com\": 1,\n\t\"nanningjie.com\": 1,\n\t\"nanpw.com\": 1,\n\t\"nanrenwo.net\": 1,\n\t\"nanrenzhuang.net\": 1,\n\t\"nansha365.com\": 1,\n\t\"nanshikaoyan.com\": 1,\n\t\"nanshiw.com\": 1,\n\t\"nantaihu.com\": 1,\n\t\"nanyuenews.com\": 1,\n\t\"nanzhao1.com\": 1,\n\t\"nanzhaohm.com\": 1,\n\t\"naradafoundation.org\": 1,\n\t\"narkii.com\": 1,\n\t\"narutom.com\": 1,\n\t\"naxue.com\": 1,\n\t\"naxww.com\": 1,\n\t\"nayao.com\": 1,\n\t\"nazhengshu.com\": 1,\n\t\"nb-rcw.com\": 1,\n\t\"nb-water.com\": 1,\n\t\"nb119.com\": 1,\n\t\"nb160.com\": 1,\n\t\"nb7000.net\": 1,\n\t\"nba.com\": 1,\n\t\"nbark.com\": 1,\n\t\"nbbltv.com\": 1,\n\t\"nbbus.com\": 1,\n\t\"nbccts.com\": 1,\n\t\"nbcei.com\": 1,\n\t\"nbch2sc.com\": 1,\n\t\"nbchem.com\": 1,\n\t\"nbcoop.com\": 1,\n\t\"nbcqjy.org\": 1,\n\t\"nbcredit.net\": 1,\n\t\"nbcsbb.org\": 1,\n\t\"nbctsg.com\": 1,\n\t\"nbcyy.com\": 1,\n\t\"nbebi.com\": 1,\n\t\"nbedi.com\": 1,\n\t\"nbfce.com\": 1,\n\t\"nbgj.net\": 1,\n\t\"nbgjj.com\": 1,\n\t\"nbgy.com\": 1,\n\t\"nbgy.org\": 1,\n\t\"nbhky.com\": 1,\n\t\"nbidea.com\": 1,\n\t\"nbip.net\": 1,\n\t\"nbjczx.com\": 1,\n\t\"nbjmrc.com\": 1,\n\t\"nbks.net\": 1,\n\t\"nbmovie.com\": 1,\n\t\"nbmtw.com\": 1,\n\t\"nbmyhome.com\": 1,\n\t\"nbol.net\": 1,\n\t\"nbow.net\": 1,\n\t\"nbptweb.net\": 1,\n\t\"nbqcrl.com\": 1,\n\t\"nbqfc.com\": 1,\n\t\"nbradio.com\": 1,\n\t\"nbrcw.com\": 1,\n\t\"nbrczp.com\": 1,\n\t\"nbsz.com\": 1,\n\t\"nbtarena.com\": 1,\n\t\"nbtelecom.com\": 1,\n\t\"nbtjzx.com\": 1,\n\t\"nbwater.com\": 1,\n\t\"nbweekly.com\": 1,\n\t\"nbxsrc.com\": 1,\n\t\"nbyouth.com\": 1,\n\t\"nbzhrc.com\": 1,\n\t\"ncacg.org\": 1,\n\t\"ncce.biz\": 1,\n\t\"ncdiy.com\": 1,\n\t\"ncfz.com\": 1,\n\t\"ncghj.com\": 1,\n\t\"nchdz.com\": 1,\n\t\"nchqw.com\": 1,\n\t\"ncielts.com\": 1,\n\t\"nciyuan.com\": 1,\n\t\"ncoto.com\": 1,\n\t\"ncpqh.com\": 1,\n\t\"ncqiche.com\": 1,\n\t\"ncrczpw.com\": 1,\n\t\"nctudi.com\": 1,\n\t\"nctzb.org\": 1,\n\t\"ncvt.net\": 1,\n\t\"ncxb.com\": 1,\n\t\"ncxww.com\": 1,\n\t\"nczl.com\": 1,\n\t\"nczx8.com\": 1,\n\t\"nd090.com\": 1,\n\t\"nd597.com\": 1,\n\t\"nddaily.com\": 1,\n\t\"ndfang.com\": 1,\n\t\"ndgjj.com\": 1,\n\t\"ndjczx.com\": 1,\n\t\"ndrcw.com\": 1,\n\t\"ndt88.com\": 1,\n\t\"nduoa.com\": 1,\n\t\"nduotuan.com\": 1,\n\t\"ne21.com\": 1,\n\t\"ne365.com\": 1,\n\t\"ne51.com\": 1,\n\t\"ne56.com\": 1,\n\t\"nec.cc\": 1,\n\t\"necoal.com\": 1,\n\t\"nectar-farm.com\": 1,\n\t\"neeu.com\": 1,\n\t\"nei-mao.com\": 1,\n\t\"neiee.com\": 1,\n\t\"neihan8.com\": 1,\n\t\"neihuang.cc\": 1,\n\t\"neikupp.com\": 1,\n\t\"neimengrc.com\": 1,\n\t\"neiscn.org\": 1,\n\t\"neitui.me\": 1,\n\t\"nengyuan.cc\": 1,\n\t\"nengyuan.com\": 1,\n\t\"nengyuan.net\": 1,\n\t\"nenqiu.com\": 1,\n\t\"neo-neon.com\": 1,\n\t\"neonan.com\": 1,\n\t\"nerjob.com\": 1,\n\t\"net-eye.net\": 1,\n\t\"net114.com\": 1,\n\t\"netandtv.com\": 1,\n\t\"netat.net\": 1,\n\t\"netbai.com\": 1,\n\t\"netbian.com\": 1,\n\t\"netease.com\": 1,\n\t\"netecweb.com\": 1,\n\t\"netentsec.com\": 1,\n\t\"netsun.com\": 1,\n\t\"networkbrand.com\": 1,\n\t\"neupioneer.com\": 1,\n\t\"new-ci.com\": 1,\n\t\"new-motherhood.com\": 1,\n\t\"new123.com\": 1,\n\t\"new7.com\": 1,\n\t\"newacer.com\": 1,\n\t\"newaq.com\": 1,\n\t\"newasp.net\": 1,\n\t\"newcger.com\": 1,\n\t\"newchannel.org\": 1,\n\t\"newexpo.com\": 1,\n\t\"newft.com\": 1,\n\t\"newhua.com\": 1,\n\t\"newman.mobi\": 1,\n\t\"neworiental-k12.org\": 1,\n\t\"neworiental.org\": 1,\n\t\"neworientalgroup.org\": 1,\n\t\"news-chtf.com\": 1,\n\t\"news0635.com\": 1,\n\t\"news18a.com\": 1,\n\t\"newsccn.com\": 1,\n\t\"newscv.com\": 1,\n\t\"newseasoft.com\": 1,\n\t\"newshainan.com\": 1,\n\t\"newshs.com\": 1,\n\t\"newsmth.net\": 1,\n\t\"newsmy.com\": 1,\n\t\"newssc.org\": 1,\n\t\"newsxc.com\": 1,\n\t\"newsxy.com\": 1,\n\t\"newsyc.com\": 1,\n\t\"newtonghua.com\": 1,\n\t\"newyx.net\": 1,\n\t\"newzealand.com\": 1,\n\t\"newzgc.com\": 1,\n\t\"newzhongyuan.com\": 1,\n\t\"nextsee.com\": 1,\n\t\"nfcmag.com\": 1,\n\t\"nfcnw.com\": 1,\n\t\"nffair.com\": 1,\n\t\"nfinv.com\": 1,\n\t\"nfmedia.com\": 1,\n\t\"nfpeople.com\": 1,\n\t\"nfrencai.com\": 1,\n\t\"nftec.com\": 1,\n\t\"nfwin.com\": 1,\n\t\"nfypw.com\": 1,\n\t\"ng114.net\": 1,\n\t\"ngacn.cc\": 1,\n\t\"ngbbs.com\": 1,\n\t\"ngfang.com\": 1,\n\t\"ngocn.net\": 1,\n\t\"ngotcm.com\": 1,\n\t\"nhaidu.com\": 1,\n\t\"nhcsw.com\": 1,\n\t\"nhnw.com\": 1,\n\t\"nhvisit.com\": 1,\n\t\"nhxxg.com\": 1,\n\t\"nhzj.com\": 1,\n\t\"niangyuan.com\": 1,\n\t\"nianw.com\": 1,\n\t\"niaogebiji.com\": 1,\n\t\"nicai.com\": 1,\n\t\"niceloo.com\": 1,\n\t\"nicocn.com\": 1,\n\t\"niczy.com\": 1,\n\t\"night9.com\": 1,\n\t\"nihaowang.com\": 1,\n\t\"nike.com\": 1,\n\t\"nikefans.com\": 1,\n\t\"nimtt.com\": 1,\n\t\"ningbo-airport.com\": 1,\n\t\"ningbobb.com\": 1,\n\t\"ningbochina.com\": 1,\n\t\"ningxiangrc.com\": 1,\n\t\"ninicat.com\": 1,\n\t\"ninxun.com\": 1,\n\t\"nipic.com\": 1,\n\t\"niubb.net\": 1,\n\t\"niuchengnews.com\": 1,\n\t\"niuchengrc.com\": 1,\n\t\"niuchengwang.com\": 1,\n\t\"niutrip.com\": 1,\n\t\"niutuku.com\": 1,\n\t\"niuwan.com\": 1,\n\t\"niuyang98.com\": 1,\n\t\"niwodai.com\": 1,\n\t\"nixiba.com\": 1,\n\t\"nj110.com\": 1,\n\t\"nj110.net\": 1,\n\t\"nj127.com\": 1,\n\t\"njcgs.com\": 1,\n\t\"njcqjy.com\": 1,\n\t\"njcw.com\": 1,\n\t\"njd1.com\": 1,\n\t\"njdfwb.com\": 1,\n\t\"njgqzs.com\": 1,\n\t\"njhaiwai.com\": 1,\n\t\"njiairport.com\": 1,\n\t\"njjsyy.com\": 1,\n\t\"njlongre.com\": 1,\n\t\"njltmp.com\": 1,\n\t\"njmama.com\": 1,\n\t\"njmuseum.com\": 1,\n\t\"njobt.com\": 1,\n\t\"njprice.com\": 1,\n\t\"njrsks.com\": 1,\n\t\"njrsrc.com\": 1,\n\t\"njsdy.com\": 1,\n\t\"njtarena.com\": 1,\n\t\"njtarena.net\": 1,\n\t\"njtctg.com\": 1,\n\t\"njutcie.com\": 1,\n\t\"njxg.com\": 1,\n\t\"njxzcy.com\": 1,\n\t\"njycyj.com\": 1,\n\t\"nk96728.com\": 1,\n\t\"nksjjxh.com\": 1,\n\t\"nlypx.com\": 1,\n\t\"nmcqjy.com\": 1,\n\t\"nmgcoop.org\": 1,\n\t\"nmgexpo.com\": 1,\n\t\"nmgfic.com\": 1,\n\t\"nmgjdxy.com\": 1,\n\t\"nmgjrw.com\": 1,\n\t\"nmglabs.com\": 1,\n\t\"nmgmt.mobi\": 1,\n\t\"nmgrc.com\": 1,\n\t\"nmgwww.com\": 1,\n\t\"nmgzkj.com\": 1,\n\t\"nmhbj.com\": 1,\n\t\"nmrcw.com\": 1,\n\t\"nmsti.com\": 1,\n\t\"nn600.com\": 1,\n\t\"nndme.com\": 1,\n\t\"nnfxcs.com\": 1,\n\t\"nngjj.com\": 1,\n\t\"nnhdqm.com\": 1,\n\t\"nnjob.com\": 1,\n\t\"nnmama.com\": 1,\n\t\"nnn666.com\": 1,\n\t\"nnnews.net\": 1,\n\t\"nntlj.com\": 1,\n\t\"nnwb.com\": 1,\n\t\"nnzgz.com\": 1,\n\t\"nnzp.com\": 1,\n\t\"no1w.com\": 1,\n\t\"noblepen.com\": 1,\n\t\"nongchengws.com\": 1,\n\t\"nongcun5.com\": 1,\n\t\"nongji1688.com\": 1,\n\t\"nongji360.com\": 1,\n\t\"nongjiayuan.org\": 1,\n\t\"nongjitong.com\": 1,\n\t\"nongjx.com\": 1,\n\t\"nongli.com\": 1,\n\t\"nongli.net\": 1,\n\t\"nongmiao.com\": 1,\n\t\"nongmintv.com\": 1,\n\t\"nongminzhuanye.com\": 1,\n\t\"nongrisheng.com\": 1,\n\t\"nongyao001.com\": 1,\n\t\"nongyerc.com\": 1,\n\t\"nongyezhan.net\": 1,\n\t\"nongzi100.com\": 1,\n\t\"nongzi360.com\": 1,\n\t\"nongzihr.com\": 1,\n\t\"noni.so\": 1,\n\t\"nonobank.com\": 1,\n\t\"nowamagic.net\": 1,\n\t\"nowec.com\": 1,\n\t\"nowscore.com\": 1,\n\t\"nowxue.com\": 1,\n\t\"np163.net\": 1,\n\t\"np5.com\": 1,\n\t\"np597.com\": 1,\n\t\"npcka.com\": 1,\n\t\"npckk.com\": 1,\n\t\"npcoop.com\": 1,\n\t\"npgjj.com\": 1,\n\t\"nphoto.net\": 1,\n\t\"npicp.com\": 1,\n\t\"npjt.com\": 1,\n\t\"npjy.com\": 1,\n\t\"npxzb.com\": 1,\n\t\"nrparking.com\": 1,\n\t\"nssd.org\": 1,\n\t\"nst666.com\": 1,\n\t\"nsw88.com\": 1,\n\t\"nsxia.com\": 1,\n\t\"nsy6.com\": 1,\n\t\"ntalker.com\": 1,\n\t\"ntgjj.com\": 1,\n\t\"nthfw.com\": 1,\n\t\"ntjob88.com\": 1,\n\t\"ntjoy.com\": 1,\n\t\"ntjxj.com\": 1,\n\t\"ntjy.net\": 1,\n\t\"ntrc.com\": 1,\n\t\"ntrgrcw.com\": 1,\n\t\"ntvimg.com\": 1,\n\t\"ntwenming.com\": 1,\n\t\"ntxx.net\": 1,\n\t\"nuandao.com\": 1,\n\t\"nuansou.com\": 1,\n\t\"nubb.com\": 1,\n\t\"nuli.org\": 1,\n\t\"nuo.cc\": 1,\n\t\"nuomi.com\": 1,\n\t\"nuozhan.com\": 1,\n\t\"nusrc.com\": 1,\n\t\"nuxue.com\": 1,\n\t\"nv43.com\": 1,\n\t\"nvrenfang.com\": 1,\n\t\"nvsheng.com\": 1,\n\t\"nvxing163.com\": 1,\n\t\"nwyhw.com\": 1,\n\t\"nx28.com\": 1,\n\t\"nxass.com\": 1,\n\t\"nxcoop.com\": 1,\n\t\"nxdzkj.com\": 1,\n\t\"nxedu.com\": 1,\n\t\"nxfang.com\": 1,\n\t\"nxflcp.com\": 1,\n\t\"nxfwz.com\": 1,\n\t\"nxgcw.com\": 1,\n\t\"nxgsl.com\": 1,\n\t\"nxkongtiao.com\": 1,\n\t\"nxnba.com\": 1,\n\t\"nxnews.net\": 1,\n\t\"nxng.net\": 1,\n\t\"nxnk.com\": 1,\n\t\"nxskl.net\": 1,\n\t\"nxsks.com\": 1,\n\t\"nxycedu.com\": 1,\n\t\"nxzgh.com\": 1,\n\t\"nxzpt.com\": 1,\n\t\"nxzwnews.net\": 1,\n\t\"nxzyk.com\": 1,\n\t\"ny0538.com\": 1,\n\t\"ny1988.com\": 1,\n\t\"ny3721.com\": 1,\n\t\"ny8888.com\": 1,\n\t\"nyato.com\": 1,\n\t\"nyedu.net\": 1,\n\t\"nyipcn.com\": 1,\n\t\"nyist.net\": 1,\n\t\"nyjjchina.com\": 1,\n\t\"nyljw.com\": 1,\n\t\"nypxw.com\": 1,\n\t\"nyrencai.com\": 1,\n\t\"nysjw.com\": 1,\n\t\"nyxzp.com\": 1,\n\t\"nyycw.com\": 1,\n\t\"nyyintong.com\": 1,\n\t\"nz165.com\": 1,\n\t\"nz86.com\": 1,\n\t\"nz99.net\": 1,\n\t\"nzczq.com\": 1,\n\t\"nzjsw.com\": 1,\n\t\"nzstatic.com\": 1,\n\t\"nzw-china.com\": 1,\n\t\"o-star.cc\": 1,\n\t\"oa8000.com\": 1,\n\t\"oacio.com\": 1,\n\t\"oadz.com\": 1,\n\t\"ob1000.com\": 1,\n\t\"ob1000.net\": 1,\n\t\"obolee.com\": 1,\n\t\"ocar.tv\": 1,\n\t\"oceanchina.com\": 1,\n\t\"oceanol.com\": 1,\n\t\"ocoal.com\": 1,\n\t\"octc.com\": 1,\n\t\"odourchina.com\": 1,\n\t\"oeeee.com\": 1,\n\t\"oem17.com\": 1,\n\t\"oemol.com\": 1,\n\t\"oemresource.com\": 1,\n\t\"oeofo.com\": 1,\n\t\"oephp.com\": 1,\n\t\"ofcard.com\": 1,\n\t\"offcn.com\": 1,\n\t\"officeask.com\": 1,\n\t\"officebc.com\": 1,\n\t\"officecd.net\": 1,\n\t\"officese.com\": 1,\n\t\"ofpay.com\": 1,\n\t\"ofuns.com\": 1,\n\t\"ofweek.com\": 1,\n\t\"ofzx.com\": 1,\n\t\"ogoqz.com\": 1,\n\t\"oh100.com\": 1,\n\t\"oho168.com\": 1,\n\t\"ohqly.com\": 1,\n\t\"oi22.com\": 1,\n\t\"oicq88.com\": 1,\n\t\"oilchem.net\": 1,\n\t\"oilequipcn.com\": 1,\n\t\"oilhr.com\": 1,\n\t\"oiwm.com\": 1,\n\t\"ok0559.com\": 1,\n\t\"ok0737.com\": 1,\n\t\"ok11.com\": 1,\n\t\"ok123.tv\": 1,\n\t\"ok165.com\": 1,\n\t\"ok87.com\": 1,\n\t\"okbao.com\": 1,\n\t\"okbuy.com\": 1,\n\t\"okbuycdn.com\": 1,\n\t\"okeycar.com\": 1,\n\t\"okfh.com\": 1,\n\t\"okgj.com\": 1,\n\t\"okhan.net\": 1,\n\t\"okhere.net\": 1,\n\t\"okhqb.com\": 1,\n\t\"oklx.com\": 1,\n\t\"okmaidan.com\": 1,\n\t\"okmeeting.com\": 1,\n\t\"okmessi.com\": 1,\n\t\"okmk.com\": 1,\n\t\"okooo.com\": 1,\n\t\"okoooimg.com\": 1,\n\t\"oksat.org\": 1,\n\t\"okwanwan.com\": 1,\n\t\"okzhuhai.com\": 1,\n\t\"okzjj.com\": 1,\n\t\"ol-img.com\": 1,\n\t\"olcdn.com\": 1,\n\t\"oldcp.com\": 1,\n\t\"older99.com\": 1,\n\t\"oledw.com\": 1,\n\t\"olyun.com\": 1,\n\t\"om-f.com\": 1,\n\t\"ometal.com\": 1,\n\t\"onccc.com\": 1,\n\t\"one101.com\": 1,\n\t\"one79.com\": 1,\n\t\"onebuild.net\": 1,\n\t\"onegreen.net\": 1,\n\t\"onekao.com\": 1,\n\t\"onekeyrom.com\": 1,\n\t\"onepiecer.com\": 1,\n\t\"oneplusbbs.com\": 1,\n\t\"onetad.com\": 1,\n\t\"onfun.net\": 1,\n\t\"onjobedu.com\": 1,\n\t\"onlinedown.net\": 1,\n\t\"onlinesjtu.com\": 1,\n\t\"onlylady.com\": 1,\n\t\"onlyonly.net\": 1,\n\t\"onlyred.net\": 1,\n\t\"oo6s.com\": 1,\n\t\"oocheoo.com\": 1,\n\t\"oodii.com\": 1,\n\t\"ooomm.com\": 1,\n\t\"ooopic.com\": 1,\n\t\"ooqiu.com\": 1,\n\t\"oosyoo.com\": 1,\n\t\"opbbs.net\": 1,\n\t\"opda.com\": 1,\n\t\"open-open.com\": 1,\n\t\"openhw.org\": 1,\n\t\"openwbs.com\": 1,\n\t\"operachina.com\": 1,\n\t\"opfun.org\": 1,\n\t\"oppein.com\": 1,\n\t\"opplandcorp.com\": 1,\n\t\"opple.com\": 1,\n\t\"optaim.com\": 1,\n\t\"oralcollege.net\": 1,\n\t\"oralpractice.com\": 1,\n\t\"oranpage.com\": 1,\n\t\"orgcc.com\": 1,\n\t\"orggx.com\": 1,\n\t\"orgnitu.com\": 1,\n\t\"orgnitu.net\": 1,\n\t\"originclean.com\": 1,\n\t\"orsoon.com\": 1,\n\t\"oschina.net\": 1,\n\t\"ostudytour.com\": 1,\n\t\"ot51.com\": 1,\n\t\"otwan.com\": 1,\n\t\"ou99.com\": 1,\n\t\"oubohao.com\": 1,\n\t\"oujiangrc.com\": 1,\n\t\"oupeng.com\": 1,\n\t\"ourfreesky.org\": 1,\n\t\"ourgame.com\": 1,\n\t\"ourpanda.com\": 1,\n\t\"ourseo.net\": 1,\n\t\"ourtra.com\": 1,\n\t\"ourxun.com\": 1,\n\t\"ouryao.com\": 1,\n\t\"oussko.com\": 1,\n\t\"outlets365.com\": 1,\n\t\"ouwan.com\": 1,\n\t\"ouyaagri.com\": 1,\n\t\"ouyaoxiazai.com\": 1,\n\t\"ouyicg.com\": 1,\n\t\"ovkj.org\": 1,\n\t\"ovupre.com\": 1,\n\t\"oxbridgedu.org\": 1,\n\t\"oyehi.com\": 1,\n\t\"oynkyy.com\": 1,\n\t\"ozhibao.com\": 1,\n\t\"p-e-china.com\": 1,\n\t\"p44.com\": 1,\n\t\"p5w.net\": 1,\n\t\"p9p9.cc\": 1,\n\t\"pache.com\": 1,\n\t\"packceo.com\": 1,\n\t\"packrc.com\": 1,\n\t\"padh.net\": 1,\n\t\"padsj.com\": 1,\n\t\"padtt.com\": 1,\n\t\"pafj.net\": 1,\n\t\"pagechoice.net\": 1,\n\t\"pahaoche.com\": 1,\n\t\"pahou.com\": 1,\n\t\"paidai.com\": 1,\n\t\"paidui.com\": 1,\n\t\"paihang360.com\": 1,\n\t\"paileduo.com\": 1,\n\t\"painb.com\": 1,\n\t\"paiorg.com\": 1,\n\t\"paipai.com\": 1,\n\t\"paipaiimg.com\": 1,\n\t\"paishoes.com\": 1,\n\t\"paixie.net\": 1,\n\t\"paizihao.net\": 1,\n\t\"paljw.com\": 1,\n\t\"pamss.net\": 1,\n\t\"panduola.com\": 1,\n\t\"panelook.com\": 1,\n\t\"panguso.com\": 1,\n\t\"panjiayuan.com\": 1,\n\t\"panjk.com\": 1,\n\t\"pansino-solutions.com\": 1,\n\t\"panzi.cc\": 1,\n\t\"panzz.com\": 1,\n\t\"paochefang.com\": 1,\n\t\"paojiao.com\": 1,\n\t\"paokoo.com\": 1,\n\t\"paopaoche.net\": 1,\n\t\"paopaoku.com\": 1,\n\t\"paoxue.com\": 1,\n\t\"paperopen.com\": 1,\n\t\"paperrater.net\": 1,\n\t\"paralworld.com\": 1,\n\t\"paratong.com\": 1,\n\t\"paris-bride.com\": 1,\n\t\"partinchina.com\": 1,\n\t\"passportmanagement.com\": 1,\n\t\"passxmu.com\": 1,\n\t\"patachina.org\": 1,\n\t\"paypal.com\": 1,\n\t\"pazx888.com\": 1,\n\t\"pc360.net\": 1,\n\t\"pc3w.com\": 1,\n\t\"pc4s.com\": 1,\n\t\"pc6.com\": 1,\n\t\"pc811.com\": 1,\n\t\"pc841.com\": 1,\n\t\"pcb818.com\": 1,\n\t\"pcbchinanet.com\": 1,\n\t\"pcbeta.com\": 1,\n\t\"pcbokjob.com\": 1,\n\t\"pcdown.net\": 1,\n\t\"pch-img.net\": 1,\n\t\"pchome.net\": 1,\n\t\"pcomic.net\": 1,\n\t\"pcpc.me\": 1,\n\t\"pcpc521.com\": 1,\n\t\"pcpop.com\": 1,\n\t\"pcrcw.net\": 1,\n\t\"pctowap.com\": 1,\n\t\"pczp.net\": 1,\n\t\"pdfangchan.com\": 1,\n\t\"pdshouse.com\": 1,\n\t\"pdsjob.org\": 1,\n\t\"pdsqcw.com\": 1,\n\t\"pdsxww.com\": 1,\n\t\"pdxx.net\": 1,\n\t\"pe-fund.com\": 1,\n\t\"pe168.com\": 1,\n\t\"pe51.com\": 1,\n\t\"pe898.com\": 1,\n\t\"peac-conf.org\": 1,\n\t\"pegjj.com\": 1,\n\t\"peixun.net\": 1,\n\t\"peixun22.com\": 1,\n\t\"peixunfei.com\": 1,\n\t\"peixuntong.com\": 1,\n\t\"peixuntop.com\": 1,\n\t\"pengchengrc.com\": 1,\n\t\"pengfu.com\": 1,\n\t\"pengfuw.com\": 1,\n\t\"penglaiu.com\": 1,\n\t\"pengpeng.com\": 1,\n\t\"pengrc.com\": 1,\n\t\"pengyou.com\": 1,\n\t\"pengzerencai.com\": 1,\n\t\"people258.com\": 1,\n\t\"peopleart.tv\": 1,\n\t\"peoplephoto.com\": 1,\n\t\"peoplerail.com\": 1,\n\t\"peryi.net\": 1,\n\t\"pethr.com\": 1,\n\t\"petzp.com\": 1,\n\t\"pf178.com\": 1,\n\t\"pfwang.com\": 1,\n\t\"pg369.com\": 1,\n\t\"ph-fc.com\": 1,\n\t\"ph2009.com\": 1,\n\t\"ph66.com\": 1,\n\t\"pharm1718.com\": 1,\n\t\"pharmjx.com\": 1,\n\t\"phb123.com\": 1,\n\t\"philips.com\": 1,\n\t\"phoenixtv.com\": 1,\n\t\"photops.com\": 1,\n\t\"photoshopcn.com\": 1,\n\t\"photosichuan.com\": 1,\n\t\"php100.com\": 1,\n\t\"php168.net\": 1,\n\t\"php186.com\": 1,\n\t\"phpchina.com\": 1,\n\t\"phpcoo.com\": 1,\n\t\"phpstat.net\": 1,\n\t\"phpwind.com\": 1,\n\t\"phpwind.net\": 1,\n\t\"phpyun.com\": 1,\n\t\"phvalue.org\": 1,\n\t\"phxzzx.org\": 1,\n\t\"phzfw.com\": 1,\n\t\"phzp.com\": 1,\n\t\"pianyifun.com\": 1,\n\t\"piao.com\": 1,\n\t\"piao88.com\": 1,\n\t\"piaojia.com\": 1,\n\t\"piaojin.com\": 1,\n\t\"piaoliang.com\": 1,\n\t\"pibaihui.com\": 1,\n\t\"picchealth.com\": 1,\n\t\"piedia.com\": 1,\n\t\"pifuyy.com\": 1,\n\t\"pig66.com\": 1,\n\t\"pigai.org\": 1,\n\t\"pigehr.com\": 1,\n\t\"pigerencai.com\": 1,\n\t\"pigpignet.com\": 1,\n\t\"pikadd.com\": 1,\n\t\"pimei.com\": 1,\n\t\"pin5i.com\": 1,\n\t\"pinbg.com\": 1,\n\t\"pincai.com\": 1,\n\t\"pinchao.cc\": 1,\n\t\"pinfengws.com\": 1,\n\t\"pingan.com\": 1,\n\t\"pinggu.org\": 1,\n\t\"pingguo7.com\": 1,\n\t\"pingguolv.com\": 1,\n\t\"pingshu8.com\": 1,\n\t\"pingtan597.com\": 1,\n\t\"pingtan66.com\": 1,\n\t\"pingtandao.com\": 1,\n\t\"pingwest.com\": 1,\n\t\"pinjiao.com\": 1,\n\t\"pinjie.cc\": 1,\n\t\"pinkecity.com\": 1,\n\t\"pinker365.com\": 1,\n\t\"pinla.com\": 1,\n\t\"pinpai-qq.com\": 1,\n\t\"pinpai37.com\": 1,\n\t\"pinpaibaike.com\": 1,\n\t\"pinpaidongli.com\": 1,\n\t\"pinpaihudong.com\": 1,\n\t\"pinpinwang.com\": 1,\n\t\"pinshan.com\": 1,\n\t\"pintour.com\": 1,\n\t\"pinyouc.com\": 1,\n\t\"pipa.com\": 1,\n\t\"pipaw.com\": 1,\n\t\"pipaw.net\": 1,\n\t\"pixlr.com\": 1,\n\t\"pjhku.com\": 1,\n\t\"pjob.net\": 1,\n\t\"pjtime.com\": 1,\n\t\"pk350.com\": 1,\n\t\"pk38.com\": 1,\n\t\"pk66.com\": 1,\n\t\"pkedu.net\": 1,\n\t\"pkpkpk.com\": 1,\n\t\"pkufi.com\": 1,\n\t\"pkulaws.com\": 1,\n\t\"pkurc.com\": 1,\n\t\"pkzx.com\": 1,\n\t\"pl520.com\": 1,\n\t\"plaaf.net\": 1,\n\t\"plateno.com\": 1,\n\t\"playacg.com\": 1,\n\t\"plxww.com\": 1,\n\t\"pm168.net\": 1,\n\t\"pmcaff.com\": 1,\n\t\"pmdoudou.com\": 1,\n\t\"pmxsd.com\": 1,\n\t\"pnzpw.com\": 1,\n\t\"pobaby.net\": 1,\n\t\"pocosite.com\": 1,\n\t\"podinns.com\": 1,\n\t\"pogare.com\": 1,\n\t\"polocai.com\": 1,\n\t\"poluoluo.com\": 1,\n\t\"polycn.com\": 1,\n\t\"polyv.net\": 1,\n\t\"pomoho.com\": 1,\n\t\"pooher.com\": 1,\n\t\"pop-bags.com\": 1,\n\t\"pop-fashion.com\": 1,\n\t\"pop-shoe.com\": 1,\n\t\"pop136.com\": 1,\n\t\"pop800.com\": 1,\n\t\"popdalian.com\": 1,\n\t\"popoho.com\": 1,\n\t\"poppur.com\": 1,\n\t\"popub.net\": 1,\n\t\"popwan.com\": 1,\n\t\"port-m.com\": 1,\n\t\"post183.net\": 1,\n\t\"postsc.com\": 1,\n\t\"posuijianzhulaji.com\": 1,\n\t\"potevio.com\": 1,\n\t\"powercdn.com\": 1,\n\t\"powerde.com\": 1,\n\t\"powereasy.net\": 1,\n\t\"powerfoo.com\": 1,\n\t\"powerpigs.net\": 1,\n\t\"powersemi.cc\": 1,\n\t\"poyanglake.org\": 1,\n\t\"pozjzz.com\": 1,\n\t\"pozzm.com\": 1,\n\t\"pp.cc\": 1,\n\t\"pp250.com\": 1,\n\t\"pp6.cc\": 1,\n\t\"ppa18.com\": 1,\n\t\"ppaaol.com\": 1,\n\t\"ppdai.com\": 1,\n\t\"ppgoo.com\": 1,\n\t\"ppgys.com\": 1,\n\t\"pphgjx.com\": 1,\n\t\"ppkao.com\": 1,\n\t\"pplive.com\": 1,\n\t\"ppmarket.com\": 1,\n\t\"pppoo.com\": 1,\n\t\"pps.tv\": 1,\n\t\"ppsimg.com\": 1,\n\t\"ppstream.com\": 1,\n\t\"ppswan.com\": 1,\n\t\"ppt123.net\": 1,\n\t\"pptbz.com\": 1,\n\t\"pptstore.net\": 1,\n\t\"pptv.com\": 1,\n\t\"ppwan.com\": 1,\n\t\"ppxmw.com\": 1,\n\t\"ppys.net\": 1,\n\t\"ppzhan.com\": 1,\n\t\"ppzhangui.com\": 1,\n\t\"ppzsw.com\": 1,\n\t\"ppzuowen.com\": 1,\n\t\"pr56789.com\": 1,\n\t\"pradafashionstore.com\": 1,\n\t\"prcedu.com\": 1,\n\t\"prechina.net\": 1,\n\t\"printhr.com\": 1,\n\t\"prnasia.com\": 1,\n\t\"processon.com\": 1,\n\t\"project-oa.com\": 1,\n\t\"property-bid.net\": 1,\n\t\"ps123.net\": 1,\n\t\"psachina.org\": 1,\n\t\"psahz.com\": 1,\n\t\"psbc.com\": 1,\n\t\"psjia.com\": 1,\n\t\"psmoban.com\": 1,\n\t\"pstatp.com\": 1,\n\t\"psychcn.com\": 1,\n\t\"psycofe.com\": 1,\n\t\"pt163.com\": 1,\n\t\"pt597.com\": 1,\n\t\"pt791.com\": 1,\n\t\"ptacn.com\": 1,\n\t\"ptbus.com\": 1,\n\t\"ptdao.com\": 1,\n\t\"ptfcxx.com\": 1,\n\t\"ptfdc.com\": 1,\n\t\"ptgxs.com\": 1,\n\t\"pthl.net\": 1,\n\t\"ptjy.com\": 1,\n\t\"ptlogin2.qq.com\": 1,\n\t\"ptmfrc.com\": 1,\n\t\"ptotour.com\": 1,\n\t\"ptpcp.com\": 1,\n\t\"ptrcw.com\": 1,\n\t\"ptsqjy.com\": 1,\n\t\"ptzpqz.com\": 1,\n\t\"ptztb.com\": 1,\n\t\"puahome.com\": 1,\n\t\"pubchn.com\": 1,\n\t\"pubmatic.com\": 1,\n\t\"puepu.com\": 1,\n\t\"puercha.cc\": 1,\n\t\"puercn.com\": 1,\n\t\"puerlife.com\": 1,\n\t\"puertea8.com\": 1,\n\t\"pujia.com\": 1,\n\t\"pump999.com\": 1,\n\t\"pumpzc.com\": 1,\n\t\"punai.com\": 1,\n\t\"pupuwang.com\": 1,\n\t\"puresky.org\": 1,\n\t\"pusa123.com\": 1,\n\t\"putaomiaomu.com\": 1,\n\t\"putclub.com\": 1,\n\t\"putschool.com\": 1,\n\t\"putuoshan.travel\": 1,\n\t\"puxinjingshe.com\": 1,\n\t\"pv-ledzm.com\": 1,\n\t\"pvall.com\": 1,\n\t\"pvc-sujiao-diban.com\": 1,\n\t\"pvc123.com\": 1,\n\t\"pvcpu.com\": 1,\n\t\"pvcqihuo.com\": 1,\n\t\"px0769.com\": 1,\n\t\"px33.com\": 1,\n\t\"px8.com\": 1,\n\t\"pxcn168.com\": 1,\n\t\"pxems.net\": 1,\n\t\"pxmfw.com\": 1,\n\t\"pxrczpw.com\": 1,\n\t\"pxrencai.com\": 1,\n\t\"pxsww.com\": 1,\n\t\"pxtew.com\": 1,\n\t\"py168.com\": 1,\n\t\"pybxfc.com\": 1,\n\t\"pybxrc.com\": 1,\n\t\"pycars.com\": 1,\n\t\"pyedu.cc\": 1,\n\t\"pygbw.com\": 1,\n\t\"pyinfo.com\": 1,\n\t\"pyinfo.net\": 1,\n\t\"pyjia.com\": 1,\n\t\"pylove.com\": 1,\n\t\"pyrc.net\": 1,\n\t\"pytogo.com\": 1,\n\t\"pyxww.com\": 1,\n\t\"pyzhufang.com\": 1,\n\t\"pzfcw.com\": 1,\n\t\"pzgt.com\": 1,\n\t\"pzhgjj.com\": 1,\n\t\"pzhls.com\": 1,\n\t\"pzhr.com\": 1,\n\t\"pzjyw.com\": 1,\n\t\"pzoom.com\": 1,\n\t\"pzsh.com\": 1,\n\t\"pzsns.com\": 1,\n\t\"pztuan.com\": 1,\n\t\"pzzc.net\": 1,\n\t\"q-ce.com\": 1,\n\t\"q0580.com\": 1,\n\t\"q1.com\": 1,\n\t\"q150.com\": 1,\n\t\"q68.com\": 1,\n\t\"qalex.com\": 1,\n\t\"qbaobei.com\": 1,\n\t\"qbdjjw.com\": 1,\n\t\"qbjtour.com\": 1,\n\t\"qbox.me\": 1,\n\t\"qc1818.com\": 1,\n\t\"qc188.com\": 1,\n\t\"qc6.com\": 1,\n\t\"qc8.cc\": 1,\n\t\"qc99.com\": 1,\n\t\"qcloud.com\": 1,\n\t\"qcplay.com\": 1,\n\t\"qcqcw.com\": 1,\n\t\"qcr.cc\": 1,\n\t\"qcrencai.com\": 1,\n\t\"qctl.net\": 1,\n\t\"qctsw.com\": 1,\n\t\"qcwe.com\": 1,\n\t\"qcwp.com\": 1,\n\t\"qcyf.net\": 1,\n\t\"qdairport.com\": 1,\n\t\"qdbeian.com\": 1,\n\t\"qdcaijing.com\": 1,\n\t\"qdcars.com\": 1,\n\t\"qdcdn.com\": 1,\n\t\"qdcuishi.com\": 1,\n\t\"qdedu.net\": 1,\n\t\"qdepi.org\": 1,\n\t\"qdfdc.com\": 1,\n\t\"qdgjg.com\": 1,\n\t\"qdgjj.com\": 1,\n\t\"qdhibi.com\": 1,\n\t\"qdhr.net\": 1,\n\t\"qdit.com\": 1,\n\t\"qdjiazheng.com\": 1,\n\t\"qdlongre.com\": 1,\n\t\"qdmama.net\": 1,\n\t\"qdmm.com\": 1,\n\t\"qdmw.net\": 1,\n\t\"qdnrc.com\": 1,\n\t\"qdnrm.com\": 1,\n\t\"qdoulu.com\": 1,\n\t\"qdqiche.com\": 1,\n\t\"qdsailing.org\": 1,\n\t\"qdtianzhen.com\": 1,\n\t\"qdwenxue.com\": 1,\n\t\"qdxumu.com\": 1,\n\t\"qdyjjh.com\": 1,\n\t\"qdzkb.com\": 1,\n\t\"qdzqs.com\": 1,\n\t\"qeecn.com\": 1,\n\t\"qeeka.com\": 1,\n\t\"qegee.com\": 1,\n\t\"qeqeqe.com\": 1,\n\t\"qf521.com\": 1,\n\t\"qfang.com\": 1,\n\t\"qfcmr.com\": 1,\n\t\"qffc8.com\": 1,\n\t\"qfwzw.com\": 1,\n\t\"qfyf.net\": 1,\n\t\"qfzp.com\": 1,\n\t\"qg597.com\": 1,\n\t\"qglish.com\": 1,\n\t\"qgnews.net\": 1,\n\t\"qgny.net\": 1,\n\t\"qgpx.com\": 1,\n\t\"qgrcsc.com\": 1,\n\t\"qgyyzs.net\": 1,\n\t\"qh12301.com\": 1,\n\t\"qhass.org\": 1,\n\t\"qhcitc.com\": 1,\n\t\"qhcl.org\": 1,\n\t\"qhcmw.com\": 1,\n\t\"qhcqjy.com\": 1,\n\t\"qhdnews.com\": 1,\n\t\"qhdrc.com\": 1,\n\t\"qhdxw.com\": 1,\n\t\"qhfcw.com\": 1,\n\t\"qhflh.com\": 1,\n\t\"qhfx.org\": 1,\n\t\"qhgate.com\": 1,\n\t\"qhhbly.com\": 1,\n\t\"qhimg.com\": 1,\n\t\"qhjiaye.com\": 1,\n\t\"qhkxw.com\": 1,\n\t\"qhlly.com\": 1,\n\t\"qhmed.com\": 1,\n\t\"qhnews.com\": 1,\n\t\"qhpta.com\": 1,\n\t\"qhradio.com\": 1,\n\t\"qhrcsc.com\": 1,\n\t\"qhsrcw.com\": 1,\n\t\"qhstv.com\": 1,\n\t\"qhswdx.com\": 1,\n\t\"qhttw.com\": 1,\n\t\"qhwriter.com\": 1,\n\t\"qhwsjd.com\": 1,\n\t\"qhzk.com\": 1,\n\t\"qi-che.com\": 1,\n\t\"qiancheng100.com\": 1,\n\t\"qianchengriben.com\": 1,\n\t\"qiandao.com\": 1,\n\t\"qiandaohu.cc\": 1,\n\t\"qianggen.com\": 1,\n\t\"qiangmi.com\": 1,\n\t\"qiangpiao.com\": 1,\n\t\"qianhuaweb.com\": 1,\n\t\"qianinfo.com\": 1,\n\t\"qianjia.com\": 1,\n\t\"qianjiangjob.com\": 1,\n\t\"qiankunlt.com\": 1,\n\t\"qianlijob.com\": 1,\n\t\"qianlima.com\": 1,\n\t\"qianlong.com\": 1,\n\t\"qianlongnews.com\": 1,\n\t\"qianqian.com\": 1,\n\t\"qianshanren.com\": 1,\n\t\"qianweb.com\": 1,\n\t\"qianxs.com\": 1,\n\t\"qianyan.biz\": 1,\n\t\"qianyan001.com\": 1,\n\t\"qianyecao.com\": 1,\n\t\"qianyuangx.com\": 1,\n\t\"qianzhan.com\": 1,\n\t\"qianzhan123.com\": 1,\n\t\"qianzheng88.com\": 1,\n\t\"qianzhengdaiban.com\": 1,\n\t\"qiaob2b.com\": 1,\n\t\"qiaobutang.com\": 1,\n\t\"qiaohule.com\": 1,\n\t\"qiaowazi.com\": 1,\n\t\"qiaxing.com\": 1,\n\t\"qibosoft.com\": 1,\n\t\"qicaispace.com\": 1,\n\t\"qicaiwan.com\": 1,\n\t\"qichecailiao.com\": 1,\n\t\"qichelian.com\": 1,\n\t\"qichengwang.com\": 1,\n\t\"qichepeijian.com\": 1,\n\t\"qichepinpai.com\": 1,\n\t\"qichetong.com\": 1,\n\t\"qicheyouqi.com\": 1,\n\t\"qicou.com\": 1,\n\t\"qidian.com\": 1,\n\t\"qidou.com\": 1,\n\t\"qieta.com\": 1,\n\t\"qifabao.com\": 1,\n\t\"qihaowh.com\": 1,\n\t\"qihihi.com\": 1,\n\t\"qihoo.com\": 1,\n\t\"qihuituan.com\": 1,\n\t\"qihuiwang.com\": 1,\n\t\"qihuokaihu.net\": 1,\n\t\"qihuozige.com\": 1,\n\t\"qijiangjob.com\": 1,\n\t\"qijuib.com\": 1,\n\t\"qikan.com\": 1,\n\t\"qikao.net\": 1,\n\t\"qilibali.com\": 1,\n\t\"qiligift.com\": 1,\n\t\"qilindao.com\": 1,\n\t\"qilooo.com\": 1,\n\t\"qiluauto.com\": 1,\n\t\"qilumovie.com\": 1,\n\t\"qina.cc\": 1,\n\t\"qinb.net\": 1,\n\t\"qinbei.com\": 1,\n\t\"qincai.com\": 1,\n\t\"qincai.net\": 1,\n\t\"qindaohr.com\": 1,\n\t\"qing5.com\": 1,\n\t\"qingdao163.com\": 1,\n\t\"qingdaochina.com\": 1,\n\t\"qingdaochina.org\": 1,\n\t\"qingdaoertong.com\": 1,\n\t\"qingdaoexpo2014.org\": 1,\n\t\"qingdaoielts.com\": 1,\n\t\"qingdaomedia.com\": 1,\n\t\"qingdaonews.com\": 1,\n\t\"qingdaosailingworldcup.com\": 1,\n\t\"qingdou.net\": 1,\n\t\"qingfenggu.com\": 1,\n\t\"qingguo.com\": 1,\n\t\"qinghe8.net\": 1,\n\t\"qinghua211.com\": 1,\n\t\"qinghuaonline.com\": 1,\n\t\"qingju.com\": 1,\n\t\"qinglian.org\": 1,\n\t\"qingrenw.com\": 1,\n\t\"qingsong.so\": 1,\n\t\"qingsongwan.com\": 1,\n\t\"qingweilou.com\": 1,\n\t\"qingyout.com\": 1,\n\t\"qingyy.com\": 1,\n\t\"qingzhou365.com\": 1,\n\t\"qiniu.com\": 1,\n\t\"qiniucdn.com\": 1,\n\t\"qiniudn.com\": 1,\n\t\"qinlianwang.com\": 1,\n\t\"qinmiaofuhua.com\": 1,\n\t\"qinqin.com\": 1,\n\t\"qinqiner.com\": 1,\n\t\"qinrun.com\": 1,\n\t\"qinseo.com\": 1,\n\t\"qinxue365.com\": 1,\n\t\"qionghaif.com\": 1,\n\t\"qionghaifc.com\": 1,\n\t\"qiongzhourc.com\": 1,\n\t\"qipaiyouxi.com\": 1,\n\t\"qipaoxian.com\": 1,\n\t\"qipei001.com\": 1,\n\t\"qipeipin.com\": 1,\n\t\"qipeiren.com\": 1,\n\t\"qipeizhan.com\": 1,\n\t\"qiqi168.com\": 1,\n\t\"qiqi6688.com\": 1,\n\t\"qiqibudy.com\": 1,\n\t\"qiqihaenews.com\": 1,\n\t\"qire123.com\": 1,\n\t\"qiremv.com\": 1,\n\t\"qiucinews.com\": 1,\n\t\"qiushibaike.com\": 1,\n\t\"qiuxian.com\": 1,\n\t\"qiwuliulanqi.com\": 1,\n\t\"qixid.net\": 1,\n\t\"qixing365.com\": 1,\n\t\"qixingtang.com\": 1,\n\t\"qixiujie.com\": 1,\n\t\"qiye56.com\": 1,\n\t\"qiyefalvguwen.com\": 1,\n\t\"qiyegu.com\": 1,\n\t\"qiyexxw.com\": 1,\n\t\"qiyi.com\": 1,\n\t\"qiyipic.com\": 1,\n\t\"qiyou.com\": 1,\n\t\"qiyouwang.com\": 1,\n\t\"qiyue.com\": 1,\n\t\"qizhongji.com\": 1,\n\t\"qj.cc\": 1,\n\t\"qj99.net\": 1,\n\t\"qjdrying.com\": 1,\n\t\"qjeda.com\": 1,\n\t\"qjfang.com\": 1,\n\t\"qjfdcw.com\": 1,\n\t\"qjherb.com\": 1,\n\t\"qjhm.net\": 1,\n\t\"qjhte.com\": 1,\n\t\"qjis.com\": 1,\n\t\"qjjy.org\": 1,\n\t\"qjkc.net\": 1,\n\t\"qjrc.com\": 1,\n\t\"qjren.com\": 1,\n\t\"qjsxtz.com\": 1,\n\t\"qjw99.com\": 1,\n\t\"qjxzsp.com\": 1,\n\t\"qjy168.com\": 1,\n\t\"qjz.com\": 1,\n\t\"qk.cc\": 1,\n\t\"qk365.com\": 1,\n\t\"qkankan.com\": 1,\n\t\"qkfang.com\": 1,\n\t\"qkzxw.net\": 1,\n\t\"qlbchina.com\": 1,\n\t\"qlcars.net\": 1,\n\t\"qljgw.com\": 1,\n\t\"qljr.com\": 1,\n\t\"qlrc.com\": 1,\n\t\"qlrc114.com\": 1,\n\t\"qltarena.com\": 1,\n\t\"qlwbshy.com\": 1,\n\t\"qm120.com\": 1,\n\t\"qmango.com\": 1,\n\t\"qmingw.com\": 1,\n\t\"qn71.com\": 1,\n\t\"qnsb.com\": 1,\n\t\"qp1001.com\": 1,\n\t\"qp110.com\": 1,\n\t\"qp365.net\": 1,\n\t\"qp966.com\": 1,\n\t\"qplus.com\": 1,\n\t\"qpzx.com\": 1,\n\t\"qq-online.net\": 1,\n\t\"qq-wan.com\": 1,\n\t\"qq.com\": 1,\n\t\"qq163.com\": 1,\n\t\"qq190.com\": 1,\n\t\"qq2013.org\": 1,\n\t\"qq295925172.com\": 1,\n\t\"qq373.com\": 1,\n\t\"qq745.com\": 1,\n\t\"qq8877.com\": 1,\n\t\"qq937.com\": 1,\n\t\"qq990.com\": 1,\n\t\"qqbaobao.com\": 1,\n\t\"qqbiaoqing.com\": 1,\n\t\"qqbifen.com\": 1,\n\t\"qqbody.com\": 1,\n\t\"qqcyl.com\": 1,\n\t\"qqdcw.com\": 1,\n\t\"qqdm.com\": 1,\n\t\"qqershou.com\": 1,\n\t\"qqfb.com\": 1,\n\t\"qqfenzu.com\": 1,\n\t\"qqgexingqianming.com\": 1,\n\t\"qqhot.com\": 1,\n\t\"qqhrnews.com\": 1,\n\t\"qqiii.cc\": 1,\n\t\"qqjay.com\": 1,\n\t\"qqjia.com\": 1,\n\t\"qqjswang.com\": 1,\n\t\"qqkqw.com\": 1,\n\t\"qqma.com\": 1,\n\t\"qqmail.com\": 1,\n\t\"qqmcc.com\": 1,\n\t\"qqmcc.org\": 1,\n\t\"qqmingzi.cc\": 1,\n\t\"qqpao.com\": 1,\n\t\"qqpifu.com\": 1,\n\t\"qqshuoshuo.com\": 1,\n\t\"qqsort.com\": 1,\n\t\"qqssn.com\": 1,\n\t\"qqtbw.com\": 1,\n\t\"qqthj.com\": 1,\n\t\"qqtn.com\": 1,\n\t\"qqtouxiang.com\": 1,\n\t\"qqtu8.com\": 1,\n\t\"qqtz.com\": 1,\n\t\"qqu360.com\": 1,\n\t\"qqwangming.org\": 1,\n\t\"qqwkids.com\": 1,\n\t\"qqwm2014.com\": 1,\n\t\"qqwuhan.com\": 1,\n\t\"qqwwr.com\": 1,\n\t\"qqxoo.com\": 1,\n\t\"qqxxzx.com\": 1,\n\t\"qqya.com\": 1,\n\t\"qqyou.com\": 1,\n\t\"qqyy.com\": 1,\n\t\"qqzbz.com\": 1,\n\t\"qqzl.cc\": 1,\n\t\"qqzl.com\": 1,\n\t\"qqzssl.com\": 1,\n\t\"qqzyw.com\": 1,\n\t\"qqzywang.com\": 1,\n\t\"qqzzhh.com\": 1,\n\t\"qs56.net\": 1,\n\t\"qshang.com\": 1,\n\t\"qsn365.com\": 1,\n\t\"qstatic.com\": 1,\n\t\"qszpw.net\": 1,\n\t\"qtaidu.com\": 1,\n\t\"qth8.com\": 1,\n\t\"qthdaily.com\": 1,\n\t\"qthnews.com\": 1,\n\t\"qthtv.com\": 1,\n\t\"qtimg.net\": 1,\n\t\"qtour.com\": 1,\n\t\"qtpep.com\": 1,\n\t\"qtulou.com\": 1,\n\t\"qu114.com\": 1,\n\t\"qu247.com\": 1,\n\t\"qu97.com\": 1,\n\t\"quanhuaoffice.com\": 1,\n\t\"quanji.com\": 1,\n\t\"quanjiamei.com\": 1,\n\t\"quanjiamei.net\": 1,\n\t\"quanjing.com\": 1,\n\t\"quanjingke.com\": 1,\n\t\"quanjinglian.com\": 1,\n\t\"quanlaoda.com\": 1,\n\t\"quanmama.com\": 1,\n\t\"quanshunjiazheng.com\": 1,\n\t\"quantserve.com\": 1,\n\t\"quanxi.cc\": 1,\n\t\"quanzhi.com\": 1,\n\t\"qubaihuo.com\": 1,\n\t\"qudao.com\": 1,\n\t\"qudao168.com\": 1,\n\t\"qudong.com\": 1,\n\t\"queshao.com\": 1,\n\t\"quhua.com\": 1,\n\t\"qujianglou.com\": 1,\n\t\"qule8.com\": 1,\n\t\"qulishi.com\": 1,\n\t\"qulv.com\": 1,\n\t\"qumaishu.com\": 1,\n\t\"qumei.com\": 1,\n\t\"qumenhu.com\": 1,\n\t\"quna.com\": 1,\n\t\"qunachi.com\": 1,\n\t\"qunar.com\": 1,\n\t\"qunarzz.com\": 1,\n\t\"qunhaowang.com\": 1,\n\t\"qunxianart.com\": 1,\n\t\"qupingche.com\": 1,\n\t\"qupk.com\": 1,\n\t\"qusu.org\": 1,\n\t\"qutuly.com\": 1,\n\t\"quwan.com\": 1,\n\t\"quwanwan.com\": 1,\n\t\"quxia.com\": 1,\n\t\"quxiu.com\": 1,\n\t\"quyouxue.org\": 1,\n\t\"quzhao.com\": 1,\n\t\"qvbuy.com\": 1,\n\t\"qvod.com\": 1,\n\t\"qw.cc\": 1,\n\t\"qw168.com\": 1,\n\t\"qwjian.com\": 1,\n\t\"qwqt.net\": 1,\n\t\"qwqtw.com\": 1,\n\t\"qwsy.com\": 1,\n\t\"qx-pump.com\": 1,\n\t\"qx121.com\": 1,\n\t\"qx162.com\": 1,\n\t\"qx818.com\": 1,\n\t\"qx960.com\": 1,\n\t\"qxmesh.com\": 1,\n\t\"qxnic.com\": 1,\n\t\"qxw.cc\": 1,\n\t\"qxw18.com\": 1,\n\t\"qxyc.net\": 1,\n\t\"qxyou.com\": 1,\n\t\"qy139.com\": 1,\n\t\"qy6.com\": 1,\n\t\"qybc.com\": 1,\n\t\"qyceo.com\": 1,\n\t\"qycn.com\": 1,\n\t\"qyer.com\": 1,\n\t\"qyjpzx.com\": 1,\n\t\"qymssc.com\": 1,\n\t\"qyoy.net\": 1,\n\t\"qyrb.com\": 1,\n\t\"qysxy.net\": 1,\n\t\"qyt.com\": 1,\n\t\"qyucn.com\": 1,\n\t\"qyxyw.com\": 1,\n\t\"qyzyw.com\": 1,\n\t\"qz123.com\": 1,\n\t\"qz597.com\": 1,\n\t\"qz828.com\": 1,\n\t\"qz828.net\": 1,\n\t\"qzbbs.com\": 1,\n\t\"qzce.com\": 1,\n\t\"qzedu.net\": 1,\n\t\"qzfood.com\": 1,\n\t\"qzfznews.com\": 1,\n\t\"qzgb.com\": 1,\n\t\"qzgjj.com\": 1,\n\t\"qzhi5.com\": 1,\n\t\"qzjw.net\": 1,\n\t\"qzkj.net\": 1,\n\t\"qzlcxww.com\": 1,\n\t\"qzone.cc\": 1,\n\t\"qzone.com\": 1,\n\t\"qzone.la\": 1,\n\t\"qzpc.org\": 1,\n\t\"qzrcw.com\": 1,\n\t\"qzrczpw.com\": 1,\n\t\"qzrls.com\": 1,\n\t\"qzrtvu.com\": 1,\n\t\"qztour.com\": 1,\n\t\"qztour.net\": 1,\n\t\"qzwb.com\": 1,\n\t\"qzwhcy.com\": 1,\n\t\"qzxxg.net\": 1,\n\t\"qzyb.com\": 1,\n\t\"qzz.cc\": 1,\n\t\"qzzpw.net\": 1,\n\t\"r018.com\": 1,\n\t\"r021.com\": 1,\n\t\"r0580.com\": 1,\n\t\"ra10000.com\": 1,\n\t\"rabook.com\": 1,\n\t\"racecareer.com\": 1,\n\t\"rachina.org\": 1,\n\t\"racing001.com\": 1,\n\t\"radiohz.com\": 1,\n\t\"radiotj.com\": 1,\n\t\"railcn.net\": 1,\n\t\"rain8.com\": 1,\n\t\"rakuten.co.jp\": 1,\n\t\"ranshao.com\": 1,\n\t\"ranwen.com\": 1,\n\t\"raoke.net\": 1,\n\t\"raorao.com\": 1,\n\t\"rapidppt.com\": 1,\n\t\"rar8.net\": 1,\n\t\"raresd.com\": 1,\n\t\"ratuo.com\": 1,\n\t\"rayhoo.net\": 1,\n\t\"rayp.com\": 1,\n\t\"rb139.com\": 1,\n\t\"rbtmm.com\": 1,\n\t\"rc.cc\": 1,\n\t\"rc0722.com\": 1,\n\t\"rc0732.com\": 1,\n\t\"rc0817.com\": 1,\n\t\"rc1001.com\": 1,\n\t\"rc114.com\": 1,\n\t\"rc365.com\": 1,\n\t\"rc3721.com\": 1,\n\t\"rc392.com\": 1,\n\t\"rc536.com\": 1,\n\t\"rc595.com\": 1,\n\t\"rc775.com\": 1,\n\t\"rc916.com\": 1,\n\t\"rca8.com\": 1,\n\t\"rcdang.com\": 1,\n\t\"rcdio.com\": 1,\n\t\"rceee.com\": 1,\n\t\"rcpx.net\": 1,\n\t\"rctong.com\": 1,\n\t\"rcuu.com\": 1,\n\t\"rcw0375.com\": 1,\n\t\"rcw0391.com\": 1,\n\t\"rcw395.com\": 1,\n\t\"rcxx.com\": 1,\n\t\"rczp.org\": 1,\n\t\"rddesign.cc\": 1,\n\t\"rdqh.com\": 1,\n\t\"rdyjs.com\": 1,\n\t\"readlishi.com\": 1,\n\t\"readmeok.com\": 1,\n\t\"readnovel.com\": 1,\n\t\"recycle366.com\": 1,\n\t\"recyclechina.com\": 1,\n\t\"redcross-sha.org\": 1,\n\t\"redcrossol.com\": 1,\n\t\"redidai.com\": 1,\n\t\"redocn.com\": 1,\n\t\"redstonevilla.com\": 1,\n\t\"reedhuabo.com\": 1,\n\t\"reformdata.org\": 1,\n\t\"regishome.com\": 1,\n\t\"rencai.net\": 1,\n\t\"rencai5.com\": 1,\n\t\"rencaiabc.com\": 1,\n\t\"rencaijob.com\": 1,\n\t\"rencailu.com\": 1,\n\t\"renren-inc.com\": 1,\n\t\"renren.com\": 1,\n\t\"renrensucai.com\": 1,\n\t\"renrentou.com\": 1,\n\t\"renrenzhe.com\": 1,\n\t\"renrzx.com\": 1,\n\t\"rensoo.com\": 1,\n\t\"renwen.com\": 1,\n\t\"replays.net\": 1,\n\t\"reporthb.com\": 1,\n\t\"reportrc.com\": 1,\n\t\"reportway.com\": 1,\n\t\"reportway.org\": 1,\n\t\"rexuedongman.com\": 1,\n\t\"rexuemil.com\": 1,\n\t\"reyoo.net\": 1,\n\t\"rfchina.com\": 1,\n\t\"rfidchina.org\": 1,\n\t\"rfidm2m.com\": 1,\n\t\"rfthr.com\": 1,\n\t\"rg50.com\": 1,\n\t\"rgfcw.com\": 1,\n\t\"rgrc365.com\": 1,\n\t\"rgzpw.com\": 1,\n\t\"rhrl.net\": 1,\n\t\"richagri.com\": 1,\n\t\"rihanyu.com\": 1,\n\t\"rijigu.com\": 1,\n\t\"rilajoy.com\": 1,\n\t\"riliw.com\": 1,\n\t\"risfond.com\": 1,\n\t\"rj0514.com\": 1,\n\t\"rjzxw.com\": 1,\n\t\"rkzdh.com\": 1,\n\t\"rlzygl.com\": 1,\n\t\"rmburl.com\": 1,\n\t\"rmhospital.com\": 1,\n\t\"rmzt.com\": 1,\n\t\"roadexam.com\": 1,\n\t\"roadexam.net\": 1,\n\t\"roadoor.com\": 1,\n\t\"roadqu.com\": 1,\n\t\"robam.com\": 1,\n\t\"roboo.com\": 1,\n\t\"robot-china.com\": 1,\n\t\"robot-home.com\": 1,\n\t\"rockszh.com\": 1,\n\t\"rockyenglish.com\": 1,\n\t\"rogi-stric.com\": 1,\n\t\"romanka.com\": 1,\n\t\"romantic214.com\": 1,\n\t\"romjd.com\": 1,\n\t\"romschina.com\": 1,\n\t\"romzhijia.net\": 1,\n\t\"romzj.com\": 1,\n\t\"roncua.com\": 1,\n\t\"rong360.com\": 1,\n\t\"rongbiz.com\": 1,\n\t\"rongchao.com\": 1,\n\t\"rongeasy.com\": 1,\n\t\"rongshidai.com\": 1,\n\t\"rongshuxia.com\": 1,\n\t\"rongxingroup.com\": 1,\n\t\"rongzhong.cc\": 1,\n\t\"rongzicn.com\": 1,\n\t\"rongzizulin.com\": 1,\n\t\"rootinhenan.com\": 1,\n\t\"rootzhushou.com\": 1,\n\t\"rooyx.com\": 1,\n\t\"ross999.com\": 1,\n\t\"rqbx.net\": 1,\n\t\"rr-sc.com\": 1,\n\t\"rr258.com\": 1,\n\t\"rrfmn.com\": 1,\n\t\"rrhjz.org\": 1,\n\t\"rrimg.com\": 1,\n\t\"rrs.com\": 1,\n\t\"rrting.net\": 1,\n\t\"rrxk.net\": 1,\n\t\"rs66.com\": 1,\n\t\"rspx.net\": 1,\n\t\"rsqhome.com\": 1,\n\t\"rsqzs.com\": 1,\n\t\"rtbidder.net\": 1,\n\t\"ruan8.com\": 1,\n\t\"ruanman.net\": 1,\n\t\"ruanmei.com\": 1,\n\t\"ruanwen.la\": 1,\n\t\"rubberhr.com\": 1,\n\t\"rubcn.com\": 1,\n\t\"ruczzy.com\": 1,\n\t\"rugao35.com\": 1,\n\t\"rugaojob.com\": 1,\n\t\"rugaozs.com\": 1,\n\t\"ruian.com\": 1,\n\t\"ruian86.com\": 1,\n\t\"ruifox.com\": 1,\n\t\"ruigongye.com\": 1,\n\t\"ruimami.com\": 1,\n\t\"ruiwen.com\": 1,\n\t\"ruixinlong.com\": 1,\n\t\"ruizhiqi.com\": 1,\n\t\"runsky.com\": 1,\n\t\"ruochu.com\": 1,\n\t\"ruoshui.com\": 1,\n\t\"rushu.net\": 1,\n\t\"rutisher.com\": 1,\n\t\"ruyi.com\": 1,\n\t\"rw-cn.com\": 1,\n\t\"rxhb110.com\": 1,\n\t\"rxjy.com\": 1,\n\t\"rxs.cc\": 1,\n\t\"rz0375.com\": 1,\n\t\"rz169.net\": 1,\n\t\"rz520.com\": 1,\n\t\"rzauto.com\": 1,\n\t\"rzdgtour.com\": 1,\n\t\"rzfdc.com\": 1,\n\t\"rzgdfc.com\": 1,\n\t\"rzinfo.net\": 1,\n\t\"rzport.com\": 1,\n\t\"rzrc.com\": 1,\n\t\"rzrsrc.com\": 1,\n\t\"rzta.com\": 1,\n\t\"rzwenlan.com\": 1,\n\t\"rzwww.com\": 1,\n\t\"rzxwwang.com\": 1,\n\t\"rzxx.com\": 1,\n\t\"rzxyfc.com\": 1,\n\t\"rzzg.com\": 1,\n\t\"s-msn.com\": 1,\n\t\"s1979.com\": 1,\n\t\"sa26.com\": 1,\n\t\"saayaa.com\": 1,\n\t\"sae-china.org\": 1,\n\t\"safe10000.com\": 1,\n\t\"safehoo.com\": 1,\n\t\"safetyw.com\": 1,\n\t\"saibeinews.com\": 1,\n\t\"saicgroup.com\": 1,\n\t\"saict.org\": 1,\n\t\"saier360.com\": 1,\n\t\"saiermedia.com\": 1,\n\t\"saike.com\": 1,\n\t\"saloonrv.com\": 1,\n\t\"samboc.com\": 1,\n\t\"samsung.com\": 1,\n\t\"sanan-e.com\": 1,\n\t\"sanbeiguoshu.com\": 1,\n\t\"sandai.net\": 1,\n\t\"sanfo.com\": 1,\n\t\"sangame.com\": 1,\n\t\"sanguosha.com\": 1,\n\t\"sanhaostreet.com\": 1,\n\t\"sanhucidiao.cc\": 1,\n\t\"sanjinci.com\": 1,\n\t\"sanjun.com\": 1,\n\t\"sanlichem.com\": 1,\n\t\"sanmaophoto.com\": 1,\n\t\"sanqan.com\": 1,\n\t\"sanqin.com\": 1,\n\t\"sanqinche.com\": 1,\n\t\"sanqindaily.com\": 1,\n\t\"sanrenwo.com\": 1,\n\t\"sanwen.net\": 1,\n\t\"sanwenqu.com\": 1,\n\t\"sanwenzx.com\": 1,\n\t\"sanyahunshasheying.com\": 1,\n\t\"sanyatour.com\": 1,\n\t\"sanyecao.com\": 1,\n\t\"sanyijishou.com\": 1,\n\t\"sanyujixie.com\": 1,\n\t\"sanzhijiao.com\": 1,\n\t\"saodijq.com\": 1,\n\t\"sarft.net\": 1,\n\t\"sasa123.com\": 1,\n\t\"sasacn.com\": 1,\n\t\"satog.com\": 1,\n\t\"sbiao360.com\": 1,\n\t\"sbo8.com\": 1,\n\t\"sbrj.net\": 1,\n\t\"sc-overseasinfo.net\": 1,\n\t\"sc115.com\": 1,\n\t\"sc157.com\": 1,\n\t\"sc2car.com\": 1,\n\t\"sc2p.com\": 1,\n\t\"sc518.com\": 1,\n\t\"scanscout.com\": 1,\n\t\"scanv.com\": 1,\n\t\"scbid.com\": 1,\n\t\"scbsm.com\": 1,\n\t\"sccin.com\": 1,\n\t\"sccnn.com\": 1,\n\t\"scco-op.com\": 1,\n\t\"sccts.com\": 1,\n\t\"scdxs.net\": 1,\n\t\"sceci.net\": 1,\n\t\"scedu.net\": 1,\n\t\"sceea.com\": 1,\n\t\"scflcp.com\": 1,\n\t\"scfzbs.com\": 1,\n\t\"scgaosheng.com\": 1,\n\t\"scgc.net\": 1,\n\t\"scgckj.com\": 1,\n\t\"scgh.org\": 1,\n\t\"scgis.net\": 1,\n\t\"scgrain.com\": 1,\n\t\"schongyuan.com\": 1,\n\t\"school51.com\": 1,\n\t\"schtrust.com\": 1,\n\t\"schylawyer.com\": 1,\n\t\"sci99.com\": 1,\n\t\"sciimg.com\": 1,\n\t\"scjtg.com\": 1,\n\t\"sclf.org\": 1,\n\t\"sclongfa.com\": 1,\n\t\"scly168.com\": 1,\n\t\"sclyzq.com\": 1,\n\t\"scmingliu.com\": 1,\n\t\"scmixin.com\": 1,\n\t\"scnj.tv\": 1,\n\t\"scnjnews.com\": 1,\n\t\"scnjtv.com\": 1,\n\t\"scnol.com\": 1,\n\t\"scntv.com\": 1,\n\t\"scorecardresearch.com\": 1,\n\t\"scqcp.com\": 1,\n\t\"scqsng.com\": 1,\n\t\"scrc168.com\": 1,\n\t\"scrxw.com\": 1,\n\t\"sctarena.com\": 1,\n\t\"sctv.com\": 1,\n\t\"sctvf.com\": 1,\n\t\"sctvgo.com\": 1,\n\t\"scu-edu.org\": 1,\n\t\"scw98.com\": 1,\n\t\"scwcgz.com\": 1,\n\t\"scweixiao.com\": 1,\n\t\"scwmw.org\": 1,\n\t\"scwxzk.com\": 1,\n\t\"scxsj.net\": 1,\n\t\"scyahua.com\": 1,\n\t\"scypzs.com\": 1,\n\t\"scyts.com\": 1,\n\t\"sczfcg.com\": 1,\n\t\"sczscd.com\": 1,\n\t\"sczshz.com\": 1,\n\t\"sczssz.com\": 1,\n\t\"sczycj.com\": 1,\n\t\"sczytv.com\": 1,\n\t\"sczyw.com\": 1,\n\t\"sd-china.com\": 1,\n\t\"sd001.com\": 1,\n\t\"sd11185.com\": 1,\n\t\"sdalevel.com\": 1,\n\t\"sdas.org\": 1,\n\t\"sdbdhy.com\": 1,\n\t\"sdbdtc.com\": 1,\n\t\"sdbear.com\": 1,\n\t\"sdchina.com\": 1,\n\t\"sdchn.com\": 1,\n\t\"sdcoop.com\": 1,\n\t\"sdcqjy.com\": 1,\n\t\"sdcrj.com\": 1,\n\t\"sdcw.net\": 1,\n\t\"sddashi.com\": 1,\n\t\"sddcp.com\": 1,\n\t\"sddigua.com\": 1,\n\t\"sddjw.com\": 1,\n\t\"sddxyy.com\": 1,\n\t\"sddzz.com\": 1,\n\t\"sdenews.com\": 1,\n\t\"sdfdc.com\": 1,\n\t\"sdg-china.com\": 1,\n\t\"sdgw.com\": 1,\n\t\"sdinfo.net\": 1,\n\t\"sditol.com\": 1,\n\t\"sdjjw.com\": 1,\n\t\"sdjob.com\": 1,\n\t\"sdjtcx.com\": 1,\n\t\"sdjy001.com\": 1,\n\t\"sdkcs.com\": 1,\n\t\"sdkxyq.com\": 1,\n\t\"sdlib.com\": 1,\n\t\"sdlycts.com\": 1,\n\t\"sdmtjy.com\": 1,\n\t\"sdmuseum.com\": 1,\n\t\"sdnxs.com\": 1,\n\t\"sdo.com\": 1,\n\t\"sdrc315.com\": 1,\n\t\"sdrclm.com\": 1,\n\t\"sdsgwy.com\": 1,\n\t\"sdt360.com\": 1,\n\t\"sdticai.com\": 1,\n\t\"sdtuomei.com\": 1,\n\t\"sdtxsc.com\": 1,\n\t\"sdtyjixie.net\": 1,\n\t\"sdwenbo.com\": 1,\n\t\"sdwenhua.com\": 1,\n\t\"sdxhce.com\": 1,\n\t\"sdzhan.com\": 1,\n\t\"sdzqrc.com\": 1,\n\t\"seadragonedu.com\": 1,\n\t\"seaman-cn.com\": 1,\n\t\"seccw.com\": 1,\n\t\"secn.com\": 1,\n\t\"secoo.com\": 1,\n\t\"secutimes.com\": 1,\n\t\"see-say.com\": 1,\n\t\"seecmedia.net\": 1,\n\t\"seedit.com\": 1,\n\t\"seekxiu.com\": 1,\n\t\"seeyoo.cc\": 1,\n\t\"segahome.com\": 1,\n\t\"segmentfault.com\": 1,\n\t\"sehand.com\": 1,\n\t\"seheli.info\": 1,\n\t\"semdn.com\": 1,\n\t\"semidata.info\": 1,\n\t\"sendong.com\": 1,\n\t\"sensor86.com\": 1,\n\t\"sensorshome.com\": 1,\n\t\"seosrx.net\": 1,\n\t\"seowhy.com\": 1,\n\t\"septwolves.com\": 1,\n\t\"sepu.net\": 1,\n\t\"seqtc.com\": 1,\n\t\"serving-sys.com\": 1,\n\t\"sexorz.com\": 1,\n\t\"sf-auto.com\": 1,\n\t\"sf-express.com\": 1,\n\t\"sfacg.com\": 1,\n\t\"sfbest.com\": 1,\n\t\"sfcdn.org\": 1,\n\t\"sffdj.com\": 1,\n\t\"sfmianhua.com\": 1,\n\t\"sfzkw.com\": 1,\n\t\"sfzmn.com\": 1,\n\t\"sfzpw.com\": 1,\n\t\"sg-rc.com\": 1,\n\t\"sg120.com\": 1,\n\t\"sg560.com\": 1,\n\t\"sg91.net\": 1,\n\t\"sgamer.com\": 1,\n\t\"sge.sh\": 1,\n\t\"sgfcw.com\": 1,\n\t\"sgfy.org\": 1,\n\t\"sgjuzi.com\": 1,\n\t\"sgnet.cc\": 1,\n\t\"sgqcw.net\": 1,\n\t\"sgrb.com\": 1,\n\t\"sgrcw.com\": 1,\n\t\"sgren.cc\": 1,\n\t\"sgtz.com\": 1,\n\t\"sguo.com\": 1,\n\t\"sgyz.com\": 1,\n\t\"sh-ielts.com\": 1,\n\t\"sh-peixun.com\": 1,\n\t\"sh-zhaopinhui.com\": 1,\n\t\"sh112.com\": 1,\n\t\"sh1188.com\": 1,\n\t\"sh361.com\": 1,\n\t\"sh51766.com\": 1,\n\t\"sh528.com\": 1,\n\t\"sh7.com\": 1,\n\t\"sh91.com\": 1,\n\t\"sha-steel.com\": 1,\n\t\"shaanxigrain.com\": 1,\n\t\"shaanxijky.com\": 1,\n\t\"shafa.com\": 1,\n\t\"shanchengrc.com\": 1,\n\t\"shandalu.com\": 1,\n\t\"shandongrc.com\": 1,\n\t\"shandongsannong.com\": 1,\n\t\"shandongtarena.com\": 1,\n\t\"shang360.com\": 1,\n\t\"shangc.net\": 1,\n\t\"shangcaifanyi.com\": 1,\n\t\"shangdu.com\": 1,\n\t\"shanghai-electric.com\": 1,\n\t\"shanghaiairport.com\": 1,\n\t\"shanghaiamts.com\": 1,\n\t\"shanghaibaomu.com\": 1,\n\t\"shanghaiconcerthall.org\": 1,\n\t\"shanghaidz.com\": 1,\n\t\"shanghaigm.com\": 1,\n\t\"shanghaijiaodakaoyan.com\": 1,\n\t\"shanghaimuseum.net\": 1,\n\t\"shanghaining.com\": 1,\n\t\"shanghairc.com\": 1,\n\t\"shanghaitour.net\": 1,\n\t\"shangjisou.com\": 1,\n\t\"shangliutatler.com\": 1,\n\t\"shangpin.com\": 1,\n\t\"shangpusou.com\": 1,\n\t\"shangqi.cc\": 1,\n\t\"shangqiurencaiwang.com\": 1,\n\t\"shangshang.com\": 1,\n\t\"shangxiang.com\": 1,\n\t\"shangxueba.com\": 1,\n\t\"shangyurencai.com\": 1,\n\t\"shanhe.cc\": 1,\n\t\"shanhuwang.com\": 1,\n\t\"shanke001.com\": 1,\n\t\"shanshan360.com\": 1,\n\t\"shantoumama.com\": 1,\n\t\"shantui.com\": 1,\n\t\"shanximuseum.com\": 1,\n\t\"shanxiql.com\": 1,\n\t\"shanxishizheng.com\": 1,\n\t\"shanxw.com\": 1,\n\t\"shaoer.com\": 1,\n\t\"shaofang.cc\": 1,\n\t\"shaolinedu.com\": 1,\n\t\"shaolinjidi.com\": 1,\n\t\"shaolinsiyuan.com\": 1,\n\t\"shaoyang51.com\": 1,\n\t\"shaoyangnews.net\": 1,\n\t\"shaoyoo.com\": 1,\n\t\"shaqing.com\": 1,\n\t\"sharewithu.com\": 1,\n\t\"shashapark.com\": 1,\n\t\"shaxzs.com\": 1,\n\t\"shbkqs.com\": 1,\n\t\"shbtob.com\": 1,\n\t\"shbyg.com\": 1,\n\t\"shbyw.com\": 1,\n\t\"shcaoan.com\": 1,\n\t\"shcce.com\": 1,\n\t\"shccig.com\": 1,\n\t\"shcifco.com\": 1,\n\t\"shcnws.com\": 1,\n\t\"shcoop.com\": 1,\n\t\"shctzh.com\": 1,\n\t\"shcxaa.com\": 1,\n\t\"shdazao.com\": 1,\n\t\"shdbjy.com\": 1,\n\t\"shdxhd.com\": 1,\n\t\"shebao8.com\": 1,\n\t\"shebaoyi.com\": 1,\n\t\"shebeijianli.com\": 1,\n\t\"shechuang.org\": 1,\n\t\"shedunews.com\": 1,\n\t\"sheencity.com\": 1,\n\t\"sheepet.com\": 1,\n\t\"sheidao.com\": 1,\n\t\"sheji777.com\": 1,\n\t\"shejiben.com\": 1,\n\t\"shejiguan.net\": 1,\n\t\"shejiqun.com\": 1,\n\t\"shejis.com\": 1,\n\t\"shen1d.com\": 1,\n\t\"shenbinghang.com\": 1,\n\t\"shenchuang.com\": 1,\n\t\"shendu.com\": 1,\n\t\"shengdh123.com\": 1,\n\t\"shengfang.com\": 1,\n\t\"shengjoy.com\": 1,\n\t\"shenglinyuan.com\": 1,\n\t\"shengpay.com\": 1,\n\t\"shengphoto.com\": 1,\n\t\"shenguang.com\": 1,\n\t\"shengyibao.com\": 1,\n\t\"shengyidi.com\": 1,\n\t\"shengyijie.net\": 1,\n\t\"shengzhujiage.com\": 1,\n\t\"shenlumf.com\": 1,\n\t\"shenmanhua.com\": 1,\n\t\"shenmayouxi.com\": 1,\n\t\"shennong.com\": 1,\n\t\"shenqing.tv\": 1,\n\t\"shenxianyu.cc\": 1,\n\t\"shenyouyou.com\": 1,\n\t\"shenzhenair.com\": 1,\n\t\"shenzhenjiaoshi.com\": 1,\n\t\"sherc.net\": 1,\n\t\"shexiannet.com\": 1,\n\t\"sheyang.cc\": 1,\n\t\"sheying8.com\": 1,\n\t\"sheyingtg.com\": 1,\n\t\"shfff.com\": 1,\n\t\"shfinancialnews.com\": 1,\n\t\"shfuyu.net\": 1,\n\t\"shgao.com\": 1,\n\t\"shgjj.com\": 1,\n\t\"shhbm.com\": 1,\n\t\"shhkws.com\": 1,\n\t\"shhswed.com\": 1,\n\t\"shhuo.com\": 1,\n\t\"shichang.com\": 1,\n\t\"shichangbu.com\": 1,\n\t\"shichengxian.com\": 1,\n\t\"shicimingju.com\": 1,\n\t\"shiciw.com\": 1,\n\t\"shidao.cc\": 1,\n\t\"shidi.org\": 1,\n\t\"shidz.com\": 1,\n\t\"shigong114.com\": 1,\n\t\"shiguangjiaoluo.com\": 1,\n\t\"shiguche88.com\": 1,\n\t\"shihuahr.com\": 1,\n\t\"shijiebang.com\": 1,\n\t\"shijiemil.com\": 1,\n\t\"shijieyouxi.com\": 1,\n\t\"shijihao.wang\": 1,\n\t\"shijue.me\": 1,\n\t\"shijuew.com\": 1,\n\t\"shikee.com\": 1,\n\t\"shilehui.com\": 1,\n\t\"shiliunet.com\": 1,\n\t\"shimaogroup.com\": 1,\n\t\"shionry.com\": 1,\n\t\"shipinzhuchi.com\": 1,\n\t\"shisu-edu.com\": 1,\n\t\"shiwan.com\": 1,\n\t\"shixi1980.com\": 1,\n\t\"shixi8.com\": 1,\n\t\"shiyan.cc\": 1,\n\t\"shiyanhospital.com\": 1,\n\t\"shiyouhr.com\": 1,\n\t\"shjdpx.com\": 1,\n\t\"shjiugong.com\": 1,\n\t\"shjmnc.com\": 1,\n\t\"shjtaq.com\": 1,\n\t\"shjyxxg.com\": 1,\n\t\"shkingchem.com\": 1,\n\t\"shmama.net\": 1,\n\t\"shmcws.com\": 1,\n\t\"shmet.com\": 1,\n\t\"shmetro.com\": 1,\n\t\"shnn.com\": 1,\n\t\"shodr.org\": 1,\n\t\"shoeshr.com\": 1,\n\t\"shopin.net\": 1,\n\t\"shopqc.net\": 1,\n\t\"shoucw.com\": 1,\n\t\"shoudurc.com\": 1,\n\t\"shoudurx.com\": 1,\n\t\"shougongke.com\": 1,\n\t\"shouji.com\": 1,\n\t\"shouji56.com\": 1,\n\t\"shouliwang.com\": 1,\n\t\"shouy120.com\": 1,\n\t\"shouyao8.com\": 1,\n\t\"shouyihuo.com\": 1,\n\t\"shouyou.com\": 1,\n\t\"shouyou520.com\": 1,\n\t\"shouyoubus.com\": 1,\n\t\"shouyoucdn.com\": 1,\n\t\"shouyoutv.com\": 1,\n\t\"shouyouzhijia.net\": 1,\n\t\"showbb.net\": 1,\n\t\"showcang.com\": 1,\n\t\"showchina.org\": 1,\n\t\"showji.com\": 1,\n\t\"showjob.com\": 1,\n\t\"showmesse.com\": 1,\n\t\"showtime.cc\": 1,\n\t\"shpho.com\": 1,\n\t\"shphome.com\": 1,\n\t\"shphouse.com\": 1,\n\t\"shpzzh.com\": 1,\n\t\"shq-pump.com\": 1,\n\t\"shqigan.com\": 1,\n\t\"shrail.com\": 1,\n\t\"shsjs.com\": 1,\n\t\"shsof.com\": 1,\n\t\"shsongjiang.com\": 1,\n\t\"shsunedu.com\": 1,\n\t\"shtimg.com\": 1,\n\t\"shtl120.com\": 1,\n\t\"shtour.org\": 1,\n\t\"shtuoba.com\": 1,\n\t\"shuaijiao.com\": 1,\n\t\"shuaji.net\": 1,\n\t\"shuajizhijia.com\": 1,\n\t\"shuajizhijia.net\": 1,\n\t\"shuame.com\": 1,\n\t\"shuangcheng.net\": 1,\n\t\"shuanghui.net\": 1,\n\t\"shuangliang.com\": 1,\n\t\"shuanglongyuanyi.com\": 1,\n\t\"shuangtao.com\": 1,\n\t\"shuangtuan.com\": 1,\n\t\"shuangtv.net\": 1,\n\t\"shuangzhengwang.com\": 1,\n\t\"shucai001.com\": 1,\n\t\"shucai123.com\": 1,\n\t\"shucar.com\": 1,\n\t\"shufa.com\": 1,\n\t\"shufa.org\": 1,\n\t\"shufa001.com\": 1,\n\t\"shufadajia.com\": 1,\n\t\"shufawu.com\": 1,\n\t\"shufe-cec.com\": 1,\n\t\"shuhai.com\": 1,\n\t\"shuhua.com\": 1,\n\t\"shuhuacun.net\": 1,\n\t\"shuhuapifa.com\": 1,\n\t\"shuhuazy.com\": 1,\n\t\"shuicao.cc\": 1,\n\t\"shuichan.cc\": 1,\n\t\"shuichan.com\": 1,\n\t\"shuichan51.com\": 1,\n\t\"shuifei168.com\": 1,\n\t\"shuigongye.com\": 1,\n\t\"shuiguo.com\": 1,\n\t\"shuiliyc.com\": 1,\n\t\"shuimotv.com\": 1,\n\t\"shuitou001.com\": 1,\n\t\"shuiwushi.net\": 1,\n\t\"shulife.com\": 1,\n\t\"shumiao.com\": 1,\n\t\"shumx.com\": 1,\n\t\"shundehr.com\": 1,\n\t\"shunderen.com\": 1,\n\t\"shunwang.com\": 1,\n\t\"shuobao.com\": 1,\n\t\"shuocar.com\": 1,\n\t\"shuoping.net\": 1,\n\t\"shuoshuodaquan.net\": 1,\n\t\"shuoshuodaquan.org\": 1,\n\t\"shuoshuokong.com\": 1,\n\t\"shuren100.com\": 1,\n\t\"shushi100.com\": 1,\n\t\"shusongji.org\": 1,\n\t\"shuxueba.com\": 1,\n\t\"shuyangba.com\": 1,\n\t\"shuzan.com\": 1,\n\t\"shuzitielu.com\": 1,\n\t\"shuzixiaoyuan.com\": 1,\n\t\"shuzixiaoyuan.org\": 1,\n\t\"shwomen.org\": 1,\n\t\"shwsdp.com\": 1,\n\t\"shxb.net\": 1,\n\t\"shxbe.com\": 1,\n\t\"shxcoal.com\": 1,\n\t\"shxdx.com\": 1,\n\t\"shxgh.org\": 1,\n\t\"shxingsen.com\": 1,\n\t\"shxsy.org\": 1,\n\t\"shynws.net\": 1,\n\t\"shyouth.net\": 1,\n\t\"shyrcw.com\": 1,\n\t\"shzaojiao.com\": 1,\n\t\"shzfzz.net\": 1,\n\t\"shzgd.org\": 1,\n\t\"shzgh.org\": 1,\n\t\"shzh.net\": 1,\n\t\"shzq.org\": 1,\n\t\"shztdxyy.com\": 1,\n\t\"si.kz\": 1,\n\t\"si114.com\": 1,\n\t\"siaholidays-beijing.com\": 1,\n\t\"siandian.com\": 1,\n\t\"sichina.com\": 1,\n\t\"siciciyu.com\": 1,\n\t\"sickcn.com\": 1,\n\t\"sidajiaoyu.com\": 1,\n\t\"sidri.com\": 1,\n\t\"sifa365.com\": 1,\n\t\"sigiscarf.com\": 1,\n\t\"sihaidiaoyu.com\": 1,\n\t\"sihaishuyuan.com\": 1,\n\t\"sihe.com\": 1,\n\t\"sihemy.com\": 1,\n\t\"sihey.com\": 1,\n\t\"sihongbbs.com\": 1,\n\t\"siilu.com\": 1,\n\t\"sijieqinmiao.com\": 1,\n\t\"sijinjiaju.com\": 1,\n\t\"sijiquan.com\": 1,\n\t\"sijitiemo.com\": 1,\n\t\"sikenet.com\": 1,\n\t\"siliaojixie.com\": 1,\n\t\"siliaoycw.com\": 1,\n\t\"siliconchina.org\": 1,\n\t\"siling.org\": 1,\n\t\"silingge.com\": 1,\n\t\"silucg.com\": 1,\n\t\"silversand.net\": 1,\n\t\"simingshan.com\": 1,\n\t\"simochem.com\": 1,\n\t\"simuwang.com\": 1,\n\t\"sina.com\": 1,\n\t\"sina.net\": 1,\n\t\"sinaapp.com\": 1,\n\t\"sinaedge.com\": 1,\n\t\"sinahk.net\": 1,\n\t\"sinaimg.com\": 1,\n\t\"sinajs.com\": 1,\n\t\"sinashow.com\": 1,\n\t\"singbon.com\": 1,\n\t\"singcere.net\": 1,\n\t\"singse.com\": 1,\n\t\"sinioa.com\": 1,\n\t\"sinmert.com\": 1,\n\t\"sino-manager.com\": 1,\n\t\"sino-web.net\": 1,\n\t\"sinocars.com\": 1,\n\t\"sinodtv.net\": 1,\n\t\"sinoec.net\": 1,\n\t\"sinoef.com\": 1,\n\t\"sinoergy.com\": 1,\n\t\"sinofarm.net\": 1,\n\t\"sinohydro.com\": 1,\n\t\"sinolub.com\": 1,\n\t\"sinomep.com\": 1,\n\t\"sinopec.com\": 1,\n\t\"sinopecgroup.com\": 1,\n\t\"sinopipenet.com\": 1,\n\t\"sinosig.com\": 1,\n\t\"sinoss.net\": 1,\n\t\"sinosteel.com\": 1,\n\t\"sinoteanet.com\": 1,\n\t\"sinotechline.com\": 1,\n\t\"sinotf.com\": 1,\n\t\"sinotrans-csc.com\": 1,\n\t\"sinovel.com\": 1,\n\t\"sinzhu.com\": 1,\n\t\"siphrd.com\": 1,\n\t\"sirenji.com\": 1,\n\t\"siriopharm.com\": 1,\n\t\"sissiok.com\": 1,\n\t\"siteloop.net\": 1,\n\t\"sitongbxg.com\": 1,\n\t\"siweiw.com\": 1,\n\t\"sixiangchina.com\": 1,\n\t\"sixiju.com\": 1,\n\t\"siyjob.com\": 1,\n\t\"siyrcw.com\": 1,\n\t\"siyuquanyun.com\": 1,\n\t\"sizuo.com\": 1,\n\t\"sj-tl.com\": 1,\n\t\"sj5d.com\": 1,\n\t\"sj998.com\": 1,\n\t\"sjapk.com\": 1,\n\t\"sjdfgl.com\": 1,\n\t\"sjfsy.com\": 1,\n\t\"sjfzxm.com\": 1,\n\t\"sjgou.com\": 1,\n\t\"sjjob88.com\": 1,\n\t\"sjkoo.com\": 1,\n\t\"sjqw.net\": 1,\n\t\"sjvip.com\": 1,\n\t\"sjway.com\": 1,\n\t\"sjwg.com\": 1,\n\t\"sjwj.com\": 1,\n\t\"sjwyx.com\": 1,\n\t\"sjxww.com\": 1,\n\t\"sjxyx.com\": 1,\n\t\"sjyyt.com\": 1,\n\t\"sjyzc.net\": 1,\n\t\"sjz.cc\": 1,\n\t\"sjzcity.com\": 1,\n\t\"sjzdd.net\": 1,\n\t\"sjzjiajiaow.com\": 1,\n\t\"sjzlongre.com\": 1,\n\t\"sjzmama.com\": 1,\n\t\"sjznews.com\": 1,\n\t\"sjzonline.com\": 1,\n\t\"sjzsheji.com\": 1,\n\t\"sjztjob.com\": 1,\n\t\"sjzyxh.com\": 1,\n\t\"sjzzsw.com\": 1,\n\t\"skg.com\": 1,\n\t\"skgskg.com\": 1,\n\t\"skinpp.com\": 1,\n\t\"skjcsc.com\": 1,\n\t\"skxox.com\": 1,\n\t\"sky-fire.com\": 1,\n\t\"skybig.net\": 1,\n\t\"skycn.com\": 1,\n\t\"skyworth.com\": 1,\n\t\"slanissue.com\": 1,\n\t\"slemb.com\": 1,\n\t\"sljjw.com\": 1,\n\t\"sljob88.com\": 1,\n\t\"slkj.org\": 1,\n\t\"sllssrq.com\": 1,\n\t\"slrbs.com\": 1,\n\t\"slstm.com\": 1,\n\t\"slsttc.com\": 1,\n\t\"slszs.com\": 1,\n\t\"slyy.org\": 1,\n\t\"slzb.com\": 1,\n\t\"slzyjsxy.com\": 1,\n\t\"sm597.com\": 1,\n\t\"sm598.com\": 1,\n\t\"smarthomecn.com\": 1,\n\t\"smarthu.com\": 1,\n\t\"smartjx.com\": 1,\n\t\"smchangan.net\": 1,\n\t\"smcjw.com\": 1,\n\t\"smecq.com\": 1,\n\t\"smecqpt.com\": 1,\n\t\"smefj.com\": 1,\n\t\"smegx.com\": 1,\n\t\"smegz.com\": 1,\n\t\"smejs.com\": 1,\n\t\"smelx.com\": 1,\n\t\"smeok.com\": 1,\n\t\"smestar.com\": 1,\n\t\"smforestry.com\": 1,\n\t\"smggw.com\": 1,\n\t\"smgjj.com\": 1,\n\t\"smhzs.com\": 1,\n\t\"smm.so\": 1,\n\t\"sms9.net\": 1,\n\t\"smszq.com\": 1,\n\t\"smudc.com\": 1,\n\t\"smvtc.com\": 1,\n\t\"smwrc.com\": 1,\n\t\"smxgjj.com\": 1,\n\t\"smxrcw.net\": 1,\n\t\"smxyz.com\": 1,\n\t\"smxzs.com\": 1,\n\t\"smyuan.com\": 1,\n\t\"smzdm.com\": 1,\n\t\"smzwzx.com\": 1,\n\t\"smzy.com\": 1,\n\t\"sn110.com\": 1,\n\t\"snail.com\": 1,\n\t\"snda.com\": 1,\n\t\"sndhr.com\": 1,\n\t\"sneac.com\": 1,\n\t\"snedu.com\": 1,\n\t\"snjob.com\": 1,\n\t\"snow021.com\": 1,\n\t\"snrtv.com\": 1,\n\t\"snsece.com\": 1,\n\t\"snsfun.cc\": 1,\n\t\"snsnb.com\": 1,\n\t\"snsqw.com\": 1,\n\t\"snsyx.com\": 1,\n\t\"snwugong.com\": 1,\n\t\"snxiaowai.com\": 1,\n\t\"snxw.com\": 1,\n\t\"snyu.com\": 1,\n\t\"snzhao.com\": 1,\n\t\"so.com\": 1,\n\t\"soautos.com\": 1,\n\t\"socang.com\": 1,\n\t\"soche8.com\": 1,\n\t\"socialtok.com\": 1,\n\t\"sociw.com\": 1,\n\t\"socksb2b.com\": 1,\n\t\"sodao.com\": 1,\n\t\"sodao.me\": 1,\n\t\"sodu.org\": 1,\n\t\"soe-soe.com\": 1,\n\t\"soershou.com\": 1,\n\t\"soft568.com\": 1,\n\t\"soft6.com\": 1,\n\t\"soft711.com\": 1,\n\t\"softbar.com\": 1,\n\t\"softhy.net\": 1,\n\t\"softparkinfo.com\": 1,\n\t\"softxp.net\": 1,\n\t\"sofu580.com\": 1,\n\t\"sogou.com\": 1,\n\t\"sogoucdn.com\": 1,\n\t\"sogoupc.com\": 1,\n\t\"sogua.com\": 1,\n\t\"sohochina.com\": 1,\n\t\"sohu.com\": 1,\n\t\"sohu.net\": 1,\n\t\"sohucs.com\": 1,\n\t\"sohusce.com\": 1,\n\t\"sohutuan.com\": 1,\n\t\"sojump.com\": 1,\n\t\"sokongyaji.com\": 1,\n\t\"soku.com\": 1,\n\t\"sola123.com\": 1,\n\t\"solar001.com\": 1,\n\t\"solar588.com\": 1,\n\t\"solarbe.com\": 1,\n\t\"solarchn.com\": 1,\n\t\"solarf.net\": 1,\n\t\"solargard.com\": 1,\n\t\"solarsupporting.com\": 1,\n\t\"solarzoom.com\": 1,\n\t\"solidot.org\": 1,\n\t\"somaiwang.com\": 1,\n\t\"somenmian.com\": 1,\n\t\"songbaixiang.com\": 1,\n\t\"songshuhui.net\": 1,\n\t\"songyuanrc.com\": 1,\n\t\"songzhuang365.com\": 1,\n\t\"songzi100.com\": 1,\n\t\"sonhoo.com\": 1,\n\t\"soo56.com\": 1,\n\t\"soo56.net\": 1,\n\t\"soocang.com\": 1,\n\t\"sooker.com\": 1,\n\t\"sooshong.com\": 1,\n\t\"sootoo.com\": 1,\n\t\"sooxue.com\": 1,\n\t\"sooyuu.com\": 1,\n\t\"soozhu.com\": 1,\n\t\"soperson.com\": 1,\n\t\"sortdoor.com\": 1,\n\t\"sosg.net\": 1,\n\t\"soshoo.com\": 1,\n\t\"soso.com\": 1,\n\t\"sosol.net\": 1,\n\t\"sosol.tv\": 1,\n\t\"sosoo.net\": 1,\n\t\"sososteel.com\": 1,\n\t\"sosoti.com\": 1,\n\t\"sosucai.com\": 1,\n\t\"sosuo.name\": 1,\n\t\"sosw.net\": 1,\n\t\"sotcbb.com\": 1,\n\t\"souacg.com\": 1,\n\t\"soubao.net\": 1,\n\t\"soubaoad.com\": 1,\n\t\"soucai.com\": 1,\n\t\"soucaigroup.com\": 1,\n\t\"souche.com\": 1,\n\t\"souchebang.com\": 1,\n\t\"soucheke.com\": 1,\n\t\"soucke.com\": 1,\n\t\"soucm.com\": 1,\n\t\"soudai360.com\": 1,\n\t\"soufang58.com\": 1,\n\t\"souff.com\": 1,\n\t\"soufun.com\": 1,\n\t\"soufunimg.com\": 1,\n\t\"souloo.com\": 1,\n\t\"soulou365.com\": 1,\n\t\"soulou8.com\": 1,\n\t\"soulvone.com\": 1,\n\t\"soupei360.com\": 1,\n\t\"soupingguo.com\": 1,\n\t\"soupu.com\": 1,\n\t\"souqian.com\": 1,\n\t\"sourceforge.net\": 1,\n\t\"southcn.com\": 1,\n\t\"southmoney.com\": 1,\n\t\"soutudi.so\": 1,\n\t\"souxuexiao.com\": 1,\n\t\"souyue.mobi\": 1,\n\t\"soweather.com\": 1,\n\t\"soxsok.com\": 1,\n\t\"soyouxi.com\": 1,\n\t\"soyuli.com\": 1,\n\t\"sozhen.com\": 1,\n\t\"sp910.com\": 1,\n\t\"spacechina.com\": 1,\n\t\"spasvo.com\": 1,\n\t\"spcce.com\": 1,\n\t\"spcywang.com\": 1,\n\t\"spdl.com\": 1,\n\t\"speiyou.com\": 1,\n\t\"spforum.net\": 1,\n\t\"spgykj.com\": 1,\n\t\"spiiker.com\": 1,\n\t\"spinlt.com\": 1,\n\t\"spjobhr.com\": 1,\n\t\"spjxcn.com\": 1,\n\t\"spo1973.com\": 1,\n\t\"spointdesign.com\": 1,\n\t\"sportscn.com\": 1,\n\t\"sporttery.com\": 1,\n\t\"springre.com\": 1,\n\t\"springtour.com\": 1,\n\t\"sprtc.com\": 1,\n\t\"spsb114.com\": 1,\n\t\"spzlwz.com\": 1,\n\t\"spzs.com\": 1,\n\t\"spzyw.com\": 1,\n\t\"sq1996.com\": 1,\n\t\"sq597.com\": 1,\n\t\"sqanju.com\": 1,\n\t\"sqbdt.com\": 1,\n\t\"sqcar.net\": 1,\n\t\"sqcjw.com\": 1,\n\t\"sqfc.com\": 1,\n\t\"sqfcw.com\": 1,\n\t\"sqjg.net\": 1,\n\t\"sqkk.com\": 1,\n\t\"sqrcw.com\": 1,\n\t\"sqs373.com\": 1,\n\t\"sqsjr.com\": 1,\n\t\"sqtv.net\": 1,\n\t\"sqyc.com\": 1,\n\t\"sqzhaopin.com\": 1,\n\t\"sqzhonghuan.com\": 1,\n\t\"sqzx.org\": 1,\n\t\"srcdd.com\": 1,\n\t\"srhcw.com\": 1,\n\t\"srrczpw.com\": 1,\n\t\"srtong.com\": 1,\n\t\"srxww.com\": 1,\n\t\"ss256.com\": 1,\n\t\"ss597.com\": 1,\n\t\"ssart.net\": 1,\n\t\"ssbgzzs.com\": 1,\n\t\"sscbw.com\": 1,\n\t\"sseinfo.com\": 1,\n\t\"ssfcw.com\": 1,\n\t\"ssfun.com\": 1,\n\t\"sshscom.net\": 1,\n\t\"ssjy.org\": 1,\n\t\"ssjzw.com\": 1,\n\t\"ssl-images-amazon.com\": 1,\n\t\"sslibrary.com\": 1,\n\t\"ssnn.net\": 1,\n\t\"ssnrw.com\": 1,\n\t\"ssofair.com\": 1,\n\t\"ssqzj.com\": 1,\n\t\"ssrcsc.com\": 1,\n\t\"ssswh.com\": 1,\n\t\"sstjtest.com\": 1,\n\t\"sswoo.com\": 1,\n\t\"ssxf.net\": 1,\n\t\"ssxw.net\": 1,\n\t\"ssydt.com\": 1,\n\t\"st5.com\": 1,\n\t\"stackoverflow.com\": 1,\n\t\"star365.com\": 1,\n\t\"star65.com\": 1,\n\t\"starbaby.cc\": 1,\n\t\"starbaby.com\": 1,\n\t\"starlott.com\": 1,\n\t\"startos.com\": 1,\n\t\"staticfile.org\": 1,\n\t\"statickksmg.com\": 1,\n\t\"staticsdo.com\": 1,\n\t\"stcn.com\": 1,\n\t\"stdaily.com\": 1,\n\t\"stedu.net\": 1,\n\t\"steelkx.com\": 1,\n\t\"steelphone.com\": 1,\n\t\"steelwin.com\": 1,\n\t\"steelyou.com\": 1,\n\t\"stjohnsau.com\": 1,\n\t\"stjunshi.com\": 1,\n\t\"stjzxx.com\": 1,\n\t\"stnts.com\": 1,\n\t\"stny369.com\": 1,\n\t\"stockstar.com\": 1,\n\t\"stockyc.com\": 1,\n\t\"stone.tm\": 1,\n\t\"stone365.com\": 1,\n\t\"stonesm.com\": 1,\n\t\"stonexp.com\": 1,\n\t\"stqq.com\": 1,\n\t\"strawberrynet.com\": 1,\n\t\"stre.net\": 1,\n\t\"strong-imm.com\": 1,\n\t\"strong-study.com\": 1,\n\t\"sttcw.com\": 1,\n\t\"sttlbb.com\": 1,\n\t\"studentboss.com\": 1,\n\t\"studydao.com\": 1,\n\t\"studyems.com\": 1,\n\t\"studyez.com\": 1,\n\t\"studyget.com\": 1,\n\t\"stuhack.com\": 1,\n\t\"stutrip.com\": 1,\n\t\"stylemode.com\": 1,\n\t\"su-long.com\": 1,\n\t\"suaee.com\": 1,\n\t\"suanpi.com\": 1,\n\t\"subaonet.com\": 1,\n\t\"sucaifengbao.com\": 1,\n\t\"sucaitianxia.com\": 1,\n\t\"sucaiw.com\": 1,\n\t\"sudasuta.com\": 1,\n\t\"sudupan.com\": 1,\n\t\"suduxx.com\": 1,\n\t\"suerda.net\": 1,\n\t\"sufeinet.com\": 1,\n\t\"sugarinfo.net\": 1,\n\t\"suifw.com\": 1,\n\t\"suiningwang.com\": 1,\n\t\"suixinews.net\": 1,\n\t\"suiyiju.com\": 1,\n\t\"suiyueart.com\": 1,\n\t\"suizhoushi.com\": 1,\n\t\"suizhoutg.com\": 1,\n\t\"sukeju.com\": 1,\n\t\"suloon.com\": 1,\n\t\"sumavision.com\": 1,\n\t\"sumcl.com\": 1,\n\t\"sumec.com\": 1,\n\t\"sumiao.net\": 1,\n\t\"sumiaohua.com\": 1,\n\t\"sumiaowang.com\": 1,\n\t\"summall.com\": 1,\n\t\"sun-cy.com\": 1,\n\t\"sun0575.com\": 1,\n\t\"sun0769.com\": 1,\n\t\"sunbo.com\": 1,\n\t\"sunchn.com\": 1,\n\t\"sungoal.org\": 1,\n\t\"sungrowpower.com\": 1,\n\t\"sunhouse2002.com\": 1,\n\t\"suning.com\": 1,\n\t\"sunkf.net\": 1,\n\t\"sunnychina.com\": 1,\n\t\"sunplusedu.com\": 1,\n\t\"sunrain.com\": 1,\n\t\"sunsirs.com\": 1,\n\t\"sunstu.com\": 1,\n\t\"sunvim.com\": 1,\n\t\"sunwy.org\": 1,\n\t\"sunyat-sen.org\": 1,\n\t\"sunyuanxx.com\": 1,\n\t\"suorang.com\": 1,\n\t\"supdri.com\": 1,\n\t\"superarmy.net\": 1,\n\t\"supercrm.com\": 1,\n\t\"supu8.com\": 1,\n\t\"supuw.com\": 1,\n\t\"supuy.com\": 1,\n\t\"suqiantuan.com\": 1,\n\t\"sushuo8.com\": 1,\n\t\"susongbbs.com\": 1,\n\t\"suv-trip.com\": 1,\n\t\"suvcm.com\": 1,\n\t\"suwurc.com\": 1,\n\t\"suxiazai.com\": 1,\n\t\"suxuewang.com\": 1,\n\t\"suyifbt.com\": 1,\n\t\"suzhounewswang.com\": 1,\n\t\"svw-volkswagen.com\": 1,\n\t\"swarow.com\": 1,\n\t\"swccw.com\": 1,\n\t\"swimbb.com\": 1,\n\t\"swjoy.com\": 1,\n\t\"swkong.com\": 1,\n\t\"swl.cc\": 1,\n\t\"swotbbs.com\": 1,\n\t\"swsm.net\": 1,\n\t\"swuee.com\": 1,\n\t\"swwenshi.com\": 1,\n\t\"swxchina.com\": 1,\n\t\"sx597.com\": 1,\n\t\"sxac.com\": 1,\n\t\"sxbjedu.com\": 1,\n\t\"sxc2255.com\": 1,\n\t\"sxcm.net\": 1,\n\t\"sxcntv.com\": 1,\n\t\"sxcnw.net\": 1,\n\t\"sxcoal.com\": 1,\n\t\"sxcse.com\": 1,\n\t\"sxdygbjy.com\": 1,\n\t\"sxdzs.com\": 1,\n\t\"sxejgfyxgs.com\": 1,\n\t\"sxfic.com\": 1,\n\t\"sxfsw.com\": 1,\n\t\"sxgdtv.com\": 1,\n\t\"sxinfo.net\": 1,\n\t\"sxjdmh.com\": 1,\n\t\"sxjx.org\": 1,\n\t\"sxjzwb.com\": 1,\n\t\"sxkp.com\": 1,\n\t\"sxlib.com\": 1,\n\t\"sxlottery.net\": 1,\n\t\"sxlove.net\": 1,\n\t\"sxlychina.com\": 1,\n\t\"sxmtxs.com\": 1,\n\t\"sxmzc.com\": 1,\n\t\"sxncb.com\": 1,\n\t\"sxny.net\": 1,\n\t\"sxol.com\": 1,\n\t\"sxpmg.com\": 1,\n\t\"sxpre.com\": 1,\n\t\"sxpta.com\": 1,\n\t\"sxpxks.com\": 1,\n\t\"sxqc.com\": 1,\n\t\"sxqiche.com\": 1,\n\t\"sxqx.net\": 1,\n\t\"sxrb.com\": 1,\n\t\"sxrcw.com\": 1,\n\t\"sxrtv.com\": 1,\n\t\"sxsanwei.com\": 1,\n\t\"sxsedu.net\": 1,\n\t\"sxshangjie.com\": 1,\n\t\"sxshu.com\": 1,\n\t\"sxsznews.com\": 1,\n\t\"sxtdrn.com\": 1,\n\t\"sxtour.com\": 1,\n\t\"sxtvs.com\": 1,\n\t\"sxtwedu.com\": 1,\n\t\"sxw100.com\": 1,\n\t\"sxwhty.com\": 1,\n\t\"sxworker.com\": 1,\n\t\"sxxcy.net\": 1,\n\t\"sxxsp.com\": 1,\n\t\"sxxw.net\": 1,\n\t\"sxxynews.com\": 1,\n\t\"sxxzxy.com\": 1,\n\t\"sxycpc.com\": 1,\n\t\"sxycrb.com\": 1,\n\t\"sxyhq.com\": 1,\n\t\"sxzcjyw.com\": 1,\n\t\"sxzj.net\": 1,\n\t\"sxzjcoop.com\": 1,\n\t\"sy128.com\": 1,\n\t\"sy456.com\": 1,\n\t\"sycu.net\": 1,\n\t\"sydang.com\": 1,\n\t\"sydaxxw.com\": 1,\n\t\"syedugroup.com\": 1,\n\t\"syfc.cc\": 1,\n\t\"syfff.com\": 1,\n\t\"sygjj.com\": 1,\n\t\"sygz1945.com\": 1,\n\t\"syhfw.com\": 1,\n\t\"syhhidc.com\": 1,\n\t\"syhmw.com\": 1,\n\t\"syhr.net\": 1,\n\t\"sying.com\": 1,\n\t\"syiptv.com\": 1,\n\t\"syjiancai.com\": 1,\n\t\"syjzjc.com\": 1,\n\t\"sykong.com\": 1,\n\t\"symama.com\": 1,\n\t\"symtc.com\": 1,\n\t\"synacast.com\": 1,\n\t\"synedu.net\": 1,\n\t\"synochip.com\": 1,\n\t\"syogame.net\": 1,\n\t\"sypf.com\": 1,\n\t\"sypglass.com\": 1,\n\t\"syqcw.net\": 1,\n\t\"syqnr.com\": 1,\n\t\"syrcw.net\": 1,\n\t\"syrczpw.com\": 1,\n\t\"sysczn.com\": 1,\n\t\"sysese.com\": 1,\n\t\"sysu-edu.org\": 1,\n\t\"sysuyz.com\": 1,\n\t\"syswin.com\": 1,\n\t\"syszyl.net\": 1,\n\t\"sytxxzsp.com\": 1,\n\t\"sytzw.com\": 1,\n\t\"syuan.net\": 1,\n\t\"sywsnet.com\": 1,\n\t\"syxwnet.com\": 1,\n\t\"syyx.com\": 1,\n\t\"syzol.com\": 1,\n\t\"syzxyz.com\": 1,\n\t\"sz-3a.com\": 1,\n\t\"sz-english.com\": 1,\n\t\"sz-qb.com\": 1,\n\t\"sz-yugong.com\": 1,\n\t\"sz100.net\": 1,\n\t\"sz1001.net\": 1,\n\t\"sz1w.com\": 1,\n\t\"sz1w.net\": 1,\n\t\"sz2011.org\": 1,\n\t\"sz61.com\": 1,\n\t\"sz68.com\": 1,\n\t\"sz7h.com\": 1,\n\t\"sz910.com\": 1,\n\t\"szaee.com\": 1,\n\t\"szaeia.com\": 1,\n\t\"szai.com\": 1,\n\t\"szass.com\": 1,\n\t\"szbbs.org\": 1,\n\t\"szcec.com\": 1,\n\t\"szceo.com\": 1,\n\t\"szcfxx.com\": 1,\n\t\"szcj.net\": 1,\n\t\"szdlkt.com\": 1,\n\t\"szeat.net\": 1,\n\t\"szects.com\": 1,\n\t\"szeds.com\": 1,\n\t\"szedu.com\": 1,\n\t\"szedu.net\": 1,\n\t\"szehs.com\": 1,\n\t\"szewhm.com\": 1,\n\t\"szfa.com\": 1,\n\t\"szfcol.com\": 1,\n\t\"szfutong.com\": 1,\n\t\"szfw.org\": 1,\n\t\"szgamfe.com\": 1,\n\t\"szgla.com\": 1,\n\t\"szguanai.com\": 1,\n\t\"szgujian.com\": 1,\n\t\"szhk.com\": 1,\n\t\"szhome.com\": 1,\n\t\"szhomeimg.com\": 1,\n\t\"szhongmu.com\": 1,\n\t\"szhr.com\": 1,\n\t\"szhrzp.com\": 1,\n\t\"szhufu.com\": 1,\n\t\"szjianguo.com\": 1,\n\t\"szjiaz.com\": 1,\n\t\"szjjedu.com\": 1,\n\t\"szjjzlh.com\": 1,\n\t\"szkz.com\": 1,\n\t\"szlab17.com\": 1,\n\t\"szlottery.org\": 1,\n\t\"szlyw12306.com\": 1,\n\t\"szlyzx.com\": 1,\n\t\"szmama.com\": 1,\n\t\"szmama.net\": 1,\n\t\"szmj.com\": 1,\n\t\"szmonalisa.com\": 1,\n\t\"sznews.com\": 1,\n\t\"sznewworld.net\": 1,\n\t\"sznmd.com\": 1,\n\t\"szol.net\": 1,\n\t\"szonline.net\": 1,\n\t\"szooo.com\": 1,\n\t\"szphoto.com\": 1,\n\t\"szpku-edu.com\": 1,\n\t\"szpxe.com\": 1,\n\t\"szqcw.com\": 1,\n\t\"szrc88.com\": 1,\n\t\"szredstone.com\": 1,\n\t\"szsfwzx.com\": 1,\n\t\"szsh.com\": 1,\n\t\"szsolar.org\": 1,\n\t\"szsta.org\": 1,\n\t\"szsti.net\": 1,\n\t\"sztalent.org\": 1,\n\t\"sztaoche.net\": 1,\n\t\"sztaofang.com\": 1,\n\t\"sztian.com\": 1,\n\t\"szutek.com\": 1,\n\t\"szvenushs.com\": 1,\n\t\"szwudao.com\": 1,\n\t\"szwwxn.com\": 1,\n\t\"szxdcc.com\": 1,\n\t\"szxnews.com\": 1,\n\t\"szyc.com\": 1,\n\t\"szykj.net\": 1,\n\t\"szyyx.com\": 1,\n\t\"szzfgjj.com\": 1,\n\t\"szzgh.org\": 1,\n\t\"t0001.com\": 1,\n\t\"t0376.com\": 1,\n\t\"t0888.com\": 1,\n\t\"t139.com\": 1,\n\t\"t262.com\": 1,\n\t\"t3nclick.com\": 1,\n\t\"t3nlink.com\": 1,\n\t\"t56.net\": 1,\n\t\"t978.com\": 1,\n\t\"taaas.org\": 1,\n\t\"tadercn.com\": 1,\n\t\"tadiao168.com\": 1,\n\t\"tadu.com\": 1,\n\t\"tahota-lawyer.com\": 1,\n\t\"tai87.com\": 1,\n\t\"taian.com\": 1,\n\t\"taicang.info\": 1,\n\t\"taicanghr.com\": 1,\n\t\"taihainet.com\": 1,\n\t\"taikang.com\": 1,\n\t\"tainfo.net\": 1,\n\t\"taiqian.cc\": 1,\n\t\"taisha.org\": 1,\n\t\"taiwandao.tw\": 1,\n\t\"taiweifeng.com\": 1,\n\t\"taizhou.cc\": 1,\n\t\"taizhou.com\": 1,\n\t\"takungpao.com\": 1,\n\t\"takungpao.com.hk\": 1,\n\t\"talentsmag.com\": 1,\n\t\"talicai.com\": 1,\n\t\"talkforex.com\": 1,\n\t\"talkyun.com\": 1,\n\t\"tan8.com\": 1,\n\t\"tangdou.com\": 1,\n\t\"tangdouban.com\": 1,\n\t\"tangjiu.com\": 1,\n\t\"tangjiu001.com\": 1,\n\t\"tangongye.com\": 1,\n\t\"tangrenju.net\": 1,\n\t\"tangxia.tv\": 1,\n\t\"tanjiaoyi.com\": 1,\n\t\"tanpaifang.com\": 1,\n\t\"tansuonet.com\": 1,\n\t\"tantuw.com\": 1,\n\t\"tanx.com\": 1,\n\t\"tao.bb\": 1,\n\t\"tao123.com\": 1,\n\t\"tao15.com\": 1,\n\t\"tao775.com\": 1,\n\t\"taoban.com\": 1,\n\t\"taobao.com\": 1,\n\t\"taobao.net\": 1,\n\t\"taobaocdn.com\": 1,\n\t\"taoche.com\": 1,\n\t\"taoche100.com\": 1,\n\t\"taoche8.com\": 1,\n\t\"taoci.com\": 1,\n\t\"taoci365.com\": 1,\n\t\"taocici.com\": 1,\n\t\"taocijiaju.com\": 1,\n\t\"taocijob.com\": 1,\n\t\"taocz.com\": 1,\n\t\"taodake.com\": 1,\n\t\"taodanyang.com\": 1,\n\t\"taoducity.com\": 1,\n\t\"taofang.com\": 1,\n\t\"taofen8.com\": 1,\n\t\"taogula.com\": 1,\n\t\"taohuren.com\": 1,\n\t\"taojindi.com\": 1,\n\t\"taojinyi.com\": 1,\n\t\"taoke.com\": 1,\n\t\"taolv365.com\": 1,\n\t\"taomee.com\": 1,\n\t\"taonb.com\": 1,\n\t\"taoneimeng.com\": 1,\n\t\"taoniu.com\": 1,\n\t\"taood.com\": 1,\n\t\"taopic.com\": 1,\n\t\"taoren100.com\": 1,\n\t\"taose98.com\": 1,\n\t\"taoshouyou.com\": 1,\n\t\"taoshu.com\": 1,\n\t\"taotaocar.com\": 1,\n\t\"taoxie.com\": 1,\n\t\"taoyunet.com\": 1,\n\t\"tarenacn.com\": 1,\n\t\"tarenasz.com\": 1,\n\t\"tarkett1872.com\": 1,\n\t\"tartsmy.com\": 1,\n\t\"taskcn.com\": 1,\n\t\"tattoo77.com\": 1,\n\t\"tax-edu.net\": 1,\n\t\"tayasaf.com\": 1,\n\t\"tb-apps.com\": 1,\n\t\"tb520.com\": 1,\n\t\"tb888.net\": 1,\n\t\"tbcache.com\": 1,\n\t\"tbkf.net\": 1,\n\t\"tbnimg.com\": 1,\n\t\"tbs-china.com\": 1,\n\t\"tbscache.com\": 1,\n\t\"tbt.cc\": 1,\n\t\"tbtsps.com\": 1,\n\t\"tbxt.com\": 1,\n\t\"tc550.com\": 1,\n\t\"tcaccp.com\": 1,\n\t\"tcdushi.com\": 1,\n\t\"tcl-lighting.com\": 1,\n\t\"tcl.com\": 1,\n\t\"tcl37.net\": 1,\n\t\"tcm361.com\": 1,\n\t\"tcnews.cc\": 1,\n\t\"tcrcsc.com\": 1,\n\t\"tcrczpw.com\": 1,\n\t\"tctzby.com\": 1,\n\t\"tcxw.cc\": 1,\n\t\"tczp.net\": 1,\n\t\"td776.com\": 1,\n\t\"tdbnw.com\": 1,\n\t\"tdfcw.com\": 1,\n\t\"tdimg.com\": 1,\n\t\"tdsyj.com\": 1,\n\t\"tdzyw.com\": 1,\n\t\"te6.com\": 1,\n\t\"tea-shexpo.com\": 1,\n\t\"tea160.com\": 1,\n\t\"tea846.com\": 1,\n\t\"tea8848.com\": 1,\n\t\"teachercn.com\": 1,\n\t\"teacherzp.com\": 1,\n\t\"teambuy.cc\": 1,\n\t\"teapic.com\": 1,\n\t\"teauo.com\": 1,\n\t\"tech-ex.com\": 1,\n\t\"tech-food.com\": 1,\n\t\"tech110.net\": 1,\n\t\"tech2ipo.com\": 1,\n\t\"techan.com\": 1,\n\t\"techannet.com\": 1,\n\t\"techanzs.com\": 1,\n\t\"techxue.com\": 1,\n\t\"tedianwang.com\": 1,\n\t\"tejia01.com\": 1,\n\t\"telecomhr.com\": 1,\n\t\"telojob.com\": 1,\n\t\"temaiku.com\": 1,\n\t\"tencent.com\": 1,\n\t\"tencentmind.com\": 1,\n\t\"tengfang.net\": 1,\n\t\"tengfun.com\": 1,\n\t\"tengzhourcw.com\": 1,\n\t\"tenpay.com\": 1,\n\t\"tesehunan.com\": 1,\n\t\"test-edu.com\": 1,\n\t\"test3g.com\": 1,\n\t\"testmart.co\": 1,\n\t\"testrust.com\": 1,\n\t\"tex68.com\": 1,\n\t\"tex688.com\": 1,\n\t\"texrc.net\": 1,\n\t\"texu1.com\": 1,\n\t\"teyoutuan.com\": 1,\n\t\"tezgc.com\": 1,\n\t\"tfauto.net\": 1,\n\t\"tffcw.com\": 1,\n\t\"tffood.net\": 1,\n\t\"tfrl.net\": 1,\n\t\"tfx888.com\": 1,\n\t\"tfyou.net\": 1,\n\t\"tfysw.com\": 1,\n\t\"tg0123.com\": 1,\n\t\"tgbus.com\": 1,\n\t\"tghezuoshe.com\": 1,\n\t\"thawte.com\": 1,\n\t\"thcha.com\": 1,\n\t\"the9.com\": 1,\n\t\"thebeijingnews.com\": 1,\n\t\"thechinawatch.com\": 1,\n\t\"theplanet.com\": 1,\n\t\"thethirdmedia.com\": 1,\n\t\"thetianfu.com\": 1,\n\t\"thhome.net\": 1,\n\t\"thjunshi.com\": 1,\n\t\"thmall.com\": 1,\n\t\"thmz.com\": 1,\n\t\"thshengda.com\": 1,\n\t\"thsware.com\": 1,\n\t\"thxdbj.com\": 1,\n\t\"thxy.org\": 1,\n\t\"thyoo.com\": 1,\n\t\"tiancity.com\": 1,\n\t\"tiancitycdn.com\": 1,\n\t\"tiandaoedu.com\": 1,\n\t\"tianditu.com\": 1,\n\t\"tianhan.org\": 1,\n\t\"tianinfo.com\": 1,\n\t\"tianji.com\": 1,\n\t\"tianjihr.com\": 1,\n\t\"tianjimedia.com\": 1,\n\t\"tianjinrc.com\": 1,\n\t\"tianjinwe.com\": 1,\n\t\"tiannv.com\": 1,\n\t\"tianpingxian.com\": 1,\n\t\"tianqi.com\": 1,\n\t\"tianqizhubo.net\": 1,\n\t\"tianshangrenjian123.com\": 1,\n\t\"tianshannet.com\": 1,\n\t\"tianshanrc.com\": 1,\n\t\"tiantian.com\": 1,\n\t\"tiantianhr.com\": 1,\n\t\"tiantianjob.com\": 1,\n\t\"tiantianxuexi.com\": 1,\n\t\"tiantianyj.com\": 1,\n\t\"tianxiazhi.net\": 1,\n\t\"tianya.net\": 1,\n\t\"tianya168.net\": 1,\n\t\"tianyaclub.com\": 1,\n\t\"tianyangjx869.com\": 1,\n\t\"tianyaui.com\": 1,\n\t\"tiao8.info\": 1,\n\t\"tiaomou.com\": 1,\n\t\"tiaowu.la\": 1,\n\t\"tibet-g.com\": 1,\n\t\"tibet3.com\": 1,\n\t\"tibetcn.com\": 1,\n\t\"tibetculture.net\": 1,\n\t\"tibetinfor.com\": 1,\n\t\"tibetmagazine.net\": 1,\n\t\"tibetpic.com\": 1,\n\t\"tiebaimg.com\": 1,\n\t\"tiebaobei.com\": 1,\n\t\"tiebaojiao.com\": 1,\n\t\"tiedelao.com\": 1,\n\t\"tiekuangshi.com\": 1,\n\t\"tielingcn.com\": 1,\n\t\"tielu.org\": 1,\n\t\"tietuku.com\": 1,\n\t\"tiexue.net\": 1,\n\t\"tieyou.com\": 1,\n\t\"tigtag.com\": 1,\n\t\"tihengjian.com\": 1,\n\t\"tihuedu.com\": 1,\n\t\"timall.hk\": 1,\n\t\"timberland-china.com\": 1,\n\t\"time-weekly.com\": 1,\n\t\"timedg.com\": 1,\n\t\"timeep.com\": 1,\n\t\"timeoutcn.com\": 1,\n\t\"ting30.com\": 1,\n\t\"ting56.com\": 1,\n\t\"ting89.com\": 1,\n\t\"tingbook.com\": 1,\n\t\"tingchina.com\": 1,\n\t\"tingclass.net\": 1,\n\t\"tingfree.com\": 1,\n\t\"tingge123.com\": 1,\n\t\"tingroom.com\": 1,\n\t\"tingshuge.com\": 1,\n\t\"tingvoa.com\": 1,\n\t\"tingyuxuan.net\": 1,\n\t\"tirechina.net\": 1,\n\t\"tisahome.com\": 1,\n\t\"titan24.com\": 1,\n\t\"tiyubisai.com\": 1,\n\t\"tjaee.com\": 1,\n\t\"tjbb.com\": 1,\n\t\"tjchildrenshospital.com\": 1,\n\t\"tjcoop.com\": 1,\n\t\"tjfic.com\": 1,\n\t\"tjflcpw.com\": 1,\n\t\"tjinfo.com\": 1,\n\t\"tjj.com\": 1,\n\t\"tjkpzx.com\": 1,\n\t\"tjkx.com\": 1,\n\t\"tjkximg.com\": 1,\n\t\"tjmama.com\": 1,\n\t\"tjmylike.com\": 1,\n\t\"tjredcross.org\": 1,\n\t\"tjshangceng.com\": 1,\n\t\"tjsjx.com\": 1,\n\t\"tjwang.net\": 1,\n\t\"tjzjbbs.com\": 1,\n\t\"tjzxfc.com\": 1,\n\t\"tl100.com\": 1,\n\t\"tl111.com\": 1,\n\t\"tlb2b.com\": 1,\n\t\"tlbaobao.com\": 1,\n\t\"tlbb2.com\": 1,\n\t\"tlbb8.com\": 1,\n\t\"tlbbsifu.com\": 1,\n\t\"tlfrc.com\": 1,\n\t\"tlfw.net\": 1,\n\t\"tlhr.net\": 1,\n\t\"tljob8001.com\": 1,\n\t\"tlpsr.com\": 1,\n\t\"tlpump.com\": 1,\n\t\"tlrc.com\": 1,\n\t\"tltesoft.com\": 1,\n\t\"tm51.com\": 1,\n\t\"tm9999.com\": 1,\n\t\"tmall.com\": 1,\n\t\"tmbbs.com\": 1,\n\t\"tmcdn.net\": 1,\n\t\"tmfang.com\": 1,\n\t\"tmhtour.com\": 1,\n\t\"tmjob88.com\": 1,\n\t\"tmjyw.com\": 1,\n\t\"tmrcw.com\": 1,\n\t\"tmsf.com\": 1,\n\t\"tmtbib.net\": 1,\n\t\"tmtforum.com\": 1,\n\t\"tmtpost.com\": 1,\n\t\"tmwcn.com\": 1,\n\t\"tnbxw.com\": 1,\n\t\"to360.com\": 1,\n\t\"to61.com\": 1,\n\t\"to8to.com\": 1,\n\t\"tobaccochina.com\": 1,\n\t\"tobaccochina.net\": 1,\n\t\"toberp.com\": 1,\n\t\"tobosu.com\": 1,\n\t\"tobosu.net\": 1,\n\t\"todayartmuseum.com\": 1,\n\t\"todayidc.com\": 1,\n\t\"todaynic.com\": 1,\n\t\"todayonhistory.com\": 1,\n\t\"toefl-edu.org\": 1,\n\t\"toefljuniorchina.com\": 1,\n\t\"togoo.com\": 1,\n\t\"toidea.com\": 1,\n\t\"tokung.com\": 1,\n\t\"tom.com\": 1,\n\t\"tom61.com\": 1,\n\t\"tomatolei.com\": 1,\n\t\"tomdurrie.com\": 1,\n\t\"tompda.com\": 1,\n\t\"tomx.com\": 1,\n\t\"tong12.com\": 1,\n\t\"tongbu.com\": 1,\n\t\"tonghaigroup.com\": 1,\n\t\"tonghuanet.com\": 1,\n\t\"tongjishi.com\": 1,\n\t\"tongkong.com\": 1,\n\t\"tonglian1998.com\": 1,\n\t\"tongliaowang.com\": 1,\n\t\"tonglingjob.com\": 1,\n\t\"tonglukuaijian.com\": 1,\n\t\"tongluren.com\": 1,\n\t\"tongpiao.com\": 1,\n\t\"tongqu.com\": 1,\n\t\"tongqz.com\": 1,\n\t\"tongxiang.net\": 1,\n\t\"tongxue8.com\": 1,\n\t\"tongyouku.com\": 1,\n\t\"tonymary.com\": 1,\n\t\"tooben.com\": 1,\n\t\"toobiao.com\": 1,\n\t\"toobm.com\": 1,\n\t\"toocle.com\": 1,\n\t\"toocrystal.com\": 1,\n\t\"toofloor.com\": 1,\n\t\"toojj.com\": 1,\n\t\"tool.la\": 1,\n\t\"tooopen.com\": 1,\n\t\"tootour.com\": 1,\n\t\"top100summit.com\": 1,\n\t\"top17.net\": 1,\n\t\"topbm.com\": 1,\n\t\"topbrandunion.com\": 1,\n\t\"topcfo.net\": 1,\n\t\"topdtv.com\": 1,\n\t\"topenergy.org\": 1,\n\t\"topfo.com\": 1,\n\t\"topfreebiz.com\": 1,\n\t\"topielts.com\": 1,\n\t\"topit.me\": 1,\n\t\"topjt.com\": 1,\n\t\"topnews9.com\": 1,\n\t\"toppk.net\": 1,\n\t\"topqikan.com\": 1,\n\t\"topsage.com\": 1,\n\t\"topsj.com\": 1,\n\t\"topthink.com\": 1,\n\t\"topu.com\": 1,\n\t\"topzj.com\": 1,\n\t\"torozi.com\": 1,\n\t\"totob.com\": 1,\n\t\"touchchinaexpo.com\": 1,\n\t\"touchf.com\": 1,\n\t\"touclick.com\": 1,\n\t\"touding.com\": 1,\n\t\"tour17.com\": 1,\n\t\"tourcool.com\": 1,\n\t\"tourdz.com\": 1,\n\t\"tourjob.net\": 1,\n\t\"tours010.com\": 1,\n\t\"toursforfun.com\": 1,\n\t\"tourzj.com\": 1,\n\t\"toutiao.com\": 1,\n\t\"toutouwan.com\": 1,\n\t\"touzhijia.com\": 1,\n\t\"touzhuzhan.com\": 1,\n\t\"touzishi.com\": 1,\n\t\"toxihu.com\": 1,\n\t\"toybaba.com\": 1,\n\t\"toyclubcn.com\": 1,\n\t\"toys365.com\": 1,\n\t\"toysbao.com\": 1,\n\t\"toysgu.com\": 1,\n\t\"tpooo.com\": 1,\n\t\"tprtc.com\": 1,\n\t\"tpu-ptfe.com\": 1,\n\t\"tpzj.com\": 1,\n\t\"tqedu.com\": 1,\n\t\"tqh168.com\": 1,\n\t\"tqkaoyan.com\": 1,\n\t\"tqlsgroup.com\": 1,\n\t\"tqmba.com\": 1,\n\t\"trade2cn.com\": 1,\n\t\"tradesns.com\": 1,\n\t\"tranbbs.com\": 1,\n\t\"travelhuzhou.com\": 1,\n\t\"travellingscope.com\": 1,\n\t\"travelsky.com\": 1,\n\t\"trdcafes.com\": 1,\n\t\"treerly.com\": 1,\n\t\"tremormedia.com\": 1,\n\t\"trfcw.com\": 1,\n\t\"trhos.com\": 1,\n\t\"trip8080.com\": 1,\n\t\"tripbaba.com\": 1,\n\t\"tripc.net\": 1,\n\t\"tripdv.com\": 1,\n\t\"tripear.com\": 1,\n\t\"trjcn.com\": 1,\n\t\"trustexporter.com\": 1,\n\t\"trustutn.org\": 1,\n\t\"trylist.com\": 1,\n\t\"tscanyin.com\": 1,\n\t\"tscndd.com\": 1,\n\t\"tshcf.com\": 1,\n\t\"tsichuan.com\": 1,\n\t\"tsinghua-sz.com\": 1,\n\t\"tsinghuapxb.com\": 1,\n\t\"tsjiuyeba.com\": 1,\n\t\"tskjzs.com\": 1,\n\t\"tsrcw.com\": 1,\n\t\"tszlx.net\": 1,\n\t\"tt-ly.com\": 1,\n\t\"tt0760.com\": 1,\n\t\"tt65.net\": 1,\n\t\"tt803.com\": 1,\n\t\"tt919.com\": 1,\n\t\"tt98.com\": 1,\n\t\"ttacc.net\": 1,\n\t\"ttb2b.com\": 1,\n\t\"ttche.com\": 1,\n\t\"tteb.com\": 1,\n\t\"ttgood.com\": 1,\n\t\"tthcw.com\": 1,\n\t\"tthhw.com\": 1,\n\t\"tthonghuo.com\": 1,\n\t\"ttkdex.com\": 1,\n\t\"ttmeishi.com\": 1,\n\t\"ttmn.com\": 1,\n\t\"ttpet.com\": 1,\n\t\"ttpod.com\": 1,\n\t\"ttqmw.com\": 1,\n\t\"ttrencai.com\": 1,\n\t\"ttslsd.com\": 1,\n\t\"ttszy.net\": 1,\n\t\"tttuangou.net\": 1,\n\t\"tttv.tv\": 1,\n\t\"tttz.com\": 1,\n\t\"ttufo.com\": 1,\n\t\"ttxuexi.net\": 1,\n\t\"ttyl5.com\": 1,\n\t\"ttys5.com\": 1,\n\t\"ttzcw.com\": 1,\n\t\"ttzhaogong.com\": 1,\n\t\"tu50.com\": 1,\n\t\"tuan800.com\": 1,\n\t\"tuan800.net\": 1,\n\t\"tuanche.com\": 1,\n\t\"tuanhuopu.com\": 1,\n\t\"tuanimg.com\": 1,\n\t\"tuanjiebao.com\": 1,\n\t\"tuanjw.com\": 1,\n\t\"tuanping.com\": 1,\n\t\"tuanweihui.com\": 1,\n\t\"tuboshu.com\": 1,\n\t\"tucao.cc\": 1,\n\t\"tuchw.com\": 1,\n\t\"tucoo.com\": 1,\n\t\"tudidaili.com\": 1,\n\t\"tudigujia.com\": 1,\n\t\"tudou.com\": 1,\n\t\"tudouui.com\": 1,\n\t\"tuhaonet.com\": 1,\n\t\"tui18.com\": 1,\n\t\"tui18edu.com\": 1,\n\t\"tui8.org\": 1,\n\t\"tuicool.com\": 1,\n\t\"tuidc.com\": 1,\n\t\"tuifeiapi.com\": 1,\n\t\"tuike888.com\": 1,\n\t\"tuilie.com\": 1,\n\t\"tuiq.net\": 1,\n\t\"tuitui99.com\": 1,\n\t\"tuituifang.com\": 1,\n\t\"tujia.com\": 1,\n\t\"tukeq.com\": 1,\n\t\"tuku.cc\": 1,\n\t\"tuku.com\": 1,\n\t\"tulaomao.net\": 1,\n\t\"tulaoshi.com\": 1,\n\t\"tuliao86.com\": 1,\n\t\"tuliaotuyao.com\": 1,\n\t\"tuliu.com\": 1,\n\t\"tulvzu.com\": 1,\n\t\"tumanduo.com\": 1,\n\t\"tumukeji.com\": 1,\n\t\"tuniu.com\": 1,\n\t\"tuniucdn.com\": 1,\n\t\"tuojin.net\": 1,\n\t\"tuoliji.net\": 1,\n\t\"tuoxian.net\": 1,\n\t\"tuozhanzhe.org\": 1,\n\t\"tuozhe8.com\": 1,\n\t\"tupian114.com\": 1,\n\t\"tupianzj.com\": 1,\n\t\"tuquu.com\": 1,\n\t\"turbocms.com\": 1,\n\t\"turenscape.com\": 1,\n\t\"tusiliao.com\": 1,\n\t\"tuu.so\": 1,\n\t\"tuwan.com\": 1,\n\t\"tuxiaobei.com\": 1,\n\t\"tuyexinxi.com\": 1,\n\t\"tuzi8.com\": 1,\n\t\"tv0714.com\": 1,\n\t\"tv189.com\": 1,\n\t\"tv373.com\": 1,\n\t\"tvapk.net\": 1,\n\t\"tvb.me\": 1,\n\t\"tvhf.com\": 1,\n\t\"tvhome.com\": 1,\n\t\"tvhuan.com\": 1,\n\t\"tvlicai.com\": 1,\n\t\"tvmao.com\": 1,\n\t\"tvmining.com\": 1,\n\t\"tvptv.com\": 1,\n\t\"tvscn.com\": 1,\n\t\"tvsou.com\": 1,\n\t\"twcczhu.com\": 1,\n\t\"twl123.com\": 1,\n\t\"tx365.com\": 1,\n\t\"tx96345.com\": 1,\n\t\"txdai.com\": 1,\n\t\"txdzw.com\": 1,\n\t\"txooo.com\": 1,\n\t\"txrz.com\": 1,\n\t\"txsec.com\": 1,\n\t\"txssw.com\": 1,\n\t\"txt99.cc\": 1,\n\t\"txtbbs.com\": 1,\n\t\"txuuu.com\": 1,\n\t\"txw.com\": 1,\n\t\"txwm.com\": 1,\n\t\"txxxb.com\": 1,\n\t\"txyes.com\": 1,\n\t\"txysyy.com\": 1,\n\t\"txzpw.net\": 1,\n\t\"ty360.com\": 1,\n\t\"tybaba.com\": 1,\n\t\"tybus.com\": 1,\n\t\"tycqjy.com\": 1,\n\t\"tygjj.com\": 1,\n\t\"tyguomiao.net\": 1,\n\t\"tyjzk.com\": 1,\n\t\"tyn.cc\": 1,\n\t\"tyn100.com\": 1,\n\t\"tyncar.com\": 1,\n\t\"tyread.com\": 1,\n\t\"tytarena.com\": 1,\n\t\"tyueo.com\": 1,\n\t\"tyuyan.com\": 1,\n\t\"tyx.cc\": 1,\n\t\"tyxrc.com\": 1,\n\t\"tyzn.net\": 1,\n\t\"tz-job.com\": 1,\n\t\"tz-rc.net\": 1,\n\t\"tz.cc\": 1,\n\t\"tz0852.com\": 1,\n\t\"tz121.com\": 1,\n\t\"tz2100.com\": 1,\n\t\"tz55.net\": 1,\n\t\"tz911.com\": 1,\n\t\"tz94.com\": 1,\n\t\"tzcdc.org\": 1,\n\t\"tzckj.cc\": 1,\n\t\"tzcz.com\": 1,\n\t\"tzedu.org\": 1,\n\t\"tzeju.com\": 1,\n\t\"tzesf.com\": 1,\n\t\"tzfdc.com\": 1,\n\t\"tzgjj.net\": 1,\n\t\"tzhaoma.com\": 1,\n\t\"tzhcz.net\": 1,\n\t\"tzhr.com\": 1,\n\t\"tzhuan.com\": 1,\n\t\"tzhzh.com\": 1,\n\t\"tzinfo.net\": 1,\n\t\"tzjob.cc\": 1,\n\t\"tzjob.com\": 1,\n\t\"tzkd.com\": 1,\n\t\"tzks.net\": 1,\n\t\"tzlink.com\": 1,\n\t\"tzmaimai.com\": 1,\n\t\"tzmarry.com\": 1,\n\t\"tzrc.com\": 1,\n\t\"tzrcg.com\": 1,\n\t\"tzrl.com\": 1,\n\t\"tzsf.org\": 1,\n\t\"tzshenxin.com\": 1,\n\t\"tzsnw.com\": 1,\n\t\"tzswdx.com\": 1,\n\t\"tztjfc.com\": 1,\n\t\"tztlt.com\": 1,\n\t\"tzxctz.com\": 1,\n\t\"tzxcw.com\": 1,\n\t\"tzyouth.com\": 1,\n\t\"tzzgz.com\": 1,\n\t\"tzzp.com\": 1,\n\t\"tzzufang.com\": 1,\n\t\"u0.com\": 1,\n\t\"u009.com\": 1,\n\t\"u0351.com\": 1,\n\t\"u0762.com\": 1,\n\t\"u1000.org\": 1,\n\t\"u148.net\": 1,\n\t\"u17.com\": 1,\n\t\"u1733.com\": 1,\n\t\"u17i.com\": 1,\n\t\"u1city.net\": 1,\n\t\"u1d1.com\": 1,\n\t\"u3399.com\": 1,\n\t\"u4123.com\": 1,\n\t\"u520.net\": 1,\n\t\"u5450.com\": 1,\n\t\"u69cn.com\": 1,\n\t\"u77u.com\": 1,\n\t\"u78.com\": 1,\n\t\"u7u7.com\": 1,\n\t\"u88.com\": 1,\n\t\"u88job.com\": 1,\n\t\"u8k8.com\": 1,\n\t\"u966.com\": 1,\n\t\"u9766.com\": 1,\n\t\"u9time.com\": 1,\n\t\"u9yoyo.com\": 1,\n\t\"ubicdn.com\": 1,\n\t\"uc129.com\": 1,\n\t\"uc8.cc\": 1,\n\t\"ucai123.com\": 1,\n\t\"ucbug.cc\": 1,\n\t\"ucbug.com\": 1,\n\t\"ucdao.com\": 1,\n\t\"ucdrs.net\": 1,\n\t\"ucjoy.com\": 1,\n\t\"uctrac.com\": 1,\n\t\"udashi.com\": 1,\n\t\"uehtml.com\": 1,\n\t\"ufang.com\": 1,\n\t\"ufangw.com\": 1,\n\t\"ufenghuang.com\": 1,\n\t\"ufojia.com\": 1,\n\t\"ufojoy.com\": 1,\n\t\"ufstone.com\": 1,\n\t\"ufstone.net\": 1,\n\t\"uftong.com\": 1,\n\t\"uggd.com\": 1,\n\t\"ugojp.com\": 1,\n\t\"uhaidao.com\": 1,\n\t\"uhenan.com\": 1,\n\t\"uibao.com\": 1,\n\t\"uimaker.com\": 1,\n\t\"uinicall.com\": 1,\n\t\"uisdc.com\": 1,\n\t\"uisheji.com\": 1,\n\t\"ujian.cc\": 1,\n\t\"ujiao.net\": 1,\n\t\"ujintan.com\": 1,\n\t\"ujob138.com\": 1,\n\t\"ujob360.com\": 1,\n\t\"ukejisong.com\": 1,\n\t\"uker.net\": 1,\n\t\"ukhorsman.com\": 1,\n\t\"ulbiz.com\": 1,\n\t\"ule.com\": 1,\n\t\"ulenp.com\": 1,\n\t\"ulink.cc\": 1,\n\t\"ulzsw.com\": 1,\n\t\"um5.cc\": 1,\n\t\"umetal.com\": 1,\n\t\"uminsky.com\": 1,\n\t\"umivi.net\": 1,\n\t\"umiwi.com\": 1,\n\t\"umkid.com\": 1,\n\t\"un188.com\": 1,\n\t\"uncars.com\": 1,\n\t\"uninf.com\": 1,\n\t\"uninforun.com\": 1,\n\t\"union178.com\": 1,\n\t\"unionli.com\": 1,\n\t\"unionpay.com\": 1,\n\t\"uniontoufang.com\": 1,\n\t\"unisachina.com\": 1,\n\t\"unitymanual.com\": 1,\n\t\"unjs.com\": 1,\n\t\"unn114.com\": 1,\n\t\"unpcn.com\": 1,\n\t\"uns114.com\": 1,\n\t\"unsuv.com\": 1,\n\t\"untvchina.com\": 1,\n\t\"untx.com\": 1,\n\t\"uoko.com\": 1,\n\t\"uooyoo.com\": 1,\n\t\"up2c.com\": 1,\n\t\"up71.com\": 1,\n\t\"upaidui.com\": 1,\n\t\"upaiyun.com\": 1,\n\t\"upanboot.com\": 1,\n\t\"upantool.com\": 1,\n\t\"updrv.com\": 1,\n\t\"upfdc.com\": 1,\n\t\"upshenghuo.com\": 1,\n\t\"upuphr.com\": 1,\n\t\"upyun.com\": 1,\n\t\"uqidong.com\": 1,\n\t\"url7.me\": 1,\n\t\"usaedu.net\": 1,\n\t\"useso.com\": 1,\n\t\"usfang.com\": 1,\n\t\"ushunde.com\": 1,\n\t\"usportnews.com\": 1,\n\t\"usteel.com\": 1,\n\t\"usvisapass.com\": 1,\n\t\"utan.com\": 1,\n\t\"utanbaby.com\": 1,\n\t\"utourworld.com\": 1,\n\t\"utsteel.com\": 1,\n\t\"uu.cc\": 1,\n\t\"uu1.com\": 1,\n\t\"uu1758.com\": 1,\n\t\"uu178.com\": 1,\n\t\"uu2car.com\": 1,\n\t\"uu38.com\": 1,\n\t\"uu50.com\": 1,\n\t\"uu7c.com\": 1,\n\t\"uu898.com\": 1,\n\t\"uucall.com\": 1,\n\t\"uunt.com\": 1,\n\t\"uuqj.com\": 1,\n\t\"uusee.com\": 1,\n\t\"uutrip.net\": 1,\n\t\"uuu9.com\": 1,\n\t\"uuufun.com\": 1,\n\t\"uuuu.cc\": 1,\n\t\"uuxoo.com\": 1,\n\t\"uuyoyo.com\": 1,\n\t\"uuzhufu.com\": 1,\n\t\"uuzu.com\": 1,\n\t\"uvdeng.com\": 1,\n\t\"uwan.com\": 1,\n\t\"ux87.com\": 1,\n\t\"ux98.com\": 1,\n\t\"uxin.com\": 1,\n\t\"uyan.cc\": 1,\n\t\"uzai.com\": 1,\n\t\"uzaicdn.com\": 1,\n\t\"uzaituan.com\": 1,\n\t\"uzise.com\": 1,\n\t\"uzzf.com\": 1,\n\t\"v-tio2.com\": 1,\n\t\"v.iask.com\": 1,\n\t\"v007.net\": 1,\n\t\"v056.com\": 1,\n\t\"v17go.com\": 1,\n\t\"v1pin.com\": 1,\n\t\"v2ex.com\": 1,\n\t\"vaecn.com\": 1,\n\t\"value500.com\": 1,\n\t\"vancl.com\": 1,\n\t\"vanclimg.com\": 1,\n\t\"vanke.com\": 1,\n\t\"vanward.com\": 1,\n\t\"vapee.com\": 1,\n\t\"vartcn.com\": 1,\n\t\"vautou.com\": 1,\n\t\"vbooking.net\": 1,\n\t\"vcimg.com\": 1,\n\t\"vcinchina.com\": 1,\n\t\"vdfly.com\": 1,\n\t\"vdolady.com\": 1,\n\t\"vedeng.com\": 1,\n\t\"veeqi.com\": 1,\n\t\"veerchina.com\": 1,\n\t\"venfang.com\": 1,\n\t\"verycd.com\": 1,\n\t\"verydz.com\": 1,\n\t\"veryen.org\": 1,\n\t\"veryhome.com\": 1,\n\t\"veryhuo.com\": 1,\n\t\"veryol.com\": 1,\n\t\"veryzhun.com\": 1,\n\t\"vfe.cc\": 1,\n\t\"vfl123.com\": 1,\n\t\"vhostgo.com\": 1,\n\t\"vi21.net\": 1,\n\t\"vicovico.com\": 1,\n\t\"vicp.net\": 1,\n\t\"vidarsoft.com\": 1,\n\t\"viewones.com\": 1,\n\t\"vikecn.com\": 1,\n\t\"villazx.com\": 1,\n\t\"vinehoo.com\": 1,\n\t\"vinux.com\": 1,\n\t\"vip.com\": 1,\n\t\"vip120.com\": 1,\n\t\"vip121.com\": 1,\n\t\"vip7758.com\": 1,\n\t\"vip800.com\": 1,\n\t\"vipcareer.com\": 1,\n\t\"vipcn.com\": 1,\n\t\"vipmtb.com\": 1,\n\t\"vipshare.com\": 1,\n\t\"vipshop.com\": 1,\n\t\"vipsinaapp.com\": 1,\n\t\"vipsoft.cc\": 1,\n\t\"vipstatic.com\": 1,\n\t\"viptijian.com\": 1,\n\t\"vipyl.com\": 1,\n\t\"visa800.com\": 1,\n\t\"visabuilders.com\": 1,\n\t\"visionunion.com\": 1,\n\t\"visitgd.com\": 1,\n\t\"visitxm.com\": 1,\n\t\"vista123.com\": 1,\n\t\"vistastory.com\": 1,\n\t\"vivijk.com\": 1,\n\t\"vizu.com\": 1,\n\t\"vj100.com\": 1,\n\t\"vjia.com\": 1,\n\t\"vmall.com\": 1,\n\t\"vmeti.com\": 1,\n\t\"vnasi.com\": 1,\n\t\"vnet.mobi\": 1,\n\t\"vnexpo.org\": 1,\n\t\"voa365.com\": 1,\n\t\"vobao.com\": 1,\n\t\"vodehr.com\": 1,\n\t\"vodjk.com\": 1,\n\t\"vodone.com\": 1,\n\t\"voguechinese.com\": 1,\n\t\"volstock.com\": 1,\n\t\"vonibo.com\": 1,\n\t\"votwo.com\": 1,\n\t\"vpimg1.com\": 1,\n\t\"vpimg2.com\": 1,\n\t\"vpimg3.com\": 1,\n\t\"vpimg4.com\": 1,\n\t\"vrdam.com\": 1,\n\t\"vrvkt.com\": 1,\n\t\"vsharing.com\": 1,\n\t\"vst88.com\": 1,\n\t\"vsuch.com\": 1,\n\t\"vvjob.com\": 1,\n\t\"vvvdj.com\": 1,\n\t\"vvwan.com\": 1,\n\t\"w0517.com\": 1,\n\t\"w1wan.com\": 1,\n\t\"w3.org\": 1,\n\t\"w5211.com\": 1,\n\t\"w707.com\": 1,\n\t\"w856.com\": 1,\n\t\"wa3.com\": 1,\n\t\"wa8688.com\": 1,\n\t\"waaku.com\": 1,\n\t\"wabuw.com\": 1,\n\t\"wacai.com\": 1,\n\t\"wadongxi.com\": 1,\n\t\"wadongxi.net\": 1,\n\t\"waerfa.com\": 1,\n\t\"waheaven.com\": 1,\n\t\"waihuifanyongwang.com\": 1,\n\t\"waihuigu.net\": 1,\n\t\"waihuo.com\": 1,\n\t\"waimao6.com\": 1,\n\t\"waipoxin.com\": 1,\n\t\"waiwaitu.com\": 1,\n\t\"waixiaoyuan.com\": 1,\n\t\"wajueji.com\": 1,\n\t\"wallcoo.com\": 1,\n\t\"wallstreetcn.com\": 1,\n\t\"walvyou.com\": 1,\n\t\"wan.com\": 1,\n\t\"wan25.com\": 1,\n\t\"wan51.com\": 1,\n\t\"wanbiansz.com\": 1,\n\t\"wanbocai.cc\": 1,\n\t\"wanchaow.com\": 1,\n\t\"wanche100.com\": 1,\n\t\"wanche168.com\": 1,\n\t\"wandafilm.com\": 1,\n\t\"wandaihao.com\": 1,\n\t\"wandodo.com\": 1,\n\t\"wandoujia.com\": 1,\n\t\"wandu.cc\": 1,\n\t\"wanfangdata.com\": 1,\n\t\"wang1314.com\": 1,\n\t\"wangdaitiandi.com\": 1,\n\t\"wangdaizhidao.com\": 1,\n\t\"wangdaizhijia.com\": 1,\n\t\"wanggou.com\": 1,\n\t\"wanggouchao.com\": 1,\n\t\"wangjiaoba.com\": 1,\n\t\"wangjiu.com\": 1,\n\t\"wangtu.com\": 1,\n\t\"wanguan.com\": 1,\n\t\"wangxianhui.com\": 1,\n\t\"wangxiao.net\": 1,\n\t\"wangxiao.so\": 1,\n\t\"wangxiaotong.com\": 1,\n\t\"wangxiaowang.com\": 1,\n\t\"wangxing.com\": 1,\n\t\"wangxingroup.com\": 1,\n\t\"wangyeba.com\": 1,\n\t\"wangyi120.com\": 1,\n\t\"wangyin.com\": 1,\n\t\"wanhu888.com\": 1,\n\t\"wanhuole.com\": 1,\n\t\"wanhupo.com\": 1,\n\t\"wanhutong.net\": 1,\n\t\"wanjia.org\": 1,\n\t\"wanjidao.com\": 1,\n\t\"wanjingchina.com\": 1,\n\t\"wanjuhe.com\": 1,\n\t\"wanlibo.com\": 1,\n\t\"wanlitong.com\": 1,\n\t\"wanlongjituan.com\": 1,\n\t\"wanmagu.com\": 1,\n\t\"wanmei.com\": 1,\n\t\"wanshouyou.net\": 1,\n\t\"wanshuba.com\": 1,\n\t\"wantfeel.com\": 1,\n\t\"wantuhao.com\": 1,\n\t\"wanweixin.com\": 1,\n\t\"wanwen99.com\": 1,\n\t\"wanxf.com\": 1,\n\t\"wanxuantong.com\": 1,\n\t\"wanyeji.com\": 1,\n\t\"wanyiwang.com\": 1,\n\t\"wanyiwang.net\": 1,\n\t\"wanyou365.com\": 1,\n\t\"wanyouxi7.com\": 1,\n\t\"wanyx.com\": 1,\n\t\"wanzhouche.com\": 1,\n\t\"wanzhoujob.com\": 1,\n\t\"wanzui.com\": 1,\n\t\"wanzui.net\": 1,\n\t\"waouji.com\": 1,\n\t\"waptw.com\": 1,\n\t\"warchina.com\": 1,\n\t\"warcraftchina.com\": 1,\n\t\"warting.com\": 1,\n\t\"wasu-umedia.com\": 1,\n\t\"wasu.com\": 1,\n\t\"wasu.tv\": 1,\n\t\"watchstor.com\": 1,\n\t\"waterculture.net\": 1,\n\t\"waterhr.com\": 1,\n\t\"watertu.com\": 1,\n\t\"wawangluo.com\": 1,\n\t\"wbiao.co\": 1,\n\t\"wbtrans.com\": 1,\n\t\"wbtt315.com\": 1,\n\t\"wcjbb.com\": 1,\n\t\"wcnimg.com\": 1,\n\t\"wcsrcw.com\": 1,\n\t\"wcwone.com\": 1,\n\t\"wdjimg.com\": 1,\n\t\"wdjl.net\": 1,\n\t\"wdjslm.com\": 1,\n\t\"wdlpump.com\": 1,\n\t\"wdphoto.net\": 1,\n\t\"wdptj.com\": 1,\n\t\"wdqh.net\": 1,\n\t\"wdres.com\": 1,\n\t\"wds369.com\": 1,\n\t\"wdsdq.com\": 1,\n\t\"wdsjz.com\": 1,\n\t\"wdstq.com\": 1,\n\t\"we.tm\": 1,\n\t\"we54.com\": 1,\n\t\"wealink.com\": 1,\n\t\"wealinkcdn.com\": 1,\n\t\"weand.com\": 1,\n\t\"weathercn.com\": 1,\n\t\"weathertj.com\": 1,\n\t\"web198.com\": 1,\n\t\"web3389.com\": 1,\n\t\"web4008.com\": 1,\n\t\"web887.com\": 1,\n\t\"webche.com\": 1,\n\t\"webciss.com\": 1,\n\t\"webdiyer.com\": 1,\n\t\"webgame163.com\": 1,\n\t\"webgameurl.com\": 1,\n\t\"webjx.com\": 1,\n\t\"webkaka.com\": 1,\n\t\"webkindu.com\": 1,\n\t\"webpowerchina.com\": 1,\n\t\"webscache.com\": 1,\n\t\"webshu.net\": 1,\n\t\"webterren.com\": 1,\n\t\"wecenter.com\": 1,\n\t\"wechatnet.com\": 1,\n\t\"wed020.net\": 1,\n\t\"wed0512.com\": 1,\n\t\"wed2008.com\": 1,\n\t\"wed9.com\": 1,\n\t\"wedohome.com\": 1,\n\t\"weentech.com\": 1,\n\t\"wehefei.com\": 1,\n\t\"wei2008.com\": 1,\n\t\"weibo.com\": 1,\n\t\"weibopay.com\": 1,\n\t\"weicaifu.com\": 1,\n\t\"weichai.com\": 1,\n\t\"weichaishi.com\": 1,\n\t\"weifengke.com\": 1,\n\t\"weifren.com\": 1,\n\t\"weigi.net\": 1,\n\t\"weiguang.cc\": 1,\n\t\"weigz.com\": 1,\n\t\"weihai.tv\": 1,\n\t\"weihaifc.com\": 1,\n\t\"weiheshidai.com\": 1,\n\t\"weihz.net\": 1,\n\t\"weijiu.org\": 1,\n\t\"weijiuxin.com\": 1,\n\t\"weikeimg.com\": 1,\n\t\"weilai.net\": 1,\n\t\"weilanhaian.com\": 1,\n\t\"weilanliuxue.com\": 1,\n\t\"weimeicun.com\": 1,\n\t\"weimeixi.com\": 1,\n\t\"weimi.me\": 1,\n\t\"weimob.com\": 1,\n\t\"weinan.org\": 1,\n\t\"weiningnews.com\": 1,\n\t\"weiot.net\": 1,\n\t\"weiphone.com\": 1,\n\t\"weiphone.net\": 1,\n\t\"weishan.cc\": 1,\n\t\"weisheng.com\": 1,\n\t\"weishengzige.com\": 1,\n\t\"weishi.com\": 1,\n\t\"weitiyan.com\": 1,\n\t\"weiwenyi.com\": 1,\n\t\"weixianwang.com\": 1,\n\t\"weiyunke.com\": 1,\n\t\"weizhang.net\": 1,\n\t\"weizhangwang.com\": 1,\n\t\"welan.com\": 1,\n\t\"weldec.com\": 1,\n\t\"welife100.com\": 1,\n\t\"well8.com\": 1,\n\t\"wellhope-ag.com\": 1,\n\t\"welltrend-edu.com\": 1,\n\t\"wellyn.com\": 1,\n\t\"wemvp.com\": 1,\n\t\"wenbo.cc\": 1,\n\t\"wenchangfc.com\": 1,\n\t\"wenda60.com\": 1,\n\t\"wendu.com\": 1,\n\t\"wenduedu.com\": 1,\n\t\"wendumba.com\": 1,\n\t\"wenjuan.com\": 1,\n\t\"wenlingrc.com\": 1,\n\t\"wenmingzs.com\": 1,\n\t\"wenrenpu.com\": 1,\n\t\"wenshen520.com\": 1,\n\t\"wenshen8.com\": 1,\n\t\"wenshenxiu.com\": 1,\n\t\"wenshitiandi.com\": 1,\n\t\"wenwanhome.com\": 1,\n\t\"wenwo.com\": 1,\n\t\"wenwuchina.com\": 1,\n\t\"wenxue24.com\": 1,\n\t\"wenyifengxiang.com\": 1,\n\t\"wenyoutai.com\": 1,\n\t\"wenyue.org\": 1,\n\t\"wenzhousx.com\": 1,\n\t\"wenzifanyi.com\": 1,\n\t\"weshequ.com\": 1,\n\t\"wesmp.com\": 1,\n\t\"west-rtv.com\": 1,\n\t\"west263.com\": 1,\n\t\"weste.net\": 1,\n\t\"westernchinafair.org\": 1,\n\t\"westholiday.com\": 1,\n\t\"westking.com\": 1,\n\t\"weyou360.com\": 1,\n\t\"wf121.com\": 1,\n\t\"wf777.com\": 1,\n\t\"wfbbs.com\": 1,\n\t\"wfcgs.com\": 1,\n\t\"wfdpjm.com\": 1,\n\t\"wff168.com\": 1,\n\t\"wfftz.com\": 1,\n\t\"wfits.com\": 1,\n\t\"wfjyxxg.com\": 1,\n\t\"wflgj.com\": 1,\n\t\"wflzw.com\": 1,\n\t\"wfrcsc.com\": 1,\n\t\"wfrsks.com\": 1,\n\t\"wgimg.com\": 1,\n\t\"wgszq.net\": 1,\n\t\"wh-motorshow.com\": 1,\n\t\"wh3351.com\": 1,\n\t\"whankj.com\": 1,\n\t\"whbear.com\": 1,\n\t\"whblct.com\": 1,\n\t\"whbws.com\": 1,\n\t\"whctv.com\": 1,\n\t\"whedu.net\": 1,\n\t\"whedu21.com\": 1,\n\t\"whgh.org\": 1,\n\t\"whgjj.net\": 1,\n\t\"whgogo.com\": 1,\n\t\"whgyw.org\": 1,\n\t\"whhouse.com\": 1,\n\t\"whir.net\": 1,\n\t\"whjlw.com\": 1,\n\t\"whjm.com\": 1,\n\t\"whjmyz.com\": 1,\n\t\"whjuren.com\": 1,\n\t\"whjy.net\": 1,\n\t\"whjzw.net\": 1,\n\t\"whlawyer.net\": 1,\n\t\"whlongda.com\": 1,\n\t\"whlongre.com\": 1,\n\t\"whmama.com\": 1,\n\t\"whmetroad.com\": 1,\n\t\"whnewnet.com\": 1,\n\t\"whpcschool.com\": 1,\n\t\"whpx.net\": 1,\n\t\"whqmcg.com\": 1,\n\t\"whqss.net\": 1,\n\t\"whrhkj.com\": 1,\n\t\"whsgj.com\": 1,\n\t\"whshangceng.com\": 1,\n\t\"whsy.org\": 1,\n\t\"whtarena.com\": 1,\n\t\"whunf.com\": 1,\n\t\"whwater.com\": 1,\n\t\"whwed.com\": 1,\n\t\"whzhaopin.net\": 1,\n\t\"whzph.com\": 1,\n\t\"wifigx.com\": 1,\n\t\"wiki8.com\": 1,\n\t\"wikipedia.org\": 1,\n\t\"wildrhino8.com\": 1,\n\t\"williamlong.info\": 1,\n\t\"win007.com\": 1,\n\t\"win4000.com\": 1,\n\t\"win7china.com\": 1,\n\t\"win8china.com\": 1,\n\t\"win8e.com\": 1,\n\t\"wincn.com\": 1,\n\t\"windchn.com\": 1,\n\t\"winddesktop.com\": 1,\n\t\"windhr.net\": 1,\n\t\"windin.com\": 1,\n\t\"windosi.com\": 1,\n\t\"windows7en.com\": 1,\n\t\"wine-world.com\": 1,\n\t\"wine9.com\": 1,\n\t\"winechina.com\": 1,\n\t\"winekee.com\": 1,\n\t\"winenice.com\": 1,\n\t\"wines-info.com\": 1,\n\t\"winfang.com\": 1,\n\t\"winfreeinfo.com\": 1,\n\t\"wingwit.com\": 1,\n\t\"winshang.com\": 1,\n\t\"wintang.com\": 1,\n\t\"winvod.com\": 1,\n\t\"winwindai.com\": 1,\n\t\"winxw.com\": 1,\n\t\"wishdown.com\": 1,\n\t\"wj-hospital.com\": 1,\n\t\"wj001.com\": 1,\n\t\"wj0556.com\": 1,\n\t\"wjclpx.com\": 1,\n\t\"wjdaily.com\": 1,\n\t\"wjfcw.com\": 1,\n\t\"wjjob.net\": 1,\n\t\"wjnin.com\": 1,\n\t\"wjqcw.com\": 1,\n\t\"wjshw.com\": 1,\n\t\"wjsw.com\": 1,\n\t\"wjyanghu.com\": 1,\n\t\"wkdty.com\": 1,\n\t\"wkimg.com\": 1,\n\t\"wlc1618.com\": 1,\n\t\"wldsb.com\": 1,\n\t\"wlfce.com\": 1,\n\t\"wlgd.net\": 1,\n\t\"wlgy.com\": 1,\n\t\"wlhagz.com\": 1,\n\t\"wljysw.com\": 1,\n\t\"wlkst.com\": 1,\n\t\"wlmq.com\": 1,\n\t\"wlmqgjj.com\": 1,\n\t\"wlmqwb.com\": 1,\n\t\"wlshw.com\": 1,\n\t\"wlstock.com\": 1,\n\t\"wlxyw.com\": 1,\n\t\"wlyht.com\": 1,\n\t\"wm090.com\": 1,\n\t\"wm927.com\": 1,\n\t\"wmb2b.com\": 1,\n\t\"wmgm.org\": 1,\n\t\"wmordos.com\": 1,\n\t\"wmpic.me\": 1,\n\t\"wmtp.net\": 1,\n\t\"wmwz.tv\": 1,\n\t\"wmzhe.com\": 1,\n\t\"wn51.com\": 1,\n\t\"wndhr.com\": 1,\n\t\"wndhw.com\": 1,\n\t\"wnfdc.com\": 1,\n\t\"wnrcw.com\": 1,\n\t\"wnrczpw.com\": 1,\n\t\"wnwb.com\": 1,\n\t\"wo116114.com\": 1,\n\t\"woaipu.com\": 1,\n\t\"wodai.com\": 1,\n\t\"wodeyouhuigou.com\": 1,\n\t\"wodingche.com\": 1,\n\t\"wofang.com\": 1,\n\t\"wofangwang.com\": 1,\n\t\"woitea.net\": 1,\n\t\"woiyu.com\": 1,\n\t\"woja.net\": 1,\n\t\"wojubl.com\": 1,\n\t\"wokan.com\": 1,\n\t\"wokanfang.com\": 1,\n\t\"wokaw.net\": 1,\n\t\"wokeji.com\": 1,\n\t\"wolai.com\": 1,\n\t\"wolaigo.com\": 1,\n\t\"womai.com\": 1,\n\t\"woman91.com\": 1,\n\t\"womenofchina.com\": 1,\n\t\"woniu.com\": 1,\n\t\"wood168.com\": 1,\n\t\"woodworking365.com\": 1,\n\t\"wool3.com\": 1,\n\t\"wopeng.net\": 1,\n\t\"wordlm.com\": 1,\n\t\"wordpress.la\": 1,\n\t\"workpcb.com\": 1,\n\t\"workyi.com\": 1,\n\t\"world-metal.com\": 1,\n\t\"worldal.com\": 1,\n\t\"worldhots.com\": 1,\n\t\"worldmr.net\": 1,\n\t\"worldscrap.com\": 1,\n\t\"worldwayhk.com\": 1,\n\t\"woshipm.com\": 1,\n\t\"wosign.com\": 1,\n\t\"wotoo.cc\": 1,\n\t\"wowody.net\": 1,\n\t\"wowoyou.com\": 1,\n\t\"wowsai.com\": 1,\n\t\"woxiu.com\": 1,\n\t\"woyaogexing.com\": 1,\n\t\"woyaojiaju.com\": 1,\n\t\"woyewan.com\": 1,\n\t\"woying.com\": 1,\n\t\"woyo365.com\": 1,\n\t\"woyouguanjia.com\": 1,\n\t\"wozhongla.com\": 1,\n\t\"wp28.com\": 1,\n\t\"wper.com\": 1,\n\t\"wpeu.net\": 1,\n\t\"wpwan.com\": 1,\n\t\"wqby.org\": 1,\n\t\"wrating.com\": 1,\n\t\"wrsa.net\": 1,\n\t\"ws8.org\": 1,\n\t\"wsbgt.com\": 1,\n\t\"wsche.com\": 1,\n\t\"wsd114.com\": 1,\n\t\"wsfjh.com\": 1,\n\t\"wsgjj.com\": 1,\n\t\"wshang.com\": 1,\n\t\"wshangyun.com\": 1,\n\t\"wshoes.net\": 1,\n\t\"wshzg.com\": 1,\n\t\"wsj.com\": 1,\n\t\"wsqsgo.com\": 1,\n\t\"wsrc999.com\": 1,\n\t\"wstdw.com\": 1,\n\t\"wstea.com\": 1,\n\t\"wszg8.com\": 1,\n\t\"wszw.com\": 1,\n\t\"wto168.net\": 1,\n\t\"wtobag.com\": 1,\n\t\"wtsteel.com\": 1,\n\t\"wtwan.com\": 1,\n\t\"wuca.net\": 1,\n\t\"wudage.com\": 1,\n\t\"wudang04.com\": 1,\n\t\"wudang3.com\": 1,\n\t\"wudang360.com\": 1,\n\t\"wudangmuseum.com\": 1,\n\t\"wudao.com\": 1,\n\t\"wudaotv.com\": 1,\n\t\"wudig.com\": 1,\n\t\"wudihan.com\": 1,\n\t\"wufun.net\": 1,\n\t\"wuguanling.com\": 1,\n\t\"wuhan4.com\": 1,\n\t\"wuhanbus.com\": 1,\n\t\"wuhaninvest.com\": 1,\n\t\"wuhu.cc\": 1,\n\t\"wuhulife.com\": 1,\n\t\"wujianghr.com\": 1,\n\t\"wujintool.com\": 1,\n\t\"wujitl.com\": 1,\n\t\"wujue.com\": 1,\n\t\"wuliantour.com\": 1,\n\t\"wuliaosi.com\": 1,\n\t\"wulingxw.com\": 1,\n\t\"wuliok.com\": 1,\n\t\"wumii.com\": 1,\n\t\"wuqing.cc\": 1,\n\t\"wuqunshuye.com\": 1,\n\t\"wushen.com\": 1,\n\t\"wutongxiang.cc\": 1,\n\t\"wuweijob.com\": 1,\n\t\"wuxijob.com\": 1,\n\t\"wuxinghuayuan.com\": 1,\n\t\"wuxiph.com\": 1,\n\t\"wuxjob.com\": 1,\n\t\"wuyiguide.com\": 1,\n\t\"wuyishan.com\": 1,\n\t\"wuyitravel.com\": 1,\n\t\"wuyuan168.com\": 1,\n\t\"wuyueit.com\": 1,\n\t\"wuzhe.com\": 1,\n\t\"wwbxw.com\": 1,\n\t\"wwenglish.com\": 1,\n\t\"wwfchina.org\": 1,\n\t\"wwwcn.org\": 1,\n\t\"wx6.org\": 1,\n\t\"wx920.com\": 1,\n\t\"wx920.net\": 1,\n\t\"wxbnbxg.com\": 1,\n\t\"wxbtlbxg.com\": 1,\n\t\"wxctkq.com\": 1,\n\t\"wxctzx.com\": 1,\n\t\"wxehs.com\": 1,\n\t\"wxfuyou.com\": 1,\n\t\"wxhouse.com\": 1,\n\t\"wxhtlxj.com\": 1,\n\t\"wxi.cc\": 1,\n\t\"wxjbbxg.com\": 1,\n\t\"wxjcgy.com\": 1,\n\t\"wxjob.com\": 1,\n\t\"wxlongre.com\": 1,\n\t\"wxlongre.org\": 1,\n\t\"wxlottery.com\": 1,\n\t\"wxmama.com\": 1,\n\t\"wxmlbb.com\": 1,\n\t\"wxqcw.com\": 1,\n\t\"wxrb.com\": 1,\n\t\"wxsbbs.com\": 1,\n\t\"wxsjxn.com\": 1,\n\t\"wxsme.org\": 1,\n\t\"wxthw.com\": 1,\n\t\"wxuse.com\": 1,\n\t\"wxw120.com\": 1,\n\t\"wxwmw.com\": 1,\n\t\"wxxqlib.com\": 1,\n\t\"wybbao.com\": 1,\n\t\"wydxjzw.com\": 1,\n\t\"wyhnn.com\": 1,\n\t\"wyjiuyuanheiji.com\": 1,\n\t\"wysap.com\": 1,\n\t\"wysjob.com\": 1,\n\t\"wyuyao.com\": 1,\n\t\"wyzc.com\": 1,\n\t\"wz121.com\": 1,\n\t\"wz12333.com\": 1,\n\t\"wz50.com\": 1,\n\t\"wzcbd.com\": 1,\n\t\"wzcheshi.com\": 1,\n\t\"wzclxx.com\": 1,\n\t\"wzdjy.com\": 1,\n\t\"wzdlyw.com\": 1,\n\t\"wzdsb.net\": 1,\n\t\"wzea.com\": 1,\n\t\"wzer.net\": 1,\n\t\"wzfg.com\": 1,\n\t\"wzfnykj.com\": 1,\n\t\"wzfx.net\": 1,\n\t\"wzgjj.com\": 1,\n\t\"wzhan.net\": 1,\n\t\"wzhd.com\": 1,\n\t\"wzi9.com\": 1,\n\t\"wzjob.com\": 1,\n\t\"wzk.com\": 1,\n\t\"wzrc.com\": 1,\n\t\"wzrc.net\": 1,\n\t\"wzrclt.com\": 1,\n\t\"wzsee.com\": 1,\n\t\"wzsky.net\": 1,\n\t\"wzszp.com\": 1,\n\t\"wztyj.com\": 1,\n\t\"wzwh.com\": 1,\n\t\"wzyds.com\": 1,\n\t\"wzzbtb.com\": 1,\n\t\"x-sing.com\": 1,\n\t\"x0750.com\": 1,\n\t\"x1616.com\": 1,\n\t\"x3cn.com\": 1,\n\t\"x888v.com\": 1,\n\t\"xa999.com\": 1,\n\t\"xabbs.com\": 1,\n\t\"xacars.com\": 1,\n\t\"xadmgjc.com\": 1,\n\t\"xafc.com\": 1,\n\t\"xahhw.com\": 1,\n\t\"xajjzh.com\": 1,\n\t\"xajob.com\": 1,\n\t\"xajobw.com\": 1,\n\t\"xamama.net\": 1,\n\t\"xanet110.com\": 1,\n\t\"xaonline.com\": 1,\n\t\"xapcn.com\": 1,\n\t\"xaprice.com\": 1,\n\t\"xarc.net\": 1,\n\t\"xarc8.com\": 1,\n\t\"xarchi.com\": 1,\n\t\"xaronline.com\": 1,\n\t\"xatianzhou.com\": 1,\n\t\"xatrm.com\": 1,\n\t\"xatvs.com\": 1,\n\t\"xawan.com\": 1,\n\t\"xawb.com\": 1,\n\t\"xaxzl.com\": 1,\n\t\"xazmkm.com\": 1,\n\t\"xazxw.com\": 1,\n\t\"xb124.net\": 1,\n\t\"xb234.com\": 1,\n\t\"xb5.cc\": 1,\n\t\"xbaixing.com\": 1,\n\t\"xbauto.com\": 1,\n\t\"xbdb2b.com\": 1,\n\t\"xbfzb.com\": 1,\n\t\"xbgk.com\": 1,\n\t\"xbiao.com\": 1,\n\t\"xbjob.com\": 1,\n\t\"xblaw.com\": 1,\n\t\"xblyy.com\": 1,\n\t\"xbmiaomu.com\": 1,\n\t\"xbsh.net\": 1,\n\t\"xbxxb.com\": 1,\n\t\"xbzgold.com\": 1,\n\t\"xc666.com\": 1,\n\t\"xcabc.com\": 1,\n\t\"xcarimg.com\": 1,\n\t\"xcetv.com\": 1,\n\t\"xcfc999.com\": 1,\n\t\"xchelp.com\": 1,\n\t\"xcjob.com\": 1,\n\t\"xcljs.com\": 1,\n\t\"xcmg.com\": 1,\n\t\"xcmh.com\": 1,\n\t\"xcqc.net\": 1,\n\t\"xcrc999.com\": 1,\n\t\"xcrj.com\": 1,\n\t\"xcs168.net\": 1,\n\t\"xcsztb.com\": 1,\n\t\"xctour.com\": 1,\n\t\"xcwenming.com\": 1,\n\t\"xcy8.com\": 1,\n\t\"xczpw.net\": 1,\n\t\"xd.com\": 1,\n\t\"xd57.com\": 1,\n\t\"xdcdn.net\": 1,\n\t\"xdcharger.com\": 1,\n\t\"xdedu.net\": 1,\n\t\"xdf666.com\": 1,\n\t\"xdfdly.com\": 1,\n\t\"xdfxly.com\": 1,\n\t\"xdkb.net\": 1,\n\t\"xdnice.com\": 1,\n\t\"xdowns.com\": 1,\n\t\"xdth.org\": 1,\n\t\"xdwan.com\": 1,\n\t\"xdxiazai.com\": 1,\n\t\"xdxmw.com\": 1,\n\t\"xdz.com\": 1,\n\t\"xdzinfo.com\": 1,\n\t\"xeeee.net\": 1,\n\t\"xemh.com\": 1,\n\t\"xenbo.com\": 1,\n\t\"xesimg.com\": 1,\n\t\"xeyjj.com\": 1,\n\t\"xf-td.com\": 1,\n\t\"xf0797.com\": 1,\n\t\"xf12356.org\": 1,\n\t\"xf88.com\": 1,\n\t\"xfbst.com\": 1,\n\t\"xfdq123.com\": 1,\n\t\"xffcol.com\": 1,\n\t\"xfgjj.com\": 1,\n\t\"xfgx.com\": 1,\n\t\"xfhqw.com\": 1,\n\t\"xfj100.com\": 1,\n\t\"xfqcol.com\": 1,\n\t\"xfsljk.net\": 1,\n\t\"xftgrx.com\": 1,\n\t\"xfun001.com\": 1,\n\t\"xfwed.com\": 1,\n\t\"xfydyt.com\": 1,\n\t\"xfzx.org\": 1,\n\t\"xgcw.com\": 1,\n\t\"xglyy.com\": 1,\n\t\"xgxedu.com\": 1,\n\t\"xgyy.co\": 1,\n\t\"xgzpw.com\": 1,\n\t\"xgzrc.com\": 1,\n\t\"xh-expo.com\": 1,\n\t\"xh003.com\": 1,\n\t\"xh925.com\": 1,\n\t\"xhafz.com\": 1,\n\t\"xhbhr.com\": 1,\n\t\"xhby.net\": 1,\n\t\"xhcce.com\": 1,\n\t\"xhd.org\": 1,\n\t\"xhengshui.com\": 1,\n\t\"xhstv.com\": 1,\n\t\"xhuaian.com\": 1,\n\t\"xhume.com\": 1,\n\t\"xi666.com\": 1,\n\t\"xiachufang.com\": 1,\n\t\"xiadele.com\": 1,\n\t\"xiadu.com\": 1,\n\t\"xiagong.com\": 1,\n\t\"xialingying.cc\": 1,\n\t\"xialv.com\": 1,\n\t\"xiamenair.com\": 1,\n\t\"xiameninvest.com\": 1,\n\t\"xiamentour.com\": 1,\n\t\"xiamenwater.com\": 1,\n\t\"xiami.com\": 1,\n\t\"xiami.net\": 1,\n\t\"xian-tourism.com\": 1,\n\t\"xianbey.com\": 1,\n\t\"xianbx.com\": 1,\n\t\"xiancn.com\": 1,\n\t\"xiandaishoucang.com\": 1,\n\t\"xiang2012.com\": 1,\n\t\"xiang5.com\": 1,\n\t\"xiangauto.com\": 1,\n\t\"xiangcunyou.com\": 1,\n\t\"xiangdang.net\": 1,\n\t\"xiangguohe.com\": 1,\n\t\"xianghe.com\": 1,\n\t\"xianghunet.com\": 1,\n\t\"xiangjiangyw.com\": 1,\n\t\"xiangmu.com\": 1,\n\t\"xiangqinyw.com\": 1,\n\t\"xiangrikui.com\": 1,\n\t\"xiangshanart.com\": 1,\n\t\"xiangshengw.com\": 1,\n\t\"xiangshu.com\": 1,\n\t\"xianguo.com\": 1,\n\t\"xiangyang.net\": 1,\n\t\"xiangyinxw.com\": 1,\n\t\"xianjj.com\": 1,\n\t\"xianlan315.com\": 1,\n\t\"xianning.com\": 1,\n\t\"xianoo.com\": 1,\n\t\"xianpp.com\": 1,\n\t\"xiansp.com\": 1,\n\t\"xianyuange.com\": 1,\n\t\"xianyuwang.com\": 1,\n\t\"xianzhilou.com\": 1,\n\t\"xiao-che.com\": 1,\n\t\"xiao84.com\": 1,\n\t\"xiaobaixitong.com\": 1,\n\t\"xiaobao8.com\": 1,\n\t\"xiaochang.org\": 1,\n\t\"xiaochangxian.com\": 1,\n\t\"xiaoche5.com\": 1,\n\t\"xiaofantian.com\": 1,\n\t\"xiaogan.com\": 1,\n\t\"xiaoguot.com\": 1,\n\t\"xiaogushi.com\": 1,\n\t\"xiaohei.com\": 1,\n\t\"xiaohuangji.com\": 1,\n\t\"xiaojiangguo123.com\": 1,\n\t\"xiaojiulou.com\": 1,\n\t\"xiaojiulou.net\": 1,\n\t\"xiaolebar.com\": 1,\n\t\"xiaoliangkou.com\": 1,\n\t\"xiaoma.com\": 1,\n\t\"xiaomayi.co\": 1,\n\t\"xiaomayi.net\": 1,\n\t\"xiaomei.cc\": 1,\n\t\"xiaomi.com\": 1,\n\t\"xiaomi.net\": 1,\n\t\"xiaomi001.com\": 1,\n\t\"xiaomishu.com\": 1,\n\t\"xiaomizha.com\": 1,\n\t\"xiaonaodai.com\": 1,\n\t\"xiaonei.com\": 1,\n\t\"xiaopi.com\": 1,\n\t\"xiaopin5.com\": 1,\n\t\"xiaopin8.com\": 1,\n\t\"xiaot.com\": 1,\n\t\"xiaotongxing.net\": 1,\n\t\"xiaoxiang.tv\": 1,\n\t\"xiaoxiangrc.com\": 1,\n\t\"xiaoxiaotong.org\": 1,\n\t\"xiaoxiaw.com\": 1,\n\t\"xiaoxinwan.com\": 1,\n\t\"xiaoyeren.com\": 1,\n\t\"xiaoyu.com\": 1,\n\t\"xiaoyuanfeng.com\": 1,\n\t\"xiaozhan.org\": 1,\n\t\"xiaozhishi.com\": 1,\n\t\"xiaozhu.com\": 1,\n\t\"xiaozhustatic1.com\": 1,\n\t\"xiaozhustatic2.com\": 1,\n\t\"xiaozhustatic3.com\": 1,\n\t\"xiashanet.com\": 1,\n\t\"xiayixian.com\": 1,\n\t\"xiazaiba.com\": 1,\n\t\"xiazaijidi.com\": 1,\n\t\"xiazaizhijia.com\": 1,\n\t\"xibakou.com\": 1,\n\t\"xicai.com\": 1,\n\t\"xiche168.com\": 1,\n\t\"xicheji1.com\": 1,\n\t\"xichengrc.com\": 1,\n\t\"xichu.net\": 1,\n\t\"xichujob.com\": 1,\n\t\"xici.net\": 1,\n\t\"xiezilou.com\": 1,\n\t\"xifengniao.com\": 1,\n\t\"xifuquan.com\": 1,\n\t\"xiggua.com\": 1,\n\t\"xigo.tv\": 1,\n\t\"xigu.com\": 1,\n\t\"xigushi.com\": 1,\n\t\"xihabang.com\": 1,\n\t\"xihaiannews.com\": 1,\n\t\"xihairc.com\": 1,\n\t\"xihawan8.com\": 1,\n\t\"xihawan8.net\": 1,\n\t\"xikoutourism.com\": 1,\n\t\"xilituan.com\": 1,\n\t\"xilu.com\": 1,\n\t\"ximalaya.com\": 1,\n\t\"ximenwai.com\": 1,\n\t\"ximij.com\": 1,\n\t\"xin3721.com\": 1,\n\t\"xinancaipiao.com\": 1,\n\t\"xinancoal.com\": 1,\n\t\"xincaijing.com\": 1,\n\t\"xincainet.com\": 1,\n\t\"xincheping.com\": 1,\n\t\"xinchou114.com\": 1,\n\t\"xinddy.com\": 1,\n\t\"xinego.com\": 1,\n\t\"xinfafloor.com\": 1,\n\t\"xinfei.com\": 1,\n\t\"xinfeihu.com\": 1,\n\t\"xinfengit.com\": 1,\n\t\"xinfenlei.com\": 1,\n\t\"xinfuwan.com\": 1,\n\t\"xingbanke.com\": 1,\n\t\"xingchenmanhua.com\": 1,\n\t\"xingjiesj.com\": 1,\n\t\"xingjiezs.com\": 1,\n\t\"xingkong.com\": 1,\n\t\"xingming.com\": 1,\n\t\"xingmucaoye.com\": 1,\n\t\"xingshu.com\": 1,\n\t\"xingtaishi.com\": 1,\n\t\"xingtaitong.com\": 1,\n\t\"xingxiangzg.com\": 1,\n\t\"xingyang114.com\": 1,\n\t\"xingyoucn.com\": 1,\n\t\"xingyunba.com\": 1,\n\t\"xingzuo123.com\": 1,\n\t\"xingzuowu.com\": 1,\n\t\"xinhe99.com\": 1,\n\t\"xinhua.org\": 1,\n\t\"xinhua08.com\": 1,\n\t\"xinhuacang.com\": 1,\n\t\"xinhuacnc.com\": 1,\n\t\"xinhuame.com\": 1,\n\t\"xinhuanet.com\": 1,\n\t\"xinhuanteng.com\": 1,\n\t\"xinhuatone.com\": 1,\n\t\"xinjianghu.com\": 1,\n\t\"xinjie88.com\": 1,\n\t\"xinjiren.com\": 1,\n\t\"xinju100.com\": 1,\n\t\"xinjunshi.com\": 1,\n\t\"xinkb.org\": 1,\n\t\"xinkuaituan.com\": 1,\n\t\"xinkz.com\": 1,\n\t\"xinlexie.com\": 1,\n\t\"xinluobo.com\": 1,\n\t\"xinm123.com\": 1,\n\t\"xinmanyuan.com\": 1,\n\t\"xinmengzl.com\": 1,\n\t\"xinnet.com\": 1,\n\t\"xinnong.com\": 1,\n\t\"xinpg.com\": 1,\n\t\"xinpian.com\": 1,\n\t\"xinpianimg.com\": 1,\n\t\"xinpiaowang.com\": 1,\n\t\"xinqianjiang.com\": 1,\n\t\"xinquanedu.com\": 1,\n\t\"xinshoucun.com\": 1,\n\t\"xinshuozhou.com\": 1,\n\t\"xinsilu.com\": 1,\n\t\"xinsinong.com\": 1,\n\t\"xinsixue.com\": 1,\n\t\"xinsuixian.com\": 1,\n\t\"xinsuwang.com\": 1,\n\t\"xintairen.com\": 1,\n\t\"xintairencai.com\": 1,\n\t\"xintaizhou.com\": 1,\n\t\"xintuan.com\": 1,\n\t\"xinwangjing.com\": 1,\n\t\"xinwo.com\": 1,\n\t\"xinxiwo.com\": 1,\n\t\"xinxunwang.com\": 1,\n\t\"xinxunwei.com\": 1,\n\t\"xinyeedu.com\": 1,\n\t\"xinyi.com\": 1,\n\t\"xinyiglass.com\": 1,\n\t\"xinyou.com\": 1,\n\t\"xinyubt.com\": 1,\n\t\"xinyurc.com\": 1,\n\t\"xinzhou.org\": 1,\n\t\"xiongying.com\": 1,\n\t\"xipingbar.com\": 1,\n\t\"xippe.org\": 1,\n\t\"xishanyihaoyuan.com\": 1,\n\t\"xishiqu.com\": 1,\n\t\"xishiwang.com\": 1,\n\t\"xishu365.com\": 1,\n\t\"xisuedu.org\": 1,\n\t\"xitek.com\": 1,\n\t\"xitongcheng.com\": 1,\n\t\"xitongcity.com\": 1,\n\t\"xituan.com\": 1,\n\t\"xiu.com\": 1,\n\t\"xiu8.com\": 1,\n\t\"xiuai.com\": 1,\n\t\"xiugei.com\": 1,\n\t\"xiuhome.com\": 1,\n\t\"xiumei.com\": 1,\n\t\"xiusheji.net\": 1,\n\t\"xiushuang.com\": 1,\n\t\"xiwenquan.com\": 1,\n\t\"xixiarc.com\": 1,\n\t\"xixik.com\": 1,\n\t\"xiyou53.com\": 1,\n\t\"xiyou54.com\": 1,\n\t\"xiyuit.com\": 1,\n\t\"xizangshop.com\": 1,\n\t\"xizhezhe.com\": 1,\n\t\"xizhi.com\": 1,\n\t\"xizhou.com\": 1,\n\t\"xizi.com\": 1,\n\t\"xiziwang.net\": 1,\n\t\"xj-zp.com\": 1,\n\t\"xj169.com\": 1,\n\t\"xj5u.com\": 1,\n\t\"xj71.com\": 1,\n\t\"xj96566.com\": 1,\n\t\"xjaas.net\": 1,\n\t\"xjass.com\": 1,\n\t\"xjauto.net\": 1,\n\t\"xjbzjj.com\": 1,\n\t\"xjche365.com\": 1,\n\t\"xjdaily.com\": 1,\n\t\"xjdwx.com\": 1,\n\t\"xjedu.org\": 1,\n\t\"xjflcp.com\": 1,\n\t\"xjfzb.com\": 1,\n\t\"xjhj.com\": 1,\n\t\"xjhjsd.com\": 1,\n\t\"xjhr.com\": 1,\n\t\"xjjjb.com\": 1,\n\t\"xjjmw.com\": 1,\n\t\"xjktarena.com\": 1,\n\t\"xjlib.org\": 1,\n\t\"xjlnwh.com\": 1,\n\t\"xjrb.com\": 1,\n\t\"xjtaobao.com\": 1,\n\t\"xjtctv.com\": 1,\n\t\"xjtonglan.com\": 1,\n\t\"xjtour.com\": 1,\n\t\"xjtour.net\": 1,\n\t\"xjtrcw.com\": 1,\n\t\"xjxnw.com\": 1,\n\t\"xjxy.com\": 1,\n\t\"xjz.com\": 1,\n\t\"xjzj.com\": 1,\n\t\"xjzsjc.com\": 1,\n\t\"xkhouse.com\": 1,\n\t\"xkseo.com\": 1,\n\t\"xkwx.com\": 1,\n\t\"xkxm.com\": 1,\n\t\"xl699.com\": 1,\n\t\"xlglsybl.com\": 1,\n\t\"xlp8.com\": 1,\n\t\"xlpan.com\": 1,\n\t\"xlxjy.com\": 1,\n\t\"xlys1904.com\": 1,\n\t\"xlysauc.com\": 1,\n\t\"xm-cs.com\": 1,\n\t\"xm12333.com\": 1,\n\t\"xm51.com\": 1,\n\t\"xm597.com\": 1,\n\t\"xm766.com\": 1,\n\t\"xm7c.com\": 1,\n\t\"xm96.com\": 1,\n\t\"xmc325.com\": 1,\n\t\"xmccc.org\": 1,\n\t\"xmcdn.com\": 1,\n\t\"xmculture.com\": 1,\n\t\"xmdj123.com\": 1,\n\t\"xmdtsh.com\": 1,\n\t\"xmecc.com\": 1,\n\t\"xmfc.com\": 1,\n\t\"xmfish.com\": 1,\n\t\"xmhougu.com\": 1,\n\t\"xmhouse.com\": 1,\n\t\"xmhunter.com\": 1,\n\t\"xmibi.com\": 1,\n\t\"xmim.org\": 1,\n\t\"xmjim.com\": 1,\n\t\"xmjobs.com\": 1,\n\t\"xmjxzx.com\": 1,\n\t\"xmjydj.com\": 1,\n\t\"xmlib.net\": 1,\n\t\"xmmama.com\": 1,\n\t\"xmnorns.com\": 1,\n\t\"xmpig.com\": 1,\n\t\"xmqilian.com\": 1,\n\t\"xmsegu.com\": 1,\n\t\"xmsjob.com\": 1,\n\t\"xmsme.com\": 1,\n\t\"xmsmjk.com\": 1,\n\t\"xmtarc.com\": 1,\n\t\"xmtsjq.com\": 1,\n\t\"xmuky.com\": 1,\n\t\"xmvivi.com\": 1,\n\t\"xmwj.com\": 1,\n\t\"xmwsjd.com\": 1,\n\t\"xmzgh.org\": 1,\n\t\"xmzrc.com\": 1,\n\t\"xmzyrc.com\": 1,\n\t\"xn--fiqs8s\": 1,\n\t\"xn121.com\": 1,\n\t\"xnfw.com\": 1,\n\t\"xnguke.com\": 1,\n\t\"xnhaofang.com\": 1,\n\t\"xnjhome.com\": 1,\n\t\"xnjjob.com\": 1,\n\t\"xnkao.com\": 1,\n\t\"xnmei.com\": 1,\n\t\"xnmtd.com\": 1,\n\t\"xnpad.com\": 1,\n\t\"xns315.com\": 1,\n\t\"xntv.tv\": 1,\n\t\"xnwsc.com\": 1,\n\t\"xnyauto.com\": 1,\n\t\"xnyfd.com\": 1,\n\t\"xnynews.com\": 1,\n\t\"xoyin.com\": 1,\n\t\"xoyo.com\": 1,\n\t\"xp14.com\": 1,\n\t\"xp3366.com\": 1,\n\t\"xp510.com\": 1,\n\t\"xp597.com\": 1,\n\t\"xp74.com\": 1,\n\t\"xp85.com\": 1,\n\t\"xp911.com\": 1,\n\t\"xp9365.com\": 1,\n\t\"xpenyou.com\": 1,\n\t\"xpf.cc\": 1,\n\t\"xpgod.com\": 1,\n\t\"xplus.com\": 1,\n\t\"xpsy.net\": 1,\n\t\"xpxww.com\": 1,\n\t\"xrecovery.net\": 1,\n\t\"xrkcdn.com\": 1,\n\t\"xs9999.com\": 1,\n\t\"xsbhjt.com\": 1,\n\t\"xsfc.com\": 1,\n\t\"xsjk.net\": 1,\n\t\"xsjob.com\": 1,\n\t\"xskhome.com\": 1,\n\t\"xsledu.com\": 1,\n\t\"xsme.com\": 1,\n\t\"xsmnews.com\": 1,\n\t\"xsmp.net\": 1,\n\t\"xsool.com\": 1,\n\t\"xsqw.com\": 1,\n\t\"xstour.com\": 1,\n\t\"xsyjn.com\": 1,\n\t\"xszp.cc\": 1,\n\t\"xszrcw.com\": 1,\n\t\"xt12333.com\": 1,\n\t\"xt512.com\": 1,\n\t\"xt866.com\": 1,\n\t\"xtauto.net\": 1,\n\t\"xtcheche.com\": 1,\n\t\"xtdtzc.com\": 1,\n\t\"xtedu.com\": 1,\n\t\"xtfj.org\": 1,\n\t\"xthg.net\": 1,\n\t\"xtjc.com\": 1,\n\t\"xtjdcjsr.com\": 1,\n\t\"xtjob.net\": 1,\n\t\"xtkjp.com\": 1,\n\t\"xtltt.com\": 1,\n\t\"xtrc.net\": 1,\n\t\"xtsou.com\": 1,\n\t\"xtuan.com\": 1,\n\t\"xtwj.net\": 1,\n\t\"xtx6.com\": 1,\n\t\"xtyhbz.com\": 1,\n\t\"xu.com\": 1,\n\t\"xuancheng.org\": 1,\n\t\"xuanchuanyi.com\": 1,\n\t\"xuanfang.org\": 1,\n\t\"xuanke.com\": 1,\n\t\"xuanke114.com\": 1,\n\t\"xuanruanjian.com\": 1,\n\t\"xuanwww.com\": 1,\n\t\"xuanxuan.com\": 1,\n\t\"xuanxue.com\": 1,\n\t\"xuanyi.com\": 1,\n\t\"xuanzequan.com\": 1,\n\t\"xuchangbbs.com\": 1,\n\t\"xue.net\": 1,\n\t\"xue163.com\": 1,\n\t\"xue2you.com\": 1,\n\t\"xue5156.com\": 1,\n\t\"xuebuyuan.com\": 1,\n\t\"xuechela.com\": 1,\n\t\"xuechenghr.com\": 1,\n\t\"xuechengkaoyan.com\": 1,\n\t\"xueda.com\": 1,\n\t\"xueersi.com\": 1,\n\t\"xueeu.com\": 1,\n\t\"xuefengwuji.com\": 1,\n\t\"xuefofa.com\": 1,\n\t\"xueid.com\": 1,\n\t\"xuejutea.com\": 1,\n\t\"xuekeedu.com\": 1,\n\t\"xueshandai.com\": 1,\n\t\"xueshanrc.com\": 1,\n\t\"xuex123.com\": 1,\n\t\"xuexi111.com\": 1,\n\t\"xuexiaodaquan.com\": 1,\n\t\"xuexifangfa.com\": 1,\n\t\"xuexila.com\": 1,\n\t\"xueyiwang.org\": 1,\n\t\"xueyiyun.com\": 1,\n\t\"xumulc.com\": 1,\n\t\"xumurc.com\": 1,\n\t\"xumuren.com\": 1,\n\t\"xumutongshi.com\": 1,\n\t\"xun-yi.com\": 1,\n\t\"xun8.com\": 1,\n\t\"xunche.com\": 1,\n\t\"xungou.com\": 1,\n\t\"xunlei.com\": 1,\n\t\"xunleimil.com\": 1,\n\t\"xunxianrc.com\": 1,\n\t\"xunzai.com\": 1,\n\t\"xuyi365.net\": 1,\n\t\"xuzhouc.com\": 1,\n\t\"xuzhoujob.com\": 1,\n\t\"xw365.com\": 1,\n\t\"xwcm.net\": 1,\n\t\"xwcsj.com\": 1,\n\t\"xwei.tv\": 1,\n\t\"xwen.com\": 1,\n\t\"xwham.com\": 1,\n\t\"xwhb.com\": 1,\n\t\"xwhb.net\": 1,\n\t\"xwhrcw.com\": 1,\n\t\"xwimg.com\": 1,\n\t\"xwpx.com\": 1,\n\t\"xx028.com\": 1,\n\t\"xxcig.com\": 1,\n\t\"xxcmw.com\": 1,\n\t\"xxcxw.com\": 1,\n\t\"xxdm.com\": 1,\n\t\"xxfang.com\": 1,\n\t\"xxgcw.com\": 1,\n\t\"xxgjj.com\": 1,\n\t\"xxhh.com\": 1,\n\t\"xxia.com\": 1,\n\t\"xxluo.com\": 1,\n\t\"xxplzx.com\": 1,\n\t\"xxs8.com\": 1,\n\t\"xxsc.com\": 1,\n\t\"xxsd.net\": 1,\n\t\"xxsp518.com\": 1,\n\t\"xxsy.net\": 1,\n\t\"xxtef.com\": 1,\n\t\"xxtg.com\": 1,\n\t\"xxtlw.com\": 1,\n\t\"xxxye.com\": 1,\n\t\"xxzhaopin.com\": 1,\n\t\"xxzq.com\": 1,\n\t\"xxzzm.com\": 1,\n\t\"xy.com\": 1,\n\t\"xy280.com\": 1,\n\t\"xy3nw.com\": 1,\n\t\"xy597.com\": 1,\n\t\"xy9981.com\": 1,\n\t\"xyanjia.com\": 1,\n\t\"xyb100.com\": 1,\n\t\"xydhl.com\": 1,\n\t\"xyfc.com\": 1,\n\t\"xyfcw.com\": 1,\n\t\"xyfnw.com\": 1,\n\t\"xyg100.com\": 1,\n\t\"xygjy.com\": 1,\n\t\"xygmed.com\": 1,\n\t\"xyimg.net\": 1,\n\t\"xyjrw.com\": 1,\n\t\"xypht.com\": 1,\n\t\"xyppzx.com\": 1,\n\t\"xyrc.net\": 1,\n\t\"xyrczpw.com\": 1,\n\t\"xyrtv.com\": 1,\n\t\"xyshu8.com\": 1,\n\t\"xywy.com\": 1,\n\t\"xyxww.com\": 1,\n\t\"xyxxg.com\": 1,\n\t\"xyxy.net\": 1,\n\t\"xyxy01.com\": 1,\n\t\"xyyao.com\": 1,\n\t\"xyybxg.com\": 1,\n\t\"xyyintong.com\": 1,\n\t\"xyzfgjj.com\": 1,\n\t\"xyzs.com\": 1,\n\t\"xyzwin.com\": 1,\n\t\"xz323.com\": 1,\n\t\"xz5u.com\": 1,\n\t\"xz5u.net\": 1,\n\t\"xz91.com\": 1,\n\t\"xzass.org\": 1,\n\t\"xzbu.com\": 1,\n\t\"xzfamily.com\": 1,\n\t\"xzfashion.com\": 1,\n\t\"xzgjj.com\": 1,\n\t\"xzhichang.com\": 1,\n\t\"xzhiliao.com\": 1,\n\t\"xzjob.net\": 1,\n\t\"xzjyh.com\": 1,\n\t\"xzl571.com\": 1,\n\t\"xzloo.com\": 1,\n\t\"xzlres.com\": 1,\n\t\"xzrbw.com\": 1,\n\t\"xzrj.cc\": 1,\n\t\"xzsw.net\": 1,\n\t\"xzt9.com\": 1,\n\t\"xzuan.com\": 1,\n\t\"xzxx.com\": 1,\n\t\"xzyuhui.com\": 1,\n\t\"xzzp.net\": 1,\n\t\"y13255262618.com\": 1,\n\t\"y261.com\": 1,\n\t\"y3600.com\": 1,\n\t\"y80s.cc\": 1,\n\t\"y999.com\": 1,\n\t\"ya247.com\": 1,\n\t\"ya597.com\": 1,\n\t\"yaanrcw.com\": 1,\n\t\"yaantv.com\": 1,\n\t\"yacely.com\": 1,\n\t\"yacol.com\": 1,\n\t\"yafengwu.com\": 1,\n\t\"yaheen.com\": 1,\n\t\"yahqq.com\": 1,\n\t\"yahui.cc\": 1,\n\t\"yakolux.com\": 1,\n\t\"yala517.com\": 1,\n\t\"yamszs.com\": 1,\n\t\"yanchang.com\": 1,\n\t\"yandongjixie.com\": 1,\n\t\"yanfabu.com\": 1,\n\t\"yanfang12365.com\": 1,\n\t\"yangche51.com\": 1,\n\t\"yangchenghuxie.com\": 1,\n\t\"yangfenzi.com\": 1,\n\t\"yangguangbao.com\": 1,\n\t\"yangji.com\": 1,\n\t\"yangjiajiao.com\": 1,\n\t\"yangjihu.com\": 1,\n\t\"yanglao120.com\": 1,\n\t\"yanglihui.com\": 1,\n\t\"yanglingwang.com\": 1,\n\t\"yangnai100.com\": 1,\n\t\"yangshenglife.com\": 1,\n\t\"yangshitianqi.com\": 1,\n\t\"yangsousou.com\": 1,\n\t\"yangsukj.com\": 1,\n\t\"yangtse.com\": 1,\n\t\"yanjiao.com\": 1,\n\t\"yanjiaorexian.com\": 1,\n\t\"yanjob.com\": 1,\n\t\"yankon.com\": 1,\n\t\"yanlutong.com\": 1,\n\t\"yanmo.net\": 1,\n\t\"yanmo360.com\": 1,\n\t\"yanmoxuan.com\": 1,\n\t\"yantai-chuanpiao.com\": 1,\n\t\"yantuchina.com\": 1,\n\t\"yantushi.com\": 1,\n\t\"yanxiaoni.com\": 1,\n\t\"yanzhaorc.com\": 1,\n\t\"yanzheng.com\": 1,\n\t\"yanzhoujob.com\": 1,\n\t\"yanzixiang.com\": 1,\n\t\"yaochufa.com\": 1,\n\t\"yaofangwang.com\": 1,\n\t\"yaofangwang.net\": 1,\n\t\"yaojingweiba.com\": 1,\n\t\"yaojobs.com\": 1,\n\t\"yaolan.com\": 1,\n\t\"yaosai.com\": 1,\n\t\"yaoshiduo.com\": 1,\n\t\"yaowan.com\": 1,\n\t\"yaoxie.net\": 1,\n\t\"yaoxinfu.com\": 1,\n\t\"yaozh.com\": 1,\n\t\"yaozs.com\": 1,\n\t\"yappygo.com\": 1,\n\t\"yarczp.com\": 1,\n\t\"yasn.com\": 1,\n\t\"yatai.com\": 1,\n\t\"yatu.tv\": 1,\n\t\"yaya888.com\": 1,\n\t\"yayawan.com\": 1,\n\t\"yb983.com\": 1,\n\t\"ybaixin.com\": 1,\n\t\"ybbbs.com\": 1,\n\t\"ybdu.com\": 1,\n\t\"ybgjj.com\": 1,\n\t\"ybhzs.com\": 1,\n\t\"ybk001.com\": 1,\n\t\"yblysy.com\": 1,\n\t\"ybmz.net\": 1,\n\t\"ybvv.com\": 1,\n\t\"ybxww.com\": 1,\n\t\"yc-cq.com\": 1,\n\t\"yc-yujia.com\": 1,\n\t\"yc.cc\": 1,\n\t\"yc123.com\": 1,\n\t\"yc597.com\": 1,\n\t\"yc9y.com\": 1,\n\t\"ycbbs.net\": 1,\n\t\"ycbole.com\": 1,\n\t\"yccar.com\": 1,\n\t\"yccdn.com\": 1,\n\t\"ycfang.net\": 1,\n\t\"ycfczc.com\": 1,\n\t\"ycgjj.com\": 1,\n\t\"ycgjj.net\": 1,\n\t\"ychdzx.co\": 1,\n\t\"ychr.com\": 1,\n\t\"yckuoda.com\": 1,\n\t\"yclunwen.com\": 1,\n\t\"ycpai.com\": 1,\n\t\"ycrczpw.com\": 1,\n\t\"ycrusher.com\": 1,\n\t\"ycseaman.com\": 1,\n\t\"ycshequ.com\": 1,\n\t\"ycsrcsc.com\": 1,\n\t\"yctarena.com\": 1,\n\t\"yctzw.org\": 1,\n\t\"ycwb.com\": 1,\n\t\"ycxc.com\": 1,\n\t\"ycxinxi.com\": 1,\n\t\"yczihua.com\": 1,\n\t\"yczjda.org\": 1,\n\t\"ydcast.com\": 1,\n\t\"ydcbw.com\": 1,\n\t\"yddyw.com\": 1,\n\t\"ydfcw.cc\": 1,\n\t\"ydjy.com\": 1,\n\t\"ydpsz.net\": 1,\n\t\"ydstatic.com\": 1,\n\t\"ydsteel.com\": 1,\n\t\"ye40.com\": 1,\n\t\"yeah.net\": 1,\n\t\"yeepay.com\": 1,\n\t\"yeesha.com\": 1,\n\t\"yefeilvshi.com\": 1,\n\t\"yejinye.com\": 1,\n\t\"yejinzg.com\": 1,\n\t\"yeluedu.org\": 1,\n\t\"yemaozi.com\": 1,\n\t\"yes515.com\": 1,\n\t\"yesfr.com\": 1,\n\t\"yeshanpo.com\": 1,\n\t\"yeshj.com\": 1,\n\t\"yesky.com\": 1,\n\t\"yesmywine.com\": 1,\n\t\"yesnb.net\": 1,\n\t\"yespearl.com\": 1,\n\t\"yesshou.com\": 1,\n\t\"yetu.net\": 1,\n\t\"yeyou.com\": 1,\n\t\"yeyoucdn.com\": 1,\n\t\"yeyoudaquan.com\": 1,\n\t\"yeyoujia.com\": 1,\n\t\"yeyouw.com\": 1,\n\t\"yeyouwo.com\": 1,\n\t\"yezhuwang.org\": 1,\n\t\"yf116.com\": 1,\n\t\"yf12365.com\": 1,\n\t\"yf133.com\": 1,\n\t\"yfdyf.com\": 1,\n\t\"yfgg.com\": 1,\n\t\"yfyc.cc\": 1,\n\t\"yg188.com\": 1,\n\t\"ygits.com\": 1,\n\t\"ygjj.com\": 1,\n\t\"ygqiantu.com\": 1,\n\t\"yh2002.com\": 1,\n\t\"yhd.com\": 1,\n\t\"yhdali.com\": 1,\n\t\"yhfd.net\": 1,\n\t\"yhganggou.com\": 1,\n\t\"yhh668.com\": 1,\n\t\"yhjj.com\": 1,\n\t\"yhouse.com\": 1,\n\t\"yhqh.net\": 1,\n\t\"yhtzx.net\": 1,\n\t\"yi-z.com\": 1,\n\t\"yi6.com\": 1,\n\t\"yi7.com\": 1,\n\t\"yiase.com\": 1,\n\t\"yibiaojob.com\": 1,\n\t\"yibinfen.com\": 1,\n\t\"yibu.com\": 1,\n\t\"yibuyibu.com\": 1,\n\t\"yicai.com\": 1,\n\t\"yicars.com\": 1,\n\t\"yichangly.com\": 1,\n\t\"yiche.com\": 1,\n\t\"yichemall.com\": 1,\n\t\"yicheshi.com\": 1,\n\t\"yichun0795.com\": 1,\n\t\"yichuntv.com\": 1,\n\t\"yicp.com\": 1,\n\t\"yida0760.com\": 1,\n\t\"yidaba.com\": 1,\n\t\"yidianchina.com\": 1,\n\t\"yidujia.com\": 1,\n\t\"yiecha.com\": 1,\n\t\"yiedu.org\": 1,\n\t\"yieldmanager.com\": 1,\n\t\"yifen.com\": 1,\n\t\"yifone.com\": 1,\n\t\"yifu.com\": 1,\n\t\"yigao.com\": 1,\n\t\"yigaokao.com\": 1,\n\t\"yihaodian.com\": 1,\n\t\"yihaodianimg.com\": 1,\n\t\"yihu.com\": 1,\n\t\"yihubaiying.com\": 1,\n\t\"yihuimg.com\": 1,\n\t\"yiihuu.com\": 1,\n\t\"yijiaqin.com\": 1,\n\t\"yijie.com\": 1,\n\t\"yijiuweilan.com\": 1,\n\t\"yijjj.com\": 1,\n\t\"yikedou.com\": 1,\n\t\"yikeer.com\": 1,\n\t\"yikuaiqu.com\": 1,\n\t\"yikuaiyou.com\": 1,\n\t\"yiledao.com\": 1,\n\t\"yili.com\": 1,\n\t\"yilianit.com\": 1,\n\t\"yiliaozhan.net\": 1,\n\t\"yilin.com\": 1,\n\t\"yiliu88.com\": 1,\n\t\"yilu365.com\": 1,\n\t\"yimanman.com\": 1,\n\t\"yimenchuang.com\": 1,\n\t\"yimianmian.com\": 1,\n\t\"yiminjiayuan.com\": 1,\n\t\"yinar.com\": 1,\n\t\"yingbishufa.com\": 1,\n\t\"yingchuang.com\": 1,\n\t\"yinghuangzs.com\": 1,\n\t\"yingjia360.com\": 1,\n\t\"yingjiesheng.com\": 1,\n\t\"yingkelawyer.com\": 1,\n\t\"yingmoo.com\": 1,\n\t\"yingqian.net\": 1,\n\t\"yingsheng.com\": 1,\n\t\"yingsoft.com\": 1,\n\t\"yingtaoai.com\": 1,\n\t\"yingwuyuzd.cc\": 1,\n\t\"yingxiao360.com\": 1,\n\t\"yingxiongji.com\": 1,\n\t\"yingyonghui.com\": 1,\n\t\"yingyu.com\": 1,\n\t\"yingyu360.com\": 1,\n\t\"yingyugaofen.com\": 1,\n\t\"yinhang.com\": 1,\n\t\"yinhang123.net\": 1,\n\t\"yinjucn.com\": 1,\n\t\"yinlianbang.com\": 1,\n\t\"yinlingyounao.com\": 1,\n\t\"yinongdai.com\": 1,\n\t\"yinsha.com\": 1,\n\t\"yinshihui.com\": 1,\n\t\"yintai.com\": 1,\n\t\"yinuowl.com\": 1,\n\t\"yinxingshu.com\": 1,\n\t\"yinyuegf.com\": 1,\n\t\"yinyuetai.com\": 1,\n\t\"yinzuojiaju.com\": 1,\n\t\"yipihuo.com\": 1,\n\t\"yiqibazi.com\": 1,\n\t\"yiqifa.com\": 1,\n\t\"yiqijixiang.com\": 1,\n\t\"yiqike.com\": 1,\n\t\"yiqisoo.com\": 1,\n\t\"yiren198.com\": 1,\n\t\"yirendai.com\": 1,\n\t\"yirong.net\": 1,\n\t\"yishu.com\": 1,\n\t\"yishujie.com\": 1,\n\t\"yisoche.com\": 1,\n\t\"yisou.com\": 1,\n\t\"yisou5.com\": 1,\n\t\"yitiaogen8.com\": 1,\n\t\"yiwan.com\": 1,\n\t\"yiwubuy.com\": 1,\n\t\"yiwufair.com\": 1,\n\t\"yiwugou.com\": 1,\n\t\"yixianjob.com\": 1,\n\t\"yixiaoba.com\": 1,\n\t\"yixieshi.com\": 1,\n\t\"yixin.im\": 1,\n\t\"yixingpx.com\": 1,\n\t\"yixue001.com\": 1,\n\t\"yixue99.com\": 1,\n\t\"yixuewang.com\": 1,\n\t\"yixuezp.com\": 1,\n\t\"yixun.com\": 1,\n\t\"yiyaolietou.com\": 1,\n\t\"yiyi.cc\": 1,\n\t\"yiyibuy.com\": 1,\n\t\"yiyu.com\": 1,\n\t\"yiyyy.com\": 1,\n\t\"yizhaopin.com\": 1,\n\t\"yizimg.com\": 1,\n\t\"yj-job.com\": 1,\n\t\"yj0577.com\": 1,\n\t\"yj518.com\": 1,\n\t\"yjbbs.net\": 1,\n\t\"yjbctv.com\": 1,\n\t\"yjbys.com\": 1,\n\t\"yjcom.com\": 1,\n\t\"yjdj.com\": 1,\n\t\"yjh321.com\": 1,\n\t\"yjlxauto.com\": 1,\n\t\"yjpdf.com\": 1,\n\t\"yjsjl.org\": 1,\n\t\"yjsyu.com\": 1,\n\t\"yk0579.com\": 1,\n\t\"ykimg.com\": 1,\n\t\"ykrx.com\": 1,\n\t\"yktchina.com\": 1,\n\t\"yktworld.com\": 1,\n\t\"ykw18.com\": 1,\n\t\"ykwin.com\": 1,\n\t\"yky.la\": 1,\n\t\"yl007.com\": 1,\n\t\"yl1001.com\": 1,\n\t\"yl114.cc\": 1,\n\t\"yldt.com\": 1,\n\t\"ylimg.com\": 1,\n\t\"ylmf.net\": 1,\n\t\"ylpcs.com\": 1,\n\t\"ylqxs.net\": 1,\n\t\"ylsw.com\": 1,\n\t\"ylsw.net\": 1,\n\t\"ylting.com\": 1,\n\t\"yltvb.com\": 1,\n\t\"ylw0813.com\": 1,\n\t\"ylw168.com\": 1,\n\t\"ylwltv.com\": 1,\n\t\"ylxw.net\": 1,\n\t\"ylxwzzb.com\": 1,\n\t\"ylxxg.com\": 1,\n\t\"ylzmhzs.com\": 1,\n\t\"ymapp.com\": 1,\n\t\"ymars.com\": 1,\n\t\"ymfile.com\": 1,\n\t\"ymkjpx.com\": 1,\n\t\"ymlaser.com\": 1,\n\t\"ymt360.com\": 1,\n\t\"yn1234.com\": 1,\n\t\"yn16.com\": 1,\n\t\"ynbz.net\": 1,\n\t\"ynchj.com\": 1,\n\t\"yncie.com\": 1,\n\t\"yncits08.com\": 1,\n\t\"yncoop.com\": 1,\n\t\"yndaily.com\": 1,\n\t\"yndtjj.com\": 1,\n\t\"ynedu.net\": 1,\n\t\"ynet.com\": 1,\n\t\"ynfjw.com\": 1,\n\t\"yngkseed.com\": 1,\n\t\"yngod.com\": 1,\n\t\"ynhl.net\": 1,\n\t\"ynhmw.com\": 1,\n\t\"ynhouse.com\": 1,\n\t\"ynhr.com\": 1,\n\t\"ynihao.com\": 1,\n\t\"yninfo.com\": 1,\n\t\"ynit580.com\": 1,\n\t\"ynithr.com\": 1,\n\t\"ynjtt.com\": 1,\n\t\"ynju.com\": 1,\n\t\"ynkcw.com\": 1,\n\t\"ynkcw.net\": 1,\n\t\"ynnm.com\": 1,\n\t\"ynpost.com\": 1,\n\t\"ynpxrz.com\": 1,\n\t\"ynradio.com\": 1,\n\t\"ynradio.net\": 1,\n\t\"ynshangji.com\": 1,\n\t\"ynsugar.com\": 1,\n\t\"yntrip88.com\": 1,\n\t\"ynwangli.com\": 1,\n\t\"ynxxb.com\": 1,\n\t\"ynyes.com\": 1,\n\t\"ynyh.com\": 1,\n\t\"ynyj.com\": 1,\n\t\"ynzol.com\": 1,\n\t\"ynzp.com\": 1,\n\t\"ynzpw.net\": 1,\n\t\"yo6.me\": 1,\n\t\"yocc.net\": 1,\n\t\"yodak.net\": 1,\n\t\"yodao.com\": 1,\n\t\"yofond.com\": 1,\n\t\"yofond.net\": 1,\n\t\"yofus.com\": 1,\n\t\"yoger01.com\": 1,\n\t\"yoher.com\": 1,\n\t\"yohobuy.com\": 1,\n\t\"yoka.com\": 1,\n\t\"yokacdn.com\": 1,\n\t\"yolk7.com\": 1,\n\t\"yongcheng.so\": 1,\n\t\"yongchengren.com\": 1,\n\t\"yongjiangrc.com\": 1,\n\t\"yongjiwooden.com\": 1,\n\t\"yonglijh.com\": 1,\n\t\"yooan.net\": 1,\n\t\"yooduo.com\": 1,\n\t\"yoofh.com\": 1,\n\t\"yoohouse.com\": 1,\n\t\"yooli.com\": 1,\n\t\"yoosure.com\": 1,\n\t\"yopin.net\": 1,\n\t\"yorkinstrument.com\": 1,\n\t\"you178.com\": 1,\n\t\"you89.com\": 1,\n\t\"youba.com\": 1,\n\t\"youban.com\": 1,\n\t\"youbian.com\": 1,\n\t\"youbianku.com\": 1,\n\t\"youbibi.com\": 1,\n\t\"youboy.com\": 1,\n\t\"youc.com\": 1,\n\t\"youcha.net\": 1,\n\t\"youcheng.org\": 1,\n\t\"youchepin.com\": 1,\n\t\"youdaili.net\": 1,\n\t\"youdao.com\": 1,\n\t\"youdu5.com\": 1,\n\t\"youfangw.com\": 1,\n\t\"yougou.com\": 1,\n\t\"youguow.com\": 1,\n\t\"youhaotravel.com\": 1,\n\t\"youhuaaa.com\": 1,\n\t\"youhuas.com\": 1,\n\t\"youjiao.com\": 1,\n\t\"youjiaxiao.com\": 1,\n\t\"youjindi.com\": 1,\n\t\"youjobit.com\": 1,\n\t\"youkecn.com\": 1,\n\t\"youkee.com\": 1,\n\t\"youkelai.com\": 1,\n\t\"youku.com\": 1,\n\t\"youle55.com\": 1,\n\t\"youlila.cc\": 1,\n\t\"youlu.net\": 1,\n\t\"youlunzhaopin.com\": 1,\n\t\"youmogu.com\": 1,\n\t\"youneng.com\": 1,\n\t\"youni.tv\": 1,\n\t\"youquba.net\": 1,\n\t\"youqudao.com\": 1,\n\t\"yousergroup.com\": 1,\n\t\"yousesky.com\": 1,\n\t\"youshang.com\": 1,\n\t\"youshanjiayuan.com\": 1,\n\t\"youshige.com\": 1,\n\t\"youtiy.com\": 1,\n\t\"youtulou.com\": 1,\n\t\"youtx.com\": 1,\n\t\"youwo.com\": 1,\n\t\"youwo123.com\": 1,\n\t\"youxi.com\": 1,\n\t\"youxi369.com\": 1,\n\t\"youxi5.net\": 1,\n\t\"youxi86.com\": 1,\n\t\"youxiake.com\": 1,\n\t\"youxiake.net\": 1,\n\t\"youxibe.com\": 1,\n\t\"youxiduo.com\": 1,\n\t\"youxigonglue8.com\": 1,\n\t\"youxigt.com\": 1,\n\t\"youxigu.com\": 1,\n\t\"youxihezi.net\": 1,\n\t\"youxihuoban.com\": 1,\n\t\"youxike.com\": 1,\n\t\"youxilao.com\": 1,\n\t\"youxile.com\": 1,\n\t\"youxinan.com\": 1,\n\t\"youxiniao.com\": 1,\n\t\"youxiping.com\": 1,\n\t\"youxiputao.com\": 1,\n\t\"youxiqun.com\": 1,\n\t\"youxituoluo.com\": 1,\n\t\"youxiuhui.com\": 1,\n\t\"youxiwangguo.com\": 1,\n\t\"youxiweixun.com\": 1,\n\t\"youxjia.com\": 1,\n\t\"youyou234.com\": 1,\n\t\"youyuan.com\": 1,\n\t\"youyy.com\": 1,\n\t\"youzhiqin.com\": 1,\n\t\"youzhuan.com\": 1,\n\t\"youzu.com\": 1,\n\t\"yoyi.tv\": 1,\n\t\"yoyobaby.com\": 1,\n\t\"yoyojie.com\": 1,\n\t\"yoyou.com\": 1,\n\t\"yp10000.com\": 1,\n\t\"yp360.net\": 1,\n\t\"yp900.com\": 1,\n\t\"ypgair.com\": 1,\n\t\"ypian.com\": 1,\n\t\"ypwjob.com\": 1,\n\t\"yq919.com\": 1,\n\t\"yqbdt.com\": 1,\n\t\"yqdown.com\": 1,\n\t\"yqfcw.net\": 1,\n\t\"yqjiehun.com\": 1,\n\t\"yqpt.net\": 1,\n\t\"yqrc.com\": 1,\n\t\"yqrtv.com\": 1,\n\t\"yr1818.com\": 1,\n\t\"ys137.com\": 1,\n\t\"ys168.com\": 1,\n\t\"ys1688.com\": 1,\n\t\"ys7.com\": 1,\n\t\"ys7828.com\": 1,\n\t\"ysali.com\": 1,\n\t\"yscbook.com\": 1,\n\t\"ysedu.org\": 1,\n\t\"yshc.net\": 1,\n\t\"yshlawyer.com\": 1,\n\t\"ysjvip.com\": 1,\n\t\"ysnews.org\": 1,\n\t\"ysrencai.com\": 1,\n\t\"ysw365.com\": 1,\n\t\"yswxcn.com\": 1,\n\t\"yt160.com\": 1,\n\t\"ytbbs.com\": 1,\n\t\"ytbxw.com\": 1,\n\t\"ytcnc.net\": 1,\n\t\"ytcutv.com\": 1,\n\t\"ytdwhyjzs.com\": 1,\n\t\"ythouse.com\": 1,\n\t\"ytinstrument.com\": 1,\n\t\"ytjob.com\": 1,\n\t\"ytloushi.com\": 1,\n\t\"ytrczpw.com\": 1,\n\t\"ytrlzyw.com\": 1,\n\t\"ytscd.com\": 1,\n\t\"ytszg.com\": 1,\n\t\"ytwrc.com\": 1,\n\t\"ytx.cc\": 1,\n\t\"ytxww.com\": 1,\n\t\"yu-dian.com\": 1,\n\t\"yuadmin.com\": 1,\n\t\"yuai.com\": 1,\n\t\"yuananren.com\": 1,\n\t\"yuanlin.com\": 1,\n\t\"yuanlin001.com\": 1,\n\t\"yuanlin365.com\": 1,\n\t\"yuanlin8.com\": 1,\n\t\"yuanliner.com\": 1,\n\t\"yuanlinyc.com\": 1,\n\t\"yuantengfei.net\": 1,\n\t\"yuanyetrip.com\": 1,\n\t\"yublue.com\": 1,\n\t\"yubooa.com\": 1,\n\t\"yucde.com\": 1,\n\t\"yuchai.com\": 1,\n\t\"yudujob.com\": 1,\n\t\"yuduzi.com\": 1,\n\t\"yue365.com\": 1,\n\t\"yuecheng.com\": 1,\n\t\"yueduge.net\": 1,\n\t\"yuedutong.com\": 1,\n\t\"yueduwen.com\": 1,\n\t\"yuejianglou.com\": 1,\n\t\"yuejob.com\": 1,\n\t\"yuelian.com.tw\": 1,\n\t\"yueloo.com\": 1,\n\t\"yuemei.com\": 1,\n\t\"yuerzaixian.com\": 1,\n\t\"yuewo.com\": 1,\n\t\"yuexiren.com\": 1,\n\t\"yueyuzhushou.com\": 1,\n\t\"yufolunchan.com\": 1,\n\t\"yugunet.com\": 1,\n\t\"yuhuijob.com\": 1,\n\t\"yujia.com\": 1,\n\t\"yujia99.com\": 1,\n\t\"yujiang.cc\": 1,\n\t\"yukuai.com\": 1,\n\t\"yule360.net\": 1,\n\t\"yulehezi.com\": 1,\n\t\"yulindayday.com\": 1,\n\t\"yulipump.com\": 1,\n\t\"yuloo.com\": 1,\n\t\"yulua.com\": 1,\n\t\"yun61.com\": 1,\n\t\"yunanjgs.com\": 1,\n\t\"yunbangwang.com\": 1,\n\t\"yunbei.com\": 1,\n\t\"yunceng.com\": 1,\n\t\"yuncheng.com\": 1,\n\t\"yunchenghr.com\": 1,\n\t\"yunci4.com\": 1,\n\t\"yundaex.com\": 1,\n\t\"yundangan.com\": 1,\n\t\"yundianrc.com\": 1,\n\t\"yunfudaily.com\": 1,\n\t\"yunhepan.com\": 1,\n\t\"yunli.com\": 1,\n\t\"yunmaotong.com\": 1,\n\t\"yunnanrc.com\": 1,\n\t\"yunnao.com\": 1,\n\t\"yunos.com\": 1,\n\t\"yunshipei.com\": 1,\n\t\"yunshow.com\": 1,\n\t\"yuntaishan.net\": 1,\n\t\"yuntaodu.com\": 1,\n\t\"yunust.com\": 1,\n\t\"yunuu.com\": 1,\n\t\"yunwenxue.com\": 1,\n\t\"yunyangrc.com\": 1,\n\t\"yupoo.com\": 1,\n\t\"yuqinge.com\": 1,\n\t\"yuqingtong.org\": 1,\n\t\"yurun.com\": 1,\n\t\"yusuan.com\": 1,\n\t\"yutai100.com\": 1,\n\t\"yuu1.com\": 1,\n\t\"yuwenba.net\": 1,\n\t\"yuxinews.com\": 1,\n\t\"yuyingchina.com\": 1,\n\t\"yuzhepeixun.com\": 1,\n\t\"yuzhou.net\": 1,\n\t\"yw11.com\": 1,\n\t\"yw2005.com\": 1,\n\t\"yw597.com\": 1,\n\t\"ywbb.com\": 1,\n\t\"ywcec.com\": 1,\n\t\"ywcq.com\": 1,\n\t\"ywec.net\": 1,\n\t\"ywefood.com\": 1,\n\t\"ywexpo.net\": 1,\n\t\"ywmeexpo.com\": 1,\n\t\"ywxue.com\": 1,\n\t\"ywzz.com\": 1,\n\t\"yx-s.com\": 1,\n\t\"yx007.com\": 1,\n\t\"yx136.com\": 1,\n\t\"yx99.com\": 1,\n\t\"yxacw.com\": 1,\n\t\"yxad.com\": 1,\n\t\"yxbao.com\": 1,\n\t\"yxdaily.com\": 1,\n\t\"yxdown.com\": 1,\n\t\"yxgjj.com\": 1,\n\t\"yxi5.com\": 1,\n\t\"yxi8.com\": 1,\n\t\"yxjiaoyu.net\": 1,\n\t\"yxks.cc\": 1,\n\t\"yxlady.com\": 1,\n\t\"yxm.com\": 1,\n\t\"yxph.com\": 1,\n\t\"yxqnews.com\": 1,\n\t\"yxsanhu.com\": 1,\n\t\"yxtvg.com\": 1,\n\t\"yxzoo.com\": 1,\n\t\"yxzp.net\": 1,\n\t\"yy.cm\": 1,\n\t\"yy.com\": 1,\n\t\"yy.tv\": 1,\n\t\"yy138.com\": 1,\n\t\"yy21.net\": 1,\n\t\"yy88.cc\": 1,\n\t\"yy960.com\": 1,\n\t\"yy99.net\": 1,\n\t\"yybbs.com\": 1,\n\t\"yycqc.com\": 1,\n\t\"yydm.com\": 1,\n\t\"yyets.com\": 1,\n\t\"yyfad.com\": 1,\n\t\"yyfdc.net\": 1,\n\t\"yyfdcw.com\": 1,\n\t\"yyfensi.com\": 1,\n\t\"yygjj.com\": 1,\n\t\"yygsl.org\": 1,\n\t\"yyhao.com\": 1,\n\t\"yyhh.com\": 1,\n\t\"yyhospital.com\": 1,\n\t\"yyhqys.com\": 1,\n\t\"yyjia.com\": 1,\n\t\"yyjol.com\": 1,\n\t\"yykc.com\": 1,\n\t\"yykx.org\": 1,\n\t\"yylm.org\": 1,\n\t\"yyly.net\": 1,\n\t\"yymjx.com\": 1,\n\t\"yyqc.com\": 1,\n\t\"yyqx.com\": 1,\n\t\"yyrc.com\": 1,\n\t\"yyrtv.com\": 1,\n\t\"yysweb.com\": 1,\n\t\"yyt360.com\": 1,\n\t\"yytcdn.com\": 1,\n\t\"yytou.com\": 1,\n\t\"yytzx.com\": 1,\n\t\"yyxggjm.com\": 1,\n\t\"yyxh.org\": 1,\n\t\"yyxinqing.com\": 1,\n\t\"yyxj8.com\": 1,\n\t\"yyxnews.com\": 1,\n\t\"yyxt.com\": 1,\n\t\"yyxxcc.com\": 1,\n\t\"yyzs.net\": 1,\n\t\"yz-china.com\": 1,\n\t\"yz2shou.com\": 1,\n\t\"yz2y.com\": 1,\n\t\"yz355.com\": 1,\n\t\"yzcl.org\": 1,\n\t\"yzcts.com\": 1,\n\t\"yzdjbh.com\": 1,\n\t\"yzdsb.com\": 1,\n\t\"yzedu.net\": 1,\n\t\"yzfcd.com\": 1,\n\t\"yzfcjy.net\": 1,\n\t\"yzfcw.com\": 1,\n\t\"yzforex.com\": 1,\n\t\"yzhyw.com\": 1,\n\t\"yzjdc.com\": 1,\n\t\"yzqcw.com\": 1,\n\t\"yzrc.com\": 1,\n\t\"yzrsrc.net\": 1,\n\t\"yzsc.net\": 1,\n\t\"yzsfcw.com\": 1,\n\t\"yzw.cc\": 1,\n\t\"yzwb.net\": 1,\n\t\"yzwh.net\": 1,\n\t\"yzxw.com\": 1,\n\t\"yzzaoxing.com\": 1,\n\t\"z4bbs.com\": 1,\n\t\"z888.net\": 1,\n\t\"zafk120.com\": 1,\n\t\"zahuishi.com\": 1,\n\t\"zaihuangshi.com\": 1,\n\t\"zaisd.com\": 1,\n\t\"zaiyunbian.com\": 1,\n\t\"zaizai5.com\": 1,\n\t\"zan800.com\": 1,\n\t\"zanba.com\": 1,\n\t\"zanzw.com\": 1,\n\t\"zaobao.com\": 1,\n\t\"zaoche168.com\": 1,\n\t\"zaojia.com\": 1,\n\t\"zaojiao.com\": 1,\n\t\"zaojiashi.com\": 1,\n\t\"zaojob.com\": 1,\n\t\"zaopang.com\": 1,\n\t\"zaoyang.org\": 1,\n\t\"zaozhichu.com\": 1,\n\t\"zaozhuangfangchan.com\": 1,\n\t\"zastatic.com\": 1,\n\t\"zauu.net\": 1,\n\t\"zaxsw.org\": 1,\n\t\"zazhipu.com\": 1,\n\t\"zb2b.net\": 1,\n\t\"zb31.com\": 1,\n\t\"zb580.tv\": 1,\n\t\"zbcars.com\": 1,\n\t\"zbedu.net\": 1,\n\t\"zbfjsj.com\": 1,\n\t\"zbgjpx.com\": 1,\n\t\"zbgl.net\": 1,\n\t\"zbhouse.com\": 1,\n\t\"zbii.com\": 1,\n\t\"zbinfo.net\": 1,\n\t\"zbintel.com\": 1,\n\t\"zbird.com\": 1,\n\t\"zbjimg.com\": 1,\n\t\"zbjinchen.com\": 1,\n\t\"zbjjrcw.com\": 1,\n\t\"zblz.net\": 1,\n\t\"zbmiao.com\": 1,\n\t\"zbnews.net\": 1,\n\t\"zbradio.com\": 1,\n\t\"zbsme.com\": 1,\n\t\"zbyz.org\": 1,\n\t\"zbzfgjj.com\": 1,\n\t\"zcbgxx.net\": 1,\n\t\"zcfun.com\": 1,\n\t\"zcgd.net\": 1,\n\t\"zcheer.com\": 1,\n\t\"zchospital.com\": 1,\n\t\"zcom.com\": 1,\n\t\"zcqiche.com\": 1,\n\t\"zcrcw.com\": 1,\n\t\"zcrczp.com\": 1,\n\t\"zctcar.com\": 1,\n\t\"zctt.com\": 1,\n\t\"zcwz.com\": 1,\n\t\"zcxn.com\": 1,\n\t\"zcyy8.com\": 1,\n\t\"zd360.com\": 1,\n\t\"zddmall.com\": 1,\n\t\"zdface.com\": 1,\n\t\"zdhnjd.com\": 1,\n\t\"zdhtjx.com\": 1,\n\t\"zdhyb.com\": 1,\n\t\"zdian.cc\": 1,\n\t\"zdic.net\": 1,\n\t\"zdmimg.com\": 1,\n\t\"zdrcw.com\": 1,\n\t\"zei6.com\": 1,\n\t\"zei6.net\": 1,\n\t\"zei8.com\": 1,\n\t\"zenque.com\": 1,\n\t\"zepao.com\": 1,\n\t\"zero-orez.com\": 1,\n\t\"zero2ipovc.com\": 1,\n\t\"zf3d.com\": 1,\n\t\"zf875.com\": 1,\n\t\"zf9918.com\": 1,\n\t\"zfang.com\": 1,\n\t\"zfn8.com\": 1,\n\t\"zft.com\": 1,\n\t\"zg-ld.com\": 1,\n\t\"zg-xbwh.com\": 1,\n\t\"zg0543.com\": 1,\n\t\"zg17.com\": 1,\n\t\"zg1929.com\": 1,\n\t\"zgb365.com\": 1,\n\t\"zgbfw.com\": 1,\n\t\"zgbigart.com\": 1,\n\t\"zgbm.com\": 1,\n\t\"zgc-bigdata.org\": 1,\n\t\"zgchangfang.com\": 1,\n\t\"zgchawang.com\": 1,\n\t\"zgcmlm.com\": 1,\n\t\"zgcsgd.com\": 1,\n\t\"zgcyfz.com\": 1,\n\t\"zgcyly.com\": 1,\n\t\"zgcylymh.com\": 1,\n\t\"zgczxzx.com\": 1,\n\t\"zgdjyj.com\": 1,\n\t\"zgdkj.net\": 1,\n\t\"zgdls.com\": 1,\n\t\"zgdrive.com\": 1,\n\t\"zget.org\": 1,\n\t\"zgfcn.com\": 1,\n\t\"zgftjg.com\": 1,\n\t\"zgfxnews.com\": 1,\n\t\"zgfxnews.net\": 1,\n\t\"zgfznews.com\": 1,\n\t\"zgg35.com\": 1,\n\t\"zggdjj.com\": 1,\n\t\"zgghw.org\": 1,\n\t\"zggwyw.com\": 1,\n\t\"zggyp.com\": 1,\n\t\"zggzn.net\": 1,\n\t\"zghbsw.com\": 1,\n\t\"zghjjlm.com\": 1,\n\t\"zgjcjs.com\": 1,\n\t\"zgjczzw.com\": 1,\n\t\"zgjf168.com\": 1,\n\t\"zgjfs.com\": 1,\n\t\"zgjhjy.com\": 1,\n\t\"zgjhjy.net\": 1,\n\t\"zgjlxww.com\": 1,\n\t\"zgjm.org\": 1,\n\t\"zgjn365.com\": 1,\n\t\"zgjnzx.com\": 1,\n\t\"zgjrcw.com\": 1,\n\t\"zgjrjw.com\": 1,\n\t\"zgjrzk.com\": 1,\n\t\"zgjsks.com\": 1,\n\t\"zgjtb.com\": 1,\n\t\"zgjy111.com\": 1,\n\t\"zgjzlw.com\": 1,\n\t\"zgjzy.org\": 1,\n\t\"zgkjzx.com\": 1,\n\t\"zgkspx.com\": 1,\n\t\"zglcppt.com\": 1,\n\t\"zgltgj.com\": 1,\n\t\"zglxw.com\": 1,\n\t\"zgmcxw.com\": 1,\n\t\"zgmdbw.com\": 1,\n\t\"zgmklt.com\": 1,\n\t\"zgmt.net\": 1,\n\t\"zgmtkj.com\": 1,\n\t\"zgmxzx.com\": 1,\n\t\"zgnfcphy.com\": 1,\n\t\"zgnfcpjx.com\": 1,\n\t\"zgnhzx.com\": 1,\n\t\"zgnmg.org\": 1,\n\t\"zgnt.net\": 1,\n\t\"zgnykj.net\": 1,\n\t\"zgnyqss.com\": 1,\n\t\"zgong.com\": 1,\n\t\"zgppny.com\": 1,\n\t\"zgqczj.com\": 1,\n\t\"zgqdrc.com\": 1,\n\t\"zgqpc.com\": 1,\n\t\"zgqsc.com\": 1,\n\t\"zgqw.com\": 1,\n\t\"zgrb.net\": 1,\n\t\"zgrcjyw.com\": 1,\n\t\"zgrdcy.com\": 1,\n\t\"zgsbzlcy.com\": 1,\n\t\"zgsc123.com\": 1,\n\t\"zgsccd.com\": 1,\n\t\"zgscpcy.com\": 1,\n\t\"zgsdsmh.com\": 1,\n\t\"zgsee.net\": 1,\n\t\"zgshengsi.com\": 1,\n\t\"zgshjy.org\": 1,\n\t\"zgshoes.com\": 1,\n\t\"zgsjylhy.com\": 1,\n\t\"zgsjyxzx.com\": 1,\n\t\"zgsjzxxx.com\": 1,\n\t\"zgslylw.com\": 1,\n\t\"zgsof.com\": 1,\n\t\"zgspgq.com\": 1,\n\t\"zgswcn.com\": 1,\n\t\"zgsxzs.com\": 1,\n\t\"zgsyb.com\": 1,\n\t\"zgsydw.com\": 1,\n\t\"zgsynews.com\": 1,\n\t\"zgtcha.com\": 1,\n\t\"zgthj.net\": 1,\n\t\"zgtjh.com\": 1,\n\t\"zgtnzx.com\": 1,\n\t\"zgxbmjw.com\": 1,\n\t\"zgxf88.com\": 1,\n\t\"zgxnyzx.com\": 1,\n\t\"zgxzw.com\": 1,\n\t\"zgycrc.com\": 1,\n\t\"zgyey.com\": 1,\n\t\"zgys.net\": 1,\n\t\"zgyspp.com\": 1,\n\t\"zgyss.mobi\": 1,\n\t\"zgyushiwang.com\": 1,\n\t\"zgyz001.com\": 1,\n\t\"zgzcw.com\": 1,\n\t\"zgznh.com\": 1,\n\t\"zgzsp.com\": 1,\n\t\"zgzsw.com\": 1,\n\t\"zgzsys.com\": 1,\n\t\"zgzx114.com\": 1,\n\t\"zgzzs.net\": 1,\n\t\"zh-365.com\": 1,\n\t\"zh-hr.com\": 1,\n\t\"zh-hz.com\": 1,\n\t\"zh28.com\": 1,\n\t\"zh5000.com\": 1,\n\t\"zh51home.com\": 1,\n\t\"zh853.com\": 1,\n\t\"zhaif.com\": 1,\n\t\"zhaigirl.com\": 1,\n\t\"zhaihei.com\": 1,\n\t\"zhainanwan.com\": 1,\n\t\"zhairport.com\": 1,\n\t\"zhanggame.com\": 1,\n\t\"zhangjiajie.me\": 1,\n\t\"zhangjiang.net\": 1,\n\t\"zhangjk.com\": 1,\n\t\"zhangle.com\": 1,\n\t\"zhangniu.com\": 1,\n\t\"zhangpu597.com\": 1,\n\t\"zhangyoushijie.com\": 1,\n\t\"zhankua.com\": 1,\n\t\"zhanqi.tv\": 1,\n\t\"zhantai.com\": 1,\n\t\"zhanzhang.net\": 1,\n\t\"zhaoapple.com\": 1,\n\t\"zhaobiaoshi.net\": 1,\n\t\"zhaocaihr.com\": 1,\n\t\"zhaochafa.com\": 1,\n\t\"zhaodanji.com\": 1,\n\t\"zhaodao123.com\": 1,\n\t\"zhaofangtong.com\": 1,\n\t\"zhaofangtong.net\": 1,\n\t\"zhaogejia.com\": 1,\n\t\"zhaoiphone.com\": 1,\n\t\"zhaojiaxiao.com\": 1,\n\t\"zhaokao.net\": 1,\n\t\"zhaoming123.com\": 1,\n\t\"zhaomingwjj.com\": 1,\n\t\"zhaopin.com\": 1,\n\t\"zhaopin2.com\": 1,\n\t\"zhaopinhui.biz\": 1,\n\t\"zhaopinhui.org\": 1,\n\t\"zhaopinxitong.com\": 1,\n\t\"zhaopuw.com\": 1,\n\t\"zhaoqiweb.com\": 1,\n\t\"zhaoshang-sh.com\": 1,\n\t\"zhaoshang.net\": 1,\n\t\"zhaoshang01.com\": 1,\n\t\"zhaoshang100.com\": 1,\n\t\"zhaoshang800.com\": 1,\n\t\"zhaoshangbao.com\": 1,\n\t\"zhaosheng.com\": 1,\n\t\"zhaotie.com\": 1,\n\t\"zhaoxi.net\": 1,\n\t\"zhaoxiaoshuo.com\": 1,\n\t\"zhaoyuan365.com\": 1,\n\t\"zhayoule.com\": 1,\n\t\"zhazhi.com\": 1,\n\t\"zhbiao.com\": 1,\n\t\"zhcoo.com\": 1,\n\t\"zhcpic.com\": 1,\n\t\"zhcw.com\": 1,\n\t\"zhdzw.com\": 1,\n\t\"zhe800.com\": 1,\n\t\"zhedakaoyan.com\": 1,\n\t\"zhelun.com\": 1,\n\t\"zhenai.com\": 1,\n\t\"zhenfangyuan.com\": 1,\n\t\"zhengfayingjie.com\": 1,\n\t\"zhengjin99.com\": 1,\n\t\"zhengquanzige.com\": 1,\n\t\"zhengwutong.com\": 1,\n\t\"zhengzhoubus.com\": 1,\n\t\"zhenimg.com\": 1,\n\t\"zhenjianghr.com\": 1,\n\t\"zhenkong.info\": 1,\n\t\"zhenpin.com\": 1,\n\t\"zhenren.com\": 1,\n\t\"zhenweiexpo.com\": 1,\n\t\"zheyangai.com\": 1,\n\t\"zheyibu.com\": 1,\n\t\"zhgczj.com\": 1,\n\t\"zhgl.com\": 1,\n\t\"zhgnews.com\": 1,\n\t\"zhhbi.com\": 1,\n\t\"zhhbw.com\": 1,\n\t\"zhhdq.com\": 1,\n\t\"zhi.hu\": 1,\n\t\"zhibio.com\": 1,\n\t\"zhibitouzi.com\": 1,\n\t\"zhibo8.cc\": 1,\n\t\"zhibo8.com\": 1,\n\t\"zhibo8.org\": 1,\n\t\"zhiboba.com\": 1,\n\t\"zhibowu.com\": 1,\n\t\"zhicg.com\": 1,\n\t\"zhicheng.com\": 1,\n\t\"zhidantour.com\": 1,\n\t\"zhiding8.com\": 1,\n\t\"zhidiy.com\": 1,\n\t\"zhifang.com\": 1,\n\t\"zhifujing.org\": 1,\n\t\"zhigame.com\": 1,\n\t\"zhige.net\": 1,\n\t\"zhigou.com\": 1,\n\t\"zhihelou.com\": 1,\n\t\"zhihongchazhuang.com\": 1,\n\t\"zhihu.com\": 1,\n\t\"zhihuilv.com\": 1,\n\t\"zhihuimami.com\": 1,\n\t\"zhiji.com\": 1,\n\t\"zhijia.com\": 1,\n\t\"zhijinsteel.com\": 1,\n\t\"zhijintuan.com\": 1,\n\t\"zhijinwang.com\": 1,\n\t\"zhileng.com\": 1,\n\t\"zhileng8.com\": 1,\n\t\"zhiliangshi.com\": 1,\n\t\"zhimantian.com\": 1,\n\t\"zhinei.com\": 1,\n\t\"zhineikaixin.com\": 1,\n\t\"zhinengjiaotong.com\": 1,\n\t\"zhinews.com\": 1,\n\t\"zhishagongyi.com\": 1,\n\t\"zhitechan.com\": 1,\n\t\"zhituad.com\": 1,\n\t\"zhitui.com\": 1,\n\t\"zhiweiwenshi.com\": 1,\n\t\"zhiwenyl.com\": 1,\n\t\"zhixiangji.net\": 1,\n\t\"zhixuan.com\": 1,\n\t\"zhiye.com\": 1,\n\t\"zhiyehushi.net\": 1,\n\t\"zhiyeyaoshi.com\": 1,\n\t\"zhiyeyishi.com\": 1,\n\t\"zhiyinmanhua.com\": 1,\n\t\"zhiyuanfuwu.com\": 1,\n\t\"zhiyuanyun.com\": 1,\n\t\"zhizaoye.net\": 1,\n\t\"zhiziyun.com\": 1,\n\t\"zhjiameng.com\": 1,\n\t\"zhjunshi.com\": 1,\n\t\"zhjy.net\": 1,\n\t\"zhjzmh.com\": 1,\n\t\"zhld.com\": 1,\n\t\"zhmmw.net\": 1,\n\t\"zhnc.org\": 1,\n\t\"zhnews.net\": 1,\n\t\"zhnjw.com\": 1,\n\t\"zhong-yao.net\": 1,\n\t\"zhongbuauto.com\": 1,\n\t\"zhongdaonet.com\": 1,\n\t\"zhongdeng.com\": 1,\n\t\"zhongdingw.com\": 1,\n\t\"zhongguodali.com\": 1,\n\t\"zhongguokanghui.com\": 1,\n\t\"zhongguolaoqu.com\": 1,\n\t\"zhongguonongziwang.com\": 1,\n\t\"zhongguosyzs.com\": 1,\n\t\"zhongguowangshi.com\": 1,\n\t\"zhonghuacar.com\": 1,\n\t\"zhongji8.com\": 1,\n\t\"zhongjiao.net\": 1,\n\t\"zhongkao.com\": 1,\n\t\"zhongkao5.com\": 1,\n\t\"zhonglianyian.com\": 1,\n\t\"zhongman.com\": 1,\n\t\"zhongp.com\": 1,\n\t\"zhongshanbus.com\": 1,\n\t\"zhongshantong.net\": 1,\n\t\"zhongso.com\": 1,\n\t\"zhongsou.com\": 1,\n\t\"zhongsou.net\": 1,\n\t\"zhongyalyw.com\": 1,\n\t\"zhongyuanauto.com\": 1,\n\t\"zhongzhourc.com\": 1,\n\t\"zhoujijl.com\": 1,\n\t\"zhousipump.com\": 1,\n\t\"zhqxj.com\": 1,\n\t\"zhsh5000.com\": 1,\n\t\"zhsho.com\": 1,\n\t\"zhsti.net\": 1,\n\t\"zhtdshy.com\": 1,\n\t\"zhtmw.com\": 1,\n\t\"zhtool.com\": 1,\n\t\"zhtv.com\": 1,\n\t\"zhuang100.com\": 1,\n\t\"zhuangjiba.com\": 1,\n\t\"zhuangku.com\": 1,\n\t\"zhuangpin.com\": 1,\n\t\"zhuangxiu.name\": 1,\n\t\"zhuangxiu315.com\": 1,\n\t\"zhuannet.com\": 1,\n\t\"zhuanseo.com\": 1,\n\t\"zhuantiku.com\": 1,\n\t\"zhuanyewanjia.com\": 1,\n\t\"zhuapo.com\": 1,\n\t\"zhuaxia.com\": 1,\n\t\"zhuayoukong.com\": 1,\n\t\"zhubajie.com\": 1,\n\t\"zhubao.com\": 1,\n\t\"zhubing120.com\": 1,\n\t\"zhuchengrc.com\": 1,\n\t\"zhuego.com\": 1,\n\t\"zhufu.tv\": 1,\n\t\"zhuhaia.com\": 1,\n\t\"zhuhaifc.com\": 1,\n\t\"zhuhaily.com\": 1,\n\t\"zhuhaimy.com\": 1,\n\t\"zhuinvsheng.com\": 1,\n\t\"zhujia360.com\": 1,\n\t\"zhujia86.com\": 1,\n\t\"zhujiaba.com\": 1,\n\t\"zhujiange.com\": 1,\n\t\"zhujiangrc.com\": 1,\n\t\"zhujiangroad.com\": 1,\n\t\"zhujiankang.com\": 1,\n\t\"zhuke.com\": 1,\n\t\"zhulang.com\": 1,\n\t\"zhulink.com\": 1,\n\t\"zhulisy.com\": 1,\n\t\"zhulong.com\": 1,\n\t\"zhunbaba.net\": 1,\n\t\"zhuo.com\": 1,\n\t\"zhuodingedu.com\": 1,\n\t\"zhuoji.com\": 1,\n\t\"zhuojie.cc\": 1,\n\t\"zhuokearts.com\": 1,\n\t\"zhuoku.com\": 1,\n\t\"zhuoyueenglish.com\": 1,\n\t\"zhuozhoufangchan.com\": 1,\n\t\"zhuozhourencai.com\": 1,\n\t\"zhuqu.com\": 1,\n\t\"zhuqunqing.com\": 1,\n\t\"zhushouwang.net\": 1,\n\t\"zhuwang.cc\": 1,\n\t\"zhuzao.com\": 1,\n\t\"zhuzaochina.com\": 1,\n\t\"zhuzaohr.com\": 1,\n\t\"zhuzhouwang.com\": 1,\n\t\"zhuzhudao.com\": 1,\n\t\"zhwsjd.com\": 1,\n\t\"zhxjyw.com\": 1,\n\t\"zhxwang.com\": 1,\n\t\"zhxww.net\": 1,\n\t\"zhyw.net\": 1,\n\t\"zhzfc.com\": 1,\n\t\"zhzyw.org\": 1,\n\t\"zibo.net\": 1,\n\t\"zibocn.com\": 1,\n\t\"zibomama.com\": 1,\n\t\"ziborc.com\": 1,\n\t\"zibosky.com\": 1,\n\t\"zidiantong.com\": 1,\n\t\"zidianwang.com\": 1,\n\t\"zihua01.com\": 1,\n\t\"zijiayoucn.com\": 1,\n\t\"zijinyin.com\": 1,\n\t\"zikao1688.com\": 1,\n\t\"zikao365.com\": 1,\n\t\"zikaos.net\": 1,\n\t\"ziling.com\": 1,\n\t\"zimilan.com\": 1,\n\t\"ziranzhibao.com\": 1,\n\t\"ziroom.com\": 1,\n\t\"ziroomapartment.com\": 1,\n\t\"zisha.com\": 1,\n\t\"zisha360.com\": 1,\n\t\"zisha8090.com\": 1,\n\t\"zishayx.com\": 1,\n\t\"zishayy.com\": 1,\n\t\"zitichina.com\": 1,\n\t\"ziuziu.net\": 1,\n\t\"ziwoniu.com\": 1,\n\t\"zixia.com\": 1,\n\t\"zixuekaoshi.net\": 1,\n\t\"zixuexi.com\": 1,\n\t\"zixuntop.com\": 1,\n\t\"ziyuan5.com\": 1,\n\t\"zj-alevel.com\": 1,\n\t\"zj.com\": 1,\n\t\"zj005.com\": 1,\n\t\"zj121.com\": 1,\n\t\"zj123.com\": 1,\n\t\"zj186.com\": 1,\n\t\"zj315.org\": 1,\n\t\"zj9.com\": 1,\n\t\"zjadgroup.com\": 1,\n\t\"zjbar.com\": 1,\n\t\"zjcaoban.com\": 1,\n\t\"zjcb.com\": 1,\n\t\"zjcheshi.com\": 1,\n\t\"zjchina.org\": 1,\n\t\"zjchuguo.com\": 1,\n\t\"zjcoal.com\": 1,\n\t\"zjcoop.com\": 1,\n\t\"zjdh.org\": 1,\n\t\"zjebbs.com\": 1,\n\t\"zjedu.org\": 1,\n\t\"zjedu.tv\": 1,\n\t\"zjftu.org\": 1,\n\t\"zjg12345.com\": 1,\n\t\"zjgdrc.com\": 1,\n\t\"zjghfw.com\": 1,\n\t\"zjghot.com\": 1,\n\t\"zjgjj.com\": 1,\n\t\"zjgjj.net\": 1,\n\t\"zjgrrb.com\": 1,\n\t\"zjgsmwy.com\": 1,\n\t\"zjhep.com\": 1,\n\t\"zjhq.com\": 1,\n\t\"zjhr.com\": 1,\n\t\"zjhzart.com\": 1,\n\t\"zjic.com\": 1,\n\t\"zjincubator.com\": 1,\n\t\"zjinvest.net\": 1,\n\t\"zjits.com\": 1,\n\t\"zjj-hc.com\": 1,\n\t\"zjjcts.com\": 1,\n\t\"zjjcy.com\": 1,\n\t\"zjjhaodi.com\": 1,\n\t\"zjjk365.com\": 1,\n\t\"zjjrc.com\": 1,\n\t\"zjjta.com\": 1,\n\t\"zjjvip.com\": 1,\n\t\"zjjxs.com\": 1,\n\t\"zjjybkzs.com\": 1,\n\t\"zjjys.org\": 1,\n\t\"zjjyzx.com\": 1,\n\t\"zjjzzp.com\": 1,\n\t\"zjk169.net\": 1,\n\t\"zjketv.com\": 1,\n\t\"zjkgz.com\": 1,\n\t\"zjknews.com\": 1,\n\t\"zjkonline.com\": 1,\n\t\"zjkrbsnews.com\": 1,\n\t\"zjks.com\": 1,\n\t\"zjks.net\": 1,\n\t\"zjkwang.com\": 1,\n\t\"zjllw.com\": 1,\n\t\"zjlottery.com\": 1,\n\t\"zjlqw.com\": 1,\n\t\"zjlscourt.com\": 1,\n\t\"zjlsedu.org\": 1,\n\t\"zjmc.tv\": 1,\n\t\"zjmj.org\": 1,\n\t\"zjmoney.com\": 1,\n\t\"zjnhaf.com\": 1,\n\t\"zjningbo.com\": 1,\n\t\"zjnw.net\": 1,\n\t\"zjolcdn.com\": 1,\n\t\"zjpark.com\": 1,\n\t\"zjphis.com\": 1,\n\t\"zjphoto.org\": 1,\n\t\"zjpost.com\": 1,\n\t\"zjpse.com\": 1,\n\t\"zjpxzx.com\": 1,\n\t\"zjrail.com\": 1,\n\t\"zjrc.com\": 1,\n\t\"zjrxz.com\": 1,\n\t\"zjscdb.com\": 1,\n\t\"zjscedu.org\": 1,\n\t\"zjsmap.com\": 1,\n\t\"zjsr.com\": 1,\n\t\"zjstv.com\": 1,\n\t\"zjszrc.com\": 1,\n\t\"zjtcn.com\": 1,\n\t\"zjtree.com\": 1,\n\t\"zjtxrc.com\": 1,\n\t\"zjwater.com\": 1,\n\t\"zjwchc.com\": 1,\n\t\"zjwmw.com\": 1,\n\t\"zjwu.net\": 1,\n\t\"zjxf119.com\": 1,\n\t\"zjxjrc.com\": 1,\n\t\"zjxww.com\": 1,\n\t\"zjzcj.com\": 1,\n\t\"zjzj.net\": 1,\n\t\"zjzs.net\": 1,\n\t\"zk21.com\": 1,\n\t\"zk3158.com\": 1,\n\t\"zk71.com\": 1,\n\t\"zkcrm.com\": 1,\n\t\"zkjkgc.com\": 1,\n\t\"zkxww.com\": 1,\n\t\"zkzp.com\": 1,\n\t\"zkzsb.net\": 1,\n\t\"zlhome.com\": 1,\n\t\"zljob.net\": 1,\n\t\"zlmfcw.com\": 1,\n\t\"zlook.com\": 1,\n\t\"zlpumps.com\": 1,\n\t\"zls365.com\": 1,\n\t\"zlwq.com\": 1,\n\t\"zlzx.org\": 1,\n\t\"zmd5.com\": 1,\n\t\"zmdfcw.com\": 1,\n\t\"zmdfdc.com\": 1,\n\t\"zmdjzw.com\": 1,\n\t\"zmdzs.net\": 1,\n\t\"zmgov.com\": 1,\n\t\"zmnedu.com\": 1,\n\t\"zmyg.org\": 1,\n\t\"zmyjy.com\": 1,\n\t\"zmzhw.com\": 1,\n\t\"znds.com\": 1,\n\t\"znhr.com\": 1,\n\t\"znimg.com\": 1,\n\t\"znxkw.com\": 1,\n\t\"zocai.com\": 1,\n\t\"zoglo.net\": 1,\n\t\"zohi.tv\": 1,\n\t\"zol.com\": 1,\n\t\"zongheng.com\": 1,\n\t\"zonglai.com\": 1,\n\t\"zonglai.mobi\": 1,\n\t\"zongsifang.com\": 1,\n\t\"zongsifang.net\": 1,\n\t\"zoomeye.org\": 1,\n\t\"zoomlion.com\": 1,\n\t\"zoopda.com\": 1,\n\t\"zoosnet.net\": 1,\n\t\"zoossoft.com\": 1,\n\t\"zoossoft.net\": 1,\n\t\"zopomobile.com\": 1,\n\t\"zotye.com\": 1,\n\t\"zouquwan.com\": 1,\n\t\"zoutu.com\": 1,\n\t\"zp0370.com\": 1,\n\t\"zp0372.com\": 1,\n\t\"zp0517.com\": 1,\n\t\"zp365.com\": 1,\n\t\"zp512.com\": 1,\n\t\"zp515.com\": 1,\n\t\"zp597.com\": 1,\n\t\"zp666.com\": 1,\n\t\"zpb365.com\": 1,\n\t\"zpedu.org\": 1,\n\t\"zpfdc.com\": 1,\n\t\"zph-sh.com\": 1,\n\t\"zph58.com\": 1,\n\t\"zplm.com\": 1,\n\t\"zprc.com\": 1,\n\t\"zpxzzx.org\": 1,\n\t\"zpydt.com\": 1,\n\t\"zpzj.com\": 1,\n\t\"zpzpw.com\": 1,\n\t\"zq8.net\": 1,\n\t\"zq84.com\": 1,\n\t\"zqgame.com\": 1,\n\t\"zqgongyi.org\": 1,\n\t\"zqlqt.com\": 1,\n\t\"zqnksw.com\": 1,\n\t\"zqrsrc.com\": 1,\n\t\"zqzhibo.com\": 1,\n\t\"zr597.com\": 1,\n\t\"zr98.com\": 1,\n\t\"zrexam.com\": 1,\n\t\"zritn.com\": 1,\n\t\"zrtg.com\": 1,\n\t\"zs-coop.com\": 1,\n\t\"zs-hospital.com\": 1,\n\t\"zs-jyx.com\": 1,\n\t\"zs27.com\": 1,\n\t\"zs310.com\": 1,\n\t\"zsbicycle.com\": 1,\n\t\"zsbwg.com\": 1,\n\t\"zsby.com\": 1,\n\t\"zschinese.com\": 1,\n\t\"zsdinghai.com\": 1,\n\t\"zsdonggang.com\": 1,\n\t\"zsedu.net\": 1,\n\t\"zsemail.com\": 1,\n\t\"zsezt.com\": 1,\n\t\"zsfuer.org\": 1,\n\t\"zsfybjy.com\": 1,\n\t\"zsglj.com\": 1,\n\t\"zsguilai.com\": 1,\n\t\"zshl.com\": 1,\n\t\"zshouyou.com\": 1,\n\t\"zshyqx.com\": 1,\n\t\"zsi68.com\": 1,\n\t\"zsjjob.com\": 1,\n\t\"zskxg.com\": 1,\n\t\"zslib.net\": 1,\n\t\"zslz.com\": 1,\n\t\"zsmama.com\": 1,\n\t\"zsmls.com\": 1,\n\t\"zsnet.com\": 1,\n\t\"zsnets.com\": 1,\n\t\"zsnl.com\": 1,\n\t\"zspt-hospital.com\": 1,\n\t\"zsputuo.com\": 1,\n\t\"zsql.org\": 1,\n\t\"zsqx.com\": 1,\n\t\"zsrc.net\": 1,\n\t\"zsrd.net\": 1,\n\t\"zssalt.com\": 1,\n\t\"zsscoop.com\": 1,\n\t\"zssns.com\": 1,\n\t\"zssou.com\": 1,\n\t\"zst365.com\": 1,\n\t\"zstj.net\": 1,\n\t\"zsw-qd.com\": 1,\n\t\"zswcn.com\": 1,\n\t\"zswoman.net\": 1,\n\t\"zsxd.net\": 1,\n\t\"zsxnts.com\": 1,\n\t\"zsyfzy.net\": 1,\n\t\"zsysdiy.com\": 1,\n\t\"zsyxw.org\": 1,\n\t\"zszgh.com\": 1,\n\t\"zszk.com\": 1,\n\t\"zszxbj.net\": 1,\n\t\"zszxt.com\": 1,\n\t\"zt5.com\": 1,\n\t\"ztcadx.com\": 1,\n\t\"ztcrc.com\": 1,\n\t\"ztems.com\": 1,\n\t\"ztgame.com\": 1,\n\t\"ztsfc.com\": 1,\n\t\"ztsfc.net\": 1,\n\t\"ztsfcw.com\": 1,\n\t\"ztv-5.com\": 1,\n\t\"ztv-8.net\": 1,\n\t\"ztyxkj.com\": 1,\n\t\"ztzftc.com\": 1,\n\t\"zubunet.com\": 1,\n\t\"zuche.com\": 1,\n\t\"zuchecdn.com\": 1,\n\t\"zuciwang.com\": 1,\n\t\"zudemi.com\": 1,\n\t\"zudong.com\": 1,\n\t\"zufang.com\": 1,\n\t\"zufang8.com\": 1,\n\t\"zufangbao.com\": 1,\n\t\"zugame.com\": 1,\n\t\"zugou.com\": 1,\n\t\"zugou.org\": 1,\n\t\"zui74.com\": 1,\n\t\"zuifengyun.com\": 1,\n\t\"zuigexing.com\": 1,\n\t\"zuijh.net\": 1,\n\t\"zuitech.com\": 1,\n\t\"zuiyouxi.com\": 1,\n\t\"zujuan.com\": 1,\n\t\"zulinnet.com\": 1,\n\t\"zunjuehuangjia.com\": 1,\n\t\"zunlongweiyu.com\": 1,\n\t\"zunyiol.com\": 1,\n\t\"zunyiyizhuan.com\": 1,\n\t\"zuoanlong.com\": 1,\n\t\"zuoche.com\": 1,\n\t\"zuodia.com\": 1,\n\t\"zuojiang.com\": 1,\n\t\"zuojiawang.com\": 1,\n\t\"zuowen.com\": 1,\n\t\"zuowenren.com\": 1,\n\t\"zuoye88.com\": 1,\n\t\"zupuk.com\": 1,\n\t\"zupulu.com\": 1,\n\t\"zuulee.com\": 1,\n\t\"zuyaya.com\": 1,\n\t\"zuzhirenshi.com\": 1,\n\t\"zuzuche.com\": 1,\n\t\"zwbk.org\": 1,\n\t\"zwcad.com\": 1,\n\t\"zwhz.com\": 1,\n\t\"zwlwrc.com\": 1,\n\t\"zwye.com\": 1,\n\t\"zwzsh.net\": 1,\n\t\"zx110.org\": 1,\n\t\"zx163k.com\": 1,\n\t\"zx580.wang\": 1,\n\t\"zx915.com\": 1,\n\t\"zx98.com\": 1,\n\t\"zxdrying.com\": 1,\n\t\"zxdyw.com\": 1,\n\t\"zxhro.com\": 1,\n\t\"zxhsd.com\": 1,\n\t\"zxip.com\": 1,\n\t\"zxiu.com\": 1,\n\t\"zxiubbs.com\": 1,\n\t\"zxjsq.net\": 1,\n\t\"zxking.com\": 1,\n\t\"zxqss.com\": 1,\n\t\"zxrcw.com\": 1,\n\t\"zxtang.com\": 1,\n\t\"zxwh.com\": 1,\n\t\"zxwygzs.com\": 1,\n\t\"zxxk.com\": 1,\n\t\"zxxww.com\": 1,\n\t\"zxxxkj.com\": 1,\n\t\"zxzhijia.com\": 1,\n\t\"zy.com\": 1,\n\t\"zy12580.com\": 1,\n\t\"zy91.com\": 1,\n\t\"zyautoe.com\": 1,\n\t\"zybb.net\": 1,\n\t\"zybus.com\": 1,\n\t\"zycits.com\": 1,\n\t\"zycmmt.com\": 1,\n\t\"zyctd.com\": 1,\n\t\"zyflipin.com\": 1,\n\t\"zygk.com\": 1,\n\t\"zygyy.com\": 1,\n\t\"zyjgkj.com\": 1,\n\t\"zynews.com\": 1,\n\t\"zyoulun.com\": 1,\n\t\"zyptm.com\": 1,\n\t\"zyqczz.com\": 1,\n\t\"zyrc.net\": 1,\n\t\"zyscw.net\": 1,\n\t\"zyshr.com\": 1,\n\t\"zysj360.com\": 1,\n\t\"zytxs.com\": 1,\n\t\"zyue.com\": 1,\n\t\"zyuexc.com\": 1,\n\t\"zyxjz.com\": 1,\n\t\"zyxuan.com\": 1,\n\t\"zyxuan.org\": 1,\n\t\"zyzhan.com\": 1,\n\t\"zyzhaopin.com\": 1,\n\t\"zyzhjt.com\": 1,\n\t\"zz597.com\": 1,\n\t\"zz91.com\": 1,\n\t\"zzb58.com\": 1,\n\t\"zzbaike.com\": 1,\n\t\"zzbbs.com\": 1,\n\t\"zzbk.com\": 1,\n\t\"zzbm.org\": 1,\n\t\"zzbs.org\": 1,\n\t\"zzbtv.com\": 1,\n\t\"zzccjsj.com\": 1,\n\t\"zzccs.com\": 1,\n\t\"zzdjw.com\": 1,\n\t\"zzdxyc.com\": 1,\n\t\"zzeol.com\": 1,\n\t\"zzfcw.com\": 1,\n\t\"zzfxj.com\": 1,\n\t\"zzfzjob.com\": 1,\n\t\"zzgjj.com\": 1,\n\t\"zzhcz.com\": 1,\n\t\"zzhpkj.com\": 1,\n\t\"zzidc.com\": 1,\n\t\"zzielts.com\": 1,\n\t\"zzjidi.com\": 1,\n\t\"zzjob88.com\": 1,\n\t\"zzjol.com\": 1,\n\t\"zzjsjy.com\": 1,\n\t\"zzleju.com\": 1,\n\t\"zzloushi.com\": 1,\n\t\"zzmama.net\": 1,\n\t\"zzmnls.com\": 1,\n\t\"zzol360.com\": 1,\n\t\"zzpgm.com\": 1,\n\t\"zzqc.com\": 1,\n\t\"zzqcw.com\": 1,\n\t\"zzqiche.com\": 1,\n\t\"zzrc.net\": 1,\n\t\"zzrsks.com\": 1,\n\t\"zzsfybjy.com\": 1,\n\t\"zzsgjj.com\": 1,\n\t\"zzsglj.com\": 1,\n\t\"zzshl.com\": 1,\n\t\"zzsr.com\": 1,\n\t\"zzstep.com\": 1,\n\t\"zzta.com\": 1,\n\t\"zztengda.com\": 1,\n\t\"zztlj.com\": 1,\n\t\"zztv.tv\": 1,\n\t\"zzwljc.com\": 1,\n\t\"zzxmjx.com\": 1,\n\t\"zzxsjswkj.com\": 1,\n\t\"zzyjs.com\": 1,\n\t\"zzyycc.com\": 1,\n\t\"zzyyss.com\": 1,\n\t\"zzz4.com\": 1,\n\t\"zzzj.com\": 1,\n\t\"zzzlll.com\": 1\n};\n\nvar wall_proxy = \"PROXY 127.0.0.1:8081;\";\nvar nowall_proxy = \"DIRECT;\";\n\nvar direct = \"DIRECT;\";\n\nvar hasOwnProperty = Object.hasOwnProperty;\n\nfunction check_ipv4(host) {\n\t// check if the ipv4 format (TODO: ipv6)\n\t// http://home.deds.nl/~aeron/regex/\n\tvar re_ipv4 = /^\\d+\\.\\d+\\.\\d+\\.\\d+$/g;\n\tif (re_ipv4.test(host)) {\n\t\t// in theory, we can add chnroutes test here.\n\t\t// but that is probably too much an overkill.\n\t\treturn true;\n\t}\n}\n\nfunction FindProxyForURL(url, host) {\n\tif ( isPlainHostName(host) === true ) {\n\t\treturn direct;\n\t}\n\tif ( check_ipv4(host) === true ) {\n\t\treturn nowall_proxy;\n\t}\n\tvar suffix;\n\tvar pos1 = host.lastIndexOf('.');\n\tvar pos = host.lastIndexOf('.', pos1 - 1);\n\n\tsuffix = host.substring(pos1 + 1);\n\tif (suffix == \"cn\") {\n\t\treturn nowall_proxy;\n\t}\n\n\twhile(1) {\n\t\tif (pos == -1) {\n\t\t\tif (hasOwnProperty.call(domains, host)) {\n\t\t\t\treturn nowall_proxy;\n\t\t\t} else {\n\t\t\t\treturn wall_proxy;\n\t\t\t}\n\t\t}\n\t\tsuffix = host.substring(pos + 1);\n\t\tif (hasOwnProperty.call(domains, suffix)) {\n\t\t\treturn nowall_proxy;\n\t\t}\n\t\tpos = host.lastIndexOf('.', pos - 1);\n\t}\n}\n\n" } ]
5
gipsa-lab-uav/trajectory_control
https://github.com/gipsa-lab-uav/trajectory_control
2c233565b7970ce4001de6093054208d67afbd4a
3456464190b02a9cb08c69ba81b3f7759fcb0c93
8ba490cf7ee3324c67f07ddbb72b421591d6eeda
refs/heads/master
2021-07-07T22:48:16.670746
2020-01-14T10:40:46
2020-01-14T10:40:46
214,182,191
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6561670899391174, "alphanum_fraction": 0.6707559823989868, "avg_line_length": 19.37837791442871, "blob_id": "723e4727441a31b777e4057891157d005d8a4d2c", "content_id": "9694c357e31f6cd5810a7d086a329bdbf1fe69ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3016, "license_type": "permissive", "max_line_length": 153, "num_lines": 148, "path": "/src/trajectory_control/DroneStates.cpp", "repo_name": "gipsa-lab-uav/trajectory_control", "src_encoding": "UTF-8", "text": "#include \"trajectory_control/DroneStates.hpp\"\n\nDS1D::DS1D()\n{\n\tposition = 0.0f;\n\tspeed = 0.0f;\n\tacceleration = 0.0f;\n\tuncertainties = 0.0f;\n}\nDS1D::DS1D(float pos, float speedC, float acc, float unc)\n{\n\tposition = pos;\n\tspeed = speedC;\n\tacceleration = acc;\n\tuncertainties = unc;\n}\nDS1D::DS1D(const DS1D& otherState)\n{\n\tposition = otherState.position;\n\tspeed = otherState.speed;\n\tacceleration = otherState.acceleration;\n\tuncertainties = otherState.uncertainties;\n}\nDS1D::~DS1D(){}\n\nDroneStates::DroneStates()\n{\n\theading = 0.0f;\n}\nDroneStates::DroneStates(DS1D xNew, DS1D yNew, DS1D zNew)\n{\n\tx = xNew;\n\ty = yNew;\n\tz = zNew;\n\theading = 0.0f;\n}\nDroneStates::~DroneStates(){}\n\nvoid DroneStates::replacePos(geometry_msgs::Vector3 position)\n{\n x.position = position.x;\n y.position = position.y;\n z.position = position.z;\n}\n\nvoid DroneStates::replacePosAndSpeed(geometry_msgs::Vector3 position, geometry_msgs::Vector3 speed)\n{\n x.position = position.x;\n y.position = position.y;\n z.position = position.z;\n\n x.speed = speed.x;\n y.speed = speed.y;\n z.speed = speed.z;\n}\n\nvoid DroneStates::replaceSpeed(geometry_msgs::Vector3 speed)\n{\n\tx.speed = speed.x;\n\ty.speed = speed.y;\n\tz.speed = speed.z;\n}\n\nvoid DroneStates::replaceAcc(geometry_msgs::Vector3 acceleration)\n{\n\tx.acceleration = acceleration.x;\n\ty.acceleration = acceleration.y;\n\tz.acceleration = acceleration.z;\n}\n\nvoid DroneStates::replaceHeading(float newHeading)\n{\n\theading = newHeading;\n}\n\ngeometry_msgs::Vector3 DroneStates::getVectPos()\n{\n geometry_msgs::Vector3 r;\n\n r.x = x.position;\n r.y = y.position;\n r.z = z.position;\n\n return r;\n}\n\ngeometry_msgs::Vector3 DroneStates::getVectSpeed()\n{\n geometry_msgs::Vector3 r;\n\n r.x = x.speed;\n r.y = y.speed;\n r.z = z.speed;\n\n return r;\n}\n\ngeometry_msgs::Vector3 DroneStates::getVectAcceleration()\n{\n geometry_msgs::Vector3 r;\n\n r.x = x.acceleration;\n r.y = y.acceleration;\n r.z = z.acceleration;\n\n return r;\n}\n\ngeometry_msgs::Vector3 DroneStates::getVectUncertainties()\n{\n geometry_msgs::Vector3 r;\n\n r.x = x.uncertainties;\n r.y = y.uncertainties;\n r.z = z.uncertainties;\n\n return r;\n}\n\n\nvoid DroneStates::fillStates (geometry_msgs::Vector3 pos, geometry_msgs::Vector3 speed, geometry_msgs::Vector3 acc)\n{\n x.position = pos.x;\n x.speed = speed.x;\n x.acceleration = acc.x;\n y.position = pos.y;\n y.speed = speed.y;\n y.acceleration = acc.y;\n z.position = pos.z;\n z.speed = speed.z;\n z.acceleration = acc.z;\n}\n\nvoid DroneStates::fillStates (geometry_msgs::Vector3 pos, geometry_msgs::Vector3 speed, geometry_msgs::Vector3 acc, geometry_msgs::Vector3 uncertainties)\n{\n x.position = pos.x;\n x.speed = speed.x;\n x.acceleration = acc.x;\n x.uncertainties = uncertainties.x;\n y.position = pos.y;\n y.speed = speed.y;\n y.acceleration = acc.y;\n y.uncertainties = uncertainties.y;\n z.position = pos.z;\n z.speed = speed.z;\n z.acceleration = acc.z;\n z.uncertainties = uncertainties.z;\n}\n" }, { "alpha_fraction": 0.7916666865348816, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 5, "blob_id": "b238f1dfaca3d9317ec555595287df0df4c6ff5c", "content_id": "fe662a63fa5b7ebd8da5e387f79652e9278aac44", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 24, "license_type": "permissive", "max_line_length": 6, "num_lines": 4, "path": "/requirements.txt", "repo_name": "gipsa-lab-uav/trajectory_control", "src_encoding": "UTF-8", "text": "numpy\nscipy\ntoml\njinja2\n" }, { "alpha_fraction": 0.5888268351554871, "alphanum_fraction": 0.6075977683067322, "avg_line_length": 50.24045944213867, "blob_id": "3cdbb49a95d2f3a7b668e0dc9feca5fcb91d8108", "content_id": "5d562a83c691c78ae07b8550d43916923845de61", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26850, "license_type": "permissive", "max_line_length": 209, "num_lines": 524, "path": "/scripts/trajectory_gen.py", "repo_name": "gipsa-lab-uav/trajectory_control", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n\nimport math\nimport numpy as np\nfrom scipy import signal\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom timeit import default_timer as time\n\nimport rospy\nfrom std_msgs.msg import Header\nfrom trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint\nfrom nav_msgs.msg import Odometry\n\n\nclass TrajectoryGeneration:\n def __init__(self, node_name='trajectory_gen_node', subscriber='mavros/local_position/odom', publisher='mavros/JointTrajectory'):\n\n rospy.init_node(node_name, anonymous=True)\n\n # Define suscribers & publishers\n rospy.Subscriber(subscriber, Odometry, self.callback)\n self.pub = rospy.Publisher(publisher, JointTrajectory, queue_size=10)\n\n self.YAW_HEADING = ['auto', [1, 0]] # auto, center, axes\n self.TRAJECTORY_REQUESTED_SPEED = 0.4 # max. linear speed [m.s-1]\n self.PUBLISH_RATE = 10 # publisher frequency [Hz]\n self.FREQUENCY = 10 # point trajectory frequency [Hz]\n self.BOX_LIMIT = [[-4., 4.], [-4., 4.], [-.01, 6.]] # [[x_min, x_max], [y_min, y_max], [z_min, z_max]]\n self.WINDOW_FRAME = .5 # publish future states comprise in the window time frame [s]\n self.EXTRA_POINTS_START = 13\n self.EXTRA_POINTS_END = 13\n\n self.MAX_LINEAR_SPEED_XY = 0.6 # max. linear speed [m.s-1]\n self.MAX_LINEAR_SPEED_Z = 0.6 # max. linear speed [m.s-1]\n self.MAX_LINEAR_ACC_XY = 1.5 # max. linear acceleration [m.s-2]\n self.MAX_LINEAR_ACC_Z = 2.0 # max. linear acceleration [m.s-2]\n\n self.is_first_callback = False\n\n self.x_discretized = [.0] * self.EXTRA_POINTS_START\n self.y_discretized = [.0] * self.EXTRA_POINTS_START\n self.z_discretized = [.0] * self.EXTRA_POINTS_START\n\n def discretise_trajectory(self, parameters=[]):\n\n start = time()\n\n x1 = self.x_discretized[-1]\n y1 = self.y_discretized[-1]\n z1 = self.z_discretized[-1]\n\n delta_l = self.TRAJECTORY_REQUESTED_SPEED / self.FREQUENCY\n\n if parameters[0] == 'vector':\n\n steps = self.norm(parameters[1], [x1, y1, z1]) / delta_l\n\n x = np.linspace(x1, parameters[1][0], steps, endpoint=True)\n y = np.linspace(y1, parameters[1][1], steps, endpoint=True)\n z = np.linspace(z1, parameters[1][2], steps, endpoint=True)\n\n elif parameters[0] == 'circle':\n center = parameters[1]\n radius = self.norm(center, [x1, y1, z1])\n steps = int(2 * math.pi * radius / delta_l)\n\n cos_a = (x1 - center[0]) / radius\n sin_a = (y1 - center[1]) / radius\n\n cos_b = lambda x: math.cos((2 * math.pi / steps) * x)\n sin_b = lambda x: math.sin((2 * math.pi / steps) * x)\n\n x = [((cos_a*cos_b(s) - sin_a*sin_b(s))*radius + center[0]) for s in range(0, steps+1)]\n y = [((sin_a*cos_b(s) + cos_a*sin_b(s))*radius + center[1]) for s in range(0, steps+1)]\n z = [(center[2]) for s in range(0, steps+1)]\n\n elif parameters[0] == 'hover':\n steps = int(parameters[1] * self.FREQUENCY)\n\n x = x1 * np.ones(steps)\n y = y1 * np.ones(steps)\n z = z1 * np.ones(steps)\n\n elif parameters[0] == 'takeoff':\n\n steps = int(abs(parameters[1] - z1) / delta_l)\n\n x = x1 * np.ones(steps)\n y = y1 * np.ones(steps)\n z = np.linspace(z1, parameters[1], steps, endpoint=True)\n\n elif parameters[0] == 'landing':\n\n steps = int(abs(z1) / delta_l)\n\n x = x1 * np.ones(steps)\n y = y1 * np.ones(steps)\n z = np.linspace(z1, -.01, steps, endpoint=True)\n\n # elif parameters[0] == 'return2home':\n # elif parameters[0] == 'square':\n # elif parameters[0] == 'inf':\n\n self.x_discretized.extend(x[1:])\n self.y_discretized.extend(y[1:])\n self.z_discretized.extend(z[1:])\n\n print('discretise_trajectory() runs in {} s'.format(time() - start))\n\n def constraint_trajectory_to_box(self):\n self.x_discretized = [self.BOX_LIMIT[0][0] if x < self.BOX_LIMIT[0][0] else x for x in self.x_discretized]\n self.x_discretized = [self.BOX_LIMIT[0][1] if x > self.BOX_LIMIT[0][1] else x for x in self.x_discretized]\n self.y_discretized = [self.BOX_LIMIT[1][0] if x < self.BOX_LIMIT[1][0] else x for x in self.y_discretized]\n self.y_discretized = [self.BOX_LIMIT[1][1] if x > self.BOX_LIMIT[1][1] else x for x in self.y_discretized]\n self.z_discretized = [self.BOX_LIMIT[2][0] if x < self.BOX_LIMIT[2][0] else x for x in self.z_discretized]\n self.z_discretized = [self.BOX_LIMIT[2][1] if x > self.BOX_LIMIT[2][1] else x for x in self.z_discretized]\n\n def generate_states(self):\n\n start = time()\n\n self.x_discretized.extend([self.x_discretized[-1]] * self.EXTRA_POINTS_END)\n self.y_discretized.extend([self.y_discretized[-1]] * self.EXTRA_POINTS_END)\n self.z_discretized.extend([self.z_discretized[-1]] * self.EXTRA_POINTS_END)\n\n self.ya_discretized = [.0]\n self.vx_discretized = [.0]\n self.vy_discretized = [.0]\n self.vz_discretized = [.0]\n self.ax_discretized = [.0]\n self.ay_discretized = [.0]\n self.az_discretized = [.0]\n self.ti_discretized = [.0]\n\n prevHeading = np.array([.0, .0])\n\n for s, _ in enumerate(self.x_discretized[1:]):\n p1 = np.array([self.x_discretized[s], self.y_discretized[s]])\n p2 = np.array([self.x_discretized[s+1], self.y_discretized[s+1]])\n\n if self.YAW_HEADING[0] == 'center':\n heading = np.array(self.YAW_HEADING[1]) - p1\n elif self.YAW_HEADING[0] == 'axes':\n heading = np.array(self.YAW_HEADING[1])\n else:\n heading = p2 - p1\n\n heading = (heading / self.norm2(heading)) if self.norm2(heading) != 0 else prevHeading\n prevHeading = heading\n\n self.ya_discretized.append(math.atan2(heading[1], heading[0]))\n self.vx_discretized.append((self.x_discretized[s+1] - self.x_discretized[s]) * self.FREQUENCY)\n self.vy_discretized.append((self.y_discretized[s+1] - self.y_discretized[s]) * self.FREQUENCY)\n self.vz_discretized.append((self.z_discretized[s+1] - self.z_discretized[s]) * self.FREQUENCY)\n self.ax_discretized.append((self.vx_discretized[-1] - self.vx_discretized[-2]) * self.FREQUENCY)\n self.ay_discretized.append((self.vy_discretized[-1] - self.vy_discretized[-2]) * self.FREQUENCY)\n self.az_discretized.append((self.vz_discretized[-1] - self.vz_discretized[-2]) * self.FREQUENCY)\n self.ti_discretized.append((s + 1.) / self.FREQUENCY)\n\n print('generate_states() runs in {} s'.format(time() - start))\n\n def generate_states_filtered(self):\n\n start = time()\n\n self.x_filtered = [self.x_discretized[0]]\n self.y_filtered = [self.y_discretized[0]]\n self.z_filtered = [self.z_discretized[0]]\n\n self.vx_filtered = [.0]\n self.vy_filtered = [.0]\n self.vz_filtered = [.0]\n\n self.ax_filtered = [.0]\n self.ay_filtered = [.0]\n self.az_filtered = [.0]\n\n for s, _ in enumerate(self.vx_discretized[1:]):\n self.ax_filtered.append(self.saturate((self.vx_discretized[s+1] - self.vx_filtered[-1]) * self.FREQUENCY, self.MAX_LINEAR_ACC_XY))\n self.ay_filtered.append(self.saturate((self.vy_discretized[s+1] - self.vy_filtered[-1]) * self.FREQUENCY, self.MAX_LINEAR_ACC_XY))\n self.az_filtered.append(self.saturate((self.vz_discretized[s+1] - self.vz_filtered[-1]) * self.FREQUENCY, self.MAX_LINEAR_ACC_Z))\n\n self.vx_filtered.append(self.saturate(self.vx_filtered[-1] + (self.ax_filtered[-1] / self.FREQUENCY), self.MAX_LINEAR_SPEED_XY))\n self.vy_filtered.append(self.saturate(self.vy_filtered[-1] + (self.ay_filtered[-1] / self.FREQUENCY), self.MAX_LINEAR_SPEED_XY))\n self.vz_filtered.append(self.saturate(self.vz_filtered[-1] + (self.az_filtered[-1] / self.FREQUENCY), self.MAX_LINEAR_SPEED_Z))\n\n self.x_filtered.append(self.x_filtered[-1] + (self.vx_filtered[-1] / self.FREQUENCY))\n self.y_filtered.append(self.y_filtered[-1] + (self.vy_filtered[-1] / self.FREQUENCY))\n self.z_filtered.append(self.z_filtered[-1] + (self.vz_filtered[-1] / self.FREQUENCY))\n\n print('generate_states_filtered() runs in {} s'.format(time() - start))\n\n def generate_states_sg_filtered(self, window_length=51, polyorder=3, deriv=0, delta=1.0, mode='mirror', on_filtered=False):\n # Info: Apply Savitzky-Golay filter to velocities\n\n start = time()\n\n self.x_filtered = [self.x_discretized[0]]\n self.y_filtered = [self.y_discretized[0]]\n self.z_filtered = [self.z_discretized[0]]\n\n if on_filtered:\n self.vx_filtered = signal.savgol_filter(x=self.vx_filtered, window_length=window_length, polyorder=polyorder, deriv=deriv, delta=delta, mode=mode)\n self.vy_filtered = signal.savgol_filter(x=self.vy_filtered, window_length=window_length, polyorder=polyorder, deriv=deriv, delta=delta, mode=mode)\n self.vz_filtered = signal.savgol_filter(x=self.vz_filtered, window_length=window_length, polyorder=polyorder, deriv=deriv, delta=delta, mode=mode)\n else:\n self.vx_filtered = signal.savgol_filter(x=self.vx_discretized, window_length=window_length, polyorder=polyorder, deriv=deriv, delta=delta, mode=mode)\n self.vy_filtered = signal.savgol_filter(x=self.vy_discretized, window_length=window_length, polyorder=polyorder, deriv=deriv, delta=delta, mode=mode)\n self.vz_filtered = signal.savgol_filter(x=self.vz_discretized, window_length=window_length, polyorder=polyorder, deriv=deriv, delta=delta, mode=mode)\n\n self.ax_filtered = [.0]\n self.ay_filtered = [.0]\n self.az_filtered = [.0]\n\n for s, _ in enumerate(self.vx_filtered[1:]):\n self.ax_filtered.append(self.saturate((self.vx_filtered[s+1] - self.vx_filtered[s]) * self.FREQUENCY, self.MAX_LINEAR_ACC_XY))\n self.ay_filtered.append(self.saturate((self.vy_filtered[s+1] - self.vy_filtered[s]) * self.FREQUENCY, self.MAX_LINEAR_ACC_XY))\n self.az_filtered.append(self.saturate((self.vz_filtered[s+1] - self.vz_filtered[s]) * self.FREQUENCY, self.MAX_LINEAR_ACC_Z))\n\n self.vx_filtered[s+1] = self.vx_filtered[s] + (self.ax_filtered[-1] / self.FREQUENCY)\n self.vy_filtered[s+1] = self.vy_filtered[s] + (self.ay_filtered[-1] / self.FREQUENCY)\n self.vz_filtered[s+1] = self.vz_filtered[s] + (self.az_filtered[-1] / self.FREQUENCY)\n\n self.x_filtered.append(self.x_filtered[-1] + (self.vx_filtered[s+1] / self.FREQUENCY))\n self.y_filtered.append(self.y_filtered[-1] + (self.vy_filtered[s+1] / self.FREQUENCY))\n self.z_filtered.append(self.z_filtered[-1] + (self.vz_filtered[s+1] / self.FREQUENCY))\n\n print('generate_states_sg_filtered() runs in {} s'.format(time() - start))\n\n def generate_yaw_filtered(self):\n\n if not hasattr(self, 'x_filtered'): return\n\n start = time()\n\n self.ya_filtered = []\n\n prevHeading = np.array([.0, .0, .0])\n\n for s, _ in enumerate(self.vx_filtered[1:]):\n p1 = np.array([self.x_filtered[s], self.y_filtered[s]])\n p2 = np.array([self.x_filtered[s+1], self.y_filtered[s+1]])\n\n if self.YAW_HEADING[0] == 'center':\n heading = np.array(self.YAW_HEADING[1]) - p1\n elif self.YAW_HEADING[0] == 'axes':\n heading = np.array(self.YAW_HEADING[1])\n else:\n heading = p2 - p1\n\n heading = (heading / self.norm2(heading)) if self.norm2(heading) != 0 else prevHeading\n prevHeading = heading\n\n self.ya_filtered.append(math.atan2(heading[1], heading[0]))\n\n self.ya_filtered.append(self.ya_filtered[-1])\n\n print('generate_yaw_filtered() runs in {} s'.format(time() - start))\n\n def plot_trajectory_extras(self):\n\n start = time()\n\n n = 3 # Plot velocity and heading every n points to get a clearer graph\n alpha = .3 # Transparancy for velocity and heading arrows\n\n fig = plt.figure(figsize=(16, 8))\n\n ax1 = fig.add_subplot(121, projection='3d')\n ax1.scatter(self.x_discretized, self.y_discretized, self.z_discretized, label='trajectory_desired', color='blue')\n if hasattr(self, 'x_filtered'):\n ax1.scatter(self.x_filtered, self.y_filtered, self.z_filtered, label='trajectory_filtered', color='red')\n ax1.quiver(\n self.x_filtered[0::n], self.y_filtered[0::n], self.z_filtered[0::n],\n self.vx_filtered[0::n], self.vy_filtered[0::n], self.vz_filtered[0::n],\n length=.05, color='red', alpha=alpha, label='velocity_filtered')\n if hasattr(self, 'ya_filtered'):\n ax1.quiver(\n self.x_filtered[0::n], self.y_filtered[0::n], self.z_filtered[0::n],\n [math.cos(a) for a in self.ya_filtered[0::n]], [math.sin(a) for a in self.ya_filtered[0::n]], [.0 for a in self.ya_filtered[0::n]],\n length=.3, color='green', alpha=alpha, label='heading_filtered')\n else:\n ax1.quiver(\n self.x_filtered[0::n], self.y_filtered[0::n], self.z_filtered[0::n],\n [math.cos(a) for a in self.ya_discretized[0::n]], [math.sin(a) for a in self.ya_discretized[0::n]], [.0 for a in self.ya_discretized[0::n]],\n length=.3, color='green', alpha=alpha, label='heading_discretized')\n else:\n ax1.quiver(\n self.x_discretized[0::n], self.y_discretized[0::n], self.z_discretized[0::n],\n self.vx_discretized[0::n], self.vy_discretized[0::n], self.vz_discretized[0::n],\n length=.05, color='red', alpha=alpha, label='velocity')\n ax1.quiver(\n self.x_discretized[0::n], self.y_discretized[0::n], self.z_discretized[0::n],\n [math.cos(a) for a in self.ya_discretized[0::n]], [math.sin(a) for a in self.ya_discretized[0::n]], [.0 for a in self.ya_discretized[0::n]],\n length=.3, color='green', alpha=alpha, label='heading')\n plt.legend()\n plt.title('Trajectory')\n\n ax2 = fig.add_subplot(322)\n ax2.plot(self.vx_discretized, color='red', label='vx_desired')\n ax2.plot(self.vy_discretized, color='green', label='vy_desired')\n ax2.plot(self.vz_discretized, color='blue', label='vz_desired')\n if hasattr(self, 'vx_filtered'): ax2.plot(self.vx_filtered, color='red', label='vx_filtered', linestyle='--')\n if hasattr(self, 'vy_filtered'): ax2.plot(self.vy_filtered, color='green', label='vy_filtered', linestyle='--')\n if hasattr(self, 'vz_filtered'): ax2.plot(self.vz_filtered, color='blue', label='vz_filtered', linestyle='--')\n plt.legend()\n plt.title('Velocity')\n\n ax3 = fig.add_subplot(324)\n ax3.plot(self.ax_discretized, color='red', label='ax_desired')\n ax3.plot(self.ay_discretized, color='green', label='ay_desired')\n ax3.plot(self.az_discretized, color='blue', label='az_desired')\n if hasattr(self, 'ax_filtered'): ax3.plot(self.ax_filtered, color='red', label='ax_filtered', linestyle='--')\n if hasattr(self, 'ay_filtered'): ax3.plot(self.ay_filtered, color='green', label='ay_filtered', linestyle='--')\n if hasattr(self, 'az_filtered'): ax3.plot(self.az_filtered, color='blue', label='az_filtered', linestyle='--')\n ax3.set_ylim([-max(self.MAX_LINEAR_ACC_XY, self.MAX_LINEAR_ACC_Z), max(self.MAX_LINEAR_ACC_XY, self.MAX_LINEAR_ACC_Z)])\n plt.legend()\n plt.title('Acceleration')\n\n ax4 = fig.add_subplot(326)\n ax4.plot(self.ya_discretized, color='red', label='ya_desired')\n if hasattr(self, 'ya_filtered'): ax4.plot(self.ya_filtered, color='red', label='ya_filtered', linestyle='--')\n plt.legend()\n plt.title('Yaw')\n\n print('plot_trajectory_extras_filtered() runs in {} s'.format(time() - start))\n\n fig.tight_layout()\n plt.show()\n\n def start(self):\n\n rate = rospy.Rate(self.PUBLISH_RATE)\n\n s = 0\n string_id = str(rospy.get_rostime().nsecs)\n\n x = self.x_filtered if hasattr(self, 'x_filtered') else self.x_discretized\n y = self.y_filtered if hasattr(self, 'y_filtered') else self.y_discretized\n z = self.z_filtered if hasattr(self, 'z_filtered') else self.z_discretized\n ya = self.ya_filtered if hasattr(self, 'ya_filtered') else self.ya_discretized\n vx = self.vx_filtered if hasattr(self, 'vx_filtered') else self.vx_discretized\n vy = self.vy_filtered if hasattr(self, 'vy_filtered') else self.vy_discretized\n vz = self.vz_filtered if hasattr(self, 'vz_filtered') else self.vz_discretized\n ax = self.ax_filtered if hasattr(self, 'ax_filtered') else self.ax_discretized\n ay = self.ay_filtered if hasattr(self, 'ay_filtered') else self.ay_discretized\n az = self.az_filtered if hasattr(self, 'az_filtered') else self.az_discretized\n\n while not (rospy.is_shutdown() or s >= len(self.x_discretized)):\n\n # Build JointTrajectory message\n header = Header()\n header.seq = s\n header.stamp = rospy.get_rostime()\n header.frame_id = string_id\n\n joint_trajectory_msg = JointTrajectory()\n joint_trajectory_msg.header = header\n joint_trajectory_msg.joint_names = ['t', 't1']\n\n # Build JointTrajectoryPoint\n for i in range(min(self.WINDOW_FRAME, len(self.x_discretized) - s)):\n joint_trajectory_point = JointTrajectoryPoint()\n joint_trajectory_point.positions = [x[s+i], y[s+i], z[s+i], ya[s+i]]\n joint_trajectory_point.velocities = [vx[s+i], vy[s+i], vz[s+i]] # if i != (self.WINDOW_FRAME - 1) else [.0, .0, .0]\n joint_trajectory_point.accelerations = [ax[s+i], ay[s+i], az[s+i]] # if i != (self.WINDOW_FRAME - 1) else [.0, .0, .0]\n joint_trajectory_point.effort = []\n joint_trajectory_point.time_from_start = rospy.Duration.from_sec(self.ti_discretized[s+i])\n\n joint_trajectory_msg.points.append(joint_trajectory_point)\n\n s = s + int(self.FREQUENCY/self.PUBLISH_RATE)\n\n rospy.loginfo('##########################################')\n rospy.loginfo(joint_trajectory_msg)\n self.pub.publish(joint_trajectory_msg)\n rate.sleep()\n\n def norm(self, p1, p2=[.0, .0, .0]):\n return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2 + (p2[2] - p1[2]) ** 2)\n\n def norm2(self, p1, p2=[.0, .0]):\n return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)\n\n def saturate(self, x, y):\n return math.copysign(min(x, y, key=abs), x)\n\n def callback(self, odom):\n if not self.is_first_callback:\n\n position = odom.pose.pose.position\n\n self.x_discretized = [position.x] * self.EXTRA_POINTS_START\n self.y_discretized = [position.y] * self.EXTRA_POINTS_START\n self.z_discretized = [position.z] * self.EXTRA_POINTS_START\n\n self.is_first_callback = True\n\n def check_callback(self):\n rospy.loginfo(\"Waiting for position measurement callback ...\")\n while not (rospy.is_shutdown() or self.is_first_callback):\n pass\n rospy.loginfo(\"Position measurement callback ok.\")\n\n\nif __name__ == '__main__':\n\n node_name = 'trajectory_gen_node'\n subscriber = 'mavros/local_position/odom'\n publisher = 'mavros/JointTrajectory'\n\n try:\n trajectory_object = TrajectoryGeneration(node_name=node_name, subscriber=subscriber, publisher=publisher)\n\n # Wait for the first measurement callback to initialize the starting position of the trajectory\n trajectory_object.check_callback()\n\n ########################################################################\n # Configuration\n trajectory_object.YAW_HEADING = ['auto', [1, 0]] # auto, center, axes\n\n trajectory_object.TRAJECTORY_REQUESTED_SPEED = 0.6 # [m.s-1] to compute the step to discretized trajectory\n\n trajectory_object.MAX_LINEAR_ACC_XY = 1.5 # max. linear acceleration [m.s-2]\n trajectory_object.MAX_LINEAR_ACC_Z = 2.0 # max. linear acceleration [m.s-2]\n\n trajectory_object.PUBLISH_RATE = 10 # publisher frequency\n trajectory_object.FREQUENCY = 10 # [Hz]\n trajectory_object.BOX_LIMIT = [[-4., 4.], [-4., 4.], [-.01, 6.]] # [[x_min, x_max], [y_min, y_max], [z_min, z_max]]\n trajectory_object.WINDOW_FRAME = 5 # publish the n future states\n ########################################################################\n\n ########################################################################\n # Trajectory definition - shape/vertices in inertial frame (x, y, z - up)\n #\n # Define trajectory by using:\n # trajectory_object.discretise_trajectory(parameters=['name', param])\n #\n # Possible parameters:\n # parameters=['takeoff', z] with z in meters\n # parameters=['hover', time] with time in seconds\n # parameters=['vector', [x, y, z]] with x, y, z the target position\n # parameters=['circle', [x, y, z]] with x, y, z the center of the circle. Circle defined by the drone position when starting the circle trajectory and the center. The drone will turn around this point.\n # parameters=['landing']\n\n # Takeoff trajectory example:\n # trajectory_object.discretise_trajectory(parameters=['takeoff', 1.])\n # trajectory_object.discretise_trajectory(parameters=['hover', 30.])\n # trajectory_object.discretise_trajectory(parameters=['landing'])\n\n # Square trajectory example:\n # trajectory_object.discretise_trajectory(parameters=['takeoff', 1.])\n # trajectory_object.discretise_trajectory(parameters=['hover', 3.])\n # trajectory_object.discretise_trajectory(parameters=['vector', [1., -.5, 1.]])\n # trajectory_object.discretise_trajectory(parameters=['hover', 2.])\n # trajectory_object.discretise_trajectory(parameters=['vector', [1., 1.5, 1.]])\n # trajectory_object.discretise_trajectory(parameters=['hover', 2.])\n # trajectory_object.discretise_trajectory(parameters=['vector', [-1., 1.5, 1.]])\n # trajectory_object.discretise_trajectory(parameters=['hover', 2.])\n # trajectory_object.discretise_trajectory(parameters=['vector', [-1., -.5, 1.]])\n # trajectory_object.discretise_trajectory(parameters=['hover', 2.])\n # trajectory_object.discretise_trajectory(parameters=['vector', [1., -.5, 1.]])\n # trajectory_object.discretise_trajectory(parameters=['hover', 2.])\n # trajectory_object.discretise_trajectory(parameters=['vector', [0., -.5, 1.]])\n # trajectory_object.discretise_trajectory(parameters=['hover', 3.])\n # trajectory_object.discretise_trajectory(parameters=['landing'])\n\n # Circle trajectory example:\n # trajectory_object.discretise_trajectory(parameters=['takeoff', 1.])\n # trajectory_object.discretise_trajectory(parameters=['hover', 5.])\n # trajectory_object.discretise_trajectory(parameters=['vector', [0., -.5, 1.]])\n # trajectory_object.discretise_trajectory(parameters=['hover', 5.])\n # trajectory_object.discretise_trajectory(parameters=['circle', [.0, .5, 1.]])\n # trajectory_object.discretise_trajectory(parameters=['circle', [.0, .5, 1.]])\n # trajectory_object.discretise_trajectory(parameters=['hover', 5.])\n # trajectory_object.discretise_trajectory(parameters=['landing'])\n\n # More complex trajectory example:\n trajectory_object.discretise_trajectory(parameters=['takeoff', 2.])\n trajectory_object.discretise_trajectory(parameters=['hover', 2.])\n trajectory_object.discretise_trajectory(parameters=['circle', [.0, 2., 2.]])\n trajectory_object.discretise_trajectory(parameters=['hover', 2.])\n trajectory_object.discretise_trajectory(parameters=['vector', [1., 2., 3.]])\n trajectory_object.discretise_trajectory(parameters=['hover', 2.])\n trajectory_object.discretise_trajectory(parameters=['circle', [.0, 1., 3.]])\n trajectory_object.discretise_trajectory(parameters=['hover', 2.])\n trajectory_object.discretise_trajectory(parameters=['vector', [.0, -.5, 3.]])\n trajectory_object.discretise_trajectory(parameters=['hover', 2.])\n trajectory_object.discretise_trajectory(parameters=['landing'])\n\n # HCERES demonstration trajectory (january 2020):\n # trajectory_object.discretise_trajectory(parameters=['takeoff', 1.0])\n # trajectory_object.discretise_trajectory(parameters=['hover', 5.])\n # trajectory_object.discretise_trajectory(parameters=['vector', [1., -0.8, 1.]])\n # trajectory_object.discretise_trajectory(parameters=['hover', 3.])\n # trajectory_object.discretise_trajectory(parameters=['vector', [1., 0.7, 1.]])\n # trajectory_object.discretise_trajectory(parameters=['hover', 3.])\n # trajectory_object.discretise_trajectory(parameters=['vector', [-1.04, -0.55, 1.]])\n # trajectory_object.discretise_trajectory(parameters=['hover', 3.])\n # trajectory_object.discretise_trajectory(parameters=['circle', [.0, .0, 1.]])\n # trajectory_object.discretise_trajectory(parameters=['hover', 3.])\n # trajectory_object.discretise_trajectory(parameters=['vector', [0., -.9, 1.]])\n # trajectory_object.discretise_trajectory(parameters=['hover', 3.])\n # trajectory_object.discretise_trajectory(parameters=['landing'])\n ########################################################################\n\n # Limit the trajectory to the BOX_LIMIT\n # trajectory_object.constraint_trajectory_to_box()\n\n # Generate the list of states - start by generating the states and then filter them\n trajectory_object.generate_states()\n trajectory_object.generate_states_sg_filtered(window_length=13, polyorder=1, mode='mirror')\n trajectory_object.generate_states_sg_filtered(window_length=13, polyorder=1, mode='mirror', on_filtered=True)\n trajectory_object.generate_yaw_filtered()\n\n # Plot the trajectory\n trajectory_object.plot_trajectory_extras()\n\n # Publish trajectory states\n trajectory_object.start()\n\n except rospy.ROSInterruptException:\n pass\n" }, { "alpha_fraction": 0.6958277225494385, "alphanum_fraction": 0.7160161733627319, "avg_line_length": 28.13725471496582, "blob_id": "73906cb4966a68b91b65103650060e00196bea9a", "content_id": "22db7ffb2eac6a033206baaaeb9e05f9045aadc8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1486, "license_type": "permissive", "max_line_length": 143, "num_lines": 51, "path": "/include/trajectory_control/DroneStates.hpp", "repo_name": "gipsa-lab-uav/trajectory_control", "src_encoding": "UTF-8", "text": "#ifndef __DRONE_STATES_HPP__\n#define __DRONE_STATES_HPP__\n\n#include <ros/ros.h>\n#include <geometry_msgs/Vector3.h>\n\n/// <summary>\n/// Respresent the current drone states used for Full State Feedback.\n/// </summary>\n\nclass DS1D {\n public:\n \tfloat position;\n \tfloat speed;\n \tfloat acceleration;\n \tfloat uncertainties;\n \tDS1D();\n \tDS1D(float pos, float speedC, float acc, float unc);\n\tDS1D(const DS1D& otherState);\n\t~DS1D();\n};\n\nclass DroneStates {\n\n\t/// <summary>\n\t/// Respresent the current drone states used for 1 dimension of Full State Feedback.\n\t/// </summary>\n\tpublic:\n\t\tDS1D x;\n\t\tDS1D y;\n\t\tDS1D z;\n float heading;\n\n\t\tDroneStates();\n\t\tDroneStates(DS1D xNew, DS1D yNew, DS1D zNew);\n\t\t~DroneStates();\n\n\t\tvoid replacePos(geometry_msgs::Vector3 position);\n\t\tvoid replacePosAndSpeed(geometry_msgs::Vector3 position, geometry_msgs::Vector3 speed);\n void replaceSpeed(geometry_msgs::Vector3 speed);\n void replaceAcc(geometry_msgs::Vector3 acceleration);\n void replaceHeading(float newHeading);\n\t\tgeometry_msgs::Vector3 getVectPos();\n\t\tgeometry_msgs::Vector3 getVectSpeed();\n\t\tgeometry_msgs::Vector3 getVectAcceleration();\n\t\tgeometry_msgs::Vector3 getVectUncertainties();\n\t\tvoid fillStates (geometry_msgs::Vector3 pos, geometry_msgs::Vector3 speed, geometry_msgs::Vector3 acc);\n\t\tvoid fillStates (geometry_msgs::Vector3 pos, geometry_msgs::Vector3 speed, geometry_msgs::Vector3 acc, geometry_msgs::Vector3 uncertainties);\n};\n\n#endif // __DRONE_STATES_HPP__\n" }, { "alpha_fraction": 0.6343761682510376, "alphanum_fraction": 0.6569920778274536, "avg_line_length": 15.791139602661133, "blob_id": "bb896ed72356da45b64bab18764e7391f8dccdca", "content_id": "83a7c7b54d3a122bad0e7492e65702843670cff6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2653, "license_type": "permissive", "max_line_length": 102, "num_lines": 158, "path": "/src/trajectory_control/fsf.cpp", "repo_name": "gipsa-lab-uav/trajectory_control", "src_encoding": "UTF-8", "text": "#include \"ros/ros.h\"\n#include \"std_msgs/String.h\"\n\n#include \"trajectory_control/fsf.hpp\"\n\n#include <sstream>\n\nFSFParameters::FSFParameters()\n{\n\tKi = 0.0f;\n Kp = 0.3f;\n\tKs = 2.5f;\n\tKpStep = 1.4f;\n\tKsStep = 1.74f;\n\tKu = 1.0f;\n\n\tuseIntegrator = false;\n\tuseFeedForward = true;\n}\n\nFSFParameters::FSFParameters(float kp, float ks, float ku)\n{\n\tKi = 0.0f;\n Kp = kp;\n\tKs = ks;\n\tKpStep = kp;\n\tKsStep = ks;\n\tKu = ku;\n\n\tuseIntegrator = false;\n\tuseFeedForward = true;\n\n}\n\nFSFParameters::FSFParameters(float kp, float ks, float ku, float ki)\n{\n\tKi = ki;\n Kp = kp;\n\tKs = ks;\n\tKpStep = kp;\n\tKsStep = ks;\n\tKu = ku;\n\n\tuseIntegrator = false;\n\tuseFeedForward = true;\n}\nFSFParameters::FSFParameters(float kp, float ks, float ku, float ki, float kpStep, float ksStep)\n{\n\tKi = ki;\n Kp = kp;\n\tKs = ks;\n\tKpStep = kpStep;\n\tKsStep = ksStep;\n\tKu = ku;\n\n\tuseIntegrator = false;\n\tuseFeedForward = true;\n}\n\nFSFParameters::~FSFParameters(){}\n\n/////////////////////////////////:\n\nFSF1D::FSF1D()\n{\n\tstepMode1D = false;\n\tiError = 0.0f;\n\tpError = 0.0f;\n\tsError = 0.0f;\n\tuError = 0.0f;\n}\n\nFSF1D::FSF1D(FSFParameters parameters)\n{\n\tparam = parameters;\n\tstepMode1D = false;\n\tiError = 0.0f;\n\tpError = 0.0f;\n\tsError = 0.0f;\n\tuError = 0.0f;\n}\n\nvoid FSF1D::updateParam(FSFParameters fsfParam)\n{\n\tparam = fsfParam;\n}\n\nvoid FSF1D::resetIntegrator()\n{\n\tiError = 0.0f;\n}\n\nfloat FSF1D::process (float dt, DS1D current, DS1D target) {\n\tif (dt == 0.0f) return current.acceleration;\n\n\tfloat cmd;\n\n\tpError = target.position - current.position;\n\tsError = target.speed - current.speed;\n\tuError = target.uncertainties - current.uncertainties;\n\n\tif (stepMode1D)\n\t{\n\t\tcmd = param.KpStep * pError + param.KsStep * sError + param.Ku * uError;\n\t}\n\telse\n\t{\n\t\tcmd = param.Kp * pError + param.Ks * sError + param.Ku * uError;\n\t}\n\n\tif(param.useIntegrator) {\n\t\tiError += pError * dt;\n\t\tcmd += param.Ki * iError;\n\t}\n\tif(param.useFeedForward) {\n\t\tcmd += target.acceleration;\n\t}\n\treturn cmd;\n}\nFSF1D::~FSF1D(){}\n\n\n\nFullStatesFeedback::FullStatesFeedback()\n{\n\tstepMode = false;\n}\nFullStatesFeedback::~FullStatesFeedback(){}\n\n\nvoid FullStatesFeedback::resetIntegrators()\n{\n\tx.FSF1D::resetIntegrator ();\n\ty.FSF1D::resetIntegrator ();\n\tz.FSF1D::resetIntegrator ();\n}\n\n\ngeometry_msgs::Vector3 FullStatesFeedback::process (float dt, DroneStates current, DroneStates target)\n{\n\tgeometry_msgs::Vector3 r;\n\tif (stepMode)\n\t{\n\t\tx.stepMode1D = true;\n\t\ty.stepMode1D = true;\n\t\tz.stepMode1D = true;\n\t}\n\telse\n\t{\n\t\tx.stepMode1D = false;\n\t\ty.stepMode1D = false;\n\t\tz.stepMode1D = false;\n\t}\n\tr.x = x.process (dt, current.x, target.x);\n\tr.y = y.process (dt, current.y, target.y);\n\tr.z = z.process (dt, current.z, target.z);\n\treturn r;\n}\n" }, { "alpha_fraction": 0.686272144317627, "alphanum_fraction": 0.7129517197608948, "avg_line_length": 25.772727966308594, "blob_id": "bc6b9c3bd751196ceb5a941ddb28573b59901628", "content_id": "a85ce5fcbdf778935b3ddebf6f9e4910975ead85", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8246, "license_type": "permissive", "max_line_length": 171, "num_lines": 308, "path": "/src/trajectory_control/statesEstimator.cpp", "repo_name": "gipsa-lab-uav/trajectory_control", "src_encoding": "UTF-8", "text": "#include \"trajectory_control/statesEstimator.hpp\"\n\n\nSEParameters::SEParameters()\n{\n\tLpos = 1.03f;\n\tLspeed = 10.7f;\n\tLunc = 9.62f;\n\tfilterCoeff = 0.95f;\n\n\tLposPos = 0.92f;\n\tLposSpeed = 0.0001f;\n\tLposUnc = 0.0001f;\n\tLspeedPos = 0.01f;\n\tLspeedSpeed = 1.0f;\n\tLspeedUnc = 8.7f;\n\n\toverSamplingFactor = 1;\n\tmaxUncertainties= 10.0f;\n\n\tmanualReset = false;\n}\nSEParameters::SEParameters(float lpos, float lspeed, float lunc, float filtercoeff)\n{\n\tLpos = lpos;\n\tLspeed = lspeed;\n\tLunc = lunc;\n\tfilterCoeff = filtercoeff;\n\n\tLposPos = 0.92f;\n\tLposSpeed = 0.0001f;\n\tLposUnc = 0.0001f;\n\tLspeedPos = 0.01f;\n\tLspeedSpeed = 1.0f;\n\tLspeedUnc = 8.7f;\n\n\toverSamplingFactor = 1;\n\tmaxUncertainties= 10.0f;\n\n\tmanualReset = false;\n}\nSEParameters::SEParameters(float lpos, float lspeed, float lunc, float filtercoeff, int oversample, float maxUnc)\n{\n\tLpos = lpos;\n\tLspeed = lspeed;\n\tLunc = lunc;\n\tfilterCoeff = filtercoeff;\n\n\tLposPos = 0.92f;\n\tLposSpeed = 0.0001f;\n\tLposUnc = 0.0001f;\n\tLspeedPos = 0.01f;\n\tLspeedSpeed = 1.0f;\n\tLspeedUnc = 8.7f;\n\n\toverSamplingFactor = oversample;\n\tmaxUncertainties = maxUnc;\n\n\tmanualReset = false;\n}\nSEParameters::SEParameters(float lpospos, float lposspeed, float lposunc, float lspeedpos, float lspeedspeed, float lspeedunc)\n{\n\tLpos = 1.03f;\n\tLspeed = 10.7f;\n\tLunc = 9.62f;\n\tfilterCoeff = 0.95f;\n\n\tLposPos = lpospos;\n\tLposSpeed = lposspeed;\n\tLposUnc = lposunc;\n\tLspeedPos = lspeedpos;\n\tLspeedSpeed = lspeedspeed;\n\tLspeedUnc = lspeedunc;\n\n\toverSamplingFactor = 1;\n\tmaxUncertainties= 10.0f;\n\n\tmanualReset = false;\n}\nSEParameters::~SEParameters(){}\n\nSE1D::SE1D()\n{\n \treset = false; //not data\n}\nSE1D::~SE1D(){}\n\nDS1D SE1D::process (float dt, float measuredPos, DS1D predicted, float cmd)\n{\n\tDS1D newStates(0.0f, 0.0f, 0.0f, 0.0f);\n\n\t/** Drone model Parameters: better here or elsewhere? **/\n\t// State matrix\n\tfloat Apos_pos = 1.0f;\n\tfloat Apos_speed = dt;\n\t//float Apos_unc = 0f;\n\n\t//float Aspeed_pos = 0f;\n\tfloat Aspeed_speed = 1.0f;\n\tfloat Aspeed_unc = dt;\n\n\t//float Aunc_pos = 0f;\n\t//float Aunc_speed = 0f;\n\tfloat Aunc_unc = 1.0f;\n\n\t// Command vector\n\t//float Bspeed = 0f;\n\tfloat Bacc = dt;\n\t//float Bunc_dot = 0f;\n\n\t// Output/measurement vector\n\tfloat Cpos = 1.0f;\n\t//float Cspeed = 0f;\n\t//float Cunc = 0f;\n\t//A*Xest\n\tnewStates.position = Apos_pos*predicted.position + Apos_speed *predicted.speed; // + Apos_unc*predicted.uncertainties;\n\tnewStates.speed = Aspeed_speed*predicted.speed + Aspeed_unc *predicted.uncertainties; // + Aspeed_pos*predicted.position;\n\tnewStates.uncertainties = Aunc_unc *predicted.uncertainties; // + Aunc_pos*predicted.position + Aunc_speed*predicted.speed;\n\n\t//+B*U\n\tnewStates.speed += Bacc *cmd;\n\n\n\t//+L(y - C*Xest)\n\tnewStates.position += param.Lpos * (measuredPos - Cpos * predicted.position);\n\tnewStates.speed += param.Lspeed * (measuredPos - Cpos * predicted.position);\n\tnewStates.uncertainties += param.Lunc * (measuredPos - Cpos * predicted.position);\n\n\t//Clamp the uncertainties\n\tnewStates.uncertainties = std::min(newStates.uncertainties, param.maxUncertainties);\n\n\tif (reset == true)\n\t{\n\t newStates.position = measuredPos;\n\t newStates.speed = 0.0f;\n\t newStates.uncertainties = 0.0f;\n\t reset = false;\n\t}\n\tif (param.manualReset == true)\n\t{\n\t newStates.position = measuredPos;\n\t newStates.speed = 0.0f;\n\t newStates.uncertainties = 0.0f;\n\t}\n\n\treturn newStates;\n}\n\nDS1D SE1D::process2 (float dt, float measuredPos, float measuredSpeed, DS1D predicted, float cmd)\n{\n\tDS1D newStates(0.0f, 0.0f, 0.0f, 0.0f);\n\n\t/** Drone second integrator linear model Parameters: better here or elsewhere? **/\n\t// State matrix\n\tfloat Apos_pos = 1.0f;\n\tfloat Apos_speed = dt;\n\t//float Apos_unc = 0f;\n\n\t//float Aspeed_pos = 0f;\n\tfloat Aspeed_speed = 1.0f;\n\tfloat Aspeed_unc = dt;\n\n\t//float Aunc_pos = 0f;\n\t//float Aunc_speed = 0f;\n\tfloat Aunc_unc = 1.0f;\n\n\t// Command vector\n\t//float Bspeed = 0f;\n\tfloat Bacc = dt;\n\t//float Bunc_dot = 0f;\n\n\t// Output/measurement vector\n\tfloat Cpos = 1.0f;\n\tfloat Cspeed = 1.0f;\n\t//float Cunc = 0f;\n\t/*End model parameters*/\n\n\n\t//A*Xest\n\tnewStates.position = Apos_pos*predicted.position + Apos_speed *predicted.speed; // + Apos_unc*predicted.uncertainties;\n\tnewStates.speed = Aspeed_speed*predicted.speed + Aspeed_unc *predicted.uncertainties; // + Aspeed_pos*predicted.position;\n\tnewStates.uncertainties = Aunc_unc *predicted.uncertainties; // + Aunc_pos*predicted.position + Aunc_speed*predicted.speed;\n\n\t//+B*U\n\tnewStates.speed += Bacc *cmd;\n\n\n\t//+L(y - C*Xest)\n\tnewStates.position += param.LposPos * (measuredPos - Cpos * predicted.position);\n\tnewStates.speed += param.LposSpeed * (measuredPos - Cpos * predicted.position);\n\tnewStates.uncertainties += param.LposUnc * (measuredPos - Cpos * predicted.position);\n\n\tnewStates.position += param.LspeedPos * (measuredSpeed - Cspeed * predicted.speed);\n\tnewStates.speed += param.LspeedSpeed * (measuredSpeed - Cspeed * predicted.speed);\n\tnewStates.uncertainties += param.LspeedUnc * (measuredSpeed - Cspeed * predicted.speed);\n\n\t//Clamp the uncertainties\n\tnewStates.uncertainties = std::min(newStates.uncertainties, param.maxUncertainties);\n\n\tif (reset == true)\n\t{\n\t newStates.position = measuredPos;\n\t newStates.speed = 0.0f;\n\t newStates.uncertainties = 0.0f;\n\t reset = false;\n\t}\n\tif (param.manualReset == true)\n\t{\n\t newStates.position = measuredPos;\n\t newStates.speed = 0.0f;\n\t newStates.uncertainties = 0.0f;\n\t}\n\n\treturn newStates;\n}\n\nvoid SE1D::resetEstimation()\n{\n\treset = true;\n}\nvoid SE1D::updateParam(SEParameters seParam)\n{\n\tparam = seParam;\n}\n\nStatesEstimator::StatesEstimator()\n{\n\tz.param.filterCoeff = 0.15f;\n\tcmdApplied.x = 0.0f;\n\tcmdApplied.y = 0.0f;\n\tcmdApplied.z = 0.0f;\n\tcmdAppliedPrev.x = 0.0f;\n\tcmdAppliedPrev.y = 0.0f;\n\tcmdAppliedPrev.z = 0.0f;\n\n}\nStatesEstimator::~StatesEstimator(){}\n\nDroneStates StatesEstimator::process(float dt, geometry_msgs::Vector3 dronePosition, DroneStates predicted, geometry_msgs::Vector3 cmd)\n{\n\n\t// Filter command to fit actuator response: first order for vertical response, second order for horizontal\n\tcmdApplied = firstOrderFilterCmd(cmdApplied, cmdAppliedPrev); //update 2nd order\n\tcmdAppliedPrev = firstOrderFilterCmd(cmdAppliedPrev, cmd); //update 1rst order\n\tcmdApplied.z = cmdAppliedPrev.z;\n\n\n\n\t//updateParam(controllerParam);\n\tfloat newDt = dt / x.param.overSamplingFactor;\n\tDroneStates r = predicted;\n\tDroneStates predictedTemp = predicted;\n\n\tfor (int i = 0; i < x.param.overSamplingFactor; i++)\n\t{\n\t\tr.x = x.process(newDt, dronePosition.x, predictedTemp.x, cmdApplied.x);\n\t\tr.y = y.process(newDt, dronePosition.y, predictedTemp.y, cmdApplied.y);\n\t\tr.z = z.process(newDt, dronePosition.z, predictedTemp.z, cmdApplied.z);\n\t\tpredictedTemp = r;\n\t}\n\n\treturn r;\n}\n\nDroneStates StatesEstimator::process2(float dt, geometry_msgs::Vector3 dronePosition, geometry_msgs::Vector3 droneSpeed, DroneStates predicted, geometry_msgs::Vector3 cmd)\n{\n\n\t// Filter command to fit actuator response: first order for vertical response, second order for horizontal\n\tcmdApplied = firstOrderFilterCmd(cmdApplied, cmdAppliedPrev); //update 2nd order\n\tcmdAppliedPrev = firstOrderFilterCmd(cmdAppliedPrev, cmd); //update 1rst order\n\tcmdApplied.z = cmdAppliedPrev.z;\n\n\n\n\t//updateParam(controllerParam);\n\tfloat newDt = dt / x.param.overSamplingFactor;\n\tDroneStates r = predicted;\n\tDroneStates predictedTemp = predicted;\n\n\tfor (int i = 0; i < x.param.overSamplingFactor; i++)\n\t{\n\t\tr.x = x.process2(newDt, dronePosition.x, droneSpeed.x, predictedTemp.x, cmdApplied.x);\n\t\tr.y = y.process2(newDt, dronePosition.y, droneSpeed.y, predictedTemp.y, cmdApplied.y);\n\t\tr.z = z.process2(newDt, dronePosition.z, droneSpeed.z, predictedTemp.z, cmdApplied.z);\n\t\tpredictedTemp = r;\n\t}\n\n\treturn r;\n}\n\nvoid StatesEstimator::resetEstimations()\n{\n\tx.resetEstimation();\n\ty.resetEstimation();\n\tz.resetEstimation();\n}\n\ngeometry_msgs::Vector3 StatesEstimator::firstOrderFilterCmd(geometry_msgs::Vector3 cmdT_1,geometry_msgs::Vector3 cmdCurrent)\n{\n\tgeometry_msgs::Vector3 cmdOut;\n\n cmdOut.x = x.param.filterCoeff * cmdT_1.x + (1.0f - x.param.filterCoeff) * cmdCurrent.x;\n cmdOut.y = y.param.filterCoeff * cmdT_1.y + (1.0f - y.param.filterCoeff) * cmdCurrent.y;\n \tcmdOut.z = z.param.filterCoeff * cmdT_1.z + (1.0f - z.param.filterCoeff) * cmdCurrent.z;\n\n\treturn cmdOut;\n\n}\n" }, { "alpha_fraction": 0.6293221116065979, "alphanum_fraction": 0.6377298831939697, "avg_line_length": 38.23711395263672, "blob_id": "1f19e8e5897226509801967506cfe9ac2cacf1de", "content_id": "3fbd98631bbf666ff5426e8e4082e6f0123b544e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 19030, "license_type": "permissive", "max_line_length": 125, "num_lines": 485, "path": "/src/trajectory_control_node.cpp", "repo_name": "gipsa-lab-uav/trajectory_control", "src_encoding": "UTF-8", "text": "#include <math.h>\n\n#include <ros/ros.h>\n#include <ros/console.h>\n\n#include <mavros_msgs/AttitudeTarget.h>\n#include <mavros_msgs/CommandBool.h>\n#include <mavros_msgs/SetMode.h>\n#include <mavros_msgs/State.h>\n\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/PoseWithCovariance.h>\n#include <geometry_msgs/TwistWithCovariance.h>\n#include <geometry_msgs/Vector3.h>\n\n#include <nav_msgs/Odometry.h>\n\n#include <tf2/LinearMath/Matrix3x3.h>\n#include <tf2/LinearMath/Quaternion.h>\n\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n\n#include <trajectory_msgs/JointTrajectory.h>\n#include <trajectory_msgs/JointTrajectoryPoint.h>\n\n#include <trajectory_control/DroneStates.hpp>\n#include <trajectory_control/fsf.hpp>\n#include <trajectory_control/kinematicTransform.hpp>\n#include <trajectory_control/statesEstimator.hpp>\n\n/*******************************Global variables*******************************/\nstd::string trajectoryID;\ntrajectory_msgs::JointTrajectory jointTrajectory;\nDroneStates lastMeasuredStates;\ngeometry_msgs::Vector3 lastEulerAngles;\nmavros_msgs::State droneState;\n\nbool isMeasuredStatesFirstCallback = false;\nbool isjointTrajectoryFirstCallback = false;\n/******************************************************************************/\n\n/**********************************Functions***********************************/\nvoid jointTrajectoryAcquireCallback(const trajectory_msgs::JointTrajectory & msg) {\n int i = 0;\n trajectory_msgs::JointTrajectoryPoint point = msg.points[0];\n\n // Set flag for first callback\n if (!isjointTrajectoryFirstCallback) isjointTrajectoryFirstCallback = true;\n\n // Check if this is a new trajectory\n if (msg.header.seq == 1) {\n trajectoryID = msg.header.frame_id;\n isjointTrajectoryFirstCallback = false;\n jointTrajectory.points.erase(jointTrajectory.points.begin(), jointTrajectory.points.end());\n ROS_INFO(\"*** New trajectory received - reset estimators and onboard trajectory time ***\");\n }\n\n // Return if the trajectory ID received does not correspond with the current trajectory ID\n if (trajectoryID != msg.header.frame_id) return;\n ROS_INFO_STREAM(trajectoryID);\n\n // Find the index in order to update the jointTrajectory.points from the topic\n for (const auto & point_saved : jointTrajectory.points){\n if (point.time_from_start == point_saved.time_from_start) break;\n i += 1;\n }\n\n // Erase the values that are going to be updated\n jointTrajectory.points.erase(jointTrajectory.points.begin() + i, jointTrajectory.points.end());\n\n // Push the new points in jointTrajectory.points\n for (const auto & point_new : msg.points){\n jointTrajectory.points.push_back(point_new);\n }\n}\n\nvoid measuredStatesAcquireCallback(const nav_msgs::Odometry & msg) {\n\n // Update measured position and velocity from topic\n geometry_msgs::PoseWithCovariance pose = msg.pose;\n geometry_msgs::TwistWithCovariance twist = msg.twist;\n\n geometry_msgs::Vector3 position, velocity;\n\n position.x = pose.pose.position.x;\n position.y = pose.pose.position.y;\n position.z = pose.pose.position.z;\n\n velocity = twist.twist.linear;\n\n lastMeasuredStates.replacePosAndSpeed(position, velocity);\n\n // Update eulerAngles (euler) from topic (quaternion) -> convertion\n geometry_msgs::Quaternion q_msg;\n tf2::Quaternion q;\n tf2::Matrix3x3 m;\n geometry_msgs::Vector3 orientation;\n\n q_msg = pose.pose.orientation;\n tf2::convert(q_msg, q); //convert geometry_msgs::Quaternion to tf2::Quaternion\n m.setRotation(q); //compute rotation matrix from quaternion\n m.getRPY(orientation.x, orientation.y, orientation.z); //get euler angles\n\n lastEulerAngles = orientation;\n\n // Set flag for first callback\n if (!isMeasuredStatesFirstCallback) isMeasuredStatesFirstCallback = true;\n\n}\n\nvoid droneStateAcquireCallback(const mavros_msgs::State::ConstPtr& msg){\n droneState = *msg;\n}\n\ntrajectory_msgs::JointTrajectoryPoint getNextTrajectoryPoint(float time){\n int i = 0;\n\n // Find the next trajectory point with respect to time\n for (const auto & point : jointTrajectory.points){\n if (point.time_from_start.toSec() > time) break;\n i += 1;\n }\n\n // Erase the outdated values\n if (i > 0) jointTrajectory.points.erase(jointTrajectory.points.begin(), jointTrajectory.points.begin() + i - 1);\n\n return jointTrajectory.points[0];\n}\n\nDroneStates getState(trajectory_msgs::JointTrajectoryPoint point){\n\n DroneStates state;\n geometry_msgs::Vector3 position, velocity, acceleration;\n\n position.x = point.positions[0];\n position.y = point.positions[1];\n position.z = point.positions[2];\n\n velocity.x = point.velocities[0];\n velocity.y = point.velocities[1];\n velocity.z = point.velocities[2];\n\n acceleration.x = point.accelerations[0];\n acceleration.y = point.accelerations[1];\n acceleration.z = point.accelerations[2];\n\n state.fillStates(position, velocity, acceleration);\n\n return state;\n}\n\ntrajectory_msgs::JointTrajectoryPoint getJointTrajectoryPoint(DroneStates state){\n\n trajectory_msgs::JointTrajectoryPoint point;\n geometry_msgs::Vector3 position, velocity, acceleration;\n position = state.getVectPos();\n velocity= state.getVectSpeed();\n acceleration = state.getVectAcceleration();\n\n point.positions.push_back(position.x);\n point.positions.push_back(position.y);\n point.positions.push_back(position.z);\n point.positions.push_back(state.heading);\n\n point.velocities.push_back(velocity.x);\n point.velocities.push_back(velocity.y);\n point.velocities.push_back(velocity.z);\n\n point.accelerations.push_back(acceleration.x);\n point.accelerations.push_back(acceleration.y);\n point.accelerations.push_back(acceleration.z);\n\n return point;\n}\n\nDroneStates getLastMeasuredStates() { return lastMeasuredStates; }\n\ngeometry_msgs::Vector3 getLastEulerAngles() { return lastEulerAngles; }\n\ngeometry_msgs::Quaternion EulerToQuaternion(float yaw, float pitch, float roll){\n\n geometry_msgs::Quaternion q;\n float cy, cp, cr, sy, sp, sr;\n\n cy = cos(yaw * .5);\n cp = cos(pitch * .5);\n cr = cos(roll * .5);\n\n sy = sin(yaw * .5);\n sp = sin(pitch * .5);\n sr = sin(roll * .5);\n\n q.w = (cy * cp * cr) + (sy * sp * sr);\n q.x = (cy * cp * sr) - (sy * sp * cr);\n q.y = (sy * cp * sr) + (cy * sp * cr);\n q.z = (sy * cp * cr) - (cy * sp * sr);\n\n return q;\n}\n/******************************************************************************/\n\nint main(int argc, char *argv[])\n{\n /*********************************Definitions********************************/\n ros::init(argc, argv, \"trajectory_control_node\");\n ros::NodeHandle nh, nh_private(\"~\");\n\n // Define subscribers\n ros::Subscriber jointTrajectory_sub = nh.subscribe(\"mavros/JointTrajectory\", 10, &jointTrajectoryAcquireCallback);\n ros::Subscriber measuredStates_sub = nh.subscribe(\"mavros/local_position/odom\", 10, &measuredStatesAcquireCallback);\n ros::Subscriber state_sub = nh.subscribe<mavros_msgs::State>(\"mavros/state\", 10, droneStateAcquireCallback);\n\n // Define publishers\n ros::Publisher attitudeCmd_pub = nh.advertise<mavros_msgs::AttitudeTarget>(\"mavros/setpoint_raw/attitude\", 10);\n ros::Publisher local_pos_pub = nh.advertise<geometry_msgs::PoseStamped>(\"mavros/setpoint_position/local\", 10);\n ros::Publisher estimatedStates_pub = nh.advertise<trajectory_msgs::JointTrajectoryPoint>(\"mavros/estimatedStates\", 10);\n ros::Publisher referenceStates_pub = nh.advertise<trajectory_msgs::JointTrajectoryPoint>(\"mavros/referenceStates\", 10);\n\n // Define service client\n ros::ServiceClient arming_client = nh.serviceClient<mavros_msgs::CommandBool>(\"mavros/cmd/arming\");\n ros::ServiceClient set_mode_client = nh.serviceClient<mavros_msgs::SetMode>(\"mavros/set_mode\");\n /****************************************************************************/\n\n /************************Class & Variable Declarations***********************/\n FullStatesFeedback fsf;\n KinematicTransform kt;\n StatesEstimator se;\n\n DroneStates predictedStates, targetStates, targetStatesNext, measuredStates, estimatedStates;\n trajectory_msgs::JointTrajectoryPoint trajectoryPoint, trajectoryPointNext;\n trajectory_msgs::JointTrajectoryPoint estimatedStatesTrajectoryPoint, targetStatesTrajectoryPoint;\n geometry_msgs::Vector3 eulerAngles, accelerationCmd, attitudeCmd, position;\n mavros_msgs::AttitudeTarget cmd;\n ros::Time time, last_request;\n float yaw, dt, time2;\n int ctrl_freq;\n bool simulated_env, useStatesObserver, reset;\n\n reset = true;\n /****************************************************************************/\n\n /*********************************Parameters*********************************/\n // Simulated environment\n nh_private.param(\"simulated_env\", simulated_env, true);\n\n // Rate of the controller\n nh_private.param(\"ctrl_freq\", ctrl_freq, 100);\n\n // Full States Feedback Gains\n nh_private.param(\"fsf_x_P\", fsf.x.param.Kp, (float) 1.0);\n nh_private.param(\"fsf_x_S\", fsf.x.param.Ks, (float) 1.7);\n nh_private.param(\"fsf_y_P\", fsf.y.param.Kp, (float) 1.0);\n nh_private.param(\"fsf_y_S\", fsf.y.param.Ks, (float) 1.7);\n nh_private.param(\"fsf_z_P\", fsf.z.param.Kp, (float) 1.56);\n nh_private.param(\"fsf_z_S\", fsf.z.param.Ks, (float) 2.4);\n\n // States Observer Gains\n nh_private.param(\"use_StatesObserver\", useStatesObserver, true);\n\n nh_private.param(\"se_x_Lpos\", se.x.param.Lpos, (float) 1.03);\n nh_private.param(\"se_y_Lpos\", se.y.param.Lpos, (float) 1.03);\n nh_private.param(\"se_z_Lpos\", se.z.param.Lpos, (float) 1.03);\n nh_private.param(\"se_x_Lspeed\", se.x.param.Lspeed, (float) 10.7);\n nh_private.param(\"se_y_Lspeed\", se.y.param.Lspeed, (float) 10.7);\n nh_private.param(\"se_z_Lspeed\", se.z.param.Lspeed, (float) 10.7);\n nh_private.param(\"se_x_Lunc\", se.x.param.Lunc, (float) 9.62);\n nh_private.param(\"se_y_Lunc\", se.y.param.Lunc, (float) 9.62);\n nh_private.param(\"se_z_Lunc\", se.z.param.Lunc, (float) 9.62);\n\n // Actuators Time Constant (used to filter the command fed to the observer)\n nh_private.param(\"se_x_Filter\", se.x.param.filterCoeff, (float) .9);\n nh_private.param(\"se_y_Filter\", se.y.param.filterCoeff, (float) .9);\n nh_private.param(\"se_z_Filter\", se.z.param.filterCoeff, (float) .15);\n\n // Kinematic Transform Parameters (= physical parameters)\n nh_private.param(\"mass\", kt.param.mass, (float) 1.);\n nh_private.param(\"hoverCompensation\", kt.param.hoverCompensation, (float) .3);\n nh_private.param(\"maxAngle\", kt.param.maxAngle, (float) 45.);\n nh_private.param(\"maxVerticalAcceleration\", kt.param.maxVerticalAcceleration, (float) 4.);\n\n ROS_INFO_STREAM(\n \"\\n********* System Parameters (can be defined in launchfile) *********\"\n << \"\\nsimulated_env: \" << simulated_env\n << \"\\n\"\n << \"\\nctrl_freq: \" << ctrl_freq\n << \"\\n\"\n << \"\\nfsf_x_P: \" << fsf.x.param.Kp << \" fsf_x_S: \" << fsf.x.param.Ks\n << \"\\nfsf_y_P: \" << fsf.y.param.Kp << \" fsf_y_S: \" << fsf.y.param.Ks\n << \"\\nfsf_z_P: \" << fsf.z.param.Kp << \" fsf_z_S: \" << fsf.z.param.Ks\n << \"\\n\"\n << \"\\nuse_StatesObserver: \" << useStatesObserver\n << \"\\n\"\n << \"\\nse_x_Lpos: \" << se.x.param.Lpos << \" nse_x_Lspeed: \" << se.x.param.Lspeed << \" se_x_Lunc: \" << se.x.param.Lunc\n << \"\\nse_y_Lpos: \" << se.y.param.Lpos << \" nse_y_Lspeed: \" << se.y.param.Lspeed << \" se_y_Lunc: \" << se.y.param.Lunc\n << \"\\nse_z_Lpos: \" << se.z.param.Lpos << \" nse_z_Lspeed: \" << se.z.param.Lspeed << \" se_z_Lunc: \" << se.z.param.Lunc\n << \"\\n\"\n << \"\\nse_x_Filter: \" << se.x.param.filterCoeff\n << \"\\nse_y_Filter: \" << se.y.param.filterCoeff\n << \"\\nse_z_Filter: \" << se.z.param.filterCoeff\n << \"\\n\"\n << \"\\nmass: \" << kt.param.mass\n << \"\\nhoverCompensation: \" << kt.param.hoverCompensation\n << \"\\nmaxAngle: \" << kt.param.maxAngle\n << \"\\nmaxVerticalAcceleration: \" << kt.param.maxVerticalAcceleration\n << \"\\n*******************************************************************\"\n );\n\n ros::Rate rate = nh_private.param<int>(\"rate\", ctrl_freq);\n /****************************************************************************/\n\n /****************************Connection & Callback***************************/\n // Wait for the drone to connect\n ROS_INFO(\"Waiting for drone connection ...\");\n while(ros::ok() && !droneState.connected){\n ros::spinOnce();\n rate.sleep();\n }\n ROS_INFO(\"Drone connected.\");\n\n // Wait for the first state measure callback\n ROS_INFO(\"Waiting for position measurement callback ...\");\n while (ros::ok() && !isMeasuredStatesFirstCallback){\n ros::spinOnce();\n rate.sleep();\n }\n ROS_INFO(\"Position measurement callback ok.\");\n\n // Wait for better measure accuracy (GPS/MOCAP) -> sleep for 2 seconds\n ros::Duration(2.).sleep();\n /****************************************************************************/\n\n /*******************************Initialization*******************************/\n // Initialize acceleration command\n accelerationCmd.x = .0;\n accelerationCmd.y = .0;\n accelerationCmd.z = .0;\n\n // Initialize first trajectory point as the measured position\n trajectory_msgs::JointTrajectoryPoint firstTrajectoryPoint;\n\n measuredStates = getLastMeasuredStates();\n eulerAngles = getLastEulerAngles();\n position = measuredStates.getVectPos();\n\n firstTrajectoryPoint.positions.push_back(position.x);\n firstTrajectoryPoint.positions.push_back(position.y);\n firstTrajectoryPoint.positions.push_back(position.z - .01f);\n firstTrajectoryPoint.positions.push_back(eulerAngles.z);\n firstTrajectoryPoint.velocities.push_back(0.);\n firstTrajectoryPoint.velocities.push_back(0.);\n firstTrajectoryPoint.velocities.push_back(0.);\n firstTrajectoryPoint.accelerations.push_back(0.);\n firstTrajectoryPoint.accelerations.push_back(0.);\n firstTrajectoryPoint.accelerations.push_back(0.);\n firstTrajectoryPoint.time_from_start = ros::Duration(.0);\n\n jointTrajectory.points.push_back(firstTrajectoryPoint);\n\n // Set OFFBOARD mode request\n mavros_msgs::SetMode offb_set_mode;\n offb_set_mode.request.custom_mode = \"OFFBOARD\";\n\n // Set arming request\n mavros_msgs::CommandBool arm_cmd;\n arm_cmd.request.value = true;\n\n // Initialize time & last_request\n ros::Duration(rate.expectedCycleTime()).sleep();\n time = ros::Time::now() - rate.expectedCycleTime();\n last_request = ros::Time::now();\n /****************************************************************************/\n\n ROS_INFO(\"*** Real test: enable the offboard control and arm the drone with the remote controller ***\");\n ROS_INFO(\"*** Estimators are reset as long as offboard control is disabled & no trajectory is being broadcasted ***\");\n ROS_INFO(\"*** Have a safe flight. ***\");\n\n while (ros::ok()) {\n\n /****************************Manage Drone Mode*****************************/\n // Only in simulated environment\n //In real world, the mode are managed by the pilot with the controller\n if (simulated_env) {\n if( droneState.mode != \"OFFBOARD\" && (ros::Time::now() - last_request > ros::Duration(5.0))) {\n if( set_mode_client.call(offb_set_mode) && offb_set_mode.response.mode_sent) ROS_INFO(\"offb_node: Offboard enabled\");\n last_request = ros::Time::now();\n } else {\n if( !droneState.armed && (ros::Time::now() - last_request > ros::Duration(5.0))) {\n if( arming_client.call(arm_cmd) && arm_cmd.response.success) ROS_INFO(\"offb_node: Vehicle armed\");\n last_request = ros::Time::now();\n }\n }\n }\n /**************************************************************************/\n\n /*******************************Update Loop********************************/\n // Compute dt and save time\n dt = (ros::Time::now().toNSec() - time.toNSec())/1000000000.0f;\n time = ros::Time::now();\n\n // Consider time for trajectory only when the drone is armed && first trajectory point received\n // if not set reset flag to true\n if ((droneState.mode == \"OFFBOARD\") && isjointTrajectoryFirstCallback) time2 += dt;\n else reset = true;\n\n // Get the last measured state\n measuredStates = getLastMeasuredStates();\n eulerAngles = getLastEulerAngles();\n\n // Get the estimated state from measures and previous estimation & command\n predictedStates = se.process(dt, measuredStates.getVectPos(), predictedStates, accelerationCmd);\n\n if(!useStatesObserver) {\n estimatedStates = measuredStates;\n estimatedStates.x.uncertainties = predictedStates.x.uncertainties;\n estimatedStates.y.uncertainties = predictedStates.y.uncertainties;\n estimatedStates.z.uncertainties = predictedStates.z.uncertainties;\n } else {\n estimatedStates = predictedStates;\n }\n\n // Get the next trajectory point and update the target state\n trajectoryPoint = getNextTrajectoryPoint(time2);\n targetStates = getState(trajectoryPoint);\n\n // Get the yaw from the trajectoryPoint\n yaw = trajectoryPoint.positions[3];\n\n // Replace heading in estimatedStates by the measured one (used by display.py)\n estimatedStates.replaceHeading(eulerAngles.z);\n /**************************************************************************/\n\n /*************************Full State Feedback & KT*************************/\n // Reset estimator and set reset flag to false\n if (reset){\n se.resetEstimations();\n time2 = .0;\n reset = false;\n }\n\n // Compute full state feedback control\n accelerationCmd = fsf.process(dt, estimatedStates, targetStates);\n\n // Generate (roll, pitch, thrust) command\n // For compatibility with different aircrafts or even terrestrial robots, this should be in its own node\n attitudeCmd = kt.process(accelerationCmd, eulerAngles);\n /**************************************************************************/\n\n /*************************Publish Attitude Command*************************/\n // Convert command in geometry_msgs::Vector3 to geometry_msgs::AttitudeTarget\n cmd.orientation = EulerToQuaternion(yaw, attitudeCmd.y, attitudeCmd.x);\n cmd.body_rate = geometry_msgs::Vector3();\n cmd.thrust = attitudeCmd.z;\n cmd.type_mask = 7; // ignore body rate\n\n // For Testing:\n // cmd.orientation = EulerToQuaternion(0, 0.5, 0); // (yaw, pitch, roll)\n // cmd.body_rate = geometry_msgs::Vector3();\n // cmd.thrust = 0.7;\n // cmd.type_mask = 7; // ignore body rate\n\n // Convert DroneStates to JointTrajectoryPoint for publishing\n estimatedStatesTrajectoryPoint = getJointTrajectoryPoint(estimatedStates);\n targetStatesTrajectoryPoint = getJointTrajectoryPoint(targetStates);\n\n attitudeCmd_pub.publish(cmd);\n\n estimatedStates_pub.publish(estimatedStatesTrajectoryPoint);\n referenceStates_pub.publish(targetStatesTrajectoryPoint);\n /**************************************************************************/\n\n /***************************Publish Pose Command***************************/\n // For Testing:\n // geometry_msgs::PoseStamped pose;\n // pose.pose.position.x = 0;\n // pose.pose.position.y = 0;\n // pose.pose.position.z = 0;\n //\n // local_pos_pub.publish(pose);\n /**************************************************************************/\n\n ros::spinOnce();\n rate.sleep();\n }\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.7150210738182068, "alphanum_fraction": 0.7304632663726807, "avg_line_length": 25.712499618530273, "blob_id": "c1efc9f0726ee9c417c233618e1572399dab3c86", "content_id": "9085ad999031748fc34f56a8235bb1a99af55918", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2137, "license_type": "permissive", "max_line_length": 156, "num_lines": 80, "path": "/include/trajectory_control/statesEstimator.hpp", "repo_name": "gipsa-lab-uav/trajectory_control", "src_encoding": "UTF-8", "text": "#ifndef __STATES_ESTIMATOR_HPP__\n#define __STATES_ESTIMATOR_HPP__\n\n#include <ros/ros.h>\n#include <geometry_msgs/Vector3.h>\n#include <cmath>\n\n#include \"DroneStates.hpp\"\n\nclass SEParameters\n{\n public:\n //Observer Gains\n\tfloat Lpos;// = 1.03f;\n\tfloat Lspeed;// = 10.7f;\n\tfloat Lunc;// = 9.62f;\n\n //Observer with speed measurement Gains\n\tfloat LposPos;\n\tfloat LposSpeed;\n\tfloat LposUnc;\n\tfloat LspeedPos;\n\tfloat LspeedSpeed;\n\tfloat LspeedUnc;\n\n\t//Filter coefficient for actuators\n\tfloat filterCoeff;\n\n\t//Tuning\n\tint overSamplingFactor;// = 1;\n\tfloat maxUncertainties;// = 10f;\n\n\t//Options\n\tbool usePosEst;// = true;\n\tbool manualReset;// = false;\n\n\tSEParameters();\n\tSEParameters(float lpos, float lspeed, float lunc, float filtercoeff);\n\tSEParameters(float lpos, float lspeed, float lunc, float filtercoeff, int oversample, float maxUnc);\n\tSEParameters(float lpospos, float lposspeed, float lposunc, float lspeedpos, float lspeedspeed, float lspeedunc);\n\t~SEParameters();\n};\n\nclass SE1D\n{\n public:\n\tSEParameters param;// = new SEParameters();\n\tbool reset;// = false;\n\n\t/// <summary>\n\t/// Estimates the drone states\n\t/// </summary>\n\t/// <param name=\"dt\">Dt.</param>\n\t/// <param name=\"current\">current drone states.</param>\n\t/// <param name=\"target\">target drone states.</param>\n\tDS1D process (float dt, float measuredPos, DS1D predicted, float cmd);\n\tDS1D process2 (float dt, float measuredPos, float measuredSpeed, DS1D predicted, float cmd);\n\tvoid resetEstimation();\n\tvoid updateParam(SEParameters seParam);\n\n\tSE1D();\n\t~SE1D();\n\n};\n\nclass StatesEstimator\n{\n public:\n\tSE1D x,y,z;\n\tgeometry_msgs::Vector3 cmdApplied, cmdAppliedPrev;\n\n\tDroneStates process(float dt, geometry_msgs::Vector3 dronePosition, DroneStates predicted, geometry_msgs::Vector3 cmd);\n\tDroneStates process2(float dt, geometry_msgs::Vector3 dronePosition, geometry_msgs::Vector3 droneSpeed, DroneStates predicted, geometry_msgs::Vector3 cmd);\n\tvoid resetEstimations();\n\tgeometry_msgs::Vector3 firstOrderFilterCmd(geometry_msgs::Vector3 cmdT_1,geometry_msgs::Vector3 cmdCurrent);\n\tStatesEstimator();\n\t~StatesEstimator();\n};\n\n#endif // __STATES_ESTIMATOR_HPP__\n" }, { "alpha_fraction": 0.691601037979126, "alphanum_fraction": 0.712598443031311, "avg_line_length": 22.121212005615234, "blob_id": "fb9980f413c31df97ae0c1a60aebc210397f3983", "content_id": "2b28b3c8dae7ff66a9c92e358c3938730f1b9cbf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 762, "license_type": "permissive", "max_line_length": 104, "num_lines": 33, "path": "/include/trajectory_control/kinematicTransform.hpp", "repo_name": "gipsa-lab-uav/trajectory_control", "src_encoding": "UTF-8", "text": "#ifndef __KINEMATIC_TRANSFORM_HPP__\n#define __KINEMATIC_TRANSFORM_HPP__\n\n#include <ros/ros.h>\n#include <geometry_msgs/Vector3.h>\n#include <cmath> \n\nclass KTParameters\n{\n public:\n float hoverCompensation;// = 0.33f;\n float mass;// = 0.287f;\n float maxAngle;// = 45.0f\n float maxVerticalAcceleration;// = 4.0f,\n\n KTParameters();\n\tKTParameters(float Komp, float m, float angleMax, float maxVerticalAcc);\n ~KTParameters();\n};\n\nclass KinematicTransform\n{\n public:\n\tKTParameters param;\n\n\tgeometry_msgs::Vector3 process(geometry_msgs::Vector3 accelerations, geometry_msgs::Vector3 radAngles);\n\tfloat clamp(float value, float lowBound, float upperBound);\n\n\tKinematicTransform();\n\t~KinematicTransform();\n};\n\n#endif // ____KINEMATIC_TRANSFORM_HPP__" }, { "alpha_fraction": 0.643478274345398, "alphanum_fraction": 0.6602484583854675, "avg_line_length": 20.756755828857422, "blob_id": "c0b9e3c4a6195c940b6c8e43f70b21ece1b69baf", "content_id": "c1d9184ac76222e0ffbe9ef3d2b10d4a856ccbab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1610, "license_type": "permissive", "max_line_length": 94, "num_lines": 74, "path": "/include/trajectory_control/fsf.hpp", "repo_name": "gipsa-lab-uav/trajectory_control", "src_encoding": "UTF-8", "text": "#ifndef __FSF_HPP__\n#define __FSF_HPP__\n\n#include <ros/ros.h>\n#include <geometry_msgs/Vector3.h>\n#include \"DroneStates.hpp\"\n\n\n/// <summary>\n/// Respresent the current drone states used for Full State Feedback.\n/// </summary>\nclass FSFParameters\n{\n public:\n\tfloat Ki;// = 0.0f;\n\tfloat Kp;// = 0.3f;\n\tfloat Ks;// = 2.5f;\n\tfloat KpStep;// = 1.4f;\n\tfloat KsStep;// = 1.74f;\n\tfloat Ku;// = 1.0f;\n\t\n\tbool useIntegrator;// = false;\n\tbool useFeedForward;// = true;\n\t\n\tFSFParameters();\n\tFSFParameters(float kp, float ks, float ku);\n\tFSFParameters(float kp, float ks, float ku, float ki);\n\tFSFParameters(float kp, float ks, float ku, float ki, float kpStep, float ksStep);\n\t~FSFParameters();\n};\n\nclass FSF1D\n{\n public:\n\tFSFParameters param;\n\n\tbool stepMode1D;// = false; \n\n\tfloat iError;// = 0f;\n\tfloat pError;// = 0f;\n\tfloat sError;// = 0f;\n\tfloat uError;// = 0f; \n\n\tvoid resetIntegrator();\n\n\t/// <summary>\n\t/// Apply a full state feedback with an optional acceleration feedforward and integral action\n\t/// </summary>\n\t/// <param name=\"dt\">Dt.</param>\n\t/// <param name=\"current\">current drone states.</param>\n\t/// <param name=\"target\">target drone states.</param>\n\tfloat process (float dt, DS1D current, DS1D target);\n\n \tvoid updateParam(FSFParameters fsfParam);\n \t\n \tFSF1D();\n \tFSF1D(FSFParameters parameters);\n \t~FSF1D();\n};\n\nclass FullStatesFeedback\n{\n public:\n\tbool stepMode; \n\t\n\tFSF1D x,y,z;\n\tvoid resetIntegrators();\t\n\tgeometry_msgs::Vector3 process (float dt, DroneStates current, DroneStates target);\n\t\n \tFullStatesFeedback();\n \t~FullStatesFeedback();\n};\n\n#endif // __FSF_HPP__\n" }, { "alpha_fraction": 0.7643530368804932, "alphanum_fraction": 0.7692087888717651, "avg_line_length": 27.69672203063965, "blob_id": "3abaa719ff007e9ac36a759b2daa25af8ce644db", "content_id": "a4d589672d7877569511b8f6e5b34a462f1beadb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3501, "license_type": "permissive", "max_line_length": 373, "num_lines": 122, "path": "/README.md", "repo_name": "gipsa-lab-uav/trajectory_control", "src_encoding": "UTF-8", "text": "# Trajectory Control\nTrajectory generation and control algorithms for UAVs with ROS wrapping.\n\nThe project uses external software such as Mavros. Below are the links directing to their documentations.\n\n[PX4 Development Guide](https://dev.px4.io/v1.9.0/en/)\n\n[PX4-Firmware](https://github.com/PX4/Firmware)\n\n[Mavros](https://github.com/mavlink/mavros/)\n\n[Sitl-Gazebo](https://github.com/PX4/sitl_gazebo)\n\n## Installation\nFor the installation, you need to have ROS melodic (or kinetic) installed, a catkin workspace and Gazebo. Follow the online documentation to set up your environement.\n\n[ROS Installation](http://wiki.ros.org/melodic/Installation/Ubuntu)\n\n[Catkin Workspace](http://wiki.ros.org/catkin/Tutorials/create_a_workspace)\n\n[Gazebo](http://gazebosim.org/tutorials?tut=install_ubuntu&cat=install)\n\n### Prerequisites\nInstall mavros\n\n```bash\nsudo apt install ros-melodic-mavros ros-melodic-mavros-extras\n```\n\nMavros request the GeographicLib datasets, install it by running the install_geographiclib_datasets.sh script\n\n```bash\nwget https://raw.githubusercontent.com/mavlink/mavros/master/mavros/scripts/install_geographiclib_datasets.sh\nchmod +x install_geographiclib_datasets.sh\nsudo ./install_geographiclib_datasets.sh\n```\nInstall libgstreamer\n\n```bash\nsudo apt install libgstreamer1.0-dev\n```\n\nInitialize rosdep and update it\n\n```bash\nsudo rosdep init\nrosdep update\n```\n\nClone sitl_gazebo and PX4 Firmware\n\n```bash\ncd ~/catkin_ws/src/\ngit clone --recursive https://github.com/PX4/sitl_gazebo\ngit clone --recursive https://github.com/PX4/Firmware px4\n```\n\n**Note:** If you have troubles installing the different packages, it is recommended to read the related documentation.\n\n### Install trajectory_control\nClone the trajectory_control repository\n```bash\ncd ~/catkin_ws/src/\ngit clone https://github.com/gipsa-lab-uav/trajectory_control\n```\n\nDon't forget to install the required Python packages, with:\n```bash\npip install -r requirements.txt\n```\n\nAnd then continue the installation:\n```bash\ncd ..\ncatkin_make\n```\n\nThen source your setup.bash\n\n```bash\nsource devel/setup.bash\n```\n\n## Testing the installation\nOn one terminal, run the following launch file:\n```bash\nroslaunch trajectory_control trajectory_control_example.launch\n```\n\nA gazebo window should open with the iris model along with a window displaying live information sush as the thrust, and a window with a generated trajectory. Close the generated trajectory window. In the gazebo window, the iris quadcopter should takeoff and start the trajectory. You can open QGroundControl in parallel also to check if everything is interfacing correctly.\n\n## Troubleshooting\n\n### catkin_make\n\nIn case of issue with catkin_make it is advisable to launch it with the ```VERBOSE=1``` option\n\nIf performance issues don't allow for the computer to finish `catkin_make`, it is possible to reduce the compiler usage on the computer, using the `-j` option. Use the `nproc` command to get the number of CPU cores/threads available. Example:\n\n```bash\nnproc\n>> 8\ncatkin_make -j2\n```\n\n### rosdep\n\nIf an error of type 'cannot download default sources list from: ... Website may be down' occurs\n\n```bash\nsudo apt-get install ca-certificates\n```\n\nIf it still does not work, try to update your system date/clock\n\n### Gazebo\n\nRun Gazebo with the verbose option to get more information on issues `gazebo --verbose`. If Gazebo process dies at the start, it might be a symbol lookup error. Upgrade all your package and try again.\n\n```bash\nsudo apt upgrade\n```\n" }, { "alpha_fraction": 0.65138840675354, "alphanum_fraction": 0.6681164503097534, "avg_line_length": 35.45121765136719, "blob_id": "a1bd84026629627ce3ad83aa823186e87eac4311", "content_id": "dcc6b84188015d6016136f184f881d4ac68aa005", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2989, "license_type": "permissive", "max_line_length": 143, "num_lines": 82, "path": "/src/trajectory_control/kinematicTransform.cpp", "repo_name": "gipsa-lab-uav/trajectory_control", "src_encoding": "UTF-8", "text": "#include \"trajectory_control/kinematicTransform.hpp\"\n\nKTParameters::KTParameters()\n{\n hoverCompensation = 0.5f;\n mass = 0.287f;\n maxAngle = 45.0f;\n maxVerticalAcceleration = 4.0f;\n}\n\nKTParameters::KTParameters(float Komp, float m, float angleMax, float maxVerticalAcc)\n{\n hoverCompensation = Komp;\n mass = m;\n maxAngle = angleMax;\n maxVerticalAcceleration = maxVerticalAcc;\n}\n\nKTParameters::~KTParameters(){}\n\nKinematicTransform::KinematicTransform(){}\nKinematicTransform::~KinematicTransform(){}\n\ngeometry_msgs::Vector3 KinematicTransform::process(geometry_msgs::Vector3 accelerations, geometry_msgs::Vector3 droneEulerAngles)\n{\n // outputCmd(x,y,z) <=> (roll, pitch, thrust)\n geometry_msgs::Vector3 outputCmd;\n float G = 9.81f;\n\n\n float Rad2Deg = 180.0f / 3.14f;\n\n float cosRoll = cos(droneEulerAngles.x);\n float cosPitch = cos(droneEulerAngles.y);\n float cosYaw = cos(droneEulerAngles.z);\n float sinYaw = sin(droneEulerAngles.z);\n\n float thrust = param.mass * (accelerations.z + G) / (cosRoll * cosPitch);\n\n //if we are going in freefall, we will do it horizontally, it will be easier to apply thrust to stabilize the drone when wanted\n if (thrust <= 0.2f * param.mass)\n {\n outputCmd.x = 0.0f;\n outputCmd.y = 0.0f;\n }\n else\n {\n // In the regular frame we have:\n // roll = std::Asin(mass / thrust * ( cmdDrone.translation.x * sinYaw - cmdDrone.translation.y * cosYaw ) );\n // pitch = std::Asin(mass / thrust * ( cmdDrone.translation.x * cosYaw + cmdDrone.translation.y * sinYaw) ) );\n // Yaw shouldn't change, so we keep the cos&sin as is, but we have x_reg = z_unity ; y_reg = -x_unity ; z_reg = y_unity\n outputCmd.x = asin(KinematicTransform::clamp(param.mass * (accelerations.x * sinYaw - accelerations.y * cosYaw) / thrust, -1.0f,1.0f));\n outputCmd.y = asin(KinematicTransform::clamp(param.mass * (accelerations.x * cosYaw + accelerations.y * sinYaw) / thrust, -1.0f,1.0f));\n }\n\n // Clamp to max values\n outputCmd.x = KinematicTransform::clamp((outputCmd.x * Rad2Deg), -param.maxAngle, param.maxAngle);\n outputCmd.y = KinematicTransform::clamp((outputCmd.y * Rad2Deg), -param.maxAngle, param.maxAngle);\n outputCmd.z = KinematicTransform::clamp(thrust, 0.0f, (G + param.maxVerticalAcceleration) * param.mass);\n\n // Map outputs between -1 and 1.\n outputCmd.x = outputCmd.x / param.maxAngle;\n outputCmd.y = outputCmd.y / param.maxAngle;\n //outputCmd.x = (outputCmd.x + param.maxAngle) / (2.0f*param.maxAngle);\n //outputCmd.y = (outputCmd.y + param.maxAngle) / (2.0f*param.maxAngle);\n outputCmd.z = outputCmd.z * param.hoverCompensation / (param.mass * G);\n\n return outputCmd;\n}\n\nfloat KinematicTransform::clamp(float value, float lowBound, float upperBound)\n{\n if (value < lowBound){\n return lowBound;\n }\n else if (value > upperBound){\n return upperBound;\n }\n else{\n return value;\n }\n}\n" } ]
12
Arent/GAN
https://github.com/Arent/GAN
09cd5c30f19f6e43275ef0cff561a2cfa705a160
3db94b14df709150facc202e37897de4bea1def2
dde48e6bfba50a4d03f31096cf2c552942ad462b
refs/heads/master
2021-01-02T08:17:00.425840
2017-08-23T11:38:32
2017-08-23T11:38:32
98,985,196
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.6217228174209595, "alphanum_fraction": 0.6322097182273865, "avg_line_length": 37.14285659790039, "blob_id": "de53a8c56d4a51a3292f86bbe493ab5dbef88fe5", "content_id": "352ec0b821bb6df566192256bd2bfb312246a736", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1335, "license_type": "no_license", "max_line_length": 82, "num_lines": 35, "path": "/inference.py", "repo_name": "Arent/GAN", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nfrom PIL import Image\nimport hyper_parameters\n\nBATCH_SIZE = 10 # overwrite batch size if needed\n\n\ndef rescale_and_save_images(images):\n for i, image_array in enumerate(images): # first dimension in the image\n image_array = np.uint8((image_array + 1) *\n 127.5) # rescale and make into integer\\\n image = Image.fromarray(image_array)\n image.save(\"\".join([model_folder, model_identifier,\n \"/\", sample_folder, str(i), \".jpeg\"]))\n\n\n# Launch graph\nwith tf.Session() as sess:\n # Restore the graph and variables\n saver = tf.train.import_meta_graph(\n \"\".join([model_folder, model_identifier, \"/\", model_name]))\n saver.restore(sess, tf.train.latest_checkpoint(\n \"\".join([model_folder, model_identifier, \"/\"])))\n\n # retrieve operations to generate fake images using the variables\n graph = tf.get_default_graph()\n Z = graph.get_tensor_by_name('Z:0')\n images_tensor = graph.get_tensor_by_name('model/fake_images:0')\n\n # generate random z and use to generate images\n z_batch = np.random.uniform(-1, 1,\n size=[BATCH_SIZE, Z_DIMENSION]).astype(np.float32)\n images = sess.run(images_tensor, feed_dict={Z: z_batch})\n rescale_and_save_images(images)\n" }, { "alpha_fraction": 0.719260036945343, "alphanum_fraction": 0.7236126065254211, "avg_line_length": 24.52777862548828, "blob_id": "9c492f71b6b08b78b4fceaf6c587a5ffd3bde7ef", "content_id": "2a2bb196f6b7b15ce96e6ea8f9b144dc427bb9dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 919, "license_type": "no_license", "max_line_length": 88, "num_lines": 36, "path": "/print_data.py", "repo_name": "Arent/GAN", "src_encoding": "UTF-8", "text": "\nimport tensorflow as tf\nimport numpy as np\nimport Image\nfrom hyper_parameters import *\nfrom image_loader import *\n\n\ntrain_image_batch, train_label_batch, test_image_batch, test_label_batch = get_batches()\n\n\n\nwith tf.Session() as sess:\n \n # initialize the variables\\\n\tsess.run(tf.local_variables_initializer())\n \n # initialize the queue threads to start to shovel data\n\tcoord = tf.train.Coordinator()\n\tthreads = tf.train.start_queue_runners(coord=coord)\n\n\tprint \"from the train set:\"\n\tfor i in range(5):\n\t\timage_batch = sess.run(train_image_batch)\n\t\tfor img in image_batch:\n\t\t\tImage.fromarray(np.uint8(np.asarray(img))).show()\n\n\n\tprint \"from the test set:\"\n\tfor i in range(5):\n\t\timage_batch = sess.run(test_image_batch)\n\t\tfor img in image_batch:\n\t\t\tImage.fromarray(np.uint8(np.asarray(img))).show()\n # stop our queue threads and properly close the session\n\tcoord.request_stop()\n\tcoord.join(threads)\n\tsess.close()" }, { "alpha_fraction": 0.8155339956283569, "alphanum_fraction": 0.8155339956283569, "avg_line_length": 50.5, "blob_id": "c14f945a9e22869fc96d17976f4f9909bdce3c64", "content_id": "d71c56887bf7d81ef8f788248c89a3ea6ddb0c59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 103, "license_type": "no_license", "max_line_length": 74, "num_lines": 2, "path": "/README.md", "repo_name": "Arent/GAN", "src_encoding": "UTF-8", "text": "A simple project illustrating the utility of a General Advesarial Network.\nAlso, infoGAN wil be added.\n" }, { "alpha_fraction": 0.6625387072563171, "alphanum_fraction": 0.7244582176208496, "avg_line_length": 20.53333282470703, "blob_id": "81c1024a431012e9a30ae2b9cd09dce1e8908448", "content_id": "a98cf830b490d87a527dab73bf9cbefc867a938b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 646, "license_type": "no_license", "max_line_length": 43, "num_lines": 30, "path": "/hyper_parameters.py", "repo_name": "Arent/GAN", "src_encoding": "UTF-8", "text": "#parameters that are actually just settings\nDEBUG = False\nrun_type = 'train' # train or retrain\nPATH_FOLDER = 'data/image_locations'\nLABEL_FOLDER = 'data/image_labels'\nmodel_folder = \"saved_models/\"\nsample_folder = 'samples/'\nmodel_identifier = \"2017-Aug-19-15-00-48\"\nmodel_name = \"0.meta\"\nNUM_THREADS = 32\n\n#parameters regarding data'\nIMAGE_HEIGHT = 64\nIMAGE_WIDTH = 64\nNUM_CHANNELS = 3\n\n\n#parameters regarding training'\nTEST_SET_SIZE = 4\nBATCH_SIZE = 64\nEPOCHS = 2\nNORMALISATION_DECAY = 0.9\nRELU_ALPHA = 1/6\nBETA_ADAM = 0.5\nLEARNING_RATE = 0.0002\n\n#parameters regarding convolutions'\nZ_DIMENSION = 100\nKERNEL_WIDTH = 4\nKERNEL_HEIGHT = 4\n" }, { "alpha_fraction": 0.5650523900985718, "alphanum_fraction": 0.5825868844985962, "avg_line_length": 39.660491943359375, "blob_id": "cb49d91de9a77bded922839802a0b55e932aff2b", "content_id": "a82572e38bf51b256658328f3488c6ea0e6498b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13174, "license_type": "no_license", "max_line_length": 105, "num_lines": 324, "path": "/model.py", "repo_name": "Arent/GAN", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom hyper_parameters import *\n\n\ndef variable_summaries(var):\n \"\"\"Attach a lot of summaries to a Tensor (for TensorBoard visualization).\"\"\"\n mean = tf.reduce_mean(var)\n tf.summary.scalar('mean', mean)\n with tf.name_scope('stddev'):\n stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n tf.summary.scalar('stddev', stddev)\n tf.summary.scalar('max', tf.reduce_max(var))\n tf.summary.scalar('min', tf.reduce_min(var))\n tf.summary.histogram('histogram', var)\n\n\ndef leaky_RELU(x):\n return tf.maximum(x, RELU_ALPHA * x)\n\n\n# init_weight_variable generates a weight variable of a given shape.\ndef init_weight_variable(shape):\n return tf.random_normal(shape, stddev=0.01)\n\n\ndef binary_cross_entropy(x, label):\n x = tf.clip_by_value(x, 1e-7, 1. - 1e-7) # for stability\n return -(label * tf.log(x) + (1. - label) * tf.log(1. - x))\n\n\ndef activate_convolution_transposed(input_dim, output_dim,\n strides, padding, input,\n activation, normalise=True):\n assert len(input_dim) == 3\n assert len(output_dim) == 3\n\n filter_shape = [output_dim[0], output_dim[1], output_dim[2], input_dim[2]]\n filter_weights = tf.get_variable(\n \"weights\", initializer=init_weight_variable(filter_shape))\n\n batch_size = tf.shape(input)[0]\n output_shape = [batch_size, output_dim[0], output_dim[1], output_dim[2]]\n\n output = tf.nn.conv2d_transpose(\n value=input,\n filter=filter_weights,\n output_shape=output_shape,\n strides=strides,\n padding=padding,\n )\n bias = tf.get_variable(\n \"bias\", initializer=init_weight_variable(output_dim))\n output_bias = output + bias\n\n if normalise:\n output_bias = tf.contrib.layers.batch_norm(output_bias,\n center=True,\n scale=True,\n decay=NORMALISATION_DECAY)\n\n activated_output_bias = activation(output_bias)\n\n with tf.variable_scope(\"Activated_output_bias\"):\n variable_summaries(activated_output_bias)\n with tf.variable_scope(\"Output_bias\"):\n variable_summaries(output_bias)\n with tf.variable_scope(\"Weights\"):\n variable_summaries(filter_weights)\n\n return activated_output_bias\n\n\ndef activate_convolution(filter_width, filter_height, input_dim,\n output_dim, strides, padding, input,\n activation, normalise=True):\n assert len(input_dim) == 3\n assert len(output_dim) == 3\n\n filter_shape = [filter_height, filter_width, input_dim[2], output_dim[2]]\n filter = tf.get_variable(\n \"weights\", initializer=init_weight_variable(filter_shape))\n bias = tf.get_variable(\n \"bias\", initializer=init_weight_variable(output_dim))\n\n output = tf.nn.conv2d(\n input=input,\n filter=filter,\n strides=strides,\n padding=padding)\n\n output_bias = output + bias\n if normalise:\n output_bias = tf.contrib.layers.batch_norm(output_bias,\n center=True,\n scale=True,\n decay=NORMALISATION_DECAY)\n activated_output_bias = activation(output_bias)\n\n with tf.variable_scope(\"Activated_output_bias\"):\n variable_summaries(activated_output_bias)\n with tf.variable_scope(\"Output_bias\"):\n variable_summaries(output_bias)\n with tf.variable_scope(\"Weights\"):\n variable_summaries(filter)\n return activated_output_bias\n\n\ndef activate_fully_connected(input, input_dim, output_dim, activation, normalize=True):\n weight_shape = [input_dim, output_dim[0]]\n weights = tf.get_variable(\n name=\"weights\", initializer=init_weight_variable(weight_shape))\n bias = tf.get_variable(\n name=\"bias\", initializer=init_weight_variable(output_dim))\n\n output = tf.matmul(input, weights)\n\n output_bias = output + bias\n if normalize:\n output_bias = tf.contrib.layers.batch_norm(output,\n center=True,\n scale=True,\n decay=NORMALISATION_DECAY)\n\n output_bias_logit = output_bias\n activated_output_bias = activation(output_bias)\n with tf.variable_scope(\"Activated_output_bias\"):\n variable_summaries(activated_output_bias)\n with tf.variable_scope(\"Output_bias\"):\n variable_summaries(output_bias)\n with tf.variable_scope(\"Weights\"):\n variable_summaries(weights)\n\n return activated_output_bias, output_bias_logit\n\n\ndef generate(z):\n batch_size = tf.shape(z)[0]\n\n with tf.variable_scope(\"generator\"):\n z = tf.reshape(z, [batch_size, 1, 1, 100])\n with tf.variable_scope(\"layer1\"):\n activated_layer_1 = activate_convolution_transposed(\n input_dim=[1, 1, 100], output_dim=[4, 4, 1024],\n strides=[1, 1, 1, 1], padding='VALID',\n input=z,\n activation=tf.nn.relu,\n normalise=True)\n\n with tf.variable_scope(\"layer2\"):\n activated_layer_2 = activate_convolution_transposed(\n input_dim=[4, 4, 1024], output_dim=[8, 8, 512],\n strides=[1, 2, 2, 1], padding='SAME',\n input=activated_layer_1,\n activation=tf.nn.relu,\n normalise=True)\n\n with tf.variable_scope(\"layer3\"):\n activated_layer_3 = activate_convolution_transposed(\n input_dim=[8, 8, 512], output_dim=[16, 16, 256],\n strides=[1, 2, 2, 1], padding='SAME',\n input=activated_layer_2,\n activation=tf.nn.relu,\n normalise=True)\n\n with tf.variable_scope(\"layer4\"):\n activated_layer_4 = activate_convolution_transposed(\n input_dim=[16, 16, 256], output_dim=[32, 32, 128],\n strides=[1, 2, 2, 1], padding='SAME',\n input=activated_layer_3,\n activation=tf.nn.relu,\n normalise=True)\n\n with tf.variable_scope(\"layer5\"):\n activated_layer_5 = activate_convolution_transposed(\n input_dim=[32, 32, 128], output_dim=[64, 64, 3],\n strides=[1, 2, 2, 1], padding='SAME',\n input=activated_layer_4,\n activation=tf.nn.relu,\n normalise=True)\n fake_image = activated_layer_5\n return fake_image\n\n\ndef discriminate(image):\n batch_size = tf.shape(image)[0]\n with tf.variable_scope(\"discriminator\"):\n with tf.variable_scope(\"layer1\"):\n activated_layer_1 = activate_convolution(\n filter_width=KERNEL_WIDTH, filter_height=KERNEL_HEIGHT,\n input_dim=[64, 64, 3], output_dim=[32, 32, 128],\n strides=[1, 2, 2, 1], padding='SAME',\n input=image,\n activation=leaky_RELU,\n normalise=True)\n\n with tf.variable_scope(\"layer2\"):\n activated_layer_2 = activate_convolution(\n filter_width=KERNEL_WIDTH, filter_height=KERNEL_HEIGHT,\n input_dim=[32, 32, 128], output_dim=[16, 16, 256],\n strides=[1, 2, 2, 1], padding='SAME',\n input=activated_layer_1,\n activation=leaky_RELU,\n normalise=True)\n\n with tf.variable_scope(\"layer3\"):\n activated_layer_3 = activate_convolution(\n filter_width=KERNEL_WIDTH, filter_height=KERNEL_HEIGHT,\n input_dim=[16, 16, 256], output_dim=[8, 8, 512],\n strides=[1, 2, 2, 1], padding='SAME',\n input=activated_layer_2,\n activation=leaky_RELU,\n normalise=True)\n\n with tf.variable_scope(\"layer4\"):\n activated_layer_4 = activate_convolution(\n filter_width=KERNEL_WIDTH, filter_height=KERNEL_HEIGHT,\n input_dim=[8, 8, 512], output_dim=[4, 4, 1024],\n strides=[1, 2, 2, 1], padding='SAME',\n input=activated_layer_3,\n activation=leaky_RELU,\n normalise=True)\n\n with tf.variable_scope(\"layer5\"):\n total_dimension = tf.reduce_prod(tf.shape(activated_layer_4)[1:])\n activated_layer_4_flattened = tf.reshape(\n activated_layer_4, [batch_size, total_dimension]) # 4*4*1024])#\n judgement, logit_judgement = activate_fully_connected(\n input=activated_layer_4_flattened,\n input_dim=4 * 4 * 1024,\n output_dim=[1],\n normalize=False,\n activation=tf.nn.tanh)\n\n return judgement, logit_judgement\n\n\ndef create_loss_functions(probability_real, logit_real, probability_fake, logit_fake):\n # Create loss functions\n loss_discriminator_real = tf.reduce_mean(binary_cross_entropy(x=probability_real,\n label=tf.ones_like(probability_real)))\n loss_discriminator_fake = tf.reduce_mean(binary_cross_entropy(x=probability_fake,\n label=tf.zeros_like(probability_fake)))\n loss_discriminator = loss_discriminator_real + loss_discriminator_fake\n\n loss_generator = tf.reduce_mean(binary_cross_entropy(x=probability_fake,\n label=tf.ones_like(probability_fake)))\n\n # summarize loss functions and probalbilities\n\n with tf.variable_scope(\"loss\") as scope:\n tf.summary.scalar(\"loss_discriminator_real\",\n tf.reduce_mean(loss_discriminator_real))\n tf.summary.scalar(\"loss_discriminator\", loss_discriminator)\n tf.summary.scalar(\"loss_generator\", loss_generator)\n tf.summary.scalar(\"loss_discriminator_fake\",\n tf.reduce_mean(loss_discriminator_fake))\n\n return loss_discriminator, loss_generator\n\n\ndef create_training_operations():\n # retrieve the loss functions and variable list\n # with tf.variable_scope(\"model\") as scope:\n\n loss_discriminator = tf.get_default_graph()\\\n .get_tensor_by_name(\"model/loss_discriminator:0\")\n loss_generator = tf.get_default_graph()\\\n .get_tensor_by_name(\"model/loss_generator:0\")\n\n discriminator_variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,\n scope='model/discriminator')\n generator_variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,\n scope='model/generator')\n\n # Create optimizer\n optimizer = tf.train.AdamOptimizer(LEARNING_RATE, beta1=BETA_ADAM)\n\n # Explicitly create gradients for optimizing and logging\n discriminator_gradients = optimizer.compute_gradients(\n loss_discriminator, var_list=discriminator_variables)\n generator_gradients = optimizer.compute_gradients(\n loss_generator, var_list=generator_variables)\n\n # Summarize all gradients\n for grad, var in discriminator_gradients + generator_gradients:\n if not grad == None:\n tf.summary.histogram(var.name + '/gradient', grad)\n\n # Create and identiy the training operations\n train_op_discrim = optimizer.apply_gradients(grads_and_vars=discriminator_gradients,\n name='train_operation_discriminator')\n train_op_gen = optimizer.apply_gradients(grads_and_vars=generator_gradients,\n name='train_operation_generator')\n\n # Merge all tensorboard summaries, identidy the merged operations\n merged_summary_op = tf.summary.merge_all()\n tf.identity(merged_summary_op, name=\"merged_summaries\")\n\n\ndef build_graph():\n Z = tf.placeholder(dtype=tf.float32, shape=(None, Z_DIMENSION), name='Z')\n real_images = tf.placeholder(\tdtype=tf.float32,\n shape=(None, IMAGE_HEIGHT,\n IMAGE_WIDTH, NUM_CHANNELS),\n name='real_images')\n\n with tf.variable_scope(\"model\") as scope:\n fake_images = generate(Z)\n tf.identity(fake_images, \"fake_images\")\n probability_real, logit_real = discriminate(real_images)\n tf.summary.scalar(\"probability_real\", tf.reduce_mean(probability_real))\n\n # Ensure the discriminate functions doesn't create new variables\n scope.reuse_variables()\n probability_fake, logit_fake = discriminate(fake_images)\n tf.summary.scalar(\"probability_fake\", tf.reduce_mean(probability_fake))\n\n loss_discriminator, loss_generator = create_loss_functions(probability_real, logit_real,\n probability_fake, logit_fake)\n\n tf.identity(loss_discriminator, \"loss_discriminator\")\n tf.identity(loss_discriminator, \"loss_generator\")\n\n create_training_operations()\n" }, { "alpha_fraction": 0.618953287601471, "alphanum_fraction": 0.6240713000297546, "avg_line_length": 38.07741928100586, "blob_id": "a9705b0a8671a303d37a022055dcce157c0f23a9", "content_id": "1025366851b6501a5e2252f93a4e8a49715d8fa0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6057, "license_type": "no_license", "max_line_length": 94, "num_lines": 155, "path": "/train.py", "repo_name": "Arent/GAN", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nfrom PIL import Image\nfrom hyper_parameters import *\nfrom image_loader import *\nfrom model import *\nimport datetime\nimport os\nimport math\n\nrun_identifier = '{:%Y-%b-%d-%H-%M-%S}'.format(datetime.datetime.now())\n\n\ndef create_save_location():\n assert os.path.isdir(\"\".join([model_folder, run_identifier])) == False\n os.mkdir(\"\".join([model_folder, run_identifier]))\n os.mkdir(\"\".join([model_folder, run_identifier, \"/\", sample_folder]))\n return \"\".join([model_folder, run_identifier, \"/\"])\nsave_location = create_save_location()\n\n\ndef rescale_and_save_image(image_array, iBatch):\n image_array = np.uint8((image_array + 1) *\n 127.5) # rescale and make into integer\\\n image = Image.fromarray(image_array)\n image.save(\"\".join([model_folder, run_identifier,\n \"/\", sample_folder, str(iBatch), \".jpeg\"]))\n\n\ndef initialise_graph_train(session):\n # Builds the graph, create data loading operations and initialises variables\n # Get que with training files\n\n build_graph() # this creates all variables and operations needed to train\n\n # initialize the variables\n session.run(tf.local_variables_initializer())\n session.run(tf.global_variables_initializer())\n\n return tf.get_default_graph()\n\n\ndef initialise_graph_retrain(session):\n # Restorres the graph, delete and recreate data loading operations\n # and initialises local variables\n\n saver = tf.train.import_meta_graph(\n \"\".join([model_folder, model_identifier, \"/\", model_name]))\n # restore variables\n saver.restore(sess, tf.train.latest_checkpoint(\n \"\".join([model_folder, model_identifier, \"/\"])))\n graph = tf.get_default_graph()\n # Delete old data loader objects and create new ones. (Cant find a better\n # way...)\n graph.clear_collection(\"queue_runners\")\n graph.clear_collection(\"local_variables\")\n\n\n # initialize the local variables, global variables have been restored\n sess.run(tf.local_variables_initializer())\n\n return graph\n\n# Get que with training files\nn_train_files, n_test_files\\\n , train_image_batch, train_label_batch, test_image_batch, test_label_batch = get_batches()\nbatches_per_epoch = int(math.ceil(float(n_train_files) / BATCH_SIZE))\n\n\n# Launch graph\nwith tf.Session() as sess:\n # get training operations and placeholders\n if run_type == \"train\":\n graph = initialise_graph_train(sess)\n elif run_type == \"retrain\":\n graph = initialise_graph_retrain(sess)\n else:\n raise NotImplementedError\n\n # Get training operations from graph\n train_op_discrim = graph.get_operation_by_name(\n \"train_operation_discriminator\")\n train_op_gen = graph.get_operation_by_name(\"train_operation_generator\")\n images_tensor = graph.get_tensor_by_name('model/fake_images:0')\n\n # Create a saver object to check progress of training\n saver = tf.train.Saver(max_to_keep=3)\n run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n run_metadata = tf.RunMetadata()\n\n summary_writer = tf.summary.FileWriter(\n \"\".join(['tensorboard_logs', \"/\", run_identifier]), graph)\n\n # Get placeholders\n Z = graph.get_tensor_by_name('Z:0')\n real_images = graph.get_tensor_by_name('real_images:0')\n\n # initialize the queue threads to start to shovel data\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n iBatch = 0\n try:\n while not coord.should_stop():\n print(iBatch)\n\n # retrieve and display epoch and batch\n epoch = int(iBatch / batches_per_epoch) + 1\n batch_number = iBatch % batches_per_epoch\n print('Epoch: ' + str(epoch) + '/' + str(EPOCHS) + ' Batch: ' +\n str(batch_number) + '/' + str(batches_per_epoch - 1))\n\n # Get Z values and image batch\n z_batch = np.random.uniform(-1, 1,\n size=[BATCH_SIZE, Z_DIMENSION]).astype(np.float32)\n image_batch = sess.run(train_image_batch, options=run_options)\n\n # Do the acual training\n _, = sess.run([train_op_gen], options=run_options, feed_dict={\n Z: z_batch, real_images: image_batch})\n _, = sess.run([train_op_discrim], options=run_options, feed_dict={\n Z: z_batch, real_images: image_batch})\n\n # Add summaries of variables to tensorboard\n merged_summary_op = tf.summary.merge_all() \n summary_str = sess.run(merged_summary_op, options=run_options,\n feed_dict={Z: z_batch, real_images: image_batch})\n summary_writer.add_summary(summary_str, iBatch)\n if iBatch == 0: # Save metagraph only once\n saved_path = saver.save(\n sess, save_location + str(batch_number), write_meta_graph=True)\n\n if batch_number % 20 == 0: # save variable state and make sample image\n images = sess.run(images_tensor, feed_dict={Z: z_batch})\n rescale_and_save_image(images[0, :, :, :], iBatch)\n saved_path = saver.save(sess, save_location + \"Epoch_\" + str(\n epoch) + \"_Batch_\" + str(batch_number), write_meta_graph=False)\n print(\"Model saved in file: %s\" % saved_path)\n iBatch = iBatch + 1\n\n except Exception, e:\n # Report exceptions to the coordinator.\n coord.request_stop(e)\n\n finally:\n # stop our queue threads and properly close the session\n print(\"This run can be identified as {}\".format(run_identifier))\n print(\"Run the command line:\\n\"\n \"--> tensorboard --logdir=tensorboard_logs \"\n \"\\nThen open http://0.0.0.0:6006/ into your web browser\")\n\n # Add meta data such as computational time per operation\n summary_writer.add_run_metadata(run_metadata, 'Mysess')\n coord.request_stop()\n coord.join(threads)\n sess.close()\n" }, { "alpha_fraction": 0.7052903771400452, "alphanum_fraction": 0.714491069316864, "avg_line_length": 35.978721618652344, "blob_id": "593669f6fa4d75074e2ee2a0eb308f442bfcaa2f", "content_id": "f0647cda3868e902fdcacc322b74cc4d5e0f75d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3478, "license_type": "no_license", "max_line_length": 108, "num_lines": 94, "path": "/image_loader.py", "repo_name": "Arent/GAN", "src_encoding": "UTF-8", "text": "# Example on how to use the tensorflow input pipelines. The explanation can be found here ischlag.github.io.\nimport tensorflow as tf\nimport numpy as np \nimport random\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import dtypes\nfrom PIL import Image\nfrom hyper_parameters import *\n\ndef image_locations_and_labels_from_files(image_locations_filename, image_labels_filename):\n\timage_locations_file = open(image_locations_filename)\n\timage_labels_file = open(image_labels_filename)\n\timage_locations = image_locations_file.read().splitlines()\n\timage_labels = image_labels_file.read().splitlines()\n\treturn image_locations, image_labels\n \n\n\ndef get_batches():\n\tall_filepaths, all_labels = image_locations_and_labels_from_files(PATH_FOLDER,LABEL_FOLDER)\n\tif DEBUG:\n\t\tall_filepaths = all_filepaths[0:63]#DEBUG\n\t\tall_labels = all_labels[0:63] #DEBUG\n\n\n\t# convert string into tensors\n\tall_images = ops.convert_to_tensor(all_filepaths, dtype=dtypes.string)\n\tall_labels = ops.convert_to_tensor(all_labels, dtype=dtypes.string)\n\n\t# create a partition vector\n\tpartitions = [0] * len(all_filepaths)\n\tpartitions[:TEST_SET_SIZE] = [1] * TEST_SET_SIZE\n\n\trandom.shuffle(partitions)\n\n\t# partition our data into a test and train set according to our partition vector\n\ttrain_images, test_images = tf.dynamic_partition(all_images, partitions, 2)\n\ttrain_labels, test_labels = tf.dynamic_partition(all_labels, partitions, 2)\n\n\tnumber_of_train_files = len(partitions) - TEST_SET_SIZE\n\tnumber_of_test_files = TEST_SET_SIZE\n\n\n\t# create input queues\n\ttrain_input_queue = tf.train.slice_input_producer(\n\t\t\t\t\t\t\t\t\t\t[train_images, train_labels],\n\t\t\t\t\t\t\t\t\t\tshuffle=True,\n\t\t\t\t\t\t\t\t\t\tnum_epochs = EPOCHS)\n\ttest_input_queue = tf.train.slice_input_producer(\n\t\t\t\t\t\t\t\t\t\t[test_images, test_labels],\n\t\t\t\t\t\t\t\t\t\tshuffle=True,\n\t\t\t\t\t\t\t\t\t\tnum_epochs= EPOCHS)\n\n\t# process path and string tensor into an image and a label\n\tfile_content = tf.read_file(train_input_queue[0])\n\ttrain_image = tf.image.decode_jpeg(file_content, channels=NUM_CHANNELS)\n\n\t# pre processing, image dimensions and range\n\ttrain_image = tf.image.resize_images(train_image,[IMAGE_HEIGHT,IMAGE_WIDTH])\n\ttrain_image = ((train_image /255) -1) * 2 # rescale to -1 , 1\n\ttrain_label = train_input_queue[1]\n\n\tfile_content = tf.read_file(test_input_queue[0])\n\ttest_image = tf.image.decode_jpeg(file_content, channels=NUM_CHANNELS)\n\ttest_image = tf.image.resize_images(test_image,[IMAGE_HEIGHT,IMAGE_WIDTH])\n\ttest_image = ((test_image /255) -1) * 2 # rescale to -1 , 1\n\n\ttest_label = test_input_queue[1]\n\n\t# define tensor shape\n\ttrain_image.set_shape([IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS])\n\ttest_image.set_shape([IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS])\n\n\n\tmin_after_dequeue = 100\n\tcapacity = min_after_dequeue + (NUM_THREADS + 3) * BATCH_SIZE\n\n\t# collect batches of images before processing\n\ttrain_image_batch, train_label_batch = tf.train.shuffle_batch(\n\t\t\t\t\t\t\t\t\t\t[train_image, train_label],\n\t\t\t\t\t\t\t\t\t\tbatch_size=BATCH_SIZE,\n\t\t\t\t\t\t\t\t\t\tnum_threads=NUM_THREADS,\n\t\t\t\t\t\t\t\t\t\tmin_after_dequeue=min_after_dequeue,\n\t\t\t\t\t\t\t\t\t\tcapacity=capacity\n\t\t\t\t\t\t\t\t\t\t)\n\ttest_image_batch, test_label_batch = tf.train.shuffle_batch(\n\t\t\t\t\t\t\t\t\t\t[test_image, test_label],\n\t\t\t\t\t\t\t\t\t\tbatch_size=BATCH_SIZE,\n\t\t\t\t\t\t\t\t\t\tnum_threads=NUM_THREADS,\n\t\t\t\t\t\t\t\t\t\tmin_after_dequeue=min_after_dequeue,\n\t\t\t\t\t\t\t\t\t\tcapacity=capacity\n\t\t\t\t\t\t\t\t\t\t)\n\treturn number_of_train_files, number_of_test_files, train_image_batch\\\n\t, train_label_batch, test_image_batch, test_label_batch\n\n\n" } ]
7
LyaxKing/My_Printor
https://github.com/LyaxKing/My_Printor
43de41d7b0577abc66351de27843f74e1fe87af8
61efb5acf656407048c225b890041ff2c711cb2b
3098c69ee9aa0d2e6502c9fa205efc91b3b66354
refs/heads/master
2020-08-10T19:05:27.259926
2019-10-11T10:03:59
2019-10-11T10:07:07
214,402,637
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.584786057472229, "alphanum_fraction": 0.6006339192390442, "avg_line_length": 19.62295150756836, "blob_id": "f270cdab8faa0d2c5c6f32341306a2b796bf858d", "content_id": "ecd8a4e3f760c2ed2f10f7097db81cc412228ee4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1666, "license_type": "no_license", "max_line_length": 84, "num_lines": 61, "path": "/3.0/FTPClient.py", "repo_name": "LyaxKing/My_Printor", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 26 16:24:35 2019\n\n@author: HP\n\"\"\"\nimport ftplib\n# 关于FTP的操作都在这个包里边。\n\n\nclass SocketGetGcode:\n# 三部分精确表示在ftp服务器上的某一个文件\n HOST = \"ftp.acc.umu.se\"\n DIR = 'Public/EFLIB/'\n FILE = 'printfile.gcode'\n\n\n# 1. 客户端链接远程主机上的FTP服务器\ndef connect_ftp_sever(self):\n try:\n self.f = ftplib.FTP()\n # 链接主机地址\n self.f.connect(self.HOST)\n except Exception as e:\n print(e)\n exit()\n print(\"***Connected to host {0}\".format(self.HOST))\n\n\n# 2. 客户端输入用户名和密码(或者“anonymous”和电子邮件地址)\ndef login(self):\n try:\n # 登录如果没有输入用户信息,则默认使用匿名登录\n self.f.login()\n except Exception as e:\n print(e)\n exit()\n print(\"***Logged in as 'anonymous'\")\n\n\n# 3. 客户端和服务器进行各种文件传输和信息查询操作\ndef change_file_dir(self):\n try:\n self.f.cwd(self.DIR)# 更改当前目录到指定目录\n except Exception as e:\n print(e)\n exit()\n print(\"*** Changed dir to {0}\".format(self.DIR))\n\n\ndef download_gcode(self):\n try:\n # 从FTP服务器上下载文件\n # 第一个参数是ftp命令,第二个参数是回调函数\n # 此函数的意思是,执行RETR命令,下载文件到本地后,运行回调函数\n self.f.retrbinary('RETR {0}'.format(self.FILE), open(self.FILE, 'wb').write)\n except Exception as e:\n print(e)\n exit()\n # 4. 客户端从远程FTP服务器退出,结束传输\n self.f.quit()\n\n\n\n\n" }, { "alpha_fraction": 0.4426877498626709, "alphanum_fraction": 0.4563697278499603, "avg_line_length": 35.153846740722656, "blob_id": "e9c6b3bd8e52b690a9b0e5f37574a8c11e13c708", "content_id": "f174737022d581f0f3cab89704e2b25e2f4f0bba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3439, "license_type": "no_license", "max_line_length": 84, "num_lines": 91, "path": "/4.0/FR.py", "repo_name": "LyaxKing/My_Printor", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom socket import *\nimport threading\n\nPORT = 9999\nHOST = '47.96.95.75'\n#HOST = '192.168.1.110'\nBUFSIZ = 1024 * 1024\nADDR = (HOST, PORT)\n\n\nclass FileReceiver:\n def __init__(self):\n print('生成客户端')\n\n def get_file(self, print_center):\n self.tcpCliSock = socket(AF_INET, SOCK_STREAM)\n print('Try connect.')\n self.tcpCliSock.connect(ADDR)\n while True:\n message_pid = '1' #确认某id的打印机连接成功\n self.tcpCliSock.send(bytes(message_pid, 'utf-8'))#确认连接成功\n print(message)\n data = self.tcpCliSock.recv(BUFSIZ)\n data = data.decode()\n print(data)\n if not data:\n break\n if data == \"0\":\n print(\"No File\")\n break\n else:\n file_total_size = int(data)\n self.tcpCliSock.send(bytes(message, 'utf-8'))#告知服务器打印文件大小已收到\n print(message)\n received_size = 0\n print(\"写入文件\")\n f = open(\"printfile.gcode\", \"wb\")\n while received_size < file_total_size:\n data = self.tcpCliSock.recv(BUFSIZ)\n f.write(data)\n received_size += len(data)\n print(received_size/file_total_size)\n f.close()\n print(\"Received: \", file_total_size, \" \", received_size)\n if file_total_size == received_size:\n message = '1'\n self.tcpCliSock.send(bytes(message, 'utf-8'))#告知服务器打印文件接收成功并开始打印\n print('接收成功!')\n print_center.print_file_alive = 1\n break\n else:\n message = '0'\n self.tcpCliSock.send(bytes(message, 'utf-8'))\n print('接收失败!')\n self.tcpCliSock.close()\n print('通讯结束')\n\n '''def start_listen(self, print_center):\n print('TCPsever on.')\n while True:\n print('waiting for connection...')\n tcpCliSocket, addr = self.tcpSerSock.accept()\n print('...connected from:', addr)\n while True:\n data = tcpCliSocket.recv(BUFSIZ)\n if not data:\n print('waiting.....')\n break\n else:\n file_total_size = int(data.decode())\n print(\"Filesize:\"+str(file_total_size))\n received_size = 0\n fp = open(\"printfile.gcode\", 'w')\n while received_size <= file_total_size:\n data = self.tcpSerSock.recv(BUFSIZ)\n fp.write(data)\n received_size += len(data)\n print(\"已接收:\", received_size)\n fp.close()\n print(\"receive done\", file_total_size, \" \", received_size)\n if received_size < file_total_size:\n tcpCliSocket.send('0')\n else:\n tcpCliSocket.send('1')\n print(\"Start printing\")\n print_center.print_model()\n break\n\n def close(self):\n self.tcpSerSock.close()'''" }, { "alpha_fraction": 0.584187388420105, "alphanum_fraction": 0.6142020225524902, "avg_line_length": 19.621212005615234, "blob_id": "dd112ea1f8a8886466e23f2d7653e61b7958ca0a", "content_id": "3d0d9faaa166b23e7e746701b493dc516c7d1dcb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1488, "license_type": "no_license", "max_line_length": 80, "num_lines": 66, "path": "/2.0/Main.py", "repo_name": "LyaxKing/My_Printor", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 26 16:24:35 2019\n\n@author: HP\n\"\"\"\nimport Printor_control\nimport socketio\nimport serial\n\n\nportname = \"COM6\"\nbaudrate = 115200\nprintid = '1'\ntem_position = [0, 2]\nsio = socketio.Client()\nps = Printor_control.print_state(printid, portname, baudrate, sio, tem_position)\nsio.connect('tcp://47.96.95.75:7002')\n\n\[email protected]('connect')\ndef on_connect():\n print('连接成功')\n if ps.start():\n statue_json = ps.get_statue_json()\n sio.emit('status', statue_json)\n print(\"打印机上线,发送打印机状态:\")\n else:\n statue_json = ps.get_statue_json()\n sio.emit('status', statue_json)\n print(\"打印机连接失败\")\n print(statue_json)\n\n\[email protected]('file')\ndef on_file(file):\n print(\"接收到打印文件\")\n fp = open(\"printfile.gcode\", 'w')\n fp.writelines(file) \n fp.close() \n gcodelist = ps.read_gcode()\n ps.startprint = 1\n ps.printing = 1\n statue_json = ps.get_statue_json()\n sio.emit('status', statue_json)\n print(statue_json)\n ps.startprint = 0\n print(\"开始打印\") \n ps.print_model(gcodelist)\n \n \[email protected]('status')\ndef on_state():\n ps.tem_get() \n statue_json = ps.get_statue_json()\n sio.emit('status', statue_json)\n print(\"打印机状态发送state\")\n print(statue_json)\n\n\[email protected]('disconnect')#只要在disconnect下发送消息即刻断开连接\ndef on_disconnect():\n print('重新连接')\n\n\nsio.wait() \n\n" }, { "alpha_fraction": 0.6372180581092834, "alphanum_fraction": 0.6372180581092834, "avg_line_length": 34.53333282470703, "blob_id": "cc44e785f0c2fb17e4ebbab35661a75df674bdb7", "content_id": "b9b2fea79a101e2d6ff252ad8ae3088f47e4d01c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 532, "license_type": "no_license", "max_line_length": 57, "num_lines": 15, "path": "/4.0/printorsever/printorsever/view.py", "repo_name": "LyaxKing/My_Printor", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\ndef hello(request):\n context = {}\n context['PrintorControl'] = 'Printor Control'\n context['State'] = 'State'\n context['id'] = 'id:'\n context['alive'] = 'alive:'\n context['printing'] = 'printing:'\n context['endprint'] = 'endprint:'\n context['startprint'] = 'startprint:'\n context['process'] = 'process:'\n context['chambertemperature'] = 'chambertemperature:'\n context['bedtemperature'] = 'bedtemperature:'\n return render(request, 'main.html', context)" }, { "alpha_fraction": 0.52173912525177, "alphanum_fraction": 0.5613811016082764, "avg_line_length": 22.02941131591797, "blob_id": "3dd5e70bc76ed2071414744dff5d16b72ffbcece", "content_id": "9fcedbc2cf4b97d28c88182dfd911497564a3878", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 806, "license_type": "no_license", "max_line_length": 101, "num_lines": 34, "path": "/wifi_ap_change.py", "repo_name": "LyaxKing/My_Printor", "src_encoding": "UTF-8", "text": "import os\nimport bs4\nfrom bs4 import BeautifulSoup\nimport requests\n\nr = requests.get('https://m.dxsbb.com/news/5463.html')\nr.encoding = r.apparent_encoding\ndemo = r.text\n\n\n\ndef gets(ulist,demo):\n soup = BeautifulSoup(demo, 'html.parser')\n t = soup.find_all('tbody')\n for tr in t[1].children:\n if isinstance(tr, bs4.element.Tag):\n tds = tr('td')\n ulist.append([tds[0].string, tds[1].string, tds[2].string, tds[3].string, tds[4].string])\n\n\ndef prints(ulist, num):\n #print('{:^10}\\t{:^10}\\t{:^10}\\t{:^10}\\t{:^10}'.format('排名','大学名称','分数','星级','层次'))\n for i in range(0, num):\n u = ulist[i]\n print(u[0]+' '+u[1]+' '+u[2]+' '+u[3]+' '+u[4])\n\n\n\ndef main():\n uinfo=[]\n gets(uinfo,demo)\n prints(uinfo,20)\n\nmain()" }, { "alpha_fraction": 0.5634469985961914, "alphanum_fraction": 0.5842803120613098, "avg_line_length": 23, "blob_id": "ab6f32fd29ad83afc851d1ea0a151cd9b1c30c53", "content_id": "0ed9aa087040d1a2aa97a254eda77c9bf1d200ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2112, "license_type": "no_license", "max_line_length": 97, "num_lines": 88, "path": "/3.0/Main.py", "repo_name": "LyaxKing/My_Printor", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 2 18:57:51 2019\n\n@author: HP\n\"\"\"\nimport PrintControl\nimport FTPClient\nimport AliyunMqtt\nimport time\nimport _thread\n\nsocket_host_name = 'http://120.79.148.35:7002'\nproductkey = 'a1RJRghvKOW'\ndevicename = 'Yinba_1'\ndevicesecret = 'WUmFrsbg1IWxPPHO1LndP6cx7BPrudk3'\nportname = \"\"\nbaudrate = 115200\nprintid = '1'\ntem_position = [0, 2]\n\noptions = {\n 'productKey': 'a1RJRghvKOW',\n 'deviceName': 'Yinba_1',\n 'deviceSecret': 'WUmFrsbg1IWxPPHO1LndP6cx7BPrudk3',\n 'port': 1883,\n 'host': 'iot-as-mqtt.cn-shanghai.aliyuncs.com'\n}\n\nhost = options['productKey'] + '.' + options['host']\n\n\ndef try_mqtt():\n while True:\n try:\n mqttclient = AliyunMqtt.MqttClient(options, host)\n return mqttclient\n except Exception as e:\n print(e)\n continue\n\n\ndef printor_is_on():\n while True:\n try:\n printcontrol = PrintControl.PrintControl(printid, portname, baudrate, tem_position)\n if printcontrol.is_start():\n printcontrol.tem_get()\n s_json = printcontrol.get_statue_json()\n return printcontrol, s_json\n except Exception as e:\n print(e)\n continue\n\n\ndef get_and_print_gcode(printcontrol, mqttclient):\n FTPClient.connect_ftp_sever()\n FTPClient.login()\n FTPClient.change_file_dir()\n FTPClient.download_gcode()\n mqttclient.check_file = 0\n printcontrol.print_model()\n\n\ndef loop_pc_repotor(mqttclient, printcontrol):\n while True:\n time.sleep(3)\n printcontrol.tem_get()\n statue_json = printcontrol.get_statue_json()\n mqttclient.pubilish_status(statue_json)\n if mqttclient.check_file:\n try:\n if thread.isAlive():\n continue\n else :\n thread.join()\n except Exception as e:\n print(e)\n thread = thread.start_new_thread(get_and_print_gcode,(printcontrol, mqttclient,))\n\n\n\n\nif __name__ == 'main':\n mc = try_mqtt()\n pc, statue_json = printor_is_on()\n mc.pubilish_status(statue_json)\n loop_pc_repotor(mc,pc)\n" }, { "alpha_fraction": 0.6736842393875122, "alphanum_fraction": 0.7315789461135864, "avg_line_length": 26.285715103149414, "blob_id": "0bbf8ea10e1a06f78d35f52ada0dab52601943f4", "content_id": "3441c269a21668785d4cdca1b8dd7e0ec34ac94f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 190, "license_type": "no_license", "max_line_length": 64, "num_lines": 7, "path": "/4.0/print.py", "repo_name": "LyaxKing/My_Printor", "src_encoding": "UTF-8", "text": "import PCC\nbaudrate = 115200\nprintid = '1'\ntem_position = [0, 2]\nportname = '/dev/ttyUSB0'\npc = PCC.PrintControl(printid, portname, baudrate, tem_position)\npc.print_model(filename=\"1.gcode\")" }, { "alpha_fraction": 0.577937662601471, "alphanum_fraction": 0.6011191010475159, "avg_line_length": 22.148147583007812, "blob_id": "112f1c5fee6963a12400c7a386b341c348c8d877", "content_id": "9acca21e73805ee0bb6f2a6ab69c34aaa4928b55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1261, "license_type": "no_license", "max_line_length": 69, "num_lines": 54, "path": "/4.0/main.py", "repo_name": "LyaxKing/My_Printor", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 2 18:57:51 2019\n\n@author: HP\n\"\"\"\nimport PCC\nimport FR\nimport SR\nimport threading\nimport time\n\nbaudrate = 115200\nprintid = '1'\ntem_position = [0, 2]\nportname = '/dev/ttyUSB0'\n#portname = 'COM6'\n\ndef state_send_thread(print_center, state_reportor):\n while True:\n if print_center.printing == 0:\n data = print_center.get_statue_json()\n state_reportor.senddata(data)\n print(\">>>Statue>>>\")\n\n\ndef get_file_thread(print_center, file_receiver):\n while True:\n if print_center.alive == 1 and print_center.printing == 0:\n file_receiver.get_file(print_center)\n if print_center.print_file_alive == 1:\n print('开始打印!')\n p = threading.Thread(target=print_center.print_model)\n p.start()\n time.sleep(10)\n\n\n\n\ndef main():\n pc = PCC.PrintControl(printid, portname, baudrate, tem_position)\n pc.printor_alive()\n fr = FR.FileReceiver()\n sr = SR.StatueReportor()\n ss = threading.Thread(target=state_send_thread, args=(pc, sr))\n gft = threading.Thread(target=get_file_thread, args=(pc, fr))\n ss.start()\n gft.start()\n ss.join()\n gft.join()\n\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.49337849020957947, "alphanum_fraction": 0.5075454115867615, "avg_line_length": 29.037036895751953, "blob_id": "4592c3596997231403d5952bbd4b1aa4bd30c0b9", "content_id": "809d8d29e6216d624588eb75600b6078de5b2569", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3267, "license_type": "no_license", "max_line_length": 92, "num_lines": 108, "path": "/3.0/PrintControl.py", "repo_name": "LyaxKing/My_Printor", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 2 18:57:51 2019\n\n@author: HP\n\"\"\"\nimport serial\nimport re\nimport os\n\n\n\nclass PrintControl:\n alive = 0\n printing = 0\n endprint = 0\n startprint = 0\n process = 0\n chambertemperature = 0\n bedtemperature = 0\n timeout = 0.5\n\n def __init__(self, printid, portname, baudrate, tem_position):\n self.portname = portname\n self.baudrate = baudrate\n self.printid = printid\n self.tem_position = tem_position\n self.ser = serial.Serial(self.portname, self.baudrate, timeout=self.timeout)\n\n def is_start(self):\n # 判断串口是否已经打开\n if self.ser.isOpen():\n self.alive = 1\n return True\n else:\n return False\n\n def tem_get(self):\n print('get tem')\n tem = []\n tem_order = \"M105\\n\".encode('ascii')\n self.ser.write(tem_order)\n while True:\n read_order = self.ser.readline()\n self.ser.flushOutput()\n if (\"ok\" in bytes.decode(read_order) or \"done\" in bytes.decode(read_order)):\n tem = re.findall(r\"\\d+\\.?\\d*\", bytes.decode(read_order))\n if len(tem) == None:\n tem = [0, 0, 0, 0]\n self.chambertemperature = tem[self.tem_position[0]]\n self.bedtemperature = tem[self.tem_position[1]]\n break\n\n def get_statue_json(self):\n statue_json = {\n 'id': self.printid,\n 'on_off': self.alive,\n 'chambertemperature': self.chambertemperature,\n 'bedtemperature': self.bedtemperature,\n 'printing': self.printing,\n 'endprint': self.endprint,\n 'startprint': self.startprint,\n 'process': self.process\n }\n return statue_json\n\n def print_model(self):\n filename = \"printfile.gcode\"\n gcodelist = []\n with open(filename, 'r') as gcodefile:\n temp_gcodelist = gcodefile.readlines()\n for line in temp_gcodelist:\n if not line.startswith(';'):\n gcodelist.append(line)\n i = 0\n j = len(gcodelist)\n for line in gcodelist:\n self.process = i / j * 100\n line = str.encode(line)\n if line == \";End of Gcode\":\n self.printing = 0\n self.endprint = 1\n break\n else:\n self.printing = 1\n self.ser.write(line)\n while True:\n read_order = self.ser.readline()\n if (\"ok\" in bytes.decode(read_order) or \"done\" in bytes.decode(read_order)):\n self.tem_get()\n i = i + 1\n break\n self.endprint = 0\n os.remove(\"printfile.gcode\")\n self.process = 0\n\n def pause_print(self):\n print('Pausing>>>>>>>>>>>>>>>>>>')\n pause_order = \"\\n\".encode('ascii')\n self.ser.write(pause_order)\n i = 0\n while i <= 500:\n read_order = self.ser.readline()\n self.ser.flushOutput()\n if (\"ok\" in bytes.decode(read_order) or \"done\" in bytes.decode(read_order)):\n return True\n i = i+1\n return False\n\n\n\n" }, { "alpha_fraction": 0.5521628260612488, "alphanum_fraction": 0.6386768221855164, "avg_line_length": 25.133333206176758, "blob_id": "e20a2e56490f2f99ec0476b716c1a247e15ce141", "content_id": "a2ba90225603db2e7cc1a0d190f615a9f20fc160", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 393, "license_type": "no_license", "max_line_length": 56, "num_lines": 15, "path": "/4.0/SR.py", "repo_name": "LyaxKing/My_Printor", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom socket import *\nimport json\nhost ='47.96.95.75'\n#host = '192.168.1.110'\nport = 10000\nbufsize = 1024*1024\naddr = (host, port)\nclass StatueReportor:\n def __init__(self):\n self.udptcpCliSock = socket(AF_INET, SOCK_DGRAM)\n\n def senddata(self, data):\n data = bytes(json.dumps(data), encoding='utf-8')\n self.udptcpCliSock.sendto(data, addr)\n\n" }, { "alpha_fraction": 0.420157253742218, "alphanum_fraction": 0.4364546239376068, "avg_line_length": 30.790908813476562, "blob_id": "126f82737c4beaa9e4b69997b362096a4ed97389", "content_id": "ccf7ec3700a1d85fa69eedf36e0cfc45c89a6d9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7217, "license_type": "no_license", "max_line_length": 98, "num_lines": 220, "path": "/1.0/fprint.py", "repo_name": "LyaxKing/My_Printor", "src_encoding": "UTF-8", "text": "\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 13 17:24:00 2019\n\n@author: HP\n\"\"\"\n\nimport socketio\nimport serial\nimport time\nimport re \nimport os\n\nclass print_state:\n printing = 0\n endprint =0 \n startprint = 0\n \nsio = socketio.Client()\nserial = serial.Serial('/dev/ttyUSB0', 250000, timeout=0.5)\nps = print_state()\nprint(\"正在连接服务器\")\n\ndef read_gcode(filename):\n #读取gcode文件,读到list\n gcodelist=[]\n with open(filename,'r') as gcodefile:\n temp_gcodelist = gcodefile.readlines()\n for line in temp_gcodelist:\n if line.startswith(\";\") or \"\\n\" == line:\n continue\n gcodelist.append(line)\n return gcodelist\n\ndef print_model(gcodelist,ser,sio):\n print(\"正在打印\")\n i=0\n j=len(gcodelist)\n for line in gcodelist:\n jindu=i/j\n linebit =str.encode(line)\n if line == \";End of Gcode\":\n ps.printing = 0\n ps.endprint = 1\n break\n else : \n ps.printing = 1 \n print(line)\n ser.write(linebit)\n while True:\n read_order = ser.readline()\n if( \"ok\" in bytes.decode(read_order) or \"done\" in bytes.decode(read_order)):\n print(bytes.decode(read_order))\n temget = str.encode('M105\\n')\n serial.write(temget) \n while True:\n tem_message=serial.readline()\n print(tem_message) \n if( \"ok\" in bytes.decode(tem_message) or \"done\" in bytes.decode(tem_message)):\n tem_message=bytes.decode(tem_message)\n tem = re.findall(r\"\\d+\\.?\\d*\",tem_message)\n print(tem)\n if len(tem) == 0:\n tem = ['0','0','0','0','0']\n payload_json = {\n 'id': 1,\n 'on_off': 1,\n 'status': {\n 'chambertemperature':float(tem[0]),\n 'bedtemperature': float(tem[2])\n },\n 'printing':ps.printing,\n 'endprint':ps.endprint,\n 'startprint':ps.startprint,\n 'jindu':jindu\n }\n sio.emit('status', payload_json)\n i=i+1\n print('Send State:')\n print(payload_json)\n print(\">>>\")\n break\n break \n ps.endprint = 0\n serial.write(temget)\n while True:\n tem_message=serial.readline()\n if( \"ok\" in bytes.decode(read_order) or \"done\" in bytes.decode(read_order)):\n tem_message=bytes.decode(tem_message)\n tem = re.findall(r\"\\d+\\.?\\d*\",tem_message)\n print(tem)\n if len(tem) == 0:\n tem = ['0','0','0','0','0']\n payload_json = {\n 'id': 1,\n 'on_off': 1,\n 'status': {\n 'chambertemperature':float(tem[0]),\n 'bedtemperature': float(tem[2])\n },\n 'printing':ps.printing,\n 'endprint':ps.endprint,\n 'startprint':ps.startprint,\n 'jindu':jindu\n }\n sio.emit('status', payload_json)\n print(\"打印结束,,发送打印机状态:\")\n print(payload_json)\n os.remove(\"printfile.gcode\")\n \n \[email protected]('connect')#连接成功触发汇报树莓派与打印机连接状态\ndef on_connect():\n print('连接成功')\n if serial.isOpen(): \n time.sleep(8)\n serial.readlines()\n serial.flushOutput()\n printmessage_json = {\n 'id': 1,\n 'on_off': 1,\n 'status': {\n 'chambertemperature':0,\n 'bedtemperature': 0\n },\n 'printing':ps.printing,\n 'endprint':ps.endprint,\n 'startprint':ps.startprint\n }\n sio.emit('status', printmessage_json)\n print(\"打印机上线,发送打印机状态:\")\n print(printmessage_json)\n else:\n printmessage_json = {\n 'id': 1,\n 'on_off': 0,\n 'status': {\n 'chambertemperature':0,\n 'bedtemperature': 0,\n },\n 'printing':ps.printing,\n 'endprint':ps.endprint,\n 'startprint':ps.startprint\n }\n sio.emit('status', printmessage_json)\n print(\"打印机连接失败\")\n print(printmessage_json)\n\n\n \[email protected]('file')#\ndef on_file(file):\n print(\"接收到打印文件\")\n sio.emit('file','getting' )\n fp = open(\"printfile.gcode\",'w') \n fp.writelines(file) \n fp.close() \n #sio.emit('file','got' )\n filename = \"printfile.gcode\"\n gcodelist = read_gcode(filename)\n ps.startprint = 1\n ps.printing = 1\n serial.write(\"M105\\n\".encode('ascii') )\n time.sleep(0.5)\n tem_message=serial.readline() \n tem_message=bytes.decode(tem_message)\n tem = re.findall(r\"\\d+\\.?\\d*\",tem_message)\n time.sleep(0.5)\n print(tem)\n if len(tem) == 0:\n tem = ['0','0','0','0','0']\n payload_json = {\n 'id': 1,\n 'on_off': 1,\n 'status': {\n 'chambertemperature':float(tem[0]),\n 'bedtemperature':float(tem[1])\n },\n 'printing':ps.printing,\n 'endprint':ps.endprint,\n 'startprint':ps.startprint\n }\n sio.emit('status', payload_json)\n print(payload_json) \n ps.startprint = 0\n print(\"开始打印\") \n print_model(gcodelist,serial,sio)\n \[email protected]('status')\ndef on_state():\n serial.write(\"M105\\n\".encode('ascii') )\n time.sleep(0.5)\n tem_message=serial.readline()\n tem_message=bytes.decode(tem_message)\n tem = re.findall(r\"\\d+\\.?\\d*\",tem_message)\n time.sleep(1)\n print(tem)\n if len(tem) == 0:\n tem = ['0','0','0','0','0']\n payload_json = {\n 'id': 1,\n 'status': {\n 'chambertemperature':float(tem[0]),\n 'bedtemperature': float(tem[2])\n },\n 'on_off': 1,\n 'printing':ps.printing,\n 'endprint':ps.endprint,\n 'startprint':ps.startprint\n } \n sio.emit('status', payload_json)\n print(\"打印机状态发送state\")\n \[email protected]('disconnect')#只要在disconnect下发送消息即刻断开连接\ndef on_disconnect():\n print('重新连接')\n\n\nsio.connect('http://120.79.148.35:7002')\nsio.wait()\n" }, { "alpha_fraction": 0.6094527244567871, "alphanum_fraction": 0.6169154047966003, "avg_line_length": 38.35293960571289, "blob_id": "755855046ff45dafdacc27e17c7d80ba10ab8ed2", "content_id": "40a13c14df2c7fc71e074ae84a903bf1f88ee5ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2010, "license_type": "no_license", "max_line_length": 119, "num_lines": 51, "path": "/3.0/AliyunMqtt.py", "repo_name": "LyaxKing/My_Printor", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 2 18:57:51 2019\n\n@author: HP\n\"\"\"\nimport aliyunsdkiotclient.AliyunIotMqttClient as iot\nimport time\n\n\nclass MqttClient:\n def __init__(self, options, host):\n self.host = host\n self.options = options\n self.client = iot.getAliyunIotMqttClient(options['productKey'], options['deviceName'], options['deviceSecret'],\n secure_mode=3)\n\n def on_subscribe(client, userdata, mid, granted_qos):\n print(\"On Subscribed: qos = %d\" % granted_qos)\n\n def on_message(self,client, userdata, msg):\n self.check_file = msg.payload\n print(msg.payload)\n\n def on_connect(self,client, userdata, flags_dict, rc):\n print(\"Connected with result code \" + str(rc))\n\n def on_disconnect(self,client, userdata, flags_dict, rc):\n print(\"Disconnected.\")\n topic_gcode = '/sys/' + self.options['productKey'] + '/' + self.options['deviceName'] + '/user/gcode'\n self.client.subscribe(topic_gcode)\n\n def pubilish_status(self, statue_json):\n topic = '/sys/' + self.options['productKey'] + '/' + self.options['deviceName'] + '/thing/event/property/post'\n topic_sever = '/sys/' + self.options['productKey'] + '/' + self.options['deviceName'] + '/user/statue'\n payload_json = {\n 'id': int(time.time()),\n 'params': statue_json,\n 'method': \"thing.event.property.post\"\n }\n print('send data to iot server: ' + str(payload_json))\n self.client.publish(topic, payload=str(payload_json))\n self.client.publish(topic_sever, payload=str(payload_json))\n\n def start_client(self):\n self.client.on_connect = self.on_connect\n self.client.on_disconnect = self.on_disconnect\n self.client.on_message = self.on_message\n self.client.on_subscribe = self.on_subscribe\n self.client.connect(host=self.host, port=self.options['port'], keepalive=60)\n self.client.loop_forever()\n\n\n\n" } ]
12
LorenzoFasolino/AutoRequester
https://github.com/LorenzoFasolino/AutoRequester
2feb1632016a939ac659efe59e57b35c38a7a400
0ce705addf1afbda4506b3e608bac67419c031ea
409d0c9012d8b93605e6e1d9387850d7e51b2050
refs/heads/master
2023-01-02T14:38:49.909635
2020-10-25T21:48:29
2020-10-25T21:48:29
306,068,865
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5951807498931885, "alphanum_fraction": 0.6048192977905273, "avg_line_length": 17, "blob_id": "b6a0b6a057b44f713df257b21e25b6b91837ec19", "content_id": "90a738c06e23172c5b953c0c91fa18fd3e0aa1f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 830, "license_type": "no_license", "max_line_length": 57, "num_lines": 46, "path": "/seleniumTest.py", "repo_name": "LorenzoFasolino/AutoRequester", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom threading import Timer\nimport sys\n\ntimerHasGone = False;\n\ndef stopTimer():\n timerHasGone = True;\n driver.close()\n print(\"stopped\")\n\ndef startTimer(min):\n print(\"starting\")\n timerHasGone = False;\n t = Timer((min * 60.0), stopTimer)\n t.start() \n print(\"started\") \n \n\ndef function ():\n with open(\"Top 50 Alexa sites/top-1m.csv\") as reader:\n\n line = reader.readline()\n while line != '' and (not timerHasGone):\n print(\"fine->\"+ line)\n driver.get(\"http://\"+line)\n line = reader.readline()\n\n\n\n\n\n#avvio il timer\nmin = sys.argv[-1]\n\nif min=='' or min==None: \n\tmin=1\nelse:\n\tmin=int(min)\n\nstartTimer(min) \ndriver = webdriver.Chrome(\"./chromedriver\")\n\n#avvio ciclo infinito\nwhile (not timerHasGone):\n function()\n\n\n" }, { "alpha_fraction": 0.520747721195221, "alphanum_fraction": 0.5359490513801575, "avg_line_length": 36.16030502319336, "blob_id": "e4160638246af310a7976fe36588e7a654103ac1", "content_id": "2e29536a38147cc62705655f53fe08f270658ada", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4869, "license_type": "no_license", "max_line_length": 97, "num_lines": 131, "path": "/jsonAnalysis.py", "repo_name": "LorenzoFasolino/AutoRequester", "src_encoding": "UTF-8", "text": "import sys\nimport urllib\nimport json\nimport time\n\nPORTA_HTTPS = \"443\"\nPORTA_HTTP = \"80\"\nurl = sys.argv[-1]\ncountHttps = 0\ncountHttp = 0\ncountHttp2 = 0\ncountHttp2Settings = 0\ndata = None\nelencoHttp = set()\nelencoHttp2 = set()\ni = 0\n\n\n# prendo il tempo di inizio script\navvio = time.perf_counter()\n\n# metodo utile per leggerere il json che ha chiavi uguali \ndef dict_raise_on_duplicates(ordered_pairs):\n \"\"\"Convert duplicate keys to JSON array.\"\"\"\n d = {}\n for k, v in ordered_pairs:\n if k in d:\n if type(d[k]) is list:\n d[k].append(v)\n else:\n d[k] = [d[k], v]\n else:\n d[k] = v\n return d\n\n\nwith open(url, encoding='utf-8') as file:\n f = file.read()\n data = json.loads(f, object_pairs_hook=dict_raise_on_duplicates)\n\n for d in data:\n tcpDstport = d['_source']['layers']['tcp']['tcp.dstport']\n contenutoLayers = d['_source']['layers']\n\n # controllo i siti http e https\n if tcpDstport == PORTA_HTTPS:\n countHttps += 1\n elif tcpDstport == PORTA_HTTP:\n countHttp += 1\n else:\n print(tcpDstport + \"\")\n\n # prelevo tutti i siti visitati\n if ('http2' in contenutoLayers):\n countHttp2 += 1\n if 'http2.stream' in contenutoLayers['http2']:\n if 'http2.header' in contenutoLayers['http2']['http2.stream']:\n for elem in contenutoLayers['http2']['http2.stream']['http2.header']:\n if elem['http2.header.name'] == \"referer\":\n urlRichiesta2 = \"\"\n http2HeaderValue = elem['http2.header.value']\n if (str(http2HeaderValue).startswith('https://')):\n urlRichiesta2 = str(http2HeaderValue).split(\n 'https://')[1].split('/')[0]\n elif (str(http2HeaderValue).startswith('http://')):\n urlRichiesta2 = str(http2HeaderValue).split(\n 'http://')[1].split('/')[0]\n else:\n urlRichiesta2 = str(http2HeaderValue)\n if urlRichiesta2.strip() != \"\":\n if not urlRichiesta2.startswith('www.'):\n urlRichiesta2 = \"www.\"+urlRichiesta2\n elencoHttp2.add(urlRichiesta2)\n\n elif ('http' in contenutoLayers):\n # cerco \"http.host\":\n urlRichiesta = \"\"\n httpHost = contenutoLayers['http']['http.host']\n if (httpHost.startswith('https://')):\n urlRichiesta = httpHost.split(\n 'https://')[1].split('/')[0]\n elif (httpHost.startswith('http://')):\n urlRichiesta = httpHost.split(\n 'http://')[1].split('/')[0]\n else:\n urlRichiesta = httpHost\n if urlRichiesta.strip() != \"\":\n if not urlRichiesta.startswith('www.'):\n urlRichiesta = \"www.\"+urlRichiesta\n elencoHttp.add(urlRichiesta)\n\n\n# primi 50 siti più visitati al mondo\nelencoSitiIniziali = set()\n# elenco completo siti chiamati\nsitiVisitati = elencoHttp.union(elencoHttp2)\n\n# leggo i 50 siti chiamati da selenium e li memorizzo in un insieme\nwith open('Top 50 Alexa sites/top-1m.csv') as f:\n for line in f.read().splitlines():\n elencoSitiIniziali.add(line)\n\n# salvo i siti chiamati da script\n# i = 1\n# with open(\"result/\"+url.split('.')[0].split('/')[1]+\"_elencoSitiChiamati.txt\", \"w+\") as out:\n# for item in elencoSitiIniziali:\n# out.write(str(i)+\") \"+str(item)+\"\\n\")\n# i += 1\n\n# salvo in un insieme i siti di terze parti\ni = 1\nwith open(\"result/\"+url.split('.')[0].split('/')[1]+\"_elencoSitiTerziChiamati.txt\", \"w+\") as out:\n for item in sitiVisitati.difference(elencoSitiIniziali):\n out.write(str(i)+\") \"+str(item)+\"\\n\")\n i += 1\n\n# prendo il tempo di fine script\nfine = time.perf_counter()\n\nwith open(\"result/\"+url.split('.')[0].split('/')[1]+\"_esito.txt\", \"w+\") as f:\n f.write(\"I pacchetti in totale sono \" + str(len(data)) + \"\\n\")\n f.write(\"I pacchetti https sono \" + str(countHttps) + \"\\n\")\n f.write(\"I pacchetti http2 sono \" + str(countHttp2) + \"\\n\")\n f.write(\"I pacchetti http che non usano ssl sono \" +\n str(countHttp) + \" (\" + (str(len(data)-countHttps)) + \")\\n\")\n f.write(\"I siti di interesse visitati sono \" +\n str(len(elencoSitiIniziali)) + \"\\n\")\n f.write(\"I siti di terze parti visitati sono \" +\n str(len(sitiVisitati.difference(elencoSitiIniziali))) + \"\\n\")\n f.write(\"Lo script ha impiegato \" +\n str(fine-avvio) + \" secondi per essere eseguito\\n\")\n" }, { "alpha_fraction": 0.7208835482597351, "alphanum_fraction": 0.736947774887085, "avg_line_length": 32.266666412353516, "blob_id": "ab242f1cde85e02ce073a688cc0b98c53e12e93a", "content_id": "10d5dbde95bb3d50a046a8f841f288bb27973205", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 498, "license_type": "no_license", "max_line_length": 92, "num_lines": 15, "path": "/README.MD", "repo_name": "LorenzoFasolino/AutoRequester", "src_encoding": "UTF-8", "text": "# ESECUZIONE\n- Avviare Wireshark\n\n- Eseguire prima il test selenium 'seleniumTest.py' indicando la durata del test in minuti\n - es. 'python3 seleniumTest.py 25'\n\n- Stoppare wireshark ed esportare il file JSON\n\n- Copiarlo nella cartella 'jsonFIles'\n - es. 'jsonFiles/25min.json'\n\n- Eseguire 'jsonAnalysis' passando come parametro il percorso del file da analizzare\n - es. 'python3 jsonAnalysis.py jsonFiles/25min.json'\n\n- I risultati saranno visibili nella cartella result" } ]
3
adotchery/Project1
https://github.com/adotchery/Project1
abe2b8a6370603be6c1446f1145dc217de28bb48
1a190c3ea7037f1667aae582d5a23d48b22f8bc7
6e5a72b295f70a2a84d6d128514b434761c54c37
refs/heads/master
2022-08-01T01:04:11.100432
2020-05-18T05:50:55
2020-05-18T05:50:55
261,588,343
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.582524299621582, "alphanum_fraction": 0.5844660401344299, "avg_line_length": 22.953489303588867, "blob_id": "a60c5de9353fdda1962e9b3f6ccbe0fd33de5026", "content_id": "e1d6b595f3bb78a7390e8f8d1f3899dbd7fb0c85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1030, "license_type": "no_license", "max_line_length": 56, "num_lines": 43, "path": "/app/todo.py", "repo_name": "adotchery/Project1", "src_encoding": "UTF-8", "text": "from flask import Flask,request,render_template,session\nfrom flask_session import Session\n\napp=Flask(__name__)\n# app.config[\"SESSION_PERMANENT\"] = False\n# app.config[\"SESSION_TYPE\"] = \"filesystem\"\n\nnotes = []\n# using counter to add ID's\ncounter = 0\[email protected]('/post', methods=['POST'])\ndef event():\n if request.method == 'POST':\n note = request.form.get('note')\n new_note = {\n 'id':counter,\n 'todo':note\n }\n up()\n notes.append(new_note)\n return render_template(\"home.html\", notes=notes)\n\[email protected]('/', methods=['GET'])\ndef find():\n if request.method == 'GET':\n note = request.form.get('note')\n\n return render_template(\"home.html\", notes=notes)\n\[email protected]('/delete', methods=['POST'])\ndef delete():\n for note in notes:\n if id == request.form.get(id):\n notes.remove(note)\n\n return render_template(\"home.html\", notes=notes)\n\ndef up():\n global counter\n counter += 1\n\nif __name__ == \"__main__\":\n app.run()\n" }, { "alpha_fraction": 0.6626722812652588, "alphanum_fraction": 0.6650689244270325, "avg_line_length": 27.775861740112305, "blob_id": "f3ab7f2d92afbb225e20c18cab92b64363ff3a82", "content_id": "2e47717466bca93d0edc416763c9827ca28ceac0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1669, "license_type": "no_license", "max_line_length": 97, "num_lines": 58, "path": "/app/app.py", "repo_name": "adotchery/Project1", "src_encoding": "UTF-8", "text": "from flask import Flask, request, render_template,url_for,redirect\nfrom flask import redirect\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:////Users/alanchery/Desktop/Project1/app/todo.db\"\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\n\ndb = SQLAlchemy(app)\ndb.session.delete\n\nclass Todo(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n text = db.Column(db.String(200))\n complete = db.Column(db.Boolean)\n\[email protected]('/')\ndef index():\n todos = Todo.query.filter_by(complete=False).all()\n\n return render_template('different.html', todos=todos)\n\[email protected]('/')\ndef finished():\n update_todo = Todo.query.filter_by(complete=True).all()\n\n return render_template('different.html', update_todo=update_todo)\n\[email protected]('/plus', methods=['POST'])\ndef add():\n todos = Todo(text=request.form['todoitem'], complete=False)\n db.session.add(todos)\n db.session.commit()\n\n return redirect(url_for('index'))\n\[email protected]('/delete/<int:todo_id>', methods=['POST','GET'])\ndef delete(todo_id):\n # searches for todo in Todo table\n todo_id = Todo.query.filter_by(id=todo_id).all()\n #for the todo selected in todo id, delete that todo ID\n for todo in todo_id:\n db.session.delete(todo)\n #save action\n db.session.commit()\n\n return redirect(url_for('index', todo_id = 'todo.id'))\n\[email protected]('/complete/<id>', methods=['POST','GET'])\ndef complete(id):\n todo = Todo.query.filter_by(id=int(id)).first()\n todo.complete = True\n db.session.commit()\n\n return redirect(url_for('index'))\n\nif __name__ == \"__main__\":\n app.run()\n" }, { "alpha_fraction": 0.5395095348358154, "alphanum_fraction": 0.5449591279029846, "avg_line_length": 18.83783721923828, "blob_id": "90428e06847d3e7b523c4a2924cf31c938674c0c", "content_id": "887d6bc395966bae1d3012b612fa229bd765a068", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 734, "license_type": "no_license", "max_line_length": 76, "num_lines": 37, "path": "/app/Templates/different.html", "repo_name": "adotchery/Project1", "src_encoding": "UTF-8", "text": "{% extends \"layout.html\" %}\n\n{% block heading %}\nTo-Do's\n<h4>Incomplete Items</h4>\n{% endblock %}\n\n{% block body %}\n{% for todo in todos %}\n<ul>\n <li>\n {{ todo.text }} <form action=\"{{url_for('complete', id = todo.id)}}\"\n method=\"post\"><button>Mark as Complete</button>\n </form>\n <form action=\"{{url_for('delete', todo_id = todo.id)}}\" method=\"post\">\n <button>DELETE</button>\n </form>\n </li>\n</ul>\n{% endfor %}\n\n<form action=\"{{url_for('add')}}\" method='post'>\n <input\n type=\"text\"\n name=\"todoitem\"\n placeholder= \"and then...\"/>\n <button>Submit</button>\n</form>\n<h4>Completed Items</h4>\n{% for todo in todos %}\n<ul>\n <li>\n {{ todo.text }}\n </li>\n </ul>\n{% endfor %}\n{% endblock %}\n" } ]
3
haggarw3/neural-networks
https://github.com/haggarw3/neural-networks
ec40520af5d18120343969e534bdd8af6be7c5b0
15da358d67abf978135200fab4fe53f1c603762b
18fae19a50dc9e40056fe686aeea90616d8fa924
refs/heads/master
2020-09-14T00:51:57.755566
2019-11-20T15:48:13
2019-11-20T15:48:13
216,838,714
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5232668519020081, "alphanum_fraction": 0.5280151963233948, "avg_line_length": 31.399999618530273, "blob_id": "8ec15a2a1c970cfcf96eaefdc9a93a3b88a6b494", "content_id": "a0e61dd695d8451cf7b751cdddeddaecacec25bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2106, "license_type": "no_license", "max_line_length": 100, "num_lines": 65, "path": "/advancedRNN.py", "repo_name": "haggarw3/neural-networks", "src_encoding": "UTF-8", "text": "import os\nimport pandas as pd\nimport numpy as np\npd.set_option('display.max_columns', None)\n\n\ndef get_data():\n print(os.getcwd())\n files = os.listdir()\n for file in files:\n if 'time' in file:\n path = os.path.join(os.getcwd(), file)\n readpathfiles = os.listdir(path)\n for x in readpathfiles:\n if 'jena' in x:\n datafile = pd.read_csv(os.path.join(path, x))\n print(datafile.head())\n print(datafile.columns)\n return datafile\n\n\nif __name__ == '__main__':\n data = get_data()\n\n\nfrom sklearn.preprocessing import StandardScaler\nX = data[['p (mbar)', 'T (degC)', 'Tpot (K)', 'Tdew (degC)',\n 'rh (%)', 'VPmax (mbar)', 'VPact (mbar)', 'VPdef (mbar)', 'sh (g/kg)',\n 'H2OC (mmol/mol)', 'rho (g/m**3)', 'wv (m/s)', 'max. wv (m/s)']]\ntransformer = StandardScaler().fit(X)\nx_standardized = transformer.transform(X)\nx_standardized = pd.DataFrame(x_standardized)\nx_standardized['wd (deg)'] = data['wd (deg)']\nprint(x_standardized.shape)\nprint(x_standardized.head())\narray = np.array(x_standardized)\n\n\n# def generator(data, lookback, delay, min_index, max_index, shuffle=False, batch_size=128, step=6):\n# if max_index is None:\n# max_index = len(data) - delay - 1\n# i = min_index + lookback\n# while 1:\n# if shuffle:\n# rows = np.random.randint(\n# min_index + lookback, max_index, size=batch_size)\n# else:\n# if i + batch_size >= max_index:\n# i = min_index + lookback\n# rows = np.arange(i, min(i + batch_size, max_index))\n# i += len(rows)\n#\n# samples = np.zeros((len(rows),\n# lookback // step,\n# data.shape[-1]))\n# targets = np.zeros((len(rows),))\n# for j, row in enumerate(rows):\n# indices = range(rows[j] - lookback, rows[j], step)\n# samples[j] = data[indices]\n# targets[j] = data[rows[j] + delay][1]\n# yield samples, targets\n#\n#\n#\n#\n" }, { "alpha_fraction": 0.6974408626556396, "alphanum_fraction": 0.7204405665397644, "avg_line_length": 31.484210968017578, "blob_id": "62e5bbc9fa87bf5738d8af6053bd4ca784db2d7d", "content_id": "9d6aec391db51fe21ae43ea29a59d7190f5b0106", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3087, "license_type": "no_license", "max_line_length": 112, "num_lines": 95, "path": "/ruetersMultilabelClassification.py", "repo_name": "haggarw3/neural-networks", "src_encoding": "UTF-8", "text": "from keras.datasets import reuters\nimport numpy as np\n(x_train, y_train), (x_test, y_test) = reuters.load_data(num_words=10000)\nprint(x_train.shape)\nprint(x_train[0])\nprint(y_train.shape)\nprint(y_train[0])\nword_index = reuters.get_word_index()\nreverse_word_index = dict([(value, key) for (key, value) in word_index.items()])\ndecoded_newswire = ' '.join([reverse_word_index.get(i - 3, '?') for i in x_train[0]])\n# Index is offset by 3 because indexes 0, 1, and 2 are reserved for padding, start of sequence, unknown\n\n\ndef vectorize_sequences(sequences, dimension=10000):\n results = np.zeros((len(sequences), dimension))\n for i, sequence in enumerate(sequences):\n results[i, sequence] = 1.\n return results\n\n\ndef to_one_hot(labels, dimension=46):\n results = np.zeros((len(labels), dimension))\n for i, label in enumerate(labels):\n results[i, label] = 1.\n return results\n\n\nx_train = vectorize_sequences(x_train)\nx_test = vectorize_sequences(x_test)\none_hot_train_labels = to_one_hot(y_train)\none_hot_test_labels = to_one_hot(y_test)\n\n# Another way to do the same thing as above for the label encoding\nfrom keras.utils.np_utils import to_categorical\none_hot_train_labels = to_categorical(y_train)\none_hot_test_labels = to_categorical(y_test)\n\nfrom keras import models\nfrom keras import layers\n\nmodel = models.Sequential()\nmodel.add(layers.Dense(64, activation='relu', input_shape=(10000,)))\nmodel.add(layers.Dense(64, activation='relu'))\nmodel.add(layers.Dense(46, activation='softmax'))\n\nmodel.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\nx_val = x_train[:1000]\npartial_x_train = x_train[1000:]\n\ny_val = one_hot_train_labels[:1000]\npartial_y_train = one_hot_train_labels[1000:]\n\nhistory = model.fit(partial_x_train, partial_y_train, epochs=20, batch_size=512, validation_data=(x_val, y_val))\nimport matplotlib.pyplot as plt\nprint(history.history.keys())\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(loss) + 1)\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.show()\n\nplt.clf()\n\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.show()\n\nresults = model.evaluate(x_test, one_hot_test_labels)\nprint(results)\nprint(model.metrics_names)\n\ny_train = np.array(y_train)\ny_test = np.array(y_test)\nmodel = models.Sequential()\nmodel.add(layers.Dense(64, activation='relu', input_shape=(10000,)))\nmodel.add(layers.Dense(4, activation='relu'))\nmodel.add(layers.Dense(46, activation='softmax'))\nmodel.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['acc'])\nmodel.fit(partial_x_train, partial_y_train, epochs=20, batch_size=128, validation_data=(x_val, y_val))\n\n" }, { "alpha_fraction": 0.6634061932563782, "alphanum_fraction": 0.6990793943405151, "avg_line_length": 32.403846740722656, "blob_id": "1cc136577151492df9b936a0e174009a2d46f86a", "content_id": "b47edf42fbac825df183a5d5478bf13c5adb4d23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1738, "license_type": "no_license", "max_line_length": 93, "num_lines": 52, "path": "/cnn.py", "repo_name": "haggarw3/neural-networks", "src_encoding": "UTF-8", "text": "import warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nwarnings.simplefilter(action='ignore', category=DeprecationWarning)\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.optimizers import SGD\nimport tensorflow as tf\nimport keras\nimport numpy as np\n\nmnist = tf.keras.datasets.mnist\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n\n# http://yann.lecun.com/exdb/mnist/\nimport matplotlib.pyplot as plt\n\n# plt.imshow(X_train[0])\n# plt.imshow(X_train[0], cmap=plt.cm.binary_r)\n# plt.show()\n\nx_train = keras.utils.normalize(X_train, axis=1)\nx_test = keras.utils.normalize(X_test, axis=1)\n\n# reshape the data to 4D tensor - (samples, x_size, y_size, num of channels) In this case - 1\nx_train = x_train.reshape(x_train.shape[0], 28, 28, 1)\nx_test = x_test.reshape(x_test.shape[0], 28, 28, 1)\n\ny_train = keras.utils.to_categorical(y_train, 10)\ny_test = keras.utils.to_categorical(y_test, 10)\n\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(5, 5), strides=(1, 1),\n activation='relu',\n input_shape=[28, 28, 1]))\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\nmodel.add(Conv2D(64, (5, 5), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(25, activation='relu'))\nmodel.add(Dense(25, activation='relu'))\nmodel.add(Dense(10, activation='softmax'))\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer=SGD(lr=0.01),\n metrics=['accuracy'])\n\nmodel.fit(x_train, y_train, epochs=5)\n\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n\n" }, { "alpha_fraction": 0.7005327343940735, "alphanum_fraction": 0.7271689772605896, "avg_line_length": 32.278480529785156, "blob_id": "ee02a07c66d4143d5d61851cebeb8c135222e98d", "content_id": "8e21c61958555288bb66a56abaa098c5224b96e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2628, "license_type": "no_license", "max_line_length": 123, "num_lines": 79, "path": "/imdbClassificationNN.py", "repo_name": "haggarw3/neural-networks", "src_encoding": "UTF-8", "text": "from keras.datasets import imdb\nfrom keras import models, layers\nfrom keras import optimizers, losses, activations, metrics\nimport pandas as pd\npd.set_option('display.max_rows', 10000)\npd.set_option('display.max_columns', 10000)\nimport numpy as np\n(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=10000)\n# print(x_train)\n# print(x_train[0])\n# print(x_train[0:2])\n\nword_index = imdb.get_word_index()\nprint(word_index)\nprint('\\n')\nreverse_word_index = dict((value, key) for (key,value) in word_index.items())\nprint(reverse_word_index)\nsentence = []\nfor i in x_train[0]:\n sentence.append(reverse_word_index[i])\nprint(sentence)\n\n\ndef vectorize_sequences(sequences, dimension=10000):\n results = np.zeros((len(sequences), dimension))\n for i, sequence in enumerate(sequences):\n results[i, sequence] = 1.\n return results\n\n\nx_train_vector = vectorize_sequences(x_train)\nx_test_vector = vectorize_sequences(x_test)\ny_train = np.asarray(y_train).astype('float32')\ny_test = np.asarray(y_test).astype('float32')\n\nnetwork = models.Sequential()\nnetwork.add(layers.Dense(16, activation='relu', input_shape=(10000,)))\nnetwork.add(layers.Dense(16, activation='relu'))\nnetwork.add(layers.Dense(1, activation='sigmoid'))\n# network.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])\nnetwork.compile(optimizer=optimizers.RMSprop(lr=0.001), loss=losses.binary_crossentropy, metrics=[metrics.binary_accuracy])\nx_val = x_train_vector[:10000]\npartial_x_train = x_train_vector[10000:]\ny_val = y_train[:10000]\npartial_y_train = y_train[10000:]\nmodel = network.fit(partial_x_train, partial_y_train, epochs=20, batch_size=512, validation_data=(x_val, y_val))\nprint(model.history) # it is a dictionary\n\nimport matplotlib.pyplot as plt\n\nhistory_dict = model.history\nloss_values = history_dict['loss']\nval_loss_values = history_dict['val_loss']\nepochs = range(1, len(loss_values) + 1)\nplt.plot(epochs, loss_values, 'bo', label='Training loss')\nplt.plot(epochs, val_loss_values, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.show()\n\nplt.clf() # Clear the previous plot\nacc_values = history_dict['acc']\nval_acc_values = history_dict['val_acc']\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.show()\n\nresults = model.evaluate(x_test, y_test)\nprint('Model evaluated on test data:', results)\nprint('Predictions on the test data are:', model.predict(x_test))" }, { "alpha_fraction": 0.6994727849960327, "alphanum_fraction": 0.7141183614730835, "avg_line_length": 30.629629135131836, "blob_id": "d29b2a20a4dc7b28bc46bcf82571ab378e4063e0", "content_id": "aee30cd18e034cde967c37273180aeb3c89b0808", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1707, "license_type": "no_license", "max_line_length": 97, "num_lines": 54, "path": "/neural-network-challenge1.-tic-tac-toe.py", "repo_name": "haggarw3/neural-networks", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport tensorflow as tf\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nprint(\"This is the original data: \\n\")\ndata = pd.read_csv('tic-tac-toe.csv')\n# data['class'].unique()\nprint(data['class'].value_counts())\nprint(\"The shape is:\", data.shape)\nprint(data.head())\nprint('\\n')\n\n\ndata = pd.get_dummies(data, drop_first=True)\nX = data.iloc[:,1:]\ny = np.where(data['class']==True, 1,0)\n\nprint(\"This is the training data: \\n\")\nX_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.25, random_state=42)\nprint(X_train.head())\nprint(\"The shape is: \", X_train.shape)\nprint('\\n')\n\nprint('Converting the dataframe into an array: \\n')\nxTrain = np.array(X_train)\nxTest = np.array(X_test)\nyTrain = np.array(y_train)\nyTest = np.array(y_test)\n\nprint(\"Building the model: \\n\")\nxTrain = tf.keras.utils.normalize(xTrain, axis=1)\nxTest = tf.keras.utils.normalize(xTest, axis=1)\nmodel = tf.keras.models.Sequential()\nmodel.add(tf.keras.layers.Flatten())\nmodel.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))\nmodel.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))\nmodel.add(tf.keras.layers.Dense(2, activation=tf.nn.softmax))\nmodel.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics=['accuracy'])\nmodel.fit(xTrain, yTrain, epochs=10)\n\nval_loss, val_acc = model.evaluate(xTest, yTest)\n\nmodel.save('tic-tac-toe.model')\nnew_model = tf.keras.models.load_model('tic-tac-toe.model')\npredictions = new_model.predict(xTest)\n\nprint(\"Testing the first 10 predictions of the model: \\n\")\nprint('This is the original test data for Y:',yTest[0:9])\nprint('The predictions are: \\n')\n\nfor i in range(10):\n print(np.argmax(predictions[i]))" }, { "alpha_fraction": 0.8222222328186035, "alphanum_fraction": 0.8222222328186035, "avg_line_length": 37.57143020629883, "blob_id": "90fea9bfbceb29730908cc84736f91852fdd1799", "content_id": "22ac590d8344adbf4f60dca0f0d76c623725ad99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 270, "license_type": "no_license", "max_line_length": 120, "num_lines": 7, "path": "/README.md", "repo_name": "haggarw3/neural-networks", "src_encoding": "UTF-8", "text": "# neural-networks\nNeural Networks Examples\n\nThis repo contains some examples for classifiacation and regression problems for beginners who are trying to understand \nnetworks. The examples are taken from a book by Fracois Collett. \n\nYour contributions and feedback is appreciated\n" }, { "alpha_fraction": 0.6731123328208923, "alphanum_fraction": 0.6933701634407043, "avg_line_length": 30.97058868408203, "blob_id": "7ded1afd390f880b8452d212dee6277732fb5392", "content_id": "d3ae895885f91efef88ee3aad99c07aad26373ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1086, "license_type": "no_license", "max_line_length": 64, "num_lines": 34, "path": "/LSTM_RNN.py", "repo_name": "haggarw3/neural-networks", "src_encoding": "UTF-8", "text": "from keras.datasets import imdb\nfrom keras.preprocessing import sequence\n\nmax_features = 10000\nmaxlen = 500\nbatch_size = 32\n\nprint('Loading data...')\n(input_train, y_train), (input_test, y_test) = imdb.load_data(\n num_words=max_features)\nprint(len(input_train), 'train sequences')\nprint(len(input_test), 'test sequences')\n\nprint('Pad sequences (samples x time)')\ninput_train = sequence.pad_sequences(input_train, maxlen=maxlen)\ninput_test = sequence.pad_sequences(input_test, maxlen=maxlen)\nprint('input_train shape:', input_train.shape)\nprint('input_test shape:', input_test.shape)\nfrom keras.layers import LSTM\nfrom keras.models import Sequential\nfrom keras.layers import Embedding, Flatten, Dense\n\nmodel = Sequential()\nmodel.add(Embedding(max_features, 32))\nmodel.add(LSTM(32))\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(optimizer='rmsprop',\n loss='binary_crossentropy',\n metrics=['acc'])\nhistory = model.fit(input_train, y_train,\n epochs=10,\n batch_size=128,\n validation_split=0.2)" }, { "alpha_fraction": 0.6409716606140137, "alphanum_fraction": 0.6527935266494751, "avg_line_length": 30.510204315185547, "blob_id": "c3c172c19690b3104553a2e978e325cb49855a3d", "content_id": "aa359a891960f790748fdb5990fcb2a3f0060763", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6175, "license_type": "no_license", "max_line_length": 95, "num_lines": 196, "path": "/imdbNLP.py", "repo_name": "haggarw3/neural-networks", "src_encoding": "UTF-8", "text": "##########################################################\nimport numpy as np\nsamples = ['The cat sat on the mat.', 'The dog ate my homework.']\ntoken_index = {}\nfor sample in samples:\n for word in sample.split():\n word = word.lower()\n if word not in token_index:\n token_index[word] = len(token_index) + 1\n\nmax_length = 10\n\nresults = np.zeros(shape=(len(samples),\n max_length,\n max(token_index.values()) + 1))\nfor i, sample in enumerate(samples):\n for j, word in list(enumerate(sample.split()))[:max_length]:\n index = token_index.get(word)\n results[i, j, index] = 1.\n\n##########################################################\n\nfrom keras.preprocessing.text import Tokenizer\n\nsamples = ['The cat sat on the mat.', 'The dog ate my homework.']\n\ntokenizer = Tokenizer(num_words=1000)\ntokenizer.fit_on_texts(samples)\nsequences = tokenizer.texts_to_sequences(samples)\none_hot_results = tokenizer.texts_to_matrix(samples, mode='binary')\nword_index = tokenizer.word_index\nprint('Found %s unique tokens.' % len(word_index))\n\n\n\n##########################################################\n\n\nimport os\n# print('current path is:', os.getcwd())\ncurrent_path = os.getcwd()\ntrain_path = os.path.join(current_path, 'aclImdb', 'train')\ntest_path = os.path.join(current_path, 'aclImdb', 'test')\nreviews = []\nlabels = []\nfor folder in ['pos', 'neg']:\n directory = os.path.join(train_path, folder)\n files = os.listdir(directory)\n for file in files:\n if file.endswith('.txt'):\n path = os.path.join(train_path, folder, file)\n f = open(path, 'r')\n reviews.append(f.read())\n if folder == 'pos':\n labels.append(1)\n else:\n labels.append(0)\n f.close()\n\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nimport numpy as np\n\nmaxlen = 100 # We will cut off the review after 100 words (padding for shorter reviews)\ntraining_samples = 200 # we want to train the model on less data intentionally\nvalidation_samples = 10000\nmax_words = 10000 # Restrict the reviews to the top 10000 most common words\n\ntokenizer = Tokenizer(num_words=max_words)\ntokenizer.fit_on_texts(reviews)\nsequences = tokenizer.texts_to_sequences(reviews)\n\nword_index = tokenizer.word_index\n# word_counts = tokenizer.word_counts\nprint('Found %s unique tokens.' % len(word_index))\n\ndata = pad_sequences(sequences, maxlen=maxlen)\n\nlabels = np.asarray(labels)\nprint('Shape of data tensor:', data.shape)\nprint('Shape of label tensor:', labels.shape)\n\nindices = np.arange(data.shape[0])\nnp.random.shuffle(indices)\ndata = data[indices]\nlabels = labels[indices]\n\nx_train = data[:training_samples]\ny_train = labels[:training_samples]\nx_val = data[training_samples: training_samples + validation_samples]\ny_val = labels[training_samples: training_samples + validation_samples]\n\n# Using a pre-trained word vector data, in 100 dimensions\nglove_dir = os.path.join(os.getcwd(), 'glove')\n\nembeddings_index = {}\nf = open(os.path.join(glove_dir, 'glove.6B.100d.txt'), 'r')\nfor line in f:\n values = line.split()\n word = values[0]\n coefs = np.asarray(values[1:], dtype='float32')\n embeddings_index[word] = coefs\nf.close()\n\nprint('Found %s word vectors.' % len(embeddings_index))\n\nembedding_dim = 100\n\nembedding_matrix = np.zeros((max_words, embedding_dim))\nfor word, i in word_index.items():\n if i < max_words:\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n embedding_matrix[i] = embedding_vector\n\nfrom keras.models import Sequential\nfrom keras.layers import Embedding, Flatten, Dense\n\nmodel = Sequential()\nmodel.add(Embedding(max_words, embedding_dim, input_length=maxlen))\nmodel.add(Flatten())\nmodel.add(Dense(32, activation='relu'))\nmodel.add(Dense(1, activation='sigmoid'))\nprint(model.summary())\n# Loading pretrained word embeddings into the Embedding layer\nmodel.layers[0].set_weights([embedding_matrix])\nmodel.layers[0].trainable = False\nmodel.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])\nhistory = model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_val, y_val))\nmodel.save_weights('pre_trained_glove_model.h5')\n\nimport matplotlib.pyplot as plt\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(acc) + 1)\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()\n\n# Training the model without the pretrained word embeddings\nfrom keras.models import Sequential\nfrom keras.layers import Embedding, Flatten, Dense\n\nmodel = Sequential()\nmodel.add(Embedding(max_words, embedding_dim, input_length=maxlen))\nmodel.add(Flatten())\nmodel.add(Dense(32, activation='relu'))\nmodel.add(Dense(1, activation='sigmoid'))\nmodel.summary()\n\nmodel.compile(optimizer='rmsprop',\n loss='binary_crossentropy',\n metrics=['acc'])\nhistory = model.fit(x_train, y_train,\n epochs=10,\n batch_size=32,\n validation_data=(x_val, y_val))\n\ntest_dir = os.path.join(imdb_dir, 'test')\n\nlabels = []\ntexts = []\n\nfor label_type in ['neg', 'pos']:\n dir_name = os.path.join(test_dir, label_type)\n for fname in sorted(os.listdir(dir_name)):\n if fname[-4:] == '.txt':\n f = open(os.path.join(dir_name, fname))\n texts.append(f.read())\n f.close()\n if label_type == 'neg':\n labels.append(0)\n else:\n labels.append(1)\n\nsequences = tokenizer.texts_to_sequences(texts)\nx_test = pad_sequences(sequences, maxlen=maxlen)\ny_test = np.asarray(labels)\n\nmodel.load_weights('pre_trained_glove_model.h5')\nmodel.evaluate(x_test, y_test)" }, { "alpha_fraction": 0.7140238285064697, "alphanum_fraction": 0.7442713379859924, "avg_line_length": 35.38333511352539, "blob_id": "89d016f51ed6780549c08a4df0493e711d453786", "content_id": "19becd767e5ec6de47946ade74d2ed602ffb6443", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2182, "license_type": "no_license", "max_line_length": 91, "num_lines": 60, "path": "/MNISTclassifiacation.py", "repo_name": "haggarw3/neural-networks", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport warnings\nfrom keras import models, layers\n\nmnist = tf.keras.datasets.mnist\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n# http://yann.lecun.com/exdb/mnist/\n\nprint(X_train.shape)\nprint(len(X_train))\nprint(y_train.shape)\nprint(len(y_train))\n\n# plt.imshow(X_train[0])\n# plt.imshow(X_train[0], cmap=plt.cm.binary_r)\n# plt.show()\n\nnetwork = models.Sequential()\nnetwork.add(layers.Dense(512, activation='relu', input_shape=(28*28,)))\nnetwork.add(layers.Dense(10, activation='softmax'))\nnetwork.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\ntrain_images = X_train.reshape(60000, 28*28)\ntrain_images = train_images.astype('float32')/255\ntest_images = X_test.reshape(10000, 28*28)\ntest_images = test_images.astype('float32')/255\n\nfrom keras.utils import to_categorical\ntrain_labels = to_categorical(y_train)\ntest_labels = to_categorical(y_test)\nnetwork.fit(train_images, train_labels, epochs=5, batch_size=128)\ntest_loss, test_acc = network.evaluate(test_images, test_labels)\nprint('Test accuracy is:', test_acc)\nprint('Network Summary is:', network.summary)\n# network.save('mnist_predictor.model1')\n\n\nprint('METHOD 2\\n\\n')\nX_train = tf.keras.utils.normalize(X_train, axis=1)\nX_test = tf.keras.utils.normalize(X_test, axis=1)\nmodel = tf.keras.models.Sequential()\nmodel.add(tf.keras.layers.Flatten())\nmodel.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))\nmodel.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))\nmodel.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))\nopt = tf.keras.optimizers.Adam(lr=0.001, epsilon=None)\nmodel.compile(optimizer=opt, loss='sparse_categorical_crossentropy', metrics=['accuracy'])\nmodel.fit(X_train, y_train, epochs=4)\nval_loss, val_acc = model.evaluate(X_test, y_test)\nprint('Accuracy: ', val_acc)\nprint(model.summary)\nmodel.save('mnist_predictor.model2')\nnew_model = tf.keras.models.load_model('mnist_predictor.model1')\npredictions = new_model.predict(X_test)\nprint(np.argmax(predictions[0]))\n\nscore = model.evaluate(X_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])" } ]
9
Hoeyboey/Gendered-Language-Correction-Discord-Bot-Heroku
https://github.com/Hoeyboey/Gendered-Language-Correction-Discord-Bot-Heroku
2c2a20204593d17306a5ab7df599faceb93dec92
2d643e635b536d896276d1ff9d265638040d0495
47f71c91bba1afa831a4cc9aa6f8fd2c6dab0a09
refs/heads/master
2020-12-03T03:51:08.228018
2017-06-29T14:10:34
2017-06-29T14:10:34
95,782,077
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7593677043914795, "alphanum_fraction": 0.7606362104415894, "avg_line_length": 47.57345962524414, "blob_id": "b4cadf5874efc864865d06bb48404c38afb7c484", "content_id": "792a33c0cb43c3afe24cbe29055e32b8e62b2ecd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10250, "license_type": "no_license", "max_line_length": 330, "num_lines": 211, "path": "/app.py", "repo_name": "Hoeyboey/Gendered-Language-Correction-Discord-Bot-Heroku", "src_encoding": "UTF-8", "text": "import discord\nimport asyncio\nimport sys\nimport json\nimport os\nimport redis\n\n# Creates the client object - just a key part of the wrapper I'm using for the Discord API\nclient = discord.Client()\nr = redis.from_url(os.environ.get(\"REDIS_URL\"))\n\n# This will be a dictionary of server ids/blacklisted words, just initialised early on. The syntax for a key value pair is:\n# { SERVERID : [[LIST OF BLACKLISTED WORDS], ID OF USERS ABLE TO CHANGE BLACKLIST]}\nblacklists = {}\n\n# This is the list of words that are the default for all servers.\nblacklist = ['DUDE', 'DUDES', 'GUYS']\n\n# Turned this into a list of strings rather than a few lines of code to make some bits easier - will probably read these from a .txt later.\nserverJoinMessages = ['I\\'ve just been invited to your server! Hi! I just need to run through some things with you!', 'First of all, we need to decide what words you want me to call out. By default, we include \"dude\" and \"guys\", but you\\'re able to add any more if you want.', 'Do you want to add any more blacklisted words? Y/N']\n\n# The callout for when someone says a blacklisted word. Currently placeholder, custom responses coming SOON.\nasync def publicVagueCallout(client, message):\n\tawait client.send_message(message.channel, 'Gendered language sucks and alienates people, or worse. Please don\\'t use it!')\n\nasync def viewServerBlacklist(client, message):\n\tcurrentBlacklist = blacklists[message.server.id]\n\tawait client.send_message(message.channel, 'The blacklist for this server is: {}'.format(currentBlacklist[0]))\n\nasync def publiclySpecifyItemToAddToBlacklist(client, message):\n\tmessageAuthor = message.author\n\tserverOwner = message.server.owner\n\tif serverOwner == messageAuthor:\n\t\tawait client.send_message(message.server, 'Alright! Please type the word you want to add to the blacklist.')\n\t\taddToBlacklist = await client.wait_for_message(author=message.author)\n\t\tawait client.add_reaction(addToBlacklist, '✅')\n\t\taddToBlacklistStr = addToBlacklist.content.upper()\n\t\tif addToBlacklistStr not in blacklists[message.server.id][0]:\n\t\t\tblacklists[message.server.id][0].append(addToBlacklistStr)\n\t\t\twriteBlacklistsToFile()\n\t\t\tprint('writebBlacklistsToFile() worked in publiclySpecifyItemToAddToBlacklist')\n\t\t\tawait client.send_message(message.server, 'Okay! Want to add any more? Y/N')\n\t\t\tnewMessage = await client.wait_for_message(author=message.author, check=checkPublicYN)\n\t\t\tif newMessage.content == 'Y':\n\t\t\t\tawait publiclySpecifyItemToRemoveFromBlacklist(client, message)\n\t\t\telse: \n\t\t\t\tawait client.send_message(message.server, 'Alright! Remember you can call what I can do with \\'!help\\'')\n\t\telse:\n\t\t\tawait client.send_message(message.server, 'This word is already in the blacklist!')\n\telse:\n\t\tawait client.send_message(message.server, 'Only the owner of the server can remove words from the blacklist.')\n\t\n\n# This is called when the server owner says !remove, allowing you to remove a word from the blacklaist\nasync def removeItemFromBlacklist(client, message):\n\tmessageAuthor = message.author\n\tserverOwner = message.server.owner\n\tif serverOwner == messageAuthor:\n\t\tawait client.send_message(message.channel, 'Okay, please type the word you want to remove from the blacklist!')\n\t\tmessageToRemove = await client.wait_for_message(author=serverOwner)\n\t\tmessageToRemoveStr = messageToRemove.content.upper()\n\t\tif messageToRemoveStr in blacklists[message.server.id][0]:\n\t\t\tblacklists[message.server.id][0].remove(messageToRemoveStr)\n\t\t\tawait client.send_message(message.channel, 'That word has now been removed!')\n\t\telse:\n\t\t\tawait client.send_message(message.channel, 'Hmm. I couldn\\'t find that one in your blacklist!')\n\telse:\n\t\tawait client.send_message(message.channel, 'Only the owner of the server can remove words from the blacklist!')\n\nasync def addItemToBlacklist(client, message):\n\tmessageAuthor = message.author\n\tserverOwner = message.server.owner\n\tif serverOwner == messageAuthor:\n\t\tawait publiclySpecifyItemToAddToBlacklist(client, message)\n\telse:\n\t\tawait client.send_message(message.channel, 'Only the owner of the server can add words to the blacklist!')\n\n#This updates the Heroku redis - this retains the blacklists between the bot turning off and on again\ndef writeBlacklistsToFile():\n\tfullCurrentBlacklistsString = json.dumps(blacklists)\n\tr.set('blacklist', fullCurrentBlacklistsString)\n\n# When the bot turns on, this runs to update its current blacklists dictionary with whatever is in the Heroku redis\ndef readExistingBlacklists():\n\tfullCurrentBlacklistsString = r.get('blacklist')\n\n\tglobal blacklists\n\tif fullCurrentBlacklistsString == None:\t\n\t\tblacklists = {}\n\telse:\n\t\tblacklists = json.loads(fullCurrentBlacklistsString)\n\n# UGH THE NAME FOR THIS IS AWFUL but it just checks if you've said Y or N to a question that asks for Y or N, need to change it\ndef check(msg):\n\tif msg.channel.is_private:\n\t\tif msg.content == 'Y' or msg.content == 'N':\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\ndef checkPublicYN(msg):\n\tif msg.content == 'Y' or msg.content == 'N':\n\t\treturn True\n\telse:\n\t\treturn False\n\n# AN EVEN WORSE NAME, just checked if your message was sent in a private channel, i.e. DM'd the bot\ndef check2(msg):\n\tif msg.channel.is_private:\n\t\treturn True\n\telse:\n\t\treturn False\n\n# Assuming conditions are met, this will be called to check if the bot should be responding to something. This is partly seperated in case I want to create custom functions later down the line.\nasync def checkIfCommandCalled(client, message):\n\tcurrentBlacklist = blacklists[str(message.server.id)]\n\tfor word in blacklists[message.server.id][0]:\n\t\tif word in message.content.upper() and message.reactions != None:\n\t\t\tawait publicVagueCallout(client, message)\n\t\t\tbreak\n\t\telif message.content == '!remove':\n\t\t\tawait removeItemFromBlacklist(client, message)\n\t\t\tbreak\n\t\telif message.content == '!view':\n\t\t\tawait viewServerBlacklist(client, message)\n\t\t\tbreak\n\t\telif message.content == '!add':\n\t\t\tawait addItemToBlacklist(client, message)\n\t\t\tbreak\n\t\telif message.content == '!help':\n\t\t\tawait publicHelpReply(client, message)\n\t\t\tbreak\n\nasync def privateHelpReply(client, message):\n\tawait client.send_message(message.author, 'If you\\'re the owner of a server I\\'m in, you can use these by typing the keyphrases in that server!')\n\tawait client.send_message(message.author, '!add to add a new word to the blacklist')\n\tawait client.send_message(message.author, '!remove to remove a word from the blacklist')\n\tawait client.send_message(message.author, '!view to see the current blacklist')\n\nasync def publicHelpReply(client, message):\n\tawait client.send_message(message.server, 'Anyone in the server can type !view to see the current blacklist!')\n\tawait client.send_message(message.server, 'The owner of the server can use the following commands:')\t\n\tawait client.send_message(message.server, '!add to add a new word to the blacklist')\n\tawait client.send_message(message.server, '!remove to remove a word from the blacklist')\n\n# Probably the meatiest part of the program - allows you to add new words to the blacklist for your server\nasync def blacklisting(client, serverOwner, serverId):\n\tnewMessage = await client.wait_for_message(author=serverOwner, check=check)\n\tif newMessage.content.upper() == 'Y':\n\t\tawait client.send_message(serverOwner, 'Alright! Please type the word you want to add to the blacklist.')\n\t\taddToBlacklist = await client.wait_for_message(author=serverOwner, check=check2)\n\t\taddToBlacklistStr = addToBlacklist.content.upper()\n\t\tif addToBlacklistStr not in blacklists[serverId][0]:\n\t\t\tblacklists[serverId][0].append(addToBlacklistStr)\n\t\t\twriteBlacklistsToFile()\n\t\telse:\n\t\t\tawait client.send_message(serverOwner, 'This word is already in the blacklist!')\n\t\tawait client.send_message(serverOwner, 'Okay! Want to add any more? Y/N')\n\t\tawait blacklisting(client, serverOwner, serverId)\n\telse:\n\t\tawait client.send_message(serverOwner, 'We\\'re all done then! For help, DM me with \\'!help\\'!')\n\t\n# All of the @client.event bits are working on events with Discord - this one works when the bot boots up and loads correctly.\n# Note - if you've added the bot to a server while this bot is offline, the on_server_join event won't activate, so in on_ready, the for loop checks if that server is already set up and, if not, will set it up to prevent errors.\[email protected]\nasync def on_ready():\n\tprint('I\\'m working!')\n\treadExistingBlacklists()\n\tprint('The redis on startup looks like this:')\n\tredisOnStartup = r.get('blacklist')\n\tprint(redisOnStartup)\n\tserversCurrentlyJoined = client.servers\n\tfor x in serversCurrentlyJoined:\n\t\tif x.id not in blacklists.keys():\n\t\t\tserverOwner = x.owner\n\t\t\tserverId = x.id\n\t\t\tblacklists[serverId] = [list(blacklist), serverOwner.id]\n\t\t\t#writeBlacklistsToFile()\n\t\t\tfor message in serverJoinMessages:\n\t\t\t\tawait client.send_message(serverOwner, message)\n\t\t\tawait blacklisting(client, serverOwner, serverId)\n\n# When the bot joins a server, it updates the blacklist with a new key for that server, and will DM the owner of the server asking if they want to add anything else.\[email protected]\nasync def on_server_join(server):\n\tserverId = str(server.id)\n\tblacklists[serverId] = [list(blacklist), server.owner.id]\n\twriteBlacklistsToFile()\n\tserverOwner = server.owner \n\tfor message in serverJoinMessages:\n\t\tawait client.send_message(serverOwner, message)\n\tawait blacklisting(client, serverOwner, serverId)\n\n# This checks for if you've said a blacklisted word, running every time it sees a message.\[email protected]\nasync def on_message(message):\n\tif message.server != None:\n\t\tif message.author.id != client.user.id:\n\t\t\tawait checkIfCommandCalled(client, message)\n\telse:\n\t\tif message.content == '!help':\n\t\t\tawait privateHelpReply(client, message)\n\t\tif message.content == '!remove':\n\t\t\tawait client.send_message(message.channel, 'You can\\'t do this in DMs! Please type \\'!remove\\' into the server you want to remove a blacklisted word from!')\n\n\nclient.run(sys.argv[1])\n\n# The actual token must be put as an argument so you can't do anything jammy with my bot. I see you.\n# blacklists.json syntax is a dictionary where the key is a server id, value is a list where index 0 is a list of the blacklisted words, index 1 is the server owner's id.\n# Bug: when it joins, it says \"Alright! Remember...\" when you say N to the DM." }, { "alpha_fraction": 0.777222752571106, "alphanum_fraction": 0.777222752571106, "avg_line_length": 65.66666412353516, "blob_id": "8eee4f5f9cc052a4bf17c5bc8da03f7814014d0e", "content_id": "81939e97ce86343eb00852ee15d314d7bbf20e6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1001, "license_type": "no_license", "max_line_length": 268, "num_lines": 15, "path": "/README.md", "repo_name": "Hoeyboey/Gendered-Language-Correction-Discord-Bot-Heroku", "src_encoding": "UTF-8", "text": "# Gendered-Language-Correction-Discord-Bot\n\nBecause I think it's important people are given tools to correct people without putting themselves into hostile situations, this is a Discord bot that monitors the text channels of server it's in, and will call it out if it sees someone say \"Dude\", \"Dudes\", or \"Guys\".\n\nEach server the bot is in has a unique blacklist, which the bot will look for. If a message contains a blacklisted term, the bot will send a message to the server saying that gendered language is bad.\n\nUsing !add, the owner of a server can add a new word to the blacklist. With !remove, the owner of a server can remove a word from the blacklist. Anyone on the server can use !view to see the current blacklist. !help lists the functions.\n\nThat's all, really! It will be hosted online soon, and I'll have an invitation link here then.\n\nUpcoming functions:\n - Custom responses to blacklisted words\n - Giving mods the ability to change the blacklist\n\nWritten in Python, using discord.py!\n\n" }, { "alpha_fraction": 0.4375, "alphanum_fraction": 0.6875, "avg_line_length": 15.5, "blob_id": "c247f94955f0b35af509b00d7196fc96913c8d63", "content_id": "bcbb034881f96d9b432d494275007bc204c5cbaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 32, "license_type": "no_license", "max_line_length": 18, "num_lines": 2, "path": "/requirements.txt", "repo_name": "Hoeyboey/Gendered-Language-Correction-Discord-Bot-Heroku", "src_encoding": "UTF-8", "text": "discord.py==0.16.8\nredis==2.10.5" } ]
3
LewiSamuel/HackathonGlobo2018
https://github.com/LewiSamuel/HackathonGlobo2018
56b82445eaf0de260a5e80ca573165e959aeb062
71ebcbe832924ac122a052e0d96e762765ea62ed
200618551b2377b16671e85bf210112925f4d262
refs/heads/master
2020-03-14T04:23:38.415718
2018-05-03T16:09:56
2018-05-03T16:09:56
131,441,116
4
2
null
null
null
null
null
[ { "alpha_fraction": 0.5573897361755371, "alphanum_fraction": 0.5759608149528503, "avg_line_length": 36.21154022216797, "blob_id": "2c5be5af66391df840f214dcc7134baf6109a313", "content_id": "703857c11cd247b3cbd1d01c3dc9a6a05b2dad1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3877, "license_type": "no_license", "max_line_length": 161, "num_lines": 104, "path": "/python/process.py", "repo_name": "LewiSamuel/HackathonGlobo2018", "src_encoding": "UTF-8", "text": "import operator\nfrom nltk import ngrams, FreqDist\nfrom nltk.tokenize import sent_tokenize, word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.metrics import *\n\nimport pandas as pd\nimport unicodedata\nimport time\n\nfrom firebase import firebase\nfirebase = firebase.FirebaseApplication('https://hackathon-globo-2018.firebaseio.com/', None)\n\nnew_df = pd.read_csv(\"comments_sort_auto.csv\", sep='\\t', encoding='utf-8')\nc_df = new_df['message'].tolist()\n\ntime.sleep(30)\n\ndf_list = []\ndf_list.append(c_df[0:int(len(c_df)/4)])\ndf_list.append(c_df[0:int(len(c_df)/2)])\ndf_list.append(c_df[:])\n\nstopWords = set(stopwords.words('portuguese'))\nstopWords.discard(\"fora\")\nstopWords.update(['.', ',', '\"', \"'\", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}', '\\\\', '#', '%'])\ncount = 0\nfor df in df_list:\n count += 1\n print(count)\n bigStr = []\n comments = []\n orgComments = []\n\n for elem in df:\n if(type(elem) is str):\n temp = str(unicodedata.normalize('NFKD', elem).encode('ascii','ignore'))[2:-1]\n orgComments.append(temp)\n temp = temp.lower()\n # temp = word_tokenize(temp)\n new_temp = list(set(word_tokenize(temp)))\n wordsFiltered = []\n for w in new_temp:\n if w not in stopWords:\n wordsFiltered.append(w)\n bigStr += wordsFiltered\n comments.append(wordsFiltered)\n\n wordsCount = FreqDist(ngrams(bigStr, 1))\n d = dict(wordsCount)\n wordsDict = dict((key[0], value) for (key, value) in d.items())\n\n sortedDict = sorted(wordsDict.items(), key=operator.itemgetter(1), reverse = True)\n\n # print(sortedDict[0:6])\n\n for a in range(0,int(len(sortedDict)/3)):\n for b in range(a+1,int(len(sortedDict)/3)):\n if(edit_distance(sortedDict[a][0], sortedDict[b][0]) <= 1):\n sortedDict[a] = (sortedDict[a][0], (sortedDict[a][1] + sortedDict[b][1]))\n sortedDict[b] = (sortedDict[b][0], 0)\n\n sortedDict = sorted(sortedDict, key=operator.itemgetter(1), reverse = True)\n print(sortedDict[0:6])\n\n medStr = []\n medCount = []\n sortedMedDict = []\n medIndices = []\n for i in range(0, 3):\n medStr.append([])\n medIndices.append([])\n for j in range(0, len(comments)):\n for k in comments[j]:\n if(edit_distance(sortedDict[i][0],k) <= 1):\n medStr[i] += comments[j]\n medIndices[i].append(j)\n break\n medCount.append(FreqDist(ngrams(medStr[i], 1)))\n d = dict(medCount[i])\n medDict = dict((key[0], value) for (key, value) in d.items())\n sortedMedDict.append(sorted(medDict.items(), key=operator.itemgetter(1), reverse = True))\n\n for a in range(0,int(len(sortedMedDict[i])/3)):\n for b in range(a+1,int(len(sortedMedDict[i])/3)):\n if(edit_distance(sortedMedDict[i][a][0], sortedMedDict[i][b][0]) <= 1):\n sortedMedDict[i][a] = (sortedMedDict[i][a][0], (sortedMedDict[i][a][1] + sortedMedDict[i][b][1]))\n sortedMedDict[i][b] = (sortedMedDict[i][b][0], 0)\n\n sortedMedDict[i] = sorted(sortedMedDict[i], key=operator.itemgetter(1), reverse = True)\n\n print(sortedMedDict[i][0:6]) \n print(orgComments[medIndices[i][0]])\n answerFire = []\n for a in range(0, 3):\n vector_temp = []\n for b in range(0, 3):\n vector_temp.append({\"word\":sortedMedDict[a][b+1][0], \"freq\":str(sortedMedDict[a][b+1][1])})\n answerFire.append({\"word\":str(sortedMedDict[a][0][0]),\"freq\":str(sortedMedDict[a][0][1]),\"related\":vector_temp, \"comment\":orgComments[medIndices[a][0]]})\n\n result = {\"name\":\"\"}\n print(firebase.delete('/topico', result[\"name\"]))\n result = firebase.post('/topico', data={\"data\":answerFire})\n print (result)\n \n\n\n" }, { "alpha_fraction": 0.5005120038986206, "alphanum_fraction": 0.52073734998703, "avg_line_length": 32.94782638549805, "blob_id": "482021e3cef0727bdf8e439e7950b04cb6137e8c", "content_id": "f540d5b56a818d0e5f9a479d57c94cf02c58cc4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3907, "license_type": "no_license", "max_line_length": 114, "num_lines": 115, "path": "/src/js/main.js", "repo_name": "LewiSamuel/HackathonGlobo2018", "src_encoding": "UTF-8", "text": "var config = {\n apiKey: \"AIzaSyCuGcOhIL48ul3N9O-DklZ4KKGP4gkK02U\",\n authDomain: \"hackathon-globo-2018.firebaseapp.com\",\n databaseURL: \"https://hackathon-globo-2018.firebaseio.com\",\n storageBucket: \"gs://hackathon-globo-2018.appspot.com\",\n messagingSenderId: \"542963821369\",\n};\nfirebase.initializeApp(config);\n\nvar palavras = [];\n\nChart.defaults.global.tooltips.enabled = false;\n\nvar color = Chart.helpers.color;\nvar horizontalBarChartData = {\n labels: [],\n datasets: [{\n label: 'Relevância',\n backgroundColor: [\"#fb8c00\",\"#ffc107\",\"#ffee58\"],\n borderColor: \"#fb8c00\",\n borderWidth: 1,\n data: [],\n hoverBackgroundColor: [\"#fb8c00aa\",\"#ffc107aa\",\"#ffee58aa\"]\n }]\n\n};\n\nvar database = firebase.database();\nvar starCountRef = firebase.database().ref('twitter');\nstarCountRef.on('value', function(snapshot) {\n if (snapshot.val() != null){\n var child = (Object.values(snapshot.val()))[0]['data'];\n\n palavras = [];\n window.myHorizontalBar.data.labels = []\n window.myHorizontalBar.data.datasets[0].data = []\n child.forEach(element => {\n window.myHorizontalBar.data.labels.push(`${element[\"word\"]} (${element[\"name\"]})`);\n window.myHorizontalBar.data.datasets[0].data.push(element[\"freq\"]);\n palavras.push(element)\n window.myHorizontalBar.update();\n });\n\n }\n\n});\n\n\nwindow.onload = function() {\n var ctx = document.getElementById('canvas').getContext('2d');\n window.myHorizontalBar = new Chart(ctx, {\n type: 'horizontalBar',\n data: horizontalBarChartData,\n showTooltips: false,\n options: {\n // Elements options apply to all of the options unless overridden in a dataset\n // In this case, we are setting the border of each horizontal bar to be 2px wide\n elements: {\n rectangle: {\n borderWidth: 5,\n }\n },\n tooltips: { enabled: false },\n hover: { mode: null },\n responsive: true,\n scaleFontColor: \"#000\",\n color: \"black\",\n legend: {\n position: 'bottom',\n color: \"white\",\n display: false\n },\n title: {\n display: true,\n text: 'Assuntos twitter #HackathonGlobo',\n color: \"white\",\n fontSize: 18\n },\n scales: {\n xAxes: [{\n ticks: {\n beginAtZero:true\n }\n }]\n },\n maintainAspectRatio: true\n\n }\n });\n\n // $(\"#canvas\").click(\n // function (evt) {\n // var activePoints = window.myHorizontalBar.getElementsAtEvent(evt);\n\n // var firstPoint = activePoints[0];\n // var label = window.myHorizontalBar.data.labels[firstPoint._index];\n // var value = window.myHorizontalBar.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];\n // palavras.forEach(element => {\n // if (element[\"word\"] === label){\n\n // window.myHorizontalBar.data.datasets[0].backgroundColor = [\"#00695c\",\"#0097a7\",\"#03a9f4\"];\n // window.myHorizontalBar.data.datasets[0].borderColor = \"#00695c\";\n // window.myHorizontalBar.data.labels = []\n // window.myHorizontalBar.data.datasets[0].data = []\n // element['related'].forEach(elem => {\n // window.myHorizontalBar.data.labels.push(element['word'] + ' ' + elem[\"word\"]);\n // window.myHorizontalBar.data.datasets[0].data.push(elem[\"freq\"]);\n // window.myHorizontalBar.update();\n // });\n // }\n // });\n // }\n // ); \n\n};\n\n\n" }, { "alpha_fraction": 0.7282758355140686, "alphanum_fraction": 0.7682758569717407, "avg_line_length": 59.41666793823242, "blob_id": "d544d4327815aaba5b95fa7d9b1ac677e9e191e2", "content_id": "c572e8a7ece453fc0be468463851fb6a729c95a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 740, "license_type": "no_license", "max_line_length": 203, "num_lines": 12, "path": "/README.md", "repo_name": "LewiSamuel/HackathonGlobo2018", "src_encoding": "UTF-8", "text": "# ComentAI\n\n![Logo](https://image.ibb.co/nQ7fyn/Screen_Shot_2018_05_03_at_13_06_22.png)\n\nFerramenta de curadoria de comentários em tempo real para transmissões ao vivo.\n\nO projeto ganhou segundo lugar no **Hackathon Globo 2018**. Para mais informações sobre o projeto, ver nossa [apresentação](https://drive.google.com/open?id=1udZiGtWOKd-5vjKwt2JuvtaZe5UH7M9vF23higs1zX8).\n\n## Libs\n- [Graph API](https://developers.facebook.com/docs/graph-api?locale=pt_BR): Para extração dos comentários do Facebook em um arquivo ```.csv```\n- [NLTK](https://www.nltk.org/): Para processamento e agrupamento dos comentários em tópicos utilizando NLP\n- [Chart.js](https://www.chartjs.org/): Para visualização dos tópicos em gráficos de barra\n" }, { "alpha_fraction": 0.6004974842071533, "alphanum_fraction": 0.6300994753837585, "avg_line_length": 31.411291122436523, "blob_id": "af2410ae8f4b7b373a3ba0a249c62d6ddb314c38", "content_id": "b1e1e094d0c05faecc99e3254db12d0632b206ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4020, "license_type": "no_license", "max_line_length": 157, "num_lines": 124, "path": "/python/twitter.py", "repo_name": "LewiSamuel/HackathonGlobo2018", "src_encoding": "UTF-8", "text": "import operator\nfrom nltk import ngrams, FreqDist\nfrom nltk.tokenize import sent_tokenize, word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.metrics import *\n\nimport pandas as pd\nimport unicodedata\nimport time\n\nimport tweepy\n\n\n\n \nconsumer_key= 'ZnD0V18VJcdlQkzTcEkOpeNgx'\nconsumer_secret= 'AwARJEnDh5IYV7hlgvmwimbmPEubMMbIXX2RyM2PfCrGLbNWXN'\n \naccess_token='63313336-pheI0pgM5xavuMfU5Hbl6dEAIwSPyBBRUEi0MMpUB'\naccess_token_secret='VYe99X6HQpDD1UGv4UOqyJclAnv9BIIClaMTfADmzu8lV'\n \nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n \napi = tweepy.API(auth)\n \nkw = \"HackathonGlobo\"\n \npublic_tweets = api.search(q = kw, rpp = 5, lang = \"pt\", show_user = False)# since_id = \"990392457937477632\")\n# 990486932433010688\ndf = []\nfor tweet in public_tweets:\n #if(tweet.text[0] != 'R'):\n df.append(tweet.text)\n print(tweet.text)\n print(tweet.user._json['name'])\n\n\nfrom firebase import firebase\nfirebase = firebase.FirebaseApplication('https://hackathon-globo-2018.firebaseio.com/', None)\n\n\n\nstopWords = set(stopwords.words('portuguese'))\nstopWords.discard(\"fora\")\nstopWords.update(['hackathonglobo', '.', ',', '\"', \"'\", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}', '\\\\', '#', '%', 'rt', '@', '...', 'https'])\ncount = 0\n\nbigStr = []\ncomments = []\norgComments = []\n\nfor elem in df:\n if(type(elem) is str):\n temp = str(unicodedata.normalize('NFKD', elem).encode('ascii','ignore'))[2:-1]\n orgComments.append(temp)\n temp = temp.lower()\n # temp = word_tokenize(temp)\n new_temp = list(set(word_tokenize(temp)))\n wordsFiltered = []\n for w in new_temp:\n if w not in stopWords:\n wordsFiltered.append(w)\n bigStr += wordsFiltered\n comments.append(wordsFiltered)\n\n\nwordsCount = FreqDist(ngrams(bigStr, 1))\nd = dict(wordsCount)\nwordsDict = dict((key[0], value) for (key, value) in d.items())\n\nsortedDict = sorted(wordsDict.items(), key=operator.itemgetter(1), reverse = True)\n\n# print(sortedDict[0:6])\n\nfor a in range(0,int(len(sortedDict)/3)):\n for b in range(a+1,int(len(sortedDict)/3)):\n if(edit_distance(sortedDict[a][0], sortedDict[b][0]) <= 1):\n sortedDict[a] = (sortedDict[a][0], (sortedDict[a][1] + sortedDict[b][1]))\n sortedDict[b] = (sortedDict[b][0], 0)\n\nsortedDict = sorted(sortedDict, key=operator.itemgetter(1), reverse = True)\nprint(sortedDict[0:6])\n\nmedStr = []\nmedCount = []\nsortedMedDict = []\nmedIndices = []\nfor i in range(0, 3):\n medStr.append([])\n medIndices.append([])\n for j in range(0, len(comments)):\n for k in comments[j]:\n if(edit_distance(sortedDict[i][0],k) <= 1):\n medStr[i] += comments[j]\n medIndices[i].append(j)\n break\n medCount.append(FreqDist(ngrams(medStr[i], 1)))\n d = dict(medCount[i])\n medDict = dict((key[0], value) for (key, value) in d.items())\n sortedMedDict.append(sorted(medDict.items(), key=operator.itemgetter(1), reverse = True))\n\n for a in range(0,int(len(sortedMedDict[i])/3)):\n for b in range(a+1,int(len(sortedMedDict[i])/3)):\n if(edit_distance(sortedMedDict[i][a][0], sortedMedDict[i][b][0]) <= 1):\n sortedMedDict[i][a] = (sortedMedDict[i][a][0], (sortedMedDict[i][a][1] + sortedMedDict[i][b][1]))\n sortedMedDict[i][b] = (sortedMedDict[i][b][0], 0)\n\n sortedMedDict[i] = sorted(sortedMedDict[i], key=operator.itemgetter(1), reverse = True)\n\n print(sortedMedDict[i][0:6]) \n print(orgComments[medIndices[i][0]])\nanswerFire = []\nfor a in range(0, 3):\n vector_temp = []\n for b in range(0, 3):\n vector_temp.append({\"word\":sortedMedDict[a][b+1][0], \"freq\":str(sortedMedDict[a][b+1][1])})\n answerFire.append({\"word\":str(sortedMedDict[a][0][0]),\"freq\":str(sortedMedDict[a][0][1]),\"related\":vector_temp, \"comment\":orgComments[medIndices[a][0]]})\n\nresult = {\"name\":\"\"}\nprint(firebase.delete('/twitter', result[\"name\"]))\nresult = firebase.post('/twitter', data={\"data\":answerFire})\nprint (result)\ntime.sleep(1)\n " } ]
4
Ma425/ma425.github.io
https://github.com/Ma425/ma425.github.io
15b531cdf7c0eeb7839749e2e34d5da25c31ae11
5558b844f58181f594e50f789759d0b94d12cac5
85f7eb536403a9c9593ccbbd5ed82f2a61b50061
refs/heads/master
2023-01-10T22:40:01.497914
2020-11-14T08:41:47
2020-11-14T08:41:47
197,936,860
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6436170339584351, "alphanum_fraction": 0.6515957713127136, "avg_line_length": 25.85714340209961, "blob_id": "9165df1e7ab67543990f0ef29a678ac003071dec", "content_id": "cac0418735ddba483ab1267d7bdf9f68a3e0060f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 376, "license_type": "no_license", "max_line_length": 50, "num_lines": 14, "path": "/fun_1.py", "repo_name": "Ma425/ma425.github.io", "src_encoding": "UTF-8", "text": "name= input(\"enter your name \\n\")\nweight = float(input(\"enter your weight in kg\\n\"))\nheight = float(input(\"enter your height in m\\n\"))\n\ndef bmi_calculation(name,weight,height):\n bmi=weight/(height**2)\n print(\"bmi\",bmi)\n if(bmi<=25):\n return name + \" not overweight\"\n else:\n return name +\" overweight\"\n\na= bmi_calculation(name,weight,height)\nprint(a)\n" }, { "alpha_fraction": 0.6139896512031555, "alphanum_fraction": 0.6398963928222656, "avg_line_length": 18.350000381469727, "blob_id": "3d59f2a35d9345b8b9bb5c96cdfcea09c419c49a", "content_id": "1e009d2aa6183a7b42e7dfbe8ed723b91935f1bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 386, "license_type": "no_license", "max_line_length": 47, "num_lines": 20, "path": "/fun_2.py", "repo_name": "Ma425/ma425.github.io", "src_encoding": "UTF-8", "text": "def hello_func(greetring):\n return '{} Function.'.format(greetring)\n#print(hello_func(\"hello\"))\n\n\ndef student_info(*args, **kwargs):\n print(args)\n print(kwargs)\n#student_info(\"Math\",\"art\",name='Manil',age=22)\n\n\ncourses=['Math','Art']\ninfo = {'name':'MAnil',\"age\":22}\n#student_info(*courses,**info)\n\n\n`#work\ndef leap_year(year):\n return year % 4 == 0\nprint(leap_year(2020))`" } ]
2
eliaharm/Sublime-text-setings
https://github.com/eliaharm/Sublime-text-setings
e6ec5bc82798c55164c6a6249c34fc75c5f08d26
7bd0731d2ba6b258ab54400892429ffd2d8053e8
062d7a289d9574cd9522bce4d8a8accb4f30a169
refs/heads/master
2021-01-24T11:19:18.277760
2018-10-24T05:41:36
2018-10-24T05:41:36
70,242,009
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 24, "blob_id": "a9836a83811d0db1cd305a6afc7fafd5ec58ebc8", "content_id": "0586a96b33c3b8878d8b6a167a6df73880af76d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 27, "license_type": "no_license", "max_line_length": 24, "num_lines": 1, "path": "/README.md", "repo_name": "eliaharm/Sublime-text-setings", "src_encoding": "UTF-8", "text": "\"# Sublime-text-setings\" \r\n" }, { "alpha_fraction": 0.5713201761245728, "alphanum_fraction": 0.5781487226486206, "avg_line_length": 30.19512176513672, "blob_id": "930bd867288ee6c9e251311b086cbc800370e994", "content_id": "f5d5cf49171630f3b7d5f98db0e536b0a2f71bee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1318, "license_type": "no_license", "max_line_length": 100, "num_lines": 41, "path": "/Packages/User/GitHelper.py", "repo_name": "eliaharm/Sublime-text-setings", "src_encoding": "UTF-8", "text": "# @author Avtandil Kikabidze\r\n# @copyright Copyright (c) 2008-2016, Avtandil Kikabidze aka LONGMAN ([email protected])\r\n# @link http://longman.me\r\n# @license The MIT License (MIT)\r\n\r\nimport sublime\r\nimport sublime_plugin\r\nimport Git.git\r\nimport functools\r\n\r\nclass GitHelperAddCommand(Git.git.GitTextCommand):\r\n\r\n def __init__(self, view):\r\n self.view = view\r\n\r\n def run(self, edit):\r\n self.run_command(['git', 'add', '.'],\r\n functools.partial(self.add_done, \"Committing whole repo\"))\r\n\r\n def add_done(self, message, result):\r\n if result.strip():\r\n sublime.error_message(\"Error adding files: \" + result)\r\n return\r\n\r\n self.view.window().show_input_panel('Commit msg', '', lambda s: self.on_done(s), None, None)\r\n\r\n\r\n def on_done(self, text):\r\n if text.strip() == \"\":\r\n sublime.error_message(\"Commit message is empty!\")\r\n return\r\n\r\n self.run_command(['git', 'commit', '-m', text],\r\n callback=self.update_status)\r\n\r\n def update_status(self, output, **kwargs):\r\n if output.find('nothing to commit, working directory clean') != -1:\r\n sublime.status_message(\"Nothing to commit, working directory clean\")\r\n return\r\n\r\n sublime.status_message(\"Commit success: \"+output)" } ]
2
lab9k/skosprovider_sparql
https://github.com/lab9k/skosprovider_sparql
d1fcf2decce547b88063d8daf92e939b0f1b1d78
cf3640035520bd8a62553d3f3b81ea16430b84ab
0c30273a02313d7b7985f61be544b5f1d6019030
refs/heads/master
2020-03-08T15:35:07.549076
2018-04-17T11:39:06
2018-04-17T11:39:06
128,215,706
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5797705054283142, "alphanum_fraction": 0.5839353799819946, "avg_line_length": 45.31889724731445, "blob_id": "f0365bc24ae101995400be87bb5cfb74f1320a0c", "content_id": "0adc2e3391a2e6cdcedb7474e55294104a9e279e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11765, "license_type": "no_license", "max_line_length": 94, "num_lines": 254, "path": "/providers.py", "repo_name": "lab9k/skosprovider_sparql", "src_encoding": "UTF-8", "text": "from SPARQLWrapper import SPARQLWrapper, JSON\nfrom skosprovider.providers import VocabularyProvider\nfrom skosprovider.skos import Concept, Collection\n\n\nclass SparqlProvider(VocabularyProvider):\n\n def __init__(self, metadata, **kwargs):\n super(SparqlProvider, self).__init__(metadata, **kwargs)\n if 'sparqlEndpoint' not in metadata:\n raise ValueError('Please provide a sparqlEndpoint in the metadata.')\n else:\n self.sparqlEndpoint = metadata['sparqlEndpoint']\n if 'defaultGraph' not in metadata:\n raise ValueError('Please provide a defaultGraph in the metadata.')\n else:\n self.defaultGraph = metadata['defaultGraph']\n self.sparql = SPARQLWrapper(self.sparqlEndpoint)\n self.sparql.addDefaultGraph(self.defaultGraph)\n\n def get_by_id(self, id):\n \"\"\"Get all information on a concept or collection, based on id.\n\n Providers should assume that all id's passed are strings. If a provider\n knows that internally it uses numeric identifiers, it's up to the\n provider to do the typecasting. Generally, this should not be done by\n changing the id's themselves (eg. from int to str), but by doing the\n id comparisons in a type agnostic way.\n\n Since this method could be used to find both concepts and collections,\n it's assumed that there are no id collisions between concepts and\n collections.\n\n :rtype: :class:`skosprovider.skos.Concept` or\n :class:`skosprovider.skos.Collection` or `False` if the concept or\n collection is unknown to the provider.\n \"\"\"\n\n pass\n\n def get_by_uri(self, uri):\n \"\"\"Get all information on a concept or collection, based on a\n :term:`URI`.\n\n :rtype: :class:`skosprovider.skos.Concept` or\n :class:`skosprovider.skos.Collection` or `False` if the concept or\n collection is unknown to the provider.\n \"\"\"\n q = \"\"\"\n PREFIX skos: <http://www.w3.org/2004/02/skos/core#>\n PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n SELECT ?uri, ?label, ?type \n WHERE {\n ?uri skos:prefLabel ?label.\n ?uri rdf:type ?type.\n FILTER (?type IN (skos:Collection, skos:Concept ) )\n FILTER (langmatches(lang(?label), 'nl'))\n FILTER ( ?uri like '%s' )\n } \n \"\"\" % uri\n self.sparql.setQuery(q)\n self.sparql.setReturnFormat(JSON)\n results = self.sparql.queryAndConvert()\n bindings = results[\"results\"][\"bindings\"]\n result = bindings[0]\n t = result[\"type\"][\"value\"][result[\"type\"][\"value\"].index(\"#\") + 1:].lower()\n ret = False\n if t == 'collection':\n ret = Collection(1, uri=result['uri']['value'], labels=[result['label']['value']])\n elif t == 'concept':\n ret = Concept(1, uri=result['uri']['value'], labels=[result['label']['value']])\n return ret\n\n def get_all(self, **kwargs):\n \"\"\"Returns all concepts and collections in this provider.\n\n :param string language: Optional. If present, it should be a\n :term:`language-tag`. This language-tag is passed on to the\n underlying providers and used when selecting the label to display\n for each concept.\n :param string sort: Optional. If present, it should either be `id`,\n `label` or `sortlabel`. The `sortlabel` option means the providers should\n take into account any `sortLabel` if present, if not it will\n fallback to a regular label to sort on.\n :param string sort_order: Optional. What order to sort in: `asc` or\n `desc`. Defaults to `asc`\n\n :returns: A :class:`lst` of concepts and collections. Each of these is a dict\n with the following keys:\n\n * id: id within the conceptscheme\n * uri: :term:`uri` of the concept or collection\n * type: concept or collection\n * label: A label to represent the concept or collection. It is \\\n determined by looking at the `language` parameter, the default \\\n language of the provider and finally falls back to `en`.\n\n \"\"\"\n self.sparql.setQuery(\"\"\"\n PREFIX skos: <http://www.w3.org/2004/02/skos/core#>\n PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n SELECT ?uri, ?label, ?type \n WHERE {\n ?uri skos:prefLabel ?label.\n ?uri rdf:type ?type.\n FILTER (?type IN (skos:Collection, skos:Concept ) )\n FILTER (langmatches(lang(?label), 'nl')) \n } \n \"\"\")\n self.sparql.setReturnFormat(JSON)\n results = self.sparql.queryAndConvert()\n bindings = results[\"results\"][\"bindings\"]\n r = list()\n for d in bindings:\n uri = d[\"uri\"][\"value\"]\n m_type = d[\"type\"][\"value\"][d[\"type\"][\"value\"].index(\"#\") + 1:].lower()\n label = d[\"label\"][\"value\"]\n r.append(dict(uri=uri, type=m_type, label=label))\n return r\n\n def get_top_concepts(self, **kwargs):\n \"\"\"\n Returns all top-level concepts in this provider.\n\n Top-level concepts are concepts that have no broader concepts\n themselves. They might have narrower concepts, but this is not\n mandatory.\n\n :param string language: Optional. If present, it should be a\n :term:`language-tag`. This language-tag is passed on to the\n underlying providers and used when selecting the label to display\n for each concept.\n :param string sort: Optional. If present, it should either be `id`,\n `label` or `sortlabel`. The `sortlabel` option means the providers should\n take into account any `sortLabel` if present, if not it will\n fallback to a regular label to sort on.\n :param string sort_order: Optional. What order to sort in: `asc` or\n `desc`. Defaults to `asc`\n\n :returns: A :class:`lst` of concepts, NOT collections. Each of these\n is a dict with the following keys:\n\n * id: id within the conceptscheme\n * uri: :term:`uri` of the concept or collection\n * type: concept or collection\n * label: A label to represent the concept or collection. It is \\\n determined by looking at the `language` parameter, the default \\\n language of the provider and finally falls back to `en`.\n\n \"\"\"\n self.sparql.setQuery(\"\"\"\n PREFIX skos: <http://www.w3.org/2004/02/skos/core#>\n SELECT *\n WHERE { ?conceptScheme skos:hasTopConcept ?concept. }\n \"\"\")\n self.sparql.setReturnFormat(JSON)\n results = self.sparql.queryAndConvert()\n bindings = results[\"results\"][\"bindings\"]\n concepts = [Concept(id=1, uri=i) for i in [i[\"concept\"][\"value\"] for i in bindings]]\n return concepts\n\n def find(self, query, **kwargs):\n \"\"\"Find concepts that match a certain query.\n\n Currently query is expected to be a dict, so that complex queries can\n be passed. You can use this dict to search for concepts or collections\n with a certain label, with a certain type and for concepts that belong\n to a certain collection.\n\n .. code-block:: python\n\n # Find anything that has a label of church.\n provider.find({'label': 'church'})\n\n # Find all concepts that are a part of collection 5.\n provider.find({'type': 'concept', 'collection': {'id': 5})\n\n # Find all concepts, collections or children of these\n # that belong to collection 5.\n provider.find({'collection': {'id': 5, 'depth': 'all'})\n\n # Find anything that has a label of church.\n # Preferentially display a label in Dutch.\n provider.find({'label': 'church'}, language='nl')\n\n :param query: A dict that can be used to express a query. The following\n keys are permitted:\n\n * `label`: Search for something with this label value. An empty \\\n label is equal to searching for all concepts.\n * `type`: Limit the search to certain SKOS elements. If not \\\n present or `None`, `all` is assumed:\n\n * `concept`: Only return :class:`skosprovider.skos.Concept` \\\n instances.\n * `collection`: Only return \\\n :class:`skosprovider.skos.Collection` instances.\n * `all`: Return both :class:`skosprovider.skos.Concept` and \\\n :class:`skosprovider.skos.Collection` instances.\n * `collection`: Search only for concepts belonging to a certain \\\n collection. This argument should be a dict with two keys:\n\n * `id`: The id of a collection. Required.\n * `depth`: Can be `members` or `all`. Optional. If not \\\n present, `members` is assumed, meaning only concepts or \\\n collections that are a direct member of the collection \\\n should be considered. When set to `all`, this method \\\n should return concepts and collections that are a member \\\n of the collection or are a narrower concept of a member \\\n of the collection.\n\n :param string language: Optional. If present, it should be a\n :term:`language-tag`. This language-tag is passed on to the\n underlying providers and used when selecting the label to display\n for each concept.\n :param string sort: Optional. If present, it should either be `id`,\n `label` or `sortlabel`. The `sortlabel` option means the providers should\n take into account any `sortLabel` if present, if not it will\n fallback to a regular label to sort on.\n :param string sort_order: Optional. What order to sort in: `asc` or\n `desc`. Defaults to `asc`\n\n :returns: A :class:`lst` of concepts and collections. Each of these\n is a dict with the following keys:\n\n * id: id within the conceptscheme\n * uri: :term:`uri` of the concept or collection\n * type: concept or collection\n * label: A label to represent the concept or collection. It is \\\n determined by looking at the `language` parameter, the default \\\n language of the provider and finally falls back to `en`.\n\n \"\"\"\n\n def expand(self, id):\n \"\"\"Expand a concept or collection to all it's narrower\n concepts.\n\n This method should recurse and also return narrower concepts\n of narrower concepts.\n\n If the id passed belongs to a :class:`skosprovider.skos.Concept`,\n the id of the concept itself should be include in the return value.\n\n If the id passed belongs to a :class:`skosprovider.skos.Collection`,\n the id of the collection itself must not be present in the return value\n In this case the return value includes all the member concepts and\n their narrower concepts.\n\n :param id: A concept or collection id.\n :rtype: A list of id's or `False` if the concept or collection doesn't\n exist.\n \"\"\"\n pass\n" }, { "alpha_fraction": 0.6377440094947815, "alphanum_fraction": 0.6832971572875977, "avg_line_length": 41, "blob_id": "f8a60aefcd8a59ff207f5cf9d0c6d357f82cf4bf", "content_id": "20a20d1a64f59877efd9b776cca5758106632e07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 461, "license_type": "no_license", "max_line_length": 108, "num_lines": 11, "path": "/test.py", "repo_name": "lab9k/skosprovider_sparql", "src_encoding": "UTF-8", "text": "from providers import SparqlProvider\n\nif __name__ == '__main__':\n p = SparqlProvider(\n dict(sparqlEndpoint=\"https://qa.stad.gent/sparql\", defaultGraph=\"http://qa.stad.gent/vocabularies\"))\n result = p.get_top_concepts(language=\"nl\", sort=\"label\", sort_order=\"desc\")\n print(result)\n result = p.get_all()\n print(result)\n result = p.get_by_uri(\"http://qa.stad.gent/id/concept/trefwoorden/0a079b8cac93345dc8fb434cf4093294\")\n print(result)" } ]
2
clintsearl/practice-selenium
https://github.com/clintsearl/practice-selenium
b307137e43effebcebdaa6a4957523efe11834f5
5064d0c0deecb0f58b22fb0793bf33dabe0ccaf4
9e73adb079235864c3e0e71314283f2ec4877a83
refs/heads/master
2020-06-19T08:16:39.566200
2019-07-12T19:33:10
2019-07-12T19:33:10
196,634,880
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.48148149251937866, "alphanum_fraction": 0.48148149251937866, "avg_line_length": 19.25, "blob_id": "a96a300731471d60cbc31dd09b136be2acbcd6d6", "content_id": "94ee004223d4c34f7e46ab09e31b4818170eadce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 81, "license_type": "no_license", "max_line_length": 28, "num_lines": 4, "path": "/Readme.md", "repo_name": "clintsearl/practice-selenium", "src_encoding": "UTF-8", "text": "## Selenium Practice ##\n____________________________\n\nLeaning selenium in python\n" }, { "alpha_fraction": 0.7478005886077881, "alphanum_fraction": 0.7536656856536865, "avg_line_length": 19.117647171020508, "blob_id": "631875a24867eb19a35372c5e9c4df71ca39c1d7", "content_id": "474800b846bf6a834af2b7f1961a4d1a6a22a8a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 341, "license_type": "no_license", "max_line_length": 91, "num_lines": 17, "path": "/test.py", "repo_name": "clintsearl/practice-selenium", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom time import sleep as s\n\n\ndriver = webdriver.Chrome()\n\n\ndriver.get(\"https://saltlakecity.gleague.nba.com/archive-getter/?nba_y=&nba_m=&nba_page=1\")\ndriver.implicitly_wait(1)\n\nelement = driver.find_element_by_tag_name(\"ul\")\n\n# print(element.text)\nhtml_page = driver.page_source\nprint(html_page)\n\ndriver.quit" } ]
2
pujahabibi/SDP-Bayes
https://github.com/pujahabibi/SDP-Bayes
782cb1f9900d036e2aaa331bae00f2a26b337303
ae0fdba8b457a589be048af7c0c116923e56b19d
4ea220977556b530e56c1d8f70a3cfa5b5370733
refs/heads/master
2021-07-18T07:34:53.472795
2017-10-26T00:08:27
2017-10-26T00:08:27
105,841,906
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5226209163665771, "alphanum_fraction": 0.5670827031135559, "avg_line_length": 26.89130401611328, "blob_id": "ba2750a196010389d111ddb21840cb34757eafb9", "content_id": "89e9f1b999404241218ce5d90d90b4adfa184b3f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1282, "license_type": "permissive", "max_line_length": 68, "num_lines": 46, "path": "/Defect_Prediction/gradient_descent.py", "repo_name": "pujahabibi/SDP-Bayes", "src_encoding": "UTF-8", "text": "__author__ = 'Kiki Rizki Arpiandi'\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\n\n\nclass model:\n def __init__(self, x,y):\n self.y = y\n self.x = x\n self.theta0 = random.randrange(-5, 5, 1)\n self.theta1 = random.randrange(-5, 5, 1)\n\n def prediksi(self, x):\n return (self.theta1 * x) + self.theta0\n\n def Error(self):\n return np.average((self.prediksi(self.x) - self.y) ** 2) / 2\n\n def delta_J_delta_theta0(self):\n return np.average((self.prediksi(self.x) - self.y))\n\n def delta_J_delta_theta1(self):\n return np.average((self.prediksi(self.x) - self.y) * self.x)\n\n def plot(self):\n plt.plot(self.x, reg.prediksi(self.x))\n plt.plot(self.x, self.y, 'ro')\n plt.show()\n\n def do_gradient_descent(self):\n error = 0\n while (abs(reg.Error() - error) > 0.0000001):\n error = reg.Error()\n temp0 = self.theta0 - 0.01 * reg.delta_J_delta_theta0()\n temp1 = self.theta1 - 0.01 * reg.delta_J_delta_theta1()\n self.theta0 = temp0\n self.theta1 = temp1\n\n\ndata_x = np.array([0., 3., 5., 6., 9.])\ndata_y = np.array([72., 95., 112., 77., 54.])\nreg = model(data_x,data_y)\nreg.do_gradient_descent()\nreg.plot()\nprint(reg.theta1,reg.theta0)" }, { "alpha_fraction": 0.6554622054100037, "alphanum_fraction": 0.6836381554603577, "avg_line_length": 51.558441162109375, "blob_id": "607b12abc4756f54b71afb6cf665de40c301fd22", "content_id": "b71e13abe65c661e93452710bab83596db7a2a4a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4046, "license_type": "permissive", "max_line_length": 112, "num_lines": 77, "path": "/Defect_Prediction/SDP_Bayes_Lib.py", "repo_name": "pujahabibi/SDP-Bayes", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\n\n\ndataset1 = pd.read_csv(\"jEdit_4.0_4.2.csv\")\ndataset2 = pd.read_csv(\"jEdit_4.2_4.3.csv\")\ndataset_target = pd.read_csv(\"petstore_metrics.csv\")\ndataset_target.drop(\"Module\", axis=1, inplace=True)\n\n# print(\"--------------------- Dataset Target ----------------------\")\n# print(dataset_target.head())\n# print(\"--------------------- Dataset jEdit_4.0_4.2 ----------------------\")\n# print(dataset1.head())\n# print(\"--------------------- Dataset jEdit_4.2_4.3 ----------------------\")\n# print(dataset2.head())\n\n#calculate number of class\nn_defect_dataset_1 = dataset1['Class'][dataset1['Class'] == True].count()\nn_non_defect_dataset1 = dataset1['Class'][dataset1['Class'] == False].count()\ntotal_dataset1 = dataset1['Class'].count()\nP_defect_dataset1 = n_defect_dataset_1 / total_dataset1\nP_non_defect_dataset1 = n_non_defect_dataset1 / total_dataset1\n\n\nprint(\"--------------------- Dataset jEdit_4.0_4.2 ----------------------\")\nprint(\"Number of Defect Class: \", n_defect_dataset_1)\nprint(\"Number of Non-Defective Class: \", n_non_defect_dataset1)\nprint(\"Total Of Data On Dataset 1: \", total_dataset1)\nprint(\"Probabillity Of Defective Class On Dataset 1: \", P_defect_dataset1)\nprint(\"Probability Of Non-Defective Class On Dataset 1 : \", P_non_defect_dataset1)\nprint(\"All Attribut Mean:\\n\",dataset1.mean())\nprint(\"All Attribut Mean Based On Module Class:\\n\",dataset1.groupby(\"Class\").mean())\nprint(\"All Attribut Variance Based On Module Class:\\n\",dataset1.groupby(\"Class\").var())\nn_defect_dataset_2 = dataset2['Class'][dataset2['Class'] == True].count()\nn_non_defect_dataset2 = dataset2['Class'][dataset2['Class'] == False].count()\ntotal_dataset2 = dataset2['Class'].count()\nP_defect_dataset2 = n_defect_dataset_2 / total_dataset2\nP_non_defect_dataset2 = n_non_defect_dataset2 / total_dataset2\n\nprint(\"--------------------- Dataset jEdit_4.2_4.3 ----------------------\")\nprint(\"Number of Defect Class: \", n_defect_dataset_2)\nprint(\"Number of Non-Defective Class: \", n_non_defect_dataset2)\nprint(\"Total Of Data On Dataset 1: \", total_dataset2)\nprint(\"Probabillity Of Defective Class On Dataset 2: \", P_defect_dataset2)\nprint(\"Probability Of Non-Defective Class On Dataset 2 : \", P_non_defect_dataset2)\nprint(\"All Attribut Mean:\\n\",dataset2.mean())\nprint(\"All Attribut Mean Based On Module Class:\\n\",dataset2.groupby(\"Class\").mean())\nprint(\"All Attribut Variance Based On Module Class:\\n\",dataset2.groupby(\"Class\").var())\n\n\n#Predict The Dataset Using Scikit-Learn\nfeature_dataset1 = dataset1[['WMC', 'DIT', 'NOC', 'CBO', 'RFC', 'LCOM', 'NPM', 'LOC']]\ntarget_dataset1 = dataset1['Class']\nfeature_dataset2 = dataset2[['WMC', 'DIT', 'NOC', 'CBO', 'RFC', 'LCOM', 'NPM', 'LOC']]\ntarget_dataset2 = dataset2['Class']\nfeature_dataset_target = dataset_target[['WMC', 'DIT', 'NOC', 'CBO', 'RFC', 'LCOM', 'NPM', 'LOC']]\ntarget_dataset_target = dataset_target['Class']\n# feature_dataset2_train, feature_dataset2_test, target_dataset2_train, target_dataset2_test = train_test_split(\n# feature_dataset2, target_dataset2, test_size=0.15, random_state=15)\ngaussian_bayes_classifier = GaussianNB()\nprint(\"------------------------- Dataset jEdit 4.0-4.2 ------------------------\")\nfitting1 = gaussian_bayes_classifier.fit(feature_dataset1, target_dataset1)\nprint(fitting1)\nclassifier_models = gaussian_bayes_classifier.predict(feature_dataset_target)\nprint(classifier_models)\naccuracy_performance = accuracy_score(target_dataset_target, classifier_models)\nprint(accuracy_performance)\nprint(\"------------------------- Dataset jEdit 4.2-4.3 ------------------------\")\nfitting2 = gaussian_bayes_classifier.fit(feature_dataset2, target_dataset2)\nprint(fitting2)\nclassifier_models = gaussian_bayes_classifier.predict(feature_dataset_target)\nprint(classifier_models)\naccuracy_performance = accuracy_score(target_dataset_target, classifier_models)\nprint(accuracy_performance)" } ]
2
Vangmay/Caesar-Cipher-demo
https://github.com/Vangmay/Caesar-Cipher-demo
737839a0d899a47a95043818c374bdcd9521c1f1
39a276d8e3a107cfc925ef83de3ccd38395920c0
d10636c8dcd0cf9d598aeb63e99ba407dac5eadf
refs/heads/main
2023-04-08T07:31:09.165993
2021-04-19T09:52:18
2021-04-19T09:52:18
359,391,457
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6211734414100647, "alphanum_fraction": 0.6237244606018066, "avg_line_length": 41.55555725097656, "blob_id": "5fdf1d5b95e8cf781cc2fbdeb41fd8f53d247b48", "content_id": "559749abce15a5c1f29030524de25225e94b3b36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 784, "license_type": "no_license", "max_line_length": 116, "num_lines": 18, "path": "/cipher.py", "repo_name": "Vangmay/Caesar-Cipher-demo", "src_encoding": "UTF-8", "text": "msg_index = []\r\nAlphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\r\nshift = int(input(\"Enter the number for shift-size\"))\r\nCipher = Alphabet[shift:] + Alphabet[:shift]\r\nmessage = str(input(\"What message do you want to decode \"))\r\ndef split(message):\r\n return [char for char in message]\r\nmessage_split = split(message)\r\n#taking character from split message and switching it to the cipher\r\nfor i in range(0,len(message_split)):\r\n if message_split[i] in Alphabet:\r\n msg_index.append(Alphabet.index(message_split[i]))\r\nnew_message = ''\r\nfor i in range(0,len(msg_index)):\r\n new_message += Cipher[msg_index[i]]\r\nprint('Decrypted: '+ message)\r\nprint('Encrypted: '+ new_message)\r\nprint('Key: ' + str(Cipher))\r\n" } ]
1
qinyao-he/Particle-Picking-Cryo-EM
https://github.com/qinyao-he/Particle-Picking-Cryo-EM
c07a6aa6898a51dc5acc5d4b7853d14bdaa95588
596dce4ddec7396786ec755a1804658e047321e0
9bffcaaa7a2e2d29dd4b27418a516ffc86f9bfcb
refs/heads/master
2021-05-31T13:12:36.822181
2016-04-17T11:14:06
2016-04-17T11:14:06
55,892,852
3
0
null
null
null
null
null
[ { "alpha_fraction": 0.4852237403392792, "alphanum_fraction": 0.5192794799804688, "avg_line_length": 34.88888931274414, "blob_id": "7c00b459668340557198f5abe7f43226af0a8f5d", "content_id": "1c14f931ad3f4eb8fdb2d2e726714f3f4d5ddeba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3553, "license_type": "no_license", "max_line_length": 78, "num_lines": 99, "path": "/gen_data.py", "repo_name": "qinyao-he/Particle-Picking-Cryo-EM", "src_encoding": "UTF-8", "text": "import os\n\nimport numpy as np\nimport scipy.io as sio\nimport skimage.transform\n\n\ndef sliding(img, labels):\n patch_size = 180\n (width, height) = img.shape\n stride = 36\n map_width = int((width - patch_size) / stride + 1)\n map_height = int((height - patch_size) / stride + 1)\n\n distance = (lambda x1, y1, x2, y2: abs(x1 - x2) + abs(y1 - y2))\n\n print(len(labels))\n\n X_negative = np.zeros((map_width, map_height, 64, 64)).astype('uint8')\n y_negative = np.zeros((map_width, map_height)).astype('uint8')\n for i in range(0, map_width):\n for j in range(0, map_width):\n patch = img[i * stride: i * stride + patch_size,\n j * stride: j * stride + patch_size] / 256.0\n X_negative[i, j] = skimage.transform.resize(patch, (64, 64)) * 256\n x_center = i * stride + patch_size / 2\n y_center = j * stride + patch_size / 2\n dist = distance(labels[:, 0], labels[:, 1], x_center, y_center)\n cond = np.where(dist <= 36)[0]\n if (len(cond) == 0):\n y_negative[i, j] = 0\n else:\n y_negative[i, j] = 1\n\n X_negative = X_negative.reshape(-1, 64, 64)\n y_negative = y_negative.reshape(-1)\n X_negative = X_negative[y_negative == 0]\n y_negative = y_negative[y_negative == 0]\n\n X_positive = np.zeros((len(labels) * 3 * 3, 64, 64)).astype('uint8')\n y_positive = np.zeros((len(labels) * 3 * 3)).astype('uint8')\n cnt = 0\n for i in range(len(labels)):\n x = labels[i, 0]\n y = labels[i, 1]\n for i_offset in range(-4, 5, 4):\n for j_offset in range(-4, 5, 4):\n x1 = x + i_offset - patch_size / 2\n x2 = x + i_offset + patch_size / 2\n y1 = y + j_offset - patch_size / 2\n y2 = y + j_offset + patch_size / 2\n if (x1 >= 0 and x2 <= width) and (y1 >= 0 and y2 <= height):\n patch = img[x1:x2, y1:y2] / 256.0\n patch = skimage.transform.resize(patch, (64, 64)) * 256\n X_positive[cnt] = patch\n y_positive[cnt] = 1\n cnt += 1\n\n X_positive = X_positive[y_positive == 1]\n y_positive = y_positive[y_positive == 1]\n\n indices = np.arange(len(X_negative))\n np.random.shuffle(indices)\n X_negative = X_negative[indices]\n y_negative = y_negative[indices]\n\n X = np.concatenate([X_negative[:len(y_positive)], X_positive], axis=0) \\\n .astype('uint8')\n y = np.concatenate([y_negative[:len(y_positive)], y_positive], axis=0) \\\n .astype('uint8')\n print(sum(y == 0), sum(y == 1))\n return (X, y)\n\n\ndef main():\n MAT_PATH = './mat/train'\n LABEL_PATH = './label/train'\n\n train_x = np.zeros((0, 64, 64)).astype('uint8')\n train_y = np.zeros((0)).astype('uint8')\n for dirpath, dirnames, filenames in os.walk(MAT_PATH):\n print(dirpath)\n for filename in filenames:\n if filename == 'full.mat':\n img = sio.loadmat(os.path.join(dirpath, filename))['data']\n img_id = dirpath.split('/')[-1]\n label_file = os.path.join(LABEL_PATH, img_id + '.mat')\n labels = sio.loadmat(label_file)['label']\n X, y = sliding(img, labels)\n train_x = np.concatenate([train_x, X], axis=0)\n train_y = np.concatenate([train_y, y], axis=0)\n sio.savemat('data_new.mat', {\n 'train_x': train_x,\n 'train_y': train_y\n })\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5862413048744202, "alphanum_fraction": 0.6061814427375793, "avg_line_length": 23.463415145874023, "blob_id": "b73169ac1263d8ced97ff6a0f30ab05352efc8dd", "content_id": "a83928fec50f74cd941d5e5d50b05980bd173aab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1003, "license_type": "no_license", "max_line_length": 68, "num_lines": 41, "path": "/svm.py", "repo_name": "qinyao-he/Particle-Picking-Cryo-EM", "src_encoding": "UTF-8", "text": "import os\nimport six\nimport pickle\n\nfrom sklearn.svm import SVC\nfrom sklearn import decomposition\n\nfrom load import load_data\n\n\ndef main():\n six.print_('loading data')\n train_x, train_y, val_x, val_y = load_data()\n train_x = train_x.reshape(-1, 64 * 64)\n val_x = val_x.reshape(-1, 64 * 64)\n six.print_('load data complete')\n\n six.print_('start PCA')\n try:\n pca = pickle.load(open('pca.pickle', 'rb'))\n except:\n pca = decomposition.PCA(n_components=8*8)\n pca.fit(train_x[:])\n train_x = pca.transform(train_x)\n six.print_('PCA complete')\n\n clf = SVC(C=0.0001, kernel='linear', verbose=True, max_iter=100)\n six.print_('start training')\n clf.fit(train_x, train_y)\n six.print_('training complete')\n\n val_x = pca.transform(val_x)\n acc = sum(val_y == clf.predict(val_x)) / float(len(val_y))\n print(acc)\n\n pickle.dump(pca, open('pca.pickle', 'wb'))\n pickle.dump(clf, open('svm.pickle', 'wb'))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4892122447490692, "alphanum_fraction": 0.5504264831542969, "avg_line_length": 38.05882263183594, "blob_id": "d1580d255813805b8db300adc2e792ca1b780dc6", "content_id": "f5e4c455024d91b4f500ed2ffe16ad8c40e186eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1993, "license_type": "no_license", "max_line_length": 76, "num_lines": 51, "path": "/models/vgg.py", "repo_name": "qinyao-he/Particle-Picking-Cryo-EM", "src_encoding": "UTF-8", "text": "from .common import *\n\n\ndef build():\n model = Sequential()\n\n # 64 * 64 * 1\n model.add(Convolution2D(32, 3, 3, border_mode='same', activation='relu',\n init='he_uniform', input_shape=(1, 64, 64)))\n model.add(Convolution2D(32, 3, 3, border_mode='same',\n init='he_uniform', activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n # 32 * 32 * 16\n\n model.add(Convolution2D(64, 3, 3, border_mode='same',\n init='he_uniform', activation='relu'))\n model.add(Convolution2D(64, 3, 3, border_mode='same',\n init='he_uniform', activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n # 16 * 16 * 32\n\n model.add(Convolution2D(128, 3, 3, border_mode='same',\n init='he_uniform', activation='relu'))\n model.add(Convolution2D(128, 3, 3, border_mode='same',\n init='he_uniform', activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n # 8 * 8 * 64\n\n model.add(Convolution2D(256, 3, 3, border_mode='same',\n init='he_uniform', activation='relu'))\n model.add(Convolution2D(256, 3, 3, border_mode='same',\n init='he_uniform', activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n # 4 * 4 * 128\n\n model.add(Convolution2D(512, 3, 3, border_mode='same',\n init='he_uniform', activation='relu'))\n model.add(Convolution2D(512, 3, 3, border_mode='same',\n init='he_uniform', activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n # 2 * 2 * 256\n\n model.add(Flatten())\n model.add(Dropout(0.5))\n model.add(Dense(2048, init='he_uniform', activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(2048, init='he_uniform', activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(1, activation='sigmoid'))\n\n return model\n\n" }, { "alpha_fraction": 0.5965909361839294, "alphanum_fraction": 0.6306818127632141, "avg_line_length": 15, "blob_id": "75b77d789270a22e54e4fb6e6b3f9cbc02bd9b98", "content_id": "106557e9941349fa20e6f5540e69adbff42322a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 176, "license_type": "no_license", "max_line_length": 47, "num_lines": 11, "path": "/models/logistic.py", "repo_name": "qinyao-he/Particle-Picking-Cryo-EM", "src_encoding": "UTF-8", "text": "from .common import *\n\n\ndef build():\n model = Sequential()\n\n model.add(Flatten(input_shape=(1, 64, 64)))\n\n model.add(Dense(1, activation='sigmoid'))\n\n return model\n" }, { "alpha_fraction": 0.8453608155250549, "alphanum_fraction": 0.8556700944900513, "avg_line_length": 47.5, "blob_id": "3a4833394f9857f3ca4a19926ed76e6437343702", "content_id": "d7f5d16ef164e471aeb11ab2316862a6c91375e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 194, "license_type": "no_license", "max_line_length": 60, "num_lines": 4, "path": "/models/common.py", "repo_name": "qinyao-he/Particle-Picking-Cryo-EM", "src_encoding": "UTF-8", "text": "from keras.models import Sequential\nfrom keras.layers import Dense, Activation, Dropout, Flatten\nfrom keras.layers import Convolution2D, MaxPooling2D\nfrom keras.layers import BatchNormalization\n" }, { "alpha_fraction": 0.5892857313156128, "alphanum_fraction": 0.6301020383834839, "avg_line_length": 19.63157844543457, "blob_id": "78d6e5f7955ee7ce42c2a509eb01277e72d108da", "content_id": "15f7092fe6fa83cc748f7e651edcc6c645c55589", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 392, "license_type": "no_license", "max_line_length": 47, "num_lines": 19, "path": "/models/mlp.py", "repo_name": "qinyao-he/Particle-Picking-Cryo-EM", "src_encoding": "UTF-8", "text": "from .common import *\n\n\ndef build():\n model = Sequential()\n\n model.add(Flatten(input_shape=(1, 64, 64)))\n\n model.add(Dense(256, init='he_uniform'))\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n\n model.add(Dense(256, init='he_uniform'))\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n\n model.add(Dense(1, activation='sigmoid'))\n\n return model\n" }, { "alpha_fraction": 0.5209763646125793, "alphanum_fraction": 0.5446224212646484, "avg_line_length": 27.5, "blob_id": "7970c36473287c7c2607c9a56b6239856e9b2f90", "content_id": "9578599ea9643d00a9de923f9ebc9775dffc894d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2622, "license_type": "no_license", "max_line_length": 75, "num_lines": 92, "path": "/cluster.py", "repo_name": "qinyao-he/Particle-Picking-Cryo-EM", "src_encoding": "UTF-8", "text": "import math\nfrom sklearn.cluster import KMeans\nfrom sklearn.cluster import AffinityPropagation\nfrom sklearn.cluster import MeanShift, estimate_bandwidth\nfrom sklearn.cluster import DBSCAN\n\n\ndef distance(x1, y1, x2, y2):\n return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)\n\n\ndef judge(pd_centers, gt_centers):\n TP = 0\n for x in gt_centers:\n for x_ in pd_centers:\n if distance(x[0], x[1], x_[0], x_[1]) < 36:\n TP += 1\n break\n precision = TP / len(pd_centers)\n recall = TP / len(gt_centers)\n f_score = 2 * (precision * recall) / (precision + recall)\n print(len(pd_centers), len(gt_centers), TP, precision, recall, f_score)\n\n\ndef get_list(filename):\n f = open(filename)\n lines = f.readlines()\n res = []\n for l in lines:\n part = (l.strip()).split(' ')\n res.append([int(float(part[0])), int(float(part[1]))])\n return res\n\n\ndef save_list(filename, out_list):\n fout = open(filename, 'w')\n for x, y in out_list:\n fout.write(str(int(y)) + \" \" + str(int(x)) + '\\n')\n fout.close()\n\n\ndef cluster(centers):\n n_class = int(len(centers) * 0.18)\n est = KMeans(n_clusters=n_class, max_iter=1000)\n est.fit(centers)\n new_list = []\n for x, y in est.cluster_centers_:\n min_num = 10000\n min_x = -1\n min_y = -1\n for x_, y_ in centers:\n dist = distance(x, y, x_, y_)\n if (dist < min_num) or (min_x == -1):\n min_num = dist\n min_x = x_\n min_y = y_\n new_list.append([min_x, min_y])\n return new_list\n\n\ndef main():\n centers = get_list('out_center.txt')\n labels = get_list('142-label.txt')\n judge(centers, labels)\n n_class = int(len(centers) * 0.18)\n est = KMeans(n_clusters=n_class, max_iter=1000)\n est.fit(centers)\n new_list = []\n for x, y in est.cluster_centers_:\n min_num = 10000\n min_x = -1\n min_y = -1\n for x_, y_ in centers:\n dist = distance(x, y, x_, y_)\n if (dist < min_num) or (min_x == -1):\n min_num = dist\n min_x = x_\n min_y = y_\n new_list.append([min_x, min_y])\n judge(new_list, labels)\n judge(est.cluster_centers_, labels)\n\n # db = DBSCAN(eps=0.3, min_samples=180).fit(centers)\n # print(db.core_sample_indices_)\n # judge(new_list, labels)\n # print(est.cluster_centers_)\n # save_list('result.txt', est.cluster_centers_)\n # af = AffinityPropagation(preference=180).fit(centers)\n # judge(af.cluster_centers_, labels)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.506056547164917, "alphanum_fraction": 0.5208613872528076, "avg_line_length": 27.576923370361328, "blob_id": "cc064f12ff291ff190ab448e49dcd1db878f7fa6", "content_id": "4d0a634b3961a5695cb025f77e5d23be3702d170", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 743, "license_type": "no_license", "max_line_length": 73, "num_lines": 26, "path": "/merge_mat.py", "repo_name": "qinyao-he/Particle-Picking-Cryo-EM", "src_encoding": "UTF-8", "text": "import os\n\nimport numpy as np\nimport scipy.io as sio\n\n\ndef main():\n MAT_DIR = './mat_new/train'\n train_x = np.zeros((0, 64, 64)).astype('uint8')\n train_y = np.zeros((0)).astype('uint8')\n for dirpath, dirnames, filenames in os.walk(MAT_DIR):\n print(dirpath)\n for filename in filenames:\n if filename == 'train.mat':\n data = sio.loadmat(os.path.join(dirpath, filename))\n train_x = np.append(train_x, data['train_x'], axis=0)\n train_y = np.append(train_y, data['train_y'].reshape(-1),\n axis=0)\n sio.savemat('data_new.mat', {\n 'train_x': train_x,\n 'train_y': train_y\n })\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4831838607788086, "alphanum_fraction": 0.5437219738960266, "avg_line_length": 30.85714340209961, "blob_id": "fe03d62fd42a8901f79c06d1f79185b18288639a", "content_id": "87f4a6b7626f8b4614b257c528960d22fef6d582", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 892, "license_type": "no_license", "max_line_length": 75, "num_lines": 28, "path": "/models/strange_cnn.py", "repo_name": "qinyao-he/Particle-Picking-Cryo-EM", "src_encoding": "UTF-8", "text": "from .common import *\n\n\ndef build():\n model = Sequential()\n\n # 64 * 64 * 1\n model.add(Convolution2D(8, 7, 7, border_mode='same', activation='relu',\n init='he_uniform',\n subsample=(2, 2), input_shape=(1, 64, 64)))\n # 32 * 32 * 8\n\n model.add(Convolution2D(8, 5, 5, border_mode='same',\n init='he_uniform', activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n # 16 * 16 * 16\n\n model.add(Convolution2D(8, 3, 3, border_mode='same',\n init='he_uniform', activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n # 8 * 8 * 32\n\n model.add(Flatten())\n model.add(Dense(1024, init='he_uniform', activation='relu'))\n model.add(Dense(1024, init='he_uniform', activation='relu'))\n model.add(Dense(1, activation='sigmoid'))\n\n return model\n" }, { "alpha_fraction": 0.4700554609298706, "alphanum_fraction": 0.49852126836776733, "avg_line_length": 32.60248565673828, "blob_id": "a3bb2b6c9ff3946e09e0f205236208c6b9fb668a", "content_id": "5fab19133eb0b986ac6d7a9896c0ee7deac337ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5410, "license_type": "no_license", "max_line_length": 79, "num_lines": 161, "path": "/detection.py", "repo_name": "qinyao-he/Particle-Picking-Cryo-EM", "src_encoding": "UTF-8", "text": "import os\nimport six\nimport pickle\n\nimport numpy as np\nimport scipy.io as sio\nimport skimage.transform\nimport matplotlib\n\nfrom cluster import cluster\n\nlogsitc_model = None\nvgg_model = None\n\n\ndef init_model():\n global logsitc_model\n global vgg_model\n import models.logistic\n logsitc_model = models.logistic.build()\n logsitc_model.compile(loss='binary_crossentropy', optimizer='sgd')\n logsitc_model.load_weights('logistic.hdf5')\n\n import models.vgg\n vgg_model = models.vgg.build()\n vgg_model.compile(loss='binary_crossentropy', optimizer='sgd')\n vgg_model.load_weights('vgg.hdf5')\n\n\ndef prediction(model, img_batch):\n img_batch = np.reshape(img_batch, (-1, 1, 64, 64))\n predict = model.predict(img_batch, verbose=0)\n return predict\n\n\ndef non_max_suppression(centers, threshold):\n if len(centers) == 0:\n return []\n\n pick = []\n x1 = centers[:, 0] - 90\n y1 = centers[:, 1] - 90\n x2 = centers[:, 0] + 90\n y2 = centers[:, 1] + 90\n idxs = np.argsort(y2)\n\n while len(idxs) > 0:\n last = len(idxs) - 1\n i = idxs[last]\n pick.append(i)\n\n xx1 = np.maximum(x1[i], x1[idxs[:last]])\n yy1 = np.maximum(y1[i], y1[idxs[:last]])\n xx2 = np.minimum(x2[i], x2[idxs[:last]])\n yy2 = np.minimum(y2[i], y2[idxs[:last]])\n\n w = np.maximum(0, xx2 - xx1 + 1)\n h = np.maximum(0, yy2 - yy1 + 1)\n\n overlap = w * h / float(180 * 180)\n\n idxs = np.delete(idxs, np.concatenate(([last],\n np.where(overlap > threshold)[0])))\n\n return centers[pick].astype(\"int\")\n\n\ndef detection(img):\n PATCH_SIZE = 180\n (width, height) = img.shape\n stride = 10\n map_width = int((width - PATCH_SIZE) / stride + 1)\n map_height = int((height - PATCH_SIZE) / stride + 1)\n\n img_batch = np.zeros((map_width, map_height, 64, 64))\n for i in range(0, map_width):\n for j in range(0, map_width):\n patch = img[i * stride: i * stride + PATCH_SIZE,\n j * stride: j * stride + PATCH_SIZE] / 256.0\n img_batch[i, j] = skimage.transform.resize(patch, (64, 64))\n\n img_batch = img_batch.reshape(-1, 64, 64)\n predict_map = prediction(logsitc_model, img_batch)\n predict_map = predict_map.reshape((map_width, map_height))\n\n candicates = []\n img_batch = np.zeros((0, 64, 64))\n for i in range(0, map_width):\n for j in range(0, map_width):\n if predict_map[i, j] > 0.8:\n patch = img[i * stride: i * stride + PATCH_SIZE,\n j * stride: j * stride + PATCH_SIZE] / 256.0\n patch = skimage.transform.resize(patch, (64, 64))\n img_batch = np.append(img_batch, patch.reshape(1, 64, 64))\n candicates.append((i * stride + PATCH_SIZE / 2,\n j * stride + PATCH_SIZE / 2))\n\n predict = prediction(vgg_model, img_batch).reshape(-1)\n candicates = np.array(candicates)\n result = candicates[predict > 0.95]\n return result\n\n\ndef main():\n # matplotlib.use('qt5agg')\n import matplotlib.pyplot as plt\n from matplotlib.patches import Rectangle\n\n init_model()\n MAT_DIR = './mat/test'\n LABEL_DIR = './label/test'\n for dirpath, dirnames, filenames in os.walk(MAT_DIR):\n print(dirpath)\n for filename in filenames:\n if filename == 'full.mat':\n data = sio.loadmat(os.path.join(dirpath, filename))\n img = data['data']\n centers = detection(img)\n img_id = dirpath.split('/')[-1]\n label_file = os.path.join(LABEL_DIR, img_id + '.mat')\n labels = sio.loadmat(label_file)['label']\n distance = (lambda x1, y1, x2, y2: abs(x1 - x2) + abs(y1 - y2))\n\n centers = cluster(centers)\n\n TP = 0\n for x, y in labels:\n for x_, y_ in centers:\n if distance(x, y, x_, y_) < 36:\n TP += 1\n break\n precision = float(TP) / len(centers)\n recall = float(TP) / len(labels)\n f_score = 2 * (precision * recall) / (precision + recall)\n six.print_(precision, recall, f_score)\n\n f = open(dirpath.split('/')[-1] + '-predict.txt', 'w')\n for x, y in centers:\n f.write(str(x) + ' ' + str(y) + '\\n')\n f.close()\n f = open(dirpath.split('/')[-1] + '-label.txt', 'w')\n for x, y in labels:\n f.write(str(x) + ' ' + str(y) + '\\n')\n f.close()\n\n # img = img / np.float32(256)\n # plt.imshow(img, cmap=plt.cm.gray)\n # currentAxis = plt.gca()\n # for x, y in labels:\n # currentAxis.add_patch(Rectangle((y - 90, x - 90),\n # 180, 180, fill=None,\n # alpha=1, color='blue'))\n # for x, y in centers:\n # currentAxis.add_patch(Rectangle((y - 90, x - 90),\n # 180, 180, fill=None,\n # alpha=1, color='red'))\n # plt.show()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5786885023117065, "alphanum_fraction": 0.6032786965370178, "avg_line_length": 23.399999618530273, "blob_id": "9c1d7ef6e4ab04e9550233913afc9979d22e78c5", "content_id": "50bab32cdf7bc5762ce829315aa3e608c89f3a3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 610, "license_type": "no_license", "max_line_length": 63, "num_lines": 25, "path": "/load.py", "repo_name": "qinyao-he/Particle-Picking-Cryo-EM", "src_encoding": "UTF-8", "text": "import numpy as np\nimport scipy.io as sio\n\n\ndef load_data():\n MAT_FILE = 'data_new.mat'\n\n data = sio.loadmat(MAT_FILE)\n\n train_x = data['train_x'].reshape(-1, 1, 64, 64)\n train_y = data['train_y'].reshape(-1)\n\n indices = np.arange(len(train_x))\n np.random.shuffle(indices)\n train_x = train_x[indices]\n train_y = train_y[indices]\n\n valid_len = int(len(train_x) / 10)\n\n train_x = train_x / np.float32(256.0)\n\n train_x, val_x = train_x[:-valid_len], train_x[-valid_len:]\n train_y, val_y = train_y[:-valid_len], train_y[-valid_len:]\n\n return (train_x, train_y, val_x, val_y)\n" }, { "alpha_fraction": 0.6198998093605042, "alphanum_fraction": 0.6313529014587402, "avg_line_length": 28.10416603088379, "blob_id": "06e8573cb1af14a81724b4f47a39bda71fd897b5", "content_id": "c0a2adf0978e4e84062e1773192bf82d960c8316", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1397, "license_type": "no_license", "max_line_length": 75, "num_lines": 48, "path": "/train.py", "repo_name": "qinyao-he/Particle-Picking-Cryo-EM", "src_encoding": "UTF-8", "text": "import os\nimport six\nimport argparse\nimport importlib\n\nimport keras\n\nfrom keras.optimizers import SGD\n\nfrom load import load_data\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Train a neural network')\n\n parser.add_argument('--model', type=str)\n parser.add_argument('--lr', type=float, default=0.001)\n parser.add_argument('--decay', type=float, default=1e-4)\n parser.add_argument('--momentum', type=float, default=0.9)\n parser.add_argument('--batch', type=int, default=128)\n parser.add_argument('--epoch', type=int, default=100)\n parser.add_argument('--output', type=str, default='weight')\n args = parser.parse_args()\n\n model = importlib.import_module(args.model).build()\n\n six.print_('loading data')\n (train_x, train_y, val_x, val_y) = load_data()\n six.print_('load data complete')\n\n sgd = SGD(lr=args.lr,\n decay=args.decay,\n momentum=args.momentum,\n nesterov=True)\n model.compile(loss='binary_crossentropy', optimizer=sgd,\n metrics=['accuracy'])\n six.print_('build model complete')\n\n six.print_('start training')\n model.fit(train_x, train_y, batch_size=args.batch, nb_epoch=args.epoch,\n verbose=2,\n shuffle=True,\n validation_data=(val_x, val_y))\n model.save_weights(args.output + '.hdf5')\n\n\nif __name__ == '__main__':\n main()\n" } ]
12
gaurang363/C4-SMP-ML
https://github.com/gaurang363/C4-SMP-ML
ffe2ea955abd78e2b309025cd17a26e322973db6
4e65d8220559af3acd184f24547704ae06cf4a24
10f030dcd042e3c465e7d8935c26a50fdf815a55
refs/heads/master
2022-07-06T18:51:40.727807
2020-05-17T06:07:31
2020-05-17T06:07:31
264,594,860
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4031413495540619, "alphanum_fraction": 0.42277488112449646, "avg_line_length": 52.57143020629883, "blob_id": "e844cf5759f03013f04e7e41e61d97c94285eec6", "content_id": "9aba7a6f74e9c6aaad0e424b667f2d8785a2513d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 764, "license_type": "no_license", "max_line_length": 130, "num_lines": 14, "path": "/Week2/tral.py", "repo_name": "gaurang363/C4-SMP-ML", "src_encoding": "UTF-8", "text": "import numpy as np\r\nimport pandas as pd\r\ndata = pd.read_csv('ex1data2.txt', sep = ',', header = None)\r\nX = data.iloc[:,0:2] # read first two columns into X\r\ny = data.iloc[:,2] # read the third column into y\r\nprint(y)\r\nm = len(y) # no. of training samples\r\nprint(data.head()) # view first few rows of the data\r\nones = np.ones((m,1)) # initializing an array of 1s as value for intercept terms\r\nX = np.hstack((ones, X))\r\nalpha = 0.01\r\niterations = 500\r\ntheta = np.zeros((3,1))\r\ny = y[:,np.newaxis]\r\n" } ]
1
shiqing881215/Python
https://github.com/shiqing881215/Python
48cbfff7aefc832373d042890dfa10972dd4df03
1afa5fa1bef7468532bdbfd7c1193c419ee77d98
1a166d6092c6da2fbe2a77e73220a8d2aa86e86b
refs/heads/master
2021-01-10T03:46:22.267219
2015-12-18T17:05:38
2015-12-18T17:05:38
45,350,475
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7326202988624573, "alphanum_fraction": 0.7379679083824158, "avg_line_length": 25.85714340209961, "blob_id": "ae67a926e3956a89f593f0aaf5935ed50382acdc", "content_id": "929ac00df33d66374efad5357a517dca951fcfd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 187, "license_type": "no_license", "max_line_length": 65, "num_lines": 7, "path": "/advanced/urllibDemo.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "import urllib\n\n# These will be more useful in the daily life than socket library\nfhand = urllib.urlopen('http://www.py4inf.com/code/romeo.txt')\n\nfor line in fhand :\n print line.strip()" }, { "alpha_fraction": 0.6783625483512878, "alphanum_fraction": 0.680701732635498, "avg_line_length": 25.65625, "blob_id": "4c5b1232479b58325db6bf20c50f0c443a897408", "content_id": "f01de41c08c551b0bbfcdf3fd097c2d81a1269c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 855, "license_type": "no_license", "max_line_length": 125, "num_lines": 32, "path": "/basic/file.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "fhandle = open('sampleFile.txt', 'r') # default mode is read, so you can also omit it\nprint fhandle\nprint type(fhandle)\n\ncount = 0\nfor line in fhandle :\n print line\n count = count + 1\nprint 'Line Count : ', count\n\n# Read the whole file into a string\n# Attention, we nee to open the file again - I guess either last time we close it after we read it, or fhanlde reach the end?\nfhandle = open('sampleFile.txt', 'r') \nwholeFile = fhandle.read();\nprint len(wholeFile)\nprint wholeFile\n\n# Search in a file\nfhandle = open('sampleFile.txt', 'r') \nfor line in fhandle :\n line = line.rstrip() # remove the ending newline symbol (right strip)\n if line.startswith('I just') :\n print line\n\n# Handle bad file name\nfname = raw_input('Enter file name')\ntry :\n fhandle = open(fname)\nexcept : \n print 'Bad file name'\n exit()\nprint fhandle\n\n\n" }, { "alpha_fraction": 0.6544020771980286, "alphanum_fraction": 0.6662286520004272, "avg_line_length": 27.69811248779297, "blob_id": "4c304a445af1bbed75082eeb93457536209916ae", "content_id": "a831f4a8379b9d5deaa4bb3034d2c52257cc55bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1522, "license_type": "no_license", "max_line_length": 88, "num_lines": 53, "path": "/advanced/rex.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "import re\n\n#search demo, return true / false\nline = \"This is an email from Jetty\"\n\nif re.search(\"This\", line) :\n print \"Yes, include 'This'\"\n\nif re.search(\"^This\", line) :\n print \"Yes, start with 'This'\"\n\n# * mean 0 - many times\nif re.search(\"^T.*\", line) :\n print \"Yes, start with T and following by any character\"\n\n# + means 1 - many times\nif re.search(\"^T.+\", line) :\n print \"Yes, start with T and following by at least one character\"\n\n# \\S means none-blank char\nif re.search(\"^T\\S+\", line) :\n print \"Yes, start with T and following by at least one none-blank character\"\n\n\n# findall demo, return a list of matching results\nline2 = \"My favorite number is 19 and 42\"\n\nprint re.findall(\"[0-9]+\", line2)\n\n\n# By default, python does the greedy matching, which means get larger one\nline3 = \"From: jetty's email: [email protected]\"\n\n# This will print the [\"From: jetty's email:\"] which tries to get the last :\nprint re.findall(\"^F.+:\", line3) \n\n# This will print [\"From:\"] which is turn off default greedy setting\nprint re.findall(\"^F.+?:\", line3) \n\n# This is to extract the email address\nprint re.findall(\"\\S+@\\S+\", line3)\n\n\n# Sometimes, we want to match something, but don't want to extract all the matched stuff\n# So we can use (), it will only return the stuff inside of ()\nline4 = \"From [email protected] saying hello\"\n\n# It will match \"From [email protected]\", but will only return \"[email protected]\"\nprint re.findall(\"^From (\\S+@\\S+)\", line4)\n\n# Extract the domain name\nprint re.findall(\"@(\\S*)\", line4)\nprint re.findall(\"@([^ ]*)\", line4)\n\n" }, { "alpha_fraction": 0.6467559337615967, "alphanum_fraction": 0.6879505515098572, "avg_line_length": 17.320755004882812, "blob_id": "63ded35f8ea2a000fb006154cc82c39df97dddca", "content_id": "b7ac5b18cc8022116a1ca9fb9df5367c57ef7806", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 971, "license_type": "no_license", "max_line_length": 44, "num_lines": 53, "path": "/basic/list.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "fruits = ['apple', 'banana', 'peach']\nprint fruits\nprint fruits[0]\n\n# String is immutable but list is\nfruit = 'apple'\n# fruit[0] = 'A' This will throw the error\nfruits[0] = 'Apple' # This is fine\n\nprint 'Length of fruits is ', len(fruits)\n\n# range() function returns you a list\nprint range(4)\nprint range(len(fruits))\n\n# concatenate\nnewList = [1,2,'haha'] + [[4,6], 'wowo']\nprint newList\n\n# slice - include start not end\nprint [1,2,3,4,5,6][1:3]\n\nprint type(fruits)\nprint dir(fruits)\n\n# constructor\ncars = list()\ncars.append('Honda')\ncars.append('Benz')\ncars.append('BMW')\nprint cars\n\nprint 1 in [1,2,3]\nprint 1 not in [1,2,3]\n\n# Sort - change the list itself\nunsorted = [45,1,55,89,100,3]\nunsorted.sort()\nprint unsorted\n\n# Other functions\nprint max(unsorted)\nprint min(unsorted)\nprint sum(unsorted)\n\n# Split\nabc = 'with three words'\nabcList = abc.split()\nprint abcList, len(abcList)\n\nabc2 = 'with;three;words'\nabcList2 = abc2.split(';')\nprint abcList2, len(abcList2)\n" }, { "alpha_fraction": 0.6566265225410461, "alphanum_fraction": 0.6912650465965271, "avg_line_length": 20.387096405029297, "blob_id": "69e040b143b1e7e3141aaff0e4dd9d4b45f41859", "content_id": "f6d3c1b1f805550e9ca91e66dd773576218c5cd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 664, "license_type": "no_license", "max_line_length": 78, "num_lines": 31, "path": "/basic/dictionary.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "purse = dict()\npurse['money'] = 12\npurse['candy'] = 5\npurse['tissues'] = 3\nprint purse\nprint purse['candy']\npurse['candy'] = purse['candy'] + 2\nprint purse\n\npurse2 = {'money':1, 'candy':2, 'tissues':3}\nprint purse2\n\nprint 'money' in purse2\n# print purse2['random'] This will give the traceback error\n\n# Second param is the default value which will be used if the key is not found\nprint purse2.get('money', -1)\nprint purse2.get('random', -1)\n\n# Loop\nfor key in purse2 :\n print key, purse2[key]\n\nprint list(purse2)\nprint purse2.keys()\nprint purse2.values()\nprint purse2.items()\n\n# Two iteration variable\nfor key,value in purse2.items() : \n print key, value\n\n" }, { "alpha_fraction": 0.6609547138214111, "alphanum_fraction": 0.6707466244697571, "avg_line_length": 16.404254913330078, "blob_id": "43ebbeacae18cb60f4de3c986033597e2d815dda", "content_id": "5928825ee8e836d2dbcf60174df574ed72510965", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 817, "license_type": "no_license", "max_line_length": 66, "num_lines": 47, "path": "/object&database/inheritence.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "class PartyAnimal :\n\tx = 0\n\tname = \"\"\n\n\t# This is the constructor\n\tdef __init__(self, name) :\n\t\tself.name = name\n\t\tprint \"I'm constructing\", self.name\n\n\t# method, each python class at least has one variable called self\n\tdef party(self):\n\t\tself.x = self.x+1\n\t\tprint self.name, \" says \", self.x\n\n\t# This is the destructor\n\tdef __del__(self):\n\t\tprint \"I'm destructed\", self.name\n\n# This is how to do the \"extends\"\nclass FootballFan(PartyAnimal) :\n\tpoints = 0\n\n\tdef touchdown(self) :\n\t\tself.points = self.points + 7\n\t\tself.party()\n\t\tprint self.name, \"Points \", self.points\n\ns = PartyAnimal(\"Sally\")\ns.party()\n\nj = FootballFan(\"Jim\")\nj.party()\nj.touchdown()\n\n\n'''\nThe result is \n\nI'm constructing Sally\nSally says 1\nI'm constructing Jim\nJim says 1\nJim says 2\nJim Points 7\nI'm destructed Jim\nI'm destructed Sally\n'''" }, { "alpha_fraction": 0.6168830990791321, "alphanum_fraction": 0.6509740352630615, "avg_line_length": 33.27777862548828, "blob_id": "d322b7dfd6a5651dfe60182724cdf6559d0c2b16", "content_id": "95fe427ecddd9abe54aee97867f7db94eb5f45ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 616, "license_type": "no_license", "max_line_length": 136, "num_lines": 18, "path": "/advanced/xmlDemo.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "import xml.etree.ElementTree as ET\n\ndata = '<person><name>Chuck</name><phone type=\"intl\">+1 222 333 4444</phone><email hide=\"yes\"/></person>'\n\ntree = ET.fromstring(data)\nprint 'Name:', tree.find('name').text\nprint 'Attr:', tree.find('email').get('hide')\n\n\ndata2= '<stuff><users><user x=\"2\"><id>011</id><name>Chuck</name></user><user x=\"7\"><id>061</id><name>John</name></user></users></stuff>'\n\nstuff = ET.fromstring(data2)\nlist = stuff.findall('users/user')\nprint 'User count', len(list)\nfor user in list :\n print 'Name', user.find('name').text\n print 'Id', user.find('id').text\n print 'Attr', user.get('x')" }, { "alpha_fraction": 0.504687488079071, "alphanum_fraction": 0.5234375, "avg_line_length": 22.66666603088379, "blob_id": "04247cfba0d46856dfb8c4f1a387ed1b4c1b09c8", "content_id": "2c45b13f65c911b994c67cf1bd401c6e9e2180ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 640, "license_type": "no_license", "max_line_length": 44, "num_lines": 27, "path": "/basic/condition.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "age = raw_input('How old are you? ')\ntry :\n ageInt = int(age)\n if (ageInt < 10) : \n print 'You are a kid'\n elif (ageInt > 20) : \n print 'You are an adult'\n else :\n print 'You are a teenager'\n print 'Done'\nexcept : \n print 'Your input is not a interger' \n\n\nx = raw_input('Give a value to x ')\ntry :\n xInt = int(x)\n if (xInt == 5) :\n print 'x is 5'\n print 'x is still 5'\n print 'x is still 5 again'\n if (xInt != 5) : \n print 'x is not 5'\n print 'x is still not 5'\n print 'x is still not 5 again'\nexcept : \n print 'Your input is not an interger'\n\n" }, { "alpha_fraction": 0.6719298362731934, "alphanum_fraction": 0.6947368383407593, "avg_line_length": 27.5, "blob_id": "3eb40716c9044047c33a89aeb472952ea40fe777", "content_id": "7430bc64f14f2165cbb2ce71efb799c771830a29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 570, "license_type": "no_license", "max_line_length": 95, "num_lines": 20, "path": "/advanced/socketDemo.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "import socket\n\n# open socket\nmysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nmysock.connect(('www.py4inf.com', 80))\n\n# This is exactly as what we did while using telnet. Based on the HTTP protocal request format \n# Like hitting enter twice at the end to send the request\nmysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\\n\\n')\n\nwhile True :\n # Each time read up to 512 char\n # For some reason, it stucks here, TODO Debug more\n data = mysock.recv(512)\n if (len(data) < 1) :\n break\n print data;\n\nprint 'close'\nmysock.close()\n" }, { "alpha_fraction": 0.5460317730903625, "alphanum_fraction": 0.5571428537368774, "avg_line_length": 20.724138259887695, "blob_id": "12431b1f6db98281ccaa4b81d7a0efb61dd01c6a", "content_id": "068ffdfd1e3f89a407ed55201f9175b6968c88f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 630, "license_type": "no_license", "max_line_length": 116, "num_lines": 29, "path": "/basic/loop.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "def printDelimeter() :\n print ''\n print '---------------------------------------'\n print ''\n\n\ntimes = raw_input('How many times do you want to loop ? ')\nintTimes = int(times)\nwhile intTimes > 0 :\n print intTimes\n intTimes = intTimes - 1\n\nprintDelimeter()\n\nwhile True : \n print 'Only when you tyle \"Done\", then I will finish myself. And if you enter \"Skip\", I will skip once for you.'\n line = raw_input('Enter your answer : ')\n if (line == 'Done') :\n break\n elif (line == 'Skip') :\n continue\n else : \n print line\nprint 'Done'\n\nprintDelimeter()\n\nfor i in [5,4,3,2,1] :\n print i\n" }, { "alpha_fraction": 0.7025495767593384, "alphanum_fraction": 0.7053824067115784, "avg_line_length": 21.125, "blob_id": "05c1f388789b054ee7c078080d4e5d3bc0c1669a", "content_id": "1ebcda17b9e0fc597db2333165e63fc3765619ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 353, "license_type": "no_license", "max_line_length": 63, "num_lines": 16, "path": "/advanced/beautifulSoupDemo.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "# The url you can try here is http://www.dr-chuch.com/page1.htm\n\nimport urllib\n# You need to put BeautifulSoup.py in the same folder\nfrom BeautifulSoup import *\n\nurl = raw_input('Enter - ')\n\nhtml = urllib.urlopen(url).read()\nsoup = BeautifulSoup(html)\n\n# Retrieve a list of anchor tags\ntags = soup('a')\n\nfor tag in tags :\n print tag.get('href', None)" }, { "alpha_fraction": 0.6630727648735046, "alphanum_fraction": 0.6738544702529907, "avg_line_length": 16.66666603088379, "blob_id": "393be373e6fe3c2f5de36b37bc3cc8f3bbd5117c", "content_id": "f8073e32b62a366ad3fb4d5e74593c3af8698db4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 742, "license_type": "no_license", "max_line_length": 66, "num_lines": 42, "path": "/object&database/constructorDestructor.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "class PartyAnimal :\n\tx = 0\n\tname = \"\"\n\n\t# This is the constructor\n\tdef __init__(self, name) :\n\t\tself.name = name\n\t\tprint \"I'm constructing\", self.name\n\n\t# method, each python class at least has one variable called self\n\tdef party(self):\n\t\tself.x = self.x+1\n\t\tprint self.name, \" says \", self.x\n\n\t# This is the destructor\n\tdef __del__(self):\n\t\tprint \"I'm destructed\", self.name\n\n# Attention - there is no \"new\" keyword\njack = PartyAnimal(\"Jack\")\nrose = PartyAnimal(\"Rose\")\njack.party()\njack.party()\njack.party()\nrose.party()\njack.party()\nrose.party()\n\n'''\nThe result is \n\nI'm constructing Jack\nI'm constructing Rose\nJack says 1\nJack says 2\nJack says 3\nRose says 1\nJack says 4\nRose says 2\nI'm destructed Rose\nI'm destructed Jack\n'''\n" }, { "alpha_fraction": 0.6323184967041016, "alphanum_fraction": 0.6569086909294128, "avg_line_length": 23.428571701049805, "blob_id": "7db0a4ae302cc07d5ca976e07851a9342da9e494", "content_id": "cf737765d67295109870dc82171bd470fff7fc6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 854, "license_type": "no_license", "max_line_length": 77, "num_lines": 35, "path": "/basic/string.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "fruit = 'banana'\nprint fruit[0]\nprint len(fruit)\n\nindex = 0\nwhile index < len(fruit) :\n print str(index) + \" : \" + fruit[index]\n index = index + 1\n\nfor letter in fruit : \n print letter\n\n# slice - include beginning/exclude ending\nprint fruit[0:4]\nprint fruit[5:6]\nprint fruit[0:100] # This returns 'banana'\nprint fruit[4:0] # This returns nothing\nprint fruit[:4] # This equals to [0:4]\nprint fruit[2:] # This equals to [2:6]\nprint fruit[:] # This equals to [0:6]\n\n# in operator\nif 'a' in fruit : \n print 'fruit has char a'\n\n# comparison\nif 'apple' < fruit :\n print 'apple is smaller'\nif 'banana' == fruit :\n print 'fruit is banana'\nprint 'The first n in fruit is ' + str(fruit.find('n'))\n\n# string library\nprint 'BANANA lowercase is ' + 'BANANA'.lower()\nprint 'This is the built in method you can call on string ' + str(dir(fruit))" }, { "alpha_fraction": 0.7925170063972473, "alphanum_fraction": 0.7925170063972473, "avg_line_length": 47.83333206176758, "blob_id": "46a6300fc697cd7bc064ffbe8a122e71fcf9cae5", "content_id": "627cc9bc032e15a65b8364278de811fc66335fed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 294, "license_type": "no_license", "max_line_length": 116, "num_lines": 6, "path": "/README.md", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "# Python\nBasic Python Knowledge\n\nBasic Python concept and handson code sample. <br/>\nFollow the Coursera python course https://www.coursera.org/learn/python/home/welcome <br/>\nThis is mainly a reference place for myself if I need some basic information about python or some basic code sample. \n" }, { "alpha_fraction": 0.5584989190101624, "alphanum_fraction": 0.6048564910888672, "avg_line_length": 19.613636016845703, "blob_id": "f17bc5064c736719d1d845b17e057a9bc2eb5503", "content_id": "642fe8559104e5f3a7ae8bdcb666e04296ee3878", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 906, "license_type": "no_license", "max_line_length": 53, "num_lines": 44, "path": "/basic/tuples.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "numbers = (1,2,3)\nprint numbers\nprint max(numbers)\nprint len(numbers)\nfor number in numbers : \n print number\n\nt = tuple()\nprint dir(t)\n\n# You can do assignment on both sides\n(x,y) = (4, 'fred')\nprint x, y\n\n# Compare - compare the first then the second and etc\nprint (1,2,3) < (9,0,0)\nprint (1,2,3) > (1,2,2)\nprint (1,2,3) == (1,2,3)\n\n# Since it's comparable, so tuples can be sorted\nts = [('b', 1), ('c', 30), ('a', 10)]\nprint ts\nts.sort()\nprint ts\nts.sort(reverse=True)\nprint ts\n\n# Use built-in sorted() method\nd = {'b' : 1, 'a' : 10, 'c' : 30}\nprint sorted(d.items())\n\n# Sort on value instead of key\nd = {'b' : 1, 'a' : 10, 'c' : 30}\ntmp = list()\nfor k,v in d.items() : \n tmp.append( (v,k) )\nprint tmp\ntmp.sort(reverse=True) # Show most frequent\nprint tmp\n\n# Short version\n# List comprehension creates a dynamic list\nd = {'b' : 1, 'a' : 10, 'c' : 30}\nprint sorted( [(v,k) for (k,v) in d.items()] )" }, { "alpha_fraction": 0.4946921467781067, "alphanum_fraction": 0.5456475615501404, "avg_line_length": 25.16666603088379, "blob_id": "a23fbf40cdead4470f3b091f7b22c5d3c10225de", "content_id": "10ce60bb02a942ae726ee8994b3fd02174516caf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 471, "license_type": "no_license", "max_line_length": 103, "num_lines": 18, "path": "/advanced/jsonDemo.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "import json\n\ndata = '{\"name\":\"Chuck\", \"phone\":{\"type\":\"intl\",\"number\":\"12223334444\"}, \"email\":{\"hide\":\"yes\"}}'\n\ninfo = json.loads(data)\n\nprint 'Name : ', info['name']\nprint 'Hide : ', info['email']['hide']\n\ndata2 = '[{\"id\" : \"001\", \"x\" : \"2\", \"name\" : \"Chuck\"} , { \"id\" : \"009\", \"x\" : \"7\", \"name\" : \"Chuck\"}]'\n\ninfo2 = json.loads(data2)\n\nprint 'User count ', len(info2)\nfor item in info2 :\n\tprint 'Name ', item['name']\n\tprint 'Id ', item['id']\n\tprint 'Attr ', item['x']\n" }, { "alpha_fraction": 0.6235294342041016, "alphanum_fraction": 0.6235294342041016, "avg_line_length": 18.69230842590332, "blob_id": "7737ed19b6434469b50f727626f837f84fc583eb", "content_id": "c749dfa94763d6f1ef7bb3944c231b4709205243", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 255, "license_type": "no_license", "max_line_length": 71, "num_lines": 13, "path": "/basic/function.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "def hello() : \n print 'Hello'\n\nhello()\nprint 'and'\nhello()\n\ndef add(a, b) :\n return a+b\n\na = raw_input('Enter your first number : ')\nb = raw_input('Enter your second number : ')\nprint 'The addition of these two number is ' + str(add(int(a), int(b)))" }, { "alpha_fraction": 0.6930894255638123, "alphanum_fraction": 0.6971544623374939, "avg_line_length": 26.38888931274414, "blob_id": "88dc99f68510f18baaf5b06632b55433bb3fad5a", "content_id": "a76be39e4f9f3f64f9c37453285cb2437317173d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 492, "license_type": "no_license", "max_line_length": 83, "num_lines": 18, "path": "/object&database/simpleClass.py", "repo_name": "shiqing881215/Python", "src_encoding": "UTF-8", "text": "class PartyAnimal :\n\t# field\n\tx = 0\n\t# method, each python class at least has one variable called self\n\t# and when you call this method, you don't need to pass the self explicitly\n\t# the object call the method become the self\n\tdef party(self):\n\t\tself.x = self.x+1\n\t\tprint \"So far\", self.x\n\n# Attention - there is no \"new\" keyword\nan = PartyAnimal()\nan.party()\nan.party()\nan.party()\n\nprint \"Type : \", type(an)\nprint \"Dir : \", dir(an) # This will list both the methods and attributes together" } ]
18
dbertouille/lolable2
https://github.com/dbertouille/lolable2
6b7d5a9f32e6ceeacdc96e67823610ed05656cc4
e609271709b1e2f9b553edf54ebc8a82513d61f5
ac0c27b97dd472574c6a1c020c123a23fc64d512
refs/heads/master
2021-01-20T17:21:36.198484
2018-11-01T01:04:12
2018-11-01T01:04:12
63,719,151
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4513997435569763, "alphanum_fraction": 0.4583550691604614, "avg_line_length": 27.899497985839844, "blob_id": "e785da8d8e0b5b447da432cb26d2ea30e0238b32", "content_id": "746957041c8d556062a1cacd3daf910e5027a31c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5751, "license_type": "no_license", "max_line_length": 113, "num_lines": 199, "path": "/frontend/src/app/comic.component.ts", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "import { Location } from '@angular/common';\nimport { Component } from '@angular/core';\nimport { OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\n\nimport { LOLService } from './lol.service';\n\nimport * as globals from './globals';\n\n@Component({\n selector: 'lol-comic',\n styles: [`\n .comic-wrapper {\n margin: auto;\n width: 100%;\n display: inline-flex;\n flex-direction: row;\n justify-content: center;\n }\n .comic {\n display: flex;\n flex-direction: column;\n max-width: 100%;\n }\n .comic-title {\n text-align: center;\n }\n .comic-title-text {\n font-weight: bold;\n margin-left: 10px;\n }\n .comic div {\n display: flex;\n flex-direction: row;\n flex-wrap: wrap;\n justify-content: center;\n }\n\n .comic-img {\n align-self: center;\n border: solid black 2px;\n max-height: 75vh;\n }\n \n .comic-menu {\n background-color: black;\n color: white;\n text-align: center;\n }\n .comic-menu a {\n color: white;\n text-decoration: none;\n padding-left: 10px;\n padding-right: 10px;\n border-radius: 0.5em;\n border-radius: 0.5em;\n }\n .comic-menu-item {\n cursor: pointer;\n padding-left: 10px;\n padding-right: 10px;\n }\n .comic-menu-item:hover {\n font-weight: bold;\n }\n .comic-menu-item.disabled {\n color: gray;\n cursor: default;\n }\n .comic-menu-item-spacer {\n // border: 1px solid #000000;\n }\n `],\n template:`\n <div *ngIf=\"comic\" class=\"title comic-title\">\n <span class=\"comic-title-text\">\n Issue #{{comic.id}}: {{comic.title}}\n </span>\n </div>\n <div *ngIf=\"comic\" class=\"comic-wrapper\">\n\n <div class=\"comic\">\n <div class=\"comic-img-wrapper\">\n <img class=\"comic-img\" src=\"{{wsurl + '/static/comics/comic' + pad(comic.id, 3) + '.jpg'}}\"/>\n </div>\n <div class=\"comic-menu\">\n <a\n (click)=\"onClickFirst()\"\n class=\"text comic-menu-item\"\n [class.disabled]=\"comic.id == 1\">\n First\n </a>\n <span class=\"text comic-menu-item-spacer\"></span>\n <a\n (click)=\"onClickBack()\"\n class=\"text comic-menu-item\"\n [class.disabled]=\"comic.id == 1\">\n Back\n </a>\n <span class=\"text comic-menu-item-spacer\"></span>\n <a (click)=\"onClickRandom()\" class=\"text comic-menu-item\">\n Random\n </a>\n <span class=\"text comic-menu-item-spacer\"></span>\n <a class=\"text comic-menu-item\" [routerLink]=\"['/archive']\">\n Archive\n </a>\n <span class=\"text comic-menu-item-spacer\"></span>\n <a\n (click)=\"onClickNext()\"\n class=\"text comic-menu-item\"\n [class.disabled]=\"comic.id == latest.id\">\n Next\n </a>\n <span class=\"text comic-menu-item-spacer\"></span>\n <a\n (click)=\"onClickNewest()\"\n class=\"text comic-menu-item\"\n [class.disabled]=\"comic.id == latest.id\">\n Newest\n </a>\n </div>\n <lol-blog-entry [selectedComic]=\"comic\"></lol-blog-entry>\n </div>\n <div style=\"height:10px;\"></div>\n </div>\n\n `,\n // directives: [BlogEntryComponent],\n})\n\n/*\n * This class assumes all comics are in sequential order starting\n * from 1. If we allow comics to be deleted, we may need to rework\n * this (and the webservice)\n */\nexport class ComicComponent implements OnInit {\n wsurl = globals.wsurl;\n latest = undefined;\n comic = undefined;\n sub = undefined;\n\n first_id = 1;\n\n constructor(\n private lolService: LOLService,\n private route: ActivatedRoute,\n private location: Location\n ) {}\n\n ngOnInit() {\n this.lolService.getComicNewest().then(comic => {\n this.latest = comic;\n this.sub = this.route.params.subscribe(params => {\n var id = +params['id'];\n if(isNaN(id) || id == undefined) {\n id = this.latest.id;\n }\n this.loadComic(id);\n });\n });\n }\n\n loadComic(id) {\n this.lolService.getComic(id).then(comic => this.setComic(comic));\n }\n\n setComic(comic) {\n this.comic = comic\n this.location.replaceState(\"/comic/\" + this.comic.id);\n }\n \n\n onClickFirst() {\n this.loadComic(this.first_id);\n }\n\n onClickBack() {\n this.loadComic(Math.max(this.comic.id - 1, this.first_id));\n }\n\n onClickRandom() {\n this.lolService.getComicRandom().then(comic => this.setComic(comic));\n }\n\n onClickNext() {\n this.loadComic(Math.min(this.comic.id + 1, this.latest.id));\n }\n\n onClickNewest() {\n this.setComic(this.latest);\n }\n\n pad(num, size) {\n var s = num+\"\";\n while (s.length < size) s = \"0\" + s;\n return s;\n }\n}\n" }, { "alpha_fraction": 0.5279449820518494, "alphanum_fraction": 0.5382631421089172, "avg_line_length": 30.432432174682617, "blob_id": "7f556b759a09afbf06e468f6c5842cbe3563d3e1", "content_id": "7a2df81282a59b0aa59cefa7e716a714b16ee86f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1163, "license_type": "no_license", "max_line_length": 71, "num_lines": 37, "path": "/webservice/resources/blogs.py", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "from flask import request\nfrom flask_restful import Resource\nfrom models import BlogModel\nfrom schemas import BlogSchema\n\nfrom utils import json_response\n\nclass BlogList(Resource):\n @json_response\n def get(self):\n limit = request.args.get('limit')\n if limit is None:\n limit = 10\n\n offset = request.args.get('offset')\n if offset is None:\n offset = 0\n\n blogs = BlogModel.query.filter(BlogModel.comic_id == None) \\\n .order_by(BlogModel.id.desc()) \\\n .limit(limit) \\\n .offset(offset) \\\n .all()\n\n return 200, BlogSchema(many=True).dump(blogs).data\n\nclass Blog(Resource):\n @json_response\n def get(self, blog_id=None, comic_id=None):\n blog = None\n if blog_id is not None:\n blog = BlogModel.query.get(blog_id)\n elif comic_id is not None:\n blog = BlogModel.query.filter_by(comic_id=comic_id).first()\n if blog is None:\n return 404, {}\n return 200, BlogSchema().dump(blog).data\n" }, { "alpha_fraction": 0.6199901103973389, "alphanum_fraction": 0.6392874717712402, "avg_line_length": 29.1641788482666, "blob_id": "5f0a8e7cec0c4ab784bb4416c07efc3a47e4ca6c", "content_id": "9d0a6834e1945b5492c2ff5ecb36cbf061e2b424", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2021, "license_type": "no_license", "max_line_length": 76, "num_lines": 67, "path": "/webservice/models.py", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "import flask_scrypt\n\nfrom extensions import db\n\nclass ArchiveItemModel():\n def __init__(self, item_type, data):\n self.item_type = item_type\n self.comic = data if item_type == 'comic' else None\n self.media = data if item_type == 'media' else None\n\nclass BlogModel(db.Model):\n __tablename__ = 'blog'\n\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(128))\n blog = db.Column(db.String(8096))\n posted_date = db.Column(db.DateTime)\n comic_id = db.Column(db.Integer, db.ForeignKey('comic.id'), unique=True)\n\nclass ComicModel(db.Model):\n __tablename__ = 'comic'\n\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(128))\n posted_date = db.Column(db.DateTime)\n\nclass ConfigurationModel(db.Model):\n __tablename__ = 'configuration'\n\n id = db.Column(db.Integer, primary_key=True)\n key = db.Column(db.String(128))\n value = db.Column(db.String(256))\n\nclass MediaModel(db.Model):\n __tablename__ = 'media'\n\n id = db.Column(db.Integer, primary_key=True)\n media_type = db.Column(db.String(128))\n title = db.Column(db.String(128))\n url = db.Column(db.String(1024))\n thumb_url = db.Column(db.String(1024))\n posted_date = db.Column(db.DateTime)\n\nclass UserModel(db.Model):\n __tablename__ = 'user'\n\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(128), unique=True)\n passhash = db.Column(db.String(256))\n passsalt = db.Column(db.String(256))\n admin = db.Column(db.Boolean)\n\n def set_password(self, ptext):\n self.passsalt = flask_scrypt.generate_random_salt()\n self.passhash = flask_scrypt.generate_password_hash(\n ptext,\n self.passsalt)\n\n def check_password(self, ptext):\n # XXX - There could be issues casting unicode to string here\n return flask_scrypt.check_password_hash(\n str(ptext),\n str(self.passhash),\n str(self.passsalt))\n\nif __name__ == '__main__':\n db.create_all()\n" }, { "alpha_fraction": 0.7551020383834839, "alphanum_fraction": 0.7551020383834839, "avg_line_length": 97, "blob_id": "3857d96641864795aa465333064326c4fa18ce7a", "content_id": "6ca6ad8aceed5bac06231b6f4e5341c51cfef967", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 196, "license_type": "no_license", "max_line_length": 98, "num_lines": 2, "path": "/ops/db/migrate.sql", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "INSERT INTO comic (id, title, posted_date) SELECT comic_num, comic_name, date FROM lolable.comics;\nINSERT INTO blog (id, title, blog, posted_date) SELECT id, title, blog, time FROM lolable.blogs;\n" }, { "alpha_fraction": 0.4096747636795044, "alphanum_fraction": 0.4230664074420929, "avg_line_length": 26.719696044921875, "blob_id": "81e75f84352ab930e5e61ccc67a3d116d02aab9b", "content_id": "b33ec5df9ec039119749674addba9d67ce0e3b2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3659, "license_type": "no_license", "max_line_length": 120, "num_lines": 132, "path": "/frontend/src/app/app.component.ts", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "import { Component } from '@angular/core';\nimport { OnInit } from '@angular/core';\n\nimport { LOLService } from './lol.service';\n\n@Component({\n selector: 'lol-app',\n styles: [`\n .main {\n min-height: 100vh;\n background-image: url('static/bg.jpg');\n display: block;\n }\n .header {\n display: flex;\n float: left\n width: 100%;\n border-bottom: 2px solid black;\n background-color: #303030;\n }\n .header-logo {\n max-height: 100px;\n }\n .header-content {\n flex-grow: 100;\n position: relative;\n\n color: white;\n margin-left: 5px;\n }\n .header-menu {\n position: absolute;\n bottom: 0;\n }\n .header-menu a {\n //background-color: black;\n color: white;\n text-decoration: none;\n font-size: 3vw;\n font-weight: bold;\n padding-left: 10px;\n padding-right: 10px;\n border-radius: 0.5em;\n border-radius: 0.5em;\n }\n\n .header-social {\n margin-right: 10px;\n margin-top: 10px;\n float: right;\n }\n\n .header-social img {\n height: 15px;\n }\n\n .header-social a {\n color: white;\n text-decoration: none;\n }\n\n .header-social a:hover {\n font-weight: bold;\n }\n .content {\n display: block;\n clear: left;\n }\n\n .footer {\n width: 100%;\n margin-top: 20px;\n text-align: center;\n min-height: 20px;\n }\n\n `],\n template:`\n <div class=\"main\">\n <div class=\"header\">\n <div>\n <img class=\"header-logo\" src=\"static/logo.jpg\"/>\n </div>\n <div class=\"header-content\">\n <div class=\"header-social\">\n <div class=\"header-social-item\">\n <img src=\"static/icons/youtube.png\"/>\n <a class=\"text\" href=\"https://www.youtube.com/channel/UC7yfCL0Xns8k2Nrpvb63Ogg\">@Lolable</a>\n </div>\n <div class=\"header-social-item\">\n <img src=\"static/icons/facebook.png\"/>\n <a class=\"text\" href=\"https://www.facebook.com/lolablecomics/\">@LolableComics</a>\n </div>\n </div>\n <div class=\"header-menu\">\n <a [routerLink]=\"['/comic']\">COMIC</a>\n <a [routerLink]=\"['/archive']\">ARCHIVE</a>\n <a [routerLink]=\"['/blog']\">BLOG</a>\n </div>\n </div>\n </div>\n <div class=\"content\">\n <router-outlet></router-outlet>\n </div>\n <div class=\"footer\">\n {{footer}}\n </div>\n </div>\n `,\n providers: [\n LOLService,\n ],\n})\n\nexport class AppComponent implements OnInit {\n title = '';\n footer = '';\n\n constructor(private lolService: LOLService) { }\n\n ngOnInit() {\n this.lolService.getConfig().then(cfg => {\n var item;\n item = cfg.find(item => item.key == 'title');\n if (item !== undefined)\n this.title = item.value;\n item = cfg.find(item => item.key == 'footer');\n if (item !== undefined)\n this.footer = item.value;\n });\n }\n}\n" }, { "alpha_fraction": 0.7192716002464294, "alphanum_fraction": 0.7192716002464294, "avg_line_length": 22.571428298950195, "blob_id": "08b7099f5c164c3756900f2b4f68db73dfa66b60", "content_id": "76d55e24942500a0675e4ca92111e346cd9644e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 659, "license_type": "no_license", "max_line_length": 42, "num_lines": 28, "path": "/webservice/schemas.py", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "from extensions import ma\nfrom marshmallow import fields\nimport models\n\nclass BlogSchema(ma.ModelSchema):\n class Meta:\n model = models.BlogModel\n\nclass ComicSchema(ma.ModelSchema):\n class Meta:\n model = models.ComicModel\n\nclass ConfigurationSchema(ma.ModelSchema):\n class Meta:\n model = models.ConfigurationModel\n\nclass MediaSchema(ma.ModelSchema):\n class Meta:\n model = models.MediaModel\n\nclass UserSchema(ma.ModelSchema):\n class Meta:\n model = models.UserModel\n\nclass ArchiveItemSchema(ma.Schema):\n item_type = fields.String()\n comic = fields.Nested(ComicSchema)\n media = fields.Nested(MediaSchema)" }, { "alpha_fraction": 0.6837416291236877, "alphanum_fraction": 0.6837416291236877, "avg_line_length": 17.70833396911621, "blob_id": "b6cb7554b06e12b1367ca12c72a6b664064919a7", "content_id": "89d4dc21b1088c51f6f38275f995564f45d44106", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 449, "license_type": "no_license", "max_line_length": 51, "num_lines": 24, "path": "/ops/deploy/frontend.sh", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nsource secrets.sh\n\ncd ../../frontend\n\nrm -fr dist\nng build --prod\n\nssh -i $KEYPATH -tt [email protected] << EOF\nrm -fr /tmp/lolbuild\nmkdir /tmp/lolbuild\nexit\nEOF\n\nscp -i $KEYPATH -r dist [email protected]:/tmp/lolbuild\nscp -i $KEYPATH -r static [email protected]:/tmp/lolbuild\n\nssh -i $KEYPATH -tt [email protected] << EOF\nsudo rm -fr /var/www/html/lolable/*\nsudo mv /tmp/lolbuild/dist/* /var/www/html/lolable\nsudo mv /tmp/lolbuild/static /var/www/html/lolable\nexit\nEOF\n" }, { "alpha_fraction": 0.7669616341590881, "alphanum_fraction": 0.7758111953735352, "avg_line_length": 29.81818199157715, "blob_id": "ff752848412a874ac166266265999afb30ce0648", "content_id": "142c6c5311e5f2828640cfb27d67a296b06713fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 339, "license_type": "no_license", "max_line_length": 69, "num_lines": 11, "path": "/webservice/resources/configuration.py", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "from flask_restful import Resource\nfrom models import ConfigurationModel\nfrom schemas import ConfigurationSchema\n\nfrom utils import json_response\n\nclass ConfigurationList(Resource):\n @json_response\n def get(self):\n configs = ConfigurationModel.query.all()\n return 200, ConfigurationSchema(many=True).dump(configs).data\n" }, { "alpha_fraction": 0.4964500367641449, "alphanum_fraction": 0.5046422481536865, "avg_line_length": 32.907405853271484, "blob_id": "d434fbd3855d24cd101db53a55f925d1df63e66b", "content_id": "1e72cd7963d7c85ca985ca9e8c5d4e344b8771b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1831, "license_type": "no_license", "max_line_length": 70, "num_lines": 54, "path": "/webservice/resources/comics.py", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "from flask import request\nfrom flask_restful import Resource\nfrom models import ComicModel\nfrom schemas import ComicSchema\nfrom sqlalchemy.sql import func\n\nfrom utils import json_response\n\nclass ComicList(Resource):\n @json_response\n def get(self):\n limit = request.args.get('limit')\n if limit is None:\n limit = 10\n\n offset = request.args.get('offset')\n if offset is None:\n offset = 0\n\n search = request.args.get('search')\n if search is None:\n search = ''\n\n comics = ComicModel.query \\\n .filter(ComicModel.title.like(\"%\" + search + \"%\")) \\\n .order_by(ComicModel.id.desc()) \\\n .limit(limit) \\\n .offset(offset) \\\n .all()\n return 200, ComicSchema(many=True).dump(comics).data\n\nclass Comic(Resource):\n @json_response\n def get(self, id):\n comic = None\n if isinstance(id, int):\n comic = ComicModel.query.get(id)\n elif isinstance(id, basestring):\n if id == 'newest':\n comic = ComicModel.query.order_by(\n ComicModel.id.desc()).limit(1).first()\n elif id == 'oldest':\n comic = ComicModel.query.order_by(\n ComicModel.id).limit(1).first()\n elif id == 'random':\n # XXX - This call may change depending on the database\n # being used.\n comic = ComicModel.query.order_by(\n func.random()).limit(1).first()\n if comic is None:\n return 404, {}\n buf = ComicSchema().dump(comic).data\n buf['path'] = 'comics/%d.png' % comic.id\n return 200, buf\n" }, { "alpha_fraction": 0.5362517237663269, "alphanum_fraction": 0.5362517237663269, "avg_line_length": 23.366666793823242, "blob_id": "6786e044728e9342419f74607bd403729e7af903", "content_id": "00018691fee7fd72b1d06cfb02f13b8db1695ac8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 731, "license_type": "no_license", "max_line_length": 57, "num_lines": 30, "path": "/frontend/src/app/about.component.ts", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "import { Component } from '@angular/core';\nimport { OnInit } from '@angular/core';\n\nimport { LOLService } from './lol.service';\n\n@Component({\n selector: 'lol-about',\n template:`\n <div *ngIf=\"data\" id=\"about\">\n <img src=\"/static/banners/about.png\"/>\n <div [innerHTML]=data align=\"left\">\n </div>\n </div>\n `\n})\n\nexport class AboutComponent implements OnInit {\n data = undefined;\n\n constructor(private lolService: LOLService) {}\n\n ngOnInit() {\n this.lolService.getConfig().then(cfg => {\n var item;\n item = cfg.find(item => item.key == 'about');\n if (item !== undefined)\n this.data = item.value;\n });\n }\n}\n" }, { "alpha_fraction": 0.4717414677143097, "alphanum_fraction": 0.4823096990585327, "avg_line_length": 29.797170639038086, "blob_id": "79ecbf3b78a8d2ff051c843b508af835d8580456", "content_id": "1560d179d4994149b3976e38ad334f68265afb3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6529, "license_type": "no_license", "max_line_length": 196, "num_lines": 212, "path": "/frontend/src/app/archive.component.ts", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "import { Location } from '@angular/common';\nimport { Component } from '@angular/core';\nimport { OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\n\nimport { LOLService } from './lol.service';\n\nimport * as globals from './globals';\n\ninterface Box {\n content: any;\n config: any;\n}\n\n@Component({\n selector: 'lol-archive',\n styles: [`\n .search {\n font-weight: bold;\n margin-top: 20px;\n margin-right: 10px;\n text-align: right;\n display: block;\n }\n .search input {\n max-width: 60%;\n }\n\n .search > * {\n display: inline-block;\n }\n\n .archive {\n margin-top: 20px;\n }\n .archive-item {\n // border-radius: 25px;\n border: 2px solid #000000;\n background-color:rgba(255, 255, 255, 0.5);\n }\n .archive-item > p {\n margin: 0px;\n width: 100%;\n }\n .archive-item-type {\n background-color: black;\n color: white;\n text-align: center;\n font-weight: bold;\n }\n .archive-item-img {\n object-fit:cover;\n }\n .archive-item-img:hover {\n cursor: pointer;\n }\n .archive-footer {\n text-align: center;\n }\n .archive-footer button {\n background-color: black;\n color: white;\n font-weight: bold;\n font-size: 24px;\n }\n `],\n template:`\n <div class=\"search title\">\n <div>\n <label>\n Search\n <input class=\"title\" type=\"text\" [value]=\"searchText\" (keyup.enter)=\"setSearch()\" (input)=\"searchText = $event.target.value\"/>\n </label>\n </div>\n <div>\n <button (click)=\"setSearch()\">\n <i class=\"fa fa-search\"></i>\n </button>\n </div>\n </div>\n <div class=\"archive\" [ngGrid]=\"gridOptions\">\n <div class=\"archive-item\" *ngFor=\"let box of boxes\" [(ngGridItem)]=\"box.config\">\n <p class=\"archive-item-type\" [style.height.px]=\"titleHeight\"><b>{{box.content.type}}</b><p>\n <img *ngIf=\"box.content.internal\" class=\"archive-item-img\" src=\"{{box.content.thumb}}\" [style.height.px]=\"imageSize\" [style.width.px]=\"imageSize\" [routerLink]=\"[box.content.url]\"/>\n <a *ngIf=\"!box.content.internal\" href=\"{{box.content.url}}\">\n <img class=\"archive-item-img\" src=\"{{box.content.thumb}}\" [style.height.px]=\"imageSize\" [style.width.px]=\"imageSize\"/>\n </a>\n </div>\n </div>\n <div class=\"archive-footer\">\n <button *ngIf=\"!atEnd\" (click)=\"addNextPage()\">Load More</button>\n </div>\n `,\n})\n\nexport class ArchiveComponent implements OnInit {\n private wsurl = globals.wsurl;\n\n public searchText = \"\";\n private search = \"\";\n\n private page = 1;\n private pageSize = 20;\n private imageSize = 0;\n private minImageSize = 50;\n private maxImageSize = 200;\n private titleHeight = 20;\n public boxes: Array<Box> = [];\n public atEnd = false;\n private mimMargin = 5;\n\n public gridOptions = {\n 'draggable': false,\n 'resizable': false,\n 'limit_to_screen': true,\n 'fix_to_grid': true,\n 'row_height': 0,\n 'col_width': 0,\n 'min_width': 0,\n 'min_height': 0,\n 'margins': [0],\n 'cascade': \"left\",\n }\n\n constructor(\n private lolService: LOLService,\n private route: ActivatedRoute,\n private location: Location\n ) {}\n\n ngOnInit() {\n this.sizeTheThings();\n this.addNextPage();\n window.onresize = (e) => {\n this.sizeTheThings();\n }\n }\n\n public addNextPage() {\n this.lolService.getArchive(this.pageSize, (this.page - 1) * this.pageSize, this.search).then(archives => {\n archives.forEach((archive, i) => {\n var content = {}\n if (archive.item_type === \"comic\") {\n content = {\n type: \"Comic\",\n name: \"Issue #\" + archive.comic.id + \": \" + archive.comic.title,\n thumb: this.wsurl + '/static/comics/comic' + this.pad(archive.comic.id, 3) + '.jpg',\n url: \"/comic/\" + archive.comic.id,\n internal: true,\n }\n } else if (archive.item_type === \"media\") {\n content ={\n type: archive.media.media_type.charAt(0).toUpperCase() + archive.media.media_type.slice(1),\n name: archive.media.title,\n thumb: archive.media.thumb_url,\n url: archive.media.url,\n internal: false,\n }\n }\n this.boxes.push({\n content: content,\n config: {\n col: i + 1,\n row: 1\n }\n });\n });\n if (archives.length < this.pageSize) {\n this.atEnd = true;\n }\n this.page++;\n });\n }\n\n public sizeTheThings() {\n let width = document.querySelectorAll('.archive')[0].clientWidth;\n\n this.imageSize = Math.floor(width / 3) - this.mimMargin * 2 - 4;\n this.imageSize = Math.max(this.imageSize, this.minImageSize);\n this.imageSize = Math.min(this.imageSize, this.maxImageSize);\n\n // + 4 for borders\n let itemWidth = this.imageSize + 4;\n let nthings = Math.floor(width / (itemWidth + this.mimMargin * 2));\n let margins = Math.floor(((width - (nthings * itemWidth)) / (nthings * 2)));\n\n this.gridOptions['margins'] = [margins];\n this.gridOptions['row_height'] = this.imageSize + this.titleHeight + 4;\n this.gridOptions['col_width'] = this.imageSize + 4;\n }\n\n public setSearch() {\n if (this.search !== this.searchText) {\n this.search = this.searchText;\n this.page = 1;\n this.atEnd = false;\n this.boxes = [];\n this.addNextPage();\n }\n }\n\n public onArchiveClick(url) {\n \n }\n\n\n pad(num, size) {\n var s = num+\"\";\n while (s.length < size) s = \"0\" + s;\n return s;\n }\n}\n" }, { "alpha_fraction": 0.7515151500701904, "alphanum_fraction": 0.7575757503509521, "avg_line_length": 22.714284896850586, "blob_id": "ca13955368b50b0f0f7c75fd1475e16163c51ede", "content_id": "9cd94540b85ab988b37cccf6f5e4510586595f7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 165, "license_type": "no_license", "max_line_length": 49, "num_lines": 7, "path": "/webservice/app.wsgi", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport os\nimport sys\n\nsys.path.insert(0,\"/var/www/lolable-api-staging\")\nos.chdir(\"/var/www/lolable-api-staging\")\nfrom app import app as application" }, { "alpha_fraction": 0.7197723984718323, "alphanum_fraction": 0.7197723984718323, "avg_line_length": 26.038461685180664, "blob_id": "03870c3a5e89af8a0f833e9d2bfdd645f90e5db1", "content_id": "da7935eac34d67f88d418787db384aa1b21aefe2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 703, "license_type": "no_license", "max_line_length": 77, "num_lines": 26, "path": "/webservice/app.py", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom flask_restful import Api\nfrom flask_restful.utils import cors\nfrom extensions import *\n\napp = Flask('lolws')\napp.config.from_pyfile('lolws.cfg')\napi = Api(app, decorators=[cors.crossdomain(origin='*')])\ninit_extensions(app)\n\nfrom resources import *\n\napi.add_resource(Authenticate, '/authenticate')\n\napi.add_resource(ArchiveList, '/archive')\n\napi.add_resource(BlogList, '/blogs')\napi.add_resource(Blog, '/blogs/<int:blog_id>', '/comics/<int:comic_id>/blog')\n\napi.add_resource(ComicList, '/comics')\napi.add_resource(Comic, '/comics/<string:id>', '/comics/<int:id>')\n\napi.add_resource(ConfigurationList, '/configuration')\n\nif __name__ == '__main__':\n app.run(threaded=True)\n" }, { "alpha_fraction": 0.6200873255729675, "alphanum_fraction": 0.6207111477851868, "avg_line_length": 22.231884002685547, "blob_id": "dcb22024d31f6918fa95e691b3830a07f1a31ba4", "content_id": "97a9d23ac51cfb86bddef3245cd22e989f782a54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1603, "license_type": "no_license", "max_line_length": 60, "num_lines": 69, "path": "/frontend/src/app/app.module.ts", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { FormsModule } from '@angular/forms';\nimport { HttpModule } from '@angular/http';\nimport { RouterModule, Routes } from '@angular/router';\nimport { NgGridModule } from 'angular4-grid';\n\nimport { AboutComponent } from './about.component';\nimport { AppComponent } from './app.component';\nimport { BlogComponent } from './blog.component';\nimport { BlogEntryComponent } from './blog-entry.component';\nimport { ComicComponent } from './comic.component';\nimport { ArchiveComponent } from './archive.component';\nimport { PodcastComponent } from './podcast.component';\n\nconst appRoutes: Routes = [\n {\n path: '',\n redirectTo: '/comic',\n pathMatch: 'full'\n },\n {\n path: 'about',\n component: AboutComponent\n },\n {\n path : 'archive',\n component: ArchiveComponent\n },\n {\n path: 'blog',\n component: BlogComponent\n },\n {\n path: 'comic',\n component: ComicComponent\n },\n {\n path : 'comic/:id',\n component: ComicComponent\n },\n {\n path : 'podcast',\n component: PodcastComponent\n }\n];\n\n\n@NgModule({\n declarations: [\n AppComponent,\n AboutComponent,\n ArchiveComponent,\n BlogComponent,\n BlogEntryComponent,\n ComicComponent,\n PodcastComponent,\n ],\n imports: [\n BrowserModule,\n FormsModule,\n HttpModule,\n NgGridModule,\n RouterModule.forRoot(appRoutes),\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }\n" }, { "alpha_fraction": 0.5927602052688599, "alphanum_fraction": 0.5927602052688599, "avg_line_length": 23.55555534362793, "blob_id": "1b5cfe79180ec82982055d824352863859bee3f9", "content_id": "caf552642555d8b71c5171735e997f0f4044b67c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 221, "license_type": "no_license", "max_line_length": 41, "num_lines": 9, "path": "/webservice/utils.py", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "from flask import jsonify\n\ndef json_response(f):\n def wrap(*args, **kwargs):\n status, data = f(*args, **kwargs)\n resp = jsonify(data)\n resp.status_code = status\n return resp\n return wrap\n" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.8055555820465088, "avg_line_length": 17, "blob_id": "41af03afa44692b482eb432f0aa0b868323329c9", "content_id": "8c75d1378866c20977267101d4599f0be1a54759", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 36, "license_type": "no_license", "max_line_length": 24, "num_lines": 2, "path": "/README.md", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "# lolable2\nLolable Colon The Sequel\n" }, { "alpha_fraction": 0.6367583274841309, "alphanum_fraction": 0.6541244387626648, "avg_line_length": 31.85714340209961, "blob_id": "5a7f73e2b17ad0c8be857707801594f1ecc6d1c5", "content_id": "dc1eaecdecc9101560cfc7dd225f6538fc7ee0c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 691, "license_type": "no_license", "max_line_length": 78, "num_lines": 21, "path": "/webservice/resources/auth.py", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "from flask import request\nfrom flask_restful import Resource\n\nfrom models import UserModel\nfrom schemas import UserSchema\nfrom utils import json_response\n\nclass Authenticate(Resource):\n @json_response\n def post(self):\n username = request.form['username']\n password = request.form['password']\n if username is None or password is None:\n return 401, {}\n # XXX - A timing attack could probably be used to enumerate users here\n user = UserModel.query.filter_by(username=username).first()\n if user is None:\n return 401, {}\n if not user.check_password(password):\n return 401, {}\n return 200, 'Success'\n\n" }, { "alpha_fraction": 0.5020352602005005, "alphanum_fraction": 0.5047490000724792, "avg_line_length": 24.413793563842773, "blob_id": "420af8c7ac6c5b23c4bc686514846a3586144d9a", "content_id": "d2d4b0007e72c652c5f028808e91814280978dd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2211, "license_type": "no_license", "max_line_length": 63, "num_lines": 87, "path": "/frontend/src/app/lol.service.ts", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { Http } from '@angular/http';\n\nimport * as globals from './globals';\n\n@Injectable()\nexport class LOLService {\n\n constructor(private http: Http) {}\n\n private get(resource: string) {\n return this.http.get(globals.wsurl + '/' + resource)\n .toPromise()\n .then(response => response.json())\n .catch(this.handleError);\n }\n\n getBlogs(limit=null, offset=null) {\n let params = [];\n var s = 'blogs?';\n if (limit !== null) {\n params.push(\"limit=\" + limit)\n }\n if (offset !== null) {\n params.push(\"offset=\" + offset)\n }\n return this.get(s + params.join('&'));\n }\n\n getConfig() {\n return this.get('configuration');\n }\n\n getComics(limit=null, offset=null, search=null) {\n let params = [];\n var s = 'comics?';\n if (limit !== null) {\n params.push(\"limit=\" + limit)\n }\n if (offset !== null) {\n params.push(\"offset=\" + offset)\n }\n if (search !== null) {\n params.push(\"search=\" + encodeURIComponent(search))\n }\n return this.get(s + params.join('&'));\n }\n\n getComic(id: number) {\n return this.get('comics/' + id);\n }\n\n getComicBlog(id: number) {\n return this.get('comics/' + id + '/blog');\n }\n\n getComicNewest() {\n return this.get('comics/newest');\n }\n\n getComicRandom() {\n return this.get('comics/random');\n }\n\n getArchive(limit=null, offset=null, search=null) {\n let params = [];\n var s = 'archive?';\n if (limit !== null) {\n params.push(\"limit=\" + limit)\n }\n if (offset !== null) {\n params.push(\"offset=\" + offset)\n }\n if (search !== null) {\n params.push(\"search=\" + encodeURIComponent(search))\n }\n return this.get(s + params.join('&'));\n }\n\n private handleError(error: any) {\n /* 404s are expected in some cases */\n if (error.status != 404) {\n console.error('An error occurred', error);\n }\n return Promise.reject(error.message || error);\n }\n}\n" }, { "alpha_fraction": 0.7798165082931519, "alphanum_fraction": 0.7798165082931519, "avg_line_length": 21, "blob_id": "6b8115c933a6830ba6b89559a26388e261d03b06", "content_id": "7c5eee1b5ba7e7cb643bdc17dffcd66217ec0d10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 109, "license_type": "no_license", "max_line_length": 27, "num_lines": 5, "path": "/webservice/resources/__init__.py", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "from archive import *\nfrom auth import *\nfrom blogs import *\nfrom comics import *\nfrom configuration import *" }, { "alpha_fraction": 0.48854732513427734, "alphanum_fraction": 0.5072332620620728, "avg_line_length": 28.362831115722656, "blob_id": "18857b53f4b7c6ec292616c4cd71f750ab7be13d", "content_id": "8474948498f0fed9dea30f22bc48bcbefdc85bc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3318, "license_type": "no_license", "max_line_length": 83, "num_lines": 113, "path": "/frontend/src/app/blog-entry.component.ts", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "import { Component, Input, OnInit } from '@angular/core';\nimport {DomSanitizer} from '@angular/platform-browser';\n\nimport { LOLService } from './lol.service';\n\n@Component({\n selector: 'lol-blog-entry',\n styles: [`\n @media (max-width: 500px) {\n .blog-entry {\n margin-left: 10px;\n margin-right: 10px;\n }\n }\n\n @media (min-width: 500px) {\n .blog-entry {\n margin-left: 50px;\n margin-right: 50px;\n }\n }\n\n .blog-entry {\n border-radius: 25px;\n border: 2px solid #000000;\n padding-top: 10px;\n padding-bottom: 10px;\n padding-left: 10px;\n text-align: left;\n background-color:rgba(255, 255, 255, 0.5);\n }\n\n :host >>> * {\n display:block;\n margin-top: 20px;\n margin-bottom: 20px;\n margin-left: auto;\n margin-right: auto;\n padding-left: 5px;\n padding-right: 5px;\n }\n `],\n template:`\n <div *ngIf=\"blogTitle && blogContent\" class=\"blog-entry\">\n <div class=\"title blog-entry-title\">\n {{blogTitle}}\n </div>\n <div class=\"text blog-entry-data\" [innerHTML]=\"blogContent\">\n </div>\n </div>\n `,\n})\n\nexport class BlogEntryComponent implements OnInit {\n comic = undefined;\n blogTitle = undefined;\n blogContent = undefined;\n\n constructor(private lolService: LOLService, private sanitizer: DomSanitizer) {}\n\n ngOnInit() {\n this.resizeYoutube();\n }\n\n @Input()\n set blog(blog) {\n if (blog === undefined) {\n this.blogTitle = undefined;\n this.blogContent = undefined;\n } else {\n this.blogTitle = blog.title;\n this.blogContent = this.sanitizer.bypassSecurityTrustHtml(blog.blog);\n }\n }\n\n @Input()\n set selectedComic(selectedComic) {\n this.comic = selectedComic;\n this.lolService.getComicBlog(this.comic.id)\n .then(blog => this.blog = blog, err => this.blog = undefined);\n }\n\n resizeYoutube() {\n var iframes = document.getElementsByTagName('iframe');\n for (var i = 0; i < iframes.length; i++) {\n var iframe = iframes[i];\n var players = /www.youtube.com|player.vimeo.com/;\n if (iframe.src.search(players) === -1) {\n continue\n }\n if (iframe.parentElement.className === 'fluid-vids') {\n continue;\n }\n\n var videoRatio = (Number(iframe.height) / Number(iframe.width)) * 100;\n iframe.style.position = 'absolute';\n iframe.style.top = '0';\n iframe.style.left = '0';\n iframe.width = '100%';\n iframe.height = '100%';\n\n var wrap = document.createElement( 'div' );\n wrap.className = 'fluid-vids';\n wrap.style.width = '100%';\n wrap.style.position = 'relative';\n wrap.style.paddingTop = videoRatio + '%';\n\n var iframeParent = iframe.parentNode;\n iframeParent.insertBefore( wrap, iframe );\n wrap.appendChild( iframe );\n }\n }\n}\n" }, { "alpha_fraction": 0.7224880456924438, "alphanum_fraction": 0.7224880456924438, "avg_line_length": 16.5, "blob_id": "a8e031af31c23351e30125cd890f01c94922d1e7", "content_id": "8ced09ae202d562f6109f318859e97fa98bf8117", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 209, "license_type": "no_license", "max_line_length": 41, "num_lines": 12, "path": "/webservice/extensions.py", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "from flask_marshmallow import Marshmallow\nfrom flask_sqlalchemy import SQLAlchemy\n\ndb = None\nma = None\n\ndef init_extensions(app):\n global db\n global ma\n\n db = SQLAlchemy(app)\n ma = Marshmallow(app)" }, { "alpha_fraction": 0.694915235042572, "alphanum_fraction": 0.694915235042572, "avg_line_length": 18.66666603088379, "blob_id": "5679f65ac89a0bb58c4cdae2db8140cd98691b4b", "content_id": "ae1d0deba6f8df43cb0ef4e98146386b5c73f09e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 59, "license_type": "no_license", "max_line_length": 43, "num_lines": 3, "path": "/frontend/src/app/globals.ts", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "'use strict';\n\nexport var wsurl='https://api.lolable.com';\n" }, { "alpha_fraction": 0.4342813193798065, "alphanum_fraction": 0.44273635745048523, "avg_line_length": 24.019229888916016, "blob_id": "d424ffd3ecdb0c03058ad014fdeb9d100149c252", "content_id": "a90e3cc933906b8c4fe106cd879cc53f7ba05fb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1301, "license_type": "no_license", "max_line_length": 74, "num_lines": 52, "path": "/frontend/src/app/podcast.component.ts", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "import { Component } from '@angular/core';\nimport { OnInit } from '@angular/core';\n\nimport { LOLService } from './lol.service';\n\ninterface Box {\n podcast: any;\n config: any;\n}\n\n@Component({\n selector: 'lol-podcast',\n styles: [`\n .blog-entry-wrapper {\n margin-top: 15px;\n }\n `],\n template:`\n <div [ngGrid]=\"gridOptions\">\n <div *ngFor=\"let box of boxes\" [(ngGridItem)]=\"box.config\">\n <img src=\"{{box.podcast.thumb}}\" style=\"width:inherit;\"/>\n <p>{{box.podcast.name}}</p>\n </div>\n </div>\n `,\n})\n\nexport class PodcastComponent implements OnInit {\n public boxes: Array<Box> = [];\n public gridOptions = {\n 'limit_to_screen': true,\n }\n\n constructor(private lolService: LOLService) {}\n\n ngOnInit() {\n for (var i = 0; i < 8; i++) {\n this.boxes[i] = {\n podcast: {\n name: \"Podcast \" + (i + 1),\n thumb: \"https://img.youtube.com/vi/mQIhIF_i3QA/0.jpg\",\n url: \"\",\n },\n config: {\n 'dragHandle': '.handle',\n 'col': i % 4 + 1,\n 'row': Math.floor(i / 4) + 1,\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.506263792514801, "alphanum_fraction": 0.5121591687202454, "avg_line_length": 22.807018280029297, "blob_id": "8bdf88e5de7d8c41a4922da8c4984c6f9861cb49", "content_id": "0727fb9efed04f68746b4027287e78d93d3f1b6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1357, "license_type": "no_license", "max_line_length": 96, "num_lines": 57, "path": "/frontend/src/app/blog.component.ts", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "import { Component } from '@angular/core';\nimport { OnInit } from '@angular/core';\n\n\nimport { LOLService } from './lol.service';\n\nimport * as globals from './globals';\n\n@Component({\n selector: 'lol-blog',\n styles: [`\n .blog-entry-wrapper {\n margin-top: 15px;\n }\n .blog-footer {\n text-align: center;\n }\n .blog-footer button {\n background-color: black;\n color: white;\n font-weight: bold;\n font-size: 24px;\n }\n `],\n template:`\n <div *ngIf=\"blogs\" id=\"blogs\">\n <div class=\"blog-entry-wrapper\" *ngFor=\"let blog of blogs\">\n <lol-blog-entry [blog]=\"blog\"></lol-blog-entry>\n </div>\n </div>\n <div class=\"blog-footer\">\n <button (click)=\"getNextChunk()\">Load More</button>\n </div>\n `,\n})\n\nexport class BlogComponent implements OnInit {\n private page = 1;\n private pageSize = 10;\n\n public blogs = [];\n\n constructor(private lolService: LOLService) {}\n\n ngOnInit() {\n this.getNextChunk();\n }\n\n getNextChunk() {\n this.lolService.getBlogs(this.pageSize, (this.page - 1) * this.pageSize).then(blogs => {\n blogs.forEach((blog, i) => {\n this.blogs.push(blog);\n });\n });\n this.page++;\n }\n}\n" }, { "alpha_fraction": 0.60317462682724, "alphanum_fraction": 0.6122449040412903, "avg_line_length": 18.173913955688477, "blob_id": "c01e3ba4bb715925efea4224ca0a59051434f77c", "content_id": "5e23a8ac011bae27a60d2ae77f94f6666b0726a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 441, "license_type": "no_license", "max_line_length": 65, "num_lines": 23, "path": "/webservice/admin/create_user.py", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "import sys\n\nfrom shared import db\nfrom models import UserModel\n\ndef usage():\n sys.stderr.write('usage: create_user.py username password\\n')\n\ndef main():\n if len(sys.argv) != 3:\n usage()\n sys.exit(0)\n\n new_user = UserModel()\n new_user.username = sys.argv[1]\n new_user.set_password(sys.argv[2])\n new_user.admin = True\n\n db.session.add(new_user)\n db.session.commit()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6842105388641357, "alphanum_fraction": 0.6842105388641357, "avg_line_length": 11.666666984558105, "blob_id": "ea87bc4fb0c23611c5ae2324818498ad2f7b5d4c", "content_id": "0e6454188ae3376a465c741b59e145193646c741", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 38, "license_type": "no_license", "max_line_length": 26, "num_lines": 3, "path": "/webservice/run.sh", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nPYTHONPATH=. python app.py\n" }, { "alpha_fraction": 0.5420439839363098, "alphanum_fraction": 0.5491591095924377, "avg_line_length": 28.730770111083984, "blob_id": "446d20cb79f0c51426b3e24f69dad05a3af1a84f", "content_id": "ee7d787e3c6a9cf4a5dc2d3935772ffbac52ca39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1546, "license_type": "no_license", "max_line_length": 92, "num_lines": 52, "path": "/webservice/resources/archive.py", "repo_name": "dbertouille/lolable2", "src_encoding": "UTF-8", "text": "from flask import request\nfrom flask_restful import Resource\nfrom models import ArchiveItemModel, ComicModel, MediaModel\nfrom schemas import ArchiveItemSchema\nfrom sqlalchemy import text\nfrom sqlalchemy.sql import func\n\nfrom extensions import db\nfrom utils import json_response\n\nclass ArchiveList(Resource):\n @json_response\n def get(self):\n limit = request.args.get('limit')\n if limit is None:\n limit = 10\n\n offset = request.args.get('offset')\n if offset is None:\n offset = 0\n\n search = request.args.get('search')\n if search is None:\n search = ''\n\n sql = text(\"\"\"\n SELECT 'comic' AS item_type, id, posted_date FROM comic WHERE title LIKE :search\n UNION \n SELECT 'media' AS item_type, id, posted_date FROM media WHERE title LIKE :search\n ORDER BY posted_date DESC\n LIMIT :limit \n OFFSET :offset\n \"\"\")\n\n result = db.engine.execute(\n sql,\n {\n 'search': '%' + search + '%',\n 'limit': int(limit),\n 'offset': int(offset)\n }\n )\n items = []\n for row in result:\n data = None\n if row[0] == 'comic':\n data = ComicModel.query.get(row[1])\n elif row[0] == 'media':\n data = MediaModel.query.get(row[1])\n items.append(ArchiveItemModel(row[0], data))\n\n return 200, ArchiveItemSchema(many=True).dump(items).data\n" } ]
27
PanggNOTlovebean/1119showmaker
https://github.com/PanggNOTlovebean/1119showmaker
a4f22fae5cbee85f1a07feedfc8e1891bea91121
1ce907cbfbffe834117c451f7166c4eb2b0f6af4
e82833ee996c1d240466213bbdf38269826b7d15
refs/heads/master
2023-04-13T11:12:35.874371
2021-04-22T15:08:43
2021-04-22T15:08:43
313,662,807
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 16, "blob_id": "ae26666e0f8ccff042256722c065d7fb9271fa01", "content_id": "5e0e1c015866484dcac7466dd142110cb5111d6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16, "license_type": "no_license", "max_line_length": 16, "num_lines": 1, "path": "/ttt.py", "repo_name": "PanggNOTlovebean/1119showmaker", "src_encoding": "UTF-8", "text": "print('ffffkkk')" }, { "alpha_fraction": 0.5957715511322021, "alphanum_fraction": 0.640896201133728, "avg_line_length": 32.02083206176758, "blob_id": "e31b66bb00c456db22618b380c717531ec57aaf2", "content_id": "4ac556e78c356b6672db644f998b1f5c3ea7d8a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3319, "license_type": "no_license", "max_line_length": 116, "num_lines": 96, "path": "/三维时空 直接.py", "repo_name": "PanggNOTlovebean/1119showmaker", "src_encoding": "UTF-8", "text": "\"\"\"\n============\n3D animation\n============\n\nA simple example of an animated plot... In 3D!\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.mplot3d.axes3d as p3\nimport matplotlib.animation as animation\nimport pandas as pd\n\ndef Gen_RandLine(length, dims=2):\n \"\"\"\n Create a line using a random walk algorithm\n\n length is the number of points for the line.\n dims is the number of dimensions the line has.\n \"\"\"\n lineData = np.empty((dims, length))\n lineData[:, 0] = np.random.rand(dims) # 初始化起点\n for index in range(1, length):\n # scaling the random numbers by 0.1 so\n # movement is small compared to position.\n # subtraction by 0.5 is to change the range to [-0.5, 0.5]\n # to allow a line to move backwards.\n step = ((np.random.rand(dims) - 0.5) * 0.1) # 步长\n # 下一步的位置\n lineData[:, index] = lineData[:, index - 1] + step\n\n return lineData # 返回一个shape为(3,25)的数组,3维坐标25帧\n\n\ndef update_lines(num, dataLines, lines):\n for line, data in zip(lines, dataLines):\n # NOTE: there is no .set_data() for 3 dim data...\n line.set_data(data[0:2, :num])\n line.set_3d_properties(data[2, :num])\n return lines\n\nplt.rcParams['font.family'] = ['sans-serif']\nplt.rcParams['font.sans-serif'] = ['SimHei']\nplt.rcParams['axes.unicode_minus'] = False\n# Attaching 3D axis to the figure\nfig = plt.figure()\nax = p3.Axes3D(fig)\n\n# Fifty lines of random 3-D lines (长为50的数组,每个元素为shape为3,25的ndarray,最后实际效果就是50条路径)\n# data = [Gen_RandLine(25, 3) for index in range(50)]\n# print(np.array(data).shape)\ndf1 = pd.read_csv(\"20日相关.csv\", engine=\"python\", encoding=\"utf-8\").dropna()\ndf2 = pd.read_csv(\"20日涨幅.csv\", engine=\"python\", encoding=\"utf-8\").dropna()\ndf3 = pd.read_csv(\"20日交易.csv\", engine=\"python\", encoding=\"utf-8\").dropna()\ndf1.set_index(\"date\", drop=True, inplace=True)\ndf2.set_index(\"date\", drop=True, inplace=True)\ndf3.set_index(\"date\", drop=True, inplace=True)\ndf1=df1['2020':]\ndf2=df2['2020':]\ndf3=df3['2020':]\n\ndata=[]\nfor column in df1.columns:\n try:\n # d1=(df1[column].values-np.min(df1[column].values))/(np.max(df1[column].values)-np.min(df1[column].values))\n # d2=(df2[column].values-np.min(df2[column].values))/(np.max(df2[column].values)-np.min(df2[column].values))\n # d3=(df3[column].values-np.min(df3[column].values))/(np.max(df3[column].values)-np.min(df3[column].values))\n d1=df1[column].values-0\n d2=df2[column].values-0\n d3=df3[column].values-0\n dt=np.array([d1,d2,d3])\n print(d3)\n data.append(dt)\n except :\n continue\n# Creating fifty line objects.\n# NOTE: Can't pass empty arrays into 3d version of plot()\nlines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data[:20]] # 每条路径的起始点\n\n# Setting the axes properties\nax.set_xlabel('相关')\nax.set_xlim(-0.5,1)\nax.set_ylabel('涨跌')\nax.set_ylim(-0.75,1)\nax.set_zlabel('收益')\nax.set_zlim(-0.75,0.75)\n\n\n\nax.set_title('3D Test')\n\n# Creating the Animation object\nline_ani = animation.FuncAnimation(fig, update_lines, 199, fargs=(data, lines),\n interval=200, blit=False,repeat=False)\n\nplt.show()" }, { "alpha_fraction": 0.5026548504829407, "alphanum_fraction": 0.5587020516395569, "avg_line_length": 29.482013702392578, "blob_id": "5517ce85ebd6b43d025264fd9533599f75169ffc", "content_id": "e4f25fc5cf5d4a72f1491ed63519958a1982115e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8869, "license_type": "no_license", "max_line_length": 73, "num_lines": 278, "path": "/app.py", "repo_name": "PanggNOTlovebean/1119showmaker", "src_encoding": "UTF-8", "text": "import json\nimport pandas as pd\nimport matplotlib as mpl\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\nimport matplotlib.animation as animation\nimport matplotlib.dates as mdates\n\ndef main0():\n mpl.rcParams[\"legend.fontsize\"] = 10\n fig = plt.figure()\n # df1 = pd.read_csv(\"相关score.csv\", engine=\"python\", encoding=\"utf-8\")\n # df2 = pd.read_csv(\"涨幅score.csv\", engine=\"python\", encoding=\"utf-8\")\n \n \n df1 = pd.read_csv(\"20日相关.csv\", engine=\"python\", encoding=\"utf-8\")\n df2 = pd.read_csv(\"20日涨幅.csv\", engine=\"python\", encoding=\"utf-8\")\n\n df1.set_index(\"date\", drop=True, inplace=True)\n df2.set_index(\"date\", drop=True, inplace=True)\n df1=df1['2020':]\n df2=df2['2020':]\n i = 0\n plt.plot()\n plt.subplots_adjust(\n top=1.0, bottom=0.0, left=0.11, right=0.9, hspace=0.2, wspace=0.2\n )\n for column in df1.columns:\n i=i+1\n\n try:\n ax = fig.gca(projection=\"3d\")\n x = np.arange(0, len(df1.index))\n y = df1[column]-0\n z = df2[column]-0\n ax.plot(x, y, z, label=column)\n ax.set_xlabel(\"时间(2020.01.01-2020.10.31)\")\n ax.set_ylabel(\"相关\")\n ax.set_zlabel(\"涨跌\")\n except :\n continue\n fig.canvas.set_window_title(\"创业板所有股票时空\")\n plt.show()\n return\n\ndef main0_1():\n mpl.rcParams[\"legend.fontsize\"] = 10\n fig = plt.figure()\n df1 = pd.read_csv(\"相关score.csv\", engine=\"python\", encoding=\"utf-8\")\n df2 = pd.read_csv(\"涨幅score.csv\", engine=\"python\", encoding=\"utf-8\")\n \n \n # df1 = pd.read_csv(\"20日相关.csv\", engine=\"python\", encoding=\"utf-8\")\n # df2 = pd.read_csv(\"20日涨幅.csv\", engine=\"python\", encoding=\"utf-8\")\n\n df1.set_index(\"date\", drop=True, inplace=True)\n df2.set_index(\"date\", drop=True, inplace=True)\n df1=df1['2020':]\n df2=df2['2020':]\n i = 0\n plt.plot()\n plt.subplots_adjust(\n top=1.0, bottom=0.0, left=0.11, right=0.9, hspace=0.2, wspace=0.2\n )\n for column in df1.columns:\n i=i+1\n\n try:\n ax = fig.gca(projection=\"3d\")\n x = np.arange(0, len(df1.index))\n y = df1[column]-0\n z = df2[column]-0\n ax.plot(x, y, z, label=column)\n ax.set_xlabel(\"时间(2020.01.01-2020.10.31)\")\n ax.set_ylabel(\"相关\")\n ax.set_zlabel(\"涨跌\")\n except :\n continue\n fig.canvas.set_window_title(\"创业板所有股票时空\")\n plt.show()\n return\ndef main1():\n mpl.rcParams[\"legend.fontsize\"] = 10\n fig = plt.figure()\n # df1 = pd.read_csv(\"相关score.csv\", engine=\"python\", encoding=\"utf-8\")\n # df2 = pd.read_csv(\"涨幅score.csv\", engine=\"python\", encoding=\"utf-8\")\n \n \n df1 = pd.read_csv(\"20日相关.csv\", engine=\"python\", encoding=\"utf-8\")\n df2 = pd.read_csv(\"20日涨幅.csv\", engine=\"python\", encoding=\"utf-8\")\n\n df1.set_index(\"date\", drop=True, inplace=True)\n df2.set_index(\"date\", drop=True, inplace=True)\n df1=df1['2020':]\n df2=df2['2020':]\n i = 0\n plt.plot()\n plt.subplots_adjust(\n top=1.0, bottom=0.0, left=0.11, right=0.9, hspace=0.2, wspace=0.2\n )\n for column in df1.columns:\n i=i+1\n\n try:\n if(i>20 and i<24):\n ax = fig.gca(projection=\"3d\")\n x = np.arange(0, len(df1.index))\n y = df1[column]-0\n z = df2[column]-0\n ax.plot(x, y, z, label=column)\n ax.set_xlabel(\"时间(2020.01.01-2020.10.31)\")\n ax.set_ylabel(\"相关\")\n ax.set_zlabel(\"涨跌\")\n ax.legend()\n except :\n continue\n fig.canvas.set_window_title(\"创业板少数股票股票时空\")\n plt.show()\n return\n\ndef main1_1():\n mpl.rcParams[\"legend.fontsize\"] = 10\n fig = plt.figure()\n df1 = pd.read_csv(\"相关score.csv\", engine=\"python\", encoding=\"utf-8\")\n df2 = pd.read_csv(\"涨幅score.csv\", engine=\"python\", encoding=\"utf-8\")\n \n \n # df1 = pd.read_csv(\"20日相关.csv\", engine=\"python\", encoding=\"utf-8\")\n # df2 = pd.read_csv(\"20日涨幅.csv\", engine=\"python\", encoding=\"utf-8\")\n\n df1.set_index(\"date\", drop=True, inplace=True)\n df2.set_index(\"date\", drop=True, inplace=True)\n df1=df1['2020':]\n df2=df2['2020':]\n i = 0\n plt.plot()\n plt.subplots_adjust(\n top=1.0, bottom=0.0, left=0.11, right=0.9, hspace=0.2, wspace=0.2\n )\n for column in df1.columns:\n i=i+1\n\n try:\n if(i>20 and i<24):\n ax = fig.gca(projection=\"3d\")\n x = np.arange(0, len(df1.index))\n y = df1[column]-0\n z = df2[column]-0\n ax.plot(x, y, z, label=column)\n ax.set_xlabel(\"时间(2020.01.01-2020.10.31)\")\n ax.set_ylabel(\"相关\")\n ax.set_zlabel(\"涨跌\")\n ax.legend()\n except :\n continue\n fig.canvas.set_window_title(\"创业板少数股票股票时空\")\n plt.show()\n return\ndef main2():\n mpl.rcParams[\"legend.fontsize\"] = 10\n fig = plt.figure()\n df1 = pd.read_csv(\"相关score.csv\", engine=\"python\", encoding=\"utf-8\")\n df2 = pd.read_csv(\"涨幅score.csv\", engine=\"python\", encoding=\"utf-8\")\n\n df1.set_index(\"date\", drop=True, inplace=True)\n df2.set_index(\"date\", drop=True, inplace=True)\n i = 0\n plt.plot()\n plt.subplots_adjust(\n top=1.0, bottom=0.0, left=0.11, right=0.9, hspace=0.2, wspace=0.2\n )\n\n i=0\n for column in df1.columns:\n i=i+1\n if(i==4):\n break\n ax = fig.gca(projection=\"3d\")\n x = np.arange(0, len(df1.index))\n y = df1[column]\n z = df2[column]\n ax.plot(x, y, z, label=column)\n ax.set_xlabel(\"时间(2020.01.01-2020.10.31)\")\n ax.set_ylabel(\"相关\")\n ax.set_zlabel(\"涨跌\")\n ax.legend()\n fig.canvas.set_window_title(\"创业板三支股票时空\")\n plt.show()\n return\n\ndef main3(date):\n mpl.rcParams[\"legend.fontsize\"] = 10\n fig = plt.figure()\n # df1 = pd.read_csv(\"相关score.csv\", engine=\"python\", encoding=\"utf-8\")\n # df2 = pd.read_csv(\"涨幅score.csv\", engine=\"python\", encoding=\"utf-8\")\n # df3 = pd.read_csv(\"配对score.csv\", engine=\"python\", encoding=\"utf-8\")\n df1 = pd.read_csv(\"20日相关.csv\", engine=\"python\", encoding=\"utf-8\")\n df2 = pd.read_csv(\"20日涨幅.csv\", engine=\"python\", encoding=\"utf-8\")\n df3 = pd.read_csv(\"20日交易.csv\", engine=\"python\", encoding=\"utf-8\")\n df1.set_index(\"date\", drop=True, inplace=True)\n df2.set_index(\"date\", drop=True, inplace=True)\n df3.set_index(\"date\", drop=True, inplace=True)\n i = 0\n plt.plot()\n plt.subplots_adjust(\n top=1.0, bottom=0.0, left=0.11, right=0.9, hspace=0.2, wspace=0.2\n )\n i=0\n x=df1.loc[date].values\n y=df2.loc[date].values\n z=df3.loc[date].values\n d=np.arange(0,len(df1.columns))\n ax = fig.gca(projection=\"3d\")\n ax.scatter(x, y, z,c=d,cmap='hsv')\n ax.set_xlabel(\"相关\")\n ax.set_ylabel(\"涨跌\")\n ax.set_zlabel(\"收益\")\n ax.legend()\n fig.canvas.set_window_title(str(date)+\"创业板\")\n plt.show()\n return\n\ndef main4():\n mpl.rcParams[\"legend.fontsize\"] = 10\n fig = plt.figure()\n\n \n plt.plot()\n plt.subplots_adjust(\n top=1.0, bottom=0.0, left=0.11, right=0.9, hspace=0.2, wspace=0.2\n )\n df1 = pd.read_csv(\"相关score.csv\", engine=\"python\", encoding=\"utf-8\")\n df2 = pd.read_csv(\"涨幅score.csv\", engine=\"python\", encoding=\"utf-8\")\n df3 = pd.read_csv(\"配对score.csv\", engine=\"python\", encoding=\"utf-8\")\n df1.set_index(\"date\", drop=True, inplace=True)\n df2.set_index(\"date\", drop=True, inplace=True)\n df3.set_index(\"date\", drop=True, inplace=True)\n i = 0\n i=0\n x=df1.loc['2020-01-02'].values\n y=df2.loc['2020-01-02'].values\n z=df3.loc['2020-01-02'].values\n # d=np.arange(0,len(df1.columns))\n d=z\n ax = fig.gca(projection=\"3d\")\n ax.scatter(x, y, z,c=d,cmap='hsv')\n\n ax.set_xlabel(\"相关\")\n ax.set_ylabel(\"涨跌\")\n ax.set_zlabel(\"收益\")\n ax.legend()\n fig.canvas.set_window_title(\"2020年1月2日创业板\")\n def update(number):\n print(number)\n anim = animation.FuncAnimation(plt.gcf(), update, interval=1)\n plt.show()\n return\n\n\nif __name__ == \"__main__\":\n plt.rcParams[\"font.family\"] = [\"sans-serif\"]\n plt.rcParams[\"font.sans-serif\"] = [\"SimHei\"]\n plt.rcParams[\"axes.unicode_minus\"] = False\n # 创业板所有股票 \n main0()\n # 创业板少数股票 \n main1()\n # 创业板所有股票 概率 \n main0_1()\n # 创业板少数股票 概率 \n main1_1()\n \n # main2()\n main3('2020-01-06')\n main3('2020-01-07')\n main3('2020-01-08')\n\n" }, { "alpha_fraction": 0.37443438172340393, "alphanum_fraction": 0.4298642575740814, "avg_line_length": 16, "blob_id": "e46bee40a70ab7b2c1fdd3ce4b586aacfe5fab6e", "content_id": "3ec660042bd9a8577909114ea48a3368bb81f960", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 884, "license_type": "no_license", "max_line_length": 36, "num_lines": 52, "path": "/figa/a.js", "repo_name": "PanggNOTlovebean/1119showmaker", "src_encoding": "UTF-8", "text": "import { Line } from '@antv/g2plot';\n\nconst data = [\n { year: '0.3', },\n { year: '', value: -0.12 },\n { year: '0.4', },\n { year: ' ', value: 0.11 },\n { year: '0.5', },\n { year: ' ', value: 0.15 },\n { year: '0.6', },\n { year: ' ', value: 0.07 },\n { year: '0.7', },\n { year: ' ', value: 0.03 },\n { year: '0.8', },\n\n];\n\nconst line = new Line('container', {\n data,\n padding:[50,30,30,200],\n xField: 'year',\n yField: 'value',\n label: {\n style: {\n fill: 'red',\n opacity: 1,\n fontSize: 15\n },\n },\n point: {\n size: 5,\n shape: 'diamond',\n style: {\n fill: 'white',\n stroke: '#5B8FF9',\n lineWidth: 2,\n },\n },\n tooltip: { showMarkers: false },\n state: {\n active: {\n style: {\n shadowBlur: 4,\n stroke: '#000',\n fill: 'red',\n },\n },\n },\n connectNulls:true,\n});\n\nline.render();\n" }, { "alpha_fraction": 0.6215022206306458, "alphanum_fraction": 0.6509572863578796, "avg_line_length": 29.200000762939453, "blob_id": "04d197f730321137d797b9115466103fa7879c44", "content_id": "1ca0d9ff6c597e78370f47850524f21514646d91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1370, "license_type": "no_license", "max_line_length": 75, "num_lines": 45, "path": "/散点动态.py", "repo_name": "PanggNOTlovebean/1119showmaker", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.animation as animation\nimport pandas as pd\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1, projection='3d')\n\n# create the parametric curve\ndf1 = pd.read_csv(\"相关score.csv\", engine=\"python\", encoding=\"utf-8\")\ndf2 = pd.read_csv(\"涨幅score.csv\", engine=\"python\", encoding=\"utf-8\")\ndf3 = pd.read_csv(\"配对score.csv\", engine=\"python\", encoding=\"utf-8\")\ndf1.set_index(\"date\", drop=True, inplace=True)\ndf2.set_index(\"date\", drop=True, inplace=True)\ndf3.set_index(\"date\", drop=True, inplace=True)\ndata=[]\nfor column in df1.columns:\n dt=np.array([df1[column],df2[column],df3[column]])\n data.append(dt)\n\npoints=[]\nfor i in len(df1.columns):\n # create the first plot\n point, = ax.plot([], [], [], 'r')\n\n\n\n# point2, =ax.plot([], [], [], '.')\n# line, = ax.plot(x, y, z, label='parametric curve')\n# ax.legend()\nax.set_xlim([0, 1])\nax.set_ylim([0, 1])\nax.set_zlim([0, 1])\n\n# second option - move the point position at every frame\ndef update_point(n, data, points):\n # point2.set_data([x[0:n], y[0:n]])\n # point2.set_3d_properties(z[0:n], 'z')\n point.set_data([x[n], y[n]])\n point.set_3d_properties(z[n], 'z')\n # point.set_array([255,0,0])\n return point\n\nani=animation.FuncAnimation(fig, update_point, 99, fargs=(x, y, z, points))\nani.save('test5.gif',writer='pillow')\nplt.show()" } ]
5
thaorell/ec463-miniproject
https://github.com/thaorell/ec463-miniproject
6cf8261d0801fcfb16bd2159d66503488b0373be
f8ea7d995f20e218b32345761a87558ae8ec6680
2da8bfd1825b2215f1e92bf0ec83d4d4053bf0ae
refs/heads/master
2020-03-28T09:47:54.490977
2018-09-21T03:13:32
2018-09-21T03:13:32
148,060,534
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7299578189849854, "alphanum_fraction": 0.752461314201355, "avg_line_length": 23.517240524291992, "blob_id": "2b4c7a0b40e817a5709abb430c6720d3859ce0ee", "content_id": "e06331f486a56683daccc52071bea0aa9df4c5f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 711, "license_type": "no_license", "max_line_length": 196, "num_lines": 29, "path": "/README.md", "repo_name": "thaorell/ec463-miniproject", "src_encoding": "UTF-8", "text": "This is a mini hardware project in EC463 Senior Design for Electrical and Computer Engineering students at Boston University. We are implementing a vehicle counting program on Raspberry Pi Zero W.\n\nContributors:\n\nCharles Thao: wrote script for vehicle counting using OpenCV and Python 3, collected, tested and saved data to disk\n\nMohammad Hashem: connected Raspberry Pi, set up Raspbian OS and SSH access, connected Pi to the Internet\n\n# Environment setup\n\n## Clone this repo\n```\ngit clone https://github.com/thaorell/ec463-miniproject\n```\n## Install Pip\n```\nsudo apt install python3-pip\n```\n\n## Install OpenCV-python\n```\nsudo pip3 install numpy\nsudo pip3 install opencv-python==3.4.3.18\n```\n\n## Run\n```\npython3 count.py\n```\n" }, { "alpha_fraction": 0.5374612808227539, "alphanum_fraction": 0.5894736647605896, "avg_line_length": 30.076923370361328, "blob_id": "8a640ce87c689b52826da080c2cc99cd38fb303d", "content_id": "e2ba5f04ae0556a0ecc595eeab69ee07e619e878", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1615, "license_type": "no_license", "max_line_length": 89, "num_lines": 52, "path": "/count.py", "repo_name": "thaorell/ec463-miniproject", "src_encoding": "UTF-8", "text": "import cv2\nimport time\nimport datetime\n\ncap = cv2.VideoCapture('./video.m4v')\n \ncar_cascade = cv2.CascadeClassifier('./cars.xml')\ncount = 0\nrate = 0\n\nstart = time.time()\nwhile True:\n # reads frames from a video\n ret, frames = cap.read()\n width = cap.get(3) \n height = cap.get(4)\n\n cv2.line(frames, (0, int(height*1/4)), (int(width), int(height*1/4)), (0,0,255), 1)\n # convert to gray scale of each frames\n gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)\n \n \n # Detects cars of different sizes in the input image\n cars = car_cascade.detectMultiScale(gray, 1.1, 1)\n\n # To draw a rectangle in each cars\n for (x,y,w,h) in cars:\n if height*1/4 - 2 <= y+h <= height*1/4 + 2: \n count = count + 1\n now = time.time() \n timeElapsed = now - start \n rate = \"{0:.2f}\".format(count / timeElapsed)\n \n cv2.rectangle(frames,(x,y),(x+w,y+h),(255,128,0),2)\n # cv2.putText(frames, str(y+h) , (x,h), cv2.FONT_HERSHEY_DUPLEX, 1 , (0,255,0))\n totalCount = \"total \" + str(count)\n rateText = str(rate) + \" cars per second \"\n cv2.putText(frames, totalCount , (50,50), cv2.FONT_HERSHEY_DUPLEX, 1 , (0,255,0))\n cv2.putText(frames, rateText , (50,80), cv2.FONT_HERSHEY_DUPLEX, 1 , (0,255,0))\n\n cv2.imshow('video2', frames)\n \n # Wait for Esc key to stop\n if cv2.waitKey(33) == 27:\n break\n\nprint(count)\nf = open(\"result.txt\", \"w\")\nout = \"The rate at \" + str(datetime.datetime.now()) + \" is \" + str(rate)\nf.write(out)\n# De-allocate any associated memory usage\ncv2.destroyAllWindows()" } ]
2
carrliitos/ClueSolver
https://github.com/carrliitos/ClueSolver
2725f831fa9844083435a0255b383107de0d1333
6b4fe1a1bf7deae58f203088c90b5459bda5feb1
1348e9383ab8acffa71f360a94ff5d22f90a83f0
refs/heads/main
2023-01-11T05:34:52.783869
2020-11-14T04:08:19
2020-11-14T04:08:19
310,163,135
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6711559891700745, "alphanum_fraction": 0.6722783446311951, "avg_line_length": 26.875, "blob_id": "7413c5177f0aa4f357abea3f17937db6ccf9194b", "content_id": "45d5980de3dd963b6b58a7769ec19c23ca784e55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 891, "license_type": "no_license", "max_line_length": 72, "num_lines": 32, "path": "/src/clue/Game.py", "repo_name": "carrliitos/ClueSolver", "src_encoding": "UTF-8", "text": "import clue.Cards as Cards\nfrom clue.Exceptions import ImpossibleError\n\n# Game class\nclass Game:\n\t'''\n\tProvide a list of players and cards.\n\tEach player should be a (name, # of cards) tuple\n\t'''\n\tnumPlayerCards = len(Cards.DECK) - 3\n\n\tdef __init__(self, me, others):\n\t\tself.others = others\n\t\tself.othersByName = {p.name for p in others}\n\t\t\n\t\tif len(self.othersByName) != len(self.others):\n\t\t\traise ImpossibleError(\"Player names must be unique!\")\n\n\t\tself.me = me\n\t\ttotalCards = self.me.numCards + sum([p.numCards for p in self.others])\n\t\tif totalCards != self.numPlayerCards:\n\t\t\traise ImpossibleError(\n\t\t\t\t\"%s cards held by players should be %s.\"\n\t\t\t\t%(totalCards, self.numPlayerCards)\n\t\t\t\t)\n\n\tdef snapshot(self):\n\t\treturn self.__class__(self.me.snapshot(), \n\t\t\t[p.snapshot() for p in self.others])\n\n\tdef __repr__(self):\n\t\treturn \"%s(%r, %r)\" % (self.__class__.__name__, self.me, self.others)" }, { "alpha_fraction": 0.6251710057258606, "alphanum_fraction": 0.6450068354606628, "avg_line_length": 27.134614944458008, "blob_id": "5f089f29d525e391660ee748ae334a02101b6db9", "content_id": "78db11c718bde35981246a1f8e18ce9ae99300fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1462, "license_type": "no_license", "max_line_length": 62, "num_lines": 52, "path": "/tests/test_game.py", "repo_name": "carrliitos/ClueSolver", "src_encoding": "UTF-8", "text": "import pytest\n\nfrom clue.Exceptions import ImpossibleError\nfrom clue.Player import Player, Me\nfrom clue import Cards\nfrom clue import Game\n\nclass TestGame:\n\t'''Test class to make sure the game behaves properly'''\n\tdef test_others(self):\n\t\t'''Testing other players'''\n\t\tg = Game.Game(Me({}), [Player(\"Foo\", 4), Player(\"Bar\", 14)])\n\n\t\tassert len(g.others) == 2\n\t\tassert g.others[0].name == \"Foo\"\n\t\tassert g.others[0].numCards == 4\n\t\tassert g.others[1].name == \"Bar\"\n\t\tassert g.others[1].numCards == 14\n\n\tdef test_me(self):\n\t\t'''Testing my behaviors as a player'''\n\t\tg = Game.Game(Me({'Plum'}), [Player(\"Foo\", 17)])\n\n\t\tassert g.me.numCards == 1\n\t\tassert g.me.hasCards == {'Plum'}\n\n\tdef test_wrong_number_card(self):\n\t\t'''Test behavior when we have the wrong number of cards'''\n\t\twith pytest.raises(ImpossibleError):\n\t\t\tGame.Game(Me({}), [Player(\"Foo\", 3)])\n\n\tdef test_dupe_player_names(self):\n\t\t'''Test behavior when multiple other names are identical'''\n\t\twith pytest.raises(ImpossibleError):\n\t\t\tGame.Game(Me({}), [Player(\"Foo\", 3), Player(\"Foo\", 13)])\n\n\tdef test_snapshot(self):\n\t\t'''Test a game state snapshot'''\n\t\tg = Game.Game(Me({'White'}), [Player(\"Foo\", 17)])\n\t\tg2 = g.snapshot()\n\t\tt = Cards.Triple('White', 'Rope', 'Hall')\n\n\t\tg.me.ask(t)\n\t\tg.others[0].show(t)\n\n\t\tassert not g2.me.asked\n\t\tassert not g2.others[0].shown\n\n\tdef test_repr(self):\n\t\tg = Game.Game(Me({'White'}), [Player(\"Foo\", 17)])\n\n\t\tassert repr(g) == \"Game(Me(['White']), [Player('Foo', 17)])\"" }, { "alpha_fraction": 0.7089201807975769, "alphanum_fraction": 0.7089201807975769, "avg_line_length": 37.818180084228516, "blob_id": "253e9ee1c8cf5148c38c0b75308e7949fb6933c1", "content_id": "7e5d45c62aaab4819902e7b7a3e585b97515c89b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 426, "license_type": "no_license", "max_line_length": 72, "num_lines": 11, "path": "/tests/smartcov.py", "repo_name": "carrliitos/ClueSolver", "src_encoding": "UTF-8", "text": "def cov_source_for_test_paths(paths):\n\t'''Given test paths, return the source paths on which to measure\n\tthe coverage. If no specific test paths were given, measure coverage on\n\tentier Python code tree.'''\n\tif not paths:\n\t\treturn ['code']\n\treturn [_code_path(p) for p in paths]\n\ndef _code_path(path):\n\t'''Returns the code path corresponding to a given test path.'''\n\treturn path.replace('tests/', 'clue/').replace('test_', '')" }, { "alpha_fraction": 0.8500000238418579, "alphanum_fraction": 0.8500000238418579, "avg_line_length": 19.5, "blob_id": "0b1cc95609dc41e2b28cd021be3bfffb718bade6", "content_id": "d854163f02d662c8d3f16c7cdc0f31e1b66c3cfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 40, "license_type": "no_license", "max_line_length": 34, "num_lines": 2, "path": "/src/clue/Exceptions.py", "repo_name": "carrliitos/ClueSolver", "src_encoding": "UTF-8", "text": "class ImpossibleError(ValueError):\n\tpass" }, { "alpha_fraction": 0.6899576783180237, "alphanum_fraction": 0.6932849287986755, "avg_line_length": 28.526784896850586, "blob_id": "a16ba56eb19b8889750fef1f903150a6e160e179", "content_id": "ce4b6d1e7fe249a8561fef35d0d353d028cfa4bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3306, "license_type": "no_license", "max_line_length": 77, "num_lines": 112, "path": "/src/clue/Cli.py", "repo_name": "carrliitos/ClueSolver", "src_encoding": "UTF-8", "text": "from clue.Cards import DECK, ROOMS, WEAPONS, PEOPLE, Triple\nfrom clue.Game import Game\nfrom clue.Player import Player, Me\n\nclass CliError(Exception):\n\tpass\n\nclass UnknownCardError(CliError):\n\tpass\n\nclass UnknownPlayerError(CliError):\n\tpass\n\ndef readGame():\n\t'''\tQuery the user about the initial game setup (players and cards).'''\n\tmyCards = readCards(\"My cards (comma-separated): \")\n\tprint(\"My cardsa re %r\" % myCards)\n\tme = Me(myCards)\n\tothers = []\n\tcardsSoFar = me.numCards\n\tprint(\"Tell me about the other players, starting from my left.\")\n\t\n\twhile cardsSoFar < Game.numPlayerCards:\n\t\tdefaultName = \"Player %s\" % (len(others) + 1)\n\t\tmaxCards = Game.numPlayerCards - cardsSoFar\n\t\tdefaultNumCards = min(3, maxCards)\n\t\tplayer = readPlayer(defaultName, defaultNumCards, maxCards=maxCards)\n\t\tothers.append(player)\n\t\tcardsSoFar += player.numCards\n\n\treturn Game(me, others)\n\ndef readTriple(prompt):\n\t'''Query user for a person/weapon/room triple.'''\n\twhile True:\n\t\tcards = readCards(prompt)\n\t\trooms = [c for c in cards if c in ROOMS]\n\t\tweapons = [c for c in cards if c in WEAPONS]\n\t\tpeople = [c for c in cards if c in PEOPLE]\n\n\t\tif any(len(l) != 1 for l in [rooms, weapons, people]):\n\t\t\tprint(\"Need a person, a weapon, and a room.\")\n\t\t\tcontinue\n\n\t\treturn Triple(people[0], weapons[0], rooms[0])\n\ndef readCards(prompt):\n\t'''Query user for any non-empty list of valid cards.'''\n\twhile True:\n\t\tcards = _read(prompt, required=True).split(',')\n\t\ttry:\n\t\t\treturn [parseCard(c) for c in cards]\n\t\texcept UnknownCardError as e:\n\t\t\tprint(e)\n\ndef readPlayer(defaultName, defaultNumCards=3,maxCards=None):\n\t'''Query user for name of a player'''\n\tname = _read(\"Name\", default=defaultName)\n\twhile True:\n\t\tnumCards = _read(\n\t\t\t\"How many cards does %s have?\" % name,\n\t\t\tdefault = defaultNumCards,\n\t\t\tcoerceTo = int\n\t\t\t)\n\t\tprint(\"got %s\" % numCards)\n\t\tif maxCards and numCards > maxCards:\n\t\t\tif maxCards == 1:\n\t\t\t\tmsg = \"There's only 1 card\"\n\t\t\telse:\n\t\t\t\tmsg = \"There are only %s cards\" % maxCards\n\n\t\t\tprint(\"%s left for %s!\" % (msg, name))\n\t\t\tcontinue\n\n\t\treturn Player(name, numCards)\n\ndef parseCard(prefix):\n\t'''Parse a valid card from given unambiguous prefix.'''\n\treturn _parse(prefix, DECK, UnknownCardError, 'card')\n\ndef parsePlayer(prefix):\n\t'''Parse a valid player from given unambiguous prefix.'''\n\treturn _parse(prefix, names, UnknownPlayerError, 'player')\n\ndef _read(prompt, default=None, required=False, coerceTo=str):\n\t'''Read a value from the input with a default, and optional type coercion'''\n\tif default is not None:\n\t\tfullPrompt = \"%s [%s] \" % (prompt, default)\n\telse:\n\t\tfullPrompt = \"%s \" % prompt\n\n\twhile True:\n\t\traw = input(fullPrompt)\n\t\ttry:\n\t\t\tval = coerceTo(raw) if raw else default\n\t\texcept(TypeError, ValueError):\n\t\t\tprint(\"Sorry, I don't understand that.\")\n\t\telse:\n\t\t\tif required and not val:\n\t\t\t\tprint(\"Cant go on without an answer!\")\n\t\t\telse:\n\t\t\t\treturn val\n\ndef _parse(prefix, options, exceptionClass, optionType):\n\t'''Select one of ''options'' based on unambiuous ''prefix''.'''\n\tcanonical = prefix.lower().strip()\n\tcandidates = [o for o in options if o.lower().startswith(canonical)]\n\tif len(candidates) > 1:\n\t\traise exceptionClass(\"More than one %s matches %s.\" % (optionType, prefix))\n\telif not candidates:\n\t\traise exceptionClass(\"No %s matches %s.\" % (optionType, prefix))\n\treturn candidates[0]" }, { "alpha_fraction": 0.635062038898468, "alphanum_fraction": 0.6395164132118225, "avg_line_length": 23, "blob_id": "d4181060157f14724610694766b9aca5f54135b2", "content_id": "cb6e1bfc901881c9990a3270cdb5382ec9f213b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3143, "license_type": "no_license", "max_line_length": 77, "num_lines": 131, "path": "/tests/test_player.py", "repo_name": "carrliitos/ClueSolver", "src_encoding": "UTF-8", "text": "import pytest\n\nfrom clue.Cards import Triple, DECK\nfrom clue.Exceptions import ImpossibleError\nfrom clue import Player\n\n'''Test class for the player'''\nclass TestPlayer:\n\t'''Test for player having cards'''\n\tdef test_has_card(self):\n\t\tp = Player.Player(\"Foo\", 3)\n\n\t\tp.hasCard('Green')\n\n\t\tassert p.hasCards == {'Green'}\n\n\t'''Test for exception error when player has too many cards'''\n\tdef test_has_too_many(self):\n\t\tp = Player.Player(\"Foo\", 3)\n\t\t\n\t\tp.hasCard('Green')\n\t\tp.hasCard('Hall')\n\t\tp.hasCard('White')\n\n\t\twith pytest.raises(ImpossibleError):\n\t\t\tp.hasCard('Rope')\n\n\t'''Test when player has identical cards'''\n\tdef test_has_identical(self):\n\t\tp = Player.Player(\"Foo\", 3)\n\n\t\tp.hasCard('Green')\n\t\tp.hasCard('Green')\n\n\t\tassert p.hasCards == {'Green'}\n\n\t'''Test when a player asks another player'''\n\tdef test_ask(self):\n\t\tp = Player.Player(\"Foo\", 3)\n\t\tt = Triple('White', 'Rope', 'Hall')\n\n\t\tp.ask(t)\n\n\t\tassert p.asked == [t]\n\n\t'''Test when a player shows another player their cards'''\n\tdef test_show(self):\n\t\tp = Player.Player(\"Foo\", 3)\n\t\tt = Triple('White', 'Rope', 'Hall')\n\n\t\tp.show(t)\n\n\t\tassert p.shown == [t]\n\n\t'''Test for an impossible error for notHasCards'''\n\tdef test_show_impossible(self):\n\t\tp = Player.Player(\"Foo\", 3)\n\t\tt = Triple('White', 'Rope', 'Hall')\n\n\t\tp.notHasCards = {'Green', 'White', 'Rope', 'Hall'}\n\n\t\twith pytest.raises(ImpossibleError):\n\t\t\tp.show(t)\n\n\t'''Test when player decides not to show their cards'''\n\tdef test_noshow(self):\n\t\tp = Player.Player(\"Foo\", 3)\n\t\tt = Triple('White', 'Rope', 'Hall')\n\n\t\tp. noshow(t)\n\n\t\tassert p.notHasCards == {'White', 'Rope', 'Hall'}\n\n\t'''Test for ImpossibleError when player decides not to show their cards'''\n\tdef test_noshow_impossible(self):\n\t\tp = Player.Player(\"Foo\", 3)\n\t\tt = Triple('White', 'Rope', 'Hall')\n\n\t\tp.hasCards = {'Rope'}\n\n\t\twith pytest.raises(ImpossibleError):\n\t\t\tp.noshow(t)\n\n\t'''Test when a player checks their cards'''\n\tdef test_check_good(self):\n\t\tp = Player.Player(\"Foo\", 3)\n\n\t\tp.hasCards = {'Green', 'Rope'}\n\t\tp.notHasCards == {'White', 'Revolver'}\n\n\t\tp.check()\n\n\t'''Test if hasCards and notHasCards have similar cards when player checks'''\n\tdef test_check_bad(self):\n\t\tp = Player.Player(\"Foo\", 3)\n\n\t\tp.hasCards = {'White', 'Rope'}\n\t\tp.notHasCards = {'White', 'Revolver'}\n\n\t\twith pytest.raises(ImpossibleError):\n\t\t\tp.check()\n\n\t'''Test string representation'''\n\tdef test_repr(self):\n\t\tp = Player.Player(\"Foo\", 3)\n\n\t\tassert repr(p) == \"Player('Foo', 3)\"\n\n'''Test class for me as a player'''\nclass TestMe:\n\t'''Test to make sure me is initialized'''\n\tdef test_init(self):\n\t\tm = Player.Me({'White', 'Green', 'Hall'})\n\n\t\tassert m.hasCards == {'White', 'Green', 'Hall'}\n\t\tassert m.numCards == 3\n\t\tassert m.notHasCards == set(DECK).difference(m.hasCards)\n\n\t'''Test when we've been duped!'''\n\tdef test_dupes(self):\n\t\tm = Player.Me({'White', 'Green', 'Hall', 'White'}) # Two 'White'\n\n\t\tassert m.hasCards == {'White', 'Green', 'Hall'}\n\t\tassert m.numCards == 3\n\t\tassert m.notHasCards == set(DECK).difference(m.hasCards)\n\n\t'''Test string representation'''\n\tdef test_repr(self):\n\t\tm = Player.Me(['Plum', 'Wrench', 'Hall'])\n\n\t\tassert repr(m) == \"Me(['Hall', 'Plum', 'Wrench'])\"" }, { "alpha_fraction": 0.7022222280502319, "alphanum_fraction": 0.7022222280502319, "avg_line_length": 38.64706039428711, "blob_id": "8fc1a108e3a642aedaf332f87ab57a60080700ad", "content_id": "6a066b01b003257af2c16d501b85c45459dfb6e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 675, "license_type": "no_license", "max_line_length": 79, "num_lines": 17, "path": "/README.md", "repo_name": "carrliitos/ClueSolver", "src_encoding": "UTF-8", "text": "# Clue Game Solver\n> Benzon Carlitos Salazar\n\n## About\nThis is a repo that consists of mainly test cases to showcase my skills in unit\ntesting using the game of Clue to solve cases as an example and also using \nPython's ***pytest*** and ***unittest***. The main folder for the game is \n[here](./src/clue), and all the important test cases are [here](./tests)\n\n## Test cases implemented\n* [Test folder](./tests)\n\t* [Test card triples](./tests/test_cards.py)\n\t![Test card triples](./imgs/test_cards.png)\n\t* [Test game functions](./tests/test_game.py)\n\t![Test card triples](./imgs/test_game.png)\n\t* [Test players functions](./tests/test_player.py)\n\t![Test card triples](./imgs/test_player.png)\n\t" }, { "alpha_fraction": 0.6762425899505615, "alphanum_fraction": 0.6762425899505615, "avg_line_length": 27.128204345703125, "blob_id": "d01b77d951465e25a2203c9a708ddbcf17801c49", "content_id": "02f95f29ef3744693142e26190ba98417416eac3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2193, "license_type": "no_license", "max_line_length": 75, "num_lines": 78, "path": "/src/clue/Player.py", "repo_name": "carrliitos/ClueSolver", "src_encoding": "UTF-8", "text": "import clue.Cards as Cards\nfrom clue.Exceptions import ImpossibleError\n\n# Player class\nclass Player:\n\tdef __init__(self, name, numCards):\n\t\tself.name = name\n\t\t# number of cards this player holds\n\t\tself.numCards = numCards\n\t\t# Set of cards this player is known to have\n\t\tself.hasCards = set()\n\t\t# Set of cards this player is known NOT to have\n\t\tself.notHasCards = set()\n\t\t# list of triple as about\n\t\tself.asked = []\n\t\t# list of triples of which one has been shown to someone\n\t\tself.shown = []\n\n\tdef hasCard(self, card):\n\t\tself.hasCards.add(card)\n\t\tif len(self.hasCards) > self.numCards:\n\t\t\traise ImpossibleError(\n\t\t\t\t\"%s has only %s cards but has shwon %r\" % \n\t\t\t\t(self.name, self.numCards, self.hasCards))\n\n\tdef ask(self, triple):\n\t\tself.asked.append(triple)\n\n\tdef show(self, triple):\n\t\tif set(triple.all_cards).issubset(self.notHasCards):\n\t\t\traise ImpossibleError(\n\t\t\t\t\"%s showed me one of %s, but earlier decline to show all those.\"\n\t\t\t\t% (self.name, triple))\n\n\t\tself.shown.append(triple)\n\n\tdef noshow(self, triple):\n\t\thas = self.hasCards.intersection(triple.all_cards)\n\t\tif has:\n\t\t\traise ImpossibleError(\n\t\t\t\t\"%s declined for %s, but we know they have %s\"\n\t\t\t\t% (self.name, triple.all_cards, has))\n\n\t\tself.notHasCards.update(triple.all_cards)\n\n\tdef check(self):\n\t\timpossible = self.hasCards.intersection(self.notHasCards)\n\t\tif impossible:\n\t\t\traise ImpossibleError(\n\t\t\t\t\"%s is known to have and known to not have %s\"\n\t\t\t\t% (self.name, impossible))\n\n\tdef snapshot(self):\n\t\ts = self.__class__(self.name, self.numCards)\n\t\ts.hasCards = self.hasCards.copy()\n\t\ts.notHasCards = self.notHasCards.copy()\n\t\ts.asked = self.asked.copy()\n\t\ts.shown = self.shown.copy()\n\t\treturn s\n\n\tdef __repr__(self):\n\t\treturn \"%s(%r, %r)\" % (self.__class__.__name__, self.name, self.numCards)\n\nclass Me(Player):\n\tdef __init__(self, myCards):\n\t\tmyCards = set(myCards)\n\t\tsuper().__init__(\"Me\", len(myCards))\n\t\tself.hasCards.update(myCards)\n\t\tself.notHasCards = set(Cards.DECK).difference(self.hasCards)\n\n\tdef snapshot(self):\n\t\ts = self.__class__(self.hasCards)\n\t\ts.asked = self.asked.copy()\n\t\ts.shown = self.shown.copy()\n\t\treturn s\n\n\tdef __repr__(self):\n\t\treturn \"%s(%r)\" % (self.__class__.__name__, sorted(self.hasCards))" }, { "alpha_fraction": 0.6596906185150146, "alphanum_fraction": 0.6596906185150146, "avg_line_length": 17.644067764282227, "blob_id": "7705f1654cf5185a3626ba93820805dddab47b4e", "content_id": "60290bbc0bbc513f350b0f0ab241790463744939", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1099, "license_type": "no_license", "max_line_length": 69, "num_lines": 59, "path": "/src/clue/Cards.py", "repo_name": "carrliitos/ClueSolver", "src_encoding": "UTF-8", "text": "# Create Rooms\nROOMS = {\n\t'Hall',\n\t'Dining Room',\n\t'Billiards Room',\n\t'Ballroom',\n\t'Kitchen',\n\t'Study',\n\t'Conservatory',\n\t'Lounge',\n\t'Library'\n}\n\n# Create People\nPEOPLE = {\n\t'Green',\n\t'Mustard',\n\t'Scarlet',\n\t'Plum',\n\t'White',\n\t'Peacock'\n}\n\n# Create Weapons\nWEAPONS = {\n\t'Revolver',\n\t'Rope',\n\t'Lead Pipe',\n\t'Wrench',\n\t'Candlestick',\n\t'Knife'\n}\n\n# Create Deck with the Rooms, People, and Weapons\nDECK = ROOMS.union(PEOPLE.union(WEAPONS))\n\n# When we get an improper deck, raise an error\nclass InvalidTriple(ValueError):\n\tpass\n\nclass Triple:\n\tdef __init__(self, person, weapon, room):\n\t\tif person not in PEOPLE:\n\t\t\traise InvalidTriple(\"%s is not a person.\" % person)\n\t\tif weapon not in WEAPONS:\n\t\t\traise InvalidTriple(\"%s is not a weapon.\" % weapon)\n\t\tif room not in ROOMS:\n\t\t\traise InvalidTriple(\"%s is not a room.\" % room)\n\t\tself.person = person\n\t\tself.weapon = weapon\n\t\tself.room = room\n\n\t# Create a property with all the cards\n\t@property\n\tdef all_cards(self):\n\t\treturn [self.person, self.weapon, self.room]\n\t\n\tdef __repr__(self):\n\t\treturn \"Triple(%r, %r, %r)\" % (self.person, self.weapon, self.room)" } ]
9
ArcticSnow/lautaret2018
https://github.com/ArcticSnow/lautaret2018
ba9e798ad84ffa74ddf5be65e092d5fe186ef097
5e3b2f8b7596a0ac93f0568163c52ecb07458f8d
f7f9a36700ee5f68b5296aba781dcae0a6184ee4
refs/heads/master
2021-03-30T16:56:07.199740
2018-03-13T10:39:13
2018-03-13T10:39:13
123,446,951
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6149830222129822, "alphanum_fraction": 0.6559644937515259, "avg_line_length": 32.578948974609375, "blob_id": "b6c2d48e507002e382cab9de9fe222d04e89c923", "content_id": "a5f3c7ec2512542f689cd42c683ec48620a2d804", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3831, "license_type": "no_license", "max_line_length": 160, "num_lines": 114, "path": "/lautaret_weather.py", "repo_name": "ArcticSnow/lautaret2018", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import division\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys, os\n\nimport netCDF4\n\n# 1. cole du lautaret simulation:\npath = '/home/tintino/Documents/snowschool_lautaret_2018/Crocus_files/forcing/'\nname = 'FORCING_2017080106_2018021406.nc'\n\nid_sim = 16\n\n### display variable names\nforcing = netCDF4.Dataset(path+name) # classic opening of netCDF file\n\nfor k in forcing.variables.iterkeys():\n print k\n\n# convert time to timestamp, figure precip\ndf = pd.DataFrame()\ndf['time'] = pd.to_datetime(forcing.variables.get('time')[:], unit='h' ,origin='2017-08-01 06:00:00')\ndf['Tair'] = forcing.variables.get('Tair')[:,id_sim]-273.15\ndf['wind_speed'] = forcing.variables.get('Wind')[:,id_sim]\ndf['wind_dir'] = forcing.variables.get('Wind_DIR')[:,id_sim]\ndf['humidity'] = forcing.variables.get('HUMREL')[:,id_sim]\ndf['rain'] = forcing.variables.get('Rainf')[:,id_sim]\ndf['snow'] = forcing.variables.get('Snowf')[:,id_sim]\ndf['precip'] = df.snow*3600 + df.rain*3600\ndf['To'] = np.abs(df.Tair*0.0)\n\ndf.set_index('time', inplace=True)\n\n# select subset of time\n\ndf_winter = df.loc[df.index >= pd.to_datetime('2017-11-01')]\ndf_winter = df_winter.loc[df_winter.index <= pd.to_datetime('2018-02-17')]\n\n\n# make plot like for Finse with Tair, wind speed, and precip, crop to Nov 1\nfig, ax = plt.subplots(5, 1, sharex=True)\nax[0].plot(df_winter.index, df_winter.Tair, color='k')\n\nax[0].grid()\n#ax[0].axhline(0, color='k')\nax[0].set_ylabel('Air temp. [degC]')\nax[0].fill_between(df_winter.index, df_winter.To,\n df_winter.Tair, where=df_winter.Tair>df_winter.To, color='tomato')\nax[0].fill_between(df_winter.index, df_winter.To,\n df_winter.Tair, where=df_winter.Tair<df_winter.To, color='lightblue')\n\n# change color for wind above 6m/s\nax[1].plot(df_winter.index, df_winter.wind_speed, color='k')\nax[1].fill_between(df_winter.index,(df_winter.wind_speed*0+4), df_winter.wind_speed, where=df_winter.wind_speed>(df_winter.wind_speed*0+4), color='yellowgreen')\n\nax[1].grid(linestyle=':')\nax[1].set_ylabel('Wind speed [m/s]')\n\nax[2].plot(df_winter.index, df_winter.precip.cumsum(), color='k')\nax[2].grid(linestyle=':')\nax[2].set_ylabel('Precipitation cumul [kg/m2]')\n\n \nax[3].plot(df_winter.index, df_winter.snow, color='k')\nax[3].grid(linestyle=':')\nax[3].set_ylabel('Snow fall rate [kg/m2/s]')\n\n\nax[4].plot(df_winter.index, df_winter.rain, color='k')\nax[4].grid(linestyle=':')\nax[4].set_ylabel('Rain fall rate [kg/m2/s]')\n\n\n#================================================\n\ndata['To'] = 0\ndata['Uth'] = 6\ndata['FF_24'] = data.FF.rolling(window=4, min_periods=2).mean()\n\nf, ax = plt.subplots(4,1,sharex=True)\nax[1].plot(data.FF_24, color='k', alpha=.5)\nax[1].fill_between(data.index,data.Uth, data.FF_24, where=data.FF_24>data.Uth, color='yellowgreen')\nax[1].grid(linestyle=':')\nax[1].set_ylim([0,20])\nax[1].set_ylabel('Wind speed (m/s)')\nax[2].plot(data.TA, color='k', alpha=.5)\nax[2].fill_between(data.index,\n data.To,\n data.TA,\n where=data.TA>data.To,\n color='tomato')\nax[2].fill_between(data.index,data.To, data.TA, where=data.TA<data.To, color='lightblue')\nax[2].grid(linestyle=':')\nax[2].set_ylabel('Air temperature (degC)')\nax[0].plot(data.SA, color='k', alpha=.5)\nax[0].grid(linestyle=':')\n\nax[0].set_ylim([0,65])\nax[0].set_ylabel('Snow depth (cm)')\nax[3].plot(data.RR_24.dropna(), color='k', alpha=.5)\nax[3].set_ylim([0,45])\nax[3].set_ylabel('Daily precip (mm)')\nax[3].grid(linestyle=':')\nmonths = mdates.MonthLocator()\nmonthsFmt = mdates.DateFormatter('%b')\ndays = dates.DayLocator()\nax[3].xaxis.set_major_locator(months)\nax[3].xaxis.set_major_formatter(monthsFmt)\nax[3].xaxis.set_minor_locator(days)\nf.subplots_adjust(hspace=0)\n\n\n\n" }, { "alpha_fraction": 0.6218575239181519, "alphanum_fraction": 0.6721368432044983, "avg_line_length": 37.67567443847656, "blob_id": "d34c7b11ebe1711f5386451e10aef93b53f42d3e", "content_id": "8ca3c2cc824856015d58f5a9c9e299bbe715fb39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2864, "license_type": "no_license", "max_line_length": 171, "num_lines": 74, "path": "/density_plot.py", "repo_name": "ArcticSnow/lautaret2018", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import division\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nimport matplotlib.pyplot as plt\nsys.path.append('/home/tintino/Documents/snowschool_lautaret_2018/github/SSWS_notebook_clean/snowtools_git')\n#os.environ[\"PYTHONPATH\"]=\"PYTHONPATH:/home/tintino/Documents/snowschool_lautaret_2018/SSWS_notebook_clean/snowtools_git/\"\nfrom plots.proReader import ProReader\nfrom utils.obsReader import ObsReader\n\n\n#===============================================\n# density from Crocus:\nid_sim = 19\nname_f06 = '/home/tintino/Documents/snowschool_lautaret_2018/Crocus_files/PRO_2017080106_2018021706_b92.nc'\npro_f06=ProReader(name_f06, point=id_sim)\n\nfig, axes = plt.subplots(1, 5, sharex=False, sharey=True, figsize=(20, 6))\ndepth2, rho = pro_f06.plot_date(axes[0], \"rho\", date='2018021518')\n\nprint rho.mean()\nprint depth2.max()\n\n\n\ndens_df = pd.read_csv('all_data/snow_distrib/depth_density_all.csv', na_values='na')\n\ndens_df.date = pd.to_datetime(dens_df.date)\nprint dens_df.columns\n\n#===============================================\n# 1. Snow depth distribution plot\ndens_df.SD_cm.mean()\ndens_df.SD_cm.std()\n\nplt.figure()\nplt.hist(dens_df.SD_cm, bins=20, label='Alll; samples = 143')\nplt.hist(dens_df.SD_cm.loc[dens_df.date==pd.to_datetime('2018/02/14')], bins=20, label='Feb 14; samples = 36', histtype='step', linewidth=3)\nplt.hist(dens_df.SD_cm.loc[dens_df.date==pd.to_datetime('2018/02/15')], bins=20, label='Feb 15; samples = 107', histtype='step', linewidth=3)\nplt.legend()\nplt.title('Snow Depth Histogram')\nplt.xlabel('Snow Depth (cm)')\n\n\nplt.figure()\nplt.hist(dens_df.SD_cm, bins=20, label='All; samples = 143', cumulative=True, normed=True)\nplt.hist(dens_df.SD_cm.loc[dens_df.date==pd.to_datetime('2018/02/14')], bins=20, label='Feb 14; samples = 36', histtype='step', linewidth=3, cumulative=True, normed=True)\nplt.hist(dens_df.SD_cm.loc[dens_df.date==pd.to_datetime('2018/02/15')], bins=20, label='Feb 15; samples = 107', histtype='step', linewidth=3, cumulative=True, normed=True)\nplt.legend()\nplt.title('Normalized Cumulative Snow Depth Distribution')\nplt.xlabel('Snow Depth (cm)')\n\n#==============================================================\n# 2. SWE tube density plots\n\nplt.figure()\ndens_df.density_kgm3.loc[dens_df.method=='fed_sampler'].hist(alpha=.8)\n\nplt.figure()\nplt.scatter(dens_df.SD_cm.loc[dens_df.method=='fed_sampler'], dens_df.density_kgm3.loc[dens_df.method=='fed_sampler'])\nplt.xlabel('Snow depth (sm)')\nplt.ylabel('Density (kg/m3)')\n\n#==============================================================\n# 3. Compare bulk density from the three methods: SWE tube, small cutter, and micropen\n\nplt.figure()\ndens_df.boxplot('density_kgm3',by='method', notch=True)\nplt.title('Bulk density measurements intercomparison')\nplt.ylabel('Density (kg/m3)')\n\n\n" }, { "alpha_fraction": 0.6480733156204224, "alphanum_fraction": 0.6844516396522522, "avg_line_length": 32.11606979370117, "blob_id": "adbc6791e9799e800e8fe572adaac6a89bd0630c", "content_id": "09801f6fcb114eec250ce1b9de8ffb7d989759e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3711, "license_type": "no_license", "max_line_length": 182, "num_lines": 112, "path": "/plot_6-hourly.py", "repo_name": "ArcticSnow/lautaret2018", "src_encoding": "UTF-8", "text": "\n# coding: utf-8\n\n# # Read and plot output Crocus files\n# Marie Dumont and Matthieu Lafaysse, Feb. 2018 \n\n# In[2]:\n\n\n# modules import\nfrom pylab import *\nimport netCDF4\nfrom pathlib import Path\nsys.path.append('/home/anselm/Seafile/diss/software/python_source_code/SSWS/SSWS_notebook_clean/snowtools_git')\nfrom plots.proReader import ProReader\n\n\n# In[3]:\n\n\n## input file name\n#home = str(Path.home())\nhome = '/home/anselm'\nfolder='/Seafile/diss/io/Col_de_Lautaret/Crocus/'\nplot_folder='/Seafile/diss/io/Col_de_Lautaret/Crocus/plots/'\ncol_porte='PRO_1994100101_1995100100_24h.nc' # example from Col de Porte\n###b92, c13, f06 (advise from Marie)\nparameterisation='f06'\ninput_file=home+folder+'PRO_2017080106_2018021706_'+parameterisation+'.nc'\n\n\n# In[4]:\n### display variable names\ncrocus=netCDF4.Dataset(input_file) # classic opening of netCDF file\n#WSN_T_ISBA = SWE (time, Number_of_Tile, Number-of_points)\n#DSN_T_ISBA = Snow depth (time, Number_of_Tile, Number-of_points)\n# print crocus.variables\nmassif=crocus.variables['massif_num'] #15 is Oisans; \nelevation=crocus.variables['ZS']\naspect=crocus.variables['aspect']\nslope=crocus.variables['slope']\nfor i in range(0,len(massif),1):\n\n point_of_interest=i\n print i\n\n information_poi =\"massif: \", massif[point_of_interest], \" elevation: \", elevation[point_of_interest], \" aspect: \", aspect[point_of_interest], \" slope: \", slope[point_of_interest]\n print information_poi\n\n\n # In[5]:\n\n\n ### Load pro file\n pro=ProReader(input_file,point=point_of_interest) # add point argument if several points (,point=i)\n\n\n # In[ ]:\n\n\n ### display snow variable profiles for a given date\n import matplotlib.pyplot as plt\n ### names of needed variables: names are the one important for the ProReader obejct, nemaes in brackets are the correcponding\n ### ones if you use the netCDF4.Dataset and their full description\n ### grain (SNOWTYPE; snow layer grain type)\n ### ep (SNOWDZ; snow layer thickness); temp (SNOWTEMP; snow temp layer)\n ### rho (SNOWRHO; snow desnity); swe (WSN_VEG; snow water equivalent layer), ssa (SNOWSSA; snow layer specific surface area)\n ### plot infos about aspect.ele etc in plot\n ### print total snow resevoir; total depth and surface temperature in plot?(dsn_t_iba; total snow depth) (WSN_T_ISBA; total snow resevoir); (TS_ISBA; surface temperature)\n # possible var values are : tel, ram, age, swe, rho, ...\n output_path=home+plot_folder\n date='2018021600'\n output_file1=output_path+date+'-'+parameterisation+'-point_of_interest_'+str(point_of_interest)+'-grain_temperature_density_swe_ssa'\n\n fig, axes = plt.subplots(1, 5, sharex=False, sharey=True, figsize=(20,6))\n pro.plot_date(axes[0], \"grain\", date=date)\n depth, temp = pro.plot_date(axes[1], \"temp\", date=date)\n depth2, rho = pro.plot_date(axes[2], \"rho\", date=date)\n depth3, swe = pro.plot_date(axes[3], \"swe\", date=date)\n depth4, ssa = pro.plot_date(axes[4], \"ssa\", date=date)\n axes[1].set_xlim(260,274)\n axes[2].set_xlim(0,1000)\n axes[0].set_ylabel('Depth (m)')\n plt.title(information_poi,loc='right')\n plt.savefig(output_file1+'.png')\n plt.savefig(output_file1+'.svg')\n\n\n# In[47]:\n\n\n\n# ### display numerical value in the netCDF file\n#\n#\n# print \"depth array\", depth\n# print \"temperature array\", temp\n#\n#\n# # In[16]:\n#\n#\n# ## display the seasonnal evolution of one variable\n# begin=\"19941201\"\n# end=\"19950501\"\n#\n#\n# fig, axes = plt.subplots(3, 1, sharex=True, sharey=False, figsize=(12,12))\n# pro.plot(axes[0], \"grain\", b=begin,e=end)\n# pro.plot(axes[1], \"ssa\", b=begin,e=end)\n# pro.plot(axes[2], \"rho\", b=begin,e=end)\n# ## possible variables to plot : tel, ram, age, swe, temp, ...\n# plt.show()\n\n" }, { "alpha_fraction": 0.7162426710128784, "alphanum_fraction": 0.7240704298019409, "avg_line_length": 37.92307662963867, "blob_id": "507da0db74a19bdb38da77909074aa02bbfc26c0", "content_id": "758707616b129790b4bc70565dfde0953ecbeb8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 511, "license_type": "no_license", "max_line_length": 132, "num_lines": 13, "path": "/readme.md", "repo_name": "ArcticSnow/lautaret2018", "src_encoding": "UTF-8", "text": "README\n\nCode to process and display data from the winter snow school 2018 at the col du Lautaret.\n\nTo plot Crocus and its forcing data use the scripts:\n - plot_crocus.py\n - lautaret_weather.py\n \nTodo:\n - plot weather and snow evo on subplots with the same x-ais extent\n - plot snowpit simulated by crocus next to observation (cannot load caaml file at the moment). maybe simply do it in illustrator\n - Compare density from SWE tube, Micro pen, and pit. Have a boxplot for all three\n - \n " }, { "alpha_fraction": 0.6122539639472961, "alphanum_fraction": 0.6683439612388611, "avg_line_length": 34.9361686706543, "blob_id": "e628f6905d8224926d096fcfc3ff3f51ed5414d5", "content_id": "701ccacc8e9fcfc3256ee6be324397b90f4d3e7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6757, "license_type": "no_license", "max_line_length": 127, "num_lines": 188, "path": "/plot_crocus.py", "repo_name": "ArcticSnow/lautaret2018", "src_encoding": "UTF-8", "text": "# script to plot and compare observation and CROCUS output\n\nfrom pylab import *\nimport netCDF4\nimport sys\nimport matplotlib.pyplot as plt\nsys.path.append('/home/tintino/Documents/snowschool_lautaret_2018/github/SSWS_notebook_clean/snowtools_git')\n#os.environ[\"PYTHONPATH\"]=\"PYTHONPATH:/home/tintino/Documents/snowschool_lautaret_2018/SSWS_notebook_clean/snowtools_git/\"\nfrom plots.proReader import ProReader\n\n\n#========================================================\n# 1. open the three simulations at col du lautaret:\nname_f06 = '/home/tintino/Documents/snowschool_lautaret_2018/Crocus_files/PRO_2017080106_2018021706_f06.nc'\nname_c13 = '/home/tintino/Documents/snowschool_lautaret_2018/Crocus_files/PRO_2017080106_2018021706_c13.nc'\nname_b92 = '/home/tintino/Documents/snowschool_lautaret_2018/Crocus_files/PRO_2017080106_2018021706_b92.nc'\n\ncroc_f06 = netCDF4.Dataset(name_f06) # classic opening of netCDF file\nfor i in croc_f06.variables.iterkeys():\n print i\n\ndef print_sim_param(input_file, poi=19):\n '''\n Functiont to print the parameter of the simulation for a given index (point of interest)\n :param input_file: paht to the crocus output file\n :param poi: point of interest (int)\n :return: nan\n '''\n\n ### display variable names\n crocus = netCDF4.Dataset(input_file) # classic opening of netCDF file\n # WSN_T_ISBA = SWE (time, Number_of_Tile, Number-of_points)\n # DSN_T_ISBA = Snow depth (time, Number_of_Tile, Number-of_points)\n # print crocus.variables\n massif = crocus.variables['massif_num'] # 15 is Oisans;\n elevation = crocus.variables['ZS']\n aspect = crocus.variables['aspect']\n slope = crocus.variables['slope']\n ### select number between 0 and 35 and see what combination you got. For investigation maybe usefull to see the netcdf file\n ### with a simple netcdf viewer like ncview (linux command line)\n information_poi = \"massif: \" + str(massif[poi]) + str(\" elevation: \") + str(elevation[poi]) + str(\n \" aspect: \") + str(aspect[poi]) + str(\" slope: \") + str(slope[poi])\n print information_poi\n return information_poi\n\n\nfor i in range(0, 45):\n print 'POI: ' + str(i)\n print_sim_param(name_f06, i)\n\nprint_sim_param(name_f06, 16)\n\n# point of interest to look at:\n# massif 16: 18,19\n# massif 15: 0,1\n#\n\n\npoi = 19\npro_f06=ProReader(name_f06, point=poi) # add point argument if several points (,point=i)\npro_c13=ProReader(name_c13, point=poi)\npro_b92=ProReader(name_b92, point=poi)\n\n#=============================================================================\n# Comparing the three simulation for a given point of interest\ndate='2018021518'\nfig, axes = plt.subplots(1, 5, sharex=False, sharey=True, figsize=(20, 6))\npro_f06.plot_date(axes[0], \"grain\", date=date)\ndepth, temp = pro_f06.plot_date(axes[1], \"temp\", date=date, color='b')\ndepth, temp = pro_c13.plot_date(axes[1], \"temp\", date=date, color='red')\ndepth, temp = pro_b92.plot_date(axes[1], \"temp\", date=date, color='green')\ndepth2, rho = pro_f06.plot_date(axes[2], \"rho\", date=date)\ndepth2, rho = pro_c13.plot_date(axes[2], \"rho\", date=date, color='red')\ndepth2, rho = pro_b92.plot_date(axes[2], \"rho\", date=date, color='green')\ndepth3, swe = pro_f06.plot_date(axes[3], \"swe\", date=date)\ndepth3, swe = pro_c13.plot_date(axes[3], \"swe\", date=date, color='red')\ndepth3, swe = pro_b92.plot_date(axes[3], \"swe\", date=date, color='green')\ndepth4, ssa = pro_f06.plot_date(axes[4], \"ssa\", date=date)\ndepth4, ssa = pro_c13.plot_date(axes[4], \"ssa\", date=date, color='red')\ndepth4, ssa = pro_b92.plot_date(axes[4], \"ssa\", date=date, color='green')\naxes[1].set_xlim(260,274)\naxes[2].set_xlim(0,1000)\naxes[0].set_ylabel('Depth (m)')\naxes[0].set_title('Simulation f06')\nplt.title(print_sim_param(name_f06, poi),loc='right')\nplt.show()\n\n\n# Comparing the grain stratigraphy inbetween the three simulation\ndate='2018021518'\nfig, axes = plt.subplots(1, 3, sharex=False, sharey=True, figsize=(20,6))\npro_f06.plot_date(axes[0], \"grain\", date=date)\npro_c13.plot_date(axes[1], \"grain\", date=date)\npro_b92.plot_date(axes[2], \"grain\", date=date)\naxes[0].set_ylabel('Depth (m)')\naxes[0].set_title('simulation f06')\naxes[1].set_title('simulation c13')\naxes[2].set_title('simulation b92')\n#plt.title(print_sim_param(name_f06, 16),loc='right')\nplt.show()\n\n\n\n\n#===========================================================================\n## display the seasonnal evolution of one variable\nbegin=\"2017110100\"\nend=\"2018021700\"\n\n# Simulation f06\nfig, axes = plt.subplots(5, 1, sharex=True, sharey=False, figsize=(12,12))\npro_f06.plot(axes[0], \"grain\", b=begin,e=end)\npro_f06.plot(axes[1], \"temp\", b=begin,e=end)\npro_f06.plot(axes[2], \"rho\", b=begin,e=end)\npro_f06.plot(axes[3], \"ssa\", b=begin,e=end)\npro_f06.plot(axes[4], \"age\", b=begin,e=end)\n## possible variables to plot : tel, ram, age, swe, temp, ...\nplt.show()\n\n\n# Simulation c13\nfig, axes = plt.subplots(5, 1, sharex=True, sharey=False, figsize=(12,12))\npro_c13.plot(axes[0], \"grain\", b=begin,e=end)\npro_c13.plot(axes[1], \"temp\", b=begin,e=end)\npro_c13.plot(axes[2], \"rho\", b=begin,e=end)\npro_c13.plot(axes[3], \"ssa\", b=begin,e=end)\npro_c13.plot(axes[4], \"age\", b=begin,e=end)\n## possible variables to plot : tel, ram, age, swe, temp, ...\nplt.show()\n\n\n# Simulation b92\nfig, axes = plt.subplots(5, 1, sharex=True, sharey=False, figsize=(12,12))\npro_b92.plot(axes[0], \"grain\", b=begin,e=end)\npro_b92.plot(axes[1], \"temp\", b=begin,e=end)\npro_b92.plot(axes[2], \"rho\", b=begin,e=end)\npro_b92.plot(axes[3], \"ssa\", b=begin,e=end)\npro_b92.plot(axes[4], \"age\", b=begin,e=end)\n## possible variables to plot : tel, ram, age, swe, temp, ...\nplt.show()\n\n\n# Combine weather and crocus snow evolution\nfig, axes = plt.subplots(4, 1, sharex=False, sharey=False, figsize=(12,12))\npro_f06.plot(axes[0], \"grain\", b=begin,e=end, legend=False, cbar_on=False)\npro_f06.plot(axes[1], \"temp\", b=begin,e=end, cbar_on=False)\n\nfig, axes = plt.subplots(1, 1, sharex=False, sharey=False, figsize=(12,12))\npro_f06.plot(axes, \"age\", b=begin,e=end, cbar_on=False)\n\n\n\naxes[3].plot(df_winter.index, df_winter.Tair, color='k')\naxes[3].grid()\n#axes[0].axhline(0, color='k')\naxes[3].set_ylabel('Air temp. [degC]')\naxes[3].fill_between(df_winter.index, df_winter.To,\n df_winter.Tair, where=df_winter.Tair>df_winter.To, color='tomato')\naxes[3].fill_between(df_winter.index, df_winter.To,\n df_winter.Tair, where=df_winter.Tair<df_winter.To, color='lightblue')\nplt.colorbar(ax=axes[3])\nplt.show()\n\n\n\n\n\n\n\n\n#WSN_T_ISBA = SWE (time, Number_of_Tile, Number-of_points)\n#DSN_T_ISBA = Snow depth (time, Number_of_Tile, Number-of_points)\n\n\n#print crocus.variables\n#print crocus.variables['aspect']\n\n\n\n\n\n\n\n# extract snow surface temperature\n\n\n\n# compare density from obs, and snowpit\n\n" }, { "alpha_fraction": 0.6110444068908691, "alphanum_fraction": 0.6812725067138672, "avg_line_length": 35.21739196777344, "blob_id": "e2b7a711c2045ecc96b1566c5314721e766a3c13", "content_id": "92c860d64bf0e1c8b1daea37f5d2c06dd121e558", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3332, "license_type": "no_license", "max_line_length": 122, "num_lines": 92, "path": "/compare_weather_snowprof.py", "repo_name": "ArcticSnow/lautaret2018", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import division\n\nfrom pylab import *\nimport netCDF4\nimport sys\nimport matplotlib.pyplot as plt\nsys.path.append('/home/tintino/Documents/snowschool_lautaret_2018/github/SSWS_notebook_clean/snowtools_git')\n#os.environ[\"PYTHONPATH\"]=\"PYTHONPATH:/home/tintino/Documents/snowschool_lautaret_2018/SSWS_notebook_clean/snowtools_git/\"\nfrom plots.proReader import ProReader\nfrom utils.obsReader import ObsReader\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nid_sim = 0\n\n#========================================================\n# 1. open the three simulations at col du lautaret:\nname_f06 = '/home/tintino/Documents/snowschool_lautaret_2018/Crocus_files/PRO_2017080106_2018021706_f06.nc'\npro_f06=ProReader(name_f06, point=id_sim) # add point argument if several points (,point=i)\n\nbegin=\"2017110100\"\nend=\"2018021700\"\n\n\nobs = ObsReader('/home/tintino/Documents/snowschool_lautaret_2018/github/201802141205_PitForest.caaml')\n\n# 1. cole du lautaret simulation:\npath = '/home/tintino/Documents/snowschool_lautaret_2018/Crocus_files/forcing/'\nname = 'FORCING_2017080106_2018021406.nc'\n\n\n\n### display variable names\nforcing = netCDF4.Dataset(path+name) # classic opening of netCDF file\n\nfor k in forcing.variables.iterkeys():\n print k\n\n# convert time to timestamp, figure precip\ndf = pd.DataFrame()\ndf['time'] = pd.to_datetime(forcing.variables.get('time')[:], unit='h' ,origin='2017-08-01 06:00:00')\ndf['Tair'] = forcing.variables.get('Tair')[:,id_sim]-273.15\ndf['wind_speed'] = forcing.variables.get('Wind')[:,id_sim]\ndf['wind_dir'] = forcing.variables.get('Wind_DIR')[:,id_sim]\ndf['humidity'] = forcing.variables.get('HUMREL')[:,id_sim]\ndf['rain'] = forcing.variables.get('Rainf')[:,id_sim]\ndf['snow'] = forcing.variables.get('Snowf')[:,id_sim]\ndf['precip'] = df.snow*3600 + df.rain*3600\ndf['To'] = np.abs(df.Tair*0.0)\n\ndf.set_index('time', inplace=True)\n\n# select subset of time\n\ndf_winter = df.loc[df.index >= pd.to_datetime('2017-11-01')]\ndf_winter = df_winter.loc[df_winter.index <= pd.to_datetime('2018-02-17')]\n\n\n#========================================================\n# Combine weather and crocus snow evolution\nfig, axes = plt.subplots(5, 1, sharex=False, sharey=False, figsize=(12,12))\npro_f06.plot(axes[0], \"grain\", b=begin,e=end, legend=False, cbar_on=False)\npro_f06.plot(axes[3], \"temp\", b=begin,e=end, cbar_on=False)\n#pro_f06.plot(axes[2], \"age\", b=begin,e=end, cbar_on=False)\n\n\naxes[1].plot(df_winter.index, df_winter.rain, color='k')\naxes[1].grid()\n#axes[0].axhline(0, color='k')\naxes[1].set_ylabel('Rain precip. [mm]')\naxes[1].set_xlim(['2017-11-01','2018-02-17'])\n\naxes[2].plot(df_winter.index, df_winter.snow, color='k')\naxes[2].grid()\n#axes[0].axhline(0, color='k')\naxes[2].set_ylabel('Snow precip. [mm]')\naxes[2].set_xlim(['2017-11-01','2018-02-17'])\n\n\naxes[4].plot(df_winter.index, df_winter.Tair, color='k')\naxes[4].grid()\n#axes[0].axhline(0, color='k')\naxes[4].set_ylabel('Air temp. [degC]')\naxes[4].set_xlim(['2017-11-01','2018-02-17'])\naxes[4].fill_between(df_winter.index, df_winter.To,\n df_winter.Tair, where=df_winter.Tair>df_winter.To, color='tomato')\naxes[4].fill_between(df_winter.index, df_winter.To,\n df_winter.Tair, where=df_winter.Tair<df_winter.To, color='lightblue')\nplt.show()\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 13, "blob_id": "476b9bed073c1834def8ae01665b6dd6d0370286", "content_id": "6e17c563fb74c6ffd5b736272ea06f350d98a905", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14, "license_type": "no_license", "max_line_length": 13, "num_lines": 1, "path": "/test.py", "repo_name": "ArcticSnow/lautaret2018", "src_encoding": "UTF-8", "text": "print 'ddfdf'\n" } ]
7
maichmueller/SCM
https://github.com/maichmueller/SCM
d5a11788c0c9fbd55c3118d10942474947f909e4
438762ee8b873636fc995d1bd7ceecdc948d7636
7f0d88e2b19b91be0162aed129ace7ef652b5e89
refs/heads/master
2021-03-12T01:21:04.338950
2021-01-15T13:14:55
2021-01-15T13:14:55
246,576,388
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7407407164573669, "alphanum_fraction": 0.7407407164573669, "avg_line_length": 26, "blob_id": "e48898a446eb27dd98d251380ce2cdbedb89d45f", "content_id": "209f38a43c21e1540e6f66adcafd63a2b7566b85", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 54, "license_type": "permissive", "max_line_length": 32, "num_lines": 2, "path": "/scmodels/__init__.py", "repo_name": "maichmueller/SCM", "src_encoding": "UTF-8", "text": "from .scm import SCM\nfrom .version import __version__\n" }, { "alpha_fraction": 0.5858680605888367, "alphanum_fraction": 0.6267377734184265, "avg_line_length": 22.917499542236328, "blob_id": "6120ce9cb95297a3d365d3bf3e345bc4148a3ae3", "content_id": "23143dd2793688e3e4175c928b2c646035f01c41", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9567, "license_type": "permissive", "max_line_length": 250, "num_lines": 400, "path": "/README.md", "repo_name": "maichmueller/SCM", "src_encoding": "UTF-8", "text": "| OS | Status |\n| :-------------: |:-------------:|\n| Linux | ![L Py 3.7 - 3.9](https://github.com/maichmueller/scm/workflows/L%20Py%203.7%20-%203.9/badge.svg) |\n| Windows | ![W Py 3.7 - 3.9](https://github.com/maichmueller/scm/workflows/W%20Py%203.7%20-%203.9/badge.svg) |\n| Mac | ![M Py 3.7 - 3.9](https://github.com/maichmueller/scm/workflows/M%20Py%203.7%20-%203.9/badge.svg) |\n\nA Python package implementing Structural Causal Models (SCM).\n\nThe library uses the CAS library [SymPy](https://github.com/sympy/sympy) to allow the user to state arbitrary assignment functions and noise distributions as supported by SymPy and builds the DAG with [networkx](https://github.com/networkx/networkx).\n\nIt supports the features:\n - Sampling\n - Intervening\n - Plotting\n - Printing\n\n and by extension all methods on a DAG provided by networkx after accessing the member variable dag\n\n# Installation\nEither install via pip\n```\npip install scmodels\n```\nor via cloning the repository and running the setup.py file\n```\ngit clone https://github.com/maichmueller/scm\ncd scm\npython setup.py install\n```\n\n# Building an SCM\n\nTo build the DAG\n\n![X \\rightarrow Y \\leftarrow Z \\rightarrow X](https://latex.codecogs.com/svg.latex?&space;X{\\rightarrow}{Y}{\\leftarrow}{Z}{\\rightarrow}X)\n\n\nwith the assignments\n\n![Z ~ LogLogistic(alpha=1, beta=1)](https://latex.codecogs.com/svg.latex?&space;Z\\sim\\text{LogLogistic}(\\alpha=1,\\beta=1)])\n\n![X = 3Z^2{\\cdot}N](https://latex.codecogs.com/svg.latex?&space;X={3Z^2}{\\cdot}N\\quad[N=\\text{LogNormal}(\\mu=1,\\sigma=1)])\n\n![Y = 2Z + \\sqrt{X} + N](https://latex.codecogs.com/svg.latex?&space;Y=2Z+\\sqrt{X}+N\\quad[N=\\text{Normal}(\\mu=2,\\sigma=1)])\n\nThere are 3 different ways of declaring the SCM:\n\n## 1. List Of Strings\nDescribe the assignments as strings of the form:\n\n'VAR = FUNC(Noise, parent1, parent2, ...), Noise ~ DistributionXYZ'\n\nNote that - out of convenience - in this case, one does not need to (and isn't allowed to)\nrestate the noise symbol string in the distribution (as would otherwise be necessary\nin constructing sympy distributions).\n\n\n```python\nfrom scmodels import SCM\n\nassignment_seq = [\n \"Z = M, M ~ LogLogistic(alpha=1, beta=1)\",\n \"X = N * 3 * Z ** 2, N ~ LogNormal(mean=1, std=1)\",\n \"Y = P + 2 * Z + sqrt(X), P ~ Normal(mean=2, std=1)\"\n]\n\nmyscm = SCM(assignment_seq)\n```\n\nAgreements:\n- The name of the noise variable in the distribution specification\n(e.g. `P ~ Normal(mean=2, std=1)`) has to align with the noise variable\nname (`P`) of the assignment string.\n\n## 2. Assignment Map\n\nOne can construct the SCM via an assignment map with the variables as keys\nand a tuple defining the assignment and the noise.\n\n### 2-Tuple: Assignments via SymPy parsing\n\nTo refer to SymPy's string parsing capability (this includes numpy functions) provide a dict entry\nwith a 2-tuple as value of the form:\n\n`'var': ('assignment string', noise)`\n\n\n\n\n```python\nfrom sympy.stats import LogLogistic, LogNormal, Normal\n\n\nassignment_map = {\n \"Z\": (\n \"M\",\n LogLogistic(\"M\", alpha=1, beta=1)\n ),\n \"X\": (\n \"N * 3 * Z ** 2\",\n LogNormal(\"N\", mean=1, std=1),\n ),\n \"Y\": (\n \"P + 2 * Z + sqrt(X)\",\n Normal(\"P\", mean=2, std=1),\n ),\n}\n\nmyscm2 = SCM(assignment_map)\n```\n\nAgreements:\n- the name of the noise distribution provided in its constructor\n(e.g. `Normal(\"N\", mean=2, std=1)`) has to align with the noise variable\nname (`N`) of the assignment string.\n\n### 3-Tuple: Assignments with arbitrary callables\n\nOne can also declare the SCM via specifying the variable assignment in a dictionary with the\nvariables as keys and as values a sequence of length 3 of the form:\n\n`'var': (['parent1', 'parent2', ...], Callable, Noise)`\n\nThis allows the user to supply complex functions outside the space of analytical functions.\n\n\n```python\nimport numpy as np\n\n\ndef Y_assignment(p, z, x):\n return p + 2 * z + np.sqrt(x)\n\n\nfunctional_map = {\n \"Z\": (\n [],\n lambda m: m,\n LogLogistic(\"M\", alpha=1, beta=1)\n ),\n \"X\": (\n [\"Z\"],\n lambda n, z: n * 3 * z ** 2,\n LogNormal(\"N\", mean=1, std=1),\n ),\n \"Y\": (\n [\"Z\", \"X\"],\n Y_assignment,\n Normal(\"P\", mean=2, std=1),\n ),\n}\n\nmyscm3 = SCM(functional_map)\n```\n\nAgreements:\n- The callable's first parameter MUST be the noise input (unless the noise distribution is `None`).\n- The order of variables in the parents list determines the semantic order of input for parameters in the functional\n(left to right).\n\n# Features\n\n## Prettyprint\n\nThe SCM supports a form of informative printing of its current setup,\nwhich includes mentioning active interventions and the assignments.\n\n\n```python\nprint(myscm)\n```\n\n Structural Causal Model of 3 variables: Z, X, Y\n Variables with active interventions: []\n Assignments:\n Z := f(M) = M\t [ M ~ LogLogistic(alpha=1, beta=1) ]\n X := f(N, Z) = N * 3 * Z ** 2\t [ N ~ LogNormal(mean=1, std=1) ]\n Y := f(P, Z, X) = P + 2 * Z + sqrt(X)\t [ P ~ Normal(mean=2, std=1) ]\n\n\nIn the case of custom callable assignments, the output is less informative\n\n\n```python\nprint(myscm3)\n```\n\n Structural Causal Model of 3 variables: Z, X, Y\n Variables with active interventions: []\n Assignments:\n Z := f(M) = __unknown__\t [ M ~ LogLogistic(alpha=1, beta=1) ]\n X := f(N, Z) = __unknown__\t [ N ~ LogNormal(mean=1, std=1) ]\n Y := f(P, Z, X) = __unknown__\t [ P ~ Normal(mean=2, std=1) ]\n\n\n## Interventions\nOne can easily perform interventions on the variables,\ne.g. a Do-intervention or also general interventions, which remodel the connections, assignments, and noise distributions.\nFor general interventions, the passing structure is dict of the following form:\n\n {var: (New Parents (Optional), New Assignment (optional), New Noise (optional))}\n\nAny part of the original variable state, that is meant to be left unchanged, has to be passed as `None`.\nE.g. to assign a new callable assignment to variable `X` without changing parents or noise, one would call:\n\n\n```python\nmy_new_callable = lambda n, z: n + z\n\nmyscm.intervention({\"X\": (None, my_new_callable, None)})\n```\n\nFor the example of the do-intervention ![\\text{do}(X=1=)](https://latex.codecogs.com/svg.latex?&space;\\text{do}(X=1)),\none can use the helper method `do_intervention`. The pendant for noise interventions is called `soft_intervention`:\n\n\n```python\nmyscm.do_intervention([(\"X\", 1)])\n\nfrom sympy.stats import FiniteRV\n\nmyscm.soft_intervention([(\"X\", FiniteRV(str(myscm[\"X\"].noise), density={-1: .5, 1: .5}))])\n```\n\nCalling `undo_intervention` restores the original state of all variables from construction time, that have been passed. One can optionally specify,\nIf no variables are specified (`variables=None`), all interventions are undone.\n\n\n```python\nmyscm.undo_intervention(variables=[\"X\"])\n```\n\n## Sampling\n\nThe SCM allows drawing as many samples as needed through the method `myscm.sample(n)`.\n\n\n```python\nn = 5\nmyscm.sample(n)\n```\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>Z</th>\n <th>X</th>\n <th>Y</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>3.130168</td>\n <td>25.518928</td>\n <td>13.524461</td>\n </tr>\n <tr>\n <th>1</th>\n <td>0.730453</td>\n <td>6.036398</td>\n <td>7.148895</td>\n </tr>\n <tr>\n <th>2</th>\n <td>0.179568</td>\n <td>0.156701</td>\n <td>3.149104</td>\n </tr>\n <tr>\n <th>3</th>\n <td>0.879909</td>\n <td>6.787311</td>\n <td>6.056273</td>\n </tr>\n <tr>\n <th>4</th>\n <td>1.710136</td>\n <td>20.079351</td>\n <td>8.894617</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\nIf infinite sampling is desired, one can also receive a sampling generator through\n\n\n```python\ncontainer = {var: [] for var in myscm}\nsampler = myscm.sample_iter(container)\n```\n\n`container` is an optional target dictionary to store the computed samples in.\n\n\n```python\nimport pandas as pd\n\nfor i in range(n):\n next(sampler)\n\npd.DataFrame.from_dict(container)\n```\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>Z</th>\n <th>X</th>\n <th>Y</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>0.341271</td>\n <td>1.271099</td>\n <td>4.547078</td>\n </tr>\n <tr>\n <th>1</th>\n <td>2.722751</td>\n <td>235.765034</td>\n <td>22.591202</td>\n </tr>\n <tr>\n <th>2</th>\n <td>0.081638</td>\n <td>0.107539</td>\n <td>3.898544</td>\n </tr>\n <tr>\n <th>3</th>\n <td>2.745713</td>\n <td>210.743838</td>\n <td>21.806575</td>\n </tr>\n <tr>\n <th>4</th>\n <td>1.528015</td>\n <td>9.768679</td>\n <td>9.058807</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\nIf the target container is not provided, the generator returns a new `dict` for every sample.\n\n\n```python\nsample = next(myscm.sample_iter())\npd.DataFrame.from_dict(sample)\n```\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>Z</th>\n <th>X</th>\n <th>Y</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>0.399457</td>\n <td>3.369994</td>\n <td>6.946475</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\n## Plotting\nIf you have graphviz installed, you can plot the DAG by calling\n\n```python\nmyscm.plot(node_size=1000, alpha=1)\n```\n\n![example_plot](https://github.com/maichmueller/scm/blob/master/docs/images/example_plot.png)\n\n\n```python\n\n```\n" }, { "alpha_fraction": 0.5064935088157654, "alphanum_fraction": 0.6883116960525513, "avg_line_length": 12, "blob_id": "78e9881fd7c622970cdbbe0cfa40a918f41e1d61", "content_id": "f19ca485dde85eeac0528773b56e40d9d75eb64c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 77, "license_type": "permissive", "max_line_length": 15, "num_lines": 6, "path": "/requirements.txt", "repo_name": "maichmueller/SCM", "src_encoding": "UTF-8", "text": "sympy>=1.7.1\nnetworkx>=2.0\npandas>=1.0\nscipy>=1.3\nnumpy>=1.19\nmatplotlib>=3.0" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.6492374539375305, "avg_line_length": 28.612903594970703, "blob_id": "75cf9f48c31cc3b270d263e931809ebb11f78512", "content_id": "01a28cf0da8670ba212104762b2bb480a14cd4e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1836, "license_type": "permissive", "max_line_length": 78, "num_lines": 62, "path": "/setup.py", "repo_name": "maichmueller/SCM", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\nimport os\n\nwith open(\"README.md\") as readme_file:\n readme = readme_file.read()\n\nwith open(\"HISTORY.md\") as history_file:\n history = history_file.read()\n\n\nwith open('requirements.txt') as f:\n requirements = f.read().splitlines()\n\nsetup_requirements = [\"pytest-runner\"]\n\ntest_requirements = [\"pytest\"]\n\nextras_requirements = {\"plot\": [\"pygraphviz\", \"graphviz\"], \"test\": [\"pytest\"]}\n\nauthor = \"Michael Aichmueller\"\n\n# This directory\ndir_setup = os.path.dirname(os.path.realpath(__file__))\n__version__ = \"\"\nwith open(os.path.join(dir_setup, 'scmodels', 'version.py')) as f:\n # Defines __version__\n exec(f.read())\n\nsetup(\n author=author,\n author_email=\"[email protected]\",\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: MIT License\",\n \"Natural Language :: English\",\n \"Programming Language :: Python :: 3.7\",\n \"Operating System :: MacOS :: MacOS X\",\n \"Operating System :: Microsoft :: Windows\",\n \"Operating System :: POSIX :: Linux\",\n \"Topic :: Scientific/Engineering :: Mathematics\",\n ],\n description=\"Structural Causal Models\",\n install_requires=requirements,\n license=\"MIT license\",\n long_description=readme + \"\\n\\n\" + history,\n long_description_content_type='text/markdown',\n include_package_data=True,\n keywords=\"bayesian graphs scm sem fcm causal graphical models causality\",\n name=\"scmodels\",\n packages=find_packages(exclude=(\"test\",)),\n setup_requires=setup_requirements,\n test_suite=\"test\",\n tests_require=test_requirements,\n extras_require=extras_requirements,\n url=\"https://github.com/maichmueller/scmodels\",\n version=__version__,\n zip_safe=False,\n)\n" }, { "alpha_fraction": 0.5501229763031006, "alphanum_fraction": 0.5856908559799194, "avg_line_length": 31.84848403930664, "blob_id": "0dcd76ab30d6e5b5e9f7fd3c6548c3114c7323e9", "content_id": "c1c97a5dc58757f67eb028019e263383ef5f68f6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9756, "license_type": "permissive", "max_line_length": 104, "num_lines": 297, "path": "/test/test_scm.py", "repo_name": "maichmueller/SCM", "src_encoding": "UTF-8", "text": "import random\nimport numpy as np\nimport pandas as pd\nfrom numpy.polynomial.polynomial import Polynomial\nfrom test.build_scm import *\nfrom scmodels.parser import parse_assignments, extract_parents\n\n\ndef manual_sample_linandpoly(n, dtype, names, seed):\n def x1(n, x0):\n return 1 + n + Polynomial([0, 0, 2])(x0)\n\n def x2(n, x0, x1):\n return 1 + n + 3 * x0 + 2 * x1\n\n def x3(n, x1, x2):\n return n + x1 + 0.5 * np.sqrt(x1.abs()) + 4 * np.log(x2.abs())\n\n def y(n, x0, x2):\n return n + Polynomial([0, 0, 0.05])(x0) + 2 * x2\n\n rng = np.random.default_rng(seed)\n noise_func = lambda size: rng.normal(loc=0, scale=1, size=size)\n sample = pd.DataFrame(np.empty((n, 5), dtype=dtype), columns=names)\n sample.loc[:, \"X_0\"] = noise_func(n)\n sample.loc[:, \"X_1\"] = x1(noise_func(n), sample[\"X_0\"])\n sample.loc[:, \"X_2\"] = x2(noise_func(n), sample[\"X_0\"], sample[\"X_1\"])\n sample.loc[:, \"X_3\"] = x3(noise_func(n), sample[\"X_1\"], sample[\"X_2\"])\n sample.loc[:, \"Y\"] = y(noise_func(n), sample[\"X_0\"], sample[\"X_2\"])\n return sample\n\n\ndef manual_sample_medium(n, dtype, names, seed):\n def x1(n, x0):\n return 1 + n + x0\n\n def x2(n, x0, x1):\n return 1 + n + 0.8 * x0 - 1.2 * x1\n\n def x3(n, x1, x2):\n return n + x1 + 0.3 * x1 + 0.4 * x2\n\n def y(n, x0, x3):\n return 0.67 + n + x3 - x0\n\n def x4(n, y):\n return 1.2 + n - 0.7 * y\n\n def x5(n, y):\n return n + 0.5 - 0.7 * y\n\n rng = np.random.default_rng(seed)\n noise_func = lambda size: rng.normal(loc=0, scale=1, size=size)\n sample = pd.DataFrame(np.empty((n, len(names)), dtype=dtype), columns=names)\n sample.loc[:, \"X_0\"] = noise_func(n)\n sample.loc[:, \"X_1\"] = x1(noise_func(n), sample[\"X_0\"])\n sample.loc[:, \"X_2\"] = x2(noise_func(n), sample[\"X_0\"], sample[\"X_1\"])\n sample.loc[:, \"X_3\"] = x3(noise_func(n), sample[\"X_1\"], sample[\"X_2\"])\n sample.loc[:, \"Y\"] = y(noise_func(n), sample[\"X_0\"], sample[\"X_3\"])\n sample.loc[:, \"X_4\"] = x4(noise_func(n), sample[\"Y\"])\n sample.loc[:, \"X_5\"] = x5(noise_func(n), sample[\"Y\"])\n return sample\n\n\ndef same_elements(list1, list2):\n return np.isin(list1, list2).all() and np.isin(list2, list1).all()\n\n\ndef test_parsing():\n test_str = \"Z_1 = Noise + 2*log(Y), Noise ~ Normal(0,1)\"\n func_map = parse_assignments([test_str])\n assert func_map[\"Z_1\"][0] == \"Noise + 2*log(Y)\"\n assert str(func_map[\"Z_1\"][1]) == \"Noise\"\n assert extract_parents(func_map[\"Z_1\"][0], \"Noise\") == [\"Y\"]\n\n test_str = \"X = N + sqrt(X_45 ** M + 342 * 2) / ( 43 * FG_2) + P, N ~ Normal(0,1)\"\n func_map = parse_assignments([test_str])\n assert func_map[\"X\"][0] == \"N + sqrt(X_45 ** M + 342 * 2) / ( 43 * FG_2) + P\"\n assert str(func_map[\"X\"][1]) == \"N\"\n assert same_elements(\n extract_parents(func_map[\"X\"][0], \"N\"), [\"X_45\", \"M\", \"FG_2\", \"P\"]\n )\n\n\ndef test_scm_from_strings():\n scm = SCM(\n [\n \"X = N, N ~ Normal(0,1)\",\n \"Y_0 = M + 2 * exp(X), M ~ StudentT(2)\",\n \"Y_1 = M + 2 * exp(sqrt(X)), M ~ Normal(0, 0.1)\",\n \"Z = P * sqrt(Y_0), P ~ Exponential(5.3)\",\n ]\n )\n assert same_elements(scm.get_variables(), [\"X\", \"Y_0\", \"Y_1\", \"Z\"])\n\n\ndef test_scm_build_from_assignmentmap():\n cn = build_scm_from_assignmentmap()\n nodes_in_graph = sorted(cn.get_variables())\n assert same_elements(nodes_in_graph, [\"X_0\", \"X_1\", \"X_3\"])\n assert same_elements(cn[\"X_3\"].parents, [\"X_0\", \"X_1\"])\n assert same_elements(cn[\"X_1\"].parents, [\"X_0\"])\n\n\ndef test_scm_build_from_functionalmap():\n cn = build_scm_from_functionalmap()\n nodes_in_graph = sorted(cn.get_variables())\n assert same_elements(nodes_in_graph, [\"X_0\", \"X_1\", \"X_3\"])\n assert same_elements(cn[\"X_3\"].parents, [\"X_0\", \"X_1\"])\n assert same_elements(cn[\"X_1\"].parents, [\"X_0\"])\n\n\ndef test_scm_build_from_assignmentstrs():\n cn = build_scm_from_assignmentstrs()\n nodes_in_graph = sorted(cn.get_variables())\n assert same_elements(nodes_in_graph, [\"X_0\", \"X_1\", \"X_3\"])\n assert same_elements(cn[\"X_3\"].parents, [\"X_0\", \"X_1\"])\n assert same_elements(cn[\"X_1\"].parents, [\"X_0\"])\n\n\ndef test_scm_builds_equal_sampling():\n cn1 = build_scm_from_assignmentmap()\n cn2 = build_scm_from_functionalmap()\n cn3 = build_scm_from_assignmentstrs()\n cn1.seed(0)\n cn2.seed(0)\n cn3.seed(0)\n n = 10\n sample1 = cn1.sample(n)\n sample2 = cn2.sample(n)\n sample3 = cn3.sample(n)\n samples = sample1, sample2, sample3\n for i in range(2):\n for var in cn1.get_variables():\n assert same_elements(samples[i][var].round(4), samples[i + 1][var].round(4))\n\n\ndef test_scm_sample_partial():\n cn = build_scm_linandpoly(seed=0)\n n = 1000\n random.seed(0)\n sample_vars = cn.sample(n, [\"X_0\"]).columns\n assert same_elements(sample_vars, [\"X_0\"])\n\n sample_vars = cn.sample(n, [\"X_2\"]).columns\n assert same_elements([\"X_0\", \"X_1\", \"X_2\"], sample_vars)\n\n sample_vars = cn.sample(n, [\"Y\"]).columns\n assert same_elements([\"X_0\", \"X_1\", \"X_2\", \"Y\"], sample_vars)\n\n\ndef test_scm_sample():\n n = 10000\n cn = build_scm_linandpoly(seed=0)\n scm_sample = cn.sample(n)\n sample = manual_sample_linandpoly(\n n, scm_sample.values.dtype, list(cn.dag.nodes), seed=0\n )\n sample_order_scm = cn.get_variables()\n sample = sample[sample_order_scm]\n\n expectation_scm = scm_sample.mean(0)\n expectation_manual = sample.mean(0)\n exp_diff = (expectation_manual - expectation_scm).abs()\n assert (exp_diff.values < 0.1).all()\n\n cn = build_scm_medium(seed=0)\n scm_sample = cn.sample(n)\n sample = manual_sample_medium(\n n, scm_sample.values.dtype, list(cn.dag.nodes), seed=0\n )\n\n sample_order_scm = cn.get_variables()\n sample = sample[sample_order_scm]\n\n expectation_scm = scm_sample.mean(0)\n expectation_manual = sample.mean(0)\n exp_diff = (expectation_manual - expectation_scm).abs()\n assert (exp_diff.values < 0.1).all()\n\n\ndef test_scm_intervention():\n seed = 0\n cn = build_scm_linandpoly(seed=seed)\n\n # do the intervention\n cn.intervention(\n {\"X_3\": (None, \"N + 2.3 * X_0 + 2.3 * Y\", Normal(\"N\", 5, 2))}\n )\n n = 10000\n\n scm_sample_interv = cn.sample(n)\n rng = np.random.default_rng(seed)\n sample = manual_sample_linandpoly(\n n, dtype=np.float, names=cn.get_variables(), seed=cn.rng_state\n )\n sample[\"X_3\"] = rng.normal(loc=5, scale=2, size=n) + 2.3 * (\n sample[\"X_0\"] + sample[\"Y\"]\n )\n sample = sample[cn.get_variables()]\n\n manual_mean = sample.mean(0)\n scm_mean = scm_sample_interv.mean(0)\n exp_diff = (manual_mean - scm_mean).abs().values\n assert (exp_diff < 0.5).all()\n\n # from here on the cn should work as normal again\n cn.undo_intervention()\n\n # reseeding needs to happen as the state of the initial noise distributions is further advanced than\n # a newly seeded noise by noise()\n cn.seed(0)\n\n manual_sample = manual_sample_linandpoly(\n n, scm_sample_interv.values.dtype, list(cn.dag.nodes), 0\n )[cn.get_variables()]\n new_cn_sample = cn.sample(n)\n manual_mean = manual_sample.mean(0)\n scm_mean = new_cn_sample.mean(0)\n exp_diff = (manual_mean - scm_mean).abs().values\n assert (exp_diff < 1e-1).all()\n\n\ndef test_scm_dointervention():\n seed = 0\n cn = build_scm_linandpoly(seed=seed)\n n = 100\n standard_sample = cn.sample(n, seed=seed)\n # do the intervention\n cn.do_intervention([(\"X_2\", 4)])\n sample = cn.sample(n)\n assert (sample[\"X_2\"] == 4).all()\n # from here on the cn should work as normal again\n cn.undo_intervention()\n new_sample = cn.sample(n, seed=seed)\n diff = (standard_sample.mean(0) - new_sample.mean(0)).abs().values\n assert (diff == 0.0).all()\n\n\ndef test_scm_softintervention():\n seed = 0\n cn = build_scm_linandpoly(seed=seed)\n n = 100\n standard_sample = cn.sample(n, seed=seed)\n # do the intervention\n cn.soft_intervention([(\"X_2\", FiniteRV(str(cn[\"X_2\"].noise), density={0: 1.}))])\n sample = cn.sample(n)\n assignment = cn[\"X_2\"].assignment\n manual_x2 = assignment(0, sample[\"X_0\"], sample[\"X_1\"])\n diff = (sample[\"X_2\"] - manual_x2).abs()\n assert np.all(diff == 0.0)\n\n # from here on the cn should work as normal again\n cn.undo_intervention()\n new_sample = cn.sample(n, seed=seed)\n diff = (standard_sample.mean(0) - new_sample.mean(0)).abs().values\n assert np.all(diff == 0.0)\n\n\ndef test_sample_iter():\n cn = build_scm_from_assignmentmap()\n samples = {var: [] for var in cn.get_variables()}\n rng1 = np.random.default_rng(seed=0)\n rng2 = np.random.default_rng(seed=0)\n iterator = cn.sample_iter(samples, seed=rng1)\n n = 1000\n for _ in range(n):\n next(iterator)\n standard_sample = cn.sample(n, seed=rng2)\n samples = pd.DataFrame.from_dict(samples)\n diff = (standard_sample.mean(0) - samples.mean(0)).abs().values\n assert (diff < 1e-1).all()\n\n\ndef test_reproducibility():\n cn = build_scm_linandpoly()\n n = 20\n sample = cn.sample(n, seed=1)\n sample2 = cn.sample(n, seed=1)\n assert (sample.to_numpy() == sample2.to_numpy()).all()\n\n\ndef test_none_noise():\n cn = SCM([\"X = 1\", \"Y = N + X, N ~ Normal(0,1)\"], seed=0)\n n = 10\n sample = cn.sample(n)\n manual_y = np.random.default_rng(0).normal(size=n) + 1\n assert (sample[\"X\"] == 1).all()\n assert (sample[\"Y\"] == manual_y).all()\n\n sample = {var: [] for var in cn.get_variables()}\n sampler = cn.sample_iter(sample, seed=0)\n list(next(sampler) for _ in range(n))\n sample = pd.DataFrame.from_dict(sample)\n manual_y = np.random.default_rng(0).normal(size=n) + 1\n assert (sample[\"X\"] == 1).all()\n assert (sample[\"Y\"] == manual_y).all()\n" }, { "alpha_fraction": 0.6235018372535706, "alphanum_fraction": 0.6274101138114929, "avg_line_length": 32.66666793823242, "blob_id": "ef11dfd5efbaa8902f65668f930ca7560cd443e1", "content_id": "4a64d573a6ec36e92b317470ab3c775398fbb092", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3838, "license_type": "permissive", "max_line_length": 119, "num_lines": 114, "path": "/scmodels/parser.py", "repo_name": "maichmueller/SCM", "src_encoding": "UTF-8", "text": "from collections import deque, defaultdict\nimport re as regex\n\nimport sympy\nfrom sympy.functions import *\nfrom sympy.stats import *\nfrom sympy.stats.rv import RandomSymbol\nfrom sympy.stats import __all__ as all_stats_imports\n\n\nfrom typing import *\n\nall_stats_imports = set(all_stats_imports)\n\nvar_p = regex.compile(r\"(?<=([(]|[)*+-/%]))\\w+(?=([)*+-/%]+|$))|^\\w+(?=([)*+-/%]+|$))\")\ndigit_p = regex.compile(r\"^\\d+$\")\n\n\ndef parse_assignments(assignment_strs: Sequence[str]):\n \"\"\"\n This parses a list of assignment strings. The assignments are supposed to be given in the following form:\n\n 'NEW_VAR = f(Parent_1, ..., Parent_n, N), N ~ DISTRIBUTION()'\n\n Any element is supposed to be named after your present use case. The function f is whatever the\n assignment is meant to do, e.g. f(X, Y, N) = N + X * Y for additive noise and multiplied parents.\n These functions need to be parsable by sympy to be correct.\n\n Parameters\n ----------\n assignment_strs: list\n The assignment strings.\n\n Returns\n -------\n dict,\n The functional map of variables with their parents, assignment strings, and noise models as needed to construct\n an SCM object.\n \"\"\"\n functional_map = dict()\n for assignment in assignment_strs:\n\n # split the assignment 'X = f(Parents, Noise), Noise ~ D' into [X, f(Parents, Noise), Noise ~ D]\n assign_var, assignment_n_noise = assignment.split(\"=\", 1)\n assign_noise_split = assignment_n_noise.split(\",\", 1)\n\n if len(assign_noise_split) == 1:\n # this is the case when there was no ',' separating functional body and noise distribution specification\n assign_str = assign_noise_split[0]\n model_sym = None\n else:\n assign_str, noise_str = assign_noise_split\n _, model_sym = allocate_noise_model(strip_whitespaces(noise_str))\n functional_map[assign_var.strip()] = assign_str.strip(), model_sym\n return functional_map\n\n\ndef extract_parents(assignment_str: str, noise_var: Union[str, sympy.Symbol]) -> List[str]:\n \"\"\"\n Extract the parent variables in an assignment string.\n\n Examples\n --------\n For the following assignment\n\n >>> 'N + sqrt(Z_0) * log(Y_2d)'\n\n this method should return the following\n\n >>> extract_parents('N + sqrt(Z_0) * log(Y_2d)', 'N')\n >>> ['Z_0', 'Y_2d']\n\n Parameters\n ----------\n assignment_str: str\n the assignment str (without '=' sign and noise distribution).\n\n noise_var: str or sympy symbol,\n the identifier of the noise variable (excluded from parents list)\n\n Returns\n -------\n list,\n the parents found in the string\n \"\"\"\n noise_var = str(noise_var)\n # set does not preserve insertion order so we need to bypass this issue with a list\n parents = []\n for match_obj in var_p.finditer(strip_whitespaces(assignment_str)):\n matched_str = match_obj.group()\n if digit_p.search(matched_str) is not None:\n # exclude digit only matches (these aren't variable names)\n continue\n else:\n # the matched str is considered a full variable name\n if not matched_str == noise_var:\n parents.append(matched_str)\n return list(dict.fromkeys(parents))\n\n\ndef allocate_noise_model(noise_assignment: str):\n noise_var, model = noise_assignment.split(\"~\")\n par_idx = model.find(\"(\") + 1\n if model[:par_idx-1] not in all_stats_imports:\n # crude check whether the noise model is supported\n raise ValueError(f\"noise model {model[:par_idx-1]} not supported.\")\n model = model[:par_idx] + r'\"' + noise_var + r'\",' + model[par_idx:]\n model_sym = []\n exec(f\"model_sym.append({model})\")\n return noise_var, model_sym[0]\n\n\ndef strip_whitespaces(s: str):\n return \"\".join(s.split())\n" }, { "alpha_fraction": 0.26696035265922546, "alphanum_fraction": 0.33421438932418823, "avg_line_length": 29.401784896850586, "blob_id": "a04bf5b508071bd9dbdc720b80d03989d7ef0871", "content_id": "ac2840ced04bd267cb023745eddb36025aa486b6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3405, "license_type": "permissive", "max_line_length": 101, "num_lines": 112, "path": "/test/build_scm.py", "repo_name": "maichmueller/SCM", "src_encoding": "UTF-8", "text": "from scmodels import SCM\nfrom sympy.stats import *\n\n\ndef build_scm_from_assignmentmap(seed=0):\n cn = SCM(\n assignments={\n \"X_0\": (\"N\", Normal(\"N\", 0, 1)),\n \"X_1\": (\"1 + X_0 + N\", Normal(\"N\", 0, 1)),\n \"X_3\": (\"0.3 * X_1 + X_0 + N\", Normal(\"N\", 0, 1)),\n },\n variable_tex_names={\"X_0\": \"$X_0$\", \"X_1\": \"$X_1$\", \"X_3\": \"$X_3$\"},\n seed=seed,\n )\n return cn\n\n\ndef build_scm_from_assignmentstrs(seed=0):\n cn = SCM(\n assignments=[\n \"X_0 = N, N ~ Normal(mean=0, std=1)\",\n \"X_1 = 1 + X_0 + N, N ~ Normal(mean=0, std=1)\",\n \"X_3 = 0.3 * X_1 + X_0 + N, N ~ Normal(mean=0, std=1)\",\n ],\n variable_tex_names={\"X_0\": \"$X_0$\", \"X_1\": \"$X_1$\", \"X_3\": \"$X_3$\"},\n seed=seed,\n )\n return cn\n\n\ndef build_scm_from_functionalmap(seed=0):\n cn = SCM(\n assignments={\n \"X_0\": ([], lambda n: n, Normal(\"P\", mean=0, std=1)),\n \"X_1\": ([\"X_0\"], lambda n, x0: 1 + x0 + n, Normal(\"D\", mean=0, std=1)),\n \"X_3\": ([\"X_0\", \"X_1\"], lambda n, x0, x1: 0.3 * x1 + x0 + n, Normal(\"M\", mean=0, std=1)),\n },\n variable_tex_names={\"X_0\": \"$X_0$\", \"X_1\": \"$X_1$\", \"X_3\": \"$X_3$\"},\n seed=seed,\n )\n return cn\n\n\ndef build_scm_simple(seed=0):\n cn = SCM(\n assignments={\n \"X_0\": (\"N\", Normal(\"N\", 0, 1)),\n \"X_1\": (\"1 + X_0 + N\", Normal(\"N\", 0, 1)),\n \"X_2\": (\"1 + 3*X_0 + N\", Normal(\"N\", 0, 1)),\n \"X_3\": (\"0.3 * X_1 + N\", Normal(\"N\", 0, 1)),\n \"Y\": (\"3 + 5 * X_3 + N\", Normal(\"N\", 0, 1)),\n \"X_4\": (\"3 + 9 * Y + N\", Normal(\"N\", 0, 1)),\n \"X_5\": (\"3 - 2.7 * X_3 + N\", Normal(\"N\", 0, 1)),\n },\n variable_tex_names={\n \"X_0\": \"$X_0$\",\n \"X_1\": \"$X_1$\",\n \"X_2\": \"$X_2$\",\n \"X_3\": \"$X_3$\",\n \"X_4\": \"$X_4$\",\n \"X_5\": \"$X_5$\",\n },\n seed=seed,\n )\n return cn\n\n\ndef build_scm_medium(seed=0):\n cn = SCM(\n assignments={\n \"X_0\": (\"N\", Normal(\"N\", 0, 1)),\n \"X_1\": (\"N + 1 + X_0\", Normal(\"N\", 0, 1)),\n \"X_2\": (\"N + 1 + 0.8 * X_0 - 1.2 * X_1\", Normal(\"N\", 0, 1)),\n \"X_3\": (\"N + 1 + 0.3 * X_1 + 0.4 * X_2\", Normal(\"N\", 0, 1)),\n \"Y\": (\"0.67 + X_3 + N - X_0\", Normal(\"N\", 0, 1)),\n \"X_4\": (\"N + 1.2 - 0.7 * Y\", Normal(\"N\", 0, 1)),\n \"X_5\": (\"N + 0.5 - 0.7 * Y\", Normal(\"N\", 0, 1)),\n },\n variable_tex_names={\n \"X_0\": \"$X_0$\",\n \"X_1\": \"$X_1$\",\n \"X_2\": \"$X_2$\",\n \"X_3\": \"$X_3$\",\n \"X_4\": \"$X_4$\",\n \"X_5\": \"$X_5$\",\n },\n seed=seed,\n )\n return cn\n\n\ndef build_scm_linandpoly(seed=0):\n cn = SCM(\n assignments={\n \"X_0\": (\"N\", Normal(\"N\", 0, 1)),\n \"X_1\": (\"N + 1 + 2 * (X_0 ** 2)\", Normal(\"N\", 0, 1)),\n \"X_2\": (\"N + 1 + 3 * X_0 + 2 * X_1\", Normal(\"N\", 0, 1)),\n \"X_3\": (\n \"N + X_1 + 0.5 * sqrt(abs(X_1)) + 4 * log(abs(X_2))\",\n Normal(\"N\", 0, 1),\n ),\n \"Y\": (\"N + 0.05 * (X_0 ** 2) + 2 * X_2\", Normal(\"N\", 0, 1)),\n },\n variable_tex_names={\n \"X_0\": \"$X_0$\",\n \"X_1\": \"$X_1$\",\n \"X_2\": \"$X_2$\",\n \"X_3\": \"$X_3$\",\n },\n seed=seed,\n )\n return cn\n" }, { "alpha_fraction": 0.5644735097885132, "alphanum_fraction": 0.5687004923820496, "avg_line_length": 35.29680252075195, "blob_id": "0461bdea01e0b79661c3173c7ea67da3d270af6d", "content_id": "7fc5d00fe5600a5e6da82e6cedb1316ccd59b367", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 39745, "license_type": "permissive", "max_line_length": 120, "num_lines": 1095, "path": "/scmodels/scm.py", "repo_name": "maichmueller/SCM", "src_encoding": "UTF-8", "text": "from scmodels.parser import parse_assignments, extract_parents\n\nimport random\nimport warnings\n\nimport numpy as np\nimport pandas as pd\nimport networkx as nx\nfrom networkx.drawing.nx_agraph import graphviz_layout\nfrom collections import deque, defaultdict\nfrom itertools import repeat\n\nimport matplotlib.pyplot as plt\nimport logging\nfrom copy import deepcopy\n\nimport sympy\nfrom sympy.core.singleton import SingletonRegistry\nfrom sympy.functions import *\nfrom sympy.stats import sample\nfrom sympy.stats.rv import RandomSymbol\n\nfrom typing import (\n List,\n Union,\n Dict,\n Tuple,\n Iterable,\n Set,\n Mapping,\n Sequence,\n Collection,\n Optional,\n Hashable,\n Sequence,\n Type,\n Generator,\n Iterator,\n Callable,\n)\n\nRV = RandomSymbol\nAssignmentSeq = Sequence[str]\nAssignmentMap = Dict[str, Union[Tuple[str, RV], Tuple[List[str], Callable, RV]]]\n\n\nclass Assignment:\n\n noise_argname = \"__{noise}__\"\n\n def __init__(\n self,\n functor: Callable,\n ordered_parents: Sequence[str],\n desc: Optional[str] = None,\n ):\n assert callable(functor), \"Passed functor must be callable.\"\n self.functor = functor\n self._as_str = desc\n self.arg_positions = {\n var: pos for (var, pos) in zip(ordered_parents, range(len(ordered_parents)))\n }\n\n @property\n def as_str(self):\n return self._as_str\n\n def __len__(self):\n return len(self.arg_positions)\n\n def __call__(self, *args, **kwargs):\n args = list(args) + [None] * (len(self) - len(args))\n for var in kwargs:\n if var in self.arg_positions:\n args[self.arg_positions[var]] = kwargs[var]\n return self.functor(*args)\n\n def __str__(self):\n if self.as_str is None:\n return \"__unknown__\"\n return self.as_str\n\n\nclass SCM:\n \"\"\"\n Class building a Structural Causal Model.\n\n With this class one can sample causally from the underlying graph and also perform do-interventions and\n soft-interventions, as well as more general interventions targeting one or more variables with arbitrary\n changes to the assignment and/or noise structure (including parent-child relationship changes).\n\n For visualization aid, the SCM can plot itself and also print a summary of itself to the console.\n To this end, the decision was made to limit the potential input to the SCM objects in terms of\n functional and noise functors.\n If a user wishes to add a custom functional or noise function to their usage of the SCM, they will need\n to provide implementations inheriting from the respective base classes of noise or functional.\n\n Notes\n -----\n When constructing or intervening the user is responsible to guarantee acyclicity in the SCM. No checks are enabled\n at this stage.\n \"\"\"\n\n # the attribute list that any given node in the graph has.\n (assignment_key, noise_key, noise_repr_key) = (\n \"assignment\",\n \"noise\",\n \"noise_repr\",\n )\n\n class NodeView:\n \"\"\"\n A view of the variable's associated attributes\n \"\"\"\n def __init__(\n self,\n var: str,\n parents: List[str],\n assignment: Assignment,\n noise: RV,\n noise_repr: str\n ):\n self.variable = var\n self.parents = parents\n self.assignment = assignment\n self.noise = noise\n self.noise_repr = noise_repr\n\n def __init__(\n self,\n assignments: Union[AssignmentMap, AssignmentSeq],\n variable_tex_names: Optional[Dict] = None,\n seed: Optional[int] = None,\n scm_name: str = \"Structural Causal Model\",\n ):\n \"\"\"\n Construct the SCM from an assignment map with the variables as keys and its assignment information\n as tuple of parents, assignment, and noise distribution or provide the assignments in a list of strings, which\n directly tell\n\n Notes\n -----\n Note, that the assignment string needs to align with the parents list namewise!\n\n Examples\n --------\n To set up 3 variables of the form\n\n .. math:: X_0 = LogListic(1, 1)\n .. math:: X_1 = 3 (X_0)^2 + Normal(1, 0.5)\n .. math:: Y = 2 * X_0 - sqrt(X_1) + Normal(2, 1)\n\n we can either build an assignment map\n\n >>> from sympy.stats import LogLogistic, LogNormal\n ...\n ... assignment = {\n ... \"X_zero\": (\n ... \"N\",\n ... LogLogistic(\"N\", alpha=1, beta=1)\n ... ),\n ... \"X_1\": (\n ... \"N * 3 * X_zero ** 2\",\n ... LogNormal(\"N\", mean=1, std=1),\n ... \"Y\": (\n ... \"N + 2 * X_zero + sqrt(X_1)\",\n ... Normal(\"N\", mean=2, std=1),\n ... ),\n ... }\n\n to initialize the scm with it\n\n >>> causal_net = SCM(\n ... assignments=assignment,\n ... variable_tex_names={\"X_zero\": \"$X_{zero}$\", \"X_1\": \"$X_1$\"}\n ... )\n\n or we can build the SCM directly from assignment strings\n\n >>> causal_net = SCM(\n ... [\n ... \"X_zero = N, N ~ LogLogistic(alpha=1, beta=1)\",\n ... \"X_1 = N * 3 * X_zero ** 2, N ~ LogNormal(mean=1, std=1)\",\n ... \"Y = N + 2 * X_zero + sqrt(X_1), N ~ Normal(mean=2, std=1)\"\n ... ],\n ... variable_tex_names={\"X_zero\": \"$X_{zero}$\", \"X_1\": \"$X_1$\"}\n ... )\n\n Parameters\n ----------\n assignments: dict,\n The functional dictionary for the SCM construction as explained above.\n variable_tex_names: (optional) Dict,\n A collection of the latex names for the variables in the causal graph. The dict needs to provide a tex name\n for each passed variable name in the form: {\"VarName\": \"VarName_in_TeX\"}.\n Any variable that is missing in the dictionary will be assumed to accept its current name as the TeX\n version.\n If not provided defaults to the input names in the functional map.\n seed: (optional) str,\n Seeding the graph for reproducibility.\n scm_name: (optional) str,\n The name of the SCM. Default is 'Structural Causal Model'.\n \"\"\"\n self.scm_name: str = scm_name\n self.rng_state = np.random.default_rng() # we always have a local RNG machine\n self.seed(seed)\n\n # a backup dictionary of the original assignments of the intervened variables,\n # in order to undo the interventions later.\n self.interventions_backup_attr: Dict = dict()\n self.interventions_backup_parent: Dict = dict()\n\n # build the graph:\n # any node will be given the attributes of function and noise to later sample from and also an incoming edge\n # from its causal parent. We will store the causal root nodes separately.\n self.dag = nx.DiGraph()\n self.roots: List = []\n self.insert(assignments)\n\n # supply any variable name, that has not been assigned a different TeX name, with itself as TeX name.\n # This prevents missing labels in the plot method.\n if variable_tex_names is not None:\n for name in self.get_variables():\n if name not in variable_tex_names:\n variable_tex_names[name] = name\n # the variable names as they can be used by the plot function to draw the names in TeX mode.\n self.var_draw_dict: Dict = variable_tex_names\n else:\n self.var_draw_dict = {name: name for name in self.get_variables()}\n\n def __getitem__(self, var):\n attr_dict = self.dag.nodes[var]\n return SCM.NodeView(\n var,\n self.dag.pred[var],\n **attr_dict\n )\n\n def __str__(self):\n return self.str()\n\n def __iter__(self):\n return self._causal_iterator()\n\n def sample(\n self,\n n: int,\n variables: Optional[Sequence[Hashable]] = None,\n seed: Optional[Union[int, np.random.Generator]] = None,\n ):\n \"\"\"\n Sample method to generate data for the given variables. If no list of variables is supplied, the method will\n simply generate data for all variables.\n Setting the seed guarantees reproducibility.\n\n Parameters\n ----------\n n: int,\n number of samples\n variables: list,\n the variable names to consider for sampling. If None, all variables will be sampled.\n seed: int,\n the seeding for the noise generators\n\n Returns\n -------\n pd.DataFrame,\n the dataframe containing the samples of all the variables needed for the selection.\n \"\"\"\n\n samples = dict()\n if seed is None:\n seed = self.rng_state\n\n for node in self._causal_iterator(variables):\n node_attr = self.dag.nodes[node]\n predecessors = list(self.dag.predecessors(node))\n\n named_args = dict()\n for pred in predecessors:\n named_args[pred] = samples[pred]\n\n noise_gen = node_attr[self.noise_key]\n if noise_gen is not None:\n named_args[Assignment.noise_argname] = np.array(\n list(sample(noise_gen, numsamples=n, seed=seed)), dtype=float\n )\n\n data = node_attr[self.assignment_key](**named_args)\n samples[node] = data\n return pd.DataFrame.from_dict(samples)\n\n def sample_iter(\n self,\n container: Optional[Dict[str, List]] = None,\n variables: Optional[Sequence[Hashable]] = None,\n seed: Optional[Union[int, np.random.Generator]] = None,\n ) -> Iterator[Dict[str, List]]:\n \"\"\"\n Sample method to generate data for the given variables. If no list of variables is supplied, the method will\n simply generate data for all variables.\n Setting the seed guarantees reproducibility.\n\n Parameters\n ----------\n container: Dict[str, List] (optional),\n the container in which to store the output. If none is provided, the sample is returned in a new container,\n otherwise the provided container is filled with the samples and returned.\n variables: list,\n the variable names to consider for sampling. If None, all variables will be sampled.\n seed: int or np.random.Generator,\n the seeding for the noise generators\n\n Returns\n -------\n pd.DataFrame,\n the dataframe containing the samples of all the variables needed for the selection.\n \"\"\"\n if seed is None:\n seed = self.rng_state\n vars_ordered = list(self._causal_iterator(variables))\n noise_iters = []\n for node in vars_ordered:\n noise_gen = self.dag.nodes[node][self.noise_key]\n if noise_gen is not None:\n noise_iters.append(\n sample(noise_gen, numsamples=SingletonRegistry.Infinity, seed=seed)\n )\n else:\n noise_iters.append(repeat(None))\n\n if container is None:\n samples = {var: [] for var in vars_ordered}\n else:\n samples = container\n while True:\n for i, node in enumerate(vars_ordered):\n node_attr = self.dag.nodes[node]\n predecessors = list(self.dag.predecessors(node))\n\n named_args = dict()\n for pred in predecessors:\n named_args[pred] = samples[pred][-1]\n\n noise = next(noise_iters[i])\n if noise is not None:\n named_args[Assignment.noise_argname] = noise\n\n data = node_attr[self.assignment_key](**named_args)\n samples[node].append(data)\n yield samples\n\n def intervention(\n self,\n interventions: Dict[\n str,\n Tuple[Optional[List[str]], Optional[Union[str, Callable]], Optional[RV]],\n ],\n ):\n \"\"\"\n Method to apply interventions on the specified variables.\n\n One can set any variable to a new functional and noise model, thus redefining its parents and their\n dependency structure. Using this method will enable the user to call sample, plot etc. on the SCM just like\n before, but with the altered SCM.\n In order to allow for undoing the intervention(s), the original state of the variables in the network is saved\n as backup and can be undone by calling ``undo_intervention``.\n\n Parameters\n ----------\n interventions: dict,\n the variables as keys and their new assignments as values. For the assignment structure\n one has to provide a tuple of length 3 with the following positions:\n 1. The new parents of the assignment.\n Pass 'None' to leave the original dependencies intact.\n 2. The new assignment function. Pass as 'str' or 'callable'. If it is a callable, then either\n the old parent structure or the new parent structure (if provided) has to be fit with the\n positional input of the function.\n Pass 'None' to leave the original assignment intact.\n 3. The new noise distribution. Ascertain that the new distributions name symbol overlaps with\n the previous name symbol.\n Pass 'None' to leave the original noise distribution intact.\n \"\"\"\n interventional_map = dict()\n\n for var, items in interventions.items():\n if var not in self.get_variables():\n logging.warning(f\"Variable '{var}' not found in graph. Omitting it.\")\n continue\n\n if not isinstance(items, Sequence):\n raise ValueError(\n f\"Intervention items container '{type(items)}' not supported.\"\n )\n\n items = [elem for elem in items]\n existing_attr = self[var]\n assert (\n len(items) == 3\n ), f\"Items tuple of variable {var} has wrong length. Given {len(items)}, expected: 3\"\n\n if items[2] is None:\n # no new noise distribution given\n items[2] = existing_attr.noise\n\n if items[1] is None:\n # no new assignment given\n items[1] = existing_attr.assignment\n\n # whether the assignment is new or old: we have to parse it\n if callable(items[1]) and items[0] is None:\n # Rebuild the parents for the assignment, because no new parent info is given,\n # but a callable assignment needs a parents list\n sorted_parents = sorted(\n self.get_variable_args(var).items(),\n key=lambda k: k[1],\n )\n items[0] = [\n parent\n for parent, _ in sorted_parents[\n 1:\n ] # element 0 is the noise name (must be removed)\n ]\n elif isinstance(items[1], str):\n # We reach this space only if a new assignment was provided, since existing assignments are already\n # converted to a callable.\n # In string assignments the parents list is deduced:\n items.pop(0)\n else:\n raise ValueError(\n f\"Variable {var} has been given an unsupported assignment type. \"\n f\"Expected: str or callable, given: {type(items[1])}\"\n )\n\n if var not in self.interventions_backup_attr:\n # the variable has NOT already been backed up. If we overwrite it now it is fine. If it had already been\n # in the backup, then it we would need to pass on this step, in order to not overwrite the backup\n # (possibly with a previous intervention)\n self.interventions_backup_attr[var] = deepcopy(self.dag.nodes[var])\n\n if var not in self.interventions_backup_parent:\n # the same logic goes for the parents backup.\n parent_backup = list(self.dag.predecessors(var))\n self.interventions_backup_parent[var] = parent_backup\n self.dag.remove_edges_from([(parent, var) for parent in parent_backup])\n # patch up the attr dict as the provided items were merely strings and now need to be parsed by sympy.\n interventional_map[var] = items\n self.insert(interventional_map)\n\n def do_intervention(self, var_val_pairs: Sequence[Tuple[str, float]]):\n \"\"\"\n Perform do-interventions, i.e. setting specific variables to a constant value.\n This method removes the noise influence of the intervened variables.\n\n Convenience wrapper around ``interventions`` method.\n\n Parameters\n ----------\n var_val_pairs Sequence of str-float tuple,\n the variables to intervene on with their new values.\n \"\"\"\n interventions_dict = dict()\n for var, val in var_val_pairs:\n interventions_dict[var] = (None, str(val), None)\n self.intervention(interventions_dict)\n\n def soft_intervention(\n self,\n var_noise_pairs: Sequence[Tuple[str, RV]],\n ):\n \"\"\"\n Perform noise interventions, i.e. modifying the noise variable of specific variables.\n\n Convenience wrapper around ``interventions`` method.\n\n Parameters\n ----------\n var_noise_pairs : Sequence of (variable, noise_model) tuples,\n the variables of which to modify the noise model.\n \"\"\"\n interventions_dict = dict()\n for var, noise in var_noise_pairs:\n interventions_dict[var] = (None, None, noise)\n self.intervention(interventions_dict)\n\n def undo_intervention(self, variables: Optional[Sequence[str]] = None):\n \"\"\"\n Method to undo previously done interventions.\n\n The variables whose interventions should be made undone can be provided in the ``variables`` argument. If no\n list is supplied, all interventions will be undone.\n\n Parameters\n ----------\n variables: list-like,\n the variables to be undone.\n \"\"\"\n if variables is not None:\n present_variables = self.filter_variable_names(variables, self.dag)\n else:\n present_variables = list(self.interventions_backup_attr.keys())\n\n for var in present_variables:\n try:\n attr_dict = self.interventions_backup_attr.pop(var)\n parents = self.interventions_backup_parent.pop(var)\n except KeyError:\n logging.warning(\n f\"Variable '{var}' not found in intervention backup. Omitting it.\"\n )\n continue\n\n self.dag.add_node(var, **attr_dict)\n self.dag.remove_edges_from(\n [(parent, var) for parent in self.dag.predecessors(var)]\n )\n self.dag.add_edges_from([(parent, var) for parent in parents])\n\n def d_separated(\n self, x: Sequence[str], y: Sequence[str], s: Optional[Sequence[str]] = None\n ):\n \"\"\"\n Checks if all variables in X are d-separated from all variables in Y by the variables in S.\n\n Parameters\n ----------\n x: Sequence,\n First set of nodes in DAG.\n\n y: Sequence,\n Second set of nodes in DAG.\n\n s: Sequence (optional),\n Set of conditioning nodes in DAG.\n\n Returns\n -------\n bool,\n A boolean indicating whether x is d-separated from y by s.\n \"\"\"\n return nx.d_separated(\n self.dag, set(x), set(y), set(s) if s is not None else set()\n )\n\n def is_dag(self):\n \"\"\"\n Check whether the current DAG is indeed a DAG\n Returns\n -------\n bool,\n A boolean indicating whether the current graphical model is indeed a DAG.\n \"\"\"\n return nx.is_directed_acyclic_graph(self.dag)\n\n def insert(self, assignments: Union[AssignmentSeq, AssignmentMap]):\n \"\"\"\n Method to insert variables into the graph. The passable assignments are the same as for the constructor of\n the SCM class.\n\n Parameters\n ----------\n assignments, Sequence of str or dictionary of nodes to assignment tuples\n The assignments to add to the graph.\n\n \"\"\"\n if isinstance(assignments, Sequence):\n assignments = parse_assignments(assignments)\n elif not isinstance(assignments, Dict):\n raise ValueError(\n f\"Assignments parameter accepts either a \"\n f\"Sequence[str] or \"\n f\"a {str(AssignmentMap).replace('typing.', '')}.\"\n )\n\n for (node_name, assignment_pack) in assignments.items():\n\n # a sequence of size 2 is expected to be (assignment string, noise model)\n if len(assignment_pack) == 2:\n assignment_str, noise_model = assignment_pack\n parents = extract_parents(assignment_str, noise_model)\n\n noise, assignment_func = sympify_assignment(\n parents, assignment_str, noise_model\n )\n\n # a sequence of size 3 is expected to be (parents list, assignment string, noise model)\n elif len(assignment_pack) == 3:\n parents, assignment_func, noise_model = assignment_pack\n assert callable(\n assignment_func\n ), \"Assignment tuple holds 3 elements, but the function entry is not callable.\"\n assignment_str = None\n else:\n raise ValueError(\n \"Assignment entry must be a sequence of 2 or 3 entries.\"\n )\n\n if len(parents) > 0:\n for parent in parents:\n self.dag.add_edge(parent, node_name)\n else:\n self.roots.append(node_name)\n\n if noise_model is not None:\n parents = [Assignment.noise_argname] + list(parents)\n\n attr_dict = {\n self.assignment_key: Assignment(\n assignment_func, parents, assignment_str\n ),\n self.noise_key: noise_model,\n self.noise_repr_key: extract_rv_desc(noise_model),\n }\n\n self.dag.add_node(\n node_name,\n **attr_dict,\n )\n\n def seed(\n self, seed: Optional[Union[int, np.random.Generator, np.random.RandomState]]\n ):\n \"\"\"\n Seeds the assignments.\n\n Parameters\n ----------\n seed: int,\n The seed to use for rng.\n \"\"\"\n if seed is not None:\n if isinstance(seed, int):\n self.rng_state = np.random.default_rng(seed=seed)\n elif isinstance(seed, (np.random.Generator, np.random.RandomState)):\n self.rng_state = seed\n else:\n raise ValueError(f\"seed type {type(seed)} not supported.\")\n\n def plot(\n self,\n draw_labels: bool = True,\n node_size: int = 500,\n figsize: Tuple[int, int] = (6, 4),\n dpi: int = 150,\n alpha: float = 0.5,\n savepath: Optional[str] = None,\n **kwargs,\n ):\n \"\"\"\n Plot the causal graph of the bayesian_graphs in a dependency oriented way.\n\n This will attempt a tree plot of the bayesian_graphs, in the case that the graph is indeed a tree.\n However, because a causal graph is a DAG and can thus have directionless cycles (but not directional cycles), a\n tree structure often can't be computed. Therefore this method relies on graphviz to compute a feasible\n representation of the causal graph.\n\n The graphviz package has been marked as an optional package for this module and therefore needs to be installed\n by the user.\n Note, that graphviz may demand further libraries to be supplied, thus the following\n command should install the necessary dependencies on Ubuntu, if graphviz couldn't be found on your system.\n Open a terminal and type:\n\n ``sudo apt-get install graphviz libgraphviz-dev pkg-config``\n\n Notes\n -----\n One will need to call ``plt.show()`` for the plot to be printed to the backend.\n\n Parameters\n ----------\n draw_labels : (optional) bool,\n Whether to draw the node labels onto the node. Can look unwieldy if the names are long.\n Default is True.\n node_size : (optional) int,\n the size of the node circles in the graph. Bigger values mean bigger circles.\n Default is 500.\n figsize : (optional) tuple,\n the size of the figure to be passed to matplotlib. Default is (6, 4).\n dpi : (optional) int,\n the dots per inch arg for matplotlib. Default is 150.\n alpha : (optional) float,\n the statistical significance level for the test. Default value is 0.05.\n savepath: (optional) str,\n the full filepath to the, to which the plot should be saved. If not provided, the plot will not be saved.\n kwargs :\n arguments to be passed to the ``networkx.draw`` method. Check its documentation for a full list.\n\n Returns\n -------\n tuple,\n the plt.figure and figure-axis objects holding the graph plot.\n \"\"\"\n if nx.is_tree(self.dag):\n pos = hierarchy_pos(self.dag, root_node=self.roots[0])\n else:\n pos = graphviz_layout(self.dag, prog=\"dot\")\n if draw_labels:\n labels = self.var_draw_dict\n else:\n labels = {}\n fig, ax = plt.subplots(1, 1, figsize=figsize, dpi=dpi)\n ax.set_title(self.scm_name)\n nx.draw(\n self.dag,\n pos=pos,\n ax=ax,\n labels=labels,\n with_labels=True,\n node_size=node_size,\n alpha=alpha,\n **kwargs,\n )\n if savepath is not None:\n fig.savefig(savepath)\n return fig, ax\n\n def str(self):\n \"\"\"\n Computes a string representation of the SCM. Specifically, returns a string of the form:\n\n 'Structural Causal Model of `nr_variables` variables: X_0, X_1, ...\n Following variables are actively intervened on: [`list(intervened variables)`]\n Current Functional Functions are:\n X_0 := f(N) = `X_0 functional_string_representation`\n X_1 := f(N, X_0) = `X_1 functional_string_representation`\n ...'\n\n Returns\n -------\n str,\n the representation.\n \"\"\"\n variables = self.get_variables()\n nr_vars = len(variables)\n lines = [\n f\"Structural Causal Model of {nr_vars} \"\n + (\"variables: \" if nr_vars > 1 else \"variable: \")\n + \", \".join(variables[0:10])\n + (\", ...\" if nr_vars > 10 else \"\"),\n f\"Variables with active interventions: {list(self.interventions_backup_attr.keys())}\",\n \"Assignments:\",\n ]\n max_var_space = max([len(var_name) for var_name in variables])\n for node in self.dag.nodes:\n node_view = self[node]\n noise_symbol = node_view.noise\n parents_var = [pred for pred in self.dag.predecessors(node)]\n if noise_symbol is not None:\n parents_var = [str(noise_symbol)] + parents_var\n args_str = \", \".join(parents_var)\n line = f\"{str(node).rjust(max_var_space)} := f({args_str}) = {str(node_view.assignment)}\"\n if noise_symbol is not None:\n # add explanation to the noise term\n line += f\"\\t [ {noise_symbol} ~ {str(node_view.noise_repr)} ]\"\n lines.append(line)\n return \"\\n\".join(lines)\n\n def get_variables(self, causal_order=True) -> List[str]:\n \"\"\"\n Get a list of the variables in the SCM.\n\n Parameters\n ----------\n causal_order: bool (optional),\n If True, the list is guaranteed to be in a causal dependency order starting with root nodes.\n Defaults to True.\n\n Returns\n -------\n list,\n the variables in the SCM.\n \"\"\"\n if causal_order:\n return list(self._causal_iterator())\n else:\n return list(self.dag.nodes)\n\n def get_variable_args(self, variable: str):\n \"\"\"\n Returns the input arguments of the node and their position as parameter in the assignment.\n\n Parameters\n ----------\n variable: str,\n the variable of interest.\n\n Returns\n -------\n dict,\n a dictionary with the arguments as keys and their position as values\n \"\"\"\n return self[variable].assignment.arg_positions\n\n @staticmethod\n def filter_variable_names(variables: Iterable, dag: nx.DiGraph):\n \"\"\"\n Filter out variable names, that are not currently in the graph. Warn for each variable that wasn't present.\n\n Returns a generator which iterates over all variables that have been found in the graph.\n\n Parameters\n ----------\n variables: list,\n the variables to be filtered\n\n dag: nx.DiGraph,\n the DAG in which the variables are supposed to be found.\n\n Returns\n -------\n generator,\n generates the filtered variables in sequence.\n \"\"\"\n for variable in variables:\n if variable in dag.nodes:\n yield variable\n else:\n logging.warning(\n f\"Variable '{variable}' not found in graph. Omitting it.\"\n )\n\n def _causal_iterator(self, variables: Optional[Iterable] = None):\n \"\"\"\n Provide a causal iterator through the graph starting from the roots going to the variables needed.\n\n This iterator passes only the ancestors of the variables and thus is helpful in filtering out all the variables\n that have no causal effect on the desired variables.\n\n Parameters\n ----------\n variables: list,\n the names of all the variables that are to be considered. Names that cannot be found in the naming list of\n the graph will be ignored (warning raised).\n\n Yields\n ------\n Hashable,\n the node object used to denote nodes in the graph in causal order. These are usually str or ints, but can be\n any hashable type passable to a dict.\n \"\"\"\n if variables is None:\n for node in nx.topological_sort(self.dag):\n yield node\n return\n visited_nodes: Set = set()\n var_causal_priority: Dict = defaultdict(int)\n queue = deque([var for var in self.filter_variable_names(variables, self.dag)])\n while queue:\n nn = queue.popleft()\n # this line appears to be pointless, but is necessary to emplace the node 'nn' in the dict with its current\n # value, if already present, otherwise with the default value (0).\n var_causal_priority[nn] = var_causal_priority[nn]\n if nn not in visited_nodes:\n for parent in self.dag.predecessors(nn):\n var_causal_priority[parent] = max(\n var_causal_priority[parent], var_causal_priority[nn] + 1\n )\n queue.append(parent)\n visited_nodes.add(nn)\n for key, _ in sorted(var_causal_priority.items(), key=lambda x: -x[1]):\n yield key\n\n\ndef sympify_assignment(parents: Iterable[str], assignment_str: str, noise_model: RV):\n \"\"\"\n Parse the provided assignment string with sympy and then lambdifies it, to be used as a normal function.\n\n Parameters\n ----------\n assignment_str: str, the assignment to parse.\n parents: Iterable, the parents' names.\n noise_model: RV, the random variable inside the assignment.\n\n Returns\n -------\n function,\n the lambdified assignment.\n \"\"\"\n\n symbols = []\n if noise_model is not None:\n symbols.append(noise_model)\n # let the noise models variable name be known as symbol. This is necessary for sympifying.\n exec(f\"{str(noise_model)} = noise_model\")\n for par in parents:\n exec(f\"{par} = sympy.Symbol('{par}')\")\n symbols.append(eval(par))\n assignment = sympy.sympify(eval(assignment_str))\n try:\n assignment = sympy.lambdify(symbols, assignment, \"numpy\")\n except NameError as e:\n warnings.warn(\n f\"The assignment string could not be resolved in numpy, the error message reads: {e}\\n\"\n f\"Lambdifying without numpy.\",\n )\n assignment = sympy.lambdify(symbols, assignment)\n return noise_model, assignment\n\n\ndef extract_rv_desc(rv: Optional[RV]):\n \"\"\"\n Extracts a human readable string description of the random variable.\n\n Parameters\n ----------\n rv: RV,\n the random variable.\n\n Returns\n -------\n str, the description.\n \"\"\"\n if rv is None:\n return str(None)\n\n dist = rv.pspace.args[1]\n argnames = dist._argnames\n args = dist.args\n dist_name = str(dist).split(\"(\", 1)[0].replace(\"Distribution\", \"\")\n full_rv_str = f\"{dist_name}({', '.join([f'{arg}={val}' for arg, val in zip(argnames, args)])})\"\n return full_rv_str\n\n\ndef hierarchy_pos(\n graph: nx.Graph,\n root_node=None,\n width=1.0,\n vert_gap=0.2,\n vert_loc=0,\n leaf_vs_root_factor=0.5,\n check_for_tree=True,\n):\n \"\"\"\n If the graph is a tree this will return the positions to plot this in a\n hierarchical layout.\n\n Based on Joel's answer at https://stackoverflow.com/a/29597209/2966723,\n but with some modifications.\n\n We include this because it may be useful for plotting transmission trees,\n and there is currently no networkx equivalent (though it may be coming soon).\n\n There are two basic approaches we think of to allocate the horizontal\n location of a node.\n\n - Top down: we allocate horizontal space to a node. Then its ``k``\n descendants split up that horizontal space equally. This tends to result\n in overlapping nodes when some have many descendants.\n - Bottom up: we allocate horizontal space to each leaf node. A node at a\n higher level gets the entire space allocated to its descendant leaves.\n Based on this, leaf nodes at higher levels get the same space as leaf\n nodes very deep in the tree.\n\n We use use both of these approaches simultaneously with ``leaf_vs_root_factor``\n determining how much of the horizontal space is based on the bottom up\n or top down approaches. ``0`` gives pure bottom up, while 1 gives pure top\n down.\n\n\n Parameters\n ----------\n **G** the graph (must be a tree)\n\n **root** the root node of the tree\n - if the tree is directed and this is not given, the root will be found and used\n - if the tree is directed and this is given, then the positions will be\n just for the descendants of this node.\n - if the tree is undirected and not given, then a random choice will be used.\n\n **width** horizontal space allocated for this branch - avoids overlap with other branches\n\n **vert_gap** gap between levels of hierarchy\n\n **vert_loc** vertical location of root\n\n **leaf_vs_root_factor**\n \"\"\"\n if check_for_tree and not nx.is_tree(graph):\n raise TypeError(\"cannot use hierarchy_pos on a graph that is not a tree\")\n\n if root_node is None:\n if isinstance(graph, nx.DiGraph):\n root_node = next(\n iter(nx.topological_sort(graph))\n ) # allows back compatibility with nx version 1.11\n else:\n root_node = np.random.choice(list(graph.nodes))\n\n def __hierarchy_pos(\n graph_,\n root_,\n leftmost_,\n width_,\n leaf_dx_=0.2,\n vert_gap_=0.2,\n vert_loc_=0,\n xcenter_=0.5,\n root_pos_=None,\n leaf_pos_=None,\n parent_=None,\n ):\n \"\"\"\n see hierarchy_pos docstring for most arguments\n\n pos: a dict saying where all nodes go if they have been assigned\n parent: parent of this branch. - only affects it if non-directed\n\n \"\"\"\n\n if root_pos_ is None:\n root_pos_ = {root_: (xcenter_, vert_loc_)}\n else:\n root_pos_[root_] = (xcenter_, vert_loc_)\n if leaf_pos_ is None:\n leaf_pos_ = {}\n children = list(graph_.neighbors(root_))\n leaf_count = 0\n if not isinstance(graph_, nx.DiGraph) and parent_ is not None:\n children.remove(parent_)\n if len(children) != 0:\n root_dx = width_ / len(children)\n nextx = xcenter_ - width_ / 2 - root_dx / 2\n for child in children:\n nextx += root_dx\n root_pos_, leaf_pos_, new_leaves = __hierarchy_pos(\n graph_,\n child,\n leftmost_ + leaf_count * leaf_dx_,\n width_=root_dx,\n leaf_dx_=leaf_dx_,\n vert_gap_=vert_gap_,\n vert_loc_=vert_loc_ - vert_gap_,\n xcenter_=nextx,\n root_pos_=root_pos_,\n leaf_pos_=leaf_pos_,\n parent_=root_,\n )\n leaf_count += new_leaves\n\n leftmost_child = min(\n (x for x, y in [leaf_pos_[child] for child in children])\n )\n rightmost_child = max(\n (x for x, y in [leaf_pos_[child] for child in children])\n )\n leaf_pos_[root_] = ((leftmost_child + rightmost_child) / 2, vert_loc_)\n else:\n leaf_count = 1\n leaf_pos_[root_] = (leftmost_, vert_loc_)\n # pos[root] = (leftmost + (leaf_count-1)*dx/2., vert_loc)\n print(leaf_count)\n return root_pos_, leaf_pos_, leaf_count\n\n x_center = width / 2.0\n if isinstance(graph, nx.DiGraph):\n leaf_count = len(\n [\n node\n for node in nx.descendants(graph, root_node)\n if graph.out_degree(node) == 0\n ]\n )\n elif isinstance(graph, nx.Graph):\n leaf_count = len(\n [\n node\n for node in nx.node_connected_component(graph, root_node)\n if graph.degree(node) == 1 and node != root_node\n ]\n )\n else:\n raise ValueError(\n \"Passed graph is neither a networkx.DiGraph nor networkx.Graph.\"\n )\n root_pos, leaf_pos, leaf_count = __hierarchy_pos(\n graph,\n root_node,\n 0,\n width,\n leaf_dx_=width * 1.0 / leaf_count,\n vert_gap_=vert_gap,\n vert_loc_=vert_loc,\n xcenter_=x_center,\n )\n pos = {}\n for node in root_pos:\n pos[node] = (\n leaf_vs_root_factor * leaf_pos[node][0]\n + (1 - leaf_vs_root_factor) * root_pos[node][0],\n leaf_pos[node][1],\n )\n x_max = max(x for x, y in pos.values())\n for node in pos:\n pos[node] = (pos[node][0] * width / x_max, pos[node][1])\n return pos\n" } ]
8
jennykatherinehudson/Rock_Paper_Scissors_game
https://github.com/jennykatherinehudson/Rock_Paper_Scissors_game
e769b959731f32fcd8540457b0d2be0fa6e6357b
d650c95e50b1eb82a976503395ccc6636cc699d2
7dd55a3f5de11f98928484488c37e7411ccecc5a
refs/heads/master
2023-05-12T16:00:53.532178
2020-10-08T16:54:08
2020-10-08T16:54:08
297,764,133
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5241830348968506, "alphanum_fraction": 0.530718982219696, "avg_line_length": 30.89583396911621, "blob_id": "497ff92a5891ee83332592b447ed44b6b612d431", "content_id": "cd92cf1e7427a104bda7e1fd698dc7c09cfd4c15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1530, "license_type": "no_license", "max_line_length": 88, "num_lines": 48, "path": "/rock_paper_scissors.py", "repo_name": "jennykatherinehudson/Rock_Paper_Scissors_game", "src_encoding": "UTF-8", "text": "# Rock - Paper - Scissors\ncountA = 0\ncountB = 0\n\nwhile True: \n print('This is the Rock-Paper-Scissors game\\nPlease write: rock, paper or scissors')\n a = input('Player A - your turn:')\n while a != 'rock' and a != 'paper' and a != 'scissors':\n print('Player A: Input correct item: rock, paper or scissors')\n a = input('Player A - your turn:')\n b = input('Player B - your turn:')\n if b != 'rock' and b != 'paper' and b != 'scissors':\n print('Player B: Input correct item: rock, paper or scissors')\n b = input('Player B - your turn:')\n\n if a == b:\n print('Draw')\n elif (a == 'paper' and b == 'rock'):\n print('Player A wins')\n countA+=1\n elif (a == 'rock' and b == 'paper'):\n print('Player B wins')\n countB+=1\n elif (a == 'rock' and b == 'scissors'):\n print('Player A wins')\n countA+=1\n elif (a == 'scissors' and b == 'rock'):\n print('Player B wins')\n countB+=1\n elif (a == 'scissors' and b == 'paper'):\n print('Player A wins')\n countA+=1\n elif (a == 'paper' and b == 'scissors'):\n print('Player B wins')\n countB+=1\n\n if countA == 3 or countB == 3:\n print('Player A : Player B')\n print(countA, ':', countB)\n break\n\n finish = input('Would you like to play again? (Yes/No)')\n if finish == 'No' or finish == 'no':\n print('Player A : Player B')\n print(countA, ':', countB)\n break\n\n #I've made some comments to see it on new branch" } ]
1
khiemnguyen240900/HuffmanTree-Visualization
https://github.com/khiemnguyen240900/HuffmanTree-Visualization
c34b20a19307f577c96fe9f3bd837af78489870c
33585bb247a35ac4ccaac824927d5649e73fb2de
da7dff43c4e3c97b8e59ef98129ee033c7e70682
refs/heads/main
2023-02-15T07:21:41.752297
2021-01-14T09:05:35
2021-01-14T09:05:35
329,559,805
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5144923329353333, "alphanum_fraction": 0.5237521529197693, "avg_line_length": 34.78627395629883, "blob_id": "b07bb433de2a59325c33269ac0a47c1229b19d82", "content_id": "11ea1982916b6001d6bf59a56e00a2c9d28bbeca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18251, "license_type": "permissive", "max_line_length": 129, "num_lines": 510, "path": "/huffman-master/huffman.py", "repo_name": "khiemnguyen240900/HuffmanTree-Visualization", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\"\"\"\nCopyright (c) 2018 Matthew Emerson\n\nA simple python implementation of Huffman coding\n\"\"\"\n\nimport struct, os, subprocess\n\nfrom priority_queue import PriorityQueue\n\nimport cv2 as cv\nimport numpy as np\n\nfrom graphviz import Digraph\nfrom sympy import *\n\ninit_printing()\ndot = Digraph(comment='Huffman Tree')\n\ndef create_TreeNode(start=None, end=None, text=None):\n dot.node(end, text, shape='doublecircle')\n dot.edge(start, end)\n\n\ndef create_TreeLeaf(start=None, end=None, text=None):\n dot.node(end, text, shape='invhouse', color='black', fillcolor='yellow', style='filled')\n dot.edge(start, end)\n\n\ndef convert(char_array):\n return \"\".join(char_array)\n\ndef graphTree():\n ###Graph the Huffman Tree\n with open('output/graph.dot', 'w') as f:\n f.write(dot.source)\n subprocess.call('dot -Tpng output/graph.dot -o output/image/graph.png', shell=True)\n ###install Graphviz && run 'dot -c' in cmd when get errors\n\ndef frequencies(text):\n \"\"\"Return a dict of frequencies for each letter found in text\"\"\"\n freq = {}\n for c in text:\n freq.setdefault(c, 0)\n freq[c] += 1\n return freq\n\n\nclass BitIter:\n \"\"\"Used to iterate through through an int bit by bit. Includes a length to add left padding 0's\"\"\"\n\n def __init__(self, i, length):\n self.i = i\n # self.length = i.bit_length() + offset\n self.length = length\n\n def __iter__(self):\n self.current_bit = 0\n return self\n\n def __next__(self):\n if self.current_bit >= self.length:\n raise StopIteration\n b = (self.i >> (self.length - self.current_bit - 1)) & 1\n self.current_bit += 1\n return b\n\n def __repr__(self):\n return \"{0:0{1}b}\".format(self.i, self.length)\n\n\nclass HuffmanNode:\n \"\"\"Nodes used in HuffmanTree\"\"\"\n\n def __init__(self, char_list, freq=0, left=None, right=None):\n \"\"\"\n Creates a new node\n\n :param char_list: list of chars found in this node and below\n :param freq: The occurrences of all chars in char_list in the input\n :param left: The 1 node\n :param right: The 0 node\n \"\"\"\n self.char_list = char_list\n self.freq = freq\n self.left = left\n self.right = right\n\n def __repr__(self):\n return \"<HuffmanNode: char_list='{}', freq={}, left={}, right={}>\".format(self.char_list, self.freq, self.left,\n self.right)\n\n def __lt__(self, other):\n return self.freq < other.freq\n\n def __le__(self, other):\n return self.freq <= other.freq\n\n def __gt__(self, other):\n return self.freq > other.freq\n\n def __ge__(self, other):\n return self.freq >= other.freq\n\n\nclass HuffmanTree:\n \"\"\"Sets up a Huffman Tree for encoding and decoding text\"\"\"\n graph_node_list = []\n\n def build_tree(self, text):\n \"\"\"\n Users letter frequency found in text to construct the Huffman tree\n\n :param text: Input text to use for calculating letter frequencies\n \"\"\"\n if not text:\n raise ValueError\n self.input = text\n self.char_freqs = frequencies(self.input)\n pqueue = PriorityQueue()\n for k, v in self.char_freqs.items():\n pqueue.push(HuffmanNode([k], v, None, None))\n \"\"\"lay 2 phan tu nho nhat\"\"\"\n left = pqueue.pop()\n right = pqueue.pop()\n\n while left and right:\n \"\"\"\"Gop 2 node nho thanh 1 node lon hon va tiep tuc\"\"\"\n pqueue.push(HuffmanNode(left.char_list + right.char_list, left.freq + right.freq, left, right))\n left = pqueue.pop()\n right = pqueue.pop()\n\n self.head = left\n self.code_dict = {}\n for c in self.head.char_list:\n self.code_dict[c] = self.get_code(c)\n\n def encode_tree(self):\n \"\"\"\n Serializes the dict of Huffman {char: (code_length, code)} into a bytes for reconstructing the tree\n :return: bytes of packed codes\n \"\"\"\n if hasattr(self, 'encoded_tree'):\n return self.encoded_tree\n else:\n out = struct.pack(\"H\", in_width)\n out += struct.pack(\"H\", in_height)\n out += struct.pack(\"H\", len(self.head.char_list))\n for i in self.head.char_list:\n length, code = self.get_code(i)\n # out += struct.pack(\"B\", ord(i))\n out += struct.pack(\"B\", i)\n out += struct.pack(\"B\", length)\n out += struct.pack(\"H\", code)\n return out\n\n def get_code(self, char):\n \"\"\"\n Get the Huffman code for a character. If we already have a constructed code table, grab\n the character from self.code_dict, otherwise traverse the tree.\n\n :param char: Input char\n :return: Tuple of (code_length, code)\n \"\"\"\n\n # Check if there's already a code_dict compiled and contains the search char\n if hasattr(self, 'code_dict'):\n if char in self.code_dict:\n return self.code_dict[char]\n code_string = ''\n # Otherwise build the code by traversing the tree\n n = self.head\n if not n.left and not n.right:\n length = 1\n code = 1\n else:\n length = 0\n code = 0\n while n.left or n.right:\n if n.left and char in n.left.char_list:\n code = (code << 1) | 1\n n = n.left\n length += 1\n code_string += '1'\n if not n.left and not n.right:\n create_TreeLeaf(start=code_string[0:len(code_string) - 1], end=code_string, text=str(char)+': '+ code_string)\n elif code_string not in self.graph_node_list:\n create_TreeNode(start=code_string[0:len(code_string)-1], end=code_string, text=code_string)\n self.graph_node_list.append(code_string)\n elif n.right and char in n.right.char_list:\n code = (code << 1) | 0\n length += 1\n n = n.right\n code_string += '0'\n if not n.left and not n.right:\n create_TreeLeaf(start=code_string[0:len(code_string) - 1], end=code_string, text=str(char)+': '+ code_string)\n elif code_string not in self.graph_node_list:\n create_TreeNode(start=code_string[0:len(code_string) - 1], end=code_string, text=code_string)\n self.graph_node_list.append(code_string)\n return length, code\n\n def get_graph(self):\n ###Graph the Huffman Tree\n with open('output/' + file_name + '_graph.dot', 'w') as f:\n f.write(dot.source)\n subprocess.call('dot -Tpng output/' + file_name + '_graph.dot -o output/image/' + file_name + '_graph.png', shell=True)\n ###install Graphviz && run 'dot -c' in cmd when get errors\n\n def get_code_string(self, char, n=None):\n \"\"\"Get the binary Huffman code in string form (ex. '11001')\"\"\"\n if n is None:\n n = self.head\n if n.left is not None:\n if char in n.left.char_list:\n return '1' + self.get_code_string(char, n.left)\n if n.right is not None:\n if char in n.right.char_list:\n return '0' + self.get_code_string(char, n.right)\n return ''\n\n def get_char(self, code, max_length=0):\n \"\"\"\n Given a code, traverses the tree to retrieve the character\n\n :param code: The binary code to search for\n :param max_length: The length of the code (used to generate left padding 0's)\n :return: Tuple of (Length of code, Character)\n \"\"\"\n bits = BitIter(code, max_length)\n n = self.head\n length = 0\n for bit in bits:\n if not n:\n return None, None\n if not n.left and not n.right:\n # We reached a leaf, but there are more bits left\n break\n else:\n length += 1\n if bit == 1:\n n = n.left\n else:\n n = n.right\n if not n or n.left or n.right:\n # Node doesn't exist or node isn't a leaf\n return None, None\n else:\n # Reached a leaf\n return length, n.char_list[0]\n\n def encode(self, text, file):\n \"\"\"\n Encodes input using the Huffman codes generated in the constructor\n\n Each code is inserted into a byte before being packed into bytes. If there is any\n overflow (the byte + code is larger then 8 bits) then the first 8 bits are packed\n and the byte is set to the remaining 8 bits. If there are any bits remaining, the last\n byte will be padded with 0's.\n\n Returns the output of encoding with the first byte being padding, the next two bytes\n being the length of data (in bytes), then the bytes.\n\n 0 1 2 3\n 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n | Padding | Length |\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n | Data (padded with 0's to the nearest byte) |\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n :return: encoded output as bytes\n \"\"\"\n output = self.encode_tree()\n byte = 0\n num_bits = 0\n total_length = 0\n for c in text:\n length, code = self.get_code(c)\n # Add the returned code to the byte\n byte = (byte << length) | code\n num_bits += length\n\n # Overflow - byte contains more then 8 bits\n if num_bits >= 8:\n overflow = num_bits - 8\n\n # Pack the first 8 bits\n output += struct.pack(\"B\", byte >> overflow)\n total_length += 1\n\n # Set the byte to the remaining bits\n byte = byte & ((1 << overflow) - 1)\n num_bits = overflow\n\n if num_bits != 0:\n padding = 8 - num_bits\n\n # Pack any bits that are remaining\n output += struct.pack(\"B\", byte << padding)\n total_length += 1\n fout = open(file, 'wb')\n fout.write(output)\n return output\n\n def decode(self, buf):\n \"\"\"\n Decodes buf using the generated Huffman tree.\n\n The first byte should be the padding found at the end of the\n buffer. The next two bytes should be the total length of input in\n bytes.\n\n See encode\n\n :param buf: Binary buffer to decode\n :return: The decoded text\n \"\"\"\n global in_width, in_height\n char_list = []\n codes = {}\n in_width = struct.unpack_from(\"H\", buf)[0]\n in_height = struct.unpack_from(\"H\", buf, 2)[0]\n header_length = struct.unpack_from(\"H\", buf, 4)[0] * 4 + 2 + 4\n for i in range(6, header_length, 4):\n char, code_length, code = struct.unpack_from(\"BBH\", buf, i)\n char_list.append(char)\n codes[char] = (code_length, code)\n # print(char)\n self.char_list = char_list\n self.code_dict = codes\n\n self.head = HuffmanNode([])\n print(self.code_dict.items())\n for k, v in self.code_dict.items():\n self.head.char_list.append(k)\n bits = BitIter(v[1], v[0])\n n = self.head\n for bit in bits:\n if bit == 1:\n if not n.left:\n n.left = HuffmanNode([k])\n else:\n n.left.char_list.append(k)\n n = n.left\n else:\n if not n.right:\n n.right = HuffmanNode([k])\n else:\n n.right.char_list.append(k)\n n = n.right\n\n total_length = len(buf) - header_length\n decoded_text = ''\n decoded_array = []\n previous_bits = 0\n previous_bits_length = 0\n i, count = 0, 0\n while True:\n # See if there is a code from the previous byte\n code_length, char = self.get_char(previous_bits, previous_bits_length)\n if code_length:\n # Found a code - calculate any left over bits\n decoded_text += str(char)\n decoded_array.append(char)\n count += 1\n if count > in_height * in_width:\n break\n decoded_text += ' '\n previous_bits_length -= code_length\n mask = (1 << previous_bits_length) - 1\n previous_bits = previous_bits & mask\n else:\n # Didn't find a code - Unpack another byte\n if i > total_length - 1:\n break\n previous_bits = (previous_bits << 8) | struct.unpack_from(\"B\", buf, i + header_length)[0]\n previous_bits_length += 8\n i += 1\n\n return decoded_text, decoded_array\n\n def decode_file(self, filename):\n \"\"\"\n Decodes buf using the generated Huffman tree.\n\n The first byte should be the padding found at the end of the\n buffer. The next two bytes should be the total length of input in\n bytes.\n\n See encode\n\n :param buf: Binary buffer to decode\n :return: The decoded text\n \"\"\"\n global in_width, in_height\n file = open(filename, 'rb')\n buf = file.read()\n char_list = []\n codes = {}\n in_width = struct.unpack_from(\"H\", buf)[0]\n in_height = struct.unpack_from(\"H\", buf, 2)[0]\n header_length = struct.unpack_from(\"H\", buf, 4)[0] * 4 + 2 + 4\n for i in range(6, header_length, 4):\n char, code_length, code = struct.unpack_from(\"BBH\", buf, i)\n char_list.append(char)\n codes[char] = (code_length, code)\n # print(char)\n self.char_list = char_list\n self.code_dict = codes\n\n self.head = HuffmanNode([])\n print(self.code_dict.items())\n for k, v in self.code_dict.items():\n self.head.char_list.append(k)\n bits = BitIter(v[1], v[0])\n n = self.head\n for bit in bits:\n if bit == 1:\n if not n.left:\n n.left = HuffmanNode([k])\n else:\n n.left.char_list.append(k)\n n = n.left\n else:\n if not n.right:\n n.right = HuffmanNode([k])\n else:\n n.right.char_list.append(k)\n n = n.right\n\n total_length = len(buf) - header_length\n decoded_text = ''\n decoded_array = []\n previous_bits = 0\n previous_bits_length = 0\n i, count = 0, 0\n while True:\n # See if there is a code from the previous byte\n code_length, char = self.get_char(previous_bits, previous_bits_length)\n if code_length:\n # Found a code - calculate any left over bits\n decoded_text += str(char)\n decoded_array.append(char)\n count += 1\n if count > in_height * in_width - 1:\n break\n decoded_text += ' '\n previous_bits_length -= code_length\n mask = (1 << previous_bits_length) - 1\n previous_bits = previous_bits & mask\n else:\n # Didn't find a code - Unpack another byte\n if i > total_length - 1:\n break\n previous_bits = (previous_bits << 8) | struct.unpack_from(\"B\", buf, i + header_length)[0]\n previous_bits_length += 8\n i += 1\n\n return decoded_text, decoded_array\n\n def print_code_table(self):\n \"\"\"Prints a table of all characters, codes, and code lengths found in the input\"\"\"\n for i in self.head.char_list:\n length, code = self.get_code(i)\n print(\"'{0}'\\t\\t{1}\\t\\t{1:0{2}b}\".format(i, code, length))\n\n def __repr__(self):\n return \"<HuffmanTree: head={}>\".format(self.head)\n\ndef read_image(path, type, width=None, height=None):\n img_array = []\n img_src = cv.imread(path + '.' + type)\n if (width is not None) and (height is not None):\n img_src = cv.resize(img_src, (width, height))\n img_src = cv.cvtColor(img_src, cv.COLOR_BGR2GRAY)\n # img_src = cv.equalizeHist(img_src)\n img_src = 350 - img_src\n cv.imwrite(path + '_gray.' + type, img_src)\n (img_width, img_height) = img_src.shape\n img_1d = img_src.reshape(img_width * img_height)\n print(str(img_width) + ' ' + str(img_height))\n for c in img_1d:\n img_array.append(c)\n return img_array, img_width, img_height\n\n\nif __name__ == \"__main__\":\n global in_width, in_height, str_size, file_name\n file_name = 'tb'\n in_str, in_width, in_height = read_image('data/' + file_name, 'jpg')\n # print(\"Original text: {}\\n\".format(in_str))\n tree = HuffmanTree()\n tree.build_tree(in_str)\n encoded_text = tree.encode(in_str, 'encoded/' + file_name + '_encoded.dat')\n tree.get_graph()\n print(\"Encoded text: {}\\n\".format(\" \".join(\"{:02x}\".format(c) for c in encoded_text)))\n tree.print_code_table()\n new_tree = HuffmanTree()\n # decoded_text, decoded_array = new_tree.decode(encoded_text)\n decoded_text, decoded_array = new_tree.decode_file('encoded/' + file_name + '_encoded.dat')\n decoded_array = np.reshape(decoded_array, (in_width, in_height))\n decoded_img = np.array(decoded_array, dtype=np.uint8)\n cv.imshow('Decoded_image', decoded_img)\n cv.waitKey(0)\n # print(\"Decoded text: {}\\n\".format(decoded_text))\n print(\"Total length of input (in bytes): {}\".format(in_height * in_width))\n # print(\"Total length of encoded text (in bytes): {}\".format(len(encoded_text)))\n # print(\"Compression ratio: {}:1\".format(str_size / len(encoded_text)))\n" }, { "alpha_fraction": 0.5652173757553101, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 16.375, "blob_id": "e78e95e46a7b3060b475816410787d0e6cc4e85c", "content_id": "2ef3ff47b850ae51cebdfb43d00434f77ea96e46", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 138, "license_type": "permissive", "max_line_length": 44, "num_lines": 8, "path": "/huffman-master/test_struct.py", "repo_name": "khiemnguyen240900/HuffmanTree-Visualization", "src_encoding": "UTF-8", "text": "import struct\n\nfout = open('test.dat', 'wb')\n\nfout.write(struct.pack('>i', 42))\nfout.write(struct.pack('>f', 2.71828182846))\n\nfout.close()" }, { "alpha_fraction": 0.7694194316864014, "alphanum_fraction": 0.774325430393219, "avg_line_length": 30.384614944458008, "blob_id": "536bea3422d3d75e25e6b12c82b1bdd67ce702d5", "content_id": "27ec2737f2750c9bacd4d73dc6432e8457be5055", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1223, "license_type": "permissive", "max_line_length": 298, "num_lines": 39, "path": "/huffman-master/README.md", "repo_name": "khiemnguyen240900/HuffmanTree-Visualization", "src_encoding": "UTF-8", "text": "## Synopsis\n\nA simple huffman encoder/decoder written in Python. Also includes a very basic Priority Queue implementation.\n\n## Details\n\nGiven input text builds variable length Huffman codes using a binary tree based on character frequency. With the Huffman tree constructed text can be encoded or decoded.\n\nEncoded text produces a bytes string prepended with a serialized representation of the code table. This allows the decode function to read in this table, reconstruct the original tree and decode the input.\n\nAfter some testing it seems the compression ratio is around 1.8:1. Since the code table is prepended to the encoded text, it's not worth encoding shorter length strings. In order to achieve a compression ratio >1:1 it requires an input where the characters are repeated at least 6 times on average.\n\nTo encode text:\n```python\nfrom huffman import HuffmanTree\nstr = \"This is a test string\"\ntree = HuffmanTree()\ntree.build_tree(str)\nencoded_text = tree.encode(str)\n```\n\nThen to decode text:\n```python\nnew_tree = HuffmanTree()\ndecoded_text = new_tree.decode(encoded_text)\n```\n\nYou can also print out the code table:\n```python\ntree.print_code_table()\n```\n\n## Author\n\nMatthew Emerson\n\n## License\n\nReleased under MIT License." }, { "alpha_fraction": 0.5109797120094299, "alphanum_fraction": 0.5827702879905701, "avg_line_length": 23.6875, "blob_id": "fe3a4e1750b6da437e2fc7b98f7cb26546823964", "content_id": "f3f0be209134bbad01d82112203b8eab6102caee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1184, "license_type": "permissive", "max_line_length": 94, "num_lines": 48, "path": "/huffman-master/show_img_test.py", "repo_name": "khiemnguyen240900/HuffmanTree-Visualization", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\n# def show_pic(p):\n# ''' use esc to see the results'''\n# print(type(p))\n# cv2.imshow('Color image', p)\n# while True:\n# k = cv2.waitKey(0) & 0xFF\n# if k == 27: break\n# return\n# cv2.destroyAllWindows()\n#\n# b = numpy.zeros([200,200,3])\n#\n# b[:,:,0] = numpy.ones([200,200])*255\n# b[:,:,1] = numpy.ones([200,200])*255\n# b[:,:,2] = numpy.ones([200,200])*0\n# cv2.imwrite('color_img.jpg', b)\n#\n#\n# c = cv2.imread('color_img.jpg', 1)\n# c = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)\n#\n# d = cv2.imread('color_img.jpg', 1)\n# d = cv2.cvtColor(c, cv2.COLOR_RGB2BGR)\n#\n# e = cv2.imread('color_img.jpg', -1)\n# e = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)\n#\n# f = cv2.imread('color_img.jpg', -1)\n# f = cv2.cvtColor(c, cv2.COLOR_RGB2BGR)\n#\n#\n# pictures = [d, c, f, e]\n#\n# for p in pictures:\n# show_pic(p)\n# # show the matrix\n# print(c)\n# print(c.shape)\n\nfloat_img = np.random.random((256,256))\nprint(float_img)\nim = np.array(float_img * 255, dtype = np.uint8)\nprint(im)\nthreshed = cv2.adaptiveThreshold(im, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 3, 0)\ncv2.imshow('a',threshed)\ncv2.waitKey(0)" }, { "alpha_fraction": 0.7580645084381104, "alphanum_fraction": 0.7580645084381104, "avg_line_length": 16.714284896850586, "blob_id": "631270444d746e1ea05af9ef8c8230fd7f136ab9", "content_id": "e03698a2a65f250bfb3b92eb3b3b9bef005ceb26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 124, "license_type": "no_license", "max_line_length": 47, "num_lines": 7, "path": "/README.md", "repo_name": "khiemnguyen240900/HuffmanTree-Visualization", "src_encoding": "UTF-8", "text": "# huffman_extra\nBuild Huffman tree, encode and decode an image.\nPackage:\n- graphviz\n- numpy\n- opencv-contrib-python\n- sympy\n" }, { "alpha_fraction": 0.6887640357017517, "alphanum_fraction": 0.6955056190490723, "avg_line_length": 25.205883026123047, "blob_id": "db7f14d75c1ff1d434c02f0214bfeba62d741628", "content_id": "50353b14aff7c9a3786f9b1cc27c7cb5f7694601", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 890, "license_type": "permissive", "max_line_length": 92, "num_lines": 34, "path": "/huffman-master/graph_test.py", "repo_name": "khiemnguyen240900/HuffmanTree-Visualization", "src_encoding": "UTF-8", "text": "import struct, os, subprocess\n\nfrom priority_queue import PriorityQueue\n\nimport cv2 as cv\nimport numpy as np\n\nfrom graphviz import Digraph\nfrom sympy import *\n\ninit_printing()\ndot = Digraph(comment='Huffman Tree')\n\ndef create_TreeNode(start=None, end=None, text=None):\n dot.node(end, text, shape='doublecircle')\n dot.edge(start, end)\n\n\ndef create_TreeLeaf(start=None, end=None, text=None):\n dot.node(end, text, shape='invhouse', color='black', fillcolor='yellow', style='filled')\n dot.edge(start, end)\n\n\ndef convert(char_array):\n return \"\".join(char_array)\n\ndef graphTree():\n ###Graph the Huffman Tree\n with open('output/graph.dot', 'w') as f:\n f.write(dot.source)\n subprocess.call('dot -Tpng output/graph.dot -o output/image/graph.png', shell=True)\n ###install Graphviz && run 'dot -c' in cmd when get errors\n\ncreate_TreeNode(start='1',end='10',text='10')" } ]
6
Z-fly/DemooPlayer-Txt-Builder
https://github.com/Z-fly/DemooPlayer-Txt-Builder
e3ba85dc236e5b7961ee068d0427717f1e4f71f7
648ab23b2ff79c16c147592ee4e97d3a0ceadf14
bed220103d144440685d094ae81b3c4c89a90fa1
refs/heads/master
2020-05-18T07:47:22.600718
2019-05-03T13:50:00
2019-05-03T13:50:00
184,274,922
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5838682055473328, "alphanum_fraction": 0.6275138854980469, "avg_line_length": 42.30331802368164, "blob_id": "82cbf899a840649bcc39f2bbfab12872d4557e6d", "content_id": "a692e2d2c1cf2b0ab7b720fa4f8c41c13be1ec5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9348, "license_type": "no_license", "max_line_length": 86, "num_lines": 211, "path": "/de.py", "repo_name": "Z-fly/DemooPlayer-Txt-Builder", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\n\r\n\r\nclass Ui_MainWindow(object):\r\n def setupUi(self, MainWindow):\r\n MainWindow.setObjectName(\"MainWindow\")\r\n MainWindow.resize(422, 488)\r\n MainWindow.setContextMenuPolicy(QtCore.Qt.NoContextMenu)\r\n self.centralwidget = QtWidgets.QWidget(MainWindow)\r\n self.centralwidget.setObjectName(\"centralwidget\")\r\n self.label10 = QtWidgets.QLabel(self.centralwidget)\r\n self.label10.setGeometry(QtCore.QRect(20, 380, 131, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n font.setPointSize(13)\r\n font.setBold(False)\r\n font.setWeight(50)\r\n self.label10.setFont(font)\r\n self.label10.setObjectName(\"label10\")\r\n self.label9 = QtWidgets.QLabel(self.centralwidget)\r\n self.label9.setGeometry(QtCore.QRect(20, 340, 131, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n font.setPointSize(13)\r\n font.setBold(False)\r\n font.setWeight(50)\r\n self.label9.setFont(font)\r\n self.label9.setObjectName(\"label9\")\r\n self.label1 = QtWidgets.QLabel(self.centralwidget)\r\n self.label1.setGeometry(QtCore.QRect(20, 22, 91, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n font.setPointSize(13)\r\n font.setBold(False)\r\n font.setWeight(50)\r\n self.label1.setFont(font)\r\n self.label1.setObjectName(\"label1\")\r\n self.label8 = QtWidgets.QLabel(self.centralwidget)\r\n self.label8.setGeometry(QtCore.QRect(20, 300, 141, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n font.setPointSize(13)\r\n font.setBold(False)\r\n font.setWeight(50)\r\n self.label8.setFont(font)\r\n self.label8.setObjectName(\"label8\")\r\n self.label2 = QtWidgets.QLabel(self.centralwidget)\r\n self.label2.setGeometry(QtCore.QRect(20, 60, 91, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n font.setPointSize(13)\r\n font.setBold(False)\r\n font.setWeight(50)\r\n self.label2.setFont(font)\r\n self.label2.setObjectName(\"label2\")\r\n self.line1 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.line1.setGeometry(QtCore.QRect(160, 20, 241, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n self.line1.setFont(font)\r\n self.line1.setObjectName(\"line1\")\r\n self.label7 = QtWidgets.QLabel(self.centralwidget)\r\n self.label7.setGeometry(QtCore.QRect(20, 260, 111, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n font.setPointSize(13)\r\n font.setBold(False)\r\n font.setWeight(50)\r\n self.label7.setFont(font)\r\n self.label7.setObjectName(\"label7\")\r\n self.label6 = QtWidgets.QLabel(self.centralwidget)\r\n self.label6.setGeometry(QtCore.QRect(20, 220, 111, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n font.setPointSize(13)\r\n font.setBold(False)\r\n font.setWeight(50)\r\n self.label6.setFont(font)\r\n self.label6.setObjectName(\"label6\")\r\n self.label4 = QtWidgets.QLabel(self.centralwidget)\r\n self.label4.setGeometry(QtCore.QRect(20, 140, 91, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n font.setPointSize(13)\r\n font.setBold(False)\r\n font.setWeight(50)\r\n self.label4.setFont(font)\r\n self.label4.setObjectName(\"label4\")\r\n self.label3 = QtWidgets.QLabel(self.centralwidget)\r\n self.label3.setGeometry(QtCore.QRect(20, 100, 91, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n font.setPointSize(13)\r\n font.setBold(False)\r\n font.setWeight(50)\r\n self.label3.setFont(font)\r\n self.label3.setObjectName(\"label3\")\r\n self.label5 = QtWidgets.QLabel(self.centralwidget)\r\n self.label5.setGeometry(QtCore.QRect(20, 180, 91, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n font.setPointSize(13)\r\n font.setBold(False)\r\n font.setWeight(50)\r\n self.label5.setFont(font)\r\n self.label5.setObjectName(\"label5\")\r\n self.line2 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.line2.setGeometry(QtCore.QRect(160, 60, 241, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n self.line2.setFont(font)\r\n self.line2.setObjectName(\"line2\")\r\n self.line3 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.line3.setGeometry(QtCore.QRect(160, 100, 241, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n self.line3.setFont(font)\r\n self.line3.setObjectName(\"line3\")\r\n self.line4 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.line4.setGeometry(QtCore.QRect(160, 140, 241, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n self.line4.setFont(font)\r\n self.line4.setObjectName(\"line4\")\r\n self.line5 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.line5.setGeometry(QtCore.QRect(160, 180, 241, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n self.line5.setFont(font)\r\n self.line5.setObjectName(\"line5\")\r\n self.line6 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.line6.setGeometry(QtCore.QRect(160, 220, 241, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n self.line6.setFont(font)\r\n self.line6.setObjectName(\"line6\")\r\n self.line7 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.line7.setGeometry(QtCore.QRect(160, 260, 241, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n self.line7.setFont(font)\r\n self.line7.setObjectName(\"line7\")\r\n self.line8 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.line8.setGeometry(QtCore.QRect(160, 300, 241, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n self.line8.setFont(font)\r\n self.line8.setObjectName(\"line8\")\r\n self.line9 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.line9.setGeometry(QtCore.QRect(160, 340, 241, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n self.line9.setFont(font)\r\n self.line9.setObjectName(\"line9\")\r\n self.line10 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.line10.setGeometry(QtCore.QRect(160, 380, 241, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n self.line10.setFont(font)\r\n self.line10.setObjectName(\"line10\")\r\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton.setGeometry(QtCore.QRect(220, 430, 75, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n self.pushButton.setFont(font)\r\n self.pushButton.setAutoDefault(False)\r\n self.pushButton.setDefault(True)\r\n self.pushButton.setObjectName(\"pushButton\")\r\n self.open = QtWidgets.QPushButton(self.centralwidget)\r\n self.open.setGeometry(QtCore.QRect(100, 430, 75, 23))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Gothic\")\r\n self.open.setFont(font)\r\n self.open.setAutoDefault(False)\r\n self.open.setDefault(True)\r\n self.open.setObjectName(\"open\")\r\n # MainWindow.setCentralWidget(self.centralwidget)\r\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\r\n self.statusbar.setObjectName(\"statusbar\")\r\n # MainWindow.setStatusBar(self.statusbar)\r\n\r\n self.retranslateUi(MainWindow)\r\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\r\n\r\n self.pushButton.clicked.connect(self.save)\r\n self.open.clicked.connect(self.read)\r\n\r\n def retranslateUi(self, MainWindow):\r\n _translate = QtCore.QCoreApplication.translate\r\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"DemooPlayer Txt Builder\"))\r\n self.label10.setText(_translate(\"MainWindow\", \"OFFSET\"))\r\n self.label9.setText(_translate(\"MainWindow\", \"PIANOVOLUME\"))\r\n self.label1.setText(_translate(\"MainWindow\", \"JSON\"))\r\n self.label8.setText(_translate(\"MainWindow\", \"AUDIOVOLUME\"))\r\n self.label2.setText(_translate(\"MainWindow\", \"AUDIO\"))\r\n self.line1.setText(_translate(\"MainWindow\", \"hard.json\"))\r\n self.label7.setText(_translate(\"MainWindow\", \"LEVEL\"))\r\n self.label6.setText(_translate(\"MainWindow\", \"DIFFICULTY\"))\r\n self.label4.setText(_translate(\"MainWindow\", \"TITLE\"))\r\n self.label3.setText(_translate(\"MainWindow\", \"COVER\"))\r\n self.label5.setText(_translate(\"MainWindow\", \"COMPOSER\"))\r\n self.line2.setText(_translate(\"MainWindow\", \"music.mp3\"))\r\n self.line3.setText(_translate(\"MainWindow\", \"cover.png\"))\r\n self.line6.setText(_translate(\"MainWindow\", \"2\"))\r\n self.line7.setText(_translate(\"MainWindow\", \"10\"))\r\n self.line8.setText(_translate(\"MainWindow\", \"100\"))\r\n self.line9.setText(_translate(\"MainWindow\", \"0\"))\r\n self.line10.setText(_translate(\"MainWindow\", \"0\"))\r\n self.pushButton.setText(_translate(\"MainWindow\", \"Save\"))\r\n self.open.setText(_translate(\"MainWindow\", \"Open\"))\r\n" }, { "alpha_fraction": 0.5616438388824463, "alphanum_fraction": 0.7123287916183472, "avg_line_length": 35.5, "blob_id": "c933f7b3d6e18167376584c8622de078b74fecdf", "content_id": "301d13d17d97cca7c654f054e1dfc2b695b28bef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 73, "license_type": "no_license", "max_line_length": 46, "num_lines": 2, "path": "/README.md", "repo_name": "Z-fly/DemooPlayer-Txt-Builder", "src_encoding": "UTF-8", "text": "# DemooPlayer Txt Builder\n![](https://s2.ax1x.com/2019/05/02/ENE2nK.jpg)\n" }, { "alpha_fraction": 0.3962756097316742, "alphanum_fraction": 0.4186219871044159, "avg_line_length": 39.953125, "blob_id": "f450c55f04d8fc79d0b8d0f6112dbea7b7167b78", "content_id": "f0b0561a3c328916bb76219d61945b311cd7b641", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2685, "license_type": "no_license", "max_line_length": 81, "num_lines": 64, "path": "/1.py", "repo_name": "Z-fly/DemooPlayer-Txt-Builder", "src_encoding": "UTF-8", "text": "import sys\r\n\r\nfrom PyQt5.QtWidgets import *\r\n\r\nfrom de import Ui_MainWindow\r\n\r\n\r\nclass mywindow(QWidget, Ui_MainWindow):\r\n def __init__(self):\r\n super(mywindow, self).__init__()\r\n self.setupUi(self)\r\n\r\n def save(self):\r\n fileName, ok = QFileDialog.getSaveFileName(self, \"Save\", \"./\", \"(*.txt)\")\r\n if fileName != \"\":\r\n txt = open(fileName, \"w\", encoding='shiftjis')\r\n txt.write(\"JSON \" + self.line1.text() + \"\\n\")\r\n txt.write(\"AUDIO \" + self.line2.text() + \"\\n\")\r\n txt.write(\"COVER \" + self.line3.text() + \"\\n\")\r\n txt.write(\"TITLE \" + self.line4.text() + \"\\n\")\r\n txt.write(\"COMPOSER \" + self.line5.text() + \"\\n\")\r\n txt.write(\"DIFFICULTY \" + self.line6.text() + \"\\n\")\r\n txt.write(\"LEVEL \" + self.line7.text() + \"\\n\")\r\n txt.write(\"AUDIOVOLUME \" + self.line8.text() + \"\\n\")\r\n txt.write(\"PIANOVOLUME \" + self.line9.text() + \"\\n\")\r\n txt.write(\"OFFSET \" + self.line10.text())\r\n txt.close()\r\n\r\n def read(self):\r\n fileName, ok = QFileDialog.getOpenFileName(self, \"Open\", './', \"(*.*)\")\r\n if fileName != \"\":\r\n with open(fileName, 'r') as f:\r\n for i in f.readlines():\r\n if i[:4] == \"Name\":\r\n self.line4.setText(i[5:-1])\r\n if i[:6] == \"Artist\":\r\n self.line5.setText(i[7:-1])\r\n if i[:4] == \"Extra\":\r\n self.line6.setText(\"3\")\r\n self.line7.setText(i[5:])\r\n if self.line7.text()[-1] == \"\\n\":\r\n self.line7.setText(self.line7.text()[:-1])\r\n if i[:4] == \"Hard\":\r\n self.line6.setText(\"2\")\r\n self.line7.setText(i[5:])\r\n if self.line7.text()[-1] == \"\\n\":\r\n self.line7.setText(self.line7.text()[:-1])\r\n if i[:4] == \"Normal\":\r\n self.line6.setText(\"1\")\r\n self.line7.setText(i[5:])\r\n if self.line7.text()[-1] == \"\\n\":\r\n self.line7.setText(self.line7.text()[:-1])\r\n if i[:4] == \"Easy\":\r\n self.line6.setText(\"0\")\r\n self.line7.setText(i[5:])\r\n if self.line7.text()[-1] == \"\\n\":\r\n self.line7.setText(self.line7.text()[:-1])\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app = QApplication(sys.argv)\r\n myshow = mywindow()\r\n myshow.show()\r\n sys.exit(app.exec_())\r\n" } ]
3
nicomn97/NicolasManrique_Ejercicio25
https://github.com/nicomn97/NicolasManrique_Ejercicio25
3fd3f690dd227d85ccd05940dc46d9ee7942a132
54e86a63159589ed7ac567ea8c216a46c57b8709
deb132d4120d96f892fc693281ff28f3bf39923d
refs/heads/master
2020-04-05T01:33:52.525744
2018-11-07T13:00:14
2018-11-07T13:00:14
156,440,879
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5839636921882629, "alphanum_fraction": 0.6096823215484619, "avg_line_length": 19.65625, "blob_id": "f7e03f2047d1e8e74a53c7bff944608f2e843bf4", "content_id": "8e47f017065b5c19c79b85bbea0c9d5d4d066261", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 661, "license_type": "no_license", "max_line_length": 60, "num_lines": 32, "path": "/sample.cpp", "repo_name": "nicomn97/NicolasManrique_Ejercicio25", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <cmath>\n#include <string>\n#include <random>\n\nvoid sGaus(int N, double mu, double sigma);\n\n\nint main(int argc, char* argv[]) {\n\n if (argc != 4) return -1;\n\n int N = atof(argv[1]);\n double mu = atof(argv[2]);\n double sigma = atof(argv[3]);\n\n //int N=200; double mu=100.0; double sigma=0.03;\n sGaus(N, mu, sigma);\n return 0;\n}\n\n\nvoid sGaus(int N, double mu, double sigma) {\n double distr[N];\n std::default_random_engine generator;\n std::normal_distribution <double> distribution(mu,sigma);\n for( int i = 0; i < N; i++ ) {\n distr[i]= distribution(generator);\n std::cout << distr[i] << std::endl;\n }\n\n}\n" }, { "alpha_fraction": 0.670769214630127, "alphanum_fraction": 0.7415384650230408, "avg_line_length": 20.66666603088379, "blob_id": "e9079e5cfee982bb6e75a50b67dd3b25481eaf93", "content_id": "4d821d0d328971ad6d28df749c128f8ae2c1f54e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 325, "license_type": "no_license", "max_line_length": 69, "num_lines": 15, "path": "/NicolasManrique_Ejercicio25.sh", "repo_name": "nicomn97/NicolasManrique_Ejercicio25", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n#PBS -l nodes=1:intel:ppn=1,mem=16gb\n#PBS -l walltime=4:00\n#PBS -M [email protected]\n#PBS -m abe\n#PBS -N nm97_Ej25\n#PBS -j oe\n#PBS -o nicomn97Out.txt\n\ngit clone https://github.com/nicomn97/NicolasManrique_Ejercicio25.git\ncd NicolasManrique_Ejercicio25/\nmodule load anaconda/python3\nmodule load gcc/4.9.4\nmake -f sample.mk\n" }, { "alpha_fraction": 0.6463414430618286, "alphanum_fraction": 0.7134146094322205, "avg_line_length": 15.399999618530273, "blob_id": "c171c85cddf7d38a829463fec02c5ed83ee6302f", "content_id": "98210217337de2d96fd2b07f44310011787de16a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 164, "license_type": "no_license", "max_line_length": 38, "num_lines": 10, "path": "/sample.mk", "repo_name": "nicomn97/NicolasManrique_Ejercicio25", "src_encoding": "UTF-8", "text": "#Make\n\nsample.pdf: sample.dat sample.py\n\tpython3 sample.py\n\nsample.dat: sample\n\t./sample 10000 10.0 2.5 >> sample.dat\n\nsample: sample.cpp\n\tg++ sample.cpp -o sample\n" }, { "alpha_fraction": 0.6425532102584839, "alphanum_fraction": 0.6829787492752075, "avg_line_length": 23.736841201782227, "blob_id": "abe65856f08dd51670748efc5eea91c45ef17c17", "content_id": "b5807dce69b4bf3e4a6074e3f7761533cc73ecb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 470, "license_type": "no_license", "max_line_length": 75, "num_lines": 19, "path": "/sample.py", "repo_name": "nicomn97/NicolasManrique_Ejercicio25", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\ndata=np.loadtxt(\"sample.dat\")\nmu=np.mean(data)\nsigma=np.std(data)\nx = np.linspace(np.min(data),np.max(data),1000)\nteo=(1.0/np.sqrt(2.0*np.pi*sigma**2)) * np.exp(-((x-mu)**2)/(2.0*sigma**2))\n\n\nplt.figure(figsize=(18,9))\n_=plt.hist(data, density=True, bins=250)\nplt.plot(x, teo)\nplt.xlim([np.min(data),np.max(data)])\nplt.xlabel('x')\nplt.ylabel('PDF(x)')\nplt.savefig(\"sample.pdf\")\n" } ]
4
JordanLeich/Login-System
https://github.com/JordanLeich/Login-System
17a38c4b492c9f56f140bf1b37157487bcbf0477
a739f47250a7925bd32eb96479e6948f16b45d24
a93f54f6844e55864aa1edb563c09981b295b563
refs/heads/master
2022-11-19T17:51:26.678517
2020-07-23T03:58:41
2020-07-23T03:58:41
280,949,627
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7936508059501648, "alphanum_fraction": 0.7952380776405334, "avg_line_length": 83, "blob_id": "fc837fe6b203f38bf0c736e893e799cf2d402ade", "content_id": "1f61993835ac48505dd7992db1518bcb180b20ea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1260, "license_type": "permissive", "max_line_length": 662, "num_lines": 15, "path": "/README.md", "repo_name": "JordanLeich/Login-System", "src_encoding": "UTF-8", "text": "# Description\nThis is a login system that allows the user to either create or access an existing account. One existing account that is built into the program by default has an email address of [email protected] and a password of admin1. I recommend using this existing account for quick and easy access, testing, or troubleshooting with my code. Once the user is successfully logged in, the user will have access to some helpful and useful programs such as a Math Calculator, Anti-Virus Program, and a Junk File Cleaner! These programs were previously created and are separately uploaded into repositories on my github account if you wish to access these programs indivindividually.\n\n# Instructions\n1. Simply download all files and read the requirements section down below. then, run the loginsystem.py\n2. If you do not have python installed, you can download and run the .exe installer file only and then run the exe file.\n\n# Requirements\n- colored - pip install colored\n\n# Important Notes\n- You do not need python to run this program! Read above for instructions section if you do not have python installed!\n- You can also visit the official site - https://jordanleich.github.io/Login-System/ for additional information!\n\n![Secure](images/login.jpg \"Secure Lock\")\n" }, { "alpha_fraction": 0.4820091128349304, "alphanum_fraction": 0.48714935779571533, "avg_line_length": 37.13218307495117, "blob_id": "e84f6c99d877cee748fa21c1dd096bff3a21f334", "content_id": "98b3bdd2fbe3a4d0bb4acbd3c56b6b1fa75580b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6809, "license_type": "permissive", "max_line_length": 120, "num_lines": 174, "path": "/loginsystem.py", "repo_name": "JordanLeich/Login-System", "src_encoding": "UTF-8", "text": "# Created by Jordan Leich on 7/19/2020\r\n\r\n# Imports\r\nfrom colored import fg, attr\r\nimport end\r\nimport restart\r\n\r\n# Global variables\r\ngreen = fg('green')\r\nred = fg('red')\r\nyellow = fg('yellow')\r\nreset = attr('reset')\r\nexisting_users1 = ['[email protected]', 'admin1']\r\n\r\n\r\ndef logged_in():\r\n print(green + 'Congrats, you have successfully logged in!\\n' + reset)\r\n\r\n user_choice2 = input(str('You have access to our Math Calculator, Anti-Virus Program, or Junk File Cleaner (calc, '\r\n 'antivirus, junk, or quit): '))\r\n print()\r\n\r\n if user_choice2.lower() == 'c' or user_choice2.lower() == 'calc' or user_choice2.lower() == 'calculator':\r\n from calculator import calculator\r\n calculator()\r\n\r\n elif user_choice2.lower() == 'a' or user_choice2.lower() == 'anti' or user_choice2.lower() == 'antivirus':\r\n import SecureAV\r\n\r\n elif user_choice2.lower() == 'j' or user_choice2.lower() == 'junk' or user_choice2.lower() == 'clean':\r\n import Cleaner\r\n Cleaner.start()\r\n\r\n elif user_choice2.lower() == 'q' or user_choice2.lower() == 'quit':\r\n end.end()\r\n\r\n else:\r\n print(red + 'User input error found! Restarting input...' + reset)\r\n logged_in()\r\n\r\n\r\ndef new_account():\r\n new_name = input(str('Please enter your first name: '))\r\n print()\r\n\r\n print('Hi there,', new_name + '!\\n')\r\n\r\n new_email = input(str('Please enter a valid email address to sign up with: '))\r\n print()\r\n\r\n if '@' not in new_email.lower():\r\n print(\r\n red + 'Error found... A valid email address must include an @ symbol! Restarting sign up page...\\n' + reset)\r\n new_account()\r\n\r\n elif '.com' not in new_email.lower():\r\n print(\r\n red + 'Error found... A valid email address must include a .com address to reach! Restarting sign up '\r\n 'page...\\n' + reset)\r\n new_account()\r\n\r\n print(yellow + 'All eligible passwords must be a total of 6 or more characters long!\\n' + reset)\r\n new_password = input(str('Please enter a new password to sign up with: '))\r\n print()\r\n\r\n if len(new_password) < 6:\r\n print(red + 'Your password is not 6 or more characters long! Restarting sign up page...\\n' + reset)\r\n new_account()\r\n\r\n confirm_password = input('Retype your new password for confirmation: ')\r\n print()\r\n\r\n if new_password == confirm_password and len(new_password) >= 6:\r\n print(yellow + 'Please keep note of your login information for future usage\\n' + reset)\r\n print('Your email address - ', green + new_email, reset, '\\n')\r\n print('Your password - ', green + confirm_password, reset, '\\n')\r\n\r\n logged_in()\r\n\r\n elif new_password != confirm_password:\r\n print(red + 'Your passwords do not match up correctly! Restarting sign up page...\\n' + reset)\r\n new_account()\r\n\r\n else:\r\n print(red + 'Error found! Restarting sign up page...\\n' + reset)\r\n new_account()\r\n\r\n\r\ndef start():\r\n print(green + 'Welcome to the login system!\\n' + reset)\r\n first_login = input(str('Are you an existing user (yes or no) '))\r\n print()\r\n\r\n if first_login.lower() == 'y' or first_login.lower() == 'yes':\r\n existing_email = input(str('Enter an existing email address: '))\r\n print()\r\n\r\n if existing_email not in existing_users1:\r\n invalid_email = input(red + 'The email address you provided does not exist!' + reset + ' Would you like to '\r\n 'create a new '\r\n 'account (yes or '\r\n 'no) ')\r\n print()\r\n\r\n if invalid_email.lower() == 'y' or invalid_email.lower() == 'yes':\r\n new_account()\r\n\r\n elif invalid_email.lower() == 'n' or invalid_email.lower() == 'no':\r\n restart.restart()\r\n\r\n else:\r\n print('Error found with user input...')\r\n restart.restart()\r\n\r\n existing_password = input('Enter an existing password for this account: ')\r\n print()\r\n\r\n if existing_email and existing_password in existing_users1:\r\n logged_in()\r\n\r\n elif existing_email not in existing_users1 and existing_password in existing_users1:\r\n invalid_email = input(red + 'The email address you provided does not exist!' + reset + ' Would you like to '\r\n 'create a new '\r\n 'account (yes or '\r\n 'no) ')\r\n print()\r\n\r\n if invalid_email.lower() == 'y' or invalid_email.lower() == 'yes':\r\n new_account()\r\n\r\n elif invalid_email.lower() == 'n' or invalid_email.lower() == 'no':\r\n restart.restart()\r\n\r\n else:\r\n print('Error found with user input...')\r\n restart.restart()\r\n\r\n elif existing_password not in existing_users1:\r\n invalid_password = input(red + 'The password you provided does not exist!' + reset + ' Would you like to '\r\n 'create a new '\r\n 'account (yes or '\r\n 'no) ')\r\n print()\r\n\r\n if invalid_password.lower() == 'y' or invalid_password.lower() == 'yes':\r\n new_account()\r\n\r\n elif invalid_password.lower() == 'n' or invalid_password.lower() == 'no':\r\n restart.restart()\r\n\r\n else:\r\n print('Error found with user input...')\r\n restart.restart()\r\n\r\n elif first_login.lower() == 'n' or first_login.lower() == 'no':\r\n user_choice1 = input(str('Would you like to create a new account (yes or no): '))\r\n print()\r\n\r\n if user_choice1.lower() == 'y' or user_choice1.lower() == 'yes':\r\n new_account()\r\n\r\n elif user_choice1.lower() == 'n' or user_choice1.lower() == 'no':\r\n end.end()\r\n\r\n else:\r\n print(red + 'User input error found!\\n' + reset)\r\n restart.restart()\r\n\r\n else:\r\n print(red + 'User input error found!\\n' + reset)\r\n restart.restart()\r\n\r\n\r\nstart()\r\n" }, { "alpha_fraction": 0.5785470604896545, "alphanum_fraction": 0.5877261757850647, "avg_line_length": 30.58974266052246, "blob_id": "b0ac5802a364ea438ebeb7216c24865c4a39bc14", "content_id": "ad1639311811d17f465a76792845759a48b6b9c5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3813, "license_type": "permissive", "max_line_length": 114, "num_lines": 117, "path": "/Cleaner.py", "repo_name": "JordanLeich/Login-System", "src_encoding": "UTF-8", "text": "# Made by Jordan Leich on 6/14/2020, Last updated on 7/22/2020 IMPORTANT NOTE TO READ*** This cleaner script will\r\n# work best if you are an administrator on your PC. Without being an administrator, the script will only partially\r\n# clean junk files and will eventually hit an error that will end the script.\r\n\r\n# All imports used\r\nimport os\r\nimport shutil\r\nimport time as ti\r\nfrom colored import fg, attr\r\n\r\n# Extra global Variables used\r\ngreen = fg('green')\r\nred = fg('red')\r\nreset_color = attr('reset')\r\n\r\n\r\n# End of the program when the cleaner finishes cleaning junk files\r\ndef end():\r\n print(green + 'Cleaning Successful!\\n', reset_color)\r\n ti.sleep(1)\r\n quit()\r\n\r\n\r\n# Second folder to clean (May require administrator)\r\ndef second():\r\n folder = 'C:\\Windows\\Temp'\r\n ti.sleep(1)\r\n list = os.listdir(folder)\r\n number_files = len(list)\r\n print(red+'Junk files/folders found in the first folder: ', number_files, reset_color, '\\n')\r\n ti.sleep(2)\r\n\r\n for filename in os.listdir(folder):\r\n file_path = os.path.join(folder, filename)\r\n print(green + \"Deleted \" + filename, '\\n', reset_color)\r\n try:\r\n if os.path.isfile(file_path) or os.path.islink(file_path):\r\n os.unlink(file_path)\r\n elif os.path.isdir(file_path):\r\n shutil.rmtree(file_path)\r\n except Exception as e:\r\n print(red + 'Failed to delete %s. Reason: %s' % (file_path, e), '\\n', reset_color)\r\n ti.sleep(1)\r\n third()\r\n\r\n\r\n# Third folder to clean (Does require administrator)\r\ndef third():\r\n second_folder = 'C:\\Windows\\Prefetch'\r\n ti.sleep(1)\r\n list = os.listdir(second_folder)\r\n number_files = len(list)\r\n print(red+'Junk files/folders found in the second folder: ', number_files, reset_color, '\\n')\r\n ti.sleep(2)\r\n\r\n for filename in os.listdir(second_folder):\r\n file_path = os.path.join(second_folder, filename)\r\n print(green + \"Deleted \" + filename, '\\n', reset_color)\r\n try:\r\n if os.path.isfile(file_path) or os.path.islink(file_path):\r\n os.unlink(file_path)\r\n elif os.path.isdir(file_path):\r\n shutil.rmtree(file_path)\r\n except Exception as e:\r\n print(red + 'Failed to delete %s. Reason: %s' % (file_path, e), '\\n', reset_color)\r\n ti.sleep(1)\r\n end()\r\n\r\n\r\n# Opens a cleaning program that is pre-installed with windows (Doesn't require administrator)\r\ndef first():\r\n clean = os.popen('cleanmgr.exe /sagerun:1').read()\r\n print(clean)\r\n ti.sleep(1)\r\n second()\r\n\r\n\r\n# Basic Clean - Opens a cleaning program that is pre-installed with windows (Doesn't require administrator)\r\ndef basic_clean():\r\n clean = os.popen('cleanmgr.exe /sagerun:1').read()\r\n print(clean)\r\n ti.sleep(1)\r\n end()\r\n\r\n\r\n# Beginning of the program\r\ndef start():\r\n try:\r\n user_choice2 = str(input('Basic clean, Advanced clean, or quit (basic, advanced, or quit): '))\r\n print()\r\n\r\n if user_choice2.lower() == 'basic' or user_choice2.lower() == 'b':\r\n print('Basic clean running...', reset_color)\r\n basic_clean()\r\n\r\n elif user_choice2.lower() == 'advanced' or user_choice2.lower() == 'a':\r\n print('Advanced clean running...', reset_color)\r\n first()\r\n\r\n elif user_choice2.lower() == 'quit' or user_choice2.lower() == 'q':\r\n print('Ending cleaner...')\r\n ti.sleep(1)\r\n quit()\r\n\r\n else:\r\n print(red + \"Invalid input... Restart input...\\n\", reset_color)\r\n ti.sleep(1)\r\n start()\r\n\r\n except Exception as e:\r\n print(red, e, '\\n', reset_color)\r\n ti.sleep(3)\r\n quit()\r\n\r\n\r\n# Starts the first section of the program\r\nstart()\r\n" }, { "alpha_fraction": 0.512175977230072, "alphanum_fraction": 0.5299816727638245, "avg_line_length": 32.71818161010742, "blob_id": "34c559cee3c92dedac9914ddc8c318d7aec4178f", "content_id": "9a431190ea6c7a2b04e4a5a657dd1c066f068405", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3819, "license_type": "permissive", "max_line_length": 102, "num_lines": 110, "path": "/SecureAV.py", "repo_name": "JordanLeich/Login-System", "src_encoding": "UTF-8", "text": "# Created by Gourav Ranjan Dutta. Updated by Jordan Leich on 7/13/2020\r\n# REQUIREMENTS - requests (pip install requests) and colored (pip install colored)\r\n\r\n# Imports\r\nimport hashlib\r\nimport os\r\nimport time\r\nimport requests\r\nfrom colored import fg, attr\r\n\r\n# Colors used\r\ngood_color = fg('green')\r\nbad_color = fg('red')\r\nreset = attr('reset')\r\n\r\nfile_list = list()\r\nroot_dir = input(\"Enter the directory location where you want to search for viruses: \")\r\nprint()\r\n\r\n\r\ndef scan():\r\n for i in range(5):\r\n print(\". \")\r\n time.sleep(0.500)\r\n\r\n infected_list = []\r\n for f in file_list:\r\n vdef = open(\"viruses.txt\", \"r\")\r\n file_not_read = False\r\n print(good_color + \"\\n scanning... : {}\".format(f), reset)\r\n hs = hashlib.sha256()\r\n try:\r\n with open(f, \"rb\") as file:\r\n try:\r\n buf = file.read()\r\n file_not_read = True\r\n hs.update(buf)\r\n file_hashed = format(hs.hexdigest())\r\n print(good_color + \"File scanned successfully :{}\".format(file_hashed), reset)\r\n apikey = \"9d38604e105e8682bdb7b4d4f30fdfa19ad3df7f32a15146122ec21f32e7e0ec\"\r\n\r\n url = 'https://www.virustotal.com/vtapi/v2/file/report'\r\n\r\n params = {'apikey': apikey, 'resource': file_hashed}\r\n\r\n response = requests.get(url, params=params)\r\n # print(response.json())\r\n res_json = response.json()\r\n\r\n if res_json['positives'] >= 5:\r\n print()\r\n print(bad_color + \"Malware Detected --> file name: {}\".format(f), '\\n', reset)\r\n infected_list.append(f)\r\n except Exception as e:\r\n print(bad_color + \" Oops!! Could not read the file: {}\".format(e), reset)\r\n except:\r\n pass\r\n if len(infected_list) == 0:\r\n print()\r\n print(good_color + \"Your folder is clear...\\n\", reset)\r\n from loginsystem import logged_in\r\n\r\n else:\r\n print(bad_color + \"Infected files found : {}\".format(infected_list))\r\n de = str(input(\"Would you like to delete the infected files (yes or no) \"))\r\n print()\r\n if de.lower() == 'yes' or de.lower() == 'y':\r\n for infected in infected_list:\r\n os.remove(infected)\r\n print(good_color + \"file removed : {}\".format(infected))\r\n print()\r\n print(good_color + \"Your folder is now clean!\\n\", reset)\r\n time.sleep(1)\r\n print(good_color + \"Thank you for using this Antivirus!\\n\", reset)\r\n time.sleep(1)\r\n from loginsystem import logged_in\r\n else:\r\n print(good_color + \"Thank you for using this Antivirus!\\n\", reset)\r\n time.sleep(1)\r\n from loginsystem import logged_in\r\n\r\n\r\nprint(good_color + \"Starting Scan\", end=\"\")\r\nfor i in range(5):\r\n print(\".\", end=\"\")\r\n time.sleep(0.500)\r\nprint()\r\nfor subdir, dirs, files in os.walk(root_dir):\r\n for file in files:\r\n # file_path=subdir + os.sep+file\r\n file_path = os.path.join(subdir, file)\r\n print(file_path)\r\n if file_path.endswith(\".exe\") or file_path.endswith(\".dll\") or file_path.endswith(\".com\") \\\r\n or file_path.endswith(\".zip\"):\r\n file_list.append(file_path)\r\n\r\nif len(file_list) == 0:\r\n print()\r\n print(good_color + \"Your folder is clean!\\n\", reset)\r\n time.sleep(1)\r\n from loginsystem import logged_in\r\n logged_in()\r\n\r\nelse:\r\n print()\r\n print(bad_color + \"We found some files that could be a virus!\\n\")\r\n time.sleep(2)\r\n print(good_color + \"Starting file scan...\")\r\n time.sleep(2)\r\n scan()\r\n" }, { "alpha_fraction": 0.5726271867752075, "alphanum_fraction": 0.5762978792190552, "avg_line_length": 25.859155654907227, "blob_id": "d28513c83cbd70d82575b26bbfe235b1214cd9ed", "content_id": "e5b873ebcb1aff814ebca30ba126b890a90bf6c0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1907, "license_type": "permissive", "max_line_length": 116, "num_lines": 71, "path": "/calculator.py", "repo_name": "JordanLeich/Login-System", "src_encoding": "UTF-8", "text": "# Code created by Jordan Leich on 6/11/2020, email me at [email protected] if you wish to code together!\n\n# Imports\nimport end\nfrom colored import fg, attr\n\n# Global Variables\ngreen = fg('green')\nred = fg('red')\nreset = attr('reset')\n\n\ndef restart():\n user_restart = input(str('Do you wish to use the calculator again (yes or no) '))\n print()\n\n if user_restart.lower() == 'y' or user_restart.lower() == 'yes':\n calculator()\n\n elif user_restart.lower() == 'n' or user_restart.lower() == 'no':\n program_choice = input(str('Would you like to use another program from the login system page (yes or no) '))\n print()\n\n if program_choice.lower() == 'y' or program_choice.lower() == 'yes':\n from loginsystem import logged_in\n logged_in()\n\n elif program_choice.lower() == 'n' or program_choice.lower() == 'no':\n end.end()\n\n else:\n print(red + 'User input error found! restarting user choice...\\n' + reset)\n restart()\n\n else:\n print(red + 'User input error found! restarting user choice...\\n' + reset)\n restart()\n\n\ndef calculator():\n first_number = int(input(\"Enter first number: \"))\n print()\n\n operator = input(str(\"Enter an operation (+ | - | * | /): \"))\n print()\n\n second_number = int(input(\"Enter second number: \"))\n print()\n\n if operator == '+':\n print(green, first_number + second_number, reset, '\\n')\n restart()\n\n elif operator == '-':\n print(green, first_number - second_number, reset, '\\n')\n restart()\n\n elif operator == '*':\n print(green, first_number * int(second_number), reset, '\\n')\n restart()\n\n elif operator == '/':\n print(green, first_number / second_number, reset, '\\n')\n restart()\n\n else:\n print(red, 'Unknown Operator! Restarting Calculator...\\n', reset)\n calculator()\n\n\ncalculator()\n" } ]
5
Bohdan-Anderson/Story
https://github.com/Bohdan-Anderson/Story
fceee4f187dfc11bab21e997ebcd023f0ff763e2
0622a8b89e3151d1d0550a4e3ee567bd6e31b91d
2612e601e8211bfc13272706e9eb46ab20ab57ee
refs/heads/master
2016-09-06T09:02:32.587664
2012-11-12T20:22:29
2012-11-12T20:23:37
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6333938241004944, "alphanum_fraction": 0.6348457336425781, "avg_line_length": 25.24761962890625, "blob_id": "2046136870923ec6a032fc3c3e3f6c7f8ca24f2f", "content_id": "a607f57f19bc8e13904e87fd15b6c76034bc0d8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2755, "license_type": "no_license", "max_line_length": 114, "num_lines": 105, "path": "/story/views.py", "repo_name": "Bohdan-Anderson/Story", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse, HttpResponseRedirect\nfrom settings import SITE_ROOT\\\n\nfrom django.utils import simplejson\nimport json, datetime\n\nfrom django import forms\n\nfrom django.template import Context\nfrom django.template.loader import get_template\nfrom django.shortcuts import render_to_response\nfrom django.utils import simplejson\n\nfrom django.core.files import File\n\nfrom django.core.context_processors import csrf\n\n\n###################################\n#Game play\n###################################\ndef loadData():\n\tjd = open(SITE_ROOT + '\\..\\data\\data.json')\n\tjjd = simplejson.load(jd)\n\n\treturn jjd\n\ndef playGame(request):\n\t##reciving end of jquery ajax\n\tif request.method == 'GET':\n\t\tGET = request.GET\n\t\tif GET.has_key(u'data'):\n\t\t\tmyFile = open(SITE_ROOT + '\\..\\data\\writtingData.txt', 'a')\t\n\n\t\t\tdata = GET[u'data']\n\t\t\tscene = GET[u'scene']\n\t\t\ttime = datetime.datetime.now().strftime(\"{'year':%Y, 'month':%m,'day':%d, 'hour':%H, 'miute':%M, 'second':%S}\")\n\n\t\t\tmyFile.write( data + \" \" + scene + \" \" + time + \" \\n\")\t\n\t\t\tmyFile.close()\n\n\tjd = open(SITE_ROOT + '\\..\\data\\data.json')\n\tjjd = simplejson.load(jd)\n\n\treturn render_to_response('story.html',{'data':jjd })#,'csrf_token': c})\n\n\n###################################\n#Creating game options\n###################################\nfrom stories.models import Story\n\ndef viewUsersStories(request):\n\tif request.user.is_authenticated():\n\t\tprint request.user\n\n\t\tstories = Story.objects.filter(creator=request.user)\n\t\ttitle = \"%s's Stories\" % request.user\n\t\tbody = \"\"\n\t\tlength = len(stories)\n\t\tif length == 0:\n\t\t\tbody = \"no Stories\"\n\t\telse:\n\t\t\tfor i in range(len(stories)):\n\t\t\t\tbody += stories[i].name\t\n\n\n\t\treturn render_to_response(\"base.html\", {'title':title, 'body': body })\n\telse:\n\t\treturn HttpResponseRedirect('/login/')\n\n\n\ndef createStory(request):\n\tif request.user.is_authenticated():\n\t\tc = {'title':\"Create Story\"}\n\t\tc.update(csrf(request))\n\n\t\tif request.method == \"POST\":\n\t\t\tPOST = request.POST\n\t\t\tname = POST[u'storyName']\n\t\t\tnewStory = Story(name = name , creator = request.user)\n\t\t\tnewStory.save()\t\n\t\t\treturn HttpResponseRedirect(\"/objectView/\")\n\t\treturn render_to_response(\"createStory.html\", c)\n\telse:\n\t\treturn HttpResponseRedirect('/login/')\n\n###################################\n#editing the data possibly\n###################################\n\nclass ContactForm(forms.Form):\n title = forms.CharField()\n intro = forms.CharField()\n conclusion = forms.CharField()\n\ndef editData(request):\n\tjson_data = loadData()\n\tmyFormList = []\n\tfor a in range(len(json_data)):\n\t\tmyForm = ContactForm({'title':json_data[a][1], 'intro':json_data[a][2], 'conclusion':json_data[a][4]})\n\t\tmyFormList.append(myForm)\n\t#print SITE_ROOT\n\treturn render_to_response('table.html', {'data':myFormList})" }, { "alpha_fraction": 0.6762589812278748, "alphanum_fraction": 0.6762589812278748, "avg_line_length": 29.40625, "blob_id": "8ed7dfa8816ac467f36ef07d2087e310df6d1ff9", "content_id": "e5044e5914a89331591c4cd4833b4f0f536f9d75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 973, "license_type": "no_license", "max_line_length": 74, "num_lines": 32, "path": "/story/urls.py", "repo_name": "Bohdan-Anderson/Story", "src_encoding": "UTF-8", "text": "from django.conf.urls import patterns, include, url\nfrom story.views import editData, playGame, viewUsersStories, createStory\n\nfrom django.contrib.auth.views import login, logout\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n\t#(r'^admin/$', include(admin.site.urls)),\n\t(r'^editData/$', editData),\n (r'^playGame/$', playGame),\n (r'^objectView/$', viewUsersStories),\n (r'^createStory/$',createStory),\n (r'^login/$', login),\n (r'^logout/$', logout),\n\n # Examples:\n # url(r'^$', 'story.views.home', name='home'),\n # url(r'^story/', include('story.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n)\n" }, { "alpha_fraction": 0.7220216393470764, "alphanum_fraction": 0.7328519821166992, "avg_line_length": 22, "blob_id": "bdc913c3198ca589be3ef0455e123539725d864e", "content_id": "efb61dd42007e4d56b16df12cf63b7301ef80359", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 277, "license_type": "no_license", "max_line_length": 43, "num_lines": 12, "path": "/stories/models.py", "repo_name": "Bohdan-Anderson/Story", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\n\nfrom story.settings import SITE_ROOT\\\n\nclass Story(models.Model):\n\tcreator = models.ForeignKey(User)\t\n \tname = models.CharField(max_length=100)\n \tdata = \"\"\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n" }, { "alpha_fraction": 0.7075664401054382, "alphanum_fraction": 0.7137014269828796, "avg_line_length": 39.83333206176758, "blob_id": "806f80b92e777b035707af96db1e754c4e39f2fd", "content_id": "8087f3b7830a96a7e9bbe7707dcfb62759711b10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 489, "license_type": "no_license", "max_line_length": 100, "num_lines": 12, "path": "/README.md", "repo_name": "Bohdan-Anderson/Story", "src_encoding": "UTF-8", "text": "<h1>TEXT BASED ADVENTURE GAME!!!</h1>\nAS of right now, I've got the game loading in the data dynamically. <br>\nNext step is to be able to edit the data.<br>\nThen included creators so they can have their own games.<br>\nBe able to record what the players of the game write<br>\nThen fix up the Game it self a bit<br>\n <ul>\n <li>as in make everything lower case once typed in</li>\n </ul>\n\n\nI have to thank <a href=\"https://github.com/and0\">Andrei</a> a shit load for what he's showing me..." } ]
4
reymond-group/lore
https://github.com/reymond-group/lore
6881fc4eed6a1ffc480706477cd01bac8a00c674
3c9e6e94f49354596d946c57366c2fb9cd0859d7
7e593631b7ccef47744d9bc7094ad738af60b1e3
refs/heads/master
2022-12-13T01:17:52.736709
2022-05-26T09:20:18
2022-05-26T09:20:18
74,750,527
27
4
MIT
2016-11-25T10:50:55
2022-10-03T14:45:59
2022-11-13T11:49:17
JavaScript
[ { "alpha_fraction": 0.6496253609657288, "alphanum_fraction": 0.6632878184318542, "avg_line_length": 20.018518447875977, "blob_id": "482441493aa21c0e9e284353a03ba4861a7751bb", "content_id": "862915ebbd96312c18ca13f0b339af124d14a94b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2269, "license_type": "permissive", "max_line_length": 77, "num_lines": 108, "path": "/app.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\n// Detect SSR (server side rendering)\nvar canUseDOM = !!(\n (typeof window !== 'undefined' &&\n window.document && window.document.createElement)\n);\n\nvar Lore = require('./src/Lore');\n\n// By Shmiddty from stackoverflow\nfunction Enum(a) {\n let i = Object\n .keys(a)\n .reduce((o, k) => (o[a[k]] = k, o), {});\n\n return Object.freeze(\n Object.keys(a).reduce((o, k) => (o[k] = a[k], o), v => i[v])\n );\n}\n\nLore.Mouse = Enum({\n Left: 0,\n Middle: 1,\n Right: 2\n});\n\nLore.Keyboard = Enum({\n Backspace: 8,\n Tab: 9,\n Enter: 13,\n Shift: 16,\n Ctrl: 17,\n Alt: 18,\n Esc: 27\n});\n\nLore.init = function (canvas, options) {\n this.opts = Lore.Utils.extend(true, Lore.defaults, options);\n\n // Lore.getGrakaInfo(canvas);\n\n var cc = Lore.Core.Color.fromHex(this.opts.clearColor);\n\n if (!(canvas instanceof Element)) {\n canvas = document.getElementById(canvas);\n }\n\n var renderer = new Lore.Core.Renderer(canvas, {\n clearColor: cc,\n verbose: true,\n fps: document.getElementById('fps'),\n center: new Lore.Math.Vector3f(125, 125, 125),\n antialiasing: this.opts.antialiasing,\n alphaBlending: this.opts.alphaBlending,\n preserveDrawingBuffer: this.opts.preserveDrawingBuffer\n });\n\n renderer.controls.limitRotationToHorizon(this.opts.limitRotationToHorizon);\n\n renderer.render = function (camera, geometries) {\n for (var key in geometries) {\n geometries[key].draw(renderer);\n }\n }\n\n return renderer;\n}\n\nLore.getGrakaInfo = function (targetId) {\n let canvas = document.getElementById(targetId);\n let gl = canvas.getContext('webgl') ||\n canvas.getContext('experimental-webgl');\n\n let info = {\n renderer: '',\n vendor: ''\n };\n\n let dbgRenderInfo = gl.getExtension('WEBGL_debug_renderer_info');\n\n if (dbgRenderInfo != null) {\n info.renderer = gl.getParameter(dbgRenderInfo.UNMASKED_RENDERER_WEBGL);\n info.vendor = gl.getParameter(dbgRenderInfo.UNMASKED_VENDOR_WEBGL);\n }\n\n return info;\n}\n\nLore.supportsHighQuality = function (targetId) {\n let info = Lore.getGrakaInfo(targetId);\n\n\n return false;\n}\n\nLore.defaults = {\n clearColor: '#121212',\n limitRotationToHorizon: false,\n antialiasing: false,\n preserveDrawingBuffer: false\n};\n\nif (canUseDOM) {\n window['Lore'] = Lore\n}\n\nmodule.exports = Lore" }, { "alpha_fraction": 0.5601404905319214, "alphanum_fraction": 0.5856013894081116, "avg_line_length": 26.14285659790039, "blob_id": "00d2855d6815ceba749c1cd8d1351b4c4b6a5902", "content_id": "e822a616d4f3b0f5a7edc8352efca9628439e6ac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1139, "license_type": "permissive", "max_line_length": 188, "num_lines": 42, "path": "/src/Math/Matrix3f.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\n\n\n/** A class representing a 3x3 float matrix */\nclass Matrix3f {\n /**\n * The constructor for the class Matrix3f.\n *\n * @param {Float32Array} [entries=new Float32Array()] The Float32Array to which the entries will be set. If no value is provided, the matrix will be initialized to the identity matrix.\n */\n constructor(entries = new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1])) {\n this.entries = entries;\n }\n\n /**\n * Clones the matrix and returns the clone as a new Matrix3f object.\n *\n * @returns {Matrix3f} The clone.\n */\n clone() {\n return new Matrix3f(new Float32Array(this.entries));\n }\n\n /**\n * Compares this matrix to another matrix.\n *\n * @param {Matrix3f} mat A matrix to be compared to this matrix.\n * @returns {boolean} A boolean indicating whether or not the two matrices are identical.\n */\n equals(mat) {\n for (let i = 0; i < this.entries.length; i++) {\n if (this.entries[i] !== mat.entries[i]) {\n return false;\n }\n }\n\n return true;\n }\n}\n\nmodule.exports = Matrix3f" }, { "alpha_fraction": 0.439314603805542, "alphanum_fraction": 0.4911946654319763, "avg_line_length": 41.02000045776367, "blob_id": "1f2715d97b4ef4c8f0f8a59acb1235d6a712a399", "content_id": "a841ae9fe001179e4662d881cf069f706425a445", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2101, "license_type": "permissive", "max_line_length": 123, "num_lines": 50, "path": "/src/Shaders/SmoothCircle.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "const Shader = require('../Core/Shader')\nconst Uniform = require('../Core/Uniform')\n\nmodule.exports = new Shader('smoothCircle', 2, { size: new Uniform('size', 5.0, 'float'),\n cutoff: new Uniform('cutoff', 0.0, 'float'),\n clearColor: new Uniform('clearColor', [0.0, 0.0, 0.0, 1.0], 'float_vec4'),\n fogDensity: new Uniform('fogDensity', 6.0, 'float') }, [\n 'uniform float size;',\n 'uniform float cutoff;',\n 'in vec3 position;',\n 'in vec3 color;',\n 'out vec3 vColor;',\n 'out float vDiscard;',\n 'vec3 floatToRgb(float n) {',\n 'float b = floor(n / 65536.0);',\n 'float g = floor((n - b * 65536.0) / 256.0);',\n 'float r = floor(n - b * 65536.0 - g * 256.0);',\n 'return vec3(r / 255.0, g / 255.0, b / 255.0);',\n '}',\n 'void main() {',\n 'float point_size = color.b;',\n 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',\n 'vec4 mv_pos = modelViewMatrix * vec4(position, 1.0);',\n 'vDiscard = 0.0;',\n 'if(-mv_pos.z < cutoff || point_size <= 0.0 || mv_pos.z > 0.0) {',\n 'vDiscard = 1.0;',\n 'return;',\n '}',\n 'gl_PointSize = point_size * size;',\n 'vColor = floatToRgb(color.r);',\n '}'\n], [\n 'uniform vec4 clearColor;',\n 'uniform float fogDensity;',\n 'in vec3 vColor;',\n 'in float vDiscard;',\n 'out vec4 fragColor;',\n 'void main() {',\n 'if(vDiscard > 0.5) discard;',\n 'float dist = distance(gl_PointCoord, vec2(0.5)) * 1.25;',\n 'float delta = fwidth(dist);',\n 'float a = 1.0 - smoothstep(0.5 - delta, 0.5 + delta, dist);',\n 'fragColor = vec4(vColor, a);',\n 'if (fogDensity > 0.0) {',\n 'float z = gl_FragCoord.z / gl_FragCoord.w;',\n 'float fog_factor = clamp(exp2(-fogDensity * fogDensity * z * z * 1.442695), 0.025, 1.0);',\n 'fragColor = mix(vec4(clearColor.rgb, a), fragColor, fog_factor);',\n '}',\n '}'\n]);\n" }, { "alpha_fraction": 0.7120689749717712, "alphanum_fraction": 0.7120689749717712, "avg_line_length": 24.2608699798584, "blob_id": "aad6e0addec79dbabcc07f47c5afcd8a7ab7e014", "content_id": "d6e514f3efc9f29e94a8ffb557c2911b859a82d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 580, "license_type": "permissive", "max_line_length": 51, "num_lines": 23, "path": "/src/Shaders/index.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "var circle = require('./Circle');\nvar coordinates = require('./Coordinates');\nvar defaultSquare = require('./Default');\nvar defaultAnimated = require('./DefaultAnimated');\nvar defaultEffect = require('./DefaultEffect');\nvar simpleSphere = require('./SimpleSphere');\nvar smoothCircle = require('./SmoothCircle');\nvar sphere = require('./Sphere');\nvar tree = require('./Tree');\nvar fxaaEffect = require('./FXAAEffect');\n\nmodule.exports = {\n circle,\n coordinates,\n defaultSquare,\n defaultAnimated,\n defaultEffect,\n simpleSphere,\n smoothCircle,\n sphere,\n tree,\n fxaaEffect\n}" }, { "alpha_fraction": 0.6998124122619629, "alphanum_fraction": 0.7166979312896729, "avg_line_length": 24.428571701049805, "blob_id": "b858ba59884be4e698855128ae2e7b62dc927fda", "content_id": "f6ed02879707888db6bec4eb86d53ac9c540ad24", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 533, "license_type": "permissive", "max_line_length": 55, "num_lines": 21, "path": "/src/Math/index.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "const Matrix3f = require('./Matrix3f');\nconst Matrix4f = require('./Matrix4f');\nconst ProjectionMatrix = require('./ProjectionMatrix');\nconst Quaternion = require('./Quaternion');\nconst RadixSort = require('./RadixSort');\nconst Ray = require('./Ray');\nconst SphericalCoords = require('./SphericalCoords');\nconst Statistics = require('./Statistics');\nconst Vector3f = require('./Vector3f');\n\nmodule.exports = {\n Matrix3f,\n Matrix4f,\n ProjectionMatrix,\n Quaternion,\n RadixSort,\n Ray,\n SphericalCoords,\n Statistics,\n Vector3f\n}" }, { "alpha_fraction": 0.5810762047767639, "alphanum_fraction": 0.5892018675804138, "avg_line_length": 32.569698333740234, "blob_id": "3579e14038dee3060135d113bfd522f4fca75fdb", "content_id": "c8c8b7d8d8c7f731aa99c83626dd858deeb3c76d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5538, "license_type": "permissive", "max_line_length": 129, "num_lines": 165, "path": "/src/Core/Shader.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst Uniform = require('./Uniform');\nconst Matrix4f = require('../Math/Matrix4f');\n\n/**\n * A class representing a shader.\n * \n * @property {String} name The name of the shader.\n * @property {Object} uniforms A map mapping uniform names to Lore Uniform instances.\n * \n */\nclass Shader {\n constructor(name, glVersion, uniforms, vertexShader, fragmentShader, fallback = 'circle') {\n this.name = name;\n this.uniforms = uniforms || {};\n this.vertexShader = vertexShader || [];\n this.fragmentShader = fragmentShader || [];\n this.glVersion = glVersion;\n this.fallback = fallback;\n this.gl = null;\n this.program = null;\n this.initialized = false;\n this.lastTime = new Date().getTime();\n \n // Add the two default shaders (the same shaders as in getVertexShader)\n this.uniforms['modelViewMatrix'] = new Uniform('modelViewMatrix',\n (new Matrix4f()).entries, 'float_mat4');\n\n this.uniforms['projectionMatrix'] = new Uniform('projectionMatrix',\n (new Matrix4f()).entries, 'float_mat4');\n }\n \n clone() {\n let uniforms = {};\n\n for (let key in this.uniforms) {\n uniforms[key] = this.uniforms[key].clone();\n }\n\n return new Shader(this.name, this.glVersion, uniforms, this.vertexShader, this.fragmentShader);\n }\n\n getVertexShaderCode() {\n return this.vertexShader.join('\\n');\n }\n\n getFragmentShaderCode() {\n return this.fragmentShader.join('\\n');\n }\n\n getVertexShader(gl, isWebGL2 = false) {\n let shader = gl.createShader(gl.VERTEX_SHADER);\n let vertexShaderCode = '';\n\n if (!isWebGL2 && this.glVersion === 2) {\n throw('The shader expects WebGL 2.0');\n } else if (this.glVersion === 2) {\n vertexShaderCode += '#version 300 es\\n';\n }\n\n vertexShaderCode += 'uniform mat4 modelViewMatrix;\\n' +\n 'uniform mat4 projectionMatrix;\\n\\n' +\n this.getVertexShaderCode();\n \n gl.shaderSource(shader, vertexShaderCode);\n gl.compileShader(shader);\n\n Shader.showCompilationInfo(gl, shader, this.name, 'Vertex Shader');\n return shader;\n }\n\n getFragmentShader(gl, isWebGL2 = false) {\n let shader = gl.createShader(gl.FRAGMENT_SHADER);\n\n let fragmentShaderCode = '';\n\n if (!isWebGL2 && this.glVersion === 2) {\n throw('The shader expects WebGL 2.0');\n } else if (this.glVersion === 2) {\n fragmentShaderCode += '#version 300 es\\n';\n }\n\n // Adding precision, see:\n // http://stackoverflow.com/questions/27058064/why-do-i-need-to-define-a-precision-value-in-webgl-shaders\n // and:\n // http://stackoverflow.com/questions/13780609/what-does-precision-mediump-float-mean\n fragmentShaderCode += '#ifdef GL_OES_standard_derivatives\\n#extension GL_OES_standard_derivatives : enable\\n#endif\\n\\n' +\n '#ifdef GL_ES\\nprecision highp float;\\n#endif\\n\\n' +\n this.getFragmentShaderCode();\n\n gl.shaderSource(shader, fragmentShaderCode);\n gl.compileShader(shader);\n\n Shader.showCompilationInfo(gl, shader, this.name, 'Fragment Shader');\n return shader;\n }\n\n init(gl, isWebGL2 = false) {\n this.gl = gl;\n this.program = this.gl.createProgram();\n let vertexShader = this.getVertexShader(this.gl, isWebGL2);\n let fragmentShader = this.getFragmentShader(this.gl, isWebGL2);\n\n if (!vertexShader || !fragmentShader) {\n console.error('Failed to create the fragment or the vertex shader.');\n return null;\n }\n\n this.gl.attachShader(this.program, vertexShader);\n this.gl.attachShader(this.program, fragmentShader);\n\n this.gl.linkProgram(this.program);\n\n if (!this.gl.getProgramParameter(this.program, this.gl.LINK_STATUS)) {\n console.error('Could not link program.\\n' +\n 'VALIDATE_STATUS: ' + this.gl.getProgramParameter(this.program, this.gl.VALIDATE_STATUS) + '\\n' +\n 'ERROR: ' + this.gl.getError());\n return null;\n }\n\n this.initialized = true;\n }\n\n updateUniforms(renderer) {\n // Always update time uniform if it exists\n if (this.uniforms['time']) {\n let unif = this.uniforms['time'];\n \n let currentTime = new Date().getTime();\n unif.value += currentTime - this.lastTime;\n this.lastTime = currentTime;\n\n Uniform.Set(this.gl, this.program, unif);\n \n unif.stale = false;\n }\n for (let uniform in this.uniforms) {\n let unif = this.uniforms[uniform];\n if (unif.stale) {\n Uniform.Set(this.gl, this.program, unif);\n }\n }\n }\n\n use() {\n this.gl.useProgram(this.program);\n this.updateUniforms();\n }\n\n static showCompilationInfo(gl, shader, name, prefix) {\n prefix = prefix || 'Shader';\n // This was stolen from THREE.js\n // https://github.com/mrdoob/three.js/blob/master/src/renderers/webgl/WebGLShader.js\n if (gl.getShaderParameter(shader, gl.COMPILE_STATUS) === false) {\n console.error(prefix + ' ' + name + ' did not compile.');\n }\n\n if (gl.getShaderInfoLog(shader) !== '') {\n console.warn(prefix + ' ' + name + ' info log: ' + gl.getShaderInfoLog(shader));\n }\n }\n}\n\nmodule.exports = Shader" }, { "alpha_fraction": 0.6100386381149292, "alphanum_fraction": 0.6370656490325928, "avg_line_length": 17.5, "blob_id": "75c36dcb2bbfff3c82cde1f42712bd45739aa87e", "content_id": "4ac47c9545ddb057686c6259fa783b897456efc8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 259, "license_type": "permissive", "max_line_length": 74, "num_lines": 14, "path": "/src/Core/DrawModes.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\n/** A map mapping draw modes as strings to their GLInt representations. */\nlet DrawModes = {\n points: 0,\n lines: 1,\n lineStrip: 2,\n lineLoop: 3,\n triangles: 4,\n traingleStrip: 5,\n triangleFan: 6\n}\n\nmodule.exports = DrawModes\n" }, { "alpha_fraction": 0.6202531456947327, "alphanum_fraction": 0.624856173992157, "avg_line_length": 29.508771896362305, "blob_id": "7645e6294072359d11f679fb070fe08c802a7ddf", "content_id": "0d1b39570ac853af6727de85c05c19a5242ca3bd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1738, "license_type": "permissive", "max_line_length": 94, "num_lines": 57, "path": "/src/Cameras/PerspectiveCamera.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst CameraBase = require('./CameraBase');\n\n/** A class representing an perspective camera. */\nclass PerspectiveCamera extends CameraBase {\n /**\n * Creates an instance of PerspectiveCamera.\n * @param {Number} fov The field of view.\n * @param {Number} aspect The aspect ration (width / height).\n * @param {Number} near Near extend of the viewing volume.\n * @param {Number} far Far extend of the viewing volume.\n */ \n constructor(fov, aspect, near = 0.1, far = 2500) {\n super();\n\n this.type = 'Lore.PerspectiveCamera';\n\n // TODO: There shouldn't be a zoom here. The problem is, that the orbital controls\n // and also the point helper and zoom rely on it. However, for the perspective camera,\n // zooming is achieved by adjusting the fov. \n this.zoom = 1.0;\n this.fov = fov;\n this.aspect = aspect;\n this.near = near;\n this.far = far;\n\n this.updateProjectionMatrix();\n }\n\n /**\n * Updates the projection matrix of this perspective camera.\n * \n * @returns {PerspectiveCamera} Returns itself.\n */\n updateProjectionMatrix() {\n this.projectionMatrix.setPerspective(this.fov, this.aspect, this.near, this.far);\n this.isProjectionMatrixStale = true;\n\n return this;\n }\n\n /**\n * Has to be called when the viewport size changes (e.g. window resize).\n * \n * @param {Number} width The width of the viewport.\n * @param {Number} height The height of the viewport.\n * \n * @returns {PerspectiveCamera} Returns itself.\n */\n updateViewport(width, height) {\n this.aspect = width / height;\n return this;\n }\n}\n\nmodule.exports = PerspectiveCamera;" }, { "alpha_fraction": 0.6054668426513672, "alphanum_fraction": 0.6163522005081177, "avg_line_length": 32.8934440612793, "blob_id": "abefc957195be109ef352c9f6fb9a212db105aaa", "content_id": "8b70ad9862078ebb08aa8f18fef75aa99c82249a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4134, "license_type": "permissive", "max_line_length": 93, "num_lines": 122, "path": "/src/Cameras/OrthographicCamera.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst CameraBase = require('./CameraBase');\nconst Vector3f = require('../Math/Vector3f');\nconst Matrix4f = require('../Math/Matrix4f');\n\n/** \n * A class representing an orthographic camera. \n * \n * @property {number} [zoom=1.0] The zoom value of this camera.\n * @property {number} left The left border of the frustum.\n * @property {number} right The right border of the frustum.\n * @property {number} top The top border of the frustum.\n * @property {number} bottom The bottom border of the frustum.\n * @property {number} near The near plane distance of the frustum.\n * @property {number} far The far plane distance of the frustum.\n * */\nclass OrthographicCamera extends CameraBase {\n /**\n * Creates an instance of OrthographicCamera.\n * @param {Number} left Left extend of the viewing volume.\n * @param {Number} right Right extend of the viewing volume.\n * @param {Number} top Top extend of the viewing volume.\n * @param {Number} bottom Bottom extend of the viewing volume.\n * @param {Number} near Near extend of the viewing volume.\n * @param {Number} far Far extend of the viewing volume.\n */\n constructor(left, right, top, bottom, near = 0.1, far = 2500) {\n super();\n\n this.type = 'Lore.OrthographicCamera';\n this.zoom = 1.0;\n this.left = left;\n this.right = right;\n this.top = top;\n this.bottom = bottom;\n this.near = near;\n this.far = far;\n\n this.updateProjectionMatrix();\n }\n\n /**\n * Updates the projection matrix of this orthographic camera.\n * \n * @returns {OrthographicCamera} Returns itself.\n */\n updateProjectionMatrix() {\n //TODO: This is called in each render loop? Does it have to?\n let width = (this.right - this.left) / (2.0 * this.zoom);\n let height = (this.top - this.bottom) / (2.0 * this.zoom);\n let x = (this.right + this.left) / 2.0;\n let y = (this.top + this.bottom) / 2.0;\n\n let left = x - width;\n let right = x + width;\n let top = y + height;\n let bottom = y - height;\n\n this.projectionMatrix.setOrthographic(left, right, top, bottom, this.near, this.far);\n this.isProjectionMatrixStale = true;\n\n this.raiseEvent('projectionmatrixupdated', { source: this });\n\n return this;\n }\n\n\n /**\n * Calculate the required zoom factor to contain an a specified width and height.\n * \n * @param {Number} width Width of regtion to be contained.\n * @param {Number} height Height of region to be contained.\n * @param {Number} padding Padding applied to the zoom as a fraction of width and height.\n * \n * @returns {Number} The zoom to be set to contain the specified width and height.\n */\n getRequiredZoomToContain(width, height, padding = 0.0) {\n\n let zoom_width = (this.right - this.left) / (width + width * padding);\n let zoom_height = (this.top - this.bottom) / (height + height * padding);\n\n return Math.min(zoom_width, zoom_height);\n }\n\n /**\n * Has to be called when the viewport size changes (e.g. window resize).\n * \n * @param {Number} width The width of the viewport.\n * @param {Number} height The height of the viewport.\n * \n * @returns {OrthographicCamera} Returns itself.\n */\n updateViewport(width, height) {\n this.left = -width / 2.0;\n this.right = width / 2.0;\n this.top = height / 2.0;\n this.bottom = -height / 2.0;\n\n this.raiseEvent('viewportupdated', { source: this });\n\n return this;\n }\n\n /**\n * Returns the frustum of the orthographic camera which is essentially just a box.\n * \n * @returns {Vector3f[]} An array that contains two vectors defining minima and maxima.\n */\n getFrustum() {\n let z = (this.near + this.far) / (this.near - this.far)\n let min = new Vector3f(-1.0, -1.0, z);\n let max = new Vector3f(1.0, 1.0, z);\n\n Matrix4f.unprojectVector(min, this);\n Matrix4f.unprojectVector(max, this);\n\n return [min, max];\n }\n}\n\nmodule.exports = OrthographicCamera;" }, { "alpha_fraction": 0.6274944543838501, "alphanum_fraction": 0.6294345855712891, "avg_line_length": 25.733333587646484, "blob_id": "c8af9ca427862966e4f3f2bf03040dc76cf4170d", "content_id": "fc54ae75d83a2cf64e11da769902db4740b974d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3608, "license_type": "permissive", "max_line_length": 105, "num_lines": 135, "path": "/src/Core/Geometry.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst DrawModes = require('./DrawModes');\nconst Attribute = require('./Attribute');\nconst Matrix4f = require('../Math/Matrix4f');\nconst Node = require('./Node');\n\n/** \n * A class representing a geometry.\n * \n * @property {String} type The type name of this object (Lore.Geometry).\n * @property {String} name The name of this geometry.\n * @property {WebGLRenderingContext} gl A WebGL rendering context.\n * @property {Shader} shader An initialized shader.\n * @property {Object} attributes A map mapping attribute names to Lore.Attrubute objects.\n * @property {DrawMode} [drawMode=gl.POINTS] The current draw mode of this geometry.\n * @property {Boolean} isVisisble A boolean indicating whether or not this geometry is currently visible.\n */\nclass Geometry extends Node {\n constructor(name, gl, shader) {\n super();\n\n this.type = 'Lore.Geometry';\n this.name = name;\n this.gl = gl;\n this.shader = shader;\n this.attributes = {};\n this.drawMode = this.gl.POINTS;\n this.isVisible = true;\n this.stale = false;\n }\n\n addAttribute(name, data, length) {\n this.attributes[name] = new Attribute(data, length, name);\n this.attributes[name].createBuffer(this.gl, this.shader.program);\n\n return this;\n }\n\n updateAttribute(name, data) {\n if (data) {\n this.attributes[name].data = data;\n }\n\n this.attributes[name].update(this.gl);\n\n return this;\n }\n\n getAttribute(name) {\n return this.attributes[name];\n }\n\n removeAttribute(name) {\n delete this.attributes[name];\n\n return this;\n }\n\n setMode(drawMode) {\n switch (drawMode) {\n case DrawModes.points:\n this.drawMode = this.gl.POINTS;\n break;\n case DrawModes.lines:\n this.drawMode = this.gl.LINES;\n break;\n case DrawModes.lineStrip:\n this.drawMode = this.gl.LINE_STRIP;\n break;\n case DrawModes.lineLoop:\n this.drawMode = this.gl.LINE_LOOP;\n break;\n case DrawModes.triangles:\n this.drawMode = this.gl.TRIANGLES;\n break;\n case DrawModes.triangleStrip:\n this.drawMode = this.gl.TRIANGLE_STRIP;\n break;\n case DrawModes.triangleFan:\n this.drawMode = this.gl.TRIANGLE_FAN;\n break;\n }\n\n return this;\n }\n\n size() {\n // Is this ok? All attributes should have the same length ...\n if (Object.keys(this.attributes).length > 0) {\n return this.attributes[Object.keys(this.attributes)[0]].size;\n }\n\n return 0;\n }\n\n hide() {\n this.isVisible = false;\n }\n\n show() {\n this.isVisible = true;\n this.stale = true;\n }\n\n draw(renderer) {\n if (!this.isVisible) return;\n\n for (let prop in this.attributes)\n if (this.attributes[prop].stale) this.attributes[prop].update(this.gl);\n\n this.shader.use();\n\n // Update the modelView and projection matrices\n if (renderer.camera.isProjectionMatrixStale || this.stale) {\n this.shader.uniforms.projectionMatrix.setValue(renderer.camera.getProjectionMatrix());\n }\n\n if (renderer.camera.isViewMatrixStale || this.stale) {\n let modelViewMatrix = Matrix4f.multiply(renderer.camera.viewMatrix, this.modelMatrix);\n this.shader.uniforms.modelViewMatrix.setValue(modelViewMatrix.entries);\n }\n\n this.shader.updateUniforms();\n\n for (let prop in this.attributes) {\n this.attributes[prop].bind(this.gl);\n }\n\n this.gl.drawArrays(this.drawMode, 0, this.size());\n this.stale = false;\n }\n}\n\nmodule.exports = Geometry" }, { "alpha_fraction": 0.6617375016212463, "alphanum_fraction": 0.6617375016212463, "avg_line_length": 20.68000030517578, "blob_id": "c596c68d4cd774909e154f247cd20c6543244900", "content_id": "13b64aa390b1b726f0f89cab8cc87d44784940fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 541, "license_type": "permissive", "max_line_length": 41, "num_lines": 25, "path": "/src/Core/index.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "const Attribute = require('./Attribute');\nconst Color = require('./Color');\nconst DrawModes = require('./DrawModes');\nconst Effect = require('./Effect');\nconst Geometry = require('./Geometry');\nconst Graph = require('./Graph');\nconst Node = require('./Node');\nconst Renderer = require('./Renderer');\nconst Shader = require('./Shader');\nconst Tree = require('./Tree');\nconst Uniform = require('./Uniform');\n\nmodule.exports = {\n Attribute,\n Color,\n DrawModes,\n Effect,\n Geometry,\n Graph,\n Node,\n Renderer,\n Shader,\n Tree,\n Uniform\n}" }, { "alpha_fraction": 0.44455021619796753, "alphanum_fraction": 0.5040456652641296, "avg_line_length": 41.02000045776367, "blob_id": "5c0bd2a2c188929170d51de8c3b9d424f0a93400", "content_id": "242b1a4f5bce029d60646805043cc01ec0024e5c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2101, "license_type": "permissive", "max_line_length": 117, "num_lines": 50, "path": "/src/Shaders/Circle.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "const Shader = require('../Core/Shader')\nconst Uniform = require('../Core/Uniform')\n\nmodule.exports = new Shader('circle', 1, { size: new Uniform('size', 5.0, 'float'),\n cutoff: new Uniform('cutoff', 0.0, 'float'),\n clearColor: new Uniform('clearColor', [0.0, 0.0, 0.0, 1.0], 'float_vec4'),\n fogDensity: new Uniform('fogDensity', 6.0, 'float') }, [\n 'uniform float size;',\n 'uniform float cutoff;',\n 'attribute vec3 position;',\n 'attribute vec3 color;',\n 'varying vec3 vColor;',\n 'varying float vDiscard;',\n 'vec3 floatToRgb(float n) {',\n 'float b = floor(n / 65536.0);',\n 'float g = floor((n - b * 65536.0) / 256.0);',\n 'float r = floor(n - b * 65536.0 - g * 256.0);',\n 'return vec3(r / 255.0, g / 255.0, b / 255.0);',\n '}',\n 'void main() {',\n 'float point_size = color.b;',\n 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',\n 'vec4 mv_pos = modelViewMatrix * vec4(position, 1.0);',\n 'vDiscard = 0.0;',\n 'if(-mv_pos.z < cutoff || point_size <= 0.0 || mv_pos.z > 0.0) {',\n 'vDiscard = 1.0;',\n 'return;',\n '}',\n 'gl_PointSize = point_size * size;',\n 'vColor = floatToRgb(color.r);',\n '}'\n], [\n 'uniform vec4 clearColor;',\n 'uniform float fogDensity;',\n 'varying vec3 vColor;',\n 'varying float vDiscard;',\n 'float rand(vec2 co) {',\n 'return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);',\n '}',\n 'void main() {',\n 'if(vDiscard > 0.5) discard;',\n 'vec3 N;',\n 'N.xy = gl_PointCoord * 2.0 - vec2(1.0);',\n 'float mag = dot(N.xy, N.xy);',\n 'if (mag > 1.0) discard; // discard fragments outside circle',\n 'float z = gl_FragCoord.z / gl_FragCoord.w;',\n 'float fog_factor = clamp(exp2(-fogDensity * fogDensity * z * z * 1.442695), 0.025, 1.0);',\n 'gl_FragColor = mix(clearColor, vec4(vColor, 1.0), fog_factor);',\n '}'\n]);\n" }, { "alpha_fraction": 0.5527787208557129, "alphanum_fraction": 0.5741532444953918, "avg_line_length": 27.97142791748047, "blob_id": "9c432f9581da0f6c2eb5ff2a70f600c0b59aa23d", "content_id": "7c14b53612449815315ce1b5c6894f12c72c88cc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3041, "license_type": "permissive", "max_line_length": 98, "num_lines": 105, "path": "/src/Math/SphericalCoords.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst Vector3f = require('./Vector3f')\n\n/** A class representing spherical coordinates. */\nclass SphericalCoords {\n /**\n * Creates an instance of SphericalCoords.\n * @param {Number} [radius=1.0] The radius.\n * @param {Number} [phi=0.0] Phi in radians.\n * @param {Number} [theta=0.0] Theta in radians.\n */\n constructor(radius = 1.0, phi = 0.0, theta = 0.0) {\n this.components = new Float32Array(3);\n this.radius = radius;\n this.phi = phi;\n this.theta = theta;\n }\n\n /**\n * Set the spherical coordinates from the radius, the phi angle and the theta angle.\n * \n * @param {Number} radius \n * @param {Number} phi \n * @param {Number} theta \n * @returns {SphericalCoords} Returns itself.\n */\n set(radius, phi, theta) {\n this.components[0] = radius;\n this.components[1] = phi;\n this.components[2] = theta;\n\n return this;\n }\n\n /**\n * Avoid overflows.\n * \n * @returns {SphericalCoords} Returns itself.\n */\n secure() {\n this.components[1] = Math.max(0.000001, Math.min(Math.PI - 0.000001, this.components[1]));\n\n return this;\n }\n\n /**\n * Set the spherical coordaintes from a vector.\n * \n * @param {Vector3f} v A vector.\n * @returns {SphericalCoords} Returns itself.\n */\n setFromVector(v) {\n this.components[0] = v.length();\n\n if (this.components[0] === 0.0) {\n this.components[1] = 0.0;\n this.components[2] = 0.0;\n } else {\n this.components[1] = Math.acos(Math.max(-1.0, Math.min(1.0, v.components[1] /\n this.components[0])));\n this.components[2] = Math.atan2(v.components[0], v.components[2]);\n }\n\n return this;\n }\n\n /**\n * Limit the rotation by setting maxima and minima for phi and theta.\n * \n * @param {Number} phiMin The minimum for phi.\n * @param {Number} phiMax The maximum for phi.\n * @param {Number} thetaMin The minimum for theta.\n * @param {Number} thetaMax The maximum for theta.\n * @returns {SphericalCoords} Returns itself.\n */\n limit(phiMin, phiMax, thetaMin, thetaMax) {\n // Limits for orbital controls\n this.components[1] = Math.max(phiMin, Math.min(phiMax, this.components[1]));\n this.components[2] = Math.max(thetaMin, Math.min(thetaMax, this.components[2]));\n \n return this;\n }\n\n /**\n * Clone this spherical coordinates object.\n * \n * @returns {SphericalCoords} A clone of the spherical coordinates object.\n */\n clone() {\n return new SphericalCoords(this.radius, this.phi, this.theta);\n }\n\n /**\n * Returns a string representation of these spherical coordinates.\n * \n * @returns {String} A string representing spherical coordinates.\n */\n toString() {\n return '(' + this.components[0] + ', ' +\n this.components[1] + ', ' + this.components[2] + ')';\n }\n}\n\nmodule.exports = SphericalCoords" }, { "alpha_fraction": 0.42776885628700256, "alphanum_fraction": 0.4727126657962799, "avg_line_length": 41.4886360168457, "blob_id": "08d226f4475f0758278f465315c49368b650a2d7", "content_id": "fb41f4b3d0744380791c94b5ddc13329c5af5925", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3738, "license_type": "permissive", "max_line_length": 108, "num_lines": 88, "path": "/src/Helpers/AABBHelper.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst DrawModes = require('../Core/DrawModes');\nconst HelperBase = require('./HelperBase');\nconst Utils = require('../Utils/Utils');\n\n/** A helper class for drawing axis aligned bounding boxes. */\nclass AABBHelper extends HelperBase {\n /**\n * Creates an instance of AABBHelper.\n * \n * @param {Renderer} renderer A Lore.Renderer object.\n * @param {array} aabbs An array containing axis-aligned bounding boxes.\n * @param {string} geometryName The name of the geometry used to render the axis-aligned bounding boxes.\n * @param {string} shaderName The name of the shader used to render the axis-aligned bounding boxes.\n * @param {object} options Options for drawing the axis-aligned bounding boxes.\n */\n constructor(renderer, aabbs, geometryName, shaderName, options) {\n // TODO: Fix error\n super(renderer, geometryName, shaderName);\n\n // Create lines\n // Replaced with indexed?\n\n let p = new Float32Array(aabbs.length * 24 * 3);\n let c = new Float32Array(aabbs.length * 24 * 3);\n\n let index = 0;\n\n for (let i = 0; i < aabbs.length; i++) {\n let aabb = aabbs[0];\n let cx = aabb.center.components[0];\n let cy = aabb.center.components[1];\n let cz = aabb.center.components[2];\n let r = aabb.radius;\n\n let p0 = [ cx - r, cy - r, cz - r ];\n let p1 = [ cx - r, cy - r, cz + r ];\n let p2 = [ cx - r, cy + r, cz - r ];\n let p3 = [ cx - r, cy + r, cz + r ];\n let p4 = [ cx + r, cy - r, cz - r ];\n let p5 = [ cx + r, cy - r, cz + r ];\n let p6 = [ cx + r, cy + r, cz - r ];\n let p7 = [ cx + r, cy + r, cz + r ];\n\n p[index++] = p0[0]; p[index++] = p0[1]; p[index++] = p0[2];\n p[index++] = p1[0]; p[index++] = p1[1]; p[index++] = p1[2];\n p[index++] = p0[0]; p[index++] = p0[1]; p[index++] = p0[2];\n p[index++] = p2[0]; p[index++] = p2[1]; p[index++] = p2[2];\n p[index++] = p0[0]; p[index++] = p0[1]; p[index++] = p0[2];\n p[index++] = p4[0]; p[index++] = p4[1]; p[index++] = p4[2];\n\n p[index++] = p1[0]; p[index++] = p1[1]; p[index++] = p1[2];\n p[index++] = p3[0]; p[index++] = p3[1]; p[index++] = p3[2];\n p[index++] = p1[0]; p[index++] = p1[1]; p[index++] = p1[2];\n p[index++] = p5[0]; p[index++] = p5[1]; p[index++] = p5[2];\n\n p[index++] = p2[0]; p[index++] = p2[1]; p[index++] = p2[2];\n p[index++] = p3[0]; p[index++] = p3[1]; p[index++] = p3[2];\n p[index++] = p2[0]; p[index++] = p2[1]; p[index++] = p2[2];\n p[index++] = p6[0]; p[index++] = p6[1]; p[index++] = p6[2];\n\n p[index++] = p3[0]; p[index++] = p3[1]; p[index++] = p3[2];\n p[index++] = p7[0]; p[index++] = p7[1]; p[index++] = p7[2];\n\n p[index++] = p4[0]; p[index++] = p4[1]; p[index++] = p4[2];\n p[index++] = p5[0]; p[index++] = p5[1]; p[index++] = p5[2];\n p[index++] = p4[0]; p[index++] = p4[1]; p[index++] = p4[2];\n p[index++] = p6[0]; p[index++] = p6[1]; p[index++] = p6[2];\n\n p[index++] = p5[0]; p[index++] = p5[1]; p[index++] = p5[2];\n p[index++] = p7[0]; p[index++] = p7[1]; p[index++] = p7[2];\n\n p[index++] = p6[0]; p[index++] = p6[1]; p[index++] = p6[2];\n p[index++] = p7[0]; p[index++] = p7[1]; p[index++] = p7[2];\n }\n\n\n \n this.opts = Utils.extend(true, AABBHelper.defaults, options);\n this.geometry.setMode(DrawModes.lines);\n\n this.setAttribute('position', p);\n this.setAttribute('color', c);\n }\n}\n\nmodule.exports = AABBHelper" }, { "alpha_fraction": 0.5980127453804016, "alphanum_fraction": 0.6021291613578796, "avg_line_length": 32.208736419677734, "blob_id": "24e75f38a584846eaf93cf63e1326e9593819317", "content_id": "1c38290182fd401482f1931f2edc03e08cc2f7a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7045, "license_type": "permissive", "max_line_length": 160, "num_lines": 206, "path": "/src/Core/Attribute.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\r\n\r\nconst Vector3f = require('../Math/Vector3f');\r\n\r\n/** \r\n * A class representing an attribute. \r\n * \r\n * @property {String} type The type name of this object (Lore.Attribute).\r\n * @property {*} data The data represented by the attribute in a 1D array. Usually a Float32Array.\r\n * @property {Number} [attributeLength=3] The length of the attribute. '3' for Vector3f.\r\n * @property {String} name The name of this attribut. Must be the name used by the shader.\r\n * @property {Number} size The length of the attribute values (defined as data.length / attributeLength).\r\n * @property {WebGLBuffer} buffer The bound WebGLBuffer.\r\n * @property {GLint} attributeLocation The attribute location for this attribute.\r\n * @property {GLenum} bufferType The buffer target. As of WebGL 1: gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER.\r\n * @property {GLenum} drawMode The draw mode. As of WebGL 1: gl.STATIC_DRAW, gl.DYNAMIC_DRAW or gl.STREAM_DRAW.\r\n * @property {Boolean} stale A boolean indicating whether or not this attribute has changed and needs to be updated.\r\n */\r\nclass Attribute {\r\n /**\r\n * Creates an instance of Attribute.\r\n * @param {*} data The data represented by the attribute in a 1D array. Usually a Float32Array.\r\n * @param {Number} attributeLength The length of the attribute (3 for RGB, XYZ, ...).\r\n * @param {String} name The name of the attribute.\r\n */\r\n constructor(data, attributeLength, name) {\r\n this.type = 'Lore.Attribute';\r\n this.data = data;\r\n this.attributeLength = attributeLength || 3;\r\n this.name = name;\r\n this.size = this.data.length / this.attributeLength;\r\n this.buffer = null;\r\n this.attributeLocation;\r\n this.bufferType = null;\r\n this.drawMode = null;\r\n this.stale = false;\r\n }\r\n\r\n /**\r\n * Set the attribute value from a vector at a given index. The vector should have the same number of components as is the length of this attribute.\r\n * \r\n * @param {Number} index The index at which to replace / set the value (is calculated as index * attributeLength).\r\n * @param {Vector3f} v A vector.\r\n */\r\n setFromVector(index, v) {\r\n this.data.set(v.components, index * this.attributeLength, v.components.length);\r\n }\r\n\r\n /**\r\n * Set the attribute values from vectors in an array.\r\n * \r\n * @param {Vector3f[]} arr An array containing vectors. The number of components of the vectors must have the same length as the attribute length specified.\r\n */\r\n setFromVectorArray(arr) {\r\n if (this.attributeLength !== arr[0].components.length)\r\n throw 'The attribute has a length of ' + this.attributeLength + '. But the vectors have ' + arr[0].components.length + ' components.';\r\n\r\n for (let i = 0; i < arr.length; i++) {\r\n this.data.set(arr[i].components, i * this.attributeLength, arr[i].components.length);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the x value at a given index.\r\n * \r\n * @param {Number} index The index.\r\n * @returns {Number} The x value at a given index.\r\n */\r\n getX(index) {\r\n return this.data[index * this.attributeLength];\r\n }\r\n\r\n /**\r\n * Set the x value at a given index.\r\n * \r\n * @param {Number} index The index.\r\n * @param {Number} value A number.\r\n */\r\n setX(index, value) {\r\n this.data[index * this.attributeLength];\r\n }\r\n\r\n /**\r\n * Gets the y value at a given index.\r\n * \r\n * @param {Number} index The index.\r\n * @returns {Number} The y value at a given index.\r\n */\r\n getY(index) {\r\n return this.data[index * this.attributeLength + 1];\r\n }\r\n\r\n /**\r\n * Set the y value at a given index.\r\n * \r\n * @param {Number} index The index.\r\n * @param {Number} value A number.\r\n */\r\n setY(index, value) {\r\n this.data[index * this.attributeLength + 1];\r\n }\r\n\r\n /**\r\n * Gets the z value at a given index.\r\n * \r\n * @param {Number} index The index.\r\n * @returns {Number} The z value at a given index.\r\n */\r\n getZ(index) {\r\n return this.data[index * this.attributeLength + 2];\r\n }\r\n\r\n /**\r\n * Set the z value at a given index.\r\n * \r\n * @param {Number} index The index.\r\n * @param {Number} value A number.\r\n */\r\n setZ(index, value) {\r\n this.data[index * this.attributeLength + 2];\r\n }\r\n\r\n /**\r\n * Gets the w value at a given index.\r\n * \r\n * @param {Number} index The index.\r\n * @returns {Number} The w value at a given index.\r\n */\r\n getW(index) {\r\n return this.data[index * this.attributeLength + 3];\r\n }\r\n\r\n /**\r\n * Set the w value at a given index.\r\n * \r\n * @param {Number} index The index.\r\n * @param {Number} value A number.\r\n */\r\n setW(index, value) {\r\n this.data[index * this.attributeLength + 3];\r\n }\r\n\r\n /**\r\n * Returns the gl type. Currently only float is supported.\r\n * \r\n * @param {WebGLRenderingContext} gl The WebGL rendering context.\r\n * @returns {Number} The type.\r\n */\r\n getGlType(gl) {\r\n // Just floats for now\r\n // TODO: Add additional types.\r\n return gl.FLOAT;\r\n }\r\n\r\n /**\r\n * Update the attribute in order for changes to take effect.\r\n * \r\n * @param {WebGLRenderingContext} gl The WebGL rendering context.\r\n */\r\n update(gl) {\r\n gl.bindBuffer(this.bufferType, this.buffer);\r\n gl.bufferData(this.bufferType, this.data, this.drawMode);\r\n\r\n this.stale = false;\r\n }\r\n\r\n /**\r\n * Create a new WebGL buffer.\r\n * \r\n * @param {WebGLRenderingContext} gl The WebGL rendering context.\r\n * @param {WebGLProgram} program A WebGL program.\r\n * @param {GLenum} bufferType The buffer type.\r\n * @param {GLenum} drawMode The draw mode.\r\n */\r\n createBuffer(gl, program, bufferType, drawMode) {\r\n this.buffer = gl.createBuffer();\r\n this.bufferType = bufferType || gl.ARRAY_BUFFER;\r\n this.drawMode = drawMode || gl.STATIC_DRAW;\r\n\r\n gl.bindBuffer(this.bufferType, this.buffer);\r\n gl.bufferData(this.bufferType, this.data, this.drawMode);\r\n\r\n this.buffer.itemSize = this.attributeLength;\r\n this.buffer.numItems = this.size;\r\n\r\n this.attributeLocation = gl.getAttribLocation(program, this.name);\r\n gl.bindBuffer(this.bufferType, null);\r\n }\r\n\r\n /**\r\n * Bind the buffer of this attribute. The attribute must exist in the current shader.\r\n * \r\n * @param {WebGLRenderingContext} gl The WebGL rendering context.\r\n */\r\n bind(gl) {\r\n gl.bindBuffer(this.bufferType, this.buffer);\r\n\r\n // Only enable attribute if it actually exists in the Shader\r\n if (this.attributeLocation >= 0) {\r\n gl.vertexAttribPointer(this.attributeLocation, this.attributeLength, this.getGlType(gl), gl.FALSE, 0, 0);\r\n gl.enableVertexAttribArray(this.attributeLocation);\r\n }\r\n }\r\n}\r\n\r\nmodule.exports = Attribute;" }, { "alpha_fraction": 0.5708285570144653, "alphanum_fraction": 0.5735013484954834, "avg_line_length": 22.185840606689453, "blob_id": "abf8ca3847751c1e715f75cae9facd8a7aea0954", "content_id": "be2f3e0fbce61341c7f0003af49b7d981a42e2d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2619, "license_type": "permissive", "max_line_length": 68, "num_lines": 113, "path": "/gulpfile.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "var fs = require('fs');\nvar gulp = require('gulp');\nvar exit = require('gulp-exit');\n\nvar browserify = require('browserify');\nvar watchify = require('watchify');\nvar babelify = require('babelify');\n\nvar source = require('vinyl-source-stream');\nvar buffer = require('vinyl-buffer');\n\nvar sourcemaps = require('gulp-sourcemaps');\n\nvar concat = require('gulp-concat');\nvar rename = require('gulp-rename');\nvar minify = require('gulp-babel-minify');\nvar jsdoc = require('gulp-jsdoc3');\nvar gulpJsdoc2md = require('gulp-jsdoc-to-markdown');\nvar gutil = require('gulp-util');\nvar webpack = require('webpack-stream');\n\nfunction compile(watch) {\n var bundler = watchify(browserify('./app.js', {\n debug: true\n }).transform(babelify, {\n presets: [['env', {\n targets: { 'chrome': '65' }\n }]],\n sourceMaps: true\n }));\n\n function rebundle() {\n return bundler\n .bundle()\n .on('error', function (err) {\n console.error(err);\n this.emit('end');\n })\n .pipe(source('build.js'))\n .pipe(buffer())\n .pipe(rename('lore.js'))\n .pipe(sourcemaps.init({\n loadMaps: true\n }))\n .pipe(gulp.dest('./dist/'))\n .pipe(minify())\n .pipe(rename('lore.min.js'))\n .pipe(sourcemaps.write('./'))\n .pipe(gulp.dest('./dist'));\n }\n\n if (watch) {\n bundler.on('update', function () {\n console.log('-> bundling...');\n rebundle();\n });\n\n rebundle();\n } else {\n rebundle().pipe(exit());\n }\n}\n\nfunction watch() {\n return compile(true);\n}\n\ngulp.task('build', function () {\n return new Promise(function(resolve, reject) {\n compile();\n resolve();\n })\n});\n\ngulp.task('watch', function () {\n return new Promise(function(resolve, reject) {\n watch();\n resolve();\n });\n});\n\ngulp.task('doc', function (cb) {\n return new Promise(function(resolve, reject) {\n var config = require('./jsdocConfig.json');\n gulp.src(['README.md', './src/*.js'], {\n read: false\n })\n .pipe(jsdoc(config, cb))\n \n resolve();\n });\n});\n\ngulp.task('md', function (cb) {\n return new Promise(function(resolve, reject) {\n var config = require('./jsdocConfig.json');\n gulp.src('./src/*.js')\n .pipe(concat('all.md'))\n .pipe(gulpJsdoc2md({\n template: fs.readFileSync('./readme.hbs', 'utf8')\n }))\n .on('error', function (err) {\n gutil.log(gutil.colors.red('jsdoc2md failed'), err.message);\n })\n .pipe(rename(function (path) {\n path.extname = '.md';\n }))\n .pipe(gulp.dest('doc'));\n resolve();\n });\n});\n\ngulp.task('default', gulp.series('build', 'doc', 'md'));" }, { "alpha_fraction": 0.7012194991111755, "alphanum_fraction": 0.7103658318519592, "avg_line_length": 26.41666603088379, "blob_id": "d227a3c6b07212a50e7f2759dc87f3e771ab9196", "content_id": "c595487cdd6c7dcbda17c614c738ee77ef1fdee1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 328, "license_type": "permissive", "max_line_length": 88, "num_lines": 12, "path": "/example/vtkToCsv.py", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport sys\nimport meshio\n\nif len(sys.argv) < 3:\n print('Please specify a file to convert as well as the output file as arguments.\\n')\n print('Example: python nrrdToCsv.py input.nrrd output.csv\\n')\n sys.exit(0)\n\n\npoints, cells, point_data, cell_data, field_data = meshio.read(sys.argv[1])\nprint(points)" }, { "alpha_fraction": 0.5988562107086182, "alphanum_fraction": 0.6135621070861816, "avg_line_length": 28.14285659790039, "blob_id": "2cdea2dd19031c67da5ac87aca55085421693aaf", "content_id": "008997f7a14c37dc0dcdbcaa36a58423e5be9674", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1224, "license_type": "permissive", "max_line_length": 101, "num_lines": 42, "path": "/src/Spice/Raycaster.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst Ray = require('../Math/Ray');\nconst Matrix4f = require('../Math/Matrix4f')\n\n/** A class representing a raycaster. */\nclass Raycaster {\n /**\n * Creates an instance of Raycaster.\n * \n * @param {Number} [threshold=0.1] Data to be sent to the listening functions.\n */\n constructor(threshold = 0.1) {\n this.ray = new Ray();\n this.near = 0;\n this.far = 1000;\n this.threshold = threshold;\n }\n\n /**\n * Set the raycaster based on a camera and the current mouse coordinates.\n * \n * @param {CameraBase} camera A camera object which extends Lore.CameraBase.\n * @param {number} mouseX The x coordinate of the mouse.\n * @param {number} mouseY The y coordinate of the mouse.\n * @returns {Raycaster} Itself.\n */\n set(camera, mouseX, mouseY) {\n this.near = camera.near;\n this.far = camera.far;\n\n this.ray.source.set(mouseX, mouseY, (camera.near + camera.far) / (camera.near - camera.far));\n Matrix4f.unprojectVector(this.ray.source, camera);\n\n this.ray.direction.set(0.0, 0.0, -1.0);\n this.ray.direction.toDirection(camera.modelMatrix);\n \n return this;\n }\n}\n\nmodule.exports = Raycaster\n" }, { "alpha_fraction": 0.7310344576835632, "alphanum_fraction": 0.7310344576835632, "avg_line_length": 19.85714340209961, "blob_id": "381df809c220e02267fb032415e42a92943acd49", "content_id": "2351be2647bbb9bb8d37265042501a5bb093fbc3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 145, "license_type": "permissive", "max_line_length": 49, "num_lines": 7, "path": "/src/Filters/index.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "const FilterBase = require('./FilterBase');\nconst InRangeFilter = require('./InRangeFilter');\n\nmodule.exports = {\n FilterBase,\n InRangeFilter\n}" }, { "alpha_fraction": 0.488237202167511, "alphanum_fraction": 0.5165968537330627, "avg_line_length": 28.846153259277344, "blob_id": "8c5ccd4e986d61cd8bf788985dda286693565f46", "content_id": "06c36e6e5cb4056c545ae13586b49fbbcfa6ace3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3103, "license_type": "permissive", "max_line_length": 66, "num_lines": 104, "path": "/src/Math/ProjectionMatrix.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst Matrix4f = require('./Matrix4f');\nconst Utils = require('../Utils/Utils');\n\n/** A class representing a projection matrix */\nclass ProjectionMatrix extends Matrix4f {\n /**\n * Set the projection matrix to an orthographic projection.\n *\n * @param {number} left The left edge.\n * @param {number} right The right edge.\n * @param {number} top The top edge.\n * @param {number} bottom The bottom edge.\n * @param {number} near The near-cutoff value.\n * @param {number} far The far-cutoff value.\n * @returns {ProjectionMatrix} Returns this projection matrix.\n */\n setOrthographic(left, right, top, bottom, near, far) {\n let w = 1.0 / (right - left);\n let h = 1.0 / (top - bottom);\n let d = 1.0 / (far - near);\n\n let x = (right + left) * w;\n let y = (top + bottom) * h;\n let z = (far + near) * d;\n\n this.setZero();\n\n this.entries[0] = 2 * w;\n this.entries[4] = 0;\n this.entries[8] = 0;\n this.entries[12] = -x;\n this.entries[1] = 0;\n this.entries[5] = 2 * h;\n this.entries[9] = 0;\n this.entries[13] = -y;\n this.entries[2] = 0;\n this.entries[6] = 0;\n this.entries[10] = -2 * d;\n this.entries[14] = -z;\n this.entries[3] = 0;\n this.entries[7] = 0;\n this.entries[11] = 0;\n this.entries[15] = 1;\n\n return this;\n }\n\n /**\n * Set the projection matrix to a perspective projection.\n *\n * @param {number} fov The field of view.\n * @param {number} aspect The aspect ratio (width / height).\n * @param {number} near The near-cutoff value.\n * @param {number} far The far-cutoff value.\n * @returns {ProjectionMatrix} Returns this projection matrix.\n */\n setPerspective(fov, aspect, near, far) {\n let range = near - far;\n let tanHalfFov = Math.tan(Utils.DEG2RAD * 0.5 * fov);\n \n let top = near * tanHalfFov;\n let height = 2.0 * top;\n let width = aspect * height;\n let left = -width / 2.0;\n let right = left + width;\n let bottom = top - height;\n // let bottom = -top;\n // let right = top * aspect;\n // let left = -right;\n\n let x = 2.0 * near / (right - left);\n let y = 2.0 * near / (top - bottom);\n\n let a = (right + left) / (right - left);\n let b = (top + bottom) / (top - bottom);\n let c = -(far + near) / (far - near);\n let d = -2 * far * near / (far - near);\n \n this.setZero();\n\n this.entries[0] = x;\n this.entries[4] = 0;\n this.entries[8] = a;\n this.entries[12] = 0;\n this.entries[1] = 0;\n this.entries[5] = y;\n this.entries[9] = b;\n this.entries[13] = 0;\n this.entries[2] = 0;\n this.entries[6] = 0;\n this.entries[10] = c;\n this.entries[14] = d;\n this.entries[3] = 0;\n this.entries[7] = 0;\n this.entries[11] = -1;\n this.entries[15] = 0;\n\n return this;\n }\n}\n\nmodule.exports = ProjectionMatrix" }, { "alpha_fraction": 0.5242817997932434, "alphanum_fraction": 0.5427496433258057, "avg_line_length": 23.788135528564453, "blob_id": "b050905a551f9efccac76232a0e89f048c07b768", "content_id": "22ef9fbfff71c1597791ad8682179d53c5dfe743", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2924, "license_type": "permissive", "max_line_length": 167, "num_lines": 118, "path": "/src/Core/Tree.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\n/** \n * A class representing a tree. \n * \n * @property {Array} tree An array of arrays where the index is the node id and the inner arrays contain the neighbours.\n */\nclass Tree {\n /**\n * The constructor of the class Tree.\n * \n * @param {Array[]} tree An array of arrays where the index is the node id and the inner arrays contain the neighbours.\n * @param {Array[]} weights An array of arrays where the index is the node id and the inner arrays contain the weights in the same order as tree contains neighbours.\n */\n constructor(tree, weights) {\n this.tree = tree;\n this.weights = weights;\n }\n\n /**\n * Layout the tree\n */\n layout() {\n let root = 0;\n let visited = new Uint8Array(this.tree.length);\n let pX = new Float32Array(this.tree.length);\n let pY = new Float32Array(this.tree.length);\n let queue = [root];\n visited[root] = 1;\n let current = null;\n \n // Position initial node\n pX[root] = 20.0;\n pY[root] = 10.0;\n\n while (queue.length > 0) {\n current = queue.shift();\n\n let offset = 0;\n for (var i = 0; i < this.tree[current].length; i++) {\n let child = this.tree[current][i];\n\n if (visited[child] === 0) {\n // Do some positioning\n\n pX[child] = pX[current] + this.weights[current][i] * 5.0;\n pY[child] = pY[current] + offset++ * 10.0 * this.weights[current][i];\n\n let fX = 0.0;\n let fY = 0.0;\n\n for (var j = 0; j < length; j++) {\n if (visited[j] === 0) {\n continue;\n }\n\n let distSquared = Math.pow(pX[j] - pX[child], 2.0) + Math.pow(pY[j] - pY[child], 2.0);\n let dist = Math.sqrt(distSquared);\n \n let fAttractive = 1000 / distSquared;\n }\n\n // Done with positioning\n\n visited[child] = 1;\n queue.push(child);\n }\n }\n }\n\n let positions = Array(this.tree.length);\n\n for (var i = 0; i < this.tree.length; i++) {\n positions[i] = [ pX[i], pY[i] ];\n }\n\n return positions;\n }\n\n /**\n * Create a tree from an edge list. \n */\n static fromEdgeList(edgeList) {\n let length = 0;\n\n for (var i = 0; i < edgeList.length; i++) {\n if (edgeList[i][0] > length) {\n length = edgeList[i][0];\n }\n\n if (edgeList[i][1] > length) {\n length = edgeList[i][1];\n }\n }\n\n length++;\n\n let neighbours = Array(length);\n let weights = Array(length);\n\n for (var i = 0; i < length; i++) {\n neighbours[i] = Array();\n weights[i] = Array();\n }\n\n for (var i = 0; i < edgeList.length; i++) {\n neighbours[edgeList[i][0]].push(edgeList[i][1]);\n neighbours[edgeList[i][1]].push(edgeList[i][0]);\n\n weights[edgeList[i][0]].push(edgeList[i][2]);\n weights[edgeList[i][1]].push(edgeList[i][2]);\n }\n\n return new Tree(neighbours, weights);\n }\n}\n\nmodule.exports = Tree" }, { "alpha_fraction": 0.534272313117981, "alphanum_fraction": 0.5441314578056335, "avg_line_length": 28.797203063964844, "blob_id": "6f2dac9b065afc3321d5588cc1cce3cb769a6657", "content_id": "53ca843334289684e098e256b4b3def2b55fdf36", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4260, "license_type": "permissive", "max_line_length": 113, "num_lines": 143, "path": "/src/Utils/Utils.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\n/** A utility class containing static methods. */\nclass Utils {\n /**\n * Merges two objects, overriding probierties set in both objects in the first one.\n * \n * @returns {object} The merged object.\n */\n static extend() {\n let extended = {};\n let deep = false;\n let i = 0;\n let length = arguments.length;\n\n if (Object.prototype.toString.call(arguments[0]) === '[object Boolean]') {\n deep = arguments[0];\n i++;\n }\n\n let merge = function (obj) {\n for (let prop in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n if (deep && Object.prototype.toString.call(obj[prop]) === '[object Object]') {\n extended[prop] = Utils.extend(true, extended[prop], obj[prop]);\n } else {\n extended[prop] = obj[prop];\n }\n }\n }\n };\n\n for ( ; i < length; i++) {\n let obj = arguments[i];\n merge(obj);\n }\n\n return extended;\n }\n\n /**\n * Checks whether or not an array contains a given value.\n * \n * @param {Array} array An array.\n * @param {object} value An object.\n * @returns {boolean} A boolean whether or not the array contains the value.\n */\n static arrayContains(array, value) {\n for(let i = 0; i < array.length; i++) {\n if(array[i] === value) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Concatinate two typed arrays.\n * \n * @param {Array|Float32Array} arrA A typed array.\n * @param {Array|Float32Array} arrB A typed array.\n * @returns {Array|Float32Array} The concatinated typed array.\n */\n static concatTypedArrays(arrA, arrB) {\n let arrC = new arrA.constructor(arrA.length + arrB.length);\n \n arrC.set(arrA);\n arrC.set(arrB, arrA.length);\n\n return arrC;\n };\n\n /**\n * Get the most significant bit (MSB) of a number.\n * \n * @param {Number} n A number. \n * @returns {Number} The most significant bit (0 or 1).\n */\n static msb(n) {\n return (n & 0x80000000) ? 31 : Utils.msb((n << 1) | 1) - 1;\n }\n\n /**\n * An utility method to merge two point distance objects containing arrays of indices and squared distances.\n * \n * @static\n * @param {object} a An object in the form of { indices: TypedArray, distancesSq: TypedArray }.\n * @param {object} b An object in the form of { indices: TypedArray, distancesSq: TypedArray }.\n * @returns {object} The object with merged indices and squared distances.\n */\n static mergePointDistances(a, b) {\n let newObj = {};\n\n newObj.indices = Utils.concatTypedArrays(a.indices, b.indices);\n newObj.distancesSq = Utils.concatTypedArrays(a.distancesSq, b.distancesSq);\n \n return newObj;\n }\n\n /**\n * Checks whether or not the number is an integer.\n * \n * @param {number} n A number.\n * @returns A boolean whether or not the number is an integer.\n */\n static isInt(n){\n return Number(n) === n && n % 1 === 0;\n }\n\n /**\n * Checks whether or not the number is a float.\n * \n * @param {number} n A number.\n * @returns A boolean whether or not the number is a float.\n */\n static isFloat(n){\n return Number(n) === n && n % 1 !== 0;\n }\n\n /**\n * A helper method enabling JSONP requests to an url.\n * \n * @param {String} url An url.\n * @param {Function} callback The callback to be called when the data is loaded.\n */\n static jsonp(url, callback) {\n let callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());\n window[callbackName] = function(response) {\n delete window[callbackName];\n document.body.removeChild(script);\n callback(response);\n };\n\n let script = document.createElement('script');\n script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;\n document.body.appendChild(script);\n }\n}\n\nUtils.DEG2RAD = Math.PI / 180.0;\n\nmodule.exports = Utils" }, { "alpha_fraction": 0.5873648524284363, "alphanum_fraction": 0.590779721736908, "avg_line_length": 26.046154022216797, "blob_id": "257a1790df2e937a9cc95c7a13f65f2829fdb704", "content_id": "cac642abdbd87fbf887d078897978656d19d6c5d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1757, "license_type": "permissive", "max_line_length": 96, "num_lines": 65, "path": "/src/Controls/FirstPersonControls.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst ControlsBase = require('../Controls/ControlsBase')\nconst Vector3f = require('../Math/Vector3f');\n\n/** A class representing orbital controls. */\nclass FirstPersonControls extends ControlsBase {\n\n /**\n * Creates an instance of FirstPersonControls.\n * @param {Renderer} renderer An instance of a Lore renderer.\n */\n constructor(renderer, radius) {\n super(renderer);\n\n this.up = Vector3f.up();\n this.renderer = renderer;\n this.camera = renderer.camera;\n this.canvas = renderer.canvas;\n\n this.camera.position = new Vector3f(radius, radius, radius);\n this.camera.updateProjectionMatrix();\n this.camera.updateViewMatrix();\n\n this.rotationLocked = false;\n\n let that = this;\n\n this.addEventListener('mousedrag', function (e) {\n that.update(e.e, e.source);\n });\n\n // Initial update\n this.update({\n x: 0,\n y: 0\n }, 'left');\n }\n\n /**\n * Update the camera (on mouse move, touch drag, mousewheel scroll, ...).\n * \n * @param {any} e A mouse or touch events data.\n * @param {String} source The source of the input ('left', 'middle', 'right', 'wheel', ...).\n * @returns {FirstPersonControls} Returns itself.\n */\n update(e, source) {\n if (source === 'left') {\n // Move forward here\n }\n\n // Update the camera\n let offset = this.camera.position.clone().subtract(this.lookAt);\n\n this.camera.position.copyFrom(this.lookAt).add(offset);\n this.camera.setLookAt(this.lookAt);\n this.camera.updateViewMatrix();\n\n this.raiseEvent('updated');\n\n return this;\n }\n}\n\nmodule.exports = FirstPersonControls;" }, { "alpha_fraction": 0.5718106031417847, "alphanum_fraction": 0.5999124646186829, "avg_line_length": 26.947010040283203, "blob_id": "8e8dbd3fb7e04b4ca432713b3b9303ae86023d4e", "content_id": "6660a9afe3e2270794a3722f91474e61bf793865", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 20568, "license_type": "permissive", "max_line_length": 166, "num_lines": 736, "path": "/src/Math/Quaternion.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst Vector3f = require('./Vector3f');\nconst Matrix4f = require('./Matrix4f');\n\n/** \n * A class representing a quaternion.\n * \n * @property {Float32Array} components A typed array storing the components of this quaternion.\n */\nclass Quaternion {\n /**\n * Creates an instance of Quaternion.\n * @param {Number} x The x component of the quaternion.\n * @param {Number} y The y component of the quaternion.\n * @param {Number} z The z component of the quaternion.\n * @param {Number} w The w component of the quaternion.\n */\n constructor(x, y, z, w) {\n if (arguments.length === 1) {\n this.components = new Float32Array(x);\n } else if (arguments.length === 2) {\n this.components = new Float32Array(4);\n this.setFromAxisAngle(x, y);\n } else {\n this.components = new Float32Array(4);\n this.components[0] = x || 0.0;\n this.components[1] = y || 0.0;\n this.components[2] = z || 0.0;\n this.components[3] = (w !== undefined) ? w : 1.0;\n }\n }\n\n /**\n * Get the x component of this quaternion.\n * \n * @returns {Number} The x component of this quaternion.\n */\n getX() {\n return this.components[0];\n }\n\n /**\n * Get the y component of this quaternion.\n * \n * @returns {Number} The y component of this quaternion.\n */\n getY() {\n return this.components[1];\n }\n\n /**\n * Get the z component of this quaternion.\n * \n * @returns {Number} The z component of this quaternion.\n */\n getZ() {\n return this.components[2];\n }\n\n /**\n * Get the w component of this quaternion.\n * \n * @returns {Number} The w component of this quaternion.\n */\n getW() {\n return this.components[3];\n }\n\n /**\n * Set the components of this quaternion.\n * \n * @param {Number} x The x component of this quaternion.\n * @param {Number} y The y component of this quaternion.\n * @param {Number} z The z component of this quaternion.\n * @param {Number} w The w component of this quaternion.\n * \n * @returns {Quaternion} Returns itself.\n */\n set(x, y, z, w) {\n this.components[0] = x;\n this.components[1] = y;\n this.components[2] = z;\n this.components[3] = w;\n\n return this;\n }\n\n /**\n * Set the x component of this quaternion.\n * \n * @param {Number} x The x component of this quaternion.\n * @returns {Quaternion} Returns itself.\n */\n setX(x) {\n this.components[0] = x;\n\n return this;\n }\n\n /**\n * Set the y component of this quaternion.\n * \n * @param {Number} y The y component of this quaternion.\n * @returns {Quaternion} Returns itself.\n */\n setY(y) {\n this.components[1] = y;\n\n return this;\n }\n\n /**\n * Set the z component of this quaternion.\n * \n * @param {Number} z The z component of this quaternion.\n * @returns {Quaternion} Returns itself.\n */\n setZ(z) {\n this.components[2] = z;\n\n return this;\n }\n\n /**\n * Set the w component of this quaternion.\n * \n * @param {Number} w The w component of this quaternion.\n * @returns {Quaternion} Returns itself.\n */\n setW(w) {\n this.components[3] = w;\n\n return this;\n }\n\n /**\n * Sets the quaternion from the axis angle representation.\n * \n * @param {Vector3f} axis The axis component.\n * @param {Number} angle The angle component.\n * @returns {Quaternion} Returns itself.\n */\n setFromAxisAngle(axis, angle) {\n // See:\n // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm\n\n // Normalize the axis. The resulting quaternion will be normalized as well\n let normAxis = Vector3f.normalize(axis);\n let halfAngle = angle / 2.0;\n let sinHalfAngle = Math.sin(halfAngle);\n\n this.components[0] = normAxis.components[0] * sinHalfAngle;\n this.components[1] = normAxis.components[1] * sinHalfAngle;\n this.components[2] = normAxis.components[2] * sinHalfAngle;\n this.components[3] = Math.cos(halfAngle);\n\n return this;\n }\n\n /**\n * Sets the quaternion from unit vectors.\n * \n * @param {Vector3f} from The from vector.\n * @param {Vector3f} to The to vector.\n * @returns {Quaternion} Returns itself.\n */\n setFromUnitVectors(from, to) {\n let v = null;\n let r = from.dot(to) + 1;\n\n if (r < 0.000001) {\n v = new Vector3f(0.0, 0.0, 0.0);\n r = 0;\n if (Math.abs(from.components[0]) > Math.abs(from.components[2]))\n v.set(-from.components[1], from.components[0], 0);\n else\n v.set(0, -from.components[2], from.components[1]);\n } else {\n v = Vector3f.cross(from, to);\n }\n\n this.set(v.components[0], v.components[1], v.components[2], r);\n this.normalize();\n\n return this;\n }\n\n /**\n * Set the quaternion based facing in a destionation direction.\n * \n * @param {Vector3f} source The source vector (the position).\n * @param {Vector3f} dest The destination vector.\n * @param {Vector3f} up The up vector of the source.\n * @returns {Quaternion} Returns itself.\n */\n lookAt(source, dest, up) {\n this.setFromMatrix(Matrix4f.lookAt(source, dest, up));\n\n return this;\n }\n\n /**\n * Get the square length of the quaternion.\n * \n * @returns {Number} The square of the length.\n */\n lengthSq() {\n return this.components[0] * this.components[0] +\n this.components[1] * this.components[1] +\n this.components[2] * this.components[2] +\n this.components[3] * this.components[3];\n }\n\n /**\n * Get the length of this quaternion.\n * \n * @returns {Number} The length.\n */\n length() {\n return Math.sqrt(this.lengthSq());\n }\n\n /**\n * Get the inverse of this quaternion.\n * \n * @returns {Quaternion} Returns itself.\n */\n inverse() {\n return this.conjugate().normalize();\n }\n\n /**\n * Normalizes this quaternion.\n * \n * @returns {Quaternion} Returns itself.\n */\n normalize() {\n let length = this.length();\n\n if (length === 0) {\n this.components[0] = 0.0;\n this.components[1] = 0.0;\n this.components[2] = 0.0;\n this.components[3] = 1.0;\n } else {\n let inv = 1 / length;\n this.components[0] *= inv;\n this.components[1] *= inv;\n this.components[2] *= inv;\n this.components[3] *= inv;\n }\n\n return this;\n }\n\n /**\n * Get the dot product of this and another quaternion.\n * \n * @param {Quaternion} q A quaternion.\n * @returns {Number} The dot product.\n */\n dot(q) {\n return this.components[0] * q.components[0] +\n this.components[1] * q.components[1] +\n this.components[2] * q.components[2] +\n this.components[3] * q.components[3];\n }\n\n /**\n * Multiply this quaternion with another (a * b).\n * \n * @param {Quaternion} b Another quaternion.\n * @returns {Quaternion} Returns itself.\n */\n multiplyA(b) {\n // See:\n // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm\n\n let x = this.components[0] * b.components[3] + this.components[3] * b.components[0] + this.components[1] * b.components[2] - this.components[2] * b.components[1];\n let y = this.components[1] * b.components[3] + this.components[3] * b.components[1] + this.components[2] * b.components[0] - this.components[0] * b.components[2];\n let z = this.components[2] * b.components[3] + this.components[3] * b.components[2] + this.components[0] * b.components[1] - this.components[1] * b.components[0];\n let w = this.components[3] * b.components[3] - this.components[0] * b.components[0] - this.components[1] * b.components[1] - this.components[2] * b.components[2];\n\n this.components[0] = x;\n this.components[1] = y;\n this.components[2] = z;\n this.components[3] = w;\n\n return this;\n }\n\n /**\n * Multiply another with this quaternion (a * b).\n * \n * @param {Quaternion} a Another quaternion.\n * @returns {Quaternion} Returns itself.\n */\n multiplyB(a) {\n // See:\n // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm\n\n let x = a.components[0] * this.components[3] + a.components[3] * this.components[0] + a.components[1] * this.components[2] - a.components[2] * this.components[1];\n let y = a.components[1] * this.components[3] + a.components[3] * this.components[1] + a.components[2] * this.components[0] - a.components[0] * this.components[2];\n let z = a.components[2] * this.components[3] + a.components[3] * this.components[2] + a.components[0] * this.components[1] - a.components[1] * this.components[0];\n let w = a.components[3] * this.components[3] - a.components[0] * this.components[0] - a.components[1] * this.components[1] - a.components[2] * this.components[2];\n\n this.components[0] = x;\n this.components[1] = y;\n this.components[2] = z;\n this.components[3] = w;\n\n return this;\n }\n\n /**\n * Multiply this quaternion with a scalar.\n * \n * @param {Number} s A scalar.\n * @returns {Quaternion} Returns itself.\n */\n multiplyScalar(s) {\n this.components[0] *= s;\n this.components[1] *= s;\n this.components[2] *= s;\n this.components[3] *= s;\n\n return this;\n }\n\n /**\n * Conjugate (* -1) this quaternion.\n * \n * @returns {Quaternion} Returns itself.\n */\n conjugate() {\n // See:\n // http://www.3dgep.com/understanding-quaternions/#Quaternion_Conjugate\n this.components[0] *= -1;\n this.components[1] *= -1;\n this.components[2] *= -1;\n\n return this;\n }\n\n /**\n * Add another quaternion to this one.\n * \n * @param {Quaternion} q A quaternion.\n * @returns {Quaternion} Returns itself.\n */\n add(q) {\n this.components[0] += q.components[0];\n this.components[1] += q.components[1];\n this.components[2] += q.components[2];\n this.components[3] += q.components[3];\n\n return this;\n }\n\n /**\n * Subtract another quaternion from this one.\n * \n * @param {Quaternion} q A quaternion.\n * @returns {Quaternion} Returns itself.\n */\n subtract(q) {\n this.components[0] -= q.components[0];\n this.components[1] -= q.components[1];\n this.components[2] -= q.components[2];\n this.components[3] -= q.components[3];\n\n return this;\n }\n\n /**\n * Rotate this quaternion around the x axis.\n * \n * @param {Number} angle An angle in radians.\n * @returns {Quaternion} Returns itself.\n */\n rotateX(angle) {\n let halfAngle = angle / 2.0;\n return this.multiplyA(\n new Quaternion(Math.sin(halfAngle), 0.0, 0.0, Math.cos(halfAngle))\n );\n }\n\n /**\n * Rotate this quaternion around the y axis.\n * \n * @param {Number} angle An angle in radians.\n * @returns {Quaternion} Returns itself.\n */\n rotateY(angle) {\n let halfAngle = angle / 2.0;\n return this.multiplyA(\n new Quaternion(0.0, Math.sin(halfAngle), 0.0, Math.cos(halfAngle))\n );\n }\n\n /**\n * Rotate this quaternion around the y axis.\n * \n * @param {Number} angle An angle in radians.\n * @returns {Quaternion} Returns itself.\n */\n rotateZ(angle) {\n let halfAngle = angle / 2.0;\n return this.multiplyA(\n new Quaternion(0.0, 0.0, Math.sin(halfAngle), Math.cos(halfAngle))\n );\n }\n\n toAxisAngle() {\n // It seems like this isn't numerically stable. This could be solved\n // by some checks as described here:\n // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/\n // or here:\n // https://www.flipcode.com/documents/matrfaq.html#Q57\n // However, this function currently isn't used.\n console.warn('The method toAxisAngle() has not been implemented.')\n }\n\n /**\n * Create a rotation matrix from this quaternion.\n * \n * @returns {Matrix4f} A rotation matrix representation of this quaternion.\n */\n toRotationMatrix() {\n let i = this.components[0];\n let j = this.components[1];\n let k = this.components[2];\n let r = this.components[3];\n\n let ii = i * i;\n let ij = i * j;\n let ik = i * k;\n let ir = i * r;\n\n let jr = j * r;\n let jj = j * j;\n let jk = j * k;\n\n let kk = k * k;\n let kr = k * r;\n\n let mat = new Matrix4f();\n\n mat.entries[0] = 1 - 2 * (jj + kk);\n mat.entries[1] = 2 * (ij + kr);\n mat.entries[2] = 2 * (ik - jr);\n mat.entries[4] = 2 * (jk - kr);\n mat.entries[5] = 1 - 2 * (ii + kk);\n mat.entries[6] = 2 * (jk + ir);\n mat.entries[8] = 2 * (ik + jr);\n mat.entries[9] = 2 * (jk - ir);\n mat.entries[10] = 1 - 2 * (ii + jj);\n\n return mat;\n }\n\n /**\n * Set this quaternion from a (rotation) matrix.\n * \n * @param {Matrix4f} m \n * @returns {Quaternion} Returns itself.\n */\n setFromMatrix(m) {\n // As in three.js, this is an implementation straight from:\n // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm\n\n // Get the rotation matrix (if m is a Matrix4f)\n let m00 = m.entries[0],\n m01 = m.entries[4],\n m02 = m.entries[8];\n let m10 = m.entries[1],\n m11 = m.entries[5],\n m12 = m.entries[9];\n let m20 = m.entries[2],\n m21 = m.entries[6],\n m22 = m.entries[10];\n\n let t = m00 + m11 + m22;\n\n if (t > 0) {\n let s = 0.5 / Math.sqrt(t + 1.0);\n this.components[0] = (m21 - m12) * s;\n this.components[1] = (m02 - m20) * s;\n this.components[2] = (m10 - m01) * s;\n this.components[3] = 0.25 / s;\n } else if (m00 > m11 && m00 > m22) {\n let s = 2.0 * Math.sqrt(1.0 + m00 - m11 - m22);\n this.components[0] = 0.25 * s;\n this.components[1] = (m01 + m10) / s;\n this.components[2] = (m02 + m20) / s;\n this.components[3] = (m21 - m12) / s;\n } else if (m11 > m22) {\n let s = 2.0 * Math.sqrt(1.0 + m11 - m00 - m22);\n this.components[0] = (m01 + m10) / s;\n this.components[1] = 0.25 * s;\n this.components[2] = (m12 + m21) / s;\n this.components[3] = (m02 - m20) / s;\n } else {\n let s = 2.0 * Math.sqrt(1.0 + m22 - m00 - m11);\n this.components[0] = (m02 + m20) / s;\n this.components[1] = (m12 + m21) / s;\n this.components[2] = 0.25 * s;\n this.components[3] = (m10 - m01) / s;\n }\n\n return this;\n }\n\n /**\n * Clone this quaternion.\n * \n * @returns {Quaternion} A clone of this quaternion.\n */\n clone() {\n return new Quaternion(this.components[0], this.components[1],\n this.components[2], this.components[3]);\n }\n\n /**\n * Checks whether the entries of this quaternion match another one.\n * \n * @param {Quaternion} q A quaternion.\n * @returns {Boolean} A boolean representing whether the entries of the two quaternions match.\n */\n equals(q) {\n return this.components[0] === q.components[0] &&\n this.components[1] === q.components[1] &&\n this.components[2] === q.components[2] &&\n this.components[3] === q.components[3];\n }\n\n /**\n * Returns a string representation of this quaternion.\n * \n * @returns {String} A string representing this quaternion.\n */\n toString() {\n return 'x: ' + this.getX() + ', y: ' + this.getY() + ', z: ' +\n this.getZ() + ', w: ' + this.getW();\n }\n\n /**\n * Calculate the dot product of two quaternions.\n * \n * @static\n * @param {Quaternion} q A quaternion.\n * @param {Quaternion} p A quaternion.\n * @returns {Number} The dot product.\n */\n static dot(q, p) {\n return new Quaternion(q.components[0] * p.components[0] +\n q.components[1] * p.components[1] +\n q.components[2] * p.components[2] +\n q.components[3] * p.components[3]);\n }\n\n /**\n * Multiply (cross product) two quaternions.\n * \n * @static\n * @param {Quaternion} a A quaternion.\n * @param {Quaternion} b A quaternion.\n * @returns {Quaternion} The cross product quaternion.\n */\n static multiply(a, b) {\n return new Quaternion(\n a.components[0] * b.components[3] + a.components[3] * b.components[0] +\n a.components[1] * b.components[2] - a.components[2] * b.components[1],\n a.components[1] * b.components[3] + a.components[3] * b.components[1] +\n a.components[2] * b.components[0] - a.components[0] * b.components[2],\n a.components[2] * b.components[3] + a.components[3] * b.components[2] +\n a.components[0] * b.components[1] - a.components[1] * b.components[0],\n a.components[3] * b.components[3] + a.components[0] * b.components[0] +\n a.components[1] * b.components[1] - a.components[2] * b.components[2]\n );\n }\n\n /**\n * Multiplies a quaternion with a scalar.\n * \n * @static\n * @param {Quaternion} q A quaternion.\n * @param {Number} s A scalar.\n * @returns {Quaternion} The resulting quaternion.\n */\n static multiplyScalar(q, s) {\n return new Quaternion(q.components[0] * s, q.components[1] * s,\n q.components[2] * s, q.components[3] * s);\n }\n\n /**\n * Inverse a quaternion.\n * \n * @static\n * @param {Quaternion} q A quaternion.\n * @returns {Quaternion} The resulting quaternion.\n */\n static inverse(q) {\n let p = new Quaternion(q.components);\n return p.conjugate().normalize();\n }\n\n /**\n * Normalize a quaternion.\n * \n * @static\n * @param {Quaternion} q A quaternion.\n * @returns {Quaternion} The resulting quaternion.\n */\n static normalize(q) {\n let length = q.length();\n\n if (length === 0) {\n return new Quaternion(0.0, 0.0, 0.0, 1.0);\n } else {\n let inv = 1 / length;\n return new Quaternion(q.components[0] * inv, q.components[1] * inv,\n q.components[2] * inv, q.components[3] * inv);\n }\n }\n\n /**\n * Conjugate (* -1) a quaternion.\n * \n * @static\n * @param {Quaternion} q A quaternion.\n * @returns {Quaternion} The resulting quaternion.\n */\n static conjugate(q) {\n return new Quaternion(q.components[0] * -1, q.components[1] * -1,\n q.components[2] * -1, q.components[3]);\n }\n\n /**\n * Sum two quaternions.\n * \n * @static\n * @param {Quaternion} q A quaternion.\n * @param {Quaternion} p A quaternion.\n * @returns {Quaternion} The resulting quaternion.\n */\n static add(q, p) {\n return new Quaternion(q.components[0] + p.components[0],\n q.components[1] + p.components[1],\n q.components[2] + p.components[2],\n q.components[3] + p.components[3]);\n }\n\n /**\n * Subtract a quaternion from another (q - p).\n * \n * @static\n * @param {Quaternion} q A quaternion.\n * @param {Quaternion} p A quaternion.\n * @returns {Quaternion} The resulting quaternion.\n */\n static subtract(q, p) {\n return new Quaternion(q.components[0] - p.components[0],\n q.components[1] - p.components[1],\n q.components[2] - p.components[2],\n q.components[3] - p.components[3]);\n }\n\n /**\n * Create a quaternion from a matrix.\n * \n * @static\n * @param {Matrix4f} m A matrix.\n * @returns {Quaternion} The resulting quaternion.\n */\n static fromMatrix(m) {\n let q = new Quaternion();\n q.setFromMatrix(m);\n return q;\n }\n\n /**\n * Interpolate between two quaternions (t is between 0 and 1).\n * \n * @static\n * @param {Quaternion} q The source quaternion.\n * @param {Quaternion} p The target quaternion.\n * @param {Number} t The interpolation value / percentage (between 0 an 1).\n * @returns {Quaternion} The resulting quaternion.\n */\n static slerp(q, p, t) {\n // See:\n // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/\n\n if (t === 0) return new Quaternion(q.components);\n if (t === 1) return new Quaternion(p.components);\n\n let tmp = new Quaternion(p.components);\n\n // The angle between quaternions\n let cosHalfTheta = q.components[0] * tmp.components[0] +\n q.components[1] * tmp.components[1] +\n q.components[2] * tmp.components[2] +\n q.components[3] * tmp.components[3];\n\n if (cosHalfTheta < 0) {\n tmp.multiplyScalar(-1);\n cosHalfTheta = -cosHalfTheta;\n }\n\n if (Math.abs(cosHalfTheta) >= 1.0) {\n return new Quaternion(q.components);\n }\n\n let halfTheta = Math.acos(cosHalfTheta);\n let sinHalfTheta = Math.sqrt(1.0 - cosHalfTheta * cosHalfTheta);\n\n if (Math.abs(sinHalfTheta) < 0.001) {\n return new Quaternion(q.components[0] * 0.5 + tmp.components[0] * 0.5,\n q.components[1] * 0.5 + tmp.components[1] * 0.5,\n q.components[2] * 0.5 + tmp.components[2] * 0.5,\n q.components[3] * 0.5 + tmp.components[3] * 0.5);\n }\n\n let ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta;\n let ratioB = Math.sin(t * halfTheta) / sinHalfTheta;\n\n return new Quaternion(q.components[0] * ratioA + tmp.components[0] * ratioB,\n q.components[1] * ratioA + tmp.components[1] * ratioB,\n q.components[2] * ratioA + tmp.components[2] * ratioB,\n q.components[3] * ratioA + tmp.components[3] * ratioB);\n }\n}\n\nmodule.exports = Quaternion" }, { "alpha_fraction": 0.6596434116363525, "alphanum_fraction": 0.6639654040336609, "avg_line_length": 30.117647171020508, "blob_id": "cc4221bd5759d8be13c0aa17f8dd0e28aa21b832", "content_id": "2c33283e9c52d3ca396a8408c3b1516e74702b2b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3702, "license_type": "permissive", "max_line_length": 174, "num_lines": 119, "path": "/src/Helpers/HelperBase.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst Shader = require('../Core/Shader');\nconst Geometry = require('../Core/Geometry');\nconst Node = require('../Core/Node');\nconst Shaders = require('../Shaders');\n\n/** \n * The base class for helper classes.\n * \n * @property {Renderer} renderer An instance of Lore.Renderer.\n * @property {Shader} shader The shader associated with this helper.\n * @property {Geometry} geometry The geometry associated with this helper.\n */\nclass HelperBase extends Node {\n /**\n * Creates an instance of HelperBase.\n * \n * @param {Renderer} renderer A Lore.Renderer object.\n * @param {String} geometryName The name of this geometry.\n * @param {String} shaderName The name of the shader used to render the geometry.\n */\n constructor(renderer, geometryName, shaderName) {\n super();\n\n // Check whether the shader requires WebGL 2.0, if it does and the\n // machine doesn't support it, go to callback.\n if (Shaders[shaderName].glVersion === 2 && !renderer.webgl2) {\n console.warn('Switching from ' + shaderName + ' to fallback shader ' + \n Shaders[shaderName].fallback + ' due to missing WebGL2 support.');\n shaderName = Shaders[shaderName].fallback;\n }\n\n this.renderer = renderer;\n this.shader = Shaders[shaderName].clone();\n this.geometry = this.renderer.createGeometry(geometryName, shaderName);\n }\n\n /**\n * Checks whether the geometry associated with this helper has an attribute with a given name.\n * \n * @param {String} name The name of the attribute.\n * @returns {boolean} A boolean indicating whether an attribute with a the given name is present.\n */\n hasAttribute(name) {\n return name in this.geometry.attributes;\n }\n\n /**\n * Set the value (a typed array) of an attribute.\n * \n * @param {String} name The name of the attribute. \n * @param {number[]|Array|Float32Array} data A typed array containing the attribute values.\n */\n setAttribute(name, data) {\n this.geometry.addAttribute(name, data);\n }\n\n /**\n * Get the value of an attribute (usually a typed array).\n * \n * @param {String} name The name of the attribute.\n * @returns {number[]|Array|Float32Array} Usually, a typed array containing the attribute values.\n */\n getAttribute(name) {\n return this.geometry.attributes[name].data;\n }\n\n /**\n * Update a the value of an attribute at a specific index and marks the attribute as stale.\n * \n * @param {String} name The name of the attribute.\n * @param {Number} index The index of the value to be updated.\n * @param {number[]|Array|Float32Array} value Usually, a typed array or array with the length of the attribute values (3 for x, y, z coordinates) containing the new values.\n */\n updateAttribute(name, index, value) {\n let attr = this.geometry.attributes[name];\n\n let j = index * attr.attributeLength;\n\n for (let i = 0; i < attr.attributeLength; i++) {\n attr.data[j + i] = value[i] || attr.data[j + i];\n }\n\n attr.stale = true;\n }\n\n /**\n * Updates all the values in the attribute and marks the attribute as stale.\n * \n * @param {String} name The name of the attribute.\n * @param {number[]|Array|Float32Array} values A typed array containing the new attribute values.\n */\n updateAttributeAll(name, values) {\n let attr = this.geometry.attributes[name];\n\n for (let i = 0; i < attr.data.length; i++) {\n attr.data[i] = values[i];\n }\n\n attr.stale = true;\n }\n\n /**\n * Calls the draw method of the underlying geometry.\n */\n draw() {\n this.geometry.draw(this.renderer);\n }\n\n /**\n * Destructor for the helper (mainly used for OctreeHelpers to clean up events).\n */\n destruct() {\n\n }\n}\n\nmodule.exports = HelperBase" }, { "alpha_fraction": 0.5642684102058411, "alphanum_fraction": 0.5650768280029297, "avg_line_length": 27.779069900512695, "blob_id": "05bfb582770ee72913146edeb3827be66b706368", "content_id": "7670892698bc9c602341a967c839ce94b7f0764f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2474, "license_type": "permissive", "max_line_length": 141, "num_lines": 86, "path": "/src/IO/FileReaderBase.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst Utils = require('../Utils/Utils');\n\n/** \n * An abstract class representing the base for file reader implementations. \n * \n * @property {String} source The source of the file. This is either a input element (type=file) or a URL. If it is a URL, set local to true.\n * */\nclass FileReaderBase {\n /**\n * Creates an instance of FileReaderBase.\n * \n * @param {String} source The source of the file. This is either a input element (type=file) or a URL. If it is a URL, set local to true.\n * @param {Boolean} [local=true] A boolean indicating whether or not the source is local (a file input) or remote (a url).\n */\n constructor(source, local = true) {\n this.source = source;\n this._eventListeners = {};\n \n let that = this;\n\n if (local) {\n this.element = document.getElementById(this.source);\n\n this.element.addEventListener('click', function() {\n this.value = null;\n });\n\n this.element.addEventListener('change', function() {\n let fileReader = new FileReader();\n\n fileReader.onload = function() {\n that.loaded(fileReader.result);\n }\n\n fileReader.readAsBinaryString(this.files[0]);\n });\n } else {\n Utils.jsonp(source, function(response) {\n that.loaded(response);\n });\n }\n }\n\n /**\n * Add an event listener.\n * \n * @param {String} eventName The name of the event.\n * @param {Function} callback A callback function associated with the event name.\n */\n addEventListener(eventName, callback) {\n if(!this._eventListeners[eventName]) {\n this._eventListeners[eventName] = [];\n }\n\n this._eventListeners[eventName].push(callback);\n }\n\n /**\n * Raise an event. To be called by inheriting classes.\n * \n * @param {String} eventName The name of the event.\n * @param {any} data Data to be passed to the handler.\n */\n raiseEvent(eventName, data) {\n if(!this._eventListeners[eventName]) {\n return;\n }\n\n for(let i = 0; i < this._eventListeners[eventName].length; i++) {\n this._eventListeners[eventName][i](data);\n }\n }\n\n /**\n * To be overwritten by inheriting classes.\n * \n * @param {any} data \n */\n loaded(data) {\n\n }\n}\n\nmodule.exports = FileReaderBase" }, { "alpha_fraction": 0.4878358840942383, "alphanum_fraction": 0.5001815557479858, "avg_line_length": 32.79754638671875, "blob_id": "3408b13f6aeeca21bcab673cdff32e5ce1729ae4", "content_id": "b67d5fafe123f6ae7b4f688e9003f34acb10756e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5508, "license_type": "permissive", "max_line_length": 141, "num_lines": 163, "path": "/src/IO/MatrixFileReader.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst FileReaderBase = require('./FileReaderBase');\nconst Utils = require('../Utils/Utils');\n\n/** A class representing a matrix file reader. */\nclass MatrixFileReader extends FileReaderBase {\n /**\n * Creates an instance of MatrixFileReader.\n * @param {String} source The source of the file. This is either a input element (type=file) or a URL. If it is a URL, set local to true.\n * @param {any} options Options. See documentation for details.\n * @param {boolean} [local=true] A boolean indicating whether or not the source is local (a file input) or remote (a url).\n */\n constructor(source, options, local = true) {\n super(source, local);\n\n this.defaults = {\n elementSeperator: '\\t',\n valueSeparator: ';',\n replaceNaNWith: 'NaN',\n skipNaN: true,\n types: []\n }\n\n this.opts = Utils.extend(true, this.defaults, options);\n this.types = this.opts.types;\n this.columns = {};\n\n if (this.types.length === 0) {\n throw('When reading data from a file, the types have to be specified.');\n }\n\n // Add the types for the indices\n this.opts.types.unshift('Int32Array');\n this.opts.types.unshift('Int32Array');\n this.opts.types.unshift('Int32Array');\n }\n\n /**\n * Called when the data is loaded, will raise the \"loaded\" event.\n * \n * @param {any} data The data loaded from the file or url.\n * @returns {MatrixFileReader} Itself.\n */\n loaded(data) {\n data = data.replace('\\n\\n', '\\n');\n data = data.replace(/^\\s+|\\s+$/g, '');\n\n if (this.opts.replaceNaNWith !== 'NaN') {\n data = data.replace('NaN', this.opts.replaceNaNWith);\n }\n\n let lines = data.split('\\n');\n let nRows = lines.length;\n let nColumns = lines[0].split(this.opts.elementSeperator).length;\n // Including the indices (x, y, z), therefore + 3\n let nValues = lines[0].split(this.opts.elementSeperator)[0].split(this.opts.valueSeparator).length + 3;\n \n if (this.types.length !== nValues || this.types.length + nValues === 0) {\n let values = lines[0].split(this.opts.valueSeparator);\n \n this.types = [];\n for (let i = 0; i < values.length; i++) {\n if(Utils.isFloat(parseFloat(values[i], 10))) {\n this.types.push('Float32Array');\n } else if (Utils.isInt(parseFloat(values[i], 10))) {\n this.types.push('Int32Array');\n } else {\n this.types.push('StringArray');\n }\n }\n }\n \n for (var i = 0; i < nValues; i++) {\n this._createArray(i, this.types[i], nRows * nColumns);\n }\n\n let actualLength = 0;\n\n for (var i = 0; i < nRows; i++) {\n let row = lines[i].split(this.opts.elementSeperator);\n\n if (row.length === 0) {\n continue;\n }\n\n for (var j = 0; j < nColumns; j++) {\n if(!row[j]) {\n continue;\n }\n \n let values = row[j].split(this.opts.valueSeparator);\n\n if (this.opts.skipNaN) {\n let skip = false;\n\n for (var k = 0; k < values.length; k++) {\n if (isNaN(values[k])) {\n skip = true;\n break;\n }\n }\n\n if (skip) {\n continue;\n }\n }\n\n this.columns[0][actualLength] = i;\n this.columns[1][actualLength] = j;\n // Set zero for 2D matrix\n this.columns[2][actualLength] = 0;\n\n for (var k = 0; k < values.length; k++) {\n this.columns[k + 3][actualLength] = values[k];\n }\n\n actualLength++;\n }\n }\n\n this._resizeArrays(actualLength);\n\n this.raiseEvent('loaded', this.columns);\n \n return this;\n }\n\n _resizeArrays(length) {\n // Might need polyfill\n for (var i = 0; i < this.columns.length; i++) {\n this.columns[i] = this.columns[i].slice(0, length);\n }\n }\n\n _createArray(index, type, length) {\n if (type == 'Int8Array') {\n this.columns[index] = new Int8Array(length);\n } else if (type == 'Uint8Array') {\n this.columns[index] = new Uint8Array(length);\n } else if (type == 'Uint8ClampedArray') {\n this.columns[index] = new Uint8ClampedArray(length);\n } else if (type == 'Int16Array') {\n this.columns[index] = new Int16Array(length);\n } else if (type == 'Uint16Array') {\n this.columns[index] = new Uint16Array(length);\n } else if (type == 'Int32Array') {\n this.columns[index] = new Int32Array(length);\n } else if (type == 'Uint32Array') {\n this.columns[index] = new Uint32Array(length);\n } else if (type == 'Float32Array') {\n this.columns[index] = new Float32Array(length);\n } else if (type == 'Float64Array') {\n this.columns[index] = new Float64Array(length);\n } else {\n this.columns[index] = new Array(length);\n }\n\n return this;\n }\n}\n\nmodule.exports = MatrixFileReader" }, { "alpha_fraction": 0.5003762245178223, "alphanum_fraction": 0.527213454246521, "avg_line_length": 35.587154388427734, "blob_id": "cf978bef359cf9788bbfb31da3f6feeb78fd04f3", "content_id": "36a0ec012c7802c2868dc17be8bf279cae623e4e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3987, "license_type": "permissive", "max_line_length": 151, "num_lines": 109, "path": "/example/flybrain3.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "(function() {\n let lore = Lore.init('lore', {\n clearColor: '#222222',\n enableTransparency: true,\n alphaBlending: true\n });\n \n let fileReader = new Lore.IO.CsvFileReader('input-upload', {\n cols: [0, 1, 2, 3],\n types: ['Uint16Array', 'Uint16Array', 'Uint16Array', 'Float32Array']\n });\n let pointHelper = null;\n let octreeHelper = null;\n let original_data = null;\n\n fileReader.addEventListener('loaded', function(data) {\n original_data = data;\n pointHelper = new Lore.Helpers.PointHelper(lore, 'Seppli', 'smoothCircle');\n pointHelper.setPositionsXYZHSS(data['x'], data['y'], data['z'], data['c'], 1.0, 1.0)\n pointHelper.setPointScale(1.0);\n pointHelper.setFog([0.05, 0.05, 0.05, 1.0], 6.0);\n pointHelper.addFilter('hueRange', new Lore.Filters.InRangeFilter('color', 0, 0.22, 0.25));\n \n lore.controls.setLookAt(pointHelper.getCenter());\n lore.controls.setRadius(pointHelper.getMaxRadius());\n\n octreeHelper = new Lore.Helpers.OctreeHelper(lore, 'OctreeGeometry', 'tree', pointHelper, {\n visualize: false\n });\n\n octreeHelper.addEventListener('hoveredchanged', function(e) {\n let indicator = document.getElementById('indicator');\n let data = document.getElementById('data');\n\n if (e.e) {\n indicator.style.opacity = 1.0;\n indicator.style.left = (e.e.screenPosition[0] - 2) + 'px';\n indicator.style.top = (e.e.screenPosition[1] - 10) + 'px';\n data.innerHTML = '(' + original_data['x'][e.e.index] + ',' + original_data['y'][e.e.index] + ',' + original_data['z'][e.e.index] + ')';\n } else {\n indicator.style.opacity = 0.0;\n data.innerHTML = '';\n }\n });\n });\n\n document.getElementById('input-cutoff').addEventListener('input', function() {\n let val = document.getElementById('input-cutoff').value;\n pointHelper.setCutoff(val);\n });\n\n let isFrontView = false;\n document.getElementById('button-frontview').addEventListener('click', function() {\n if (!isFrontView) {\n lore.controls.setFrontView();\n isFrontView = true;\n } else {\n lore.controls.setFreeView();\n isFrontView = false;\n }\n });\n\n document.addEventListener('keydown', function(e) {\n if (e.keyCode === 48) {\n let filter = pointHelper.getFilter('hueRange');\n filter.reset();\n } else if (e.keyCode === 49) {\n let filter = pointHelper.getFilter('hueRange');\n filter.setMin(0.0);\n filter.setMax(0.05);\n filter.filter();\n } else if (e.keyCode == 50) {\n let filter = pointHelper.getFilter('hueRange');\n filter.setMin(0.1);\n filter.setMax(0.15);\n filter.filter();\n } else if (e.keyCode == 51) {\n let filter = pointHelper.getFilter('hueRange');\n filter.setMin(0.2);\n filter.setMax(0.25);\n filter.filter();\n } else if (e.keyCode == 52) {\n let filter = pointHelper.getFilter('hueRange');\n filter.setMin(0.4);\n filter.setMax(0.45);\n filter.filter();\n } else if (e.keyCode == 53) {\n let filter = pointHelper.getFilter('hueRange');\n filter.setMin(0.6);\n filter.setMax(0.65);\n filter.filter();\n } else if (e.keyCode == 54) {\n let filter = pointHelper.getFilter('hueRange');\n filter.setMin(0.8);\n filter.setMax(0.85);\n filter.filter();\n } else if (e.keyCode == 55) {\n \n } else if (e.keyCode == 56) {\n \n } else if (e.keyCode == 57) {\n \n } else if (e.keyCode == 58) {\n \n } else if (e.keyCode == 59) {\n \n }\n });\n})();" }, { "alpha_fraction": 0.3867018222808838, "alphanum_fraction": 0.49051254987716675, "avg_line_length": 27.100664138793945, "blob_id": "74ae22eee809017335fd7477777a83632643f318", "content_id": "2cc381af23f05a373e643677360fd9a25d721a01", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 25402, "license_type": "permissive", "max_line_length": 113, "num_lines": 904, "path": "/src/Math/Matrix4f.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst Vector3f = require('./Vector3f');\n\n/** A class representing a 4x4 float matrix */\nclass Matrix4f {\n // Do NOT go double precision on GPUs!!!\n // See:\n // http://stackoverflow.com/questions/2079906/float-vs-double-on-graphics-hardware\n\n /**\n * Creates an instance of Matrix4f.\n * @param {Float32Array} [entries=new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])] \n */\n constructor(entries = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])) {\n this.entries = entries;\n }\n\n /**\n * \n * \n * @param {Number} m00 A matrix entry.\n * @param {Number} m10 A matrix entry.\n * @param {Number} m20 A matrix entry.\n * @param {Number} m30 A matrix entry.\n * @param {Number} m01 A matrix entry.\n * @param {Number} m11 A matrix entry.\n * @param {Number} m21 A matrix entry.\n * @param {Number} m31 A matrix entry.\n * @param {Number} m02 A matrix entry.\n * @param {Number} m12 A matrix entry.\n * @param {Number} m22 A matrix entry.\n * @param {Number} m32 A matrix entry.\n * @param {Number} m03 A matrix entry.\n * @param {Number} m13 A matrix entry.\n * @param {Number} m23 A matrix entry.\n * @param {Number} m33 A matrix entry.\n * @returns {Matrix4f} Returns itself.\n */\n set(m00, m10, m20, m30, m01, m11, m21, m31, m02, m12, m22, m32, m03, m13, m23, m33) {\n this.entries.set([m00, m10, m20, m30,\n m01, m11, m21, m31,\n m02, m12, m22, m32,\n m03, m13, m23, m33\n ]);\n\n return this;\n }\n\n /**\n * Sets all entries in the matrix to zero.\n * \n * @returns {Matrix4f} Returns itself.\n */\n setZero() {\n return this;\n }\n\n /**\n * Multiplies this matrix with another matrix (a * b).\n * \n * @param {any} b Another matrix.\n * @returns {Matrix4f} Returns itself.\n */\n multiplyA(b) {\n // First, store the values in local variables.\n // See:\n // http://blog.tojicode.com/2010/06/stupidly-fast-webgl-matricies.html\n\n let a00 = this.entries[0],\n a01 = this.entries[4],\n a02 = this.entries[8],\n a03 = this.entries[12];\n let a10 = this.entries[1],\n a11 = this.entries[5],\n a12 = this.entries[9],\n a13 = this.entries[13];\n let a20 = this.entries[2],\n a21 = this.entries[6],\n a22 = this.entries[10],\n a23 = this.entries[14];\n let a30 = this.entries[3],\n a31 = this.entries[7],\n a32 = this.entries[11],\n a33 = this.entries[15];\n\n let b00 = b.entries[0],\n b01 = b.entries[4],\n b02 = b.entries[8],\n b03 = b.entries[12];\n let b10 = b.entries[1],\n b11 = b.entries[5],\n b12 = b.entries[9],\n b13 = b.entries[13];\n let b20 = b.entries[2],\n b21 = b.entries[6],\n b22 = b.entries[10],\n b23 = b.entries[14];\n let b30 = b.entries[3],\n b31 = b.entries[7],\n b32 = b.entries[11],\n b33 = b.entries[15];\n\n this.entries[0] = a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30;\n this.entries[1] = a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30;\n this.entries[2] = a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30;\n this.entries[3] = a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31;\n this.entries[4] = a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30;\n this.entries[5] = a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31;\n this.entries[6] = a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31;\n this.entries[7] = a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31;\n this.entries[8] = a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32;\n this.entries[9] = a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32;\n this.entries[10] = a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32;\n this.entries[11] = a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32;\n this.entries[12] = a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33;\n this.entries[13] = a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33;\n this.entries[14] = a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33;\n this.entries[15] = a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33;\n\n return this;\n }\n\n /**\n * Multiplies another matrix with this matrix (a * b).\n * \n * @param {any} a Another matrix.\n * @returns {Matrix4f} Returns itself.\n */\n multiplyB(a) {\n // First, store the values in local variables.\n // See:\n // http://blog.tojicode.com/2010/06/stupidly-fast-webgl-matricies.html\n\n let a00 = a.entries[0],\n a01 = a.entries[4],\n a02 = a.entries[8],\n a03 = a.entries[12];\n let a10 = a.entries[1],\n a11 = a.entries[5],\n a12 = a.entries[9],\n a13 = a.entries[13];\n let a20 = a.entries[2],\n a21 = a.entries[6],\n a22 = a.entries[10],\n a23 = a.entries[14];\n let a30 = a.entries[3],\n a31 = a.entries[7],\n a32 = a.entries[11],\n a33 = a.entries[15];\n\n let b00 = this.entries[0],\n b01 = this.entries[4],\n b02 = this.entries[8],\n b03 = this.entries[12];\n let b10 = this.entries[1],\n b11 = this.entries[5],\n b12 = this.entries[9],\n b13 = this.entries[13];\n let b20 = this.entries[2],\n b21 = this.entries[6],\n b22 = this.entries[10],\n b23 = this.entries[14];\n let b30 = this.entries[3],\n b31 = this.entries[7],\n b32 = this.entries[11],\n b33 = this.entries[15];\n\n this.entries[0] = a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30;\n this.entries[1] = a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30;\n this.entries[2] = a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30;\n this.entries[3] = a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31;\n this.entries[4] = a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30;\n this.entries[5] = a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31;\n this.entries[6] = a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31;\n this.entries[7] = a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31;\n this.entries[8] = a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32;\n this.entries[9] = a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32;\n this.entries[10] = a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32;\n this.entries[11] = a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32;\n this.entries[12] = a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33;\n this.entries[13] = a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33;\n this.entries[14] = a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33;\n this.entries[15] = a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33;\n\n return this;\n }\n\n /**\n * Set the scale component of this matrix.\n * \n * @param {Vector3f} vec The scaling vector.\n * @returns {Matrix4f} Returns itself.\n */\n scale(vec) {\n let x = vec.components[0];\n let y = vec.components[1];\n let z = vec.components[2];\n\n this.entries[0] *= x;\n this.entries[1] *= x;\n this.entries[2] *= x;\n this.entries[3] *= x;\n\n this.entries[4] *= y;\n this.entries[5] *= y;\n this.entries[6] *= y;\n this.entries[7] *= y;\n\n this.entries[8] *= z;\n this.entries[9] *= z;\n this.entries[10] *= z;\n this.entries[11] *= z;\n\n return this;\n }\n\n /**\n * Set the position component of this matrix.\n * \n * @param {any} vec The position vector.\n * @returns {Matrix4f} Returns itself.\n */\n setPosition(vec) {\n this.entries[12] = vec.components[0];\n this.entries[13] = vec.components[1];\n this.entries[14] = vec.components[2];\n\n return this;\n }\n\n /**\n * Set the rotation component of this matrix.\n * \n * @param {Quaternion} q A quaternion representing the rotation.\n * @returns {Matrix4f} Returns itself.\n */\n setRotation(q) {\n let x = q.components[0];\n let y = q.components[1];\n let z = q.components[2];\n let w = q.components[3];\n\n let x2 = x + x,\n y2 = y + y,\n z2 = z + z;\n let xx = x * x2,\n xy = x * y2,\n xz = x * z2;\n let yy = y * y2,\n yz = y * z2,\n zz = z * z2;\n let wx = w * x2,\n wy = w * y2,\n wz = w * z2;\n\n this.entries[0] = 1 - (yy + zz);\n this.entries[1] = xy + wz;\n this.entries[2] = xz - wy;\n this.entries[4] = xy - wz;\n this.entries[5] = 1 - (xx + zz);\n this.entries[6] = yz + wx;\n this.entries[8] = xz + wy;\n this.entries[9] = yz - wx;\n this.entries[10] = 1 - (xx + yy);\n\n this.entries[3] = 0.0;\n this.entries[7] = 0.0;\n this.entries[11] = 0.0;\n this.entries[12] = 0.0;\n this.entries[13] = 0.0;\n this.entries[14] = 0.0;\n this.entries[15] = 1.0;\n\n return this;\n }\n\n /**\n * Get the determinant of the matrix.\n * \n * @returns {Number} The determinant of this matrix.\n */\n determinant() {\n let a = this.entries;\n \n let a00 = a.entries[0],\n a01 = a.entries[4],\n a02 = a.entries[8],\n a03 = a.entries[12];\n let a10 = a.entries[1],\n a11 = a.entries[5],\n a12 = a.entries[9],\n a13 = a.entries[13];\n let a20 = a.entries[2],\n a21 = a.entries[6],\n a22 = a.entries[10],\n a23 = a.entries[14];\n let a30 = a.entries[3],\n a31 = a.entries[7],\n a32 = a.entries[11],\n a33 = a.entries[15];\n\n return (\n a30 * (\n a03 * a12 * a21 - a02 * a13 * a21 -\n a03 * a11 * a22 + a01 * a13 * a22 +\n a02 * a11 * a23 - a01 * a12 * a23\n ) +\n a31 * (\n a00 * a12 * a23 - a00 * a13 * a22 +\n a03 * a10 * a22 - a02 * a10 * a23 +\n a02 * a13 * a20 - a03 * a12 * a20\n ) +\n a32 * (\n a00 * a13 * a21 - a00 * a11 * a23 -\n a03 * a10 * a21 + a01 * a10 * a23 +\n a03 * a11 * a20 - a01 * a13 * a20\n ) +\n a33 * (-a02 * a11 * a20 - a00 * a12 * a21 +\n a00 * a11 * a22 + a02 * a10 * a21 -\n a01 * a10 * a22 + a01 * a12 * a20\n )\n );\n }\n\n /**\n * Decomposes the matrix into its positional, rotational and scaling component.\n * \n * @param {Vector3f} outPosition The positional component will be written to this vector.\n * @param {Quaternion} outQuaternion The rotational component will be written to this quaternion.\n * @param {Vector3f} outScale The scaling component will be written to this vector.\n * @returns {Matrix4f} Returns itself.\n */\n decompose(outPosition, outQuaternion, outScale) {\n let m = new Matrix4f();\n\n // The position is the simple one\n outPosition.set(this.entries[12], this.entries[13], this.entries[14]);\n\n // Calculate the scale\n let sx = Math.sqrt(this.entries[0] * this.entries[0] +\n this.entries[1] * this.entries[1] +\n this.entries[2] * this.entries[2]);\n\n let sy = Math.sqrt(this.entries[4] * this.entries[4] +\n this.entries[5] * this.entries[5] +\n this.entries[6] * this.entries[6]);\n\n let sz = Math.sqrt(this.entries[8] * this.entries[8] +\n this.entries[9] * this.entries[9] +\n this.entries[10] * this.entries[10]);\n\n let det = this.determinant();\n\n if (det < 0) {\n sx = -sx;\n }\n\n // Set the scale\n outScale.set(sx, sy, sz);\n\n // Get the info for the quaternion, this involves scaling the rotation\n // See:\n // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/\n let isx = 1.0 / sx;\n let isy = 1.0 / sy;\n let isz = 1.0 / sz;\n\n m.entries.set(this.entries);\n\n m.entries[0] *= isx;\n m.entries[1] *= isx;\n m.entries[2] *= isx;\n\n m.entries[4] *= isy;\n m.entries[5] *= isy;\n m.entries[6] *= isy;\n\n m.entries[8] *= isz;\n m.entries[9] *= isz;\n m.entries[10] *= isz;\n\n outQuaternion.setFromMatrix(m);\n\n return this;\n }\n\n /**\n * Composes the matrix from the positional, rotational and scaling components.\n * \n * @param {Vector3f} position The positional component.\n * @param {Quaternion} quaternion The rotational component.\n * @param {Vector3f} scale The scaling component.\n * @returns {Matrix4f} Returns itself.\n */\n compose(position, quaternion, scale) {\n this.setRotation(quaternion);\n this.scale(scale);\n this.setPosition(position);\n\n return this;\n }\n\n /**\n * Inverts this matrix.\n * \n * @returns {Matrix4f} Returns itself.\n */\n invert() {\n // Fugly implementation lifted from MESA (originally in C++)\n let im = new Matrix4f();\n let m = this.entries;\n\n im.entries[0] = m[5] * m[10] * m[15] -\n m[5] * m[11] * m[14] -\n m[9] * m[6] * m[15] +\n m[9] * m[7] * m[14] +\n m[13] * m[6] * m[11] -\n m[13] * m[7] * m[10];\n\n im.entries[4] = -m[4] * m[10] * m[15] +\n m[4] * m[11] * m[14] +\n m[8] * m[6] * m[15] -\n m[8] * m[7] * m[14] -\n m[12] * m[6] * m[11] +\n m[12] * m[7] * m[10];\n\n im.entries[8] = m[4] * m[9] * m[15] -\n m[4] * m[11] * m[13] -\n m[8] * m[5] * m[15] +\n m[8] * m[7] * m[13] +\n m[12] * m[5] * m[11] -\n m[12] * m[7] * m[9];\n\n im.entries[12] = -m[4] * m[9] * m[14] +\n m[4] * m[10] * m[13] +\n m[8] * m[5] * m[14] -\n m[8] * m[6] * m[13] -\n m[12] * m[5] * m[10] +\n m[12] * m[6] * m[9];\n\n im.entries[1] = -m[1] * m[10] * m[15] +\n m[1] * m[11] * m[14] +\n m[9] * m[2] * m[15] -\n m[9] * m[3] * m[14] -\n m[13] * m[2] * m[11] +\n m[13] * m[3] * m[10];\n\n im.entries[5] = m[0] * m[10] * m[15] -\n m[0] * m[11] * m[14] -\n m[8] * m[2] * m[15] +\n m[8] * m[3] * m[14] +\n m[12] * m[2] * m[11] -\n m[12] * m[3] * m[10];\n\n im.entries[9] = -m[0] * m[9] * m[15] +\n m[0] * m[11] * m[13] +\n m[8] * m[1] * m[15] -\n m[8] * m[3] * m[13] -\n m[12] * m[1] * m[11] +\n m[12] * m[3] * m[9];\n\n im.entries[13] = m[0] * m[9] * m[14] -\n m[0] * m[10] * m[13] -\n m[8] * m[1] * m[14] +\n m[8] * m[2] * m[13] +\n m[12] * m[1] * m[10] -\n m[12] * m[2] * m[9];\n\n im.entries[2] = m[1] * m[6] * m[15] -\n m[1] * m[7] * m[14] -\n m[5] * m[2] * m[15] +\n m[5] * m[3] * m[14] +\n m[13] * m[2] * m[7] -\n m[13] * m[3] * m[6];\n\n im.entries[6] = -m[0] * m[6] * m[15] +\n m[0] * m[7] * m[14] +\n m[4] * m[2] * m[15] -\n m[4] * m[3] * m[14] -\n m[12] * m[2] * m[7] +\n m[12] * m[3] * m[6];\n\n im.entries[10] = m[0] * m[5] * m[15] -\n m[0] * m[7] * m[13] -\n m[4] * m[1] * m[15] +\n m[4] * m[3] * m[13] +\n m[12] * m[1] * m[7] -\n m[12] * m[3] * m[5];\n\n im.entries[14] = -m[0] * m[5] * m[14] +\n m[0] * m[6] * m[13] +\n m[4] * m[1] * m[14] -\n m[4] * m[2] * m[13] -\n m[12] * m[1] * m[6] +\n m[12] * m[2] * m[5];\n\n im.entries[3] = -m[1] * m[6] * m[11] +\n m[1] * m[7] * m[10] +\n m[5] * m[2] * m[11] -\n m[5] * m[3] * m[10] -\n m[9] * m[2] * m[7] +\n m[9] * m[3] * m[6];\n\n im.entries[7] = m[0] * m[6] * m[11] -\n m[0] * m[7] * m[10] -\n m[4] * m[2] * m[11] +\n m[4] * m[3] * m[10] +\n m[8] * m[2] * m[7] -\n m[8] * m[3] * m[6];\n\n im.entries[11] = -m[0] * m[5] * m[11] +\n m[0] * m[7] * m[9] +\n m[4] * m[1] * m[11] -\n m[4] * m[3] * m[9] -\n m[8] * m[1] * m[7] +\n m[8] * m[3] * m[5];\n\n im.entries[15] = m[0] * m[5] * m[10] -\n m[0] * m[6] * m[9] -\n m[4] * m[1] * m[10] +\n m[4] * m[2] * m[9] +\n m[8] * m[1] * m[6] -\n m[8] * m[2] * m[5];\n\n let det = m[0] * im.entries[0] +\n m[1] * im.entries[4] +\n m[2] * im.entries[8] +\n m[3] * im.entries[12];\n\n if (det == 0) {\n throw 'Determinant is zero.';\n }\n\n det = 1.0 / det;\n\n for (let i = 0; i < 16; i++) {\n this.entries[i] = im.entries[i] * det;\n }\n\n return this;\n }\n\n /**\n * Projects the vector from world space into camera space.\n * \n * @param {Vector3f} v A vector to project.\n * @param {CameraBase} camera A camera instance.\n * @returns {Vector3f} The vector in camera space.\n */\n static projectVector(v, camera) {\n return v.applyProjection(Matrix4f.multiply(camera.projectionMatrix, Matrix4f.invert(camera.modelMatrix)));\n }\n\n /**\n * Projects the vector from camera space into world space.\n * \n * @param {Vector3f} v A vector to unproject.\n * @param {CameraBase} camera A camera instance.\n * @returns {Vector3f} The vector in world space.\n */\n static unprojectVector(v, camera) {\n return v.applyProjection(Matrix4f.multiply(camera.modelMatrix, Matrix4f.invert(camera.projectionMatrix)));\n }\n\n /**\n * Clones this matrix.\n * \n * @returns {Matrix4f} A clone of the matrix.\n */\n clone() {\n return new Matrix4f(new Float32Array(this.entries));\n }\n\n /**\n * Checks whether or not the entries of the two matrices match.\n * \n * @param {Matrix4f} a A matrix.\n * @returns {Boolean} A boolean indicating whether or not the entries of the two matrices match.\n */\n equals(a) {\n for (let i = 0; i < this.entries.length; i++) {\n if (this.entries[i] !== a.entries[i]) return false;\n }\n\n return true;\n }\n\n /**\n * Returns a string representation of the matrix.\n * \n * @returns {String} The string representation of this matrix.\n */\n toString() {\n let str = this.entries[0] + ', ' + this.entries[4] + ', ' + this.entries[8] + ', ' + this.entries[12] + '\\n';\n str += this.entries[1] + ', ' + this.entries[5] + ', ' + this.entries[9] + ', ' + this.entries[13] + '\\n';\n str += this.entries[2] + ', ' + this.entries[6] + ', ' + this.entries[10] + ', ' + this.entries[14] + '\\n';\n str += this.entries[3] + ', ' + this.entries[7] + ', ' + this.entries[11] + ', ' + this.entries[15] + '\\n';\n\n return str;\n }\n\n /**\n * Multiply the two matrices (a * b).\n * \n * @static\n * @param {any} a A matrix to be multiplied.\n * @param {any} b A matrix to be multiplied.\n * @returns {Matrix4f} A matrix.\n */\n static multiply(a, b) {\n // First, store the values in local variables.\n // See:\n // http://blog.tojicode.com/2010/06/stupidly-fast-webgl-matricies.html\n\n let a00 = a.entries[0],\n a01 = a.entries[4],\n a02 = a.entries[8],\n a03 = a.entries[12];\n let a10 = a.entries[1],\n a11 = a.entries[5],\n a12 = a.entries[9],\n a13 = a.entries[13];\n let a20 = a.entries[2],\n a21 = a.entries[6],\n a22 = a.entries[10],\n a23 = a.entries[14];\n let a30 = a.entries[3],\n a31 = a.entries[7],\n a32 = a.entries[11],\n a33 = a.entries[15];\n\n let b00 = b.entries[0],\n b01 = b.entries[4],\n b02 = b.entries[8],\n b03 = b.entries[12];\n let b10 = b.entries[1],\n b11 = b.entries[5],\n b12 = b.entries[9],\n b13 = b.entries[13];\n let b20 = b.entries[2],\n b21 = b.entries[6],\n b22 = b.entries[10],\n b23 = b.entries[14];\n let b30 = b.entries[3],\n b31 = b.entries[7],\n b32 = b.entries[11],\n b33 = b.entries[15];\n\n return new Matrix4f(new Float32Array([\n a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30,\n a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30,\n a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30,\n a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30,\n a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31,\n a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31,\n a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31,\n a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31,\n a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32,\n a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32,\n a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32,\n a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32,\n a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33,\n a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33,\n a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33,\n a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33\n ]));\n }\n\n /**\n * Initialize a matrix from a quaternion.\n * \n * @static\n * @param {Quaternion} q A quaternion.\n * @returns {Matrix4f} A matrix.\n */\n static fromQuaternion(q) {\n // First, store the values in local variables.\n // See:\n // http://blog.tojicode.com/2010/06/stupidly-fast-webgl-matricies.html\n // https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Quaternion-derived_rotation_matrix\n let x = q.components[0],\n y = q.components[1],\n z = q.components[2],\n w = q.components[3];\n let x2 = x + x,\n y2 = y + y,\n z2 = z + z;\n let xx = x * x2,\n xy = x * y2,\n xz = x * z2;\n let yy = y * y2,\n yz = y * z2,\n zz = z * z2;\n let wx = w * x2,\n wy = w * y2,\n wz = w * z2;\n\n return new Matrix4f(new Float32Array([\n 1 - (yy + zz), xy + wz, xz - wy, 0,\n xy - wz, 1 - (xx + zz), yz + wx, 0,\n xz + wy, yz - wx, 1 - (xx + yy), 0,\n 0, 0, 0, 1\n ]));\n }\n\n /**\n * Create a lookat matrix for a camera.\n * \n * @static\n * @param {Vector3f} cameraPosition The position of the camera.\n * @param {Vector3f} target The lookat (target) of the camera.\n * @param {Vector3f} up The up vector of the camera node.\n * @returns {Matrix4f} A matrix.\n */\n static lookAt(cameraPosition, target, up) {\n // See here in order to return a quaternion directly:\n // http://www.euclideanspace.com/maths/algebra/vectors/lookat/\n let z = Vector3f.subtract(cameraPosition, target).normalize();\n\n if (z.lengthSq() === 0.0) {\n z.components[2] = 1.0\n }\n\n let x = Vector3f.cross(up, z).normalize();\n\n if (x.lengthSq() === 0.0) {\n z.components[2] += 0.0001;\n x = Vector3f.cross(up, z).normalize();\n }\n\n let y = Vector3f.cross(z, x);\n\n return new Matrix4f(new Float32Array([\n x.components[0], x.components[1], x.components[2], 0,\n y.components[0], y.components[1], y.components[2], 0,\n z.components[0], z.components[1], z.components[2], 0,\n 0, 0, 0, 1\n ]));\n }\n\n /**\n * Composes a matrix from the positional, rotational and scaling components.\n * \n * @param {Vector3f} position The positional component.\n * @param {Quaternion} quaternion The rotational component.\n * @param {Vector3f} scale The scaling component.\n * @returns {Matrix4f} A matrix.\n */\n static compose(position, quaternion, scale) {\n let m = new Matrix4f();\n\n m.setRotation(quaternion);\n m.scale(scale);\n m.setPosition(position);\n\n return m;\n }\n\n /**\n * Inverts a matrix.\n * \n * @static\n * @param {Matrix4f} matrix A matrix to be inverted.\n * @returns The inverted matrix.\n */\n static invert(matrix) {\n // Fugly implementation lifted from MESA (originally in C++)\n let im = new Matrix4f();\n\n let m = matrix.entries;\n\n im.entries[0] = m[5] * m[10] * m[15] -\n m[5] * m[11] * m[14] -\n m[9] * m[6] * m[15] +\n m[9] * m[7] * m[14] +\n m[13] * m[6] * m[11] -\n m[13] * m[7] * m[10];\n\n im.entries[4] = -m[4] * m[10] * m[15] +\n m[4] * m[11] * m[14] +\n m[8] * m[6] * m[15] -\n m[8] * m[7] * m[14] -\n m[12] * m[6] * m[11] +\n m[12] * m[7] * m[10];\n\n im.entries[8] = m[4] * m[9] * m[15] -\n m[4] * m[11] * m[13] -\n m[8] * m[5] * m[15] +\n m[8] * m[7] * m[13] +\n m[12] * m[5] * m[11] -\n m[12] * m[7] * m[9];\n\n im.entries[12] = -m[4] * m[9] * m[14] +\n m[4] * m[10] * m[13] +\n m[8] * m[5] * m[14] -\n m[8] * m[6] * m[13] -\n m[12] * m[5] * m[10] +\n m[12] * m[6] * m[9];\n\n im.entries[1] = -m[1] * m[10] * m[15] +\n m[1] * m[11] * m[14] +\n m[9] * m[2] * m[15] -\n m[9] * m[3] * m[14] -\n m[13] * m[2] * m[11] +\n m[13] * m[3] * m[10];\n\n im.entries[5] = m[0] * m[10] * m[15] -\n m[0] * m[11] * m[14] -\n m[8] * m[2] * m[15] +\n m[8] * m[3] * m[14] +\n m[12] * m[2] * m[11] -\n m[12] * m[3] * m[10];\n\n im.entries[9] = -m[0] * m[9] * m[15] +\n m[0] * m[11] * m[13] +\n m[8] * m[1] * m[15] -\n m[8] * m[3] * m[13] -\n m[12] * m[1] * m[11] +\n m[12] * m[3] * m[9];\n\n im.entries[13] = m[0] * m[9] * m[14] -\n m[0] * m[10] * m[13] -\n m[8] * m[1] * m[14] +\n m[8] * m[2] * m[13] +\n m[12] * m[1] * m[10] -\n m[12] * m[2] * m[9];\n\n im.entries[2] = m[1] * m[6] * m[15] -\n m[1] * m[7] * m[14] -\n m[5] * m[2] * m[15] +\n m[5] * m[3] * m[14] +\n m[13] * m[2] * m[7] -\n m[13] * m[3] * m[6];\n\n im.entries[6] = -m[0] * m[6] * m[15] +\n m[0] * m[7] * m[14] +\n m[4] * m[2] * m[15] -\n m[4] * m[3] * m[14] -\n m[12] * m[2] * m[7] +\n m[12] * m[3] * m[6];\n\n im.entries[10] = m[0] * m[5] * m[15] -\n m[0] * m[7] * m[13] -\n m[4] * m[1] * m[15] +\n m[4] * m[3] * m[13] +\n m[12] * m[1] * m[7] -\n m[12] * m[3] * m[5];\n\n im.entries[14] = -m[0] * m[5] * m[14] +\n m[0] * m[6] * m[13] +\n m[4] * m[1] * m[14] -\n m[4] * m[2] * m[13] -\n m[12] * m[1] * m[6] +\n m[12] * m[2] * m[5];\n\n im.entries[3] = -m[1] * m[6] * m[11] +\n m[1] * m[7] * m[10] +\n m[5] * m[2] * m[11] -\n m[5] * m[3] * m[10] -\n m[9] * m[2] * m[7] +\n m[9] * m[3] * m[6];\n\n im.entries[7] = m[0] * m[6] * m[11] -\n m[0] * m[7] * m[10] -\n m[4] * m[2] * m[11] +\n m[4] * m[3] * m[10] +\n m[8] * m[2] * m[7] -\n m[8] * m[3] * m[6];\n\n im.entries[11] = -m[0] * m[5] * m[11] +\n m[0] * m[7] * m[9] +\n m[4] * m[1] * m[11] -\n m[4] * m[3] * m[9] -\n m[8] * m[1] * m[7] +\n m[8] * m[3] * m[5];\n\n im.entries[15] = m[0] * m[5] * m[10] -\n m[0] * m[6] * m[9] -\n m[4] * m[1] * m[10] +\n m[4] * m[2] * m[9] +\n m[8] * m[1] * m[6] -\n m[8] * m[2] * m[5];\n\n let det = m[0] * im.entries[0] +\n m[1] * im.entries[4] +\n m[2] * im.entries[8] +\n m[3] * im.entries[12];\n\n if (det == 0) {\n throw 'Determinant is zero.';\n }\n\n det = 1.0 / det;\n\n for (let i = 0; i < 16; i++) {\n im.entries[i] = im.entries[i] * det;\n }\n\n return im;\n }\n}\n\nmodule.exports = Matrix4f" }, { "alpha_fraction": 0.5314685106277466, "alphanum_fraction": 0.561188817024231, "avg_line_length": 29.105262756347656, "blob_id": "4de310d142055667c26392ed9d5b2fd2360cbe85", "content_id": "878d0fc9886ee62adbb2cc5721b26f7832d833bb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 572, "license_type": "permissive", "max_line_length": 82, "num_lines": 19, "path": "/src/Shaders/Coordinates.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "const Shader = require('../Core/Shader')\nconst Uniform = require('../Core/Uniform')\n\nmodule.exports = new Shader('coordinates', 1, { }, [\n 'attribute vec3 position;',\n 'attribute vec3 color;',\n 'varying vec3 vColor;',\n 'void main() {',\n 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',\n 'vec4 mv_pos = modelViewMatrix * vec4(position, 1.0);',\n 'gl_PointSize = 1.0;',\n 'vColor = color;',\n '}'\n], [\n 'varying vec3 vColor;',\n 'void main() {',\n 'gl_FragColor = vec4(vColor, 1.0);',\n '}'\n]);\n" }, { "alpha_fraction": 0.6158536672592163, "alphanum_fraction": 0.6309370994567871, "avg_line_length": 30.806121826171875, "blob_id": "a2a06f6d61e13ce4fc0dcc04898a0eaa50850b38", "content_id": "6b9d6fd98f5c815f5f00d4c55926de2616aaa54f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3116, "license_type": "permissive", "max_line_length": 133, "num_lines": 98, "path": "/src/Core/Effect.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst Shaders = require('../Shaders');\n\nclass Effect {\n constructor(renderer, shaderName) {\n this.renderer = renderer;\n this.gl = this.renderer.gl;\n\n this.framebuffer = this.initFramebuffer();\n this.texture = this.initTexture();\n this.renderbuffer = this.initRenderbuffer();\n this.shader = Shaders[shaderName].clone();\n this.shader.init(this.renderer.gl);\n\n this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null);\n }\n\n initBuffer() {\n let g = this.gl;\n let texCoordLocation = g.getAttribLocation(this.shader.program, 'v_coord');\n\n // provide texture coordinates for the rectangle.\n let texCoordBuffer = g.createBuffer();\n g.bindBuffer(g.ARRAY_BUFFER, texCoordBuffer);\n g.bufferData(g.ARRAY_BUFFER, new Float32Array([\n 1.0, 1.0,\n -1.0, 1.0,\n -1.0, -1.0,\n -1.0, -1.0,\n 1.0, -1.0,\n 1.0, 1.0]), g.STATIC_DRAW);\n\n g.enableVertexAttribArray(texCoordLocation);\n g.vertexAttribPointer(texCoordLocation, 2, g.FLOAT, false, 0, 0);\n\n return texCoordBuffer;\n }\n\n initTexture() {\n let g = this.gl;\n\n let texture = g.createTexture();\n g.bindTexture(g.TEXTURE_2D, texture);\n g.texParameteri(g.TEXTURE_2D, g.TEXTURE_WRAP_S, g.CLAMP_TO_EDGE);\n g.texParameteri(g.TEXTURE_2D, g.TEXTURE_WRAP_T, g.CLAMP_TO_EDGE);\n g.texParameteri(g.TEXTURE_2D, g.TEXTURE_MIN_FILTER, g.LINEAR);\n g.texParameteri(g.TEXTURE_2D, g.TEXTURE_MAG_FILTER, g.LINEAR);\n\n g.bindTexture(g.TEXTURE_2D, texture);\n g.texImage2D(g.TEXTURE_2D, 0, g.RGBA, this.renderer.getWidth(), this.renderer.getHeight(), 0, g.RGBA, g.UNSIGNED_BYTE, null);\n\n g.framebufferTexture2D(g.FRAMEBUFFER, g.COLOR_ATTACHMENT0, g.TEXTURE_2D, texture, 0);\n\n return texture;\n }\n\n initFramebuffer() {\n let g = this.gl;\n\n let framebuffer = g.createFramebuffer();\n g.bindFramebuffer(g.FRAMEBUFFER, framebuffer);\n return framebuffer;\n }\n\n initRenderbuffer() {\n let g = this.gl;\n\n let renderbuffer = g.createRenderbuffer();\n g.bindRenderbuffer(g.RENDERBUFFER, renderbuffer);\n\n g.renderbufferStorage(g.RENDERBUFFER, g.DEPTH_COMPONENT16, this.renderer.getWidth(), this.renderer.getHeight());\n g.framebufferRenderbuffer(g.FRAMEBUFFER, g.DEPTH_ATTACHMENT, g.RENDERBUFFER, renderbuffer);\n\n // g.renderbufferStorage(g.RENDERBUFFER, g.DEPTH_STENCIL, this.renderer.getWidth(), this.renderer.getHeight());\n // g.framebufferRenderbuffer(g.FRAMEBUFFER, g.DEPTH_STENCIL_ATTACHMENT, g.RENDERBUFFER, renderbuffer);\n\n return renderbuffer;\n }\n\n bind() {\n let g = this.gl;\n g.bindFramebuffer(g.FRAMEBUFFER, this.framebuffer);\n g.clear(g.COLOR_BUFFER_BIT | g.DEPTH_BUFFER_BIT);\n }\n\n unbind() {\n let g = this.gl;\n g.bindRenderbuffer(g.RENDERBUFFER, null);\n g.bindFramebuffer(g.FRAMEBUFFER, null);\n\n this.initBuffer();\n this.shader.use();\n g.drawArrays(g.TRIANGLES, 0, 6);\n }\n}\n\nmodule.exports = Effect" }, { "alpha_fraction": 0.6195749044418335, "alphanum_fraction": 0.6301482319831848, "avg_line_length": 32.64904022216797, "blob_id": "fe8f2022aca1a5f3cb1ce68520603ba324afd436", "content_id": "8fe471307698ead84561614768cd028194ee6265", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 27995, "license_type": "permissive", "max_line_length": 198, "num_lines": 832, "path": "/src/Spice/Octree.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst AABB = require('./AABB');\nconst Vector3f = require('../Math/Vector3f');\nconst ProjectionMatrix = require('../Math/ProjectionMatrix');\nconst Utils = require('../Utils/Utils');\nconst Raycaster = require('./Raycaster');\nconst RadixSort = require('../Math/RadixSort');\n\n/** \n * @class\n * An octree constructed using the point cloud.\n * @property {number} threshold - A threshold indicating whether or not a further subdivision is needed based on the number of data points in the current node.\n * @property {number} maxDepth - A maximum depth of the octree.\n * @property {Object} points - An object storing the points belonging to each node indexed by the location id of the node.\n * @property {Object} aabbs - An object storing the axis-aligned bounding boxes belonging to each node indexed by the location id of the node.\n * @constructor\n * @param {number} threshold - A threshold indicating whether or not a further subdivision is needed based on the number of data points in the current node.\n * @param {number} maxDepth - A maximum depth of the octree.\n */\n\nclass Octree {\n constructor(threshold, maxDepth) {\n this.threshold = threshold || 500;\n this.maxDepth = maxDepth || 8;\n this.points = {};\n this.aabbs = {};\n\n this.offsets = [\n [-0.5, -0.5, -0.5],\n [-0.5, -0.5, +0.5],\n [-0.5, +0.5, -0.5],\n [-0.5, +0.5, +0.5],\n [+0.5, -0.5, -0.5],\n [+0.5, -0.5, +0.5],\n [+0.5, +0.5, -0.5],\n [+0.5, +0.5, +0.5]\n ];\n }\n\n /**\n * Builds the octree by assigning the indices of data points and axis-aligned bounding boxes to assoziative arrays indexed by the location code.\n * @param {Uint32Array} pointIndices - An set of points that are either sub-divided into sub nodes or assigned to the current node.\n * @param {Float32Array} vertices - An array containing the positions of all the vertices.\n * @param {AABB} aabb - The bounding box of the current node.\n * @param {number} [locCode=1] - A binary code encoding the id and the level of the current node.\n */\n build(pointIndices, vertices, aabb, locCode = 1) {\n // Set the location code of the axis-aligned bounding box\n aabb.setLocCode(locCode);\n\n // Store the axis aligned bounding box of this node\n // and set the points belonging to the node to null\n this.points[locCode] = null;\n this.aabbs[locCode] = aabb;\n\n // Check if this node reaches the maximum depth or the threshold\n let depth = this.getDepth(locCode);\n\n if (pointIndices.length <= this.threshold || depth >= this.maxDepth) {\n this.points[locCode] = new Uint32Array(pointIndices.length);\n for (var i = 0; i < pointIndices.length; i++) {\n this.points[locCode][i] = pointIndices[i];\n }\n\n return true;\n }\n\n let childPointCounts = new Uint32Array(8);\n let codes = new Float32Array(pointIndices.length);\n\n for (var i = 0; i < pointIndices.length; i++) {\n // Points are indices to the vertices array\n // which stores x,y,z coordinates linear\n let k = pointIndices[i] * 3;\n\n // Assign point to subtree, this gives a code\n // 000, 001, 010, 011, 100, 101, 110, 111\n // (-> 8 possible subtrees)\n if (vertices[k + 0] >= aabb.center.components[0]) codes[i] |= 4;\n if (vertices[k + 1] >= aabb.center.components[1]) codes[i] |= 2;\n if (vertices[k + 2] >= aabb.center.components[2]) codes[i] |= 1;\n\n childPointCounts[codes[i]]++;\n }\n\n let nextPoints = new Array(8);\n let nextAabb = new Array(8);\n\n for (var i = 0; i < 8; i++) {\n if (childPointCounts[i] == 0) continue;\n nextPoints[i] = new Uint32Array(childPointCounts[i]);\n\n for (var j = 0, k = 0; j < pointIndices.length; j++) {\n if (codes[j] == i) {\n nextPoints[i][k++] = pointIndices[j];\n }\n }\n\n let o = this.offsets[i];\n let offset = new Vector3f(o[0], o[1], o[2]);\n offset.multiplyScalar(aabb.radius);\n nextAabb[i] = new AABB(aabb.center.clone().add(offset), 0.5 * aabb.radius);\n }\n\n for (var i = 0; i < 8; i++) {\n if (childPointCounts[i] == 0) {\n continue;\n }\n\n let nextLocCode = this.generateLocCode(locCode, i);\n this.build(nextPoints[i], vertices, nextAabb[i], nextLocCode);\n }\n\n return this;\n }\n\n /**\n * Returns an array containing the location codes of all the axis-aligned\n * bounding boxes inside this octree.\n */\n getLocCodes() {\n return Object.keys(this.aabbs);\n }\n\n /**\n * Calculates the depth of the node from its location code.\n * @param {number} locCode - A binary code encoding the id and the level of the current node.\n * @returns {number} The depth of the node with the provided location code.\n */\n getDepth(locCode) {\n // If the msb is at position 6 (e.g. 1000000) the\n // depth is 2, since the locCode contains two nodes (2 x 3 bits)\n return Utils.msb(locCode) / 3;\n }\n\n /**\n * Generates a location code for a node based on the full code of the parent and the code of the current node.\n * @param {number} parentCode The full location code of the parent node.\n * @param {number} nodeCode The 3 bit code of the current node.\n * @returns {number} The full location code for the current node.\n */\n generateLocCode(parentCode, nodeCode) {\n // Insert the code of this new node, just before the msb (that is set to 1)\n // of the parents code\n let msb = Utils.msb(parentCode);\n\n if (msb == -1) {\n return nodeCode | 8;\n } else {\n // Left-shift the parent code by msb\n parentCode = parentCode <<= 3;\n // OR parent code with node code\n return parentCode | nodeCode;\n }\n }\n\n /**\n * Traverses the octree depth-first.\n * @param {Function} traverseCallback - Is called for each node where a axis-aligned bounding box exists.\n * @param {number} [locCode=1] - The location code of the node that serves as the starting node for the traversion.\n */\n traverse(traverseCallback, locCode = 1) {\n for (var i = 0; i < 8; i++) {\n let next = locCode << 3 | i;\n\n // If it has an aabb, it exists\n if (this.aabbs[next]) {\n traverseCallback(this.points[next], this.aabbs[next], next);\n this.traverse(traverseCallback, next);\n }\n }\n }\n\n /**\n * Traverses the octree depth-first, does not visit nodes / subtrees if a condition is not met.\n * @param {Function} traverseIfCallback - Is called for each node where a axis-aligned bounding box exists and returns either true or false, with false stopping further exploration of the subtree.\n * @param {Function} conditionCallback - Is called to test whether or not a subtree should be explored.\n * @param {number} [locCode=1] - The location code of the node that serves as the starting node for the traversion.\n */\n traverseIf(traverseIfCallback, conditionCallback, locCode = 1) {\n for (var i = 0; i < 8; i++) {\n let next = locCode << 3 | i;\n\n // If it has an aabb, it exists\n if (this.aabbs[next]) {\n if (!conditionCallback(this.aabbs[next], next)) {\n continue;\n }\n\n traverseIfCallback(this.points[next], this.aabbs[next], next);\n this.traverseIf(traverseIfCallback, conditionCallback, next);\n }\n }\n }\n\n /**\n * Searches for octree nodes that are intersected by the ray and returns all the points associated with those nodes.\n * @param {Raycaster} raycaster - The raycaster used for checking for intersects.\n * @returns {Array} A set of points which are associated with octree nodes intersected by the ray.\n */\n raySearch(raycaster) {\n let result = [];\n\n // Info: shouldn't be necessary any more\n // Always add the points from the root\n // The root has the location code 1\n // ... looks like it's still necessary\n if (this.points[1]) {\n for (var i = 0; i < this.points[1].length; i++) {\n result.push({\n index: this.points[1][i],\n locCode: 1\n });\n }\n }\n\n // Calculate the direction, and the percentage\n // of the direction, of the ray\n let dir = raycaster.ray.direction.clone();\n dir.normalize();\n\n let inverseDir = new Vector3f(1, 1, 1);\n inverseDir.divide(dir);\n\n this.traverseIf(function (points, aabb, locCode) {\n // If there is an aabb, that contains no points but only\n // nodes, skip here\n if (!points) {\n return;\n }\n\n for (var i = 0; i < points.length; i++) {\n result.push({\n index: points[i],\n locCode: locCode\n });\n }\n }, function (aabb, locCode) {\n return aabb.cylinderTest(raycaster.ray.source, inverseDir,\n raycaster.far, raycaster.threshold);\n });\n\n return result;\n }\n\n /**\n * Returns the locCodes and number of points of axis aligned bounding boxes that are intersected by a box defined by min and max vectors. Boxes not containing any points are ignored.\n * @param {Vector3f} min - The minima of the box.\n * @param {Vector3f} max - The maxima of the box.\n * @returns {Array} An array containing locCodes and the number of points of the intersected axis aligned bounding boxes.\n */\n intersectBox(min, max) {\n let result = [];\n\n console.log(this.aabbs);\n\n // console.log(min, max);\n\n this.traverseIf(function (points, aabb, locCode) {\n if (!points) {\n return;\n }\n\n console.log(locCode, points.length);\n }, function (aabb, locCode) {\n // console.log(min, max);\n // console.log(aabb);\n // console.log(locCode);\n return !((min.getX() < aabb.max[0]) && (max.getX() > aabb.min[0]) &&\n (min.getY() < aabb.max[1]) && (max.getY() > aabb.min[1]) &&\n (min.getZ() < aabb.max[2]) && (max.getZ() > aabb.min[2]));\n });\n\n return result;\n }\n\n /**\n * Returns an array containing all the centers of the axis-aligned bounding boxes\n * in this octree that have points associated with them.\n * @returns {Array} An array containing the centers as Lore.Vector3f objects.\n */\n getCenters(threshold) {\n threshold = threshold || 0;\n let centers = new Array();\n\n this.traverse(function (points, aabb, next) {\n if (points && points.length > threshold) {\n centers.push(aabb.center);\n }\n });\n\n return centers;\n }\n\n /**\n * This function returns the closest box in the octree to the point given as an argument.\n * @param {Vector3f} point - The point.\n * @param {number} threshold - The minimum number of points an axis-aligned bounding box should contain to count as a hit.\n * @param {number} [locCode=1] - The starting locCode, if not set, starts at the root.\n * @returns {AABB} The closest axis-aligned bounding box to the input point.\n */\n getClosestBox(point, threshold, locCode = 1) {\n let closest = -1;\n let minDist = Number.MAX_VALUE;\n\n for (var i = 0; i < 8; i++) {\n let next = locCode << 3 | i;\n\n // If it has an aabb, it exists\n if (this.aabbs[next]) {\n // Continue if under threshold\n if (this.points[next] && this.points[next].length < threshold) {\n continue;\n }\n\n let dist = this.aabbs[next].distanceToPointSq(point.components[0], point.components[1], point.components[2]);\n if (dist < minDist) {\n minDist = dist;\n closest = next;\n }\n }\n }\n\n if (closest < 0) {\n return this.aabbs[locCode];\n } else {\n return this.getClosestBox(point, threshold, closest);\n }\n }\n\n /**\n * This function returns the closest box in the octree to the point given as an argument. The distance measured is to the\n * box center.\n * @param {Vector3f} point - The point.\n * @param {number} threshold - The minimum number of points an axis-aligned bounding box should contain to count as a hit.\n * @param {number} [locCode=1] - The starting locCode, if not set, starts at the root.\n * @returns {AABB} The closest axis-aligned bounding box to the input point.\n */\n getClosestBoxFromCenter(point, threshold, locCode = 1) {\n let closest = -1;\n let minDist = Number.MAX_VALUE;\n\n for (var i = 0; i < 8; i++) {\n let next = locCode << 3 | i;\n\n // If it has an aabb, it exists\n if (this.aabbs[next]) {\n // Continue if under threshold\n if (this.points[next] && this.points[next].length < threshold) {\n continue;\n }\n\n let dist = this.aabbs[next].distanceFromCenterToPointSq(point.components[0], point.components[1], point.components[2]);\n\n if (dist < minDist) {\n minDist = dist;\n closest = next;\n }\n }\n }\n\n if (closest < 0) {\n return this.aabbs[locCode];\n } else {\n return this.getClosestBox(point, threshold, closest);\n }\n }\n\n /**\n * This function returns the farthest box in the octree to the point given as an argument.\n * @param {Vector3f} point - The point.\n * @param {number} threshold - The minimum number of points an axis-aligned bounding box should contain to count as a hit.\n * @param {number} [locCode=1] - The starting locCode, if not set, starts at the root.\n * @returns {AABB} The farthest axis-aligned bounding box to the input point.\n */\n getFarthestBox(point, threshold, locCode) {\n let farthest = -1;\n let maxDist = Number.MIN_VALUE;\n\n for (var i = 0; i < 8; i++) {\n let next = locCode << 3 | i;\n\n // If it has an aabb, it exists\n if (this.aabbs[next]) {\n // Continue if under threshold\n if (this.points[next] && this.points[next].length < threshold) {\n continue;\n }\n\n let dist = this.aabbs[next].distanceToPointSq(point.components[0], point.components[1], point.components[2]);\n if (dist > maxDist) {\n maxDist = dist;\n farthest = next;\n }\n }\n }\n\n if (farthest < 0) {\n return this.aabbs[locCode];\n } else {\n return this.getFarthestBox(point, threshold, farthest);\n }\n }\n\n /**\n * Finds the closest point inside the octree to the point provided as an argument.\n * @param {Vector3f} point - The point.\n * @param {Float32Array} positions - An array containing the positions of the points.\n * @param {number} threshold - Only consider points inside a axis-aligned bounding box with a minimum of [threshold] points.\n * @param {number} locCode - If specified, the axis-aligned bounding box in which the point is searched for. If not set, all boxes are searched.\n * @returns {Vector3f} The position of the closest point.\n */\n getClosestPoint(point, positions, threshold, locCode) {\n threshold = threshold || 0;\n let minDist = Number.MAX_VALUE;\n let result = null;\n\n let box = null;\n\n if (locCode) {\n box = this.aabbs[locCode];\n } else {\n box = this.getClosestBox(point, threshold);\n }\n\n let boxPoints = this.points[box.getLocCode()];\n\n // If the box does not contain any points\n if (!boxPoints) {\n return null;\n }\n\n for (var i = 0; i < boxPoints.length; i++) {\n let index = boxPoints[i];\n index *= 3;\n let x = positions[index];\n let y = positions[index + 1];\n let z = positions[index + 2];\n\n let pc = point.components;\n\n let distSq = Math.pow(pc[0] - x, 2) + Math.pow(pc[1] - y, 2) + Math.pow(pc[2] - z, 2);\n if (distSq < minDist) {\n minDist = distSq;\n result = {\n x: x,\n y: y,\n z: z\n };\n }\n }\n\n if (!result) {\n return null;\n }\n\n return new Vector3f(result.x, result.y, result.z);\n }\n\n /**\n * Finds the farthest point inside the octree to the point provided as an argument.\n * @param {Vector3f} point - The point.\n * @param {Float32Array} positions - An array containing the positions of the points.\n * @param {number} threshold - Only consider points inside a axis-aligned bounding box with a minimum of [threshold] points.\n * @param {number} locCode - If specified, the axis-aligned bounding box in which the point is searched for. If not set, all boxes are searched.\n * @returns {Vector3f} The position of the farthest point.\n */\n getFarthestPoint(point, positions, threshold, locCode) {\n threshold = threshold || 0;\n let maxDist = Number.MIN_VALUE;\n let result = null;\n\n // Get farthest box\n let box = null;\n\n if (locCode) {\n box = this.aabbs[locCode];\n } else {\n box = this.getFarthestBox(point, threshold);\n }\n\n let boxPoints = this.points[box.getLocCode()];\n\n // If the box does not contain any points\n if (!boxPoints) {\n return null;\n }\n\n for (var i = 0; i < boxPoints.length; i++) {\n let index = boxPoints[i];\n index *= 3;\n let x = positions[index];\n let y = positions[index + 1];\n let z = positions[index + 2];\n\n let pc = point.components;\n\n let distSq = Math.pow(pc[0] - x, 2) + Math.pow(pc[1] - y, 2) + Math.pow(pc[2] - z, 2);\n if (distSq > maxDist) {\n maxDist = distSq;\n result = {\n x: x,\n y: y,\n z: z\n };\n }\n }\n\n if (!result) {\n return null;\n }\n\n return new Vector3f(result.x, result.y, result.z);\n }\n\n /**\n * Returns the parent of a given location code by simply shifting it to the right by tree, removing the current code.\n * @param {number} locCode - The location code of a node.\n */\n getParent(locCode) {\n return locCode >>> 3;\n }\n\n /**\n * Find neighbouring axis-aligned bounding boxes.\n * @param {number} locCode - The location code of the axis-aligned bounding box whose neighbours will be returned\n * @returns {Array} An array of location codes of the neighbouring axis-aligned bounding boxes.\n */\n getNeighbours(locCode) {\n let self = this;\n let locCodes = new Array();\n\n this.traverseIf(function (points, aabbs, code) {\n if (points && points.length > 0 && code != locCode) {\n locCodes.push(code);\n }\n }, function (aabb, code) {\n // Exit branch if this node is not a neighbour\n return aabb.testAABB(self.aabbs[locCode]);\n });\n\n return locCodes;\n }\n\n /**\n * Returns the k-nearest neighbours of a vertex.\n * @param {number} k - The number of nearest neighbours to return.\n * @param {number} point - The index of a vertex or a vertex.\n * @param {number} locCode - The location code of the axis-aligned bounding box containing the vertex. If not set, the box is searched for.\n * @param {Float32Array} positions - The position information for the points indexed in this octree.\n * @param {Function} kNNCallback - The callback that is called after the k-nearest neighbour search has finished.\n */\n kNearestNeighbours(k, point, locCode, positions, kNNCallback) {\n k += 1; // Account for the fact, that the point itself should be returned as well.\n let length = positions.length / 3;\n let p = point;\n\n // TODO: WTF is happening here\n if (!isNaN(parseFloat(point))) {\n let p = {\n x: positions[p * 3],\n y: positions[p * 3 + 1],\n z: positions[p * 3 + 2]\n };\n }\n\n if (locCode === null) {\n locCode = this.getClosestBoxFromCenter(new Vector3f(p.x, p.y, p.z), 0).locCode;\n }\n\n // Calculte the distances to the other cells\n let cellDistances = this.getCellDistancesToPoint(p.x, p.y, p.z, locCode);\n\n // Calculte the distances to the other points in the same cell\n let pointDistances = this.pointDistancesSq(p.x, p.y, p.z, locCode, positions)\n\n // Sort the indices according to distance\n let radixSort = new RadixSort();\n let sortedPointDistances = radixSort.sort(pointDistances.distancesSq, true);\n\n // Sort the neighbours according to distance\n let sortedCellDistances = radixSort.sort(cellDistances.distancesSq, true);\n\n // Since the closest points always stay the closest points event when adding\n // the points of another cell, instead of resizing the array, just define\n // an offset\n let pointOffset = 0;\n\n // Get all the neighbours from this cell that are closer than the nereast box\n let indexCount = 0;\n let indices = new Uint32Array(k);\n\n for (var i = 0; indexCount < k && i < sortedPointDistances.array.length; i++) {\n // Break if closest neighbouring cell is closer than the closest remaining point\n if (sortedPointDistances.array[i] > sortedCellDistances.array[0]) {\n // Set the offset to the most distant closest member\n pointOffset = i;\n break;\n }\n\n indices[i] = pointDistances.indices[sortedPointDistances.indices[i]];\n indexCount++;\n }\n\n // If enough neighbours have been found in the same cell, no need to continue\n if (indexCount == k) {\n return indices;\n }\n\n for (var i = 0; i < sortedCellDistances.array.length; i++) {\n // Get the points from the cell and merge them with the already found ones\n let locCode = cellDistances.locCodes[sortedCellDistances.indices[i]];\n let newPointDistances = this.pointDistancesSq(p.x, p.y, p.z, locCode, positions);\n\n pointDistances = Octree.mergePointDistances(pointDistances, newPointDistances);\n\n // Sort the merged points\n let sortedNewPointDistances = radixSort.sort(pointDistances.distancesSq, true);\n\n for (var j = pointOffset; indexCount < k && j < sortedNewPointDistances.array.length; j++) {\n if (sortedNewPointDistances.array[j] > sortedCellDistances.array[i + 1]) {\n pointOffset = j;\n break;\n }\n\n indices[j] = pointDistances.indices[sortedNewPointDistances.indices[j]];\n indexCount++;\n }\n\n if (indexCount == k || indexCount >= length - 1) {\n // kNNCallback(indices);\n return indices;\n }\n }\n\n //kNNCallback(indices);\n return indices;\n }\n\n /**\n * Calculates the distances from a given point to all of the cells containing points\n * @param {number} x - The x-value of the coordinate.\n * @param {number} y - The y-value of the coordinate.\n * @param {number} z - The z-value of the coordinate.\n * @param {number} locCode - The location code of the cell containing the point.\n * @returns {Object} An object containing arrays for the locCodes and the squred distances.\n */\n getCellDistancesToPoint(x, y, z, locCode) {\n let locCodes = new Array();\n\n this.traverse(function (points, aabb, code) {\n if (points && points.length > 0 && code != locCode) {\n locCodes.push(code);\n }\n });\n\n let dists = new Float32Array(locCodes.length);\n for (var i = 0; i < locCodes.length; i++) {\n dists[i] = this.aabbs[locCodes[i]].distanceToPointSq(x, y, z);\n }\n\n return {\n locCodes: locCodes,\n distancesSq: dists\n };\n }\n\n /**\n * Expands the current neighbourhood around the cell where the point specified by x, y, z is in.\n * @param {number} x - The x-value of the coordinate.\n * @param {number} y - The y-value of the coordinate.\n * @param {number} z - The z-value of the coordinate.\n * @param {number} locCode - The location code of the cell containing the point.\n * @param {Object} cellDistances - The object containing location codes and distances.\n * @returns {number} The number of added location codes.\n */\n expandNeighbourhood(x, y, z, locCode, cellDistances) {\n let locCodes = cellDistances.locCodes;\n let distancesSq = cellDistances.distancesSq;\n let length = locCodes.length;\n\n for (var i = length - 1; i >= 0; i--) {\n let neighbours = this.getNeighbours(locCodes[i]);\n\n for (var j = 0; j < neighbours.length; j++) {\n if (neighbours[j] !== locCode && !Utils.arrayContains(locCodes, neighbours[j])) {\n locCodes.push(neighbours[j]);\n }\n }\n }\n\n // Update the distances\n let l1 = locCodes.length;\n let l2 = distancesSq.length;\n\n if (l1 === l2) {\n return;\n }\n\n let dists = new Float32Array(l1 - l2);\n\n for (var i = l2, c = 0; i < l1; i++, c++) {\n dists[c] = this.aabbs[locCodes[i]].distanceToPointSq(x, y, z);\n }\n\n cellDistances.distancesSq = Utils.concatTypedArrays(distancesSq, dists);\n\n return locCodes.length - length;\n }\n\n /**\n * Returns a list of the cells neighbouring the cell with the provided locCode and the point specified by x, y and z.\n * @param {number} x - The x-value of the coordinate.\n * @param {number} y - The y-value of the coordinate.\n * @param {number} z - The z-value of the coordinate.\n * @param {number} locCode - The number of the axis-aligned bounding box.\n * @returns {Object} An object containing arrays for the locCodes and the squred distances.\n */\n cellDistancesSq(x, y, z, locCode) {\n let locCodes = this.getNeighbours(locCode);\n\n let dists = new Float32Array(locCodes.length);\n\n for (var i = 0; i < locCodes.length; i++) {\n dists[i] = this.aabbs[locCodes[i]].distanceToPointSq(x, y, z);\n }\n\n return {\n locCodes: locCodes,\n distancesSq: dists\n };\n }\n\n /**\n * Returns a list of the the squared distances of the points contained in the axis-aligned bounding box to the provided coordinates.\n * @param {number} x - The x-value of the coordinate.\n * @param {number} y - The y-value of the coordinate.\n * @param {number} z - The z-value of the coordinate.\n * @param {number} locCode - The number of the axis-aligned bounding box.\n * @param {Float32Array} positions - The array containing the vertex coordinates.\n * @returns {Object} An object containing arrays for the indices and distances.\n */\n pointDistancesSq(x, y, z, locCode, positions) {\n let points = this.points[locCode];\n let indices = new Uint32Array(points.length);\n let dists = new Float32Array(points.length);\n\n for (var i = 0; i < points.length; i++) {\n let index = points[i] * 3;\n let x2 = positions[index];\n let y2 = positions[index + 1];\n let z2 = positions[index + 2];\n\n indices[i] = points[i];\n dists[i] = Math.pow(x2 - x, 2) + Math.pow(y2 - y, 2) + Math.pow(z2 - z, 2);\n }\n return {\n indices: indices,\n distancesSq: dists\n };\n }\n\n /**\n * Concatenates the two typed arrays a and b and returns a new array. The two arrays have to be of the same type.\n * Due to performance reasons, there is no check whether the types match.\n * @param {Array} a - The first array.\n * @param {Array} b - The second array.\n * @returns {Array} The concatenated array.\n */\n static concatTypedArrays(a, b) {\n let c = new a.constructor(a.length + b.length);\n\n c.set(a);\n c.set(b, a.length);\n\n return c;\n }\n\n /**\n * Merges the two arrays (indices and distancesSq) in the point distances object.\n * @param {Object} a - The first point distances object.\n * @param {Object} b - The second point distances object.\n * @returns {Object} The concatenated point distances object.\n */\n static mergePointDistances(a, b) {\n let newObj = {};\n\n newObj.indices = Octree.concatTypedArrays(a.indices, b.indices);\n newObj.distancesSq = Octree.concatTypedArrays(a.distancesSq, b.distancesSq);\n\n return newObj;\n }\n\n /**\n * Merges the two arrays (locCodes and distancesSq) in the cell distances object.\n * @param {Object} a - The first cell distances object.\n * @param {Object} b - The second cell distances object.\n * @returns {Object} The concatenated cell distances object.\n */\n static mergeCellDistances(a, b) {\n let newObj = {};\n\n newObj.locCodes = Octree.concatTypedArrays(a.locCodes, b.locCodes);\n newObj.distancesSq = Octree.concatTypedArrays(a.distancesSq, b.distancesSq);\n\n return newObj;\n }\n\n /**\n * Clones an octree.\n * @param {Octree} original - The octree to be cloned.\n * @returns {Octree} The cloned octree.\n */\n static clone(original) {\n let clone = new Octree();\n\n clone.threshold = original.threshold;\n clone.maxDepth = original.maxDepth;\n clone.points = original.points;\n\n for (var property in original.aabbs) {\n if (original.aabbs.hasOwnProperty(property)) {\n clone.aabbs[property] = AABB.clone(original.aabbs[property]);\n }\n }\n\n return clone;\n }\n}\n\nmodule.exports = Octree" }, { "alpha_fraction": 0.565657377243042, "alphanum_fraction": 0.5729801058769226, "avg_line_length": 26.312358856201172, "blob_id": "9de46cb44a977556f3135c314cb552e3e367637d", "content_id": "093910a29b37ef6489d72fdca7ac405def79914b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 12154, "license_type": "permissive", "max_line_length": 109, "num_lines": 445, "path": "/src/Controls/ControlsBase.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst Vector3f = require(\"../Math/Vector3f\");\n/**\n * An abstract class representing the base for controls implementations.\n *\n * @property {Renderer} renderer A Lore Renderer instance.\n * @property {CameraBase} camera A Lore CameraBase extending object.\n * @property {HTMLCanvasElement} canvas A HTMLCanvasElement.\n * @property {Number} lowFps The FPS limit when throttling FPS.\n * @property {Number} highFps The FPS limit when not throttling FPS.\n * @property {String} touchMode The current touch mode.\n * @property {Vector3f} lookAt The current lookat associated with these controls.\n */\nclass ControlsBase {\n /**\n * Creates an instance of ControlsBase.\n * @param {Renderer} renderer An instance of a Lore renderer.\n * @param {Vector3f} [lookAt=new Vector3f()] The look at vector of the controls.\n * @param {Boolean} [enableVR=false] Whether or not to track phone spatial information using the WebVR API.\n */\n constructor(\n renderer,\n lookAt = new Vector3f(0.0, 0.0, 0.0),\n enableVR = false\n ) {\n this.renderer = renderer;\n this.camera = renderer.camera;\n this.canvas = renderer.canvas;\n this.lowFps = 15;\n this.highFps = 30;\n this._eventListeners = {};\n this.renderer.setMaxFps(this.lowFps);\n this.touchMode = \"drag\";\n this.lookAt = lookAt;\n\n this.mouse = {\n previousPosition: {\n x: null,\n y: null\n },\n delta: {\n x: 0.0,\n y: 0.0\n },\n state: {\n left: false,\n middle: false,\n right: false\n },\n normalizedPosition: {\n x: 0.0,\n y: 0.0\n },\n moved: false,\n touches: 0,\n pointerCache: [],\n pinchDiff: 0\n };\n\n this.keyboard = {\n alt: false,\n ctrl: false,\n shift: false\n };\n\n this.VR = {};\n\n let that = this;\n\n // Set the touch action of the canvas\n this.canvas.style.touchAction = 'none';\n\n this.canvas.addEventListener(\"pointermove\", function(e) {\n // Find this event in the cache and update its record with this event\n for (var i = 0; i < that.mouse.pointerCache.length; i++) {\n if (e.pointerId == that.mouse.pointerCache[i].pointerId) {\n that.mouse.pointerCache[i] = e;\n break;\n }\n }\n \n // Get the current average / center of mass pointer location\n let pointerLoc = that.getPointerLocation();\n \n // Handle touch gestures and mouse events\n // If there are two pointer events, it has to be touch\n if (that.mouse.pointerCache.length === 2) {\n var diff = Math.pow(that.mouse.pointerCache[1].clientX - that.mouse.pointerCache[0].clientX, 2) +\n Math.pow(that.mouse.pointerCache[1].clientY - that.mouse.pointerCache[0].clientY, 2);\n\n if (that.mouse.pinchDiff > 0) {\n if (diff > that.mouse.pinchDiff) {\n that.raiseEvent(\"touch\", {\n e: { x: -1, y: -1, speed: 0.5 },\n source: \"pinch\"\n });\n }\n else if (diff < that.mouse.pinchDiff) {\n that.raiseEvent(\"touch\", {\n e: { x: 1, y: 1, speed: 0.5 },\n source: \"pinch\"\n });\n }\n }\n\n that.mouse.pinchDiff = diff;\n } else if (that.mouse.previousPosition.x !== null && that.mouse.pointerCache.length === 3) {\n that.mouse.delta.x = pointerLoc[0] - that.mouse.previousPosition.x;\n that.mouse.delta.y = pointerLoc[1] - that.mouse.previousPosition.y;\n\n that.mouse.moved = true;\n\n that.raiseEvent(\"mousedrag\", {\n e: that.mouse.delta,\n source: \"right\"\n });\n } else if (\n that.mouse.previousPosition.x !== null && (that.mouse.state.left ||\n that.mouse.state.middle ||\n that.mouse.state.right)\n ) {\n that.mouse.delta.x = pointerLoc[0] - that.mouse.previousPosition.x;\n that.mouse.delta.y = pointerLoc[1] - that.mouse.previousPosition.y;\n\n that.mouse.moved = true;\n\n // Give priority to left, then middle, then right\n if (that.mouse.state.left) {\n that.raiseEvent(\"mousedrag\", {\n e: that.mouse.delta,\n source: \"left\"\n });\n } else if (that.mouse.state.middle) {\n that.raiseEvent(\"mousedrag\", {\n e: that.mouse.delta,\n source: \"middle\"\n });\n } else if (that.mouse.state.right) {\n that.raiseEvent(\"mousedrag\", {\n e: that.mouse.delta,\n source: \"right\"\n });\n }\n }\n\n // Set normalized mouse position\n let rect = that.canvas.getBoundingClientRect();\n let s = that.renderer.devicePixelRatio;\n that.mouse.normalizedPosition.x =\n ((e.clientX - rect.left * s) / that.canvas.width) * s * 2 - 1;\n that.mouse.normalizedPosition.y =\n -(((e.clientY - rect.top * s) / that.canvas.height) * s) * 2 + 1;\n \n that.raiseEvent(\"mousemove\", {\n e: that\n });\n\n that.mouse.previousPosition.x = pointerLoc[0];\n that.mouse.previousPosition.y = pointerLoc[1];\n });\n\n let wheelevent = \"mousewheel\";\n if (navigator.userAgent.toLowerCase().indexOf(\"firefox\") > -1)\n wheelevent = \"DOMMouseScroll\";\n\n this.canvas.addEventListener(wheelevent, function(e) {\n if (that.isInIframe() && !e.ctrlKey) {\n return;\n }\n\n e.preventDefault();\n\n let delta = \"wheelDelta\" in e ? e.wheelDelta : -40 * e.detail;\n that.raiseEvent(\"mousewheel\", {\n e: delta\n });\n });\n\n this.canvas.addEventListener(\"keydown\", function(e) {\n if (e.which == 16) {\n that.keyboard.shift = true;\n } else if (e.which == 17) {\n that.keyboard.ctrl = true;\n } else if (e.which == 18) {\n that.keyboard.alt = true;\n }\n\n that.raiseEvent(\"keydown\", {\n e: e.which\n });\n });\n\n this.canvas.addEventListener(\"keyup\", function(e) {\n if (e.which == 16) {\n that.keyboard.shift = false;\n } else if (e.which == 17) {\n that.keyboard.ctrl = false;\n } else if (e.which == 18) {\n that.keyboard.alt = false;\n }\n\n that.raiseEvent(\"keyup\", {\n e: e.which\n });\n });\n\n this.canvas.addEventListener(\"pointerdown\", function(e) {\n let btn = e.button;\n let source = \"left\";\n that.mouse.pointerCache.push(e);\n\n // Only handle single button events\n if (btn == 0) {\n that.mouse.state.left = true;\n } else if (btn == 1) {\n that.mouse.state.middle = true;\n source = \"middle\";\n } else if (btn == 2) {\n that.mouse.state.right = true;\n source = \"right\";\n }\n\n that.renderer.setMaxFps(that.highFps);\n that.mouse.moved = false;\n\n that.raiseEvent(\"mousedown\", {\n e: that,\n source: source\n });\n });\n\n this.canvas.addEventListener(\"click\", function(e) {\n let btn = e.button;\n let source = \"left\";\n \n if (!that.mouse.moved) {\n that.raiseEvent(\"click\", {\n e: that,\n source: source\n });\n } \n });\n\n this.canvas.addEventListener(\"dblclick\", function(e) {\n let btn = e.button;\n let source = \"left\";\n\n that.raiseEvent(\"dblclick\", {\n e: that,\n source: source\n });\n });\n\n // This function is added to multiple pointer events\n let pointerUpEvent = function(e) {\n let btn = e.button;\n let source = \"left\";\n that.removeEvent(e);\n that.mouse.pinchDiff = 0;\n\n // Only handle single button events\n if (btn == 0) {\n that.mouse.state.left = false;\n } else if (btn == 1) {\n that.mouse.state.middle = false;\n source = \"middle\";\n } else if (btn == 2) {\n that.mouse.state.right = false;\n source = \"right\";\n }\n\n // Reset the previous position and delta of the mouse\n that.mouse.previousPosition.x = null;\n that.mouse.previousPosition.y = null;\n that.mouse.state.left = false;\n that.mouse.state.middle = false;\n that.mouse.state.right = false;\n\n that.renderer.setMaxFps(that.lowFps);\n\n that.raiseEvent(\"mouseup\", {\n e: that,\n source: source\n });\n };\n\n this.canvas.addEventListener(\"pointerup\", function(e) {\n pointerUpEvent(e);\n });\n\n this.canvas.addEventListener(\"pointercancel\", function(e) {\n pointerUpEvent(e);\n });\n\n this.canvas.addEventListener(\"pointerleave\", function(e) {\n pointerUpEvent(e);\n });\n }\n\n /**\n * Initialiizes WebVR, if the API is available and the device suppports it.\n */\n /*\n initWebVR() {\n if (navigator && navigator.getVRDevices) {\n navigator.getVRDisplays().then(function (displays) {\n if (displays.length === 0) {\n return;\n }\n\n for (var i = 0; i < displays.length; ++i) {\n\n }\n });\n }\n }\n */\n\n /**\n * Adds an event listener to this controls instance.\n *\n * @param {String} eventName The name of the event that is to be listened for.\n * @param {Function} callback A callback function to be called on the event being fired.\n */\n addEventListener(eventName, callback) {\n if (!this._eventListeners[eventName]) {\n this._eventListeners[eventName] = [];\n }\n\n this._eventListeners[eventName].push(callback);\n }\n\n /**\n * Remove an event listener from this controls instance.\n *\n * @param {String} eventName The name of the event that is to be listened for.\n * @param {Function} callback A callback function to be called on the event being fired.\n */\n removeEventListener(eventName, callback) {\n if (!this._eventListeners.hasOwnProperty(eventName)) {\n return;\n }\n\n let index = this._eventListeners[eventName].indexOf(callback);\n\n if (index > -1) {\n this._eventListeners[eventName].splice(index, 1);\n }\n }\n\n /**\n * Raises an event.\n *\n * @param {String} eventName The name of the event to be raised.\n * @param {*} [data={}] The data to be supplied to the callback function.\n */\n raiseEvent(eventName, data = {}) {\n if (this._eventListeners[eventName]) {\n for (let i = 0; i < this._eventListeners[eventName].length; i++) {\n this._eventListeners[eventName][i](data);\n }\n }\n }\n\n /**\n * Returns the current look at vector associated with this controls.\n *\n * @returns {Vector3f} The current look at vector.\n */\n getLookAt() {\n return this.lookAt;\n }\n\n /**\n * Virtual method. Sets the lookat vector, which is the center of the orbital camera sphere.\n *\n * @param {Vector3f} lookAt The lookat vector.\n * @returns {ControlsBase} Returns itself.\n */\n setLookAt(lookAt) {\n return null;\n }\n\n /**\n * Update the camera (on mouse move, touch drag, mousewheel scroll, ...).\n *\n * @param {*} [e=null] A mouse or touch events data.\n * @param {String} [source=null] The source of the input ('left', 'middle', 'right', 'wheel', ...).\n * @returns {ControlsBase} Returns itself.\n */\n update(e = null, source = null) {\n return this;\n }\n\n /**\n * Checks whether the script is being run in an IFrame.\n *\n * @returns {Boolean} Returns whether the script is run in an IFrame.\n */\n isInIframe() {\n try {\n return window.self !== window.top;\n } catch (e) {\n return true;\n }\n }\n\n /**\n * Removes a pointer event from the event cache.\n *\n * @param {PointerEvent} e The pointer event\n */\n removeEvent(e) {\n for (var i = 0; i < this.mouse.pointerCache.length; i++) {\n if (this.mouse.pointerCache[i].pointerId == e.pointerId) {\n this.mouse.pointerCache.splice(i, 1);\n break;\n }\n }\n }\n\n /**\n * Get the position of the pointer (e.g. the mouse). In case of multi-\n * touch, the center of mass is returned.\n * \n * @returns {Number[]} The pointer position\n */\n getPointerLocation() {\n let x = 0;\n let y = 0;\n let n = this.mouse.pointerCache.length;\n\n if (n === 0) return [null, null];\n\n for (var i = 0; i < n; i++) {\n x += this.mouse.pointerCache[i].pageX;\n y += this.mouse.pointerCache[i].pageY;\n }\n\n return [x, y];\n }\n}\n\nmodule.exports = ControlsBase;\n" }, { "alpha_fraction": 0.5883433818817139, "alphanum_fraction": 0.5967769026756287, "avg_line_length": 24.972972869873047, "blob_id": "57728d98e661d455c449862945693bb849e6f9a4", "content_id": "0dd5e293b7ee37030f3a250bd649541dc133f553", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 11976, "license_type": "permissive", "max_line_length": 120, "num_lines": 444, "path": "/src/Controls/OrbitalControls.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\r\n\r\nconst ControlsBase = require(\"../Controls/ControlsBase\");\r\nconst Vector3f = require(\"../Math/Vector3f\");\r\nconst SphericalCoords = require(\"../Math/SphericalCoords\");\r\n\r\n/**\r\n * A class representing orbital controls.\r\n *\r\n * @property {Vector3f} up The global up vector.\r\n * @property {Number} radius The distance from the camera to the lookat vector.\r\n * @property {Number} [yRotationLimit=Math.PI] The limit for the vertical rotation.\r\n * @property {SphericalCoords} spherical The spherical coordinates of the camera on the sphere around the lookat vector.\r\n * @property {Number} scale The sensitivity scale.\r\n * @property {CameraBase} camera The camera associated with these controls.\r\n */\r\nclass OrbitalControls extends ControlsBase {\r\n /**\r\n * Creates an instance of OrbitalControls.\r\n * @param {Renderer} renderer An instance of a Lore renderer.\r\n * @param {Number} radius The distance of the camera to the lookat vector.\r\n * @param {Vector3f} lookAt The lookat vector.\r\n */\r\n constructor(renderer, radius, lookAt = new Vector3f(0.0, 0.0, 0.0)) {\r\n super(renderer, lookAt);\r\n\r\n this.up = Vector3f.up();\r\n this.radius = radius;\r\n\r\n this.yRotationLimit = Math.PI;\r\n\r\n this._dPhi = 0.0;\r\n this._dTheta = 0.0;\r\n this._dPan = new Vector3f(0.0, 0.0, 0.0);\r\n\r\n this.spherical = new SphericalCoords();\r\n\r\n this.scale = 0.95;\r\n\r\n this.camera.position = new Vector3f(radius, radius, radius);\r\n this.camera.updateProjectionMatrix();\r\n this.camera.updateViewMatrix();\r\n\r\n this.rotationLocked = false;\r\n\r\n let that = this;\r\n\r\n this.addEventListener(\"mousedrag\", function (e) {\r\n that.update(e.e, e.source);\r\n });\r\n\r\n this.addEventListener(\"touch\", function (e) {\r\n that.update(e.e, e.source);\r\n });\r\n\r\n this.addEventListener(\"mousewheel\", function (e) {\r\n that.update(\r\n {\r\n x: 0,\r\n y: -e.e\r\n },\r\n \"wheel\"\r\n );\r\n });\r\n\r\n // Initial update\r\n this.update(\r\n {\r\n x: 0,\r\n y: 0\r\n },\r\n \"left\"\r\n );\r\n }\r\n\r\n /**\r\n * Limit the vertical rotation to the horizon (the upper hemisphere).\r\n *\r\n * @param {Boolean} limit A boolean indicating whether or not to limit the vertical rotation to the horizon.\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n limitRotationToHorizon(limit) {\r\n if (limit) {\r\n this.yRotationLimit = 0.5 * Math.PI;\r\n } else {\r\n this.yRotationLimit = Math.PI;\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Sets the distance (radius of the sphere) from the lookat vector to the camera.\r\n *\r\n * @param {Number} radius The radius.\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n setRadius(radius) {\r\n this.radius = radius;\r\n this.camera.position = new Vector3f(0, 0, radius);\r\n\r\n this.camera.updateProjectionMatrix();\r\n this.camera.updateViewMatrix();\r\n this.update();\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Update the camera (on mouse move, touch drag, mousewheel scroll, ...).\r\n *\r\n * @param {*} [e=null] A mouse or touch events data.\r\n * @param {String} [source=null] The source of the input ('left', 'middle', 'right', 'wheel', ...).\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n update(e = null, source = null) {\r\n if (source == \"left\" && !this.rotationLocked) {\r\n // Rotate\r\n this._dTheta =\r\n (-2 * Math.PI * e.x) / (this.canvas.clientWidth * this.camera.zoom);\r\n this._dPhi =\r\n (-2 * Math.PI * e.y) / (this.canvas.clientHeight * this.camera.zoom);\r\n\r\n // It's just to fast like this ...\r\n // this._dTheta = -2 * Math.PI * e.x / this.canvas.clientWidth;\r\n // this._dPhi = -2 * Math.PI * e.y / this.canvas.clientHeight;\r\n } else if (source == \"right\" || (source == \"left\" && this.rotationLocked)) {\r\n // Translate\r\n let x =\r\n (e.x * (this.camera.right - this.camera.left)) /\r\n this.camera.zoom /\r\n this.canvas.clientWidth;\r\n let y =\r\n (e.y * (this.camera.top - this.camera.bottom)) /\r\n this.camera.zoom /\r\n this.canvas.clientHeight;\r\n\r\n let u = this.camera.getUpVector().components;\r\n let r = this.camera.getRightVector().components;\r\n\r\n this._dPan.components[0] = r[0] * -x + u[0] * y;\r\n this._dPan.components[1] = r[1] * -x + u[1] * y;\r\n this._dPan.components[2] = r[2] * -x + u[2] * y;\r\n } else if (source == \"middle\" || source == \"wheel\" || source == \"pinch\") {\r\n if (e.y > 0) {\r\n // Zoom Out\r\n this.camera.zoom = Math.max(0, this.camera.zoom * this.scale);\r\n this.camera.updateProjectionMatrix();\r\n this.raiseEvent(\"zoomchanged\", this.camera.zoom);\r\n } else if (e.y < 0) {\r\n // Zoom In\r\n this.camera.zoom = Math.max(0, this.camera.zoom / this.scale);\r\n this.camera.updateProjectionMatrix();\r\n this.raiseEvent(\"zoomchanged\", this.camera.zoom);\r\n }\r\n }\r\n\r\n // Update the camera\r\n let offset = this.camera.position.clone().subtract(this.lookAt);\r\n\r\n this.spherical.setFromVector(offset);\r\n this.spherical.components[1] += this._dPhi;\r\n this.spherical.components[2] += this._dTheta;\r\n this.spherical.limit(0, this.yRotationLimit, -Infinity, Infinity);\r\n this.spherical.secure();\r\n\r\n // Limit radius here\r\n this.lookAt.add(this._dPan);\r\n offset.setFromSphericalCoords(this.spherical);\r\n\r\n this.camera.position.copyFrom(this.lookAt).add(offset);\r\n this.camera.setLookAt(this.lookAt);\r\n this.camera.updateViewMatrix();\r\n\r\n this._dPhi = 0.0;\r\n this._dTheta = 0.0;\r\n this._dPan.set(0, 0, 0);\r\n\r\n this.raiseEvent(\"updated\");\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Sets the lookat vector, which is the center of the orbital camera sphere.\r\n *\r\n * @param {Vector3f} lookAt The lookat vector.\r\n * @returns {ControlsBase} Returns itself.\r\n */\r\n setLookAt(lookAt) {\r\n // TODO: Most of this code (except for setting lookAt to lookAt instead of _dPan)\r\n // is compied from updated. Maybe fix that\r\n\r\n // Update the camera\r\n let offset = this.camera.position.clone().subtract(this.lookAt);\r\n\r\n this.spherical.setFromVector(offset);\r\n this.spherical.components[1] += this._dPhi;\r\n this.spherical.components[2] += this._dTheta;\r\n this.spherical.limit(0, this.yRotationLimit, -Infinity, Infinity);\r\n this.spherical.secure();\r\n\r\n // Limit radius here\r\n this.lookAt = lookAt.clone();\r\n offset.setFromSphericalCoords(this.spherical);\r\n\r\n this.camera.position.copyFrom(this.lookAt).add(offset);\r\n this.camera.setLookAt(this.lookAt);\r\n this.camera.updateViewMatrix();\r\n\r\n this.raiseEvent(\"updated\");\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Moves the camera around the sphere by spherical coordinates.\r\n *\r\n * @param {Number} phi The phi component of the spherical coordinates.\r\n * @param {Number} theta The theta component of the spherical coordinates.\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n setView(phi, theta) {\r\n let offset = this.camera.position.clone().subtract(this.lookAt);\r\n\r\n this.spherical.setFromVector(offset);\r\n this.spherical.components[1] = phi;\r\n this.spherical.components[2] = theta;\r\n this.spherical.secure();\r\n\r\n offset.setFromSphericalCoords(this.spherical);\r\n\r\n this.camera.position.copyFrom(this.lookAt).add(offset);\r\n this.camera.setLookAt(this.lookAt);\r\n this.camera.updateViewMatrix();\r\n this.raiseEvent(\"updated\");\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Zoom in on the lookat vector.\r\n *\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n zoomIn() {\r\n this.camera.zoom = Math.max(0, this.camera.zoom / this.scale);\r\n this.camera.updateProjectionMatrix();\r\n this.raiseEvent(\"zoomchanged\", this.camera.zoom);\r\n this.raiseEvent(\"updated\");\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Zoom out from the lookat vector.\r\n *\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n zoomOut() {\r\n this.camera.zoom = Math.max(0, this.camera.zoom * this.scale);\r\n this.camera.updateProjectionMatrix();\r\n this.raiseEvent(\"zoomchanged\", this.camera.zoom);\r\n this.raiseEvent(\"updated\");\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set the zoom to a given value.\r\n *\r\n * @param {Number} zoom The zoom value.\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n setZoom(zoom) {\r\n this.camera.zoom = zoom;\r\n this.camera.updateProjectionMatrix();\r\n this.raiseEvent(\"zoomchanged\", this.camera.zoom);\r\n this.update();\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Get the zoom.\r\n *\r\n * @returns {Number} The zoom value.\r\n */\r\n getZoom() {\r\n return this.camera.zoom;\r\n }\r\n\r\n /**\r\n * Set zoom so it contains a bounding box\r\n * \r\n * @param {Number} width The width of the square to be contained.\r\n * @param {Number} height The height of the square to be contained.\r\n * @param {Number} padding Padding applied to the zoom as a fraction of width and height.\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n zoomTo(width, height, padding = 0.0) {\r\n if (this.camera.type !== 'Lore.OrthographicCamera') {\r\n throw ('Feature not implemented.');\r\n }\r\n\r\n this.setZoom(this.camera.getRequiredZoomToContain(\r\n width,\r\n height,\r\n padding\r\n ));\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * \r\n * @param {Vector3f} v The vector to pan to.\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n panTo(v) {\r\n return this;\r\n }\r\n\r\n /**\r\n * Sets the view by name (left, right, top, bottom, back, front, free)\r\n *\r\n * @param {String} viewName The name of the view.\r\n *\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n\r\n setViewByName(viewName) {\r\n switch (viewName) {\r\n case \"left\":\r\n this.setLeftView();\r\n break;\r\n case \"right\":\r\n this.setRightView();\r\n break;\r\n case \"top\":\r\n this.setTopView();\r\n break;\r\n case \"bottom\":\r\n this.setBottomView();\r\n break;\r\n case \"back\":\r\n this.setBackView();\r\n break;\r\n case \"front\":\r\n this.setFrontView();\r\n break;\r\n default:\r\n this.setFreeView();\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set the camera to the top view (locks rotation).\r\n *\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n setTopView() {\r\n this.setView(0.0, 2.0 * Math.PI);\r\n this.rotationLocked = true;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set the camera to the bottom view (locks rotation).\r\n *\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n setBottomView() {\r\n this.setView(0.0, 0.0);\r\n this.rotationLocked = true;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set the camera to the right view (locks rotation).\r\n *\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n setRightView() {\r\n this.setView(0.5 * Math.PI, 0.5 * Math.PI);\r\n this.rotationLocked = true;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set the camera to the left view (locks rotation).\r\n *\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n setLeftView() {\r\n this.setView(0.5 * Math.PI, -0.5 * Math.PI);\r\n this.rotationLocked = true;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set the camera to the front view (locks rotation).\r\n *\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n setFrontView() {\r\n this.setView(0.5 * Math.PI, 2.0 * Math.PI);\r\n this.rotationLocked = true;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set the camera to the back view (locks rotation).\r\n *\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n setBackView() {\r\n this.setView(0.5 * Math.PI, Math.PI);\r\n this.rotationLocked = true;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set the camera to free view (unlocks rotation).\r\n *\r\n * @returns {OrbitalControls} Returns itself.\r\n */\r\n setFreeView() {\r\n this.setView(0.25 * Math.PI, 0.25 * Math.PI);\r\n this.rotationLocked = false;\r\n\r\n return this;\r\n }\r\n}\r\n\r\nmodule.exports = OrbitalControls;\r\n" }, { "alpha_fraction": 0.5561426877975464, "alphanum_fraction": 0.5931307673454285, "avg_line_length": 31.923913955688477, "blob_id": "eac34dd0f984b0f99a5a0e050c162132ef1ee983", "content_id": "56987143d120efc269ca8e4b7a9b2376250884a6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3028, "license_type": "permissive", "max_line_length": 143, "num_lines": 92, "path": "/example/flybrain2.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "(function () {\n let lore = Lore.init('lore', {\n clearColor: '#222222'\n });\n\n let fileReader = new Lore.IO.CsvFileReader('input-upload', {\n cols: [0, 1, 2, 3],\n types: ['Uint16Array', 'Uint16Array', 'Uint16Array', 'Float32Array']\n });\n let pointHelper = null;\n let octreeHelper = null;\n let original_data = null;\n\n fileReader.addEventListener('loaded', function (data) {\n original_data = data;\n pointHelper = new Lore.Helpers.PointHelper(lore, 'Seppli', 'defaultSquare');\n pointHelper.setPositionsXYZHSS(data['x'], data['y'], data['z'], data['c'], 1.0, 1.0)\n pointHelper.setPointScale(1.0);\n pointHelper.setFog([0.05, 0.05, 0.05, 1.0], 6.0);\n pointHelper.addFilter('hueRange', new Lore.Filters.InRangeFilter('color', 0, 0.22, 0.25));\n\n lore.controls.setLookAt(pointHelper.getCenter());\n lore.controls.setRadius(pointHelper.getMaxRadius());\n\n octreeHelper = new Lore.Helpers.OctreeHelper(lore, 'OctreeGeometry', 'tree', pointHelper, {\n visualize: 'cubes'\n });\n\n octreeHelper.addEventListener('hoveredchanged', function (e) {\n let indicator = document.getElementById('indicator');\n let data = document.getElementById('data');\n\n if (e.e) {\n indicator.style.opacity = 1.0;\n indicator.style.left = (e.e.screenPosition[0] - 2) + 'px';\n indicator.style.top = (e.e.screenPosition[1] - 10) + 'px';\n data.innerHTML = '(' + original_data['x'][e.e.index] + ',' + original_data['y'][e.e.index] + ',' + original_data['z'][e.e.index] + ')';\n } else {\n indicator.style.opacity = 0.0;\n data.innerHTML = '';\n }\n });\n });\n\n document.addEventListener('keydown', function (e) {\n if (e.keyCode === 48) {\n let filter = pointHelper.getFilter('hueRange');\n filter.reset();\n } else if (e.keyCode === 49) {\n let filter = pointHelper.getFilter('hueRange');\n filter.setMin(0.0);\n filter.setMax(0.05);\n filter.filter();\n } else if (e.keyCode == 50) {\n let filter = pointHelper.getFilter('hueRange');\n filter.setMin(0.05);\n filter.setMax(0.15);\n filter.filter();\n } else if (e.keyCode == 51) {\n let filter = pointHelper.getFilter('hueRange');\n filter.setMin(0.15);\n filter.setMax(0.25);\n filter.filter();\n } else if (e.keyCode == 52) {\n let filter = pointHelper.getFilter('hueRange');\n filter.setMin(0.35);\n filter.setMax(0.45);\n filter.filter();\n } else if (e.keyCode == 53) {\n let filter = pointHelper.getFilter('hueRange');\n filter.setMin(0.55);\n filter.setMax(0.65);\n filter.filter();\n } else if (e.keyCode == 54) {\n let filter = pointHelper.getFilter('hueRange');\n filter.setMin(0.75);\n filter.setMax(0.85);\n filter.filter();\n } else if (e.keyCode == 55) {\n console.log('test');\n octreeHelper.getVisible();\n } else if (e.keyCode == 56) {\n\n } else if (e.keyCode == 57) {\n\n } else if (e.keyCode == 58) {\n\n } else if (e.keyCode == 59) {\n\n }\n });\n})();" }, { "alpha_fraction": 0.7698744535446167, "alphanum_fraction": 0.7698744535446167, "avg_line_length": 25.66666603088379, "blob_id": "c59f114384568f2bd2f0ea301632ea49a7195b0a", "content_id": "83d98aed0bd596a9be8818d08294139984c95975", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 239, "license_type": "permissive", "max_line_length": 59, "num_lines": 9, "path": "/src/Cameras/index.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "const CameraBase = require('./CameraBase');\nconst OrthographicCamera = require('./OrthographicCamera');\nconst PerspectiveCamera = require('./PerspectiveCamera');\n\nmodule.exports = {\n CameraBase,\n OrthographicCamera,\n PerspectiveCamera\n}" }, { "alpha_fraction": 0.48206618428230286, "alphanum_fraction": 0.4986390769481659, "avg_line_length": 25.037796020507812, "blob_id": "cbe0afe5ba2ea57bf534b7558128a6140c3a3d2f", "content_id": "c4f7346549749b2bd4d918120ef5fcf7168b221e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 16533, "license_type": "permissive", "max_line_length": 182, "num_lines": 635, "path": "/src/Core/Graph.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\n\n/** \n * A class representing the molecular graph. \n * \n * @property {Array[]} distanceMatrix The distance matrix of this graph.\n */\nclass Graph {\n /**\n * The constructor of the class Graph.\n * \n * @param {Array[]} adjacencyMatrix The weighted adjacency matrix of a graph.\n */\n constructor(adjacencyMatrix) {\n this.adjacencyMatrix = adjacencyMatrix;\n\n // Replace zeros with infinity\n for (var i = 0; i < this.adjacencyMatrix.length; i++) {\n for (var j = 0; j < this.adjacencyMatrix.length; j++) {\n if (this.adjacencyMatrix[i][j] === 0) {\n this.adjacencyMatrix[i][j] = Infinity;\n }\n }\n }\n\n this.distanceMatrix = this.getDistanceMatrix();\n this.diameter = this.getDiameter();\n }\n\n /**\n * Returns the unweighted adjacency matrix of this graph.\n * \n * @returns {Array} The unweighted adjacency matrix of this graph.\n */\n getUnweightedAdjacencyMatrix() {\n let length = this.adjacencyMatrix.length;\n let unweightedAdjacencyMatrix = Array(length);\n\n for (var i = 0; i < length; i++) {\n unweightedAdjacencyMatrix[i] = new Uint8Array(length);\n\n for (var j = 0; j < length; j++) {\n unweightedAdjacencyMatrix[i][j] = this.adjacencyMatrix[i][j] > 0 ? 1 : 0;\n }\n }\n\n return unweightedAdjacencyMatrix;\n }\n\n /**\n * Returns an edge list of this graph.\n * \n * @returns {Array} An array of edges in the form of [vertexId, vertexId, edgeWeight].\n */\n getEdgeList() {\n let length = this.adjacencyMatrix.length;\n let edgeList = Array();\n\n for (var i = 0; i < length - 1; i++) {\n for (var j = i; j < length; j++) {\n if (this.adjacencyMatrix[i][j] !== Infinity) {\n edgeList.push([i, j, this.adjacencyMatrix[i][j]]);\n }\n }\n }\n\n return edgeList;\n }\n\n /**\n * \n */\n forceLayout(radius = 1000, iterations = 1000, q = 1.5, k = 0.01, ke = 1000.0, zoom = 1.0) {\n let matDist = this.distanceMatrix.slice();\n let length = matDist.length;\n let nNeighbours = new Int16Array(length);\n\n // Get the number of neighbours\n for (var i = 0; i < length; i++) {\n nNeighbours[i] = this.adjacencyMatrix[i].reduce((acc, val) => (val !== Infinity) ? ++acc : acc, 0);\n }\n\n // Square distances\n for (var i = 0; i < length; i++) {\n for (var j = 0; j < length; j++) {\n matDist[i][j] = Math.pow(matDist[i][j], q);\n }\n }\n\n // Normalize distance matrix\n let max = 0.0;\n\n for (var i = 0; i < length; i++) {\n for (var j = 0; j < length; j++) {\n if (matDist[i][j] > max) {\n max = matDist[i][j];\n }\n }\n }\n\n for (var i = 0; i < length; i++) {\n for (var j = 0; j < length; j++) {\n // Added math pow to decrease influence of long distances\n matDist[i][j] = matDist[i][j] / max;\n }\n }\n\n // Forces\n let fx = new Float32Array(length);\n let fy = new Float32Array(length);\n\n // Positions\n let px = new Float32Array(length);\n let py = new Float32Array(length);\n\n // Initialize positions to random values\n for (var i = 0; i < length; i++) {\n px[i] = Math.random() * radius;\n py[i] = Math.random() * radius;\n }\n\n for (var n = 0; n < iterations; n++) {\n // Spring forces\n for (var i = 0; i < length - 1; i++) {\n for (var j = i + 1; j < length; j++) {\n if (matDist[i][j] === Infinity) {\n continue;\n }\n\n let dx = px[i] - px[j];\n let dy = py[i] - py[j];\n\n let d = Math.sqrt(Math.pow(dx, 2.0) + Math.pow(dy, 2.0));\n\n if (d === 0) {\n d = 0.01;\n }\n\n // Normalize dx and dy to d\n dx /= d;\n dy /= d;\n\n // Hooke's law, F=kX, is the force between x and y\n let f = k * (matDist[i][j] * radius - d);\n\n if (this.adjacencyMatrix[i][j] !== Infinity) {\n f *= length;\n }\n\n fx[i] += f * dx;\n fy[i] += f * dy;\n\n fx[j] += -f * dx;\n fy[j] += -f * dy;\n }\n }\n\n // Repulsive forces between vertices\n for (var i = 0; i < length - 1; i++) {\n for (var j = i; j < length; j++) {\n for (var j = i; j < length; j++) {\n if (this.adjacencyMatrix[i][j] !== Infinity) {\n continue;\n }\n \n let dx = px[i] - px[j];\n let dy = py[i] - py[j];\n\n let dSquared = Math.pow(dx, 2.0) + Math.pow(dy, 2.0);\n let d = Math.sqrt(dSquared);\n\n if (d === 0) {\n d = 0.01;\n }\n\n if (dSquared === 0) {\n dSquared = 0.05;\n }\n\n // Normalize dx and dy to d\n dx /= d;\n dy /= d;\n\n // Coulomb's law, F = k_e * q1 * q2 / r^2, is the force between x and y\n let f = ke / dSquared;\n\n fx[i] += f * dx;\n fy[i] += f * dy;\n\n fx[j] += -f * dx;\n fy[j] += -f * dy;\n }\n }\n }\n\n // Move the vertices\n for (var i = 0; i < length; i++) {\n \n\n // fx[i] = Math.min(Math.max(-1, fx[i]), 1);\n // fy[i] = Math.min(Math.max(-1, fy[i]), 1);\n\n fx[i] = Math.sign(fx[i]) * Math.sqrt(Math.abs(fx[i]));\n fy[i] = Math.sign(fy[i]) * Math.sqrt(Math.abs(fy[i]));\n\n px[i] += fx[i];\n py[i] += fy[i];\n }\n\n // Reset force and position deltas\n for (var i = 0; i < length; i++) {\n fx[i] = 0.0;\n fy[i] = 0.0;\n }\n }\n\n // Move the graph to the center\n let avgX = 0.0;\n let avgY = 0.0;\n\n for (var i = 0; i < length; i++) {\n // Zoom\n px[i] *= zoom;\n py[i] *= zoom;\n\n avgX += px[i];\n avgY += py[i]; \n }\n\n avgX /= length;\n avgY /= length;\n\n for (var i = 0; i < length; i++) {\n px[i] = px[i] - (avgX - radius / 2.0);\n py[i] = py[i] - (avgY - radius / 2.0);\n }\n\n let positions = Array(length);\n\n for (var i = 0; i < length; i++) {\n positions[i] = [px[i], py[i]];\n }\n\n return [positions, this.getEdgeList()];\n }\n\n /**\n * Positiones the (sub)graph using Kamada and Kawais algorithm for drawing general undirected graphs. https://pdfs.semanticscholar.org/b8d3/bca50ccc573c5cb99f7d201e8acce6618f04.pdf\n * \n * @param {Number} radius The radius within which to initialize the vertices.\n * @param {Boolean} logWeights Apply log() to the weights before layouting.\n * @param {Boolean} squareWeights Apply pow(x,2) to the weights before layouting.\n * @param {Boolean} normalizeWeights Normalize the edge weights before layouting and after log() or exp().\n * @return {Array} An array of vertex positions of the form [ x, y ].\n */\n kkLayout(radius = 500, logWeights = false, squareWeights = false, normalizeWeights = false) {\n let edgeStrength = 50.0;\n\n let matDist = this.distanceMatrix;\n let length = this.distanceMatrix.length;\n\n // Transform data\n if (logWeights) {\n for (var i = 0; i < length; i++) {\n for (var j = 0; j < length; j++) {\n if (matDist[i][j] !== Infinity) {\n matDist[i][j] = Math.log(matDist[i][j]);\n }\n }\n }\n }\n\n if (normalizeWeights) {\n for (var i = 0; i < length; i++) {\n for (var j = 0; j < length; j++) {\n if (matDist[i][j] !== Infinity && matDist[i][j] !== 0) {\n matDist[i][j] = Math.pow(matDist[i][j], 2.0);\n }\n }\n }\n }\n\n // Normalize the edge weights\n if (normalizeWeights) {\n let maxWeight = 0;\n\n for (var i = 0; i < length; i++) {\n for (var j = 0; j < length; j++) {\n if (matDist[i][j] > maxWeight && matDist[i][j] !== Infinity) {\n maxWeight = matDist[i][j];\n }\n }\n }\n\n for (var i = 0; i < length; i++) {\n for (var j = 0; j < length; j++) {\n if (matDist[i][j] !== Infinity) {\n matDist[i][j] = matDist[i][j] / maxWeight;\n }\n }\n }\n }\n\n // Initialize the positions. Place all vertices on a ring around the center\n let halfR\n let angle = 2 * Math.PI / length;\n let a = 0.0;\n let arrPositionX = new Float32Array(length);\n let arrPositionY = new Float32Array(length);\n let arrPositioned = Array(length);\n let l = radius / (2 * this.diameter);\n console.log('l: ' + l);\n console.log('diameter: ' + this.diameter);\n\n radius /= 2.0;\n\n var i = length;\n while (i--) {\n arrPositionX[i] = radius + Math.cos(a) * radius;\n arrPositionY[i] = radius + Math.sin(a) * radius;\n\n arrPositioned[i] = false;\n a += angle;\n }\n\n // Create the matrix containing the lengths\n let matLength = Array(length);\n i = length;\n while (i--) {\n matLength[i] = new Array(length);\n var j = length;\n while (j--) {\n matLength[i][j] = l * matDist[i][j];\n }\n }\n\n // Create the matrix containing the spring strenghts\n let matStrength = Array(length);\n i = length;\n while (i--) {\n matStrength[i] = Array(length);\n var j = length;\n while (j--) {\n matStrength[i][j] = edgeStrength * Math.pow(matDist[i][j], -2.0);\n }\n }\n\n // Create the matrix containing the energies\n let matEnergy = Array(length);\n let arrEnergySumX = new Float32Array(length);\n let arrEnergySumY = new Float32Array(length);\n i = length;\n while (i--) {\n matEnergy[i] = Array(length);\n }\n\n i = length;\n let ux, uy, dEx, dEy, vx, vy, denom;\n\n while (i--) {\n ux = arrPositionX[i];\n uy = arrPositionY[i];\n dEx = 0.0;\n dEy = 0.0;\n let j = length;\n while (j--) {\n if (i === j) {\n continue;\n }\n vx = arrPositionX[j];\n vy = arrPositionY[j];\n denom = 1.0 / Math.sqrt((ux - vx) * (ux - vx) + (uy - vy) * (uy - vy));\n matEnergy[i][j] = [\n matStrength[i][j] * ((ux - vx) - matLength[i][j] * (ux - vx) * denom) || 0.0,\n matStrength[i][j] * ((uy - vy) - matLength[i][j] * (uy - vy) * denom) || 0.0\n ]\n matEnergy[j][i] = matEnergy[i][j];\n dEx += matEnergy[i][j][0];\n dEy += matEnergy[i][j][1];\n }\n arrEnergySumX[i] = dEx;\n arrEnergySumY[i] = dEy;\n }\n\n // Utility functions, maybe inline them later\n let energy = function (index) {\n return [arrEnergySumX[index] * arrEnergySumX[index] + arrEnergySumY[index] * arrEnergySumY[index], arrEnergySumX[index], arrEnergySumY[index]];\n }\n\n let highestEnergy = function () {\n let maxEnergy = 0.0;\n let maxEnergyId = 0;\n let maxDEX = 0.0;\n let maxDEY = 0.0\n\n i = length;\n while (i--) {\n let [delta, dEX, dEY] = energy(i);\n\n if (delta > maxEnergy) {\n maxEnergy = delta;\n maxEnergyId = i;\n maxDEX = dEX;\n maxDEY = dEY;\n }\n }\n\n return [maxEnergyId, maxEnergy, maxDEX, maxDEY];\n }\n\n let update = function (index, dEX, dEY) {\n let dxx = 0.0;\n let dyy = 0.0;\n let dxy = 0.0;\n let ux = arrPositionX[index];\n let uy = arrPositionY[index];\n let arrL = matLength[index];\n let arrK = matStrength[index];\n\n i = length;\n while (i--) {\n if (i === index) {\n continue;\n }\n\n let vx = arrPositionX[i];\n let vy = arrPositionY[i];\n let l = arrL[i];\n let k = arrK[i];\n let m = (ux - vx) * (ux - vx);\n let denom = 1.0 / Math.pow(m + (uy - vy) * (uy - vy), 1.5);\n\n dxx += k * (1 - l * (uy - vy) * (uy - vy) * denom) || 0.0;\n dyy += k * (1 - l * m * denom) || 0.0;\n dxy += k * (l * (ux - vx) * (uy - vy) * denom) || 0.0;\n }\n\n // Prevent division by zero\n if (dxx === 0) {\n dxx = 0.1;\n }\n\n if (dyy === 0) {\n dyy = 0.1;\n }\n\n if (dxy === 0) {\n dxy = 0.1;\n }\n\n let dy = (dEX / dxx + dEY / dxy);\n dy /= (dxy / dxx - dyy / dxy); // had to split this onto two lines because the syntax highlighter went crazy.\n let dx = -(dxy * dy + dEX) / dxx;\n\n arrPositionX[index] += dx;\n arrPositionY[index] += dy;\n\n // Update the energies\n let arrE = matEnergy[index];\n dEX = 0.0;\n dEY = 0.0;\n\n ux = arrPositionX[index];\n uy = arrPositionY[index];\n\n let vx, vy, prevEx, prevEy, denom;\n\n i = length;\n while (i--) {\n if (index === i) {\n continue;\n }\n vx = arrPositionX[i];\n vy = arrPositionY[i];\n // Store old energies\n prevEx = arrE[i][0];\n prevEy = arrE[i][1];\n denom = 1.0 / Math.sqrt((ux - vx) * (ux - vx) + (uy - vy) * (uy - vy));\n dx = arrK[i] * ((ux - vx) - arrL[i] * (ux - vx) * denom) || 0.0;\n dy = arrK[i] * ((uy - vy) - arrL[i] * (uy - vy) * denom) || 0.0;\n\n arrE[i] = [dx, dy];\n dEX += dx;\n dEY += dy;\n arrEnergySumX[i] += dx - prevEx;\n arrEnergySumY[i] += dy - prevEy;\n }\n arrEnergySumX[index] = dEX;\n arrEnergySumY[index] = dEY;\n }\n\n // Setting parameters\n let threshold = 0.1;\n let innerThreshold = 0.1;\n let maxIteration = 6000;\n let maxInnerIteration = 10;\n let maxEnergy = 1e9;\n\n // Setting up variables for the while loops\n let maxEnergyId = 0;\n let dEX = 0.0;\n let dEY = 0.0;\n let delta = 0.0;\n let iteration = 0;\n let innerIteration = 0;\n\n while (maxEnergy > threshold && maxIteration > iteration) {\n iteration++;\n [maxEnergyId, maxEnergy, dEX, dEY] = highestEnergy();\n\n delta = maxEnergy;\n innerIteration = 0;\n while (delta > innerThreshold && maxInnerIteration > innerIteration) {\n innerIteration++;\n update(maxEnergyId, dEX, dEY);\n [delta, dEX, dEY] = energy(maxEnergyId);\n }\n }\n\n let positions = Array(length);\n\n i = length;\n while (i--) {\n positions[i] = [arrPositionX[i], arrPositionY[i]];\n }\n\n return [positions, this.getEdgeList()];\n }\n\n getDiameter() {\n let diameter = 0;\n\n for (var i = 0; i < this.distanceMatrix.length - 1; i++) {\n for (var j = i; j < this.distanceMatrix.length; j++) {\n if (this.distanceMatrix[i][j] > diameter && this.distanceMatrix[i][j] < Infinity) {\n diameter = this.distanceMatrix[i][j];\n }\n }\n }\n\n return diameter;\n }\n\n /**\n * Get the distance matrix of the graph.\n * \n * @returns {Array[]} The distance matrix of the graph.\n */\n getDistanceMatrix() {\n let length = this.adjacencyMatrix.length;\n let dist = Array(length);\n\n for (var i = 0; i < length; i++) {\n dist[i] = new Float32Array(length);\n dist[i].fill(Infinity);\n }\n\n for (var i = 0; i < length; i++) {\n for (var j = 0; j < length; j++) {\n if (this.adjacencyMatrix[i][j] < Infinity) {\n dist[i][j] = this.adjacencyMatrix[i][j];\n }\n }\n }\n\n for (var k = 0; k < length; k++) {\n for (var i = 0; i < length; i++) {\n for (var j = 0; j < length; j++) {\n if (dist[i][j] > dist[i][k] + dist[k][j]) {\n dist[i][j] = dist[i][k] + dist[k][j]\n }\n }\n }\n }\n\n return dist;\n }\n\n /**\n * Returns a new graph object. Vertex ids have to be 0 to n.\n * \n * @param {Array[]} edgeList An edge list in the form [ [ vertexId, vertexId, weight ], ... ].\n * @param {Boolean} invertWeights Whether or not to invert the weights.\n * @returns {Graph} A graph object.\n */\n static fromEdgeList(edgeList, invertWeights = false) {\n // Get the max vertex id.\n let max = 0;\n for (var i = 0; i < edgeList.length; i++) {\n if (edgeList[i][0] > max) {\n max = edgeList[i][0];\n }\n\n if (edgeList[i][1] > max) {\n max = edgeList[i][1];\n }\n }\n\n max++;\n\n if (invertWeights) {\n let maxWeight = 0;\n\n for (var i = 0; i < edgeList.length; i++) {\n if (edgeList[i][2] > maxWeight) {\n maxWeight = edgeList[i][2];\n }\n }\n\n maxWeight++;\n\n for (var i = 0; i < edgeList.length; i++) {\n edgeList[i][2] = maxWeight - edgeList[i][2];\n }\n }\n\n let adjacencyMatrix = Array(max);\n\n for (var i = 0; i < max; i++) {\n adjacencyMatrix[i] = new Float32Array(max);\n adjacencyMatrix[i].fill(0);\n }\n\n for (var i = 0; i < edgeList.length; i++) {\n let edge = edgeList[i];\n adjacencyMatrix[edge[0]][edge[1]] = edge[2];\n adjacencyMatrix[edge[1]][edge[0]] = edge[2];\n }\n\n return new Graph(adjacencyMatrix);\n }\n}\n\nmodule.exports = Graph" }, { "alpha_fraction": 0.5991918444633484, "alphanum_fraction": 0.6111040711402893, "avg_line_length": 27.31704330444336, "blob_id": "aa4927ceca751eef2ae71275f42bf0cac84ebdf5", "content_id": "e78809e080472d393695ba38bb09d2c281708de9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 23757, "license_type": "permissive", "max_line_length": 148, "num_lines": 839, "path": "/src/Helpers/PointHelper.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst HelperBase = require('./HelperBase');\nconst DrawModes = require('../Core/DrawModes')\nconst Color = require('../Core/Color');\nconst Utils = require('../Utils/Utils');\nconst Vector3f = require('../Math/Vector3f');\nconst AABB = require('../Spice/AABB');\nconst Octree = require('../Spice/Octree');\nconst FilterBase = require('../Filters/FilterBase');\n\n/** \n * A helper class wrapping a point cloud.\n * \n * @property {Object} opts An object containing options.\n * @property {Number[]} indices Indices associated with the data.\n * @property {Octree} octree The octree associated with the point cloud.\n * @property {OctreeHelper} octreeHelper The octreeHelper associated with the pointHelper.\n * @property {Object} filters A map mapping filter names to Lore.Filter instances associated with this helper class.\n * @property {Number} pointSize The scaled and constrained point size of this data.\n * @property {Number} pointScale The scale of the point size.\n * @property {Number} rawPointSize The point size before scaling and constraints.\n * @property {Object} dimensions An object with the properties min and max, each a 3D vector containing the extremes.\n */\nclass PointHelper extends HelperBase {\n /**\n * Creates an instance of PointHelper.\n * @param {Renderer} renderer An instance of Lore.Renderer.\n * @param {String} geometryName The name of this geometry.\n * @param {String} shaderName The name of the shader used to render the geometry.\n * @param {Object} options An object containing options.\n */\n constructor(renderer, geometryName, shaderName, options) {\n super(renderer, geometryName, shaderName);\n\n let defaults = {\n octree: true,\n octreeThreshold: 500.0,\n octreeMaxDepth: 8,\n pointScale: 1.0,\n maxPointSize: 100.0\n };\n\n this.opts = Utils.extend(true, defaults, options);\n this.indices = null;\n this.octree = null;\n this.octreeHelper = null;\n this.geometry.setMode(DrawModes.points);\n this.initPointSize();\n this.filters = {};\n this.pointScale = this.opts.pointScale;\n this.rawPointSize = 1.0;\n this.pointSize = this.rawPointSize * this.pointScale;\n\n this.dimensions = {\n min: new Vector3f(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY),\n max: new Vector3f(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY)\n };\n\n let that = this;\n this._zoomchangedHandler = function (zoom) {\n let threshold = that.setPointSize(zoom + 0.1);\n if (that.octreeHelper) {\n that.octreeHelper.setThreshold(threshold);\n }\n };\n\n renderer.controls.addEventListener('zoomchanged', this._zoomchangedHandler);\n }\n\n /**\n * Get the max length of the length of three arrays.\n * \n * @param {Number[]|Array|Float32Array} x \n * @param {Number[]|Array|Float32Array} y \n * @param {Number[]|Array|Float32Array} z \n * @returns {Number} The length of the largest array.\n */\n getMaxLength(x, y, z) {\n return Math.max(x.length, Math.max(y.length, z.length));\n }\n\n /**\n * Returns an object containing the dimensions of this point cloud.\n * \n * @returns {Object} An object with the properties min and max, each a 3D vector containing the extremes.\n */\n getDimensions() {\n return this.dimensions;\n }\n\n /**\n * Get the center (average) of the point cloud.\n * \n * @returns {Vector3f} The center (average) of the point cloud.\n */\n getCenter() {\n return new Vector3f((this.dimensions.max.getX() + this.dimensions.min.getX()) / 2.0,\n (this.dimensions.max.getY() + this.dimensions.min.getY()) / 2.0,\n (this.dimensions.max.getZ() + this.dimensions.min.getZ()) / 2.0);\n }\n\n /**\n * Gets the distance between the center and the point furthest from the center.\n * \n * @return {Number} The maximal radius.\n */\n getMaxRadius() {\n let center = this.getCenter();\n return center.subtract(this.dimensions.max).length();\n }\n\n /**\n * Set the positions of points in this point cloud.\n * \n * @param {Number[]|Array|Float32Array} positions The positions (linear array).\n * @returns {PointHelper} Itself.\n */\n setPositions(positions) {\n // Min, max will NOT be calculated as of now!\n // TODO?\n\n this.setAttribute('position', positions);\n\n return this;\n }\n\n /**\n * Set the positions of points in this point clouds.\n * \n * @param {Number[]|Array|Float32Array} x An array containing the x components.\n * @param {Number[]|Array|Float32Array} y An array containing the y components.\n * @param {Number[]|Array|Float32Array} z An array containing the z components.\n * @returns {PointHelper} Itself.\n */\n setPositionsXYZ(x, y, z) {\n const length = x.length;\n let positions = new Float32Array(length * 3);\n\n for (var i = 0; i < length; i++) {\n let j = 3 * i;\n\n positions[j] = x[i] || 0;\n positions[j + 1] = y[i] || 0;\n positions[j + 2] = z[i] || 0;\n\n if (x[i] > this.dimensions.max.getX()) {\n this.dimensions.max.setX(x[i]);\n }\n\n if (x[i] < this.dimensions.min.getX()) {\n this.dimensions.min.setX(x[i]);\n }\n\n if (y[i] > this.dimensions.max.getY()) {\n this.dimensions.max.setY(y[i]);\n }\n\n if (y[i] < this.dimensions.min.getY()) {\n this.dimensions.min.setY(y[i]);\n }\n\n if (z[i] > this.dimensions.max.getZ()) {\n this.dimensions.max.setZ(z[i]);\n }\n\n if (z[i] < this.dimensions.min.getZ()) {\n this.dimensions.min.setZ(z[i]);\n }\n }\n\n if (this.opts.octree) {\n let initialBounds = AABB.fromPoints(positions);\n let indices = new Uint32Array(length);\n\n for (var i = 0; i < length; i++) {\n indices[i] = i;\n }\n\n this.octree = new Octree(this.opts.octreeThreshold, this.opts.octreeMaxDepth);\n this.octree.build(indices, positions, initialBounds);\n }\n\n this.setAttribute('position', positions);\n\n return this;\n }\n\n /**\n * Set the positions (XYZ), the color (RGB) and size (S) of the points.\n * \n * @param {Number[]|Array|Float32Array} x An array containing the x components.\n * @param {Number[]|Array|Float32Array} y An array containing the y components.\n * @param {Number[]|Array|Float32Array} z An array containing the z components.\n * @param {Number[]|Array|Float32Array} r An array containing the r components.\n * @param {Number[]|Array|Float32Array} g An array containing the g components.\n * @param {Number[]|Array|Float32Array} b An array containing the b components.\n * @param {Number} [s=1.0] The size of the points.\n * @returns {PointHelper} Itself.\n */\n setXYZRGBS(x, y, z, r, g, b, s = 1.0) {\n const length = r.length;\n let c = new Float32Array(length);\n\n for (var i = 0; i < length; i++) {\n c[i] = Color.rgbToFloat(r[i], g[i], b[i]);\n }\n\n this._setValues(x, y, z, c, s);\n return this;\n }\n\n /**\n * Set the positions (XYZ), the color (RGB) and size (S) of the points.\n * \n * @param {Number[]|Array|Float32Array} x An array containing the x components.\n * @param {Number[]|Array|Float32Array} y An array containing the y components.\n * @param {Number[]|Array|Float32Array} z An array containing the z components.\n * @param {String} hex A hex value.\n * @param {Number} [s=1.0] The size of the points.\n * @returns {PointHelper} Itself.\n */\n setXYZHexS(x, y, z, hex, s = 1.0) {\n const length = x.length;\n let c = new Float32Array(length);\n let floatColor = Color.hexToFloat(hex);\n for (var i = 0; i < length; i++) {\n c[i] = floatColor;\n }\n\n this._setValues(x, y, z, c, s);\n return this;\n }\n\n /**\n * Set the positions (XYZ), the hue (H) and size (S) of the points.\n * \n * @param {Number[]|Array|Float32Array} x An array containing the x components.\n * @param {Number[]|Array|Float32Array} y An array containing the y components.\n * @param {Number[]|Array|Float32Array} z An array containing the z components.\n * @param {Number[]|Array|Float32Array|Number} [h=1.0] The hue as a number or an array.\n * @param {Number[]|Array|Float32Array|Number} [s=1.0] The size of the points.\n * @returns {PointHelper} Itself.\n */\n setXYZHS(x, y, z, h = 1.0, s = 1.0) {\n const length = x.length;\n let c = new Float32Array(length);\n \n if (typeof h !== 'number') {\n for (var i = 0; i < length; i++) {\n c[i] = Color.hslToFloat(h[i]);\n }\n } else if (typeof h) {\n h = Color.hslToFloat(h);\n for (var i = 0; i < length; i++) {\n c[i] = h;\n }\n }\n\n this._setValues(x, y, z, c, s);\n return this;\n }\n\n // TODO: Get rid of saturation\n _setValues(x, y, z, c, s) {\n let length = this.getMaxLength(x, y, z);\n let saturation = new Float32Array(length);\n\n for (var i = 0; i < length; i++) {\n saturation[i] = 0.0;\n }\n\n if (typeof s === 'number') {\n let tmpSize = new Float32Array(length);\n for (var i = 0; i < length; i++) {\n tmpSize[i] = s;\n }\n s = tmpSize;\n }\n\n this.setPositionsXYZ(x, y, z);\n this.setHSSFromArrays(c, saturation, s);\n\n // TODO: Check why the projection matrix update is needed\n this.renderer.camera.updateProjectionMatrix();\n this.renderer.camera.updateViewMatrix();\n\n return this;\n }\n\n /**\n * Set the positions and the HSS (Hue, Saturation, Size) values of the points in the point cloud.\n * \n * @param {Number[]|Array|Float32Array} x An array containing the x components.\n * @param {Number[]|Array|Float32Array} y An array containing the y components.\n * @param {Number[]|Array|Float32Array} z An array containing the z components.\n * @param {Number[]|Array|Float32Array|Number} hue An array containing the hues of the data points.\n * @param {Number[]|Array|Float32Array|Number} saturation An array containing the saturations of the data points.\n * @param {Number[]|Array|Float32Array|Number} size An array containing the sizes of the data points.\n * @returns {PointHelper} Itself.\n */\n setPositionsXYZHSS(x, y, z, hue, saturation, size) {\n console.warn('The method \"setPositionsXYZHSS\" is marked as deprecated.');\n let length = this.getMaxLength(x, y, z);\n saturation = new Float32Array(length);\n\n for (var i = 0; i < length; i++) {\n saturation[i] = 0.0;\n }\n\n if (typeof size === 'number') {\n let tmpSize = new Float32Array(length);\n for (var i = 0; i < length; i++) {\n tmpSize[i] = size;\n }\n size = tmpSize;\n }\n\n this.setPositionsXYZ(x, y, z);\n\n if (typeof hue === 'number' && typeof saturation === 'number' && typeof size === 'number') {\n let rgb = Color.hslToRgb(hue, 1.0, 0.5);\n this.setHSS(Color.rgbToFloat(rgb[0], rgb[1], rgb[2]), saturation, size, length);\n } else if (typeof hue !== 'number' && typeof saturation !== 'number' && typeof size !== 'number') {\n for (var i = 0; i < hue.length; i++) {\n let rgb = Color.hslToRgb(hue[i], 1.0, 0.5);\n hue[i] = Color.rgbToFloat(rgb[0], rgb[1], rgb[2]);\n }\n this.setHSSFromArrays(hue, saturation, size);\n } else {\n if (typeof hue === 'number') {\n let hueTmp = new Float32Array(length);\n let rgb = Color.hslToRgb(hue, 1.0, 0.5);\n hueTmp.fill(Color.rgbToFloat(rgb[0], rgb[1], rgb[2]));\n hue = hueTmp;\n } else if (typeof hue !== 'number') {\n for (var i = 0; i < hue.length; i++) {\n let rgb = Color.hslToRgb(hue[i], 1.0, 0.5);\n hue[i] = Color.rgbToFloat(rgb[0], rgb[1], rgb[2]);\n }\n this.setHSSFromArrays(hue, saturation, size);\n }\n\n if (typeof saturation === 'number') {\n let saturationTmp = new Float32Array(length);\n saturationTmp.fill(saturation);\n saturation = saturationTmp;\n }\n\n if (typeof size === 'number') {\n let sizeTmp = new Float32Array(length);\n sizeTmp.fill(size);\n size = sizeTmp;\n }\n\n this.setHSSFromArrays(hue, saturation, size);\n }\n\n // TODO: Check why the projection matrix update is needed\n this.renderer.camera.updateProjectionMatrix();\n this.renderer.camera.updateViewMatrix();\n\n return this;\n }\n \n\n /**\n * Set the colors (HSS) for the points.\n * \n * @param {Number[]|Array|Float32Array} colors An array containing the HSS values.\n * @returns {PointHelper} Itself.\n */\n setColors(colors) {\n this.setAttribute('color', colors);\n\n return this;\n }\n\n /**\n * Update the colors (HSS) for the points.\n * \n * @param {Number[]|Array|Float32Array} colors An array containing the HSS values.\n * @returns {PointHelper} Itself.\n */\n updateColors(colors) {\n this.updateAttributeAll('color', colors);\n\n return this;\n }\n\n /**\n * Update the color (HSS) at a specific index.\n * \n * @param {Number} index The index of the data point.\n * @param {Color} color An instance of Lore.Color containing HSS values.\n * @returns {PointHelper} Itself.\n */\n updateColor(index, color) {\n console.warn('The method \"updateColor\" is marked as deprecated.');\n this.updateAttribute('color', index, color.components);\n\n return this;\n }\n \n\n /**\n * Update the color (HSS) at a specific index.\n * \n * @param {Number} index The index of the data point.\n * @param {Color} color An instance of Lore.Color containing HSS values.\n * @returns {PointHelper} Itself.\n */\n setColor(index, color) {\n let c = new Color(color.toFloat(), this.getSaturation(index), this.getSize(index));\n this.updateAttribute('color', index, c.components);\n\n return this;\n }\n\n /**\n * Set the global point size.\n * \n * @param {Number} size The global point size.\n * @returns {Number} The threshold for the raycaster.\n */\n setPointSize(size) {\n this.rawPointSize = size;\n\n this.updatePointSize();\n\n let pointSize = this.rawPointSize * this.opts.pointScale;\n\n if (pointSize > this.opts.maxPointSize) {\n return 0.5 * (this.opts.maxPointSize / pointSize);\n } else {\n return 0.5;\n }\n }\n\n /**\n * Updates the displayed point size.\n */\n updatePointSize() {\n let pointSize = this.rawPointSize * this.opts.pointScale;\n\n if (pointSize > this.opts.maxPointSize) {\n this.pointSize = this.opts.maxPointSize;\n } else {\n this.pointSize = pointSize;\n }\n\n this.geometry.shader.uniforms.size.value = this.pointSize;\n }\n\n /**\n * Get the global point size.\n * \n * @returns {Number} The global point size.\n */\n getPointSize() {\n return this.geometry.shader.uniforms.size.value;\n }\n\n /**\n * Get the global point scale.\n * \n * @returns {Number} The global point size.\n */\n getPointScale() {\n return this.opts.pointScale;\n }\n\n /**\n * Sets the global point scale.\n * \n * @param {Number} pointScale The global point size.\n * @returns {PointHelper} Itself.\n */\n setPointScale(pointScale) {\n this.opts.pointScale = pointScale;\n this.updatePointSize();\n\n return this;\n }\n\n /**\n * Sets the fog colour and it's density, as seen from the camera.\n * \n * @param {any} color An array or hex string defining the rgba values of the fog colour.\n * @param {Number} fogDensity The density of the fog.\n * @returns {PointHelper} Itself.\n */\n setFog(color, fogDensity = 6.0) {\n if (!this.geometry.shader.uniforms.clearColor || !this.geometry.shader.uniforms.fogDensity) {\n console.warn('Shader \"' + this.geometry.shader.name + '\" does not support fog.');\n return this;\n }\n\n // If the color is passed as a string, convert the hex value to an array\n if (typeof color === 'string') {\n let c = Color.fromHex(color);\n color = [c.getR(), c.getG(), c.getB(), 1.0];\n }\n\n this.geometry.shader.uniforms.clearColor.value = color;\n this.geometry.shader.uniforms.fogDensity.value = fogDensity;\n\n return this;\n }\n\n /**\n * Initialize the point size based on the current zoom.\n * \n * @returns {PointHelper} Itself.\n */\n initPointSize() {\n this.setPointSize(this.renderer.camera.zoom + 0.1);\n\n return this;\n }\n\n /**\n * Get the current cutoff value.\n * \n * @returns {Number} The current cutoff value.\n */\n getCutoff() {\n return this.geometry.shader.uniforms.cutoff.value;\n }\n\n /**\n * Set the cutoff value.\n * \n * @param {Number} cutoff A cutoff value.\n * @returns {PointHelper} Itself.\n */\n setCutoff(cutoff) {\n this.geometry.shader.uniforms.cutoff.value = cutoff;\n\n return this;\n }\n\n /**\n * Get the hue for a given index.\n * \n * @param {Number} index An index.\n * @returns {Number} The hue of the specified index.\n */\n getHue(index) {\n console.warn('The method \"getHue\" is marked as deprecated. Please use \"getColor\".');\n let colors = this.getAttribute('color');\n\n return Color.floatToHsl(colors[index * 3]);\n }\n\n /**\n * Get the color for a given index.\n * \n * @param {Number} index An index.\n * @returns {Number[]|Array} The color of the specified index in RGB.\n */\n getColor(index) {\n let colors = this.getAttribute('color');\n\n return Color.floatToRgb(colors[index * 3]);\n }\n\n /**\n * Get the saturation for a given index.\n * \n * @param {Number} index An index.\n * @returns {Number} The saturation of the specified index.\n */\n getSaturation(index) {\n let colors = this.getAttribute('color');\n\n return colors[index * 3 + 1];\n }\n\n /**\n * Get the size for a given index.\n * \n * @param {Number} index An index.\n * @returns {Number} The size of the specified index.\n */\n getSize(index) {\n let colors = this.getAttribute('color');\n\n return colors[index * 3 + 2];\n }\n\n /**\n * Get the position for a given index.\n * \n * @param {Number} index An index.\n * @returns {Vector3f} The position of the specified index.\n */\n getPosition(index) {\n let positions = this.getAttribute('position');\n\n return new Vector3f(positions[index * 3], positions[index * 3 + 1],\n positions[index * 3 + 2]);\n }\n\n /**\n * Set the hue. If a number is supplied, all the hues are set to the supplied number.\n * \n * @param {Number[]|Array|Float32Array|Number} hue The hue to be set. If a number is supplied, all hues are set to its value.\n */\n setHue(hue) {\n let colors = this.getAttribute('color');\n let index = 0;\n\n if (typeof hue === 'number') {\n hue = Color.hslToFloat(hue);\n\n for (let i = 0; i < colors.length; i++) {\n colors[i * 3] = hue;\n }\n } else {\n for (let i = 0; i < hue.length; i++) {\n colors[i * 3] = Color.hslToFloat(hue[i]);\n }\n }\n\n this.setColors(colors);\n }\n\n /**\n * Set the saturation. If a number is supplied, all the saturations are set to the supplied number.\n * \n * @param {Number[]|Array|Float32Array|Number} saturation The saturation to be set. If a number is supplied, all saturations are set to its value.\n */\n setSaturation(saturation) {\n let colors = this.getAttribute('color');\n let c = null;\n let index = 0;\n\n if (typeof saturation === 'number') {\n let length = colors.length;\n\n c = new Float32Array(length * 3);\n\n for (let i = 0; i < length * 3; i += 3) {\n c[i] = colors[i];\n c[i + 1] = saturation;\n c[i + 2] = colors[i + 2];\n }\n } else {\n let length = saturation.length;\n\n c = new Float32Array(length * 3);\n\n for (let i = 0; i < length * 3; i += 3) {\n c[i] = colors[i];\n c[i + 1] = saturation[index++];\n c[i + 2] = colors[i + 2];\n }\n }\n\n this.setColors(c);\n }\n\n /**\n * Set the size. If a number is supplied, all the sizes are set to the supplied number.\n * \n * @param {Number[]|Array|Float32Array|Number} size The size to be set. If a number is supplied, all sizes are set to its value.\n */\n setSize(size) {\n let colors = this.getAttribute('color');\n let c = null;\n let index = 0;\n\n if (typeof size === 'number') {\n let length = colors.length;\n\n c = new Float32Array(length * 3);\n\n for (let i = 0; i < length * 3; i += 3) {\n c[i] = colors[i];\n c[i + 1] = colors[i + 1];\n c[i + 2] = size;\n }\n } else {\n let length = size.length;\n\n c = new Float32Array(length * 3);\n\n for (let i = 0; i < length * 3; i += 3) {\n c[i] = colors[i];\n c[i + 1] = colors[i + 1];\n c[i + 2] = size[index++];\n }\n }\n\n this.setColors(c);\n }\n\n /**\n * Set the HSS values. Sets all indices to the same values.\n * \n * @param {Number} hue A hue value.\n * @param {Number} saturation A saturation value.\n * @param {Number} size A size value.\n * @param {Number} length The length of the arrays.\n */\n setHSS(hue, saturation, size, length) {\n let c = new Float32Array(length * 3);\n\n for (let i = 0; i < length * 3; i += 3) {\n c[i] = hue;\n c[i + 1] = saturation;\n c[i + 2] = size;\n }\n\n this.setColors(c);\n }\n \n /**\n * Set the color from RGB values. Sets all indices to the same values.\n * \n * @param {Number} r The red colour component.\n * @param {Number} g The green colour component.\n * @param {Number} b The blue colour component.\n */\n setRGB(r, g, b) {\n let c = this.getAttribute('color');\n\n for (let i = 0; i < c.length; i++) {\n c[i * 3] = Color.rgbToFloat(r, g, b);\n }\n\n this.setColors(c);\n }\n\n /**\n * Set the color from RGB values. Sets all indices to the same values.\n * \n * @param {Number[]|Array|Float32Array} r The red colour component.\n * @param {Number[]|Array|Float32Array} g The green colour component.\n * @param {Number[]|Array|Float32Array} b The blue colour component.\n */\n setRGBFromArrays(r, g, b) {\n const length = Math.min(Math.min(r.length, g.length), b.length);\n let c = this.getAttribute('color');\n\n for (let i = 0; i < length; i++) {\n c[i * 3] = Color.rgbToFloat(r[i], g[i], b[i]);\n }\n\n this.setColors(c);\n }\n\n /**\n * Set the HSS values.\n * \n * @param {Number[]|Array|Float32Array} hue An array of hue values.\n * @param {Number[]|Array|Float32Array} saturation An array of saturation values.\n * @param {Number[]|Array|Float32Array} size An array of size values.\n */\n setHSSFromArrays(hue, saturation, size) {\n let length = hue.length;\n let c = new Float32Array(length * 3);\n let index = 0;\n\n if (hue.length !== length && saturation.length !== length && size.length !== length) {\n throw 'Hue, saturation and size have to be arrays of length \"length\" (' + length + ').';\n }\n\n for (let i = 0; i < length * 3; i += 3) {\n c[i] = hue[index];\n c[i + 1] = saturation[index];\n c[i + 2] = size[index];\n\n index++;\n }\n\n this.setColors(c);\n }\n\n /**\n * Add a filter to this point helper.\n * \n * @param {String} name The name of the filter.\n * @param {FilterBase} filter A filter instance.\n * @returns {PointHelper} Itself.\n */\n addFilter(name, filter) {\n filter.setGeometry(this.geometry);\n this.filters[name] = filter;\n\n return this;\n }\n\n /**\n * Remove a filter by name.\n * \n * @param {String} name The name of the filter to be removed.\n * @returns {PointHelper} Itself.\n */\n removeFilter(name) {\n delete this.filters[name];\n\n return this;\n }\n\n /**\n * Get a filter by name.\n * \n * @param {String} name The name of a filter.\n * @returns {FilterBase} A filter instance.\n */\n getFilter(name) {\n return this.filters[name];\n }\n\n /**\n * Hide the geometry associated with this pointHelper.\n */\n show() {\n this.geometry.show();\n }\n\n /**\n * Show the geometry associated with this pointHelper.\n */\n hide() {\n this.geometry.hide();\n }\n\n /**\n * Remove eventhandlers from associated controls.\n */\n destruct() {\n this.renderer.controls.removeEventListener('zoomchanged', this._zoomchangedHandler);\n }\n}\n\nmodule.exports = PointHelper" }, { "alpha_fraction": 0.46724364161491394, "alphanum_fraction": 0.5074496269226074, "avg_line_length": 23.864023208618164, "blob_id": "0c5b97ad3001284011d9706bd0ee15425b2c7168", "content_id": "e9751697d61ec69264217c3393f17f6ba9f3f030", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 9128, "license_type": "permissive", "max_line_length": 97, "num_lines": 353, "path": "/src/Core/Color.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\r\n\r\n/** \r\n * A class representing a Color. \r\n * \r\n * @property {Float32Array} components A typed array storing the components of this color (rgba).\r\n */\r\nclass Color {\r\n /**\r\n * Creates an instance of Color.\r\n * @param {Number} r The red component (0.0 - 1.0).\r\n * @param {Number} g The green component (0.0 - 1.0).\r\n * @param {Number} b The blue component (0.0 - 1.0).\r\n * @param {Number} [a=1.0] The alpha component (0.0 - 1.0).\r\n */\r\n constructor(r, g, b, a = 1.0) {\r\n if (arguments.length === 1) {\r\n this.components = new Float32Array(r);\r\n } else {\r\n this.components = new Float32Array(4);\r\n this.components[0] = r || 0.0;\r\n this.components[1] = g || 0.0;\r\n this.components[2] = b || 0.0;\r\n this.components[3] = a || 1.0;\r\n }\r\n }\r\n\r\n /**\r\n * Set the red, green, blue and alpha components of the color.\r\n * \r\n * @param {Number} r The red component (0.0 - 1.0).\r\n * @param {Number} g The green component (0.0 - 1.0).\r\n * @param {Number} b The blue component (0.0 - 1.0).\r\n * @param {Number} a The alpha component (0.0 - 1.0).\r\n * @returns {Color} Returns itself.\r\n */\r\n set(r, g, b, a) {\r\n this.components[0] = r;\r\n this.components[1] = g;\r\n this.components[2] = b;\r\n\r\n if (arguments.length == 4) {\r\n this.components[3] = a;\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Get the red component of the color.\r\n * \r\n * @returns {Number} The red component of the color.\r\n */\r\n getR() {\r\n return this.components[0];\r\n }\r\n\r\n /**\r\n * Get the green component of the color.\r\n * \r\n * @returns {Number} The green component of the color.\r\n */\r\n getG() {\r\n return this.components[1];\r\n }\r\n\r\n /**\r\n * Get the blue component of the color.\r\n * \r\n * @returns {Number} The blue component of the color.\r\n */\r\n getB() {\r\n return this.components[2];\r\n }\r\n\r\n /**\r\n * Get the alpha component of the color.\r\n * \r\n * @returns {Number} The alpha component of the color.\r\n */\r\n getA() {\r\n return this.components[3];\r\n }\r\n\r\n /**\r\n * Convert this colour to a float.\r\n * \r\n * @returns {Number} A float representing this colour.\r\n */\r\n toFloat() {\r\n return Color.rgbToFloat(this.getR() * 255.0, this.getG() * 255.0, this.getB() * 255.0);\r\n }\r\n\r\n /**\r\n * Set the r,g,b components from a hex string.\r\n * \r\n * @static\r\n * @param {string} hex A hex string in the form of #ABCDEF or #ABC.\r\n * @returns {Color} A color representing the hex string.\r\n */\r\n static fromHex(hex) {\r\n let rgb = Color.hexToRgb(hex);\r\n return new Color(rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0, 1.0);\r\n }\r\n\r\n /**\r\n * Create an rgb array from the r,g,b components from a hex string.\r\n * \r\n * @static\r\n * @param {string} hex A hex string in the form of #ABCDEF or #ABC.\r\n * @returns {Array} Returns an array containing rgb values.\r\n */\r\n static hexToRgb(hex) {\r\n // Thanks to Tim Down\r\n // http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb\r\n\r\n let shorthandRegex = /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i;\r\n\r\n hex = hex.replace(shorthandRegex, function (m, r, g, b) {\r\n return r + r + g + g + b + b;\r\n });\r\n\r\n let result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\r\n let r = parseInt(result[1], 16);\r\n let g = parseInt(result[2], 16);\r\n let b = parseInt(result[3], 16);\r\n\r\n return [r, g, b];\r\n }\r\n\r\n /**\r\n * Get the r, g or b value from a hue component.\r\n * \r\n * @static\r\n * @param {Number} p \r\n * @param {Number} q \r\n * @param {Number} t \r\n * @returns {Number} The r, g or b component value.\r\n */\r\n static hueToRgb(p, q, t) {\r\n if (t < 0) {\r\n t += 1;\r\n } else if (t > 1) {\r\n t -= 1;\r\n } else if (t < 0.1667) {\r\n return p + (q - p) * 6 * t;\r\n } else if (t < 0.5) {\r\n return q;\r\n } else if (t < 0.6667) {\r\n return p + (q - p) * (0.6667 - t) * 6;\r\n }\r\n\r\n return p;\r\n }\r\n\r\n /**\r\n * Converts HSL to RGB.\r\n * \r\n * @static\r\n * @param {Number} h The hue component.\r\n * @param {Number} s The saturation component.\r\n * @param {Number} l The lightness component.\r\n * @returns {Number[]} An array containing the r, g and b values ([r, g, b]).\r\n */\r\n static hslToRgb(h, s, l) {\r\n let r, g, b;\r\n\r\n if (s == 0) {\r\n r = g = b = l;\r\n } else {\r\n let q = l < 0.5 ? l * (1 + s) : l + s - l * s;\r\n let p = 2 * l - q;\r\n r = Color._hue2rgb(p, q, h + 1 / 3);\r\n g = Color._hue2rgb(p, q, h);\r\n b = Color._hue2rgb(p, q, h - 1 / 3);\r\n }\r\n\r\n return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];\r\n }\r\n\r\n /**\r\n * Helper for HSL to RGB converter.\r\n */\r\n static _hue2rgb(p, q, t) {\r\n if (t < 0) t += 1;\r\n if (t > 1) t -= 1;\r\n if (t < 0.16666666666) return p + (q - p) * 6 * t;\r\n if (t < 0.5) return q;\r\n if (t < 0.66666666666) return p + (q - p) * (0.66666666666 - t) * 6;\r\n return p;\r\n }\r\n\r\n /**\r\n * Converts HSL to Hex.\r\n * \r\n * @static\r\n * @param {Number} h The hue component.\r\n * @param {Number} s The saturation component.\r\n * @param {Number} l The lightness component.\r\n * @returns {String} A hex string representing the color (#RRGGBB).\r\n */\r\n static hslToHex(h, s, l) {\r\n let [r, g, b] = Color.hslToRgb(h, s, l);\r\n return '#' + [r, g, b].map(e => {\r\n const hex = e.toString(16);\r\n return hex.length === 1 ? '0' + hex : hex\r\n }).join('')\r\n }\r\n\r\n /**\r\n * Converts RGB to Hex.\r\n * \r\n * @static\r\n * @param {Number} r The red component.\r\n * @param {Number} g The green component.\r\n * @param {Number} b The blue component.\r\n * @returns {String} A hex string representing the color (#RRGGBB).\r\n */\r\n static rgbToHex(r, g, b) {\r\n return '#' + [r, g, b].map(e => {\r\n const hex = e.toString(16);\r\n return hex.length === 1 ? '0' + hex : hex\r\n }).join('')\r\n }\r\n\r\n /**\r\n * Converts RGB to HSL.\r\n * \r\n * @static\r\n * @param {Number} r The red component.\r\n * @param {Number} g The green component.\r\n * @param {Number} b The blue component.\r\n * @returns {Number[]} An array containing the h, s and l values ([h, s, l]).\r\n */\r\n static rgbToHsl(r, g, b) {\r\n r /= 255, g /= 255, b /= 255;\r\n\r\n let max = Math.max(r, g, b);\r\n let min = Math.min(r, g, b);\r\n let h, s, l = (max + min) / 2;\r\n\r\n if (max == min) {\r\n h = s = 0; // achromatic\r\n } else {\r\n var d = max - min;\r\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\r\n\r\n switch (max) {\r\n case r: h = (g - b) / d + (g < b ? 6 : 0); break;\r\n case g: h = (b - r) / d + 2; break;\r\n case b: h = (r - g) / d + 4; break;\r\n }\r\n\r\n h /= 6;\r\n }\r\n\r\n return [ h, s, l ];\r\n }\r\n\r\n /**\r\n * Transform hsl to rgb colour values and then encode them as a 24-bit (highp) float.\r\n * \r\n * @static\r\n * @param {Number} h \r\n * @param {Number} [s=1.0] \r\n * @param {Number} [l=0.5]\r\n * @returns {number} A RGB colour (NOT hsl) encoded as a float.\r\n */\r\n static hslToFloat(h, s = 1.0, l = 0.5) {\r\n let rgb = Color.hslToRgb(h, s, l);\r\n return Math.floor(rgb[0] + rgb[1] * 256.0 + rgb[2] * 256.0 * 256.0);\r\n }\r\n\r\n /**\r\n * Encode rgb colour values as a 24-bit (highp) float.\r\n * \r\n * @static\r\n * @param {Number} r \r\n * @param {Number} g \r\n * @param {Number} b\r\n * @returns {number} A RGB colour encoded as a float.\r\n */\r\n static rgbToFloat(r, g, b) {\r\n return Math.floor(r + g * 256.0 + b * 256.0 * 256.0);\r\n }\r\n\r\n /**\r\n * Encode a hex colour values as a 24-bit (highp) float.\r\n * \r\n * @static\r\n * @param {String} hex A hex value encoding a colour. \r\n * @returns {number} A RGB colour encoded as a float.\r\n */\r\n static hexToFloat(hex) {\r\n let rgb = Color.hexToRgb(hex);\r\n return Color.rgbToFloat(rgb[0], rgb[1], rgb[2]);\r\n }\r\n\r\n /**\r\n * Decode rgb colour values from a 24-bit (highp) float.\r\n * \r\n * @static\r\n * @param {Number} n \r\n * @returns {*} An array containing rgb values. \r\n */\r\n static floatToRgb(n) {\r\n let b = Math.floor(n / (256.0 * 256.0));\r\n let g = Math.floor((n - b * (256.0 * 256.0)) / 256.0);\r\n let r = Math.floor(n - b * (256.0 * 256.0) - g * 256.0);\r\n\r\n return [r, g, b]\r\n }\r\n\r\n /**\r\n * Decode hsl colour values from a 24-bit (highp) float.\r\n * \r\n * @static\r\n * @param {Number} n \r\n * @returns {*} An array containing hsl values. \r\n */\r\n static floatToHsl(n) {\r\n let b = Math.floor(n / (256.0 * 256.0));\r\n let g = Math.floor((n - b * (256.0 * 256.0)) / 256.0);\r\n let r = Math.floor(n - b * (256.0 * 256.0) - g * 256.0);\r\n\r\n return Color.rgbToHsl(r, g, b);\r\n }\r\n\r\n /**\r\n * Shifts the hue so that 0.0 represents blue and 1.0 represents magenta.\r\n * \r\n * @static\r\n * @param {Number} hue A hue component.\r\n * @returns {Number} The hue component shifted so that 0.0 is blue and 1.0 is magenta.\r\n */\r\n static gdbHueShift(hue) {\r\n hue = 0.85 * hue + 0.66;\r\n\r\n if (hue > 1.0) {\r\n hue = hue - 1.0;\r\n }\r\n\r\n hue = (1 - hue) + 0.33\r\n\r\n if (hue > 1.0) {\r\n hue = hue - 1.0\r\n }\r\n\r\n return hue;\r\n }\r\n}\r\n\r\nmodule.exports = Color" }, { "alpha_fraction": 0.5172203183174133, "alphanum_fraction": 0.5272060036659241, "avg_line_length": 28.20833396911621, "blob_id": "42680991962ae54b014a2e254b99d1fa157cdea2", "content_id": "d8fa5e8113abf85b22baf48dec3fbe7de098cf03", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4907, "license_type": "permissive", "max_line_length": 111, "num_lines": 168, "path": "/src/Math/Statistics.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\n/** A helper class containing statistics methods. */\nclass Statistics {\n /**\n * Transposes an array of arrays (2d array).\n \n * @param {Array} arr The 2d array to be transposed.\n * @returns {Array} The transpose of the 2d array.\n */\n static transpose2dArray(arr) {\n return arr[0].map((col, i) => arr.map(row => row[i]));\n }\n\n /**\n * Returns a normally distributed (pseudo) random number.\n * \n * @returns {Number} A normally distributed (pseudo) random number.\n */\n static randomNormal() {\n let val, u, v, s, mul;\n\n if (Statistics.spareRandomNormal !== null) {\n val = Statistics.spareRandomNormal;\n Statistics.spareRandomNormal = null;\n } else {\n do {\n u = Math.random() * 2 - 1;\n v = Math.random() * 2 - 1;\n\n s = u * u + v * v;\n } while (s === 0 || s >= 1);\n\n mul = Math.sqrt(-2 * Math.log(s) / s);\n val = u * mul;\n Statistics.spareRandomNormal = v * mul;\n }\n\n return val / 14;\n }\n\n /**\n * Returns a normally distributed (pseudo) random number within a range.\n * \n * @param {Number} a The start of the range.\n * @param {Number} b The end of the range.\n * @returns {Number} A normally distributed (pseudo) random number within a range.\n */\n static randomNormalInRange(a, b) {\n let val;\n\n do {\n val = Statistics.randomNormal();\n } while (val < a || val > b);\n\n return val;\n }\n\n /**\n * Returns a normally distributed (pseudo) random number around a mean with a standard deviation.\n * \n * @param {Number} mean The mean.\n * @param {Number} sd The standard deviation.\n * @returns {Number} A normally distributed (pseudo) random number around a mean with a standard deviation.\n */\n static randomNormalScaled(mean, sd) {\n let r = Statistics.randomNormalInRange(-1, 1);\n \n return r * sd + mean;\n }\n\n /**\n * Normalize / scale an array between 0 and 1.\n * \n * @param {Number[]} arr An array.\n * @returns {Number[]} The normalized / scaled array.\n */\n static normalize(arr) {\n let newArr = arr.slice();\n let max = Number.NEGATIVE_INFINITY;\n let min = Number.POSITIVE_INFINITY;\n\n for (let i = 0; i < newArr.length; i++) {\n let val = newArr[i];\n if (val > max) max = val;\n if (val < min) min = val;\n }\n\n let diff = max - min;\n\n for (let i = 0; i < newArr.length; i++) {\n newArr[i] = (newArr[i] - min) / diff;\n }\n \n return newArr;\n }\n\n /**\n * Normalize / scale an array between 0 and 1 (outliers will be set to max or min respectively).\n * The IQR method is used for outlier detection.\n * \n * @param {Number[]} arr An array.\n * @param {Number} q1 The q1 percentage.\n * @param {Number} q3 The q3 percentage.\n * @param {Number} k The IQR scaling factor.\n * @returns {Number[]} The normalized / scaled array.\n */\n static normalizeNoOutliers(arr, q1 = 0.25, q3 = 0.75, k = 1.5) {\n let newArr = arr.slice();\n\n newArr.sort((a, b) => a - b);\n\n let a = Statistics.getPercentile(newArr, q1);\n let b = Statistics.getPercentile(newArr, q3);\n let iqr = b - a;\n let lower = a - (iqr * k);\n let upper = b + (iqr * k);\n \n let diff = upper - lower;\n\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] < lower) {\n newArr[i] = 0.0;\n } else if (arr[i] > upper) {\n newArr[i] = 1.0;\n } else {\n newArr[i] = (arr[i] - lower) / diff;\n }\n }\n \n return newArr;\n }\n\n /**\n * Gets the percentile from a sorted array.\n * \n * @param {Number[]} arr A sorted array.\n * @param {Number} percentile The percentile (e.g. 0.25).\n * @returns {Number} The percentile value.\n */\n static getPercentile(arr, percentile) {\n let index = percentile * arr.length;\n\n if (Math.floor(index) === index) {\n return (arr[index - 1] + arr[index]) / 2.0;\n } else {\n return arr[Math.floor(index)];\n }\n }\n\n /**\n * Scales a number to within a given scale.\n * \n * @param {Number} value The number.\n * @param {Number} oldMin The current minimum.\n * @param {Number} oldMax The current maximum.\n * @param {Number} newMin The cnew minimum.\n * @param {Number} newMax The new maximum.\n * @returns {Number} The scaled number.\n */\n static scale(value, oldMin, oldMax, newMin, newMax) {\n return (newMax - newMin) * (value - oldMin) / (oldMax - oldMin) + newMin;\n }\n}\n\nStatistics.spareRandomNormal = null;\n\nmodule.exports = Statistics\n" }, { "alpha_fraction": 0.4901791214942932, "alphanum_fraction": 0.5100679397583008, "avg_line_length": 25.487266540527344, "blob_id": "32cfacc61d34fafdbf64e449dee4fd0ab8bb959b", "content_id": "45ee75ab1f0de509d94fcd49f548ad2628d10121", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 16190, "license_type": "permissive", "max_line_length": 93, "num_lines": 589, "path": "/src/Math/Vector3f.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\r\n\r\nconst SphericalCoordinates = require('./SphericalCoords');\r\n\r\n/** \r\n * A class representing 3D float vector.\r\n * \r\n * @property {Float32Array} components A typed array storing the components of this vector.\r\n */\r\nclass Vector3f {\r\n /**\r\n * Creates an instance of Vector3f.\r\n * @param {Number} x The x component of the vector.\r\n * @param {Number} y The y component of the vector.\r\n * @param {Number} z The z component of the vector.\r\n */\r\n constructor(x, y, z) {\r\n if (arguments.length === 1) {\r\n this.components = new Float32Array(x);\r\n } else {\r\n this.components = new Float32Array(3);\r\n this.components[0] = x || 0.0;\r\n this.components[1] = y || 0.0;\r\n this.components[2] = z || 0.0;\r\n }\r\n }\r\n\r\n /**\r\n * Sets the x, y and z components of this vector.\r\n * \r\n * @param {Number} x The x component of the vector.\r\n * @param {Number} y The y component of the vector.\r\n * @param {Number} z The z component of the vector.\r\n * @returns {Vector3f} Returns itself.\r\n */\r\n set(x, y, z) {\r\n this.components[0] = x;\r\n this.components[1] = y;\r\n this.components[2] = z;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Gets the x component of this vector.\r\n * \r\n * @returns {Number} The x component of this vector.\r\n */\r\n getX() {\r\n return this.components[0];\r\n }\r\n\r\n /**\r\n * Gets the y component of this vector.\r\n * \r\n * @returns {Number} The y component of this vector.\r\n */\r\n getY() {\r\n return this.components[1];\r\n }\r\n\r\n /**\r\n * Gets the z component of this vector.\r\n * \r\n * @returns {Number} The z component of this vector.\r\n */\r\n getZ() {\r\n return this.components[2];\r\n }\r\n\r\n /**\r\n * Sets the x component of this vector.\r\n * \r\n * @param {Number} x The value to which the x component of this vectors will be set.\r\n * @returns {Vector3f} Returns itself.\r\n */\r\n setX(x) {\r\n this.components[0] = x;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Sets the y component of this vector.\r\n * \r\n * @param {Number} y The value to which the y component of this vectors will be set.\r\n * @returns {Vector3f} Returns itself.\r\n */\r\n setY(y) {\r\n this.components[1] = y;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Sets the z component of this vector.\r\n * \r\n * @param {Number} z The value to which the z component of this vectors will be set.\r\n * @returns {Vector3f} Returns itself.\r\n */\r\n setZ(z) {\r\n this.components[2] = z;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Sets this vector from spherical coordinates.\r\n * \r\n * @param {SphericalCoordinates} s A spherical coordinates object.\r\n * @returns {Vector3f} Returns itself.\r\n */\r\n setFromSphericalCoords(s) {\r\n var radius = s.components[0];\r\n var phi = s.components[1];\r\n var theta = s.components[2];\r\n\r\n var t = Math.sin(phi) * radius;\r\n\r\n this.components[0] = Math.sin(theta) * t;\r\n this.components[1] = Math.cos(phi) * radius;\r\n this.components[2] = Math.cos(theta) * t;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Copies the values from another vector\r\n * \r\n * @param {Vector3f} v A vector.\r\n * @returns {Vector3f} Returns itself.\r\n */\r\n copyFrom(v) {\r\n this.components[0] = v.components[0];\r\n this.components[1] = v.components[1];\r\n this.components[2] = v.components[2];\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set the length / magnitude of the vector.\r\n * \r\n * @param {Number} length The length / magnitude to set the vector to.\r\n * @returns {Vector3f} Returns itself.\r\n */\r\n setLength(length) {\r\n return this.multiplyScalar(length / this.length());\r\n }\r\n\r\n /**\r\n * Get the square of the length / magnitude of the vector.\r\n * \r\n * @returns {Number} The square of length / magnitude of the vector.\r\n */\r\n lengthSq() {\r\n return this.components[0] * this.components[0] +\r\n this.components[1] * this.components[1] +\r\n this.components[2] * this.components[2];\r\n }\r\n\r\n /**\r\n * The length / magnitude of the vector.\r\n * \r\n * @returns {Number} The length / magnitude of the vector.\r\n */\r\n length() {\r\n return Math.sqrt(this.lengthSq());\r\n }\r\n\r\n /**\r\n * Normalizes the vector.\r\n * \r\n * @returns {Vector3f} Returns itself.\r\n */\r\n normalize() {\r\n return this.divideScalar(this.length());\r\n }\r\n\r\n /**\r\n * Multiply the vector with another vector.\r\n * \r\n * @param {Vector3f} v A vector.\r\n * @returns {Vector3f} Returns itself.\r\n */\r\n multiply(v) {\r\n this.components[0] *= v.components[0];\r\n this.components[1] *= v.components[1];\r\n this.components[2] *= v.components[2];\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Multiplies this vector with a scalar.\r\n * \r\n * @param {Number} s A scalar.\r\n * @returns {Vector3f} Returns itself.\r\n */\r\n multiplyScalar(s) {\r\n this.components[0] *= s;\r\n this.components[1] *= s;\r\n this.components[2] *= s;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Divides the vector by another vector.\r\n * \r\n * @param {Vector3f} v A vector.\r\n * @returns {Vector3f} Returns itself.\r\n */\r\n divide(v) {\r\n this.components[0] /= v.components[0];\r\n this.components[1] /= v.components[1];\r\n this.components[2] /= v.components[2];\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Divides the vector by a scalar.\r\n * \r\n * @param {Number} s A scalar.\r\n * @returns {Vector3f} Returns itself.\r\n */\r\n divideScalar(s) {\r\n this.components[0] /= s;\r\n this.components[1] /= s;\r\n this.components[2] /= s;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Sums the vector with another.\r\n * \r\n * @param {Vector3f} v A vector.\r\n * @returns {Vector3f} Returns itself.\r\n */\r\n add(v) {\r\n this.components[0] += v.components[0];\r\n this.components[1] += v.components[1];\r\n this.components[2] += v.components[2];\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Substracts a vector from this one.\r\n * \r\n * @param {Vector3f} v A vector.\r\n * @returns {Vector3f} Returns itself.\r\n */\r\n subtract(v) {\r\n this.components[0] -= v.components[0];\r\n this.components[1] -= v.components[1];\r\n this.components[2] -= v.components[2];\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Calculates the dot product for the vector with another vector.\r\n * \r\n * @param {Vector3f} v A vector.\r\n * @returns {Number} The dot product of the two vectors.\r\n */\r\n dot(v) {\r\n return this.components[0] * v.components[0] +\r\n this.components[1] * v.components[1] +\r\n this.components[2] * v.components[2];\r\n }\r\n\r\n /**\r\n * Calculates the cross product for the vector with another vector.\r\n * \r\n * @param {Vector3f} v A vector.\r\n * @returns {Vector3f} The cross product of the two vectors.\r\n */\r\n cross(v) {\r\n return new Vector3f(\r\n this.components[1] * v.components[2] - this.components[2] * v.components[1],\r\n this.components[2] * v.components[0] - this.components[0] * v.components[2],\r\n this.components[0] * v.components[1] - this.components[1] * v.components[0]\r\n );\r\n }\r\n\r\n /**\r\n * Applies a projection matrix to the vector.\r\n * \r\n * @param {Matrix4f} m A (projection) matrix.\r\n * @returns {Vector3f} Returns itself.\r\n */\r\n applyProjection(m) {\r\n var x = this.components[0];\r\n var y = this.components[1];\r\n var z = this.components[2];\r\n\r\n var e = m.entries;\r\n var p = 1.0 / (e[3] * x + e[7] * y + e[11] * z + e[15]);\r\n\r\n this.components[0] = (e[0] * x + e[4] * y + e[8] * z + e[12]) * p;\r\n this.components[1] = (e[1] * x + e[5] * y + e[9] * z + e[13]) * p;\r\n this.components[2] = (e[2] * x + e[6] * y + e[10] * z + e[14]) * p;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Rotates the vector into the direction defined by the rotational component of a matrix.\r\n * \r\n * @param {Matrix4f} m A matrix.\r\n * @returns {Vector3f} Returns itself.\r\n */\r\n toDirection(m) {\r\n var x = this.components[0];\r\n var y = this.components[1];\r\n var z = this.components[2];\r\n\r\n var e = m.entries;\r\n\r\n this.components[0] = e[0] * x + e[4] * y + e[8] * z;\r\n this.components[1] = e[1] * x + e[5] * y + e[9] * z;\r\n this.components[2] = e[2] * x + e[6] * y + e[10] * z;\r\n\r\n this.normalize();\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Applies a quaternion to the vector (usually a rotation).\r\n * \r\n * @param {Quaternion} q Quaternion.\r\n * @returns {Vector3f} Returns itself.\r\n */\r\n applyQuaternion(q) {\r\n var x = this.components[0];\r\n var y = this.components[1];\r\n var z = this.components[2];\r\n\r\n var qx = q.components[0];\r\n var qy = q.components[1];\r\n var qz = q.components[2];\r\n var qw = q.components[3];\r\n\r\n var ix = qw * x + qy * z - qz * y;\r\n var iy = qw * y + qz * x - qx * z;\r\n var iz = qw * z + qx * y - qy * x;\r\n var iw = -qx * x - qy * y - qz * z;\r\n\r\n this.components[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;\r\n this.components[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;\r\n this.components[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Calculates the square of the distance to another vector.\r\n * \r\n * @param {Vector3f} v A vector.\r\n * @returns {Number} The square of the distance to the other vector.\r\n */\r\n distanceToSq(v) {\r\n var dx = this.components[0] - v.components[0];\r\n var dy = this.components[1] - v.components[1];\r\n var dz = this.components[2] - v.components[2];\r\n\r\n return dx * dx + dy * dy + dz * dz;\r\n }\r\n\r\n /**\r\n * Calculates the distance to another vector.\r\n * \r\n * @param {Vector3f} v A vector.\r\n * @returns {Number} The distance to the other vector.\r\n */\r\n distanceTo(v) {\r\n return Math.sqrt(this.distanceToSq(v));\r\n }\r\n\r\n /**\r\n * Clones this vector.\r\n * \r\n * @returns {Vector3f} A clone of this vector.\r\n */\r\n clone() {\r\n return new Vector3f(this.components[0], this.components[1],\r\n this.components[2]);\r\n }\r\n\r\n /**\r\n * Compares the components of the vector to those of another.\r\n * \r\n * @param {Vector3f} v A vector.\r\n * @returns {Boolean} A vector indicating whether or not the two vectors are equal.\r\n */\r\n equals(v) {\r\n return this.components[0] === v.components[0] &&\r\n this.components[1] === v.components[1] &&\r\n this.components[2] === v.components[2];\r\n }\r\n\r\n /**\r\n * Returns a string representation of the vector.\r\n * \r\n * @returns {String} A string representation of the vector.\r\n */\r\n toString() {\r\n return '(' + this.components[0] + ', ' + this.components[1] + ', ' +\r\n this.components[2] + ')';\r\n }\r\n\r\n /**\r\n * Normalizes a vector.\r\n * \r\n * @static\r\n * @param {Vector3f} v A vector. \r\n * @returns {Vector3f} The noramlized vector.\r\n */\r\n static normalize(v) {\r\n return Vector3f.divideScalar(v, v.length());\r\n }\r\n\r\n /**\r\n * Multiplies two vectors.\r\n * \r\n * @static\r\n * @param {Vector3f} u A vector. \r\n * @param {Vector3f} v A vector. \r\n * @returns {Vector3f} The product of the two vectors.\r\n */\r\n static multiply(u, v) {\r\n return new Vector3f(u.components[0] * v.components[0],\r\n u.components[1] * v.components[1],\r\n u.components[2] * v.components[2]);\r\n }\r\n\r\n /**\r\n * Multiplies a vector with a scalar.\r\n * \r\n * @static\r\n * @param {Vector3f} v A vector. \r\n * @param {Number} s A scalar.\r\n * @returns {Vector3f} The vector multiplied by the scalar.\r\n */\r\n static multiplyScalar(v, s) {\r\n return new Vector3f(v.components[0] * s,\r\n v.components[1] * s,\r\n v.components[2] * s);\r\n }\r\n\r\n /**\r\n * Divides a vector by another vector (u / v).\r\n * \r\n * @static\r\n * @param {Vector3f} u A vector. \r\n * @param {Vector3f} v A vector. \r\n * @returns {Vector3f} The fraction vector.\r\n */\r\n static divide(u, v) {\r\n return new Vector3f(u.components[0] / v.components[0],\r\n u.components[1] / v.components[1],\r\n u.components[2] / v.components[2]);\r\n }\r\n\r\n /**\r\n * Divides a vector by a scalar.\r\n * \r\n * @static\r\n * @param {Vector3f} v A vector. \r\n * @param {Number} s A scalar.\r\n * @returns {Vector3f} The vector divided by the scalar.\r\n */\r\n static divideScalar(v, s) {\r\n return new Vector3f(v.components[0] / s,\r\n v.components[1] / s,\r\n v.components[2] / s);\r\n }\r\n\r\n /**\r\n * Sums two vectors.\r\n * \r\n * @static\r\n * @param {Vector3f} u A vector. \r\n * @param {Vector3f} v A vector. \r\n * @returns {Vector3f} The sum of the two vectors.\r\n */\r\n static add(u, v) {\r\n return new Vector3f(u.components[0] + v.components[0],\r\n u.components[1] + v.components[1],\r\n u.components[2] + v.components[2]);\r\n }\r\n\r\n /**\r\n * Subtracts one vector from another (u - v)\r\n * \r\n * @static\r\n * @param {Vector3f} u A vector. \r\n * @param {Vector3f} v A vector. \r\n * @returns {Vector3f} The difference between the two vectors.\r\n */\r\n static subtract(u, v) {\r\n return new Vector3f(u.components[0] - v.components[0],\r\n u.components[1] - v.components[1],\r\n u.components[2] - v.components[2]);\r\n }\r\n\r\n /**\r\n * Calculates the cross product of two vectors.\r\n * \r\n * @static\r\n * @param {Vector3f} u A vector. \r\n * @param {Vector3f} v A vector. \r\n * @returns {Vector3f} The cross product of the two vectors.\r\n */\r\n static cross(u, v) {\r\n return new Vector3f(\r\n u.components[1] * v.components[2] - u.components[2] * v.components[1],\r\n u.components[2] * v.components[0] - u.components[0] * v.components[2],\r\n u.components[0] * v.components[1] - u.components[1] * v.components[0]\r\n );\r\n }\r\n\r\n /**\r\n * Calculates the dot product of two vectors.\r\n * \r\n * @static\r\n * @param {Vector3f} u A vector. \r\n * @param {Vector3f} v A vector. \r\n * @returns {Number} The dot product of the two vectors.\r\n */\r\n static dot(u, v) {\r\n return u.components[0] * v.components[0] +\r\n u.components[1] * v.components[1] +\r\n u.components[2] * v.components[2];\r\n }\r\n\r\n /**\r\n * Calculates the midpoint between two vectors.\r\n * \r\n * @static\r\n * @param {Vector3f} u A vector. \r\n * @param {Vector3f} v A vector. \r\n * @returns {Vector3f} The midpoint between the two vectors.\r\n */\r\n static midpoint(u, v) {\r\n return new Vector3f(\r\n u.components[0] + v.components[0] / 2.0,\r\n u.components[1] + v.components[1] / 2.0,\r\n u.components[2] + v.components[2] / 2.0\r\n );\r\n }\r\n\r\n /**\r\n * Returns the forward vector (0, 0, 1).\r\n * \r\n * @static\r\n * @returns {Vector3f} The forward vector.\r\n */\r\n static forward() {\r\n return new Vector3f(0, 0, 1);\r\n }\r\n\r\n /**\r\n * Returns the up vector (0, 1, 0).\r\n * \r\n * @static\r\n * @returns {Vector3f} The up vector.\r\n */\r\n static up() {\r\n return new Vector3f(0, 1, 0);\r\n }\r\n\r\n /**\r\n * Returns the right vector (1, 0, 0).\r\n * \r\n * @static\r\n * @returns {Vector3f} The right vector.\r\n */\r\n static right() {\r\n return new Vector3f(1, 0, 0);\r\n }\r\n}\r\n\r\nmodule.exports = Vector3f\r\n" }, { "alpha_fraction": 0.6571428775787354, "alphanum_fraction": 0.6571428775787354, "avg_line_length": 25.25, "blob_id": "d123e4373a341f79c3882cca80f13d9593ebffc9", "content_id": "b63e64c945231c3f9d4824e4bf7a44dc88582d8d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 105, "license_type": "permissive", "max_line_length": 96, "num_lines": 4, "path": "/doc/all.md", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "[![view on npm](http://img.shields.io/npm/v/example.svg)](https://www.npmjs.org/package/example)\n\n\n* * *\n" }, { "alpha_fraction": 0.6030505895614624, "alphanum_fraction": 0.6127232313156128, "avg_line_length": 25.36274528503418, "blob_id": "72c97a9af182d100eeee726803293b5050f11f68", "content_id": "bbdb94a2aee3d0e632470a313d36cc6fb2814432", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2688, "license_type": "permissive", "max_line_length": 214, "num_lines": 102, "path": "/src/Filters/InRangeFilter.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst FilterBase = require('./FilterBase');\nconst Color = require('../Core/Color');\n\n/** \n * A class representing an In-Range-Filter. It is used to filter a geometry based on a min and max value. \n * @property {number} min The minimum value.\n * @property {number} max The maximum value.\n * */\nclass InRangeFilter extends FilterBase {\n /**\n * Creates an instance of InRangeFilter.\n * @param {string} attribute The name of the attribute to filter on.\n * @param {number} attributeIndex The attribute-index to filter on.\n * @param {number} min The minum value.\n * @param {number} max The maximum value.\n */\n constructor(attribute, attributeIndex, min, max) {\n super(attribute, attributeIndex);\n\n this.min = min;\n this.max = max;\n }\n\n /**\n * Get the minimum.\n * \n * @returns {number} The minimum.\n */\n getMin() {\n return this.min;\n }\n\n /**\n * Set the minimum.\n * \n * @param {number} value The minimum.\n */\n setMin(value) {\n this.min = value;\n }\n\n /**\n * Get the maximum.\n * \n * @returns {number} The maximum.\n */\n getMax() {\n return this.max;\n }\n\n /**\n * Set the maximum.\n * \n * @param {number} value The maximum.\n */\n setMax(value) {\n this.max = value;\n }\n\n /**\n * Execute the filter operation on the specified attribute and attribute-index. In order to filter, the HSS size value (attribute-index 2 of the color attribute) is set to its negative (1.0 -> -1.0, 2.5 -> -2.5).\n */\n filter() {\n let attribute = this.geometry.attributes[this.attribute];\n let isHue = (this.attribute === 'color') && (this.attributeIndex === 0);\n\n for (let i = 0; i < attribute.data.length; i += attribute.attributeLength) {\n let value = attribute.data[i + this.attributeIndex];\n\n if (isHue) {\n value = Color.floatToHsl(value)[0];\n }\n\n let size = this.geometry.attributes['color'].data[i + 2];\n if (value > this.max || value < this.min) {\n this.geometry.attributes['color'].data[i + 2] = -Math.abs(size);\n } else {\n this.geometry.attributes['color'].data[i + 2] = Math.abs(size);\n }\n }\n\n this.geometry.updateAttribute('color');\n }\n\n /**\n * Resets the filter (\"removes\" it). The HSS size value is set back to its original value (-1.0 -> 1.0, -2.5 -> 2.5). \n */\n reset() {\n let attribute = this.geometry.attributes[this.attribute];\n\n for (let i = 0; i < attribute.data.length; i += attribute.attributeLength) {\n let size = this.geometry.attributes['color'].data[i + 2];\n this.geometry.attributes['color'].data[i + 2] = Math.abs(size);\n }\n\n this.geometry.updateAttribute('color');\n }\n}\n\nmodule.exports = InRangeFilter" }, { "alpha_fraction": 0.44080403447151184, "alphanum_fraction": 0.4767839312553406, "avg_line_length": 40.983123779296875, "blob_id": "18ba3c5d379260c7f1be16b6814399ab17cde3d3", "content_id": "5cd608a76e484506b22aa23196de8cdb8d86202c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 9950, "license_type": "permissive", "max_line_length": 151, "num_lines": 237, "path": "/src/Helpers/CoordinatesHelper.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst Color = require('../Core/Color');\nconst HelperBase = require('./HelperBase');\nconst Vector3f = require('../Math/Vector3f');\nconst Utils = require('../Utils/Utils');\nconst DrawModes = require('../Core/DrawModes');\nconst PointHelper = require('./PointHelper')\n\n/** A helper class for drawing coordinate system indicators. For example, a grid cube. */\nclass CoordinatesHelper extends HelperBase {\n\n /**\n * Creates an instance of CoordinatesHelper.\n * \n * @param {Renderer} renderer A Lore.Renderer object.\n * @param {string} geometryName The name of this geometry.\n * @param {string} shaderName The name of the shader used to render the coordinates.\n * @param {object} options Options for drawing the coordinates. See documentation for details.\n */\n constructor(renderer, geometryName, shaderName = 'coordinates', options = {}) {\n super(renderer, geometryName, shaderName);\n this.defaults = {\n position: new Vector3f(0.0, 0.0, 0.0),\n axis: {\n x: {\n length: 50.0,\n color: Color.fromHex('#222222')\n },\n y: {\n length: 50.0,\n color: Color.fromHex('#222222')\n },\n z: {\n length: 50.0,\n color: Color.fromHex('#222222')\n }\n },\n ticks: {\n enabled: true,\n x: {\n count: 10,\n length: 5.0,\n offset: new Vector3f(0.0, 0.0, 0.0),\n color: Color.fromHex('#1f1f1f')\n },\n y: {\n count: 10,\n length: 5.0,\n offset: new Vector3f(0.0, 0.0, 0.0),\n color: Color.fromHex('#1f1f1f')\n },\n z: {\n count: 10,\n length: 5.0,\n offset: new Vector3f(0.0, 0.0, 0.0),\n color: Color.fromHex('#1f1f1f')\n }\n },\n box: {\n enabled: true,\n x: {\n color: Color.fromHex('#222222')\n },\n y: {\n color: Color.fromHex('#222222')\n },\n z: {\n color: Color.fromHex('#222222')\n }\n },\n }\n\n this.opts = Utils.extend(true, this.defaults, options);\n\n this.geometry.setMode(DrawModes.lines);\n this.init();\n }\n\n /**\n * Initializes the coordinates system.\n */\n init() {\n let p = this.opts.position.components;\n let ao = this.opts.axis;\n\n // Setting the origin position of the axes\n let positions = [\n p[0], p[1], p[2], p[0] + ao.x.length, p[1], p[2],\n p[0], p[1], p[2], p[0], p[1] + ao.y.length, p[2],\n p[0], p[1], p[2], p[0], p[1], p[2] + ao.z.length\n ];\n\n // Setting the colors of the axes\n let cx = ao.x.color.components;\n let cy = ao.y.color.components;\n let cz = ao.z.color.components;\n\n let colors = [\n cx[0], cx[1], cx[2], cx[0], cx[1], cx[2],\n cy[0], cy[1], cy[2], cy[0], cy[1], cy[2],\n cz[0], cz[1], cz[2], cz[0], cz[1], cz[2]\n ];\n\n // Adding the box\n if (this.opts.box.enabled) {\n let bx = this.opts.box.x.color.components;\n let by = this.opts.box.y.color.components;\n let bz = this.opts.box.z.color.components;\n\n positions.push(\n p[0] + ao.x.length, p[1] + ao.y.length, p[2] + ao.z.length, p[0], p[1] + ao.y.length, p[2] + ao.z.length,\n p[0] + ao.x.length, p[1], p[2] + ao.z.length, p[0], p[1], p[2] + ao.z.length,\n p[0] + ao.x.length, p[1] + ao.y.length, p[2], p[0], p[1] + ao.y.length, p[2],\n p[0] + ao.x.length, p[1] + ao.y.length, p[2] + ao.z.length, p[0] + ao.x.length, p[1], p[2] + ao.z.length,\n p[0], p[1] + ao.y.length, p[2] + ao.z.length, p[0], p[1], p[2] + ao.z.length,\n p[0] + ao.x.length, p[1] + ao.y.length, p[2], p[0] + ao.x.length, p[1], p[2],\n p[0] + ao.x.length, p[1] + ao.y.length, p[2] + ao.z.length, p[0] + ao.x.length, p[1] + ao.y.length, p[2],\n p[0], p[1] + ao.y.length, p[2] + ao.z.length, p[0], p[1] + ao.y.length, p[2],\n p[0] + ao.x.length, p[1], p[2] + ao.z.length, p[0] + ao.x.length, p[1], p[2]\n );\n\n colors.push(\n bx[0], bx[1], bx[2], bx[0], bx[1], bx[2],\n bx[0], bx[1], bx[2], bx[0], bx[1], bx[2],\n bx[0], bx[1], bx[2], bx[0], bx[1], bx[2],\n by[0], by[1], by[2], by[0], by[1], by[2],\n by[0], by[1], by[2], by[0], by[1], by[2],\n by[0], by[1], by[2], by[0], by[1], by[2],\n bz[0], bz[1], bz[2], bz[0], bz[1], bz[2],\n bz[0], bz[1], bz[2], bz[0], bz[1], bz[2],\n bz[0], bz[1], bz[2], bz[0], bz[1], bz[2]\n );\n }\n\n // Adding the ticks\n if (this.opts.ticks.enabled) {\n let xTicks = this.opts.ticks.x, xTickOffset = ao.x.length / xTicks.count;\n let yTicks = this.opts.ticks.y, yTickOffset = ao.y.length / yTicks.count;\n let zTicks = this.opts.ticks.z, zTickOffset = ao.z.length / zTicks.count;\n\n // X ticks\n let pos = p[0];\n let col = xTicks.color.components;\n\n for (let i = 0; i < xTicks.count - 1; i++) {\n pos += xTickOffset;\n // From\n positions.push(pos + xTicks.offset.components[0], p[1] + xTicks.offset.components[1], p[2] + xTicks.offset.components[2],\n pos + xTicks.offset.components[0], p[1] + xTicks.offset.components[1] + xTicks.length, p[2] + xTicks.offset.components[2]);\n colors.push(col[0], col[1], col[2], col[0], col[1], col[2]);\n }\n\n pos = p[0];\n\n for (let i = 0; i < xTicks.count - 1; i++) {\n pos += xTickOffset;\n // From\n positions.push(pos + xTicks.offset.components[0], p[1] + xTicks.offset.components[1], p[2] + xTicks.offset.components[2],\n pos + xTicks.offset.components[0], p[1] + xTicks.offset.components[1], p[2] + xTicks.offset.components[2] + xTicks.length);\n colors.push(col[0], col[1], col[2], col[0], col[1], col[2]);\n }\n\n // Y ticks\n pos = p[1];\n col = yTicks.color.components;\n\n for (let i = 0; i < yTicks.count - 1; i++) {\n pos += yTickOffset;\n // From\n positions.push(p[0] + yTicks.offset.components[0], pos + yTicks.offset.components[1], p[2] + yTicks.offset.components[2],\n p[0] + yTicks.offset.components[0] + yTicks.length, pos + yTicks.offset.components[1], p[2] + yTicks.offset.components[2]);\n colors.push(col[0], col[1], col[2], col[0], col[1], col[2]);\n }\n\n pos = p[1];\n\n for (let i = 0; i < yTicks.count - 1; i++) {\n pos += yTickOffset;\n // From\n positions.push(p[0] + yTicks.offset.components[0], pos + yTicks.offset.components[1], p[2] + yTicks.offset.components[2],\n p[0] + yTicks.offset.components[0], pos + yTicks.offset.components[1], p[2] + yTicks.offset.components[2] + yTicks.length);\n colors.push(col[0], col[1], col[2], col[0], col[1], col[2]);\n }\n\n // Z ticks\n pos = p[2];\n col = zTicks.color.components;\n \n for (let i = 0; i < zTicks.count - 1; i++) {\n pos += zTickOffset;\n // From\n positions.push(p[0] + zTicks.offset.components[0], p[1] + zTicks.offset.components[1], pos + zTicks.offset.components[2],\n p[0] + zTicks.offset.components[0], p[1] + zTicks.offset.components[1] + zTicks.length, pos + zTicks.offset.components[2]);\n colors.push(col[0], col[1], col[2], col[0], col[1], col[2]);\n }\n\n pos = p[2];\n \n for (let i = 0; i < zTicks.count - 1; i++) {\n pos += zTickOffset;\n // From\n positions.push(p[0] + zTicks.offset.components[0], p[1] + zTicks.offset.components[1], pos + zTicks.offset.components[2],\n p[0] + zTicks.offset.components[0] + zTicks.length, p[1] + zTicks.offset.components[1], pos + zTicks.offset.components[2]);\n colors.push(col[0], col[1], col[2], col[0], col[1], col[2]);\n }\n }\n\n this.setAttribute('position', new Float32Array(positions));\n this.setAttribute('color', new Float32Array(colors));\n }\n\n /**\n * Creates an instance of CoordinatesHelper from a PointHelper.\n * \n * @param {PointHelper} pointHelper A Lore.Helpers.PointHelper object.\n */\n static fromPointHelper(pointHelper, options = {}) {\n let renderer = pointHelper.renderer;\n let geometryName = pointHelper.geometry.name + '_Coordinates';\n\n let opts = {\n axis: {\n x: { length: Math.abs(pointHelper.getDimensions().max.getX()) + Math.abs(pointHelper.getDimensions().min.getX()) },\n y: { length: Math.abs(pointHelper.getDimensions().max.getY()) + Math.abs(pointHelper.getDimensions().min.getY()) },\n z: { length: Math.abs(pointHelper.getDimensions().max.getZ()) + Math.abs(pointHelper.getDimensions().min.getZ()) }\n }\n }\n\n\n opts = Utils.extend(true, opts, options);\n\n return new CoordinatesHelper(renderer, geometryName, opts)\n }\n}\n\nmodule.exports = CoordinatesHelper\n" }, { "alpha_fraction": 0.5893296599388123, "alphanum_fraction": 0.6013387441635132, "avg_line_length": 27.94301986694336, "blob_id": "59cffd403619faf097a34db3bf64b2301efe72c6", "content_id": "4d0c13c9575c1a9be19c4567f0449576f01ba962", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 20318, "license_type": "permissive", "max_line_length": 147, "num_lines": 702, "path": "/src/Helpers/OctreeHelper.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst HelperBase = require(\"./HelperBase\");\nconst PointHelper = require(\"./PointHelper\");\nconst Octree = require(\"../Spice/Octree\");\nconst Raycaster = require(\"../Spice/Raycaster\");\nconst DrawModes = require(\"../Core/DrawModes\");\nconst Utils = require(\"../Utils/Utils\");\nconst Vector3f = require(\"../Math/Vector3f\");\nconst AABB = require(\"../Spice/AABB\");\nconst Matrix4f = require(\"../Math/Matrix4f\");\nconst FilterBase = require(\"../Filters/FilterBase\");\nconst Ray = require(\"../Math/Ray\");\n\n/**\n * A helper class to create an octree associated with vertex data.\n *\n * @property {*} opts An object containing options.\n * @property {PointHelper} target The Lore.PointHelper object from which this octree is constructed.\n * @property {Renderer} renderer An instance of Lore.Renderer.\n * @property {Octree} octree The octree associated with the target.\n * @property {Raycaster} raycaster An instance of Lore.Raycaster.\n * @property {Object} hovered The currently hovered item.\n * @property {Object[]} selected The currently selected items.\n */\nclass OctreeHelper extends HelperBase {\n /**\n * Creates an instance of OctreeHelper.\n *\n * @param {Renderer} renderer A Lore.Renderer object.\n * @param {String} geometryName The name of this geometry.\n * @param {String} shaderName The name of the shader used to render this octree.\n * @param {PointHelper} target The Lore.PointHelper object from which this octree is constructed.\n * @param {Object} options The options used to draw this octree.\n */\n constructor(renderer, geometryName, shaderName, target, options) {\n super(renderer, geometryName, shaderName);\n\n this.defaults = {\n visualize: false,\n multiSelect: true\n };\n\n this.opts = Utils.extend(true, this.defaults, options);\n this._eventListeners = {};\n this.target = target;\n this.renderer = renderer;\n this.octree = this.target.octree;\n this.raycaster = new Raycaster(1.0);\n this.hovered = null;\n this.selected = [];\n\n // Register this octreeHelper with the pointHelper\n this.target.octreeHelper = this;\n\n let that = this;\n\n this._clickHandler = function(e) {\n if (\n e.e.mouse.state.middle ||\n e.e.mouse.state.right ||\n !that.target.geometry.isVisible\n ) {\n return;\n }\n\n let mouse = e.e.mouse.normalizedPosition;\n let result = that.getIntersections(mouse);\n\n if (result.length > 0) that.addSelected(result[0]);\n };\n\n renderer.controls.addEventListener(\"click\", this._clickHandler);\n\n this._dblclickHandler = function(e) {\n if (\n e.e.mouse.state.middle ||\n e.e.mouse.state.right ||\n !that.target.geometry.isVisible\n ) {\n return;\n }\n\n let mouse = e.e.mouse.normalizedPosition;\n let result = that.getIntersections(mouse);\n\n if (result.length > 0) that.addSelected(result[0]);\n };\n\n renderer.controls.addEventListener(\"dblclick\", this._dblclickHandler);\n\n this._mousemoveHandler = function(e) {\n if (\n e.e.mouse.state.left ||\n e.e.mouse.state.middle ||\n e.e.mouse.state.right ||\n !that.target.geometry.isVisible\n ) {\n return;\n }\n\n let mouse = e.e.mouse.normalizedPosition;\n let result = that.getIntersections(mouse);\n\n if (result.length > 0) {\n if (that.hovered && that.hovered.index === result[0].index) {\n return;\n }\n\n that.hovered = result[0];\n that.hovered.screenPosition = that.renderer.camera.sceneToScreen(\n result[0].position,\n renderer\n );\n\n that.raiseEvent(\"hoveredchanged\", {\n e: that.hovered\n });\n } else {\n that.hovered = null;\n that.raiseEvent(\"hoveredchanged\", {\n e: null\n });\n }\n };\n\n renderer.controls.addEventListener(\"mousemove\", this._mousemoveHandler);\n\n this._updatedHandler = function() {\n if (!that.target.geometry.isVisible) {\n return;\n }\n\n for (let i = 0; i < that.selected.length; i++) {\n that.selected[i].screenPosition = that.renderer.camera.sceneToScreen(\n that.selected[i].position,\n renderer\n );\n }\n\n if (that.hovered) {\n that.hovered.screenPosition = that.renderer.camera.sceneToScreen(\n that.hovered.position,\n renderer\n );\n }\n\n that.raiseEvent(\"updated\");\n };\n\n renderer.controls.addEventListener(\"updated\", this._updatedHandler);\n\n this.init();\n }\n\n /**\n * Initialize this octree.\n */\n init() {\n if (this.opts.visualize === \"centers\") {\n this.drawCenters();\n } else if (this.opts.visualize === \"cubes\") {\n this.drawBoxes();\n } else {\n this.geometry.isVisible = false;\n }\n }\n\n /**\n * Get the screen position of a vertex by its index.\n *\n * @param {Number} index The index of a vertex.\n * @returns {Number[]} An array containing the screen position. E.g. [122, 290].\n */\n getScreenPosition(index) {\n let positions = this.target.geometry.attributes[\"position\"].data;\n let k = index * 3;\n let p = new Vector3f(positions[k], positions[k + 1], positions[k + 2]);\n\n return this.renderer.camera.sceneToScreen(p, this.renderer);\n }\n\n /**\n * Adds an object to the selected collection of this Lore.OctreeHelper object.\n *\n * @param {Object|Number} item Either an item (used internally) or the index of a vertex from the associated Lore.PointHelper object.\n */\n addSelected(item) {\n // If item is only the index, create a dummy item\n if (!isNaN(parseFloat(item))) {\n let positions = this.target.geometry.attributes[\"position\"].data;\n let k = item * 3;\n\n let color = null;\n if (this.target.hasAttribute('color'))\n color = this.target.getColor(item);\n\n item = {\n distance: -1,\n index: item,\n locCode: -1,\n position: new Vector3f(\n positions[k],\n positions[k + 1],\n positions[k + 2]\n ),\n color: color\n };\n }\n\n if (this.selectedContains(item.index)) {\n this.raiseEvent(\"reselected\", {\n e: item\n });\n return;\n }\n\n // Add a timestamp to every selected item. This can be used to order\n // selected items in a GUI\n item[\"timestamp\"] = Date.now();\n\n let index = this.selected.length;\n\n if (this.opts.multiSelect) {\n this.selected.push(item);\n } else {\n this.selected[0] = item;\n index = 0;\n }\n\n this.selected[index].screenPosition = this.renderer.camera.sceneToScreen(\n item.position,\n this.renderer\n );\n this.raiseEvent(\"selectedchanged\", {\n e: this.selected\n });\n }\n\n /**\n * Remove an item from the selected collection of this Lore.OctreeHelper object.\n *\n * @param {Number} index The index of the item in the selected collection.\n */\n removeSelected(index) {\n this.selected.splice(index, 1);\n\n this.raiseEvent(\"selectedchanged\", {\n e: this.selected\n });\n }\n\n /**\n * Clear the selected collection of this Lore.OctreeHelper object.\n */\n clearSelected() {\n this.selected = [];\n\n this.raiseEvent(\"selectedchanged\", {\n e: this.selected\n });\n }\n\n /**\n * Check whether or not the selected collection of this Lore.OctreeHelper object contains a vertex with a given index.\n *\n * @param {Number} index The index of a vertex in the associated Lore.PointHelper object.\n * @returns {Boolean} A boolean indicating whether or not the selected collection of this Lore.OctreeHelper contains a vertex with a given index.\n */\n selectedContains(index) {\n for (let i = 0; i < this.selected.length; i++) {\n if (this.selected[i].index === index) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Adds a vertex with a given index to the currently hovered vertex of this Lore.OctreeHelper object.\n *\n * @param {Number} index The index of a vertex in the associated Lore.PointHelper object.\n */\n setHovered(index) {\n if (this.hovered && this.hovered.index === index) {\n return;\n }\n\n let k = index * 3;\n let positions = this.target.geometry.attributes[\"position\"].data;\n \n let color = null;\n if (this.target.hasAttribute('color'))\n color = this.target.getColor(index);\n\n this.hovered = {\n index: index,\n position: new Vector3f(positions[k], positions[k + 1], positions[k + 2]),\n color: color\n };\n\n this.hovered.screenPosition = this.renderer.camera.sceneToScreen(\n this.hovered.position,\n this.renderer\n );\n this.raiseEvent(\"hoveredchanged\", {\n e: this.hovered\n });\n }\n\n /**\n * Add the currently hovered vertex to the collection of selected vertices.\n */\n selectHovered() {\n if (!this.hovered || this.selectedContains(this.hovered.index)) {\n return;\n }\n\n this.addSelected({\n distance: this.hovered.distance,\n index: this.hovered.index,\n locCode: this.hovered.locCode,\n position: this.hovered.position,\n color: this.hovered.color\n });\n }\n\n /**\n * Show the centers of the axis-aligned bounding boxes of this octree.\n */\n showCenters() {\n this.opts.visualize = \"centers\";\n this.drawCenters();\n this.geometry.isVisible = true;\n }\n\n /**\n * Show the axis-aligned boudning boxes of this octree as cubes.\n */\n showCubes() {\n this.opts.visualize = \"cubes\";\n this.drawBoxes();\n this.geometry.isVisible = true;\n }\n\n /**\n * Hide the centers or cubes of the axis-aligned bounding boxes associated with this octree.\n */\n hide() {\n this.opts.visualize = false;\n this.geometry.isVisible = false;\n\n this.setAttribute(\"position\", new Float32Array([]));\n this.setAttribute(\"color\", new Float32Array([]));\n }\n\n /**\n * Get the indices and distances of the vertices currently intersected by the ray sent from the mouse position.\n *\n * @param {Object} mouse A mouse object containing x and y properties.\n * @returns {Object[]} A distance-sorted (ASC) array containing the interesected vertices.\n */\n getIntersections(mouse) {\n this.raycaster.set(this.renderer.camera, mouse.x, mouse.y);\n\n let tmp = this.octree.raySearch(this.raycaster);\n let result = this.rayIntersections(tmp);\n\n result.sort(function(a, b) {\n return a.distance - b.distance;\n });\n\n return result;\n }\n\n /**\n * \n */\n getVisible() {\n let frustum = this.renderer.camera.getFrustum();\n console.log(frustum[0].toString());\n console.log(frustum[1].toString());\n this.octree.intersectBox(frustum[0], frustum[1]);\n }\n\n /**\n * Add an event listener to this Lore.OctreeHelper object.\n *\n * @param {String} eventName The name of the event to listen for.\n * @param {Function} callback A callback function called when an event is fired.\n */\n addEventListener(eventName, callback) {\n if (!this._eventListeners[eventName]) {\n this._eventListeners[eventName] = [];\n }\n\n this._eventListeners[eventName].push(callback);\n }\n\n /**\n * Raise an event with a given name and send the data to the functions listening for this event.\n *\n * @param {String} eventName The name of the event to be rised.\n * @param {*} [data={}] Data to be sent to the listening functions.\n */\n raiseEvent(eventName, data = {}) {\n if (!this._eventListeners[eventName]) {\n return;\n }\n\n for (let i = 0; i < this._eventListeners[eventName].length; i++) {\n this._eventListeners[eventName][i](data);\n }\n }\n\n /**\n * Adds a hoveredchanged event to multiple octrees and merges the event property e.\n *\n * @param {OctreeHelper[]} octreeHelpers An array of octree helpers to join.\n * @param {Function} eventListener A event listener for hoveredchanged.\n */\n static joinHoveredChanged(octreeHelpers, eventListener) {\n for (let i = 0; i < octreeHelpers.length; i++) {\n octreeHelpers[i].addEventListener(\"hoveredchanged\", function(e) {\n let result = { e: null, source: null };\n for (let j = 0; j < octreeHelpers.length; j++) {\n if (octreeHelpers[j].hovered !== null) {\n result = { e: octreeHelpers[j].hovered, source: j };\n }\n }\n eventListener(result);\n });\n }\n }\n\n /**\n * Adds a selectedchanged event to multiple octrees and merges the event property e.\n *\n * @param {OctreeHelper[]} octreeHelpers An array of octree helpers to join.\n * @param {Function} eventListener A event listener for selectedchanged.\n */\n static joinSelectedChanged(octreeHelpers, eventListener) {\n for (let i = 0; i < octreeHelpers.length; i++) {\n octreeHelpers[i].addEventListener(\"selectedchanged\", function(e) {\n let result = [];\n for (let j = 0; j < octreeHelpers.length; j++) {\n for (let k = 0; k < octreeHelpers[j].selected.length; k++)\n result.push({\n timestamp: octreeHelpers[j].selected[k].timestamp,\n item: octreeHelpers[j].selected[k],\n index: k,\n source: j\n });\n }\n eventListener(result);\n });\n }\n }\n\n /**\n * Adds a reselected event to multiple octrees and merges the event property e.\n *\n * @param {OctreeHelper[]} octreeHelpers An array of octree helpers to join.\n * @param {Function} eventListener A event listener for selectedchanged.\n */\n static joinReselected(octreeHelpers, eventListener) {\n for (let i = 0; i < octreeHelpers.length; i++) {\n octreeHelpers[i].addEventListener(\"reselected\", function(e) {\n let result = [];\n for (let j = 0; j < octreeHelpers.length; j++) {\n result.push({\n item: e,\n source: j\n });\n }\n eventListener(result);\n });\n }\n }\n\n /**\n * Draw the centers of the axis-aligned bounding boxes of this octree.\n */\n drawCenters() {\n this.geometry.setMode(DrawModes.points);\n\n let aabbs = this.octree.aabbs;\n let length = Object.keys(aabbs).length;\n let colors = new Float32Array(length * 3);\n let positions = new Float32Array(length * 3);\n\n let i = 0;\n\n for (var key in aabbs) {\n let c = aabbs[key].center.components;\n let k = i * 3;\n\n colors[k] = 1;\n colors[k + 1] = 1;\n colors[k + 2] = 1;\n\n positions[k] = c[0];\n positions[k + 1] = c[1];\n positions[k + 2] = c[2];\n\n i++;\n }\n\n this.setAttribute(\"position\", new Float32Array(positions));\n this.setAttribute(\"color\", new Float32Array(colors));\n }\n\n /**\n * Draw the axis-aligned bounding boxes of this octree.\n */\n drawBoxes() {\n this.geometry.setMode(DrawModes.lines);\n\n let aabbs = this.octree.aabbs;\n let length = Object.keys(aabbs).length;\n let c = new Float32Array(length * 24 * 3);\n let p = new Float32Array(length * 24 * 3);\n\n for (let i = 0; i < c.length; i++) {\n c[i] = 255.0;\n }\n\n let index = 0;\n\n for (var key in aabbs) {\n let corners = AABB.getCorners(aabbs[key]);\n\n p[index++] = corners[0][0];\n p[index++] = corners[0][1];\n p[index++] = corners[0][2];\n p[index++] = corners[1][0];\n p[index++] = corners[1][1];\n p[index++] = corners[1][2];\n p[index++] = corners[0][0];\n p[index++] = corners[0][1];\n p[index++] = corners[0][2];\n p[index++] = corners[2][0];\n p[index++] = corners[2][1];\n p[index++] = corners[2][2];\n p[index++] = corners[0][0];\n p[index++] = corners[0][1];\n p[index++] = corners[0][2];\n p[index++] = corners[4][0];\n p[index++] = corners[4][1];\n p[index++] = corners[4][2];\n\n p[index++] = corners[1][0];\n p[index++] = corners[1][1];\n p[index++] = corners[1][2];\n p[index++] = corners[3][0];\n p[index++] = corners[3][1];\n p[index++] = corners[3][2];\n p[index++] = corners[1][0];\n p[index++] = corners[1][1];\n p[index++] = corners[1][2];\n p[index++] = corners[5][0];\n p[index++] = corners[5][1];\n p[index++] = corners[5][2];\n\n p[index++] = corners[2][0];\n p[index++] = corners[2][1];\n p[index++] = corners[2][2];\n p[index++] = corners[3][0];\n p[index++] = corners[3][1];\n p[index++] = corners[3][2];\n p[index++] = corners[2][0];\n p[index++] = corners[2][1];\n p[index++] = corners[2][2];\n p[index++] = corners[6][0];\n p[index++] = corners[6][1];\n p[index++] = corners[6][2];\n\n p[index++] = corners[3][0];\n p[index++] = corners[3][1];\n p[index++] = corners[3][2];\n p[index++] = corners[7][0];\n p[index++] = corners[7][1];\n p[index++] = corners[7][2];\n\n p[index++] = corners[4][0];\n p[index++] = corners[4][1];\n p[index++] = corners[4][2];\n p[index++] = corners[5][0];\n p[index++] = corners[5][1];\n p[index++] = corners[5][2];\n p[index++] = corners[4][0];\n p[index++] = corners[4][1];\n p[index++] = corners[4][2];\n p[index++] = corners[6][0];\n p[index++] = corners[6][1];\n p[index++] = corners[6][2];\n\n p[index++] = corners[5][0];\n p[index++] = corners[5][1];\n p[index++] = corners[5][2];\n p[index++] = corners[7][0];\n p[index++] = corners[7][1];\n p[index++] = corners[7][2];\n\n p[index++] = corners[6][0];\n p[index++] = corners[6][1];\n p[index++] = corners[6][2];\n p[index++] = corners[7][0];\n p[index++] = corners[7][1];\n p[index++] = corners[7][2];\n }\n\n this.setAttribute(\"position\", p);\n this.setAttribute(\"color\", c);\n }\n\n /**\n * Set the threshold of the raycaster associated with this Lore.OctreeHelper object.\n *\n * @param {Number} threshold The threshold (maximum distance to the ray) of the raycaster.\n */\n setThreshold(threshold) {\n this.raycaster.threshold = threshold;\n }\n\n /**\n * Execute a ray intersection search within this octree.\n *\n * @param {Number[]} indices The indices of the octree nodes that are intersected by the ray.\n * @returns {*} An array containing the vertices intersected by the ray.\n */\n rayIntersections(indices) {\n let result = [];\n let inverseMatrix = Matrix4f.invert(this.target.modelMatrix); // this could be optimized, since the model matrix does not change\n let ray = new Ray();\n let threshold = this.raycaster.threshold * this.target.getPointScale();\n let positions = this.target.geometry.attributes[\"position\"].data; \n\n // Only get points further away than the cutoff set in the point HelperBase\n let cutoff = this.target.getCutoff();\n\n ray.copyFrom(this.raycaster.ray).applyProjection(inverseMatrix);\n\n let localThreshold = threshold; // / ((pointCloud.scale.x + pointCloud.scale.y + pointCloud.scale.z) / 3);\n let localThresholdSq = localThreshold * localThreshold;\n\n for (let i = 0; i < indices.length; i++) {\n let index = indices[i].index;\n let locCode = indices[i].locCode;\n let k = index * 3;\n let v = new Vector3f(positions[k], positions[k + 1], positions[k + 2]);\n\n let color = null;\n if (this.target.hasAttribute('color'))\n color = this.target.getColor(index);\n\n let rayPointDistanceSq = ray.distanceSqToPoint(v);\n if (rayPointDistanceSq < localThresholdSq) {\n let intersectedPoint = ray.closestPointToPoint(v);\n intersectedPoint.applyProjection(this.target.modelMatrix);\n let dist = this.raycaster.ray.source.distanceTo(intersectedPoint);\n let isVisible = FilterBase.isVisible(this.target.geometry, index);\n if (\n dist < this.raycaster.near ||\n dist > this.raycaster.far ||\n dist < cutoff ||\n !isVisible\n )\n continue;\n\n result.push({\n distance: dist,\n index: index,\n locCode: locCode,\n position: v,\n color: color\n });\n }\n }\n\n return result;\n }\n\n /**\n * Remove eventhandlers from associated controls.\n */\n destruct() {\n this.renderer.controls.removeEventListener(\"click\", this._dblclickHandler);\n this.renderer.controls.removeEventListener(\n \"dblclick\",\n this._dblclickHandler\n );\n this.renderer.controls.removeEventListener(\n \"mousemove\",\n this._mousemoveHandler\n );\n this.renderer.controls.removeEventListener(\"updated\", this._updatedHandler);\n }\n}\n\nmodule.exports = OctreeHelper;\n" }, { "alpha_fraction": 0.5931726694107056, "alphanum_fraction": 0.6100401878356934, "avg_line_length": 27.965116500854492, "blob_id": "5a429d54a6c301b9b1d5403c70a524cec4f05a52", "content_id": "a85d6c435652884d19efb7615d900733ac1e99f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2490, "license_type": "permissive", "max_line_length": 98, "num_lines": 86, "path": "/src/Math/Ray.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst Vector3f = require('./Vector3f');\nconst ProjectionMatrix = require('./ProjectionMatrix');\nconst Matrix4f = require('./Matrix4f');\n\n/** A class representing a ray */\nclass Ray {\n\n /**\n * Creates an instance of Ray.\n * @param {Vector3f} [source = new Vector3f(0.0, 0.0, 0.0)] The source of the ray.\n * @param {Vector3f} [direction = new Vector3f(0.0, 0.0, 0.0)] The direction of the ray.\n */\n constructor(source = new Vector3f(0.0, 0.0, 0.0), direction = new Vector3f(0.0, 0.0, 0.0)) {\n this.source = source;\n this.direction = direction;\n }\n\n /**\n * Copy the values from another ray.\n * \n * @param {Ray} r A ray.\n * @returns {Ray} Returns itself.\n */\n copyFrom(r) {\n this.source.copyFrom(r.source);\n this.direction.copyFrom(r.direction);\n\n return this;\n }\n\n /**\n * Apply a projection matrix to this ray.\n * \n * @param {Matrix4f|ProjectionMatrix} m A matrix / projection matrix.\n * @returns {Ray} Returns itself.\n */\n applyProjection(m) {\n this.direction.add(this.source).applyProjection(m);\n this.source.applyProjection(m);\n this.direction.subtract(this.source);\n this.direction.normalize();\n\n return this;\n }\n\n // See if the two following functions can be optimized\n /**\n * The square of the distance of a vector to this ray.\n * \n * @param {Vector3f} v A vector.\n * @returns {Number} The square pf the distance between the point and this ray.\n */\n distanceSqToPoint(v) {\n let tmp = Vector3f.subtract(v, this.source);\n let directionDistance = tmp.dot(this.direction);\n\n if (directionDistance < 0) {\n return this.source.distanceToSq(v);\n }\n\n tmp.copyFrom(this.direction).multiplyScalar(directionDistance).add(this.source);\n\n return tmp.distanceToSq(v);\n }\n\n /**\n * Find a point on the ray that is closest to a supplied vector.\n * \n * @param {Vector3f} v A vector.\n * @returns {Vector3f} The cloest point on the ray to the supplied point.\n */\n closestPointToPoint(v) {\n let result = Vector3f.subtract(v, this.source);\n let directionDistance = result.dot(this.direction);\n\n if (directionDistance < 0) {\n return result.copyFrom(this.source);\n }\n\n return result.copyFrom(this.direction).multiplyScalar(directionDistance).add(this.source);\n }\n}\n\nmodule.exports = Ray" }, { "alpha_fraction": 0.7412060499191284, "alphanum_fraction": 0.7412060499191284, "avg_line_length": 25.600000381469727, "blob_id": "8df381749517e451d6d911fa233d6e89978b1a99", "content_id": "150b2b23f374036e4173bb1506a8d1034db9180a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 398, "license_type": "permissive", "max_line_length": 57, "num_lines": 15, "path": "/src/Helpers/index.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "const AABBHelper = require('./AABBHelper');\nconst CoordinatesHelper = require('./CoordinatesHelper');\nconst HelperBase = require('./HelperBase');\nconst OctreeHelper = require('./OctreeHelper');\nconst PointHelper = require('./PointHelper');\nconst TreeHelper = require('./TreeHelper');\n\nmodule.exports = {\n AABBHelper,\n CoordinatesHelper,\n HelperBase,\n OctreeHelper,\n PointHelper,\n TreeHelper\n}" }, { "alpha_fraction": 0.5998366475105286, "alphanum_fraction": 0.6312780976295471, "avg_line_length": 35.82706832885742, "blob_id": "1796b0584a1400bc97fadb031ead1dc6876a433a", "content_id": "a210f343ac12f65cbefba699cd25a05ca396e4d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4898, "license_type": "permissive", "max_line_length": 403, "num_lines": 133, "path": "/README.md", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "![Lore](https://github.com/reymond-group/lore/blob/master/logo.png?raw=true)\n\nIf you use this code or application, please cite the original paper published by Bioinformatics: [10.1093/bioinformatics/btx760](http://dx.doi.org/10.1093/bioinformatics/btx760)\n\n# Lore\nCurrent Version: 1.1.20 ([Godzilla](https://youtu.be/RTzb-sduiWc))\n\n### Teasers\n<table style=\"width=100%\">\n <tbody>\n <tr>\n <td><img src=\"http://doc.gdb.tools/fun/img/lore_faerun_small.gif\"></img></td>\n <td><img src=\"http://doc.gdb.tools/fun/img/lore_faerun2_small.gif\"></img></td>\n <td><img src=\"http://doc.gdb.tools/fun/img/lore_flybrain_small.gif\"></img></td>\n <td><img src=\"http://doc.gdb.tools/fun/img/lore_larva_small.gif\"></img></td>\n </tr>\n </tbody>\n</table>\n\nBrowsing the SureChEMBL database (containing > 12 million datapoints): [Faerun](http://faerun.gdb.tools).\n\n### Example\nA basic [fiddle](https://jsfiddle.net/bmkxpg7g/2/)\n**See the examples folder for more details.**\n\n\n### Installation\nYou can either download or clone this repository and use the JavaScript file in the dist folder, or you can use yarn to install the package lore-engine:\n```bash\nyarn add lore-engine\n```\n\n### Building Lore\nIf you decide not to use the ready-to-go scripts in `dist`, you can (edit and) build the project by running:\n```bash\nnpm install\ngulp\n```\n\n### Getting Started\nA simple example can be found in the `example` folder. The [example data file](https://github.com/reymond-group/lore/blob/master/example/v5_s10544-17fe05-03.pce) was downloaded from the [website](http://bdtnp.lbl.gov/Fly-Net/) of the Berkeley Drosophila Transcription Network Project. It is a very small data set (N=6000) chosen because of the small file size (larger files can not be hosted on github).\n\n### Options\n#### Renderer\n| Option | Identifier | Data Type | Default Value |\n|---|---|---|---|\n| Antialiasing | antialiasing | boolean | true |\n| Verbose Mode | verbose | boolean | false |\n| The HTML element where FPS info is displayed | fpsElement | HTMLElement | document.getElementById('fps') |\n| The canvas background color | clearColor | Lore.Color | Lore.Color.fromHex('#000000') |\n| The distance of the camera to the center | radius | number | 500 |\n| Clear Depth | clearDepth | number | 1.0 |\n| Center (LookAt) | center | Lore.Vector3f | new Lore.Vector3f() |\n| Enable depth test | enableDepthTest | boolean | true |\n| Enable alpha blending | alphaBlending | boolean | false |\n\n#### CoordinatesHelper\nThe options for the coordinate helper are self-explanatory:\n```javascript\n{\n position: new Lore.Vector3f(),\n axis: {\n x: {\n length: 50.0,\n color: Lore.Color.fromHex('#222222')\n },\n y: {\n length: 50.0,\n color: Lore.Color.fromHex('#222222')\n },\n z: {\n length: 50.0,\n color: Lore.Color.fromHex('#222222')\n }\n },\n ticks: {\n enabled: true,\n x: {\n count: 10,\n length: 5.0,\n offset: new Lore.Vector3f(),\n color: Lore.Color.fromHex('#1f1f1f')\n },\n y: {\n count: 10,\n length: 5.0,\n offset: new Lore.Vector3f(),\n color: Lore.Color.fromHex('#1f1f1f')\n },\n z: {\n count: 10,\n length: 5.0,\n offset: new Lore.Vector3f(),\n color: Lore.Color.fromHex('#1f1f1f')\n }\n },\n box: {\n enabled: true,\n x: {\n color: Lore.Color.fromHex('#222222')\n },\n y: {\n color: Lore.Color.fromHex('#222222')\n },\n z: {\n color: Lore.Color.fromHex('#222222')\n }\n },\n}\n```\n\n#### OctreeHelper\n| Option | Identifier | Data Type | Default Value |\n|---|---|---|---|\n| Visualize the octree (for debug purposes) | visualize | boolean or string | false, 'centers', 'cubes' |\n| Enable multiselect | multiSelect | boolean | true |\n\n#### PointHelper\n| Option | Identifier | Data Type | Default Value |\n|---|---|---|---|\n| Create an octree when setting positions | octree | boolean | true |\n| The maximum number of vertices in a octree node | octreeThreshold | number | 500 |\n| The maximum depth of the octree | octreeMaxDepth | number | 8 |\n| Point size scaling | pointScale | number | 1.0 |\n| The maximum point size | maxPointSize | number | 100.0 |\n\n### [Documentation](/doc/all.md)\nThe documentation can be found in the docs folder. A markdown version is available [here](/doc/all.md)\n\n### Contributions & Thanks\n![BrowserStack Logo](https://d98b8t1nnulk5.cloudfront.net/production/images/layout/logo-header.png?1469004780)\n\nBig thanks to [Browserstack](https://www.browserstack.com/) for providing us with their excellent App and Browser Testing service. This allows us to test our library quickly on a wide range of browsers and operating systems.\n" }, { "alpha_fraction": 0.59608393907547, "alphanum_fraction": 0.6086713075637817, "avg_line_length": 38.733333587646484, "blob_id": "49ff8ed63760d823ccc303fe30d66d9f35cb62e8", "content_id": "b5dd6714283715b7737bc44d8431c79da7b76e5b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3575, "license_type": "permissive", "max_line_length": 208, "num_lines": 90, "path": "/src/Core/Uniform.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\n/**\n * A class representing a uniform.\n * \n * @property {String} name The name of this uniform. Also the variable name in the shader.\n * @property {Number|number[]|Float32Array} value The value of this uniform.\n * @property {String} type The type of this uniform. Available types: int, int_vec2, int_vec3, int_vec4, int_array, float, float_vec2, float_vec3, float_vec4, float_array, float_mat2, float_mat3, float_mat4.\n * @property {Boolean} stale A boolean indicating whether or not this uniform is stale and needs to be updated.\n */\nclass Uniform {\n /**\n * Creates an instance of Uniform.\n * @param {String} name The name of this uniform. Also the variable name in the shader.\n * @param {Number|number[]|Float32Array} value The value of this uniform.\n * @param {String} type The type of this uniform. Available types: int, int_vec2, int_vec3, int_vec4, int_array, float, float_vec2, float_vec3, float_vec4, float_array, float_mat2, float_mat3, float_mat4.\n */\n constructor(name, value, type) {\n this.name = name;\n this.value = value;\n this.type = type;\n this.stale = true;\n }\n\n /**\n * Create and return a new instance of this uniform.\n * \n * @returns {Uniform} A clone of this uniform.\n */\n clone() {\n return new Uniform(this.name, this.value, this.type);\n }\n\n /**\n * Set the value of this uniform.\n * \n * @param {Number} value A number which is valid for the specified type.\n */\n setValue(value) {\n this.value = value;\n this.stale = true;\n }\n\n /**\n * Pushes the uniform to the GPU.\n * \n * @param {WebGLRenderingContext} gl A WebGL rendering context.\n * @param {WebGLUniformLocation} program \n * @param {Uniform} uniform \n */\n static Set(gl, program, uniform) {\n let location = gl.getUniformLocation(program, uniform.name);\n\n if (uniform.type === 'int') {\n gl.uniform1i(location, uniform.value);\n } else if (uniform.type === 'int_vec2') {\n gl.uniform2iv(location, uniform.value);\n } else if (uniform.type === 'int_vec3') {\n gl.uniform3iv(location, uniform.value);\n } else if (uniform.type === 'int_vec4') {\n gl.uniform4iv(location, uniform.value);\n } else if (uniform.type === 'int_array') {\n gl.uniform1iv(location, uniform.value);\n } else if (uniform.type === 'float') {\n gl.uniform1f(location, uniform.value);\n } else if (uniform.type === 'float_vec2') {\n gl.uniform2fv(location, uniform.value);\n } else if (uniform.type === 'float_vec3') {\n gl.uniform3fv(location, uniform.value);\n } else if (uniform.type === 'float_vec4') {\n gl.uniform4fv(location, uniform.value);\n } else if (uniform.type === 'float_array') {\n gl.uniform1fv(location, uniform.value);\n } else if (uniform.type === 'float_mat2') {\n // false, see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/uniformMatrix\n gl.uniformMatrix2fv(location, false, uniform.value);\n } else if (uniform.type === 'float_mat3') {\n gl.uniformMatrix3fv(location, false, uniform.value);\n } else if (uniform.type === 'float_mat4') {\n gl.uniformMatrix4fv(location, false, uniform.value);\n }\n\n // TODO: Add SAMPLER_2D and SAMPLER_CUBE\n\n // Had to set this to true because point sizes did not update...\n uniform.stale = true;\n }\n}\n\nmodule.exports = Uniform" }, { "alpha_fraction": 0.6289398074150085, "alphanum_fraction": 0.6332378387451172, "avg_line_length": 27.69862937927246, "blob_id": "8bfb4962d66ab0200dab9dfe4bd1c861c28dd0c6", "content_id": "61f21760c22673ed001300f6707d2bf15615b493", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2094, "license_type": "permissive", "max_line_length": 161, "num_lines": 73, "path": "/src/Filters/FilterBase.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst Geometry = require('../Core/Geometry');\n\n/** \n * An abstract class representing the base for filter implementations. \n * \n * @property {string} type The type name of this object (Lore.FilterBase).\n * @property {Geometry} geometry The Geometry associated with this filter.\n * @property {string} attribute The name of the attribute to filter on.\n * @property {number} attributeIndex The attribute-index to filter on.\n * @property {boolean} active Whether or not the filter is active.\n */\nclass FilterBase {\n\n /**\n * Creates an instance of FilterBase.\n * @param {string} attribute The name of the attribute to filter on.\n * @param {number} attributeIndex The attribute-index to filter on.\n */\n constructor(attribute, attributeIndex) {\n this.type = 'Lore.FilterBase';\n this.geometry = null;\n this.attribute = attribute;\n this.attributeIndex = attributeIndex;\n this.active = false;\n }\n\n /**\n * Returns the geometry associated with this filter.\n * \n * @returns {Geometry} The geometry associated with this filter.\n */\n getGeometry() {\n return this.geometry;\n }\n\n /**\n * Sets the geometry associated with this filter.\n * \n * @param {Geometry} value The geometry to be associated with this filter.\n */\n setGeometry(value) {\n this.geometry = value;\n }\n\n /**\n * Abstract method. \n */\n filter() {\n\n }\n\n /**\n * Abstract method. \n */\n reset() {\n \n }\n\n /**\n * Check whether or not a vertex with a given index is visible. A vertex is visible when its color attribute is > 0.0 at attribute-index 2 (the size in HSS).\n *\n * @param {Geometry} geometry A Lore.Geometry with a color attribute.\n * @param {number} index A vertex index.\n * @returns {boolean} A boolean indicating whether or not the vertex specified by index is visible (HSS size > 0.0).\n */\n static isVisible(geometry, index) {\n return geometry.attributes['color'].data[index * 3 + 2] > 0.0;\n }\n}\n\nmodule.exports = FilterBase" }, { "alpha_fraction": 0.47993311285972595, "alphanum_fraction": 0.49101170897483826, "avg_line_length": 33.17856979370117, "blob_id": "c8c1f70682e94780dc14af3ed0b0ef4dc15ada18", "content_id": "660717e156bb3b2b84eb56cd643b955841b4677f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4784, "license_type": "permissive", "max_line_length": 141, "num_lines": 140, "path": "/src/IO/CsvFileReader.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "//@ts-check\n\nconst FileReaderBase = require('./FileReaderBase');\nconst Utils = require('../Utils/Utils');\n\n/** A class representing a CSV file reader. */\nclass CsvFileReader extends FileReaderBase {\n /**\n * Creates an instance of CsvFileReader.\n * @param {String} source The source of the file. This is either a input element (type=file) or a URL. If it is a URL, set local to true.\n * @param {any} options Options. See documentation for details.\n * @param {boolean} [local=true] A boolean indicating whether or not the source is local (a file input) or remote (a url).\n */\n constructor(source, options, local = true) {\n super(source, local);\n\n this.defaults = {\n separator: ',',\n cols: [],\n types: [],\n header: true\n }\n\n this.opts = Utils.extend(true, this.defaults, options);\n this.columns = {};\n this.headers = [];\n this.types = this.opts.types;\n this.cols = this.opts.cols;\n }\n\n /**\n * Called when the data is loaded, will raise the \"loaded\" event.\n * \n * @param {any} data The data loaded from the file or url.\n * @returns {CsvFileReader} Itself.\n */\n loaded(data) {\n data = data.replace('\\n\\n', '\\n');\n data = data.replace(/^\\s+|\\s+$/g, '');\n\n let lines = data.split('\\n');\n let length = lines.length;\n let init = true;\n let h = this.opts.header ? 1 : 0;\n\n if (this.cols.length !== 0) {\n if (this.types.length !== this.cols.length) {\n throw 'Types and cols must have the same number of elements.'\n }\n } else {\n if (this.types.length !== this.cols.length || this.types.length + this.cols.length === 0) {\n let values = lines[h].split(this.opts.separator);\n \n this.types = [];\n for (let i = 0; i < values.length; i++) {\n if(Utils.isFloat(parseFloat(values[i], 10))) {\n this.types.push('Float32Array');\n } else if (Utils.isInt(parseFloat(values[i], 10))) {\n this.types.push('Int32Array');\n } else {\n this.types.push('StringArray');\n }\n }\n }\n }\n\n if (this.cols.length === 0) {\n let values = lines[0].split(this.opts.separator);\n \n for (let i = 0; i < values.length; i++) {\n this.cols.push(i);\n }\n }\n\n if (h) {\n let headerNames = lines[0].split(this.opts.separator);\n\n for (let i = 0; i < this.cols.length; i++) {\n this.headers[i] = headerNames[this.cols[i]].trim();\n }\n } else {\n for (let i = 0; i < this.cols.length; i++) {\n this.headers[i] = i;\n }\n }\n \n for (let i = h; i < length; i++) {\n let values = lines[i].split(this.opts.separator);\n\n if (this.cols.length == 0)\n for (let j = 0; j < values.length; j++) {\n this.cols.push[j];\n }\n\n if (init) {\n for (let j = 0; j < this.cols.length; j++) {\n this._createArray(this.headers[j], this.types[j], length - h);\n }\n\n init = false;\n }\n\n for (let j = 0; j < this.cols.length; j++) {\n this.columns[this.headers[j]][i - h] = values[this.cols[j]];\n }\n }\n\n this.raiseEvent('loaded', this.columns);\n \n return this;\n }\n\n _createArray(index, type, length) {\n if (type == 'Int8Array') {\n this.columns[index] = new Int8Array(length);\n } else if (type == 'Uint8Array') {\n this.columns[index] = new Uint8Array(length);\n } else if (type == 'Uint8ClampedArray') {\n this.columns[index] = new Uint8ClampedArray(length);\n } else if (type == 'Int16Array') {\n this.columns[index] = new Int16Array(length);\n } else if (type == 'Uint16Array') {\n this.columns[index] = new Uint16Array(length);\n } else if (type == 'Int32Array') {\n this.columns[index] = new Int32Array(length);\n } else if (type == 'Uint32Array') {\n this.columns[index] = new Uint32Array(length);\n } else if (type == 'Float32Array') {\n this.columns[index] = new Float32Array(length);\n } else if (type == 'Float64Array') {\n this.columns[index] = new Float64Array(length);\n } else {\n this.columns[index] = new Array(length);\n }\n\n return this;\n }\n}\n\nmodule.exports = CsvFileReader" }, { "alpha_fraction": 0.4228571355342865, "alphanum_fraction": 0.47224488854408264, "avg_line_length": 42.75, "blob_id": "edb020dff021d7fd223b893caacfafd05fe7f29e", "content_id": "15ba768f68aae7a657950ce171a25a032e66c198", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2450, "license_type": "permissive", "max_line_length": 126, "num_lines": 56, "path": "/src/Shaders/DefaultAnimated.js", "repo_name": "reymond-group/lore", "src_encoding": "UTF-8", "text": "const Shader = require('../Core/Shader')\nconst Uniform = require('../Core/Uniform')\n\nmodule.exports = new Shader('defaultAnimated', 1, { size: new Uniform('size', 5.0, 'float'),\n cutoff: new Uniform('cutoff', 0.0, 'float'),\n time: new Uniform('time', 0.0, 'float'),\n clearColor: new Uniform('clearColor', [0.0, 0.0, 0.0, 1.0], 'float_vec4'),\n fogDensity: new Uniform('fogDensity', 6.0, 'float') }, [\n 'uniform float size;',\n 'uniform float cutoff;',\n 'uniform float time;',\n 'attribute vec3 position;',\n 'attribute vec3 color;',\n 'varying vec3 vColor;',\n 'varying float vDiscard;',\n 'vec3 rgb2hsv(vec3 c) {',\n 'vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);',\n 'vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));',\n 'vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));',\n\n 'float d = q.x - min(q.w, q.y);',\n 'float e = 1.0e-10;',\n 'return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);',\n '}',\n 'vec3 hsv2rgb(vec3 c) {',\n 'vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);',\n 'vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);',\n 'return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);',\n '}',\n 'void main() {',\n 'vec3 hsv = vec3(color.r, color.g, 1.0);',\n 'float saturation = color.g;',\n 'float point_size = color.b;',\n 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',\n 'vec4 mv_pos = modelViewMatrix * vec4(position, 1.0);',\n 'vDiscard = 0.0;',\n 'if(-mv_pos.z < cutoff || point_size <= 0.0) {',\n 'vDiscard = 1.0;',\n 'return;',\n '}',\n 'gl_PointSize = size;',\n 'hsv.g *= max(0.15, abs(sin(time * 0.002)));',\n 'vColor = hsv2rgb(hsv);',\n '}'\n], [\n 'uniform vec4 clearColor;',\n 'uniform float fogDensity;',\n 'varying vec3 vColor;',\n 'varying float vDiscard;',\n 'void main() {',\n 'if(vDiscard > 0.5) discard;',\n 'float z = gl_FragCoord.z / gl_FragCoord.w;',\n 'float fog_factor = clamp(exp2(-fogDensity * fogDensity * z * z * 1.442695), 0.025, 1.0);',\n 'gl_FragColor = mix(clearColor, vec4(vColor, 1.0), fog_factor);',\n '}'\n]);\n" } ]
52
RenanAlmeidaSilva/Alarme-828D
https://github.com/RenanAlmeidaSilva/Alarme-828D
b05e54bd1167078ac1861f3223f240c51acefc56
4f00f8f88dfc9a7724fd066ca74b65c6209dbfa4
88a2b6f0d8040fb67a98c9526269ee3114deb5f2
refs/heads/main
2023-07-20T02:04:45.465112
2021-08-18T11:18:41
2021-08-18T11:18:41
383,153,721
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5424180030822754, "alphanum_fraction": 0.5461065769195557, "avg_line_length": 42.3636360168457, "blob_id": "a71e53dd73180f143657d49356d5232bcd9048b6", "content_id": "7d0af01f35189121e756a4a9bf0c02a3dd5e07a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4933, "license_type": "permissive", "max_line_length": 162, "num_lines": 110, "path": "/BOT.py", "repo_name": "RenanAlmeidaSilva/Alarme-828D", "src_encoding": "UTF-8", "text": "import logging\r\nimport json\r\n\r\nfrom aiogram import Bot, Dispatcher, executor, types\r\n\r\nAPI_TOKEN = '1844881714:AAHUgvk1ZLPx7jIXb_1ktoTEpBS3VccvaE4'\r\n\r\n# Configure logging\r\nlogging.basicConfig(level=logging.DEBUG)\r\n\r\n# Initialize bot and dispatcher\r\nbot = Bot(token=API_TOKEN)\r\ndp = Dispatcher(bot)\r\nwith open('alarmes.json', 'r') as f:\r\n alarmes = json.load(f)\r\n\r\n\r\[email protected]_handler(commands=['info'])\r\nasync def send_welcome(message: types.Message):\r\n await message.reply(\"Hi! I'm Alarmes828DBot!\\nPowered by: \\nDev. Laura Sorato. (Estagiário Developer) \\nDev. Renan Almeida. (Estagiário Developer)\\n\")\r\n\r\n\r\[email protected]_handler(commands=['start'])\r\nasync def send_welcome(message: types.Message):\r\n with open('user.txt') as file:\r\n userList = file.read()\r\n user = userList.split('\\n')\r\n textomsg1 = ''\r\n if message['chat']['username']:\r\n textomsg1 += message[\"chat\"][\"username\"]\r\n with open('logs.log', 'a') as arquivo:\r\n arquivo.write('\\n' + message[\"chat\"][\"username\"] + '\\n\\n')\r\n if textomsg1 in user:\r\n await message.answer('Olá ' + message['chat'][\r\n 'first_name'] + ', eu sou o Bot para o alarme 828D, criado para encontrar as informações do seu erro.\\n'\r\n 'Você deve me fornecer um valor para pesquisa.')\r\n else:\r\n await message.answer(\"Olá, eu sou o Bot para o alarme 828D, criado para encontrar as informações do seu erro.\\n\"\r\n \"No momento você não possui permissão para acessar as informações internas.\\n\"\r\n \"Entre em contato com os desenvolvedores.\\n\"\r\n \"Para mais informações dos meu criadores digite '/info'\")\r\n else:\r\n await message.answer('Olá ' + message['chat'][\r\n 'first_name'] + ', no momento não encontrei seu username. Você deve verifica-lo nas configurações do Telegram.')\r\n\r\n\r\[email protected]_handler()\r\nasync def echo(message: types.Message):\r\n\r\n segundos = message['date']\r\n with open('logs.log', 'a') as arquivo:\r\n arquivo.write(segundos.__str__())\r\n\r\n with open('user.txt') as file:\r\n userList = file.read()\r\n #print(userList)\r\n\r\n user = userList.split('\\n')\r\n #print(user)\r\n textomsg = ''\r\n if message[\"chat\"][\"username\"]:\r\n textomsg += message[\"chat\"][\"username\"]\r\n with open('logs.log', 'a') as arquivo:\r\n arquivo.write('\\n'+message[\"chat\"][\"username\"]+'\\n\\n')\r\n else:\r\n await message.answer(\"Você não possui um Username. Logo, deverá ir em suas configurações e nomea-lo.\")\r\n\r\n if textomsg in user:\r\n entradas = ['oi', 'olá', 'ola', 'oie', 'roi', 'hey', 'eai', 'eae', 'salve', 'hello', 'ei', 'hi', 'oii', 'oiee']\r\n alarmes\r\n txt = ''\r\n for alarme in alarmes:\r\n if alarme['numero'] == message.text:\r\n if alarme['titulo']:\r\n txt += f'TÍTULO: {alarme[\"titulo\"]}\\n'\r\n if alarme['definicoes']:\r\n txt += f'\\nDEFINIÇÕES:\\n{alarme[\"definicoes\"]}\\n'\r\n if alarme['reacoes']:\r\n txt += f'\\nREAÇÕES:\\n{alarme[\"reacoes\"]}\\n'\r\n if alarme['correcoes']:\r\n txt += f'CORREÇÕES:\\n{alarme[\"correcoes\"]}\\n'\r\n if alarme['programa']:\r\n txt += f'CONTINUAÇÃO DO PROGRAMA:{alarme[\"programa\"]}\\n'\r\n if alarme['parametro']:\r\n txt += f'PARÂMETRO:\\n{alarme[\"parametro\"]}\\n'\r\n if alarme['valormsg']:\r\n txt += f'VALOR DE MENSAGEM:\\n{alarme[\"valormsg\"]}\\n'\r\n if alarme['objeto']:\r\n txt += f'OBJETO:\\n{alarme[\"objeto\"]}\\n'\r\n if alarme['reconhecimento']:\r\n txt += f'RECONHECIMENTO:\\n{alarme[\"reconhecimento\"]}\\n'\r\n if alarme['causa']:\r\n txt += f'CAUSA:\\n{alarme[\"causa\"]}\\n'\r\n if txt != '':\r\n await message.answer(txt)\r\n elif message.text.lower() in (entradas):\r\n await message.answer('Olá ' + message['chat']['first_name'] + ', eu sou o Bot para o alarme 828D, criado para encontrar as informações do seu erro.\\n'\r\n 'Você deve me fornecer um valor para pesquisa.')\r\n else:\r\n erro = \"Você deve fornecer um valor válido.\"\r\n await message.answer(erro)\r\n else:\r\n await message.answer(\"Olá, eu sou o Bot para o alarme 828D, criado para encontrar as informações do seu erro.\\n\"\r\n \"No momento você não possui permissão para acessar as informações internas.\\n\"\r\n \"Entre em contato com os desenvolvedores.\\n\"\r\n \"Para mais informações dos meu criadores digite '/info'\")\r\n\r\n\r\nif __name__ == '__main__':\r\n executor.start_polling(dp, skip_updates=True)\r\n" }, { "alpha_fraction": 0.5267289876937866, "alphanum_fraction": 0.5442990660667419, "avg_line_length": 37.955223083496094, "blob_id": "51171f0f7009332feaf82b0cd5fcf0f4a2112ceb", "content_id": "fcfe0e184210c228dc71f5499564d43d05d34a0f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2682, "license_type": "permissive", "max_line_length": 93, "num_lines": 67, "path": "/teste.py", "repo_name": "RenanAlmeidaSilva/Alarme-828D", "src_encoding": "UTF-8", "text": "manual = ''\r\nwith open('manual.txt', 'rb') as m:\r\n manual = m.read().decode()\r\nfull = []\r\nalarmes = []\r\ntxt = ''\r\nmanualList = manual.split('\\n')\r\nfor linha in manualList:\r\n if linha not in ['Alarmes\\r', 'NCK-Alarme\\r']:\r\n if not linha.find('Manual de diagnóstico, 03/2013, 6FC5398-8BP40-3KA1') >= 0:\r\n if linha[:3].isdigit():\r\n if txt:\r\n full.append(txt)\r\n txt = ''\r\n\r\n txt += linha + '\\n'\r\nfor x in full:\r\n if x[:7].split()[0].isdigit():\r\n numero = x.split()[0]\r\n titulo = x.split('\\n')[0][x.split('\\n')[0].find(' '):]\r\n # print(numero, titulo)\r\n alarmes.append(dict(\r\n numero=numero,\r\n titulo=titulo\r\n ))\r\n\r\n\r\nprint([x for x in alarmes if x['numero'] == '2001'][0]['titulo'])\r\n\r\n''' for alarme in alarmes:\r\n if alarme['numero'] == message.text:\r\n saida = (f'Titulo = {alarme[\"titulo\"]}\\n'\r\n f'definicoes = {alarme[\"definicoes\"]}\\n'\r\n f'Titulo = {alarme[\"titulo\"]}\\n')\r\n \r\n if x.find('Reação:') >= 0:\r\n await message.answer(reacoes)\r\n\r\n if x.find('Definições:') >= 0:\r\n await message.answer(definicoes)\r\n else:\r\n definicoes = ''\r\n if x.find('Reação:') >= 0:\r\n await message.answer(reacoes)\r\n\r\n\r\n saida = [x for x in alarmes if x['numero'] == message.text][0]['titulo']\r\n saida2 = [x for x in alarmes if x['numero'] == message.text][0]['reconhecimento']\r\n saida3 = [x for x in alarmes if x['numero'] == message.text][0]['correcao']\r\n\r\n titulo = [x for x in alarmes if x['numero'] == message.text][0]['titulo']\r\n definicoes = [x for x in alarmes if x['numero'] == message.text][0]['definicoes']\r\n reacoes = [x for x in alarmes if x['numero'] == message.text][0]['reacoes']\r\n correcoes = [x for x in alarmes if x['numero'] == message.text][0]['correcoes']\r\n programa = [x for x in alarmes if x['numero'] == message.text][0]['programa']\r\n parametro = [x for x in alarmes if x['numero'] == message.text][0]['parametro']\r\n valormsg = [x for x in alarmes if x['numero'] == message.text][0]['valormsg']\r\n objeto = [x for x in alarmes if x['numero'] == message.text][0]['objeto']\r\n reconhecimento = [x for x in alarmes if x['numero'] == message.text][0]['reconhecimento']\r\n causa = [x for x in alarmes if x['numero'] == message.text][0]['causa']\r\n correcao = [x for x in alarmes if x['numero'] == message.text][0]['correcao']\r\n \r\n if txt != '':\r\n await message.answer(txt,parse_mode=types.ParseMode.HTML)\r\n \r\nwith open('alarmes.json', 'r') as f: alarmes = json.load(f)\r\n'''" } ]
2
Kirthivasun/Flask-API-Authentication
https://github.com/Kirthivasun/Flask-API-Authentication
da5ca5c8c118a70a239ab9e6e35a35d2e0658341
fd250dc9b95d89cc268a3dc56b365fb30227a529
e48cd7ed63d6147fd1ac4bc69a5320822685cc9a
refs/heads/master
2022-11-18T07:40:24.717749
2020-07-15T07:03:37
2020-07-15T07:03:37
279,781,970
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7174975275993347, "alphanum_fraction": 0.7174975275993347, "avg_line_length": 30.03125, "blob_id": "40214ade0f01f98e81e7fdfdda04b98e2b19b4c0", "content_id": "c3d1fef4f21d51b0a482c84e9b104bb4c421b31a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1023, "license_type": "no_license", "max_line_length": 94, "num_lines": 32, "path": "/api.py", "repo_name": "Kirthivasun/Flask-API-Authentication", "src_encoding": "UTF-8", "text": "import json\r\nfrom six.moves.urllib.request import urlopen\r\nfrom functools import wraps\r\nfrom flask import Flask, request, jsonify, _request_ctx_stack\r\nfrom flask_cors import cross_origin\r\nfrom Authorization import AuthError,requires_auth\r\n\r\napp = Flask(__name__)\r\n\r\[email protected](AuthError)\r\ndef handle_auth_error(ex):\r\n response = jsonify(ex.error)\r\n response.status_code = ex.status_code\r\n return response\r\n\r\n# This doesn't need authentication\r\[email protected](\"/api/public\")\r\n@cross_origin(headers=[\"Content-Type\", \"Authorization\"])\r\ndef public():\r\n response = \"Hello from a public endpoint! You don't need to be authenticated to see this.\"\r\n return jsonify(message=response)\r\n\r\n# This needs authentication\r\[email protected](\"/api/private\")\r\n@cross_origin(headers=[\"Content-Type\", \"Authorization\"])\r\n@requires_auth\r\ndef private():\r\n response = \"Hello from a private endpoint! You need to be authenticated to see this.\"\r\n return jsonify(message=response)\r\n\r\nif __name__=='__main__':\r\n app.run(debug=True)" }, { "alpha_fraction": 0.7799999713897705, "alphanum_fraction": 0.7799999713897705, "avg_line_length": 8.399999618530273, "blob_id": "19c02472f85b6d569f6c477d88fbf9f8ffd8f428", "content_id": "e4f9738faa2bd5492eb69ff06a79f9ba74e89195", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 50, "license_type": "no_license", "max_line_length": 13, "num_lines": 5, "path": "/requirement.txt", "repo_name": "Kirthivasun/Flask-API-Authentication", "src_encoding": "UTF-8", "text": "flask\r\npython-dotenv\r\npython-jose\r\nflask-cors\r\nsix" }, { "alpha_fraction": 0.8092485666275024, "alphanum_fraction": 0.8208092451095581, "avg_line_length": 42.25, "blob_id": "713b1701f034501736ed62651548245ac50a74b0", "content_id": "673113cdf95da5be02cd3178b9f35dbdacb7a59b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 173, "license_type": "no_license", "max_line_length": 103, "num_lines": 4, "path": "/README.md", "repo_name": "Kirthivasun/Flask-API-Authentication", "src_encoding": "UTF-8", "text": "# Flask-API-Authentication\nJWT token validation in python Flask API\n\nUpdate AUTH0_DOMAIN and API_AUDIENCE parameter to map it with your Auth0 tenant and run the application\n" } ]
3
JoseMMA88/SnakeGame
https://github.com/JoseMMA88/SnakeGame
dcdedb10850181c8505bfb5fe5f73febf7cc36f2
fbc732677da23b87c3a0a033ed820129a3bf62fe
d28c2542fd595a4d9d0e1cc11f551495cccc3e69
refs/heads/master
2023-01-30T02:37:49.761292
2020-12-16T10:58:36
2020-12-16T10:58:36
321,153,280
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.528363049030304, "alphanum_fraction": 0.5372771620750427, "avg_line_length": 25.276596069335938, "blob_id": "cd0c349d3bf06d1c6fa2c7dc3603644fa039ec0d", "content_id": "5f042ad879ea6294064fd81e658724941dfb8bcf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1234, "license_type": "no_license", "max_line_length": 99, "num_lines": 47, "path": "/score.py", "repo_name": "JoseMMA88/SnakeGame", "src_encoding": "UTF-8", "text": "from turtle import Turtle\n\n\nALIGMENT = \"center\"\nFONT = (\"Verdana\", 17, \"normal\")\n\n\nclass Score(Turtle):\n def __init__(self):\n super().__init__()\n with open(\"high_score.txt\") as file:\n h_score = int(file.read())\n\n self.score = 0\n self.high_score = h_score\n\n self.hideturtle()\n self.penup()\n self.color(\"white\")\n self.goto(0, 265)\n self.update_scoreboard()\n self.speed(\"fastest\")\n\n def update_scoreboard(self):\n self.clear()\n self.write(f\"Score: {self.score} High Score: {self.high_score}\", align=ALIGMENT, font=FONT)\n\n def up_score(self):\n self.score += 1\n self.update_scoreboard()\n\n def start(self):\n self.home()\n self.write(f\"PRESS 'SPACE' TO START\", align=ALIGMENT, font=FONT)\n\n def reset(self):\n if self.score > self.high_score:\n self.high_score = self.score\n\n with open(\"high_score.txt\") as file:\n h_score = int(file.read())\n if self.high_score > h_score:\n with open(\"high_score.txt\", \"w\") as file1:\n file1.write(f\"{self.high_score}\")\n\n self.score = 0\n self.update_scoreboard()" }, { "alpha_fraction": 0.6141732335090637, "alphanum_fraction": 0.6338582634925842, "avg_line_length": 21.74626922607422, "blob_id": "ab8e8b438398f8c680d2e05c8bce1634e8138b44", "content_id": "ad21ba33cf2eeb29589ee3e3f57af3a2cb4c4f06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1524, "license_type": "no_license", "max_line_length": 118, "num_lines": 67, "path": "/main.py", "repo_name": "JoseMMA88/SnakeGame", "src_encoding": "UTF-8", "text": "from turtle import Screen\nfrom snake import Snake\nfrom food import Food\nfrom score import Score\nimport time\n\n\n# Screen Setup\nscreen = Screen()\nscreen.setup(width=600, height=600)\nscreen.bgcolor(\"black\")\nscreen.title(\"SNAKE GAME\")\n# Turn off the tracer to prevent blinking\nscreen.tracer(0)\n\n\n# Snake Setup\nsnake = Snake()\n\n# Food Setup\nfood = Food()\n\n# Score Setup\nscore = Score()\n\n# Listen Keys\nscreen.listen()\nscreen.onkeypress(key=\"Up\", fun=snake.head_up)\nscreen.onkeypress(key=\"Down\", fun=snake.head_down)\nscreen.onkeypress(key=\"Left\", fun=snake.head_left)\nscreen.onkeypress(key=\"Right\", fun=snake.head_right)\n\n\ndef game():\n score.goto(0, 265)\n score.update_scoreboard()\n\n # GAME MAINLOOP\n is_game = True\n while is_game:\n # Refresh the screen to prevent blinking at moving the snake\n screen.update()\n time.sleep(0.1)\n snake.move()\n\n # Check collisions with food\n if snake.head.distance(food) < 15:\n food.generate_food()\n score.up_score()\n snake.grown()\n\n # Check collision with wall\n if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280:\n score.reset()\n snake.reset()\n\n # Check collision with snake own tail\n for body in snake.snake[1:]:\n if snake.head.distance(body) < 10:\n score.reset()\n snake.reset()\n\n\nscore.start()\nscreen.onkeypress(key=\"space\", fun=game)\n\nscreen.exitonclick()\n" }, { "alpha_fraction": 0.49076831340789795, "alphanum_fraction": 0.5193567872047424, "avg_line_length": 26.491804122924805, "blob_id": "634fe1125742105b27885813200067ccb6e10e8f", "content_id": "038a2d7b1c443915056e929fb0faca87d2ecc9c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1679, "license_type": "no_license", "max_line_length": 86, "num_lines": 61, "path": "/snake.py", "repo_name": "JoseMMA88/SnakeGame", "src_encoding": "UTF-8", "text": "from turtle import Turtle\n\nclass Snake:\n def __init__(self):\n self.snake = []\n self.body_count = 3\n self.position = {\"x\": 0, \"y\": 0}\n self.create_snake()\n self.head = self.snake[0]\n\n def create_snake(self):\n # Snake Setup\n for i in range(self.body_count):\n self.add_body(self.position)\n\n def reset(self):\n for body in self.snake:\n body.goto(2000, 2000)\n\n self.snake.clear()\n self.body_count = 3\n self.position = {\"x\": 0, \"y\": 0}\n self.create_snake()\n self.head = self.snake[0]\n\n def add_body(self, position):\n body = Turtle(\"square\")\n body.penup()\n body.color(\"white\")\n body.goto(position[\"x\"], position[\"y\"])\n self.position[\"x\"] -= 20\n self.position[\"y\"] = position[\"y\"]\n self.snake.append(body)\n\n def grown(self):\n self.body_count += 1\n position = {\"x\": self.snake[-1].xcor(), \"y\": self.snake[-1].ycor()}\n self.add_body(position)\n\n def move(self):\n # Snake Movement\n for i in range(len(self.snake) - 1, 0, -1):\n if i - 1 >= 0:\n self.snake[i].goto(self.snake[i - 1].xcor(), self.snake[i - 1].ycor())\n self.head.forward(20)\n\n def head_up(self):\n if self.head.heading() != 270:\n self.head.setheading(90)\n\n def head_down(self):\n if self.head.heading() != 90:\n self.head.setheading(270)\n\n def head_left(self):\n if self.head.heading() != 0:\n self.head.setheading(180)\n\n def head_right(self):\n if self.head.heading() != 180:\n self.head.setheading(0)\n\n\n" } ]
3
NarendraBabuOggu/Data-Science-Portfolio
https://github.com/NarendraBabuOggu/Data-Science-Portfolio
5c4b73958a08468c49597d7c6f785d1965caff39
33e53e928ceb2744ed5f23efa9cd5857858e3f89
6e262d80e7863e37ddaa0543080e55b94fb62b7a
refs/heads/master
2022-12-08T07:34:20.274409
2020-08-23T07:34:52
2020-08-23T07:34:52
281,441,236
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.8028169274330139, "alphanum_fraction": 0.8169013857841492, "avg_line_length": 34.5, "blob_id": "b33fcdde386e91aed1e3b3d86462deded90d8b52", "content_id": "ef35cb81cf91adf87354f06cb4cf00ad99de0be7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 71, "license_type": "no_license", "max_line_length": 42, "num_lines": 2, "path": "/Machine Learning/ASHRAE Energy Prediction/README.md", "repo_name": "NarendraBabuOggu/Data-Science-Portfolio", "src_encoding": "UTF-8", "text": "# Ashrae-Energy-Predictor-3\nAshrae Energy Predictor Challenge (Kaggle)\n" }, { "alpha_fraction": 0.5813565254211426, "alphanum_fraction": 0.5900434255599976, "avg_line_length": 40.55555725097656, "blob_id": "2e2c9e849f982d13efc58460e1f6b6e12044cc89", "content_id": "87ef2ff47d1b289d2f22d0eb26b784853f2cc678", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2993, "license_type": "no_license", "max_line_length": 130, "num_lines": 72, "path": "/Web Scraping/Naukri Job Search Selenium/main.py", "repo_name": "NarendraBabuOggu/Data-Science-Portfolio", "src_encoding": "UTF-8", "text": "import os\nimport time\nfrom selenium import webdriver\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndriver = webdriver.Chrome(r\"D:/chromedriver.exe\")\n\"\"\"\njobs = {\n \"roles\" : ['Data Scientist', 'Data Engineer', 'ETL Developer', 'Machine Learning Engineer', 'AI Engineer', 'Spark Developer'],\n \"title_contains\" : [\n 'Data Science', 'ETL', 'Machine Learning', 'ML', 'Deep Learning', 'DL', 'AI', 'Artificial Intelligence', \n 'Data Hub', 'DataHub', 'InfoCenter', 'Info Center', 'DH&IC', 'DH-IC'\n ],\n \"locations\" : [],\n \"experience\" : [],\n \"skills\" : [\n 'Python', 'Spark', 'PySpark', 'Informatica', 'SAP BODS', 'SAP Data Services', 'Tensorflow', \n 'Tensor Flow', 'PyTorch', 'Py Torch', 'GCP', 'Google Cloud Platform', 'Amazon Web Services', \n 'AWS', 'Data Science'\n ]\n}\n\"\"\"\n\nsearch_skills = [\n 'Python', 'Spark', 'PySpark', 'Informatica', 'SAP BODS', 'SAP Data Services', 'Tensorflow', \n 'Tensor Flow', 'PyTorch', 'Py Torch', 'GCP', 'Google Cloud Platform', 'Amazon Web Services', \n 'AWS', 'Data Science'\n]\n\nfor skill in search_skills : \n driver.get(\"https://www.naukri.com/top-skill-jobs\")\n time.sleep(5)\n inp = driver.find_element_by_class_name('sugInp')\n inp.send_keys('Data Scientist')\n loc = driver.find_element_by_class_name('sugInp.w135')\n search = driver.find_element_by_class_name('qsbSrch.blueBtn')\n search.click()\n time.sleep(5)\n details = []\n curr_page = 0\n while True : \n pages = driver.find_element_by_class_name('fleft.pages')\n pages = pages.find_elements_by_tag_name('a')\n total_pages = len(pages)\n if curr_page >= total_pages : \n break\n page = pages[curr_page]\n href = page.get_attribute('href')\n driver.get(href)\n time.sleep(5)\n lst = driver.find_elements_by_class_name('jobTuple.bgWhite.br4.mb-8')\n #print(len(lst))\n for item in lst : \n title = item.find_element_by_class_name('title.fw500.ellipsis').text\n company = item.find_element_by_class_name('subTitle.ellipsis.fleft').text\n try : \n rating = item.find_element_by_class_name('starRating.fleft.dot').text\n except : \n rating = 'N/A'\n exp_n_sal = item.find_elements_by_class_name('ellipsis.fleft.fs12.lh16')\n desc = item.find_element_by_class_name('fleft.icon-16.lh16.mr-4.naukicon.naukicon-desc').text\n skills = item.find_elements_by_class_name('fleft.fs12.grey-text.lh16.dot')\n #print(title, company, rating,[i.text for i in exp_n_sal], desc, [i.text for i in skills], sep = '\\n')\n details.append([title, company, rating,[i.text for i in exp_n_sal], desc, [i.text for i in skills]])\n #print('\\n')\n\n curr_page += 1\n\n details_df = pd.DataFrame(details)\n #print(details_df.head())\n details_df.to_csv(f\"{skill}.csv\", index = False)\n\n" }, { "alpha_fraction": 0.7673745155334473, "alphanum_fraction": 0.7770270109176636, "avg_line_length": 38.88461685180664, "blob_id": "79a1b8067a24e13f2f889ac80ab9a773d3cc84fd", "content_id": "807700e94ac16ad9126aa2d810224e3f4132fd4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1036, "license_type": "no_license", "max_line_length": 147, "num_lines": 26, "path": "/Deep Learning/Intel Image Classifier/README.md", "repo_name": "NarendraBabuOggu/Data-Science-Portfolio", "src_encoding": "UTF-8", "text": "# Starter for deploying [fast.ai](https://www.fast.ai) models on [Google App Engine](https://cloud.google.com/appengine)\nThis repo can be used as a starting point to deploy Fast.AI or Pytorch Models on Google App Engine.\n\nThis is based on the deployment tutorial by FastAI at https://course.fast.ai/deployment_google_app_engine.html # Test it out with bear images!\n\nYou can test your changes locally by installing Docker and using the following command:\n\n```\ndocker build -t fastai-v3 . && docker run --rm -it -p 5000:5000 fastai-v3\n```\n\nor By creating a Virtual Environment with the requirements and test with following Command\n\n\"\"\"\npython app/server.py server\n\n\"\"\"\n\nThe notebook Explains the training of the Classifier model on Intel Image Dataset.\n\n\nTo use this repo to deploy your custom model Please update the following\n\nRequirements.txt - to include your custom model requirements\n\nInside app/server.py - update classes to your custom model classes and classifier path to ur custom model's google drive path(direct download link)" }, { "alpha_fraction": 0.837837815284729, "alphanum_fraction": 0.837837815284729, "avg_line_length": 36, "blob_id": "7b887523046fee0a04c34b76d5f73f3995002da2", "content_id": "ef02a25af851b186ff3485b522e670bc4fa37355", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 74, "license_type": "no_license", "max_line_length": 48, "num_lines": 2, "path": "/Deep Learning/README.md", "repo_name": "NarendraBabuOggu/Data-Science-Portfolio", "src_encoding": "UTF-8", "text": "# Data-Science-Portfolio\nIt contains the practiced Deep Learning projects\n" }, { "alpha_fraction": 0.8441558480262756, "alphanum_fraction": 0.8441558480262756, "avg_line_length": 37.5, "blob_id": "2302069d31bb9948a2de5ef44b7d7674b1bc2f54", "content_id": "8d89710afce03553e160576d4dfac2e6064d0c4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 77, "license_type": "no_license", "max_line_length": 51, "num_lines": 2, "path": "/Machine Learning/README.md", "repo_name": "NarendraBabuOggu/Data-Science-Portfolio", "src_encoding": "UTF-8", "text": "# Data-Science-Portfolio\nIt contains the practiced Machine Learning Projects\n" }, { "alpha_fraction": 0.8380952477455139, "alphanum_fraction": 0.8380952477455139, "avg_line_length": 51.5, "blob_id": "d51bcf23ac60c308c31bedb0ffc3ae210b438d9d", "content_id": "3d67a3644ae9044153da571a111deac485669218", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 105, "license_type": "no_license", "max_line_length": 79, "num_lines": 2, "path": "/README.md", "repo_name": "NarendraBabuOggu/Data-Science-Portfolio", "src_encoding": "UTF-8", "text": "# Data-Science-Portfolio\nIt contains the practiced data science/ML/DL projects and Hackathon Submissions\n" } ]
6
rmmanoj23/PythonCode
https://github.com/rmmanoj23/PythonCode
fb106a798ad1e426ee707353d4465577bd4509e0
b6627925058c8bed4100fe5c75b24de0f7edc18b
5104ef369b027b87c5930a87664fad1ff2f2334e
refs/heads/master
2022-11-08T08:58:15.810029
2020-07-01T23:42:59
2020-07-01T23:42:59
276,501,821
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.600734293460846, "alphanum_fraction": 0.620009183883667, "avg_line_length": 22.67934799194336, "blob_id": "7da57db2cc346e1fc7535c5a5effe4d5f099bce4", "content_id": "9ac09ef4480a9e601707c83905b5c9485b1dbe9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4358, "license_type": "no_license", "max_line_length": 86, "num_lines": 184, "path": "/EightQueens_Solution.py", "repo_name": "rmmanoj23/PythonCode", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[45]:\n\n\ndef generate_randomdist():\n# randomly generates a sequence of board states.\n global nQueens\n init_distribution = np.arange(nQueens)\n np.random.shuffle(init_distribution)\n return init_distribution\n\ndef initial_Population(population_size = 100):\n global POPULATION\n\n POPULATION = population_size\n\n initial_population = [EightQueensPosition() for i in range(population_size)]\n for i in range(population_size):\n initial_population[i].setSequence(generate_randomdist())\n initial_population[i].setFitness(calc_fitness(initial_population[i].sequence))\n\n return initial_population\n \n\n\n# In[46]:\n\n\ndef calc_fitness(population = None):\n conflicts = 0;\n row_col_conflicts = abs(len(population) - len(np.unique(population)))\n conflicts += row_col_conflicts\n\n# calculate diagonal clashes\n for i in range(len(population)):\n for j in range(len(population)):\n if ( i != j):\n dx = abs(i-j)\n dy = abs(population[i] - population[j])\n if(dx == dy):\n conflicts += 1\n\n\n return 28 - conflicts\n\n\n# In[47]:\n\n\ndef crossover(parent1, parent2):\n globals()\n n = len(parent1.sequence)\n c = np.random.randint(n, size=1)\n child = QueenPosition()\n child.sequence = []\n child.sequence.extend(parent1.sequence[0:c])\n child.sequence.extend(parent2.sequence[c:])\n child.setFitness(calc_fitness(child.sequence))\n return child\n\n\ndef mutate(child):\n if child.survival < MUTATE:\n c = np.random.randint(8)\n child.sequence[c] = np.random.randint(8)\n return child\n\n\n# In[48]:\n\n\ndef select_Parent():\n globals()\n parent1, parent2 = None, None\n# parent is decided by random probability of survival.\n# since the fitness of each board position is an integer >0, \n# we need to normaliza the fitness in order to find the solution\n\n summation_fitness = np.sum([x.fitness for x in population])\n for each in population:\n each.survival = each.fitness/(summation_fitness*1.0)\n\n while True:\n parent1_random = np.random.rand()\n parent1_rn = [x for x in population if x.survival <= parent1_random]\n try:\n parent1 = parent1_rn[0]\n break\n except:\n pass\n\n while True:\n parent2_random = np.random.rand()\n parent2_rn = [x for x in population if x.survival <= parent2_random]\n try:\n t = np.random.randint(len(parent2_rn))\n parent2 = parent2_rn[t]\n if parent2 != parent1:\n break\n else:\n print(\"equal parents\")\n continue\n except:\n print(\"exception\")\n continue\n\n if parent1 is not None and parent2 is not None:\n return parent1, parent2\n else:\n sys.exit(-1)\n\n\n# In[49]:\n\n\ndef Genetic_Algo(iteration):\n globals()\n newpopulation = []\n for i in range(len(population)):\n parent1, parent2 = select_Parent()\n child = crossover(parent1, parent2)\n \n if(MUTATE_FLAG):\n child = mutate(child)\n newpopulation.append(child)\n return newpopulation\n\n\ndef stop():\n globals()\n fitnessvals = [pos.fitness for pos in population]\n if STOP_CTR in fitnessvals:\n return True\n if MAX_ITER == iteration:\n return True\n return False\n\n\n# In[50]:\n\n\nimport numpy as np\nimport sys\nnQueens = 8\nSTOP_CTR = 28\nMUTATE = 0.000001\nMUTATE_FLAG = True\nMAX_ITER = 100000\nPOPULATION = None\n\nclass EightQueensPosition:\n def __init__(self):\n self.sequence = None\n self.fitness = None\n self.survival = None\n def setSequence(self, val):\n self.sequence = val\n def setFitness(self, fitness):\n self.fitness = fitness\n def setSurvival(self, val):\n self.survival = val\n def getAttr(self):\n return {'sequence':sequence, 'fitness':fitness, 'survival':survival}\n\n\n# In[54]:\n\n\npopulation = initial_Population(1000)\n\nprint(\"POPULATION size : \", population)\n\niteration = 0;\nwhile not stop():\n# keep iteratin till you find the best position\n population = Genetic_Algo(iteration)\n iteration +=1 \n\nprint(\"Iteration number : \", iteration)\nfor each in population:\n if each.fitness == 28:\n print(\"Sequence is {0}\".format(each.sequence))\n\n" } ]
1
chachasikes/DataTrain
https://github.com/chachasikes/DataTrain
182e4e4f9b1dde01a892beb4738312c7599154c4
b15e253abcfebd984cfbc6decd18c18587f6d772
655dab6223435de65d2e0fbcddfcf0698d743480
refs/heads/master
2020-05-04T17:01:16.589315
2015-02-26T22:10:14
2015-02-26T22:10:14
28,458,904
5
0
null
null
null
null
null
[ { "alpha_fraction": 0.739130437374115, "alphanum_fraction": 0.748792290687561, "avg_line_length": 24.75, "blob_id": "14dee99eab58a7716ca1444236b6c6f74e40d84c", "content_id": "c1d811000bf985bf84d2610b31edf7728d56291f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 207, "license_type": "no_license", "max_line_length": 62, "num_lines": 8, "path": "/projects/existing_data_dictionaries/National Weather Service Data Dictionary/README.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "## National Weather Service\n http://catalog.data.gov/dataset/national-weather-service\n\n\n They have a Data Dictionary: http://w1.weather.gov/glossary/\n\n\n http://w1.weather.gov/glossary/index.php?letter=c\n\n" }, { "alpha_fraction": 0.5583660006523132, "alphanum_fraction": 0.5645881295204163, "avg_line_length": 24.23208236694336, "blob_id": "74fd6314bd4729d58870b29c6586afe067f5911b", "content_id": "4a0d219df76cc33497934ae13d2ec5b36a6556e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7393, "license_type": "no_license", "max_line_length": 91, "num_lines": 293, "path": "/datatools/scrapeURLS/scrapeURLS.py", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport sys, os, urllib2, json, urllib, requests,datetime\nfrom bs4 import BeautifulSoup\n\n# Read file and return cropped file, or random sample.\ndef process_file(file_path, limit, selector, process_only):\n # Total number lines\n f = open(file_path, 'r')\n lines = f.readlines()\n line_count = file_len(file_path)\n print \"Total number urls: \" + str(line_count)\n\n\n count = 0\n text = ''\n csv_object_array = []\n for row in lines:\n if count < int(limit):\n row = row.strip('\\n')\n line = row.split(',')\n\n file_name = str(line[2]) + \"_\" + str(line[1])\n # if os.path.isfile(\"output/raw/\" + file_name + \".html\") == False:\n url = line[0]\n csv_object = processURL(url, file_name, selector, process_only)\n csv_object_array.append(csv_object)\n # print \"making \" + file_name + \" \" + str(count)\n count = count + 1\n\n saveCSV(csv_object_array)\n\n print \"Saved new file with \" + str(limit) + \" rows at: \"\n\n f.close()\n return text\n\n\ndef saveCSV(csv_object_array):\n csv_file_name = datetime.date.today().strftime(\"%Y-%B-%d\")\n\n csv_out = open(\"output/csv/\" + csv_file_name + \".csv\",\"w\")\n csv_out.seek(0)\n\n csv = buildCSV(csv_object_array)\n\n csv_out.write(csv)\n\n csv_out.truncate()\n csv_out.close()\n\ndef buildCSV(csv_list):\n output = ''\n\n\n # Build complete attribute list from all csv objects.\n attributes = []\n\n # @TODO Group by dataset name\n full_attributes = []\n for record in csv_list:\n keys = record.keys()\n attributes_set = set(attributes)\n keys_set = set(keys)\n\n difference = keys_set - attributes_set\n\n full_attributes = attributes + list(difference)\n\n print full_attributes\n\n rebuilt_csv_list = []\n\n for item in csv_list:\n csv_object = {}\n\n for attribute in full_attributes:\n\n if item[attribute] == \"None\":\n csv_object[attribute] = \"NULL\"\n else:\n csv_object[attribute] = item[attribute]\n\n rebuilt_csv_list.append(csv_object)\n\n\n counter = 0\n for record_item in rebuilt_csv_list:\n\n if counter == 0: \n for label_attr, label_value in record_item.items():\n output = output + \"'\" + label_attr + \"',\"\n output = output + '\\n'\n \n for attr, value in record_item.items():\n output = output + \"'\" + value + \"',\"\n\n \n\n counter = counter + 1\n output = output + '\\n'\n return output\n\n\n\n# Save sample as file.\ndef save_sample(text, output_file_name):\n current_directory = os.path.dirname(os.path.realpath(__file__))\n print current_directory + \"/\" + output_file_name\n fout = open(\"output/\" + output_file_name,\"w\")\n fout.seek(0)\n fout.write(text)\n fout.truncate()\n fout.close()\n\n# Get length of file.\ndef file_len(fname):\n with open(fname) as f:\n for i, l in enumerate(f):\n pass\n return i + 1\n\n\ndef processURL(url, file_name, selector,process_only):\n # Loading URL.\n print \"Loading \" + url\n\n results = storeURLResults(url, file_name, selector,process_only)\n output = compressResultsCSV(file_name, results)\n\n return output\n\ndef compressResultsCSV(file_name, results):\n count = 0\n lines = results.split('\\n')\n output = ''\n\n csv_object = {}\n\n for line in lines:\n l = line.split(',')\n\n csv_object['File Name'] = file_name\n\n if count == 0:\n csv_object['Dataset Name'] = l[0]\n\n if len(l) > 1:\n csv_object['Dataset Description'] = l[1]\n\n else:\n if len(l) > 1:\n csv_object[l[0].strip(':')] = l[1]\n count = count + 1\n\n return csv_object\n\ndef storeURLResults(url, file_name, selector, process_only):\n # Store results from visit to web page.\n if process_only == True:\n with open(\"output/processed/\" + file_name + \".txt\", \"wb\") as write_file:\n print \"Processing data only.\"\n with open(\"output/raw/\" + file_name + \".html\", 'r') as read_file:\n text = read_file.read()\n content = getFileNameDetails(text,selector)\n content = content + getFileDescriptionDetails(text,selector) + '\\n'\n content = content + limitResultsBySelector(text,selector)\n write_file.write(str(content) + \"\\n\")\n return str(content)\n else:\n r = requests.get(url)\n text = r.content\n\n with open(\"output/raw/\" + file_name + '.html', \"wb\") as f:\n f.write(text)\n\n with open(\"output/processed/\" + file_name + \".txt\", \"wb\") as f:\n content = getFileNameDetails(text,selector)\n content = content + getFileDescriptionDetails(text,selector) + '\\n'\n content = content + limitResultsBySelector(text,selector)\n f.write(str(content) + \"\\n\")\n return str(content)\n\ndef getFileNameDetails(text,selector):\n output = ''\n soup = BeautifulSoup(text)\n\n # Name\n name_selector = selector[0].split(' ')\n last_selector = name_selector.pop()\n name_selector = ' '.join(name_selector)\n\n result_name = soup.select(name_selector)\n\n for r in result_name:\n \n div = r.find_all(last_selector)\n\n for d in div:\n if d != []:\n value = str(d.string).strip()\n return value + \",\"\n\n\ndef getFileDescriptionDetails(text,selector):\n output = ''\n soup = BeautifulSoup(text)\n\n # Name\n name_selector = selector[1].split(' ')\n last_selector = name_selector.pop()\n name_selector = ' '.join(name_selector)\n\n result_name = soup.select(name_selector)\n\n for r in result_name:\n div = r.find_all(last_selector)\n \n for d in div:\n value = str(d.string).strip()\n\n return value\n\ndef limitResultsBySelector(text,selector):\n # Find selector in results.\n # Return results from selector.\n\n #http://www.briancarpio.com/2012/12/02/website-scraping-with-python-and-beautiful-soup/\n soup = BeautifulSoup(text)\n # Content\n result = soup.select(selector[2])\n output = ''\n for r in result:\n div = r.find_all('div')\n d_count = 0\n for d in div:\n value = str(d.string)\n output = output + value.strip()\n if d_count < len(div) - 1:\n output = output + \",\"\n d_count = d_count + 1\n output = output + \"\\n\"\n return output\n\n\n# Main program. Read system arguments, read file, make output file.\ndef main():\n # Create list of files.\n file_list = []\n\n if len(sys.argv) > 1:\n input_path = str(sys.argv[1])\n\n if input_path.endswith(\".csv\"):\n file_list.append(file)\n\n if len(sys.argv) > 2:\n limit = str(sys.argv[2])\n else:\n limit = 10\n\n if len(sys.argv) > 3:\n selector = str(sys.argv[3])\n selector = selector.split(',')\n else:\n print \"No selector given\"\n selector = ''\n\n process = False\n\n if len(sys.argv) > 4:\n process_only = str(sys.argv[4])\n print process_only\n if process_only == 'process-only':\n\n process = True\n\n\n\n url_results = process_file(input_path, limit, selector, process)\n\n else:\n \"File supplied not CSV\"\n\n else:\n print \"No file given\"\n\n\n\nmain()\n\nprint \"Done.\"\n\nsys.exit()\n" }, { "alpha_fraction": 0.7776349782943726, "alphanum_fraction": 0.7789202928543091, "avg_line_length": 55.92683029174805, "blob_id": "70c27641776dc18b2940ee14daea1a541de7a847", "content_id": "d417e28f93165a73b36f603d625be7e5d85e90cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2334, "license_type": "no_license", "max_line_length": 150, "num_lines": 41, "path": "/README.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "DataTrain\n=========\nA social \"data dictionary\" for public data.\n\nDataTrain is a data service that makes it easier and faster to understand and communicate the meaning, value and implications of open, public data.\n\n\n### Features\n* Add: Import dataset sample, get permalink to metadata about the dataset fields (elements and properties.)\n* Add definitions: Import existing data dictionary based on schema. (Some libraries for common data dictionary formats.)\n* Collaboratively edit information about for fields and values in datasets based on suggested \"question sets\" appropriate to that type of information.\n* Search for field abbreviations and names. Get descriptions for similar fields from other datasets, if available.\n* Share your research notes and expertise and help raise the bar of how we understand the work of our governments.\n* Export data in JSON format for incorporation in open data APIs\n* Make API requests for field metadata (labels, descriptions, privacy suggestions), for storing and presenting with hosted data.\n* Get open data documented faster.\n\n\n##### See also\n* ROADMAP.md - Document describing the growth of the project.\n* BACKGROUND.md - Background info\n* _specs/APP.md - Document describing the application.\n* _specs/API.md - Document describing the API.\n* _specs/DATA.md - Document describing the data.\n* _specs/FORMATS.md - Document describing the exported data formats.\n* _specs/INTERACTION.md - Document describing the interaction.\n* _specs/INTERFACE.md - Document describing the interface.\n* _specs/QUESTIONS.md - Document about the questions to ask of different datasets, fields and values.\n* _design/ - Folder for design assets. Will also eventually use Dropbox.\n* _content/ - Folder for written copy for the application & communications materials.\n* data/data_schema.json - Document showing the schema format for metadata records for each dataset.\n* data/examples/example_data_1.json - Sample dataset in schema format.\n* data/examples/example_data_2.json - Sample dataset in schema format.\n* data/examples/example_data_3.json - Sample dataset in schema format.\n* data/source/ - Folder for original CSV datasets\n* data/db - Folder for flat file JSON document object records of metadata for each dataset.\n* app - Application\n\n\n* URL (reserved) http://data-train.org\n* Twitter (reserved) @TheDataTrain\n" }, { "alpha_fraction": 0.7615545988082886, "alphanum_fraction": 0.7825630307197571, "avg_line_length": 51.83333206176758, "blob_id": "b2e39c7d2b1798b7182a18a84aefcbca9f474a4e", "content_id": "df7fd1bb355028451a7b9f408f13330c07e7ef1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 952, "license_type": "no_license", "max_line_length": 185, "num_lines": 18, "path": "/ROADMAP.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "## ROADMAP\n### Timeline & Next Steps\n\n12/04/2014 - project conception (after several years of observation)\n\n12/24/2014 - publish project description\n\n* Publish technical road map\n* Publish schema\n* Publish draft of question sets\n* MVP & Research: Jan - March: reach out to possible projects and document datasets according to working draft of metadata schema. Use question sets & publish results as JSON in github.\n* Build design mockup of app interface\n* Mock up app\n* Document spec of app (currently is in scribble notes on a pieces of paper)\n* Raise some cash to support active development and outreach efforts in 2015 and get this going as a public data utility.\n* Prototype ajax widget for integration with data platforms\n* research, measure, test, more partners, grow if MVP seems like it is working and beneficial.\n* change culture around talking about data... make data descriptions and plain language communication more commonplace & easier.\n\n" }, { "alpha_fraction": 0.8425531983375549, "alphanum_fraction": 0.8425531983375549, "avg_line_length": 32.71428680419922, "blob_id": "47a0c79755f4ddafe6430697e6fe051421b41b7c", "content_id": "9a52ec7ade9b80c2180722bdd88e83c9113a3e78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 235, "license_type": "no_license", "max_line_length": 83, "num_lines": 7, "path": "/projects/README.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "# Projects\n\n* Define Data Dictionary Spec\nResearch and recommend lightweight formats for sharing data dictionary information.\n\n* Existing Data Dictionaries\nResearching existing formats of Data Dictionaries and data dictionary catalogs." }, { "alpha_fraction": 0.7890137434005737, "alphanum_fraction": 0.7902621626853943, "avg_line_length": 42.6363639831543, "blob_id": "1ecbd977b11900a5ae97c03754d04b72d15d96d5", "content_id": "29475881987fc9e2e5de390ddefbdadcddeb7aaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2405, "license_type": "no_license", "max_line_length": 202, "num_lines": 55, "path": "/projects/existing_data_dictionaries/NYC - Pluto Data Dictionary/README.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "\n# Make Machine readable PLUTO Data Dictionary\n\n\n### Convert the 53 page PLUTO Data Dictionary document into machine-readable format.\n* Source: http://www.nyc.gov/html/dcp/pdf/bytes/pluto_datadictionary.pdf, copied into microtasks/sources/pluto_datadictionary.pdf\n* See also: http://www.nyc.gov/html/dcp/html/bytes/applbyte.shtml\n\"Extensive land use and geographic data at the tax lot level in comma–separated values (CSV) file format. The PLUTO files contain more than seventy fields derived from data maintained by city agencies.\"\n\n\n## TODO\n* Check that this is the most recent version of the file.\n* More research to see if this has already been done (ask around.)\n* More research to see what issues people have had with the data dictionary.\n* Downlaod the PLUTO dataset and investigate data samples.\n* Make new git repository for parsing the PLUTO Data Dictionary.\n\nIf all is a go:\n* Parse the PDF file and render the contents according to the data_dictionary schema /data/schema/data_dictionary/data_dictionary_spec.md\n\n\n\n###Examples\n\n### Dataset\nid, name, dataUrl, sourceName, sourceURL, type, location, tags, description, comments, dateAdded, dateUpdated, published, contributors, revision\n, \"PLUTO Data Dictionary\", \"http://www.nyc.gov/html/dcp/pdf/bytes/pluto_datadictionary.pdf\", \n\n## Fields\nid, name, fieldName, dataTypeName, description, comments, renderTypeName, datasetId, datasetName, contentSummary\n\n## Localization\nid, type, fieldId, language, fieldName, abbreviation, labelShort, labelLong, description, definition, icon, reference, contact, supplemental\n\n\n\nField Name: BOROUGH (Borough)\nFormat: Alphanumeric - 2 characters\nData Source: Department of City Planning - based on data from:\nDepartment of Finance - RPAD Master File\nDescription: The borough that the tax lot is located in.\nThis field contains a two character borough code.\nCODES DECODES\nBX Bronx\nBK Brooklyn\nMN Manhattan\nQN Queens\nSI Staten Island\nNOTE: Two portions of the city, Marble Hill and Rikers Island, are each\nlegally located in one borough but are serviced by different\nboroughs. The BOROUGH codes associated with these areas\nare the boroughs they are legally located in.\nSpecifically, Marble Hill is serviced by the Bronx but is legally\nlocated in Manhattan and has a Manhattan BOROUGH Code.\nRikers Island has a Bronx BOROUGH Code because it is legally\nlocated in the Bronx although it is serviced by Queens.\n\n\n" }, { "alpha_fraction": 0.5245803594589233, "alphanum_fraction": 0.5461630821228027, "avg_line_length": 28.522123336791992, "blob_id": "28bbc9cb5c176cdfedc57170012f659d854f5d03", "content_id": "c32f1a88235ea1ec8bcb736198a3fcf2e8b63357", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3336, "license_type": "no_license", "max_line_length": 226, "num_lines": 113, "path": "/projects/existing_data_dictionaries/data.gov/getDataDictionaries/getDataDictionaries.py", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport sys, os, urllib2, json, urllib, requests, datetime, csv\n\n# http://catalog.data.gov/api/3/action/package_search?q=dataDictionary:*&rows=1000&start=2\n\n# Read file and parse JSON based on dot syntax\ndef process_file(file_list):\n csv_data = [['id','title','data_dictionary','notes','tags','metadata_created','metadata_modified','maintainer','state','resource_formats','data_urls']]\n \n \n\n\n for file_path in file_list:\n print \"Processing: \" + file_path\n f = open(os.path.dirname(os.path.realpath(__file__)) + \"/data/\" + file_path, 'r')\n json_object = json.load(f)\n results = json_object['result']['results']\n\n for result in results:\n data = {}\n data['id'] = result['id'].encode('utf-8')\n data['title'] = result['title'].encode('utf-8')\n data['notes'] = result['notes'].encode('utf-8')\n data['metadata_created'] = result['metadata_created']\n data['metadata_modified'] = result['metadata_modified']\n data['maintainer'] = result['maintainer']\n data['state'] = result['state']\n resources = result['resources']\n # id: \"1e68f387-5f1c-46c0-a0d1-46044ffef5bf\",\n # metadata_created: \"2014-02-26T00:48:24.897497\",\n # metadata_modified: \"2015-01-16T18:05:17.138759\",\n # data['url'] = result['url']\n # data['format'] = result['format']\n\n\n \n \n data['data_dictionary'] = ''\n extras = result['extras']\n for extra in extras:\n if extra['key'] == 'dataDictionary':\n data['data_dictionary'] = extra[\"value\"]\n if extra['key'] == 'describedBy':\n data['data_dictionary'] = extra[\"value\"]\n\n tags = result['tags']\n tag_array = []\n for tag in tags:\n tag_array.append(tag['display_name'].encode('utf-8'))\n\n resource_formats_array = []\n data_urls = []\n for resource in resources:\n resource_formats_array.append(resource['format'].encode('utf-8'))\n data_urls.append(resource['url'].encode('utf-8'))\n csv_data.append([data['id'],data['title'], data['data_dictionary'], data['notes'], tag_array, data['metadata_created'], data['metadata_modified'],data['maintainer'],data['state'],resource_formats_array, data_urls])\n\n \n \n f.close()\n saveCSV(csv_data)\n return \"done\"\n\n\ndef saveCSV(csv_data):\n \n csv_file_name = \"output/csv/\" + datetime.date.today().strftime(\"%Y-%B-%d\") + \".csv\"\n csv_writer = csv.writer(open(csv_file_name, 'wb'))\n\n for row in csv_data:\n csv_writer.writerow(row)\n\n# Main program. Read system arguments, read file, make output file.\ndef main():\n # Create list of files.\n file_list = []\n\n\n input_folder = \"data\"\n\n current_directory = os.path.dirname(os.path.realpath(__file__)) + '/'\n\n files = os.listdir(current_directory + input_folder)\n\n for file in files:\n if file.endswith(\".json\"):\n file_list.append(file)\n\n\n\n \n\n\n\n\n \n \n else:\n \"File supplied not JSON\"\n\n \n\n process_file(file_list)\n\n\n\n\n\nmain()\n\nprint \"Done.\"\n\nsys.exit()\n" }, { "alpha_fraction": 0.7963096499443054, "alphanum_fraction": 0.8074095249176025, "avg_line_length": 69.07070922851562, "blob_id": "92a1a513236cc5969ea79a2d906679a5614fca9d", "content_id": "547b21b6fccfc52c76e0936b808859f37844a572", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6977, "license_type": "no_license", "max_line_length": 596, "num_lines": 99, "path": "/notes/data dictionaries.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "# Notes on Data Dictionaries and Best Practices\n\n\n## Definition Data Dictionary\nFrom Wikipedia: http://en.wikipedia.org/wiki/Data_dictionary\nA data dictionary, or metadata repository, as defined in the IBM Dictionary of Computing, is a \"centralized repository of information about data such as meaning, relationships to other data, origin, usage, and format.\"[1] The term can have one of several closely related meanings pertaining to databases and database management systems (DBMS):\n\nA document describing a database or collection of databases\nAn integral component of a DBMS that is required to determine its structure\nA piece of middleware that extends or supplants the native data dictionary of a DBMS\n\n#### Notes from Oracle\n* https://docs.oracle.com/html/A96524_01/c05dicti.htm\n----\n\"One of the most important parts of an Oracle database is its data dictionary, which is a read-only set of tables that provides information about the database. A data dictionary contains:\n • The definitions of all schema objects in the database (tables, views, indexes, clusters, synonyms, sequences, procedures, functions, packages, triggers, and so on)
\n • How much space has been allocated for, and is currently used by, the schema objects
\n • Default values for columns
\n • Integrity constraint information
\n • The names of Oracle users
\n • Privileges and roles each user has been granted
\n • Auditing information, such as who has accessed or updated various schema objects
\na • Other general database information
\nThe data dictionary is structured in tables and views, just like other database data. All the data dictionary tables and views for a given database are stored in that database's SYSTEM tablespace.\nNot only is the data dictionary central to every Oracle database, it is an important tool for all users, from end users to application designers and database administrators. Use SQL statements to access the data dictionary. Because the data dictionary is read-only, you can issue only queries (SELECT statements) against it's tables and views.\n\"\n\n#### MODERNIZATION ideas \n* change to read-write & comment (social, collaboratively edited, stack overflow like)\n* sample values\n* distinct values with counts\n* conversations about the data can influence the very nature of the data and formatting (example: requesting data improvements, like parsing out dates when not normally available, but are critical to actually making the data useful.)\n\n\n\n#### Notes on managing Data Dictionaries\n* http://library.ahima.org/xpedio/groups/public/documents/ahima/bok1_049331.hcsp?dDocName=bok1_049331\n\"Common Data Inconsistencies\nIn many organizations data are stored in different databases and may be of inconsistent quality. Issues such as variable naming conventions, definitions, field length, and element values can all lead to misuse or misinterpretation of data in reporting. The following examples illustrate common data inconsistencies.\n\nInconsistent naming conventions. The date of the patient's admission is referred to differently in different systems: \"Date of Admission\" in the patient management module within the EHR, \"Admit Date\" in the fetal monitoring system, and \"Admission Date\" in the cardiology database. The unique patient identifier is referred to as a \"Medical Record Number\" in the patient management system, \"Patient Record Identifier\" in the operating room system, \"A number\" (a moniker leftover from a legacy system from 25 years ago), and \"Enterprise Master Patient Identifier\" in the catheterization lab system.\n\nInconsistent definitions. The patient access module defines date of admission as the date on which an inpatient or day surgery visit occurs; the trauma registry system defines it as the date on which the trauma patient enters the operating room. Pediatric age is defined as age less than or equal to 13 in the EHR module, while the pediatric disease registry defines pediatric age as below the age of 18. In the bed board system, a nursing unit may be defined as 5W or 5 West. Within the scheduling system, unique locations are defined as short procedure unit or SPU, x-ray, or radiology.\n\nVarying field length for same data element. The field length for a patient's last name is 50 characters in the patient management module and 25 characters in the cancer registry system. The medical record number in the patient management system is 16 characters long, while the cancer registry system maintains a 13-character length for the medical record number.\n\nVaried element values. The patient's gender is captured as M, F, or U in the patient access module, while the gender is captured as Male, Female, or Other in the peripheral vascular lab database.\n\nInconsistencies in data definitions can lead to innaccurate data use and health data reporting and can potentially affect the quality of care.\"\n\n\"The Benefits of a Data Dictionary\n\nA data dictionary promotes data integrity by supporting the adoption and use of consistent data elements and terminology within health IT systems. By adopting a data dictionary, organizations can improve the reliability, dependability, and trustworthiness of data use.\n\nAn established data dictionary can provide organizations and enterprises many benefits, including:\n\nImproved data quality\nImproved trust in data integrity\nImproved documentation and control\nReduced data redundancy\nReuse of data\nConsistency in data use\nEasier data analysis\nImproved decision making based on better data\nSimpler programming\nEnforcement of standards1\nA data dictionary promotes clearer understanding of data elements; helps users find information; promotes more efficient use and reuse of information; and promotes better data management.\n\nNote\n\nDepartment of Health and Human Services. \"Health Information Technology: Initial Set of Standards, Implementation Specifications, and Certification Criteria for Electronic Health Record Technology.\" Federal Register, July 28, 2010. http://federalregister.gov/a/2010-17210.\"\n\n### Best practicies in creating a data dictionary\nhttp://www.utexas.edu/cola/orgs/redcap/Best-Practices.php\n\n### Best Practices for Data Dictionary Definitions and Usage\n Version 1.1 2006-11-14 \nhttp://www.pnamp.org/sites/default/files/best_practices_for_data_dictionary_definitions_and_usage_version_1.1_2006-11-14.pdf\n\n\n\"According to the International Standards Organization (ISO)2\n “The increased use of data processing and\nelectronic data interchange heavily relies on accurate, reliable, controllable, and verifiable data\nrecorded in databases. One of the prerequisites for a correct and proper use and interpretation of data is\nthat both users and owners of data have a common understanding of the meaning and descriptive\ncharacteristics (e.g., representation) of that data. To guarantee this shared view, a number of basic\nattributes has to be defined.”\n\n\n\n### Useful \"TABLE II - DIVERGENCE IN TERMINOLOGY USED TO DESCRIBE DATA-DICTIONARY ELEMENTS\"\n" }, { "alpha_fraction": 0.7430406808853149, "alphanum_fraction": 0.7665953040122986, "avg_line_length": 35, "blob_id": "724edf5537f01a3a23c1b0936a4d4734361190ab", "content_id": "3575908f2e13a2cce071d4bc4f48a33814d709f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 467, "license_type": "no_license", "max_line_length": 150, "num_lines": 13, "path": "/datatools/chopCSV/README.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "# Chop CSV\nChop a long CSV file into a shorter one, for quick data sampling.\nExample: 98MB many lines into 500 lines. \n\n* Make sure chmod +x chopCSV.py\n\n### Usage\nRun the file giving the input path, file name and number of rows to return\n\n./chopCSV.py full_path_input_file file_name_output_file number_rows\n\nExample:\n/chopCSV.py /Folder/datatrain/projects/existing_data_dictionaries/NYC\\ -\\ Pluto\\ Data\\ Dictionary/source_files/nyc_pluto_14v2/MN.csv MN_sample.csv 100" }, { "alpha_fraction": 0.751937985420227, "alphanum_fraction": 0.7829457521438599, "avg_line_length": 61.5, "blob_id": "99cc2687a68c094ce327d6ad55a581ab4728aaa9", "content_id": "d698237bf000b7a50e5f867db9fa3cfefe1b7cbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 129, "license_type": "no_license", "max_line_length": 110, "num_lines": 2, "path": "/projects/existing_data_dictionaries/Census.gov/README.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "\n## Census.gov\n* http://www.census.gov/programs-surveys/sipp/tech-documentation/data-dictionaries/data-dictionaries-2008.html\n\n\n\n" }, { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 95, "blob_id": "1605788d1e68cc4d129915cacb59a2799334c989", "content_id": "609e96d4f2de3d147089c5e3c6decfd32a599dc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 96, "license_type": "no_license", "max_line_length": 95, "num_lines": 1, "path": "/projects/existing_data_dictionaries/Food Access Research Atlas/REAME.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "http://www.ers.usda.gov/data-products/food-access-research-atlas/documentation.aspx#definitions\n" }, { "alpha_fraction": 0.7089518904685974, "alphanum_fraction": 0.7233468294143677, "avg_line_length": 41.71154022216797, "blob_id": "ae4e2182293e840ead40bb2264f28872bf277074", "content_id": "e4315c497daae5607595b168e642cd41ec29bad2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2225, "license_type": "no_license", "max_line_length": 210, "num_lines": 52, "path": "/projects/existing_data_dictionaries/OpenFDA/README.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "\n\n## Open FDA\nThis modern online data resource has the best quality documentation for the data in the Open FDA fields.\n* Open FDA https://open.fda.gov/api/reference/\n\n### Notes\n\"Query syntax\n\nQueries to the openFDA API are made up of parameters joined by an ampersand &. Each parameter is followed by an equals sign = and an argument.\n\nSearches have a special syntax: search=field:term. Note that there is only one equals sign = and there is a colon : between the field to search, and the term to search for.\n\nHere are a few syntax patterns that may help if you’re new to this API.\n\nPattern Description\nsearch=field:term Search within a specific field for a term.\nsearch=field:term+AND+field:term Search for records that match two terms.\nsearch=field:term+field:term Search for records that match either of two terms.\nsearch=field:term&count=field.exact Search for matching records, then count within that set the number of records that match the unique values of a field.\"\n\n\n\"Field-by-field reference\"\n\n\nrecalling_firm\nstring\nThe firm that initiates a recall or, in the case of an FDA requested recall or FDA mandated recall, the firm that has primary responsibility for the manufacture and (or) marketing of the product to be recalled.\n\n\nhttps://open.fda.gov/food/enforcement/reference/\n\nEnforcement Report\n\"results\": [\n {\n \"reason_for_recall\": \"Cass-Clay Creamery is voluntarily recalling a number of ice cream products because they may contain undeclared soy (lecithin).\",\n \"status\": \"Ongoing\",\n \"distribution_pattern\": \"ND, AZ, MN, SD, KS\",\n \"product_quantity\": \"81 containers\",\n \"recall_initiation_date\": \"20120720\",\n \"state\": \"ND\",\n \"event_id\": \"62644\",\n \"product_type\": \"Food\",\n \"product_description\": \"Cass-Clay , Swiss Chip, 3 Gallon(11.34 L).\",\n \"country\": \"US\",\n \"city\": \"Fargo\",\n \"recalling_firm\": \"Cass Clay Creamery AMPI Fargo Division\",\n \"report_date\": \"20120905\",\n \"voluntary_mandated\": \"Voluntary: Firm Initiated\",\n \"classification\": \"Class II\",\n \"code_info\": \"all products that has a plant code of \\\"38-25\\\".\",\n \"openfda\": {},\n \"initial_firm_notification\": \"Two or more of the following: Email, Fax, Letter, Press Release, Telephone, Visit\"\n }\n" }, { "alpha_fraction": 0.8252426981925964, "alphanum_fraction": 0.8252426981925964, "avg_line_length": 103, "blob_id": "4a9a86c4bfe0773f03b11efe440319d2717cb9ae", "content_id": "6246620218402d35c883db9f96b8fd59342f1d2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 103, "license_type": "no_license", "max_line_length": 103, "num_lines": 1, "path": "/notes/README.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "These notes will eventually become some blog posts or articles, as well as guidelines for this project." }, { "alpha_fraction": 0.764397919178009, "alphanum_fraction": 0.801047146320343, "avg_line_length": 53, "blob_id": "77024a96e21a6aaf82b3b5b82c6cd1fd01abee27", "content_id": "f93e04988626aa90bf91e3250508cb38f99d4dd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 382, "license_type": "no_license", "max_line_length": 116, "num_lines": 7, "path": "/projects/existing_data_dictionaries/README.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "\n\n\n* google doc of data dictionaries: \nhttps://docs.google.com/spreadsheets/d/15rL8PeKaIT3-FyCxr_qwpSD-feBXjaBxj9NIX7ffkjg/edit#gid=0\n\n\nData SF SFO Customer Survey\nYearly surveys of where in the world people are coming from (as measured at the san francisco international airport)\n* https://data.sfgov.org/Transportation/Data-SF-Data-Dictionary-For-2011-Customer-Survey/yw9r-e59z?\n\n" }, { "alpha_fraction": 0.7934845685958862, "alphanum_fraction": 0.7958115339279175, "avg_line_length": 189.55555725097656, "blob_id": "bf8b36ce92e387a5ac69f0fe279810943598a269", "content_id": "17d33409e88536e5c352d9b0c3f543dd3844ba94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1719, "license_type": "no_license", "max_line_length": 877, "num_lines": 9, "path": "/LICENSING_ATTRIBUTION.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "The application code (/app) in this open source repository is offered with a GPL license and may be used as a free tool to faciliate the documentation of datasets for public use.\n\nThe metadata schema is a public document, and should be referred to as the [Public Metadata Schema]* [DataTrain] [version number]**\n * Thinking of a name for the schema - will depend on conversations.\n ** @TODO check syntax here and best practice. The idea is to allow for a shared name, and our own variation that we will use, plus a version number. This should cut down on the need for lengthy schema discussions about governance.\n\nThe project assets (copy, design elements, architecture, questions etc.) related to DataTrain as a data service belong to DataTrain the project, located at data-train.org and related accounts. These elements are provided for purposes of collaboration, transparency, and to help promote good design and copy-editing practices. The spirit of this is that DataTrain should be able to become a small business entity to support providing software as a service (SASS) and maintain leadership in the direction of the software, while the open source code provides the options for complex agencies to adapt the software for promoting comprehension and understanding of data, especially in situations with privacy concerns. As of December 2014, we expect that if this tool proves useful, that it will be forked as necessary, and at which point, non-app related assets should be removed. \n\nIf you use this software, we request that you let us know about your project and periodically send us stories of success and failure, as a courtesy for our good faith in sharing this with you in the public interest.\n\n\n\n\n" }, { "alpha_fraction": 0.6697108149528503, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 37.70588302612305, "blob_id": "1c47aac764083c37e62de0dfad42c479f8e0cd38", "content_id": "471ee03b2afc862f792299c5854abac0a9b27489", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 657, "license_type": "no_license", "max_line_length": 172, "num_lines": 17, "path": "/projects/existing_data_dictionaries/data.gov/README.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "# Notes\n\nData Dictionary is a field in the data.gov CKAN API\n\n## Links\nhttp://vocab.data.gov/\n\n\n## Figuring out how to get a list of all URLs to all data.gov data dictionaries:\n* http://catalog.data.gov/api/3/\n* http://catalog.data.gov/api/3/action/package_list\n* http://catalog.data.gov/api/3/action/package_search?q=dataDictionary\n* Normal search: dataset?q=dataDictionary&sort=none&ext_location=&ext_bbox=&ext_prev_extent=-139.21874999999997%2C8.754794702435605%2C-61.87499999999999%2C61.77312286453148\n\n\nThe data dictionary on this dataset is wrong:\n* http://catalog.data.gov/dataset/baby-names-from-social-security-card-applications-national-level-data" }, { "alpha_fraction": 0.6963647603988647, "alphanum_fraction": 0.7470057010650635, "avg_line_length": 40, "blob_id": "6e5f34fb328109541113809197f0a186b2267c3f", "content_id": "954cf44b5326e1c62889d506105cf0c1c3c36618", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4759, "license_type": "no_license", "max_line_length": 161, "num_lines": 116, "path": "/projects/existing_data_dictionaries/data.gov/getDataDictionaries/notes/2015-1-23.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "# Analysis of data.gov Data Dictionaries, as of 1/23/2015\n\nTotal Data Packages as of 1/23/2015: 137908\n\nPackages with a datadictionary: 6630\nDownloaded 6629 (1 missing as a result of paging results?, will download again later)\n\nPackages with describedBy: 734 \nDownloaded 734 (1 missing as a result of paging results?, will download again later)\n\nTotal Records in CSV file: 7362\n\n7362 total datasets with documentation\n\n5.34% of all datasets have data dictionaries.\n\n502 distinct results\nTop ten data dictionary URLS point to: 5463 of the results (of 6629) = 82.4%\n20%: 1166 data dictionaries with 50 or less references:\n\n1. http://ofmpub.epa.gov/sor_internet/registry/termreg/home/overview/home.do 3555\n2. http://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=310&DB_Short_Name=Air%20Carriers 903\n3. http://www.dot.gov/policy/aviation-policy/air-fare-information-consumers 309\n4. http://transtats.bts.gov/DatabaseInfo.asp?DB_ID=125&DB_URL= 284\n5. http://www.fhwa.dot.gov/policyinformation/hpms/fieldmanual/ 104\n6. http://www.transtats.bts.gov/TableInfo.asp?Table_ID=236&DB_Short_Name=On-Time&Info_Only=0 71\n7. http://www.rita.dot.gov/bts/sites/rita.dot.gov.bts/files/subject_areas/omnibus_surveys/index.html 68\n8. http://www.dot.gov/policy/aviation-policy/airline-quarterly-financial-review 58\n9. http://www.itsdeployment.its.dot.gov/download.aspx 55\n10. http://gravelocator.cem.va.gov/j2ee/servlet/NGL_v1 54\n\n134: .pdf -- 97 of the distinct results\n362: contain .htm -- 157 of the distinct results\n1461: contain .asp -- 45 of the distinct results\n25 contain .cfm \n104 contain .xls - 28 distinct results\na bunch are just unique webpages\n18 contain .zip --8 of the distinct results\n\n\n### Types of files\ndo 4271 (33 distinct)\nasp 1531 (115 distinct)\nwebsite 921 (430 distinct)\npdf 356 (166 disinct)\nxls 117 (38 distinct)\ntxt 66 (52 distinct)\ncfm 40 (19 distinct)\ndoc 28 (22 distinct)\nzip 22 (12 distinct)\ncsv 3 (3 distinct)\ninvalid 2 (2 distinct)\nxsd 2 (1 distinct)\njson 1 (1 distinct)\n\n\n## Whether or not links connect to actual data dictionaries:\n\nof 7362 records: \n\n2.8% - Probably a data dictionary (Contain word 'dictionary' in file name): 207 \n50 % - Required to look up in terminology service (no guarantee that it works): 3626\n20 % - Probably a data dictionary because of file format (pdf, zip): 1522\n21 % - Links to informational webpage (no guarantee that the information makes sense or is actually correct): 1600 \n4.4% - %Probably not a data dictionary / probably not helpful: 329\n\n\n# General Questions\n\n1. Is there any analysis of the quality of the data in data.gov? is the data in data.gov definitely data? \n\n2. What does \"data.gov\" mean by data? Does this match expectations of the public?\n\nMy expectation is that government open data is:\n\n* the raw published records\n* form entries\n* sensor readings\n* measurements\n* permit records\n* survey results\n* geospatial information (boundaries, points)\n* vocabularies\n\nand that the likely usage of the data would be:\n\n* aid in government transactions (tracking, reporting, allocating resources)\n* perform statistical analysis\n* use in applications that improve communication and efficiency\n* combine datasets to allow for new insights\n* show activity, traffic, movement, transactions\n* other communication-related uses: like creating maps, posters, art\n\n## Summary\nIt's unclear that anyone had much of an idea of how to make a useful data dictionary or why that would be necessary.\n\nDocument explaining how to prepare data for data.gov:\nhttp://www.digitalgov.gov/resources/how-to-get-your-open-data-on-data-gov/\n\n3. How to get a list of the top 1000 most popular datasets? Maybe we can look at these and analyze how they are documented & start working from there to improve.\n\nPopular\nhttp://catalog.data.gov/dataset/federal-logistics-information-system-web-search-webflis\nhttp://catalog.data.gov/dataset/consumer-complaint-database\nhttp://catalog.data.gov/dataset/national-stock-number-extract\nhttp://catalog.data.gov/dataset/us-international-trade-in-goods-and-services\nhttp://catalog.data.gov/dataset/business-identification-numbers-cross-referencing-bincs-system\nhttp://catalog.data.gov/dataset/climate-data-online-cdo\nhttp://catalog.data.gov/dataset/farmers-markets-geographic-data\nhttp://catalog.data.gov/dataset/u-s-hourly-precipitation-data\n\n\n4. Strategic publications\n a. currently in action: disasters.data.gov or others coming up in the next few months?\n These datasets are being requested and a data dictionary intervention could happen.\n b. Recently published strategic releases? (what are good examples?)\n\n\n\n" }, { "alpha_fraction": 0.7970049977302551, "alphanum_fraction": 0.7970049977302551, "avg_line_length": 74.125, "blob_id": "1091570e37280a0d2b3501a4ca02c5bbce9496f5", "content_id": "c36f33c49677f259c602796a76ecdb5b4893d2da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 601, "license_type": "no_license", "max_line_length": 182, "num_lines": 8, "path": "/_specs/DATA_spec.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "### Anticipated data input formats and information sources:\n* online web forms & comments\n* data harvesting from existing data dictionaries\n* dataset metadata from existing data platforms\n* urls pointing to files in following formats: CSV, JSON, XML... (etc as necessarily/helpful)\n* machine: visiting related links (mostly goverment web pages and PDFs) and guessing related information and pulling out snippets of it & then checking it off if valid (human review)\n* subject matter expert interviews (data workers and collectors, industry professionals)\n* research (students, novice industry workers)\n" }, { "alpha_fraction": 0.7992116808891296, "alphanum_fraction": 0.8007047176361084, "avg_line_length": 158.45713806152344, "blob_id": "41ab8d776964171cd7ced71ba03a2950ab21bc1a", "content_id": "7c7de7a923bad214ccbfc70aee86b04e2f2d4d78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 16744, "license_type": "no_license", "max_line_length": 1020, "num_lines": 105, "path": "/BACKGROUND.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "\n\n### The Problem\nIn government, words matter. Specific words carry deep meaning about how and why we do things the way we do. For better or worse.\n\nA growing open data movement is making more of the complicated government data available to encourage innovation, efficiency and better collaborations among agencies, the private sector, organizations and civilians.\n\nA common problem for anyone using a government dataset is to develop a functional understanding of the fields and values of a given dataset. This can be data that is publicly downloaded through a web-based service or open data portal, or some FOIA's information that was extracted from PDFs. This is similar to any training a government worker would do in the course of their work, as they become oriented to the various processes that are part of the every day functioning of government.\n\nTo understand the data, researchers, journalists, industry professionals and others conduct deep research and technical phone calls with government agencies to make sense of the specific meanings and implications of certain values. Sometimes this is simple, somethings this takes many meetings and nuanced interviews.\n\nA big problem is that this work must be repeated by anyone working with a similar dataset, and they may be likely to have similar questions, or make similar mistakes. In some cases, it can take months to understand the real government processes taking place behind the data. This could be permit data, information about businesses, regulated data and other forms of data that were put in place to help improve our quality of life and help us function as a civilization.\n\nThe questions we ask are not only useful to us. The questions we ask of government, the small requests we make to reformat the data to be more useful to our needs. Usually the data a government holds is housed in a service provided by a government contractor, and most government contractors would *like* to make their product more valuable to governments. The explanations we help create can help train new government staff, or help with inter-agency communication.\n\n### Previous solutions\nIn ideal circumstances, a data provider shares a 'metadata dictionary' with a dataset. This can sometimes be found in GIS shapefiles, and sometimes there is a website for an agency that links to a document that explains the process. Sometimes you can find the original form where the data was collected, and figure out the meaning in that way. The more documented datasets tend to be the more highly used datasets, such as weather or the simpler tables like zipcodes.\n\nThere is a lot of information that is the product of various administrations and subject matter experts. Data that is newly released after an encouragment to open up data is less likely to have a metadata dictionary accompanying it, and this dictionary is most certainly not an intelligent product of the answers given by agencies to people working with the datasets. \n\nFor whever reasons, it's very rare to find descriptions of open data. This is probably because data was converted from a less machine-readable format, just to make it open and available at all, and the process of documenting and \"being right\" would form a cultural and process bottleneck that would mean the data would never be publishing at all! Which wouldn't be helpful. Raw data is better than no data. \n\nSomewhere in that process, however, it seems that the important part of making the dataset very clear and understandable was perhaps not prioritized. It's also very likely that the dialogue between citizens and goverment have traditionally been carried out over email, phone and at conferences, by industry workers, and so it's not a budgetary priority to make the data comprehensible to the general public, who typically have little power or influence over the day-to-day operations within government. However, as we see new applications that leverage open data to provide services and useful information for citizens and the public good, the capacity of the public to use datasets to make smarter decisions and investments in the future is shifting. Civic hackers and civic service companies are using this data and developing the capacity to work with more complex data. In order to innovate and continue to progress, we will need to lower the bar for understanding our valuable and complicated bureaucratic datasets.\n\nFortunately, we have many many open datasets and data platforms to work with and support. We can easily create a service & community of translators that focus on making data much more comprehensible, and this can plug in easily to existing data platforms.\n\n\n### Examples & Stories\nWhile some data is pretty self-explanatory (such as latitude, longituge, name, email, url), there are many others that *almost* make sense, and yet if you ask any government worker, you can usually get a very long explanation of the historical and precise meanings of a datasets. For example, we can look at the Nominations & Appointments dataset on <a href=\"https://opendata.socrata.com/dataset/The-White-House-Nominations-Appointments/n5m4-mism\">Socrata</a> that has over 500K views, and appears on <a href=\"http://www.whitehouse.gov/briefing-room/nominations-and-appointments\">White House.gov.</a>\n\n#### On \"Confirmations\"\nIn this dataset, there is a field called \"Confirmed.\" I clicked the little (i) information button, which doesn't tell me anything. (However, the \"Re-nomination\" field does say \"Indicates that the Nomination Date listed is for a re-nomination (after a previous nomination of the same individual to the same post was returned by the Senate at a recess or adjournment).\")\n\nThe value of Confirmation is a checkbox, and there is an accompanying date. \n\n*But what is a Confirmation?* Yes, anyone in government will cringe that most people don't know. In my case, I'm fine admitting my ignorance because I know I speak for most people. I lost any feeling of shame and instead adopted this as a personal mission when I was able to ask some city employees of Seattle what percentage of their population had any idea what they were doing, and they said that 10% of people had a clue at all. And then, later on, I realized that *most* government bureaucratic process *are* processes made by people, from our brains, and so somewhat arbitrary. Most complicated government data requires training and education to understand it. This encourages a culture of specialists.\n\nMy guess about a \"confirmation\" is that maybe it is a swearing in session, and the day on which an appointee becomes \"official.\" But, after watching every episode of West Wing and The Good Wife, it could *also* be that the confirmation is the day that one of the government bodies agreed to an appointee, and the appointee would start working an some sort of transition day. I really don't know. I am going to have to ask some people who studied government in college. Fortunately for me, I know people like that, but most of my life, it wasn't something I thought about. Remember, we stopped civics education in America. I've gone through my whole life hearing these words and knowing that they mean something 'governmenty' and also that it has no relevance to me. But in actuality, this is my country, and a government I would like to improve and I would like to help improve how we live, so actually I would really like to know what a confirmation is.\n\nSo I looked at Wikipedia, and got very confused. I also looked up \"Confirmation\" in the dictionary, and this was also not helpful. Surely there is a dictionary of government terminology, perhaps in a textbook? We should link these textbook definitions to these public datasets if we can.\n\nEventually, I read that \n* \"Confirmation\" has something to do with <a href=\"http://en.wikipedia.org/wiki/Advice_and_consent\">\"Advice and Consent\"</a> which leads down another (interesting) legistlative rabbithole, \n* it has something to do with the President making a recommendation for <a href=\"http://en.wikipedia.org/wiki/List_of_positions_filled_by_presidential_appointment_with_Senate_confirmation\">various roles</a> and then the Senate confirming it. \n\nIt's on us to decide how much we want to invest in a making this kind of information comprehensible to most Americans. Does it matter if we all understand what a Confirmation is? \n\n#### On terminology\n\nThere are some things you can say, about what a particular field in a dataset means, and some kinds of information that are much more sensitive. For example, some government language uses complex wording because any other word could be inaccurate and imply that something has happened that actually hasn't. This can really stress out or freak out someone who fears certain consequences. It may be that these consequences are fictitious, or they are very real. In any case, datasets with obscure and technical elements should be explained in a plain-language way that helps all tax payers understand the spirit and value of the point of data collection.\n\nWhen I was working with California Water Rights data, there were two statuses for a water right (a type of permit) that were \"Adjudicated\" and \"Claimed.\" It took me a lot of conferences, conversations with lawyers and with the State Water Resource Control board to understand that \"Adjudicated\" often meant that a many year long court process had happened, potentially involving hundreds of water basin residents. \"Claimed\" meant that someone had simply claimed that they had a water right, and it might not be official. Even today, I am only 90% certain that I fully understand. There was no way for me to share this valuable information, aside from trying to make notes in a github repository. This information could help Californians prepare better for droughts.\n\nSimilarly, in building permits, there is a stage called \"Issuance\" -- which means that a permit is in a stage in which it is in the process of being issued. No regular person uses this word. That presents one more barrier to new business owners, in making a process of getting permission just a little more complicated... and multiplied by the millions of times permits are issued.\n\n\n#### On technical data\nIn scientific data, sometimes there are very specific API's that reflect the measurement of sensors. My favorite example is that of RFID tags on whales, sea turtles and sharks in the ocean. There is a whole public API of this information, which means you can make animated maps of where whales are swimming. But the problem is, the API is entirely based on acronyms and the only reason I learned about it was because an NOAA scientist took a day to come participate in a data visualization workshop for the Exloratorium. \n\nImagine how many other sensor readings have a similar fate, public but unusable because of obcure names, locations and very abstracted acronyms. This data is already public and already in API-format. (I would get you a URL for this project, but it had such a complicated and technical name that I have been unable to locate it again, despite looking for it on 4 separate occasions!)\n\nThere are many other words that are 'red flags', because of history and legality. With a dataset such as a gun registry database, there are implications about the personally identifiable information and the address of the permit applicant. There is no way to communicate about the political sensitivity of that dataset, or to build on what others have learned. If we want to keep innovating in how we present all of this new data that is becoming public, then we need to build on what we learn. Governments shut down sensitive data as soon as it seems like it might become problematic. If we don't create a way to discuss the ethical use and implications of datasets, then we will continue to have struggles. The same goes for crime data, which at first glance seems like a useful thing to publish, but there are many discussions about how presenting crime data without other contextual information can have unintended societal implications.\n\n\n#### On plain-language communication.\n<a href=\"http://gov.uk\">Gov.UK</a> has a great <a href=\"https://www.gov.uk/guidance/content-design/writing-for-gov-uk#plain-english\">document</a> and effort to encourage government workers to use plain-language wherever possible, and this also means choosing the \"slightly less accurate\" in favor of helping more people understand. Service providers often must translate \"gov-speak\" into plain-language to make it possible to provide better services. We have a new movment of civic designers who care about the quality and comprehensibility of content. We need a way to share our best \"labels\" for certain types of information.\n\nWe have a lot of potential to understand better what we are actually *doing* to make our cities and lives better.\n\n\n# The Solution\nDataTrain is a social data service that encourages us to share our notes and research regarding the meanings of various fields and values in datasets. We are modernizing an older technology, \"metadata registries\", and making them more social and more attuned to the kinds of questions that non-subject matter experts might have with regard to the meaning of various datasets. We ask sets of questions appropriate to each field, and capture information such as legal or political implications, information about sensors and measurements, and allow for notes about the data collection process.\n\nIn addition to a collaborative workspace in the form of a data service & an open source application, a metadata schema will be researched, and we will publish our best practices that we learn as a result of doing this project. \n\n\n### Get On Board! Ways to help\n\n#### Have a dataset you have worked closely with and would like to share what you learned?\n\nWe are prototyping this application, and have a simple manual checklist of questions you can do with your dataset. We will format your answers according to a JSON schema, and make those available to a demonstration interface prototype, and then uploaded more formally one our research period is concluded.\n\n\n#### App development hack days\n\nIn January and February 2015 we will have some hack days to build out the prototype. Let us know if you are interested in volunteering. There is a schema. We will probably build this with nodejs (maybe sails) (or rails or drupal.) We might use PostGRES 9.4 sort of as a document object store, or we might use MongoDB. We will try out some fun CSS/bootstrappy frameworks and use markdown whereever possible. We will probably host the app on Digital Ocean. Early datasets will be stored in GitHub, since we may refactor the data as we learn more.\n\nHack days and nights will happen at some Brigade nights, at Code for America, and on google hangouts.\n\n#### Librarians and Content-writers\nDo you love plain-language writing? Do you get excited about the difference between 4th grade reading level and 10th grade? Bring your public understanding of everything skills to look at some tricky NSF project data and help translate it for the public.\n\n#### Design & User Research\nWe are prototyping the questions we can ask of the elements of a dataset, based on various types of information. If you are interested in doing some phone calls and taking notes, let us know.\n\n#### Subject matter experts\nDo you know a lot about a certain area of government and would be willing to be interviewed? You probably already have a good idea of the ways that people using data get confused. We want to help you get word out so that citizens understand and represent your data accurately. \n\n#### Team, Partners & Advisors\nIf you are interested and want to get this off the ground in 2015, get in touch! Otherwise, I will be reaching out and then updating this list. Will be reaching out to agencies, data platform providers. city governments & departments, information scientists, Code for America brigades and civic hackers & companies. This should be a pretty simple service to get going and be able to add value to existing data sets.\n\n### Train Conductor\nChach Sikes @chachasikes, [email protected], http://chachaville.com\n\nChach is an open data advocate and web engineer/designer/facilitator who is interested in increasing comprehension around technical and specialized information, especially after working in science museums for a long time, where writers and researchers figured out how to democratize understanding of science.\n\nShe currently works at CivicInsight publishing building development and code enforcement data, & was a Code for America Alum, '11 where she co-founded the Iconathon, a design event that encourages citizens and designers to work with subject matter experts to create visual symbols for civic concepts." }, { "alpha_fraction": 0.7731092572212219, "alphanum_fraction": 0.7731092572212219, "avg_line_length": 28.75, "blob_id": "dcae48985c254188948afbf4357faf2e8d910f99", "content_id": "f6e1daf83277bc266b913ce8ce8f533b17ec6a8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 119, "license_type": "no_license", "max_line_length": 74, "num_lines": 4, "path": "/_specs/FORMATS.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "### Anticipated output formats\n* csv\n* json\n* HTML with RDF output and appropriate signalling to page indexing robots.\n" }, { "alpha_fraction": 0.7925170063972473, "alphanum_fraction": 0.7925170063972473, "avg_line_length": 28.5, "blob_id": "b3566bdc96e4064f7f6141e7fe7637558a4037c1", "content_id": "57a8a9159ec384fb5ebdd7fd047191e5b679024f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 294, "license_type": "no_license", "max_line_length": 59, "num_lines": 10, "path": "/_specs/INTERACTION.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "### Interaction elements (running list)\n\n* input definitions\n* search definitions\n* convert definition to JSON in various appropriate schemas\n* load dataset to preview\n* provide ajax json snippet for quick lookups\n* pre-selected question sets\n* customized question sets (TBD)\n* moderation queue" }, { "alpha_fraction": 0.7886598110198975, "alphanum_fraction": 0.8298969268798828, "avg_line_length": 25.91666603088379, "blob_id": "fbcc917018dd98591df72f7b2a7f29d22f402d14", "content_id": "f34c05ca86ee2edebb6683191fafec5f0b1fa547", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 970, "license_type": "no_license", "max_line_length": 72, "num_lines": 36, "path": "/projects/existing_data_dictionaries/CSM Open Payments/README.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "http://www.cms.gov/OpenPayments/Downloads/OpenPaymentsDataDictionary.pdf\n\n\nAttribute Description Sample Data Data Type Format\nMin\nLength\nMax\nLength\nMasked in\nDe-identified\nFiles?\nGeneral_Transaction_ID System-assigned identifier to the general\ntransaction at the time of submission 100000000241 Number Number 1 38 N\n\nProgram_Year The calendar year for which the payment is\nreported in Open Payments 2013 Varchar String 0 4 N\n\nPayment_Publication_Date The predefined / calculated date when the\npayment or other transfer of value is\nscheduled to be published 09/30/2014 Date\nMM/DD/YY\nYY\n10 10 N\n\nSubmitting_Applicable_Manufact\nurer_or_Applicable_GPO_Name\nTextual proper name of the submitting\napplicable manufacturer or submitting\napplicable GPO\nABCDE\nManufacturing\nVarchar String 0 100 N\n\nCovered_Recipient_Type Indicator showing if recipient of the payment\nor other transfer of value is a physician\ncovered recipient or a teaching hospital Physician Char String 0 50 N\n\n" }, { "alpha_fraction": 0.6314767003059387, "alphanum_fraction": 0.6386010646820068, "avg_line_length": 27.081817626953125, "blob_id": "8264f3effac28f0ab4d030a5884e9ffb08b796d4", "content_id": "f8521a4c9cd22129865d567a8c20341b57929059", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3088, "license_type": "no_license", "max_line_length": 105, "num_lines": 110, "path": "/projects/existing_data_dictionaries/Planetary Data Systems/README.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "http://pds.nasa.gov/tools/ddlookup/data_dictionary_lookup.cfm\n\nhttp://pds.nasa.gov/tools/ddlookup/data_dictionary_detail.cfm?ResultsSelBox=a_axis_radius\n\n Column Name = a_axis_radius\n\n BL Name = aaxisradius\n Terse Name = aaxisradius\n Gen Data Type = REAL\n Unit Id = km\n Std Value Type = RANGE\n Minimum Column Value = N/A \n Maximum Column Value = UNK \n Minimum Length = N/A \n Maximum Length = N/A \n Default = \n \n\n Change Date = 1989-01-01\n Status Type = APPROVED\n Source Name = \n SQL Format = FLOAT \n BL SQL Format = bcdflt(31)\n Display Format = SCI(1,2)\n Std Val Output Flag = N\n Text Flag = N\n Available Value Type = \n \nDescription\n \n \nThe a_axis_radius element provides the value of the semimajor axis of \nthe ellipsoid that defines the approximate shape of a target body. 'A' \nis usually in the equitorial plane. \n\nNo Standard Values exist for this Element.\n\n General Classification \nGEOMETRY \n\n System Classification \nCOMMON \n\nObject Name Required\nimage_map_projection Y\nNo Aliases exist for this Element.\n\nNo Formation Rule exists for this Element.\n\nNo Standard Value Description exists for this Element.\n\nLabel Revision Note\n\n\n#### average_orbit_peri_tdb_time\n* http://pds.nasa.gov/tools/ddlookup/data_dictionary_detail.cfm?ResultsSelBox=average_orbit_peri_tdb_time\n Column Name = average_orbit_peri_tdb_time\n\n BL Name = mgn18\n Terse Name = \n Gen Data Type = REAL\n Unit Id = none\n Std Value Type = RANGE\n Minimum Column Value = N/A \n Maximum Column Value = UNK \n Minimum Length = N/A \n Maximum Length = N/A \n Default = \n \n\n Change Date = 1991-05-30\n Status Type = APPROVED\n Source Name = \n SQL Format = \n BL SQL Format = \n Display Format = JUSTLEFT\n Std Val Output Flag = N\n Text Flag = N\n Available Value Type = \n \nDescription\n \n The average_orbit_peri_tdb_time element provides the value \nof the periapsis time of the predicted orbit. This orbit is \nbased on the elements used to generate the uplink commands \nfor the current mapping pass. It represents an average over \nthe entire orbit, and is not the result of post-orbit \nnavigation solutions. The elements should be used for \ncomparison purposes only, since they may involve large \nerrors. The predicted orbit elements are copied from the \norbit header file of the ALT-EDR tape, or, if unavailable, \nfrom the orbit header file of the C-BIDR. \n\nNo Standard Values exist for this Element.\n\n General Classification \nSYSTEM \n\n System Classification \nPDS_GEO_MGN \n\nNo Objects are listed for this Element.\n\nNo Aliases exist for this Element.\n\nNo Formation Rule exists for this Element.\n\nNo Standard Value Description exists for this Element.\n\nLabel Revision Note" }, { "alpha_fraction": 0.7076808214187622, "alphanum_fraction": 0.7337807416915894, "avg_line_length": 32.45000076293945, "blob_id": "db007e3c4f0856b30fe3e8a935ad4595ed685a37", "content_id": "4d9c9509de4d6ed32b45c50e99fa404d74ab0e75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1341, "license_type": "no_license", "max_line_length": 120, "num_lines": 40, "path": "/notes/multilingual databases, localization, multilingual technical writing.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "\n\nObjective:\n* Create clearly articulated data schema for the application and data storage.\n* Document fields, especially the unique ones.\n* Make data schema valid & formatted for automated testing and easy user-data validation.\n\nNotes:\n* http://jsonschema.net\n* http://json-schema.org/implementations.html\n* https://github.com/lbovet/docson\n\n\n# Localization\n* efficient mongodb storage for mulitlingual databases:\nhttp://stackoverflow.com/questions/7528733/what-is-an-efficient-mongodb-schema-design-for-a-multilingual-e-commerce-site\n\n\n{ \"_id\" : ObjectId(\"4e9bfb4b4403871c0f080000\"), \n\"name\" : \"some internal name\", \n\"sku\" : \"10001\", \n\"company\" : { /* reference to another collection */ }, \"price\" : 99.99,\n\"attributes\": { \n \"description\": { \"en\": \"english desc\", \"de\": \"deutsche Beschreibung\" },\n \"another_field\": { \"en\": \"something\", \"de\": \"etwas\"}, \n \"non_i18n_field\": { \"*\": xxx } \n }\n}\n\n* http://en.wikipedia.org/wiki/Language_localisation\n\n\n# Writing technically\n* http://www.writingassist.com/resources/articles/think-globally-write-locally/\n* \"controlled english\" : http://www.slideshare.net/Enlaso/localization-technical-writing-and-translation\n* framemaker\n* translator workbench\n* \"global readiness\" writing: http://techwhirl.com/writing-global-readiness-technical-writers-need-know/\n\n\nQuestions:\n* use en_us instead of en?\n\n" }, { "alpha_fraction": 0.7951613068580627, "alphanum_fraction": 0.7951613068580627, "avg_line_length": 35.52941131591797, "blob_id": "15636b61d64e7854d835cd3935dad662fef134f4", "content_id": "783dad72a7abf5c1c9d2354dcb3727ee12ee4ef3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 620, "license_type": "no_license", "max_line_length": 103, "num_lines": 17, "path": "/projects/existing_data_dictionaries/Government Acronyms/README.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "http://www.ers.usda.gov/data-products/food-access-research-atlas/documentation.aspx#definitions\n\n\n* Department of Defense Dictionary of Military Terms http://www.dtic.mil/doctrine/dod_dictionary/\nhttp://www.dtic.mil/doctrine/dod_dictionary/\ndownloaded .xlsx file\n\n\n* Acronym Finder http://www.acronymfinder.com/\n\n* List of gov agencies: http://abbreviations.yourdictionary.com/articles/government-acronyms.html\n\n* gov speak: http://ucsd.libguides.com/govspeak\n\n* all acroynms: http://www.allacronyms.com/_government\n\n* EPA: http://ofmpub.epa.gov/sor_internet/registry/termreg/searchandretrieve/termsandacronyms/search.do" }, { "alpha_fraction": 0.7394156455993652, "alphanum_fraction": 0.751937985420227, "avg_line_length": 30.05555534362793, "blob_id": "f7bfce885dcb6b1d8bf6db7dc661d5824ace9f7b", "content_id": "5582685e686d304105cbd58eee987d3525170bed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1677, "license_type": "no_license", "max_line_length": 274, "num_lines": 54, "path": "/projects/define_data_dictionary_spec/data_dictionary_spec.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "## Dataset\n\n\n### Formats\n#### Socrata:\n* See: \nid, name, dataUrl, sourceName, sourceURL, type, location, tags, description, comments, dateAdded, dateUpdated, published, contributors, revision\n\n#### data.gov:\n* See: http://catalog.data.gov/dataset/national-weather-service\n\nResource Type, Metadata Date, Metadata Created Date,Metadata Updated Date,Reference Date(s),Responsible Party,Contact Email,Access Level,Data Dictionary,Data Quality,Frequency Of Update,Issued,Metadata Source,References,Spatial Text,Theme \n\nExample:\nResource Type, Metadata Date, Metadata Created Date,Metadata Updated Date,Reference Date(s),Responsible Party,Contact Email,Access Level,Data Dictionary,Data Quality,Frequency Of Update,Issued,Metadata Source,References,Spatial Text,Theme \n\n\"Dataset\",\"2013\",\"Aug 03, 2013\",\"Jan 12, 2014\",\"Present\",\"Unknown\",\"[email protected]\",\"public\",\"http://www.weather.gov/glossary/\",\"TRUE\",\"Hourly, Daily,Monthly\",\"1999\",\"dms\",\"http://www.weather.gov/admin.php\",\"United States and its Territories\",\"Section 6. Geography and Environment\"\n \n \n\n \n \n--------------------------------\n\n\n\n\n## Fields\nid, name, fieldName, dataTypeName, description, comments, renderTypeName, datasetId, datasetName, contentSummary\n\n## Localization\nid, type, fieldId, language, fieldName, abbreviation, labelShort, labelLong, description, definition, icon, reference, contact, supplemental\n\n### Formatted Contact\nA hash with any of the following attributes:\n\n* name\n* email\n* phone\n* url\n* address\n* latitute\n* longitude\n\n## Comment\nid, type, field_id, content, formatted, author, dateAdded, dateUpdated, tags, published, promoted\n\n### Comment Types\n\ncontact\ndescription\ndefinition\nquestion\nresponse\n" }, { "alpha_fraction": 0.7814634442329407, "alphanum_fraction": 0.785365879535675, "avg_line_length": 36.96296310424805, "blob_id": "8a410d60d974c51912cfe57c3d7a79db91d90e3d", "content_id": "2b871d2c67e871a113da5487a1c568750a7b2275", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1029, "license_type": "no_license", "max_line_length": 210, "num_lines": 27, "path": "/projects/define_data_dictionary_spec/project open data/README.md", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "\nhttps://project-open-data.cio.gov/\n\n\nhttps://project-open-data.cio.gov/schema/\n\nExpanded Field: \ndataDictionary Data Dictionary URL to the data dictionary for the dataset or API. Note that documentation other than a data dictionary can be referenced using Related Documents as shown in the expanded fields.\n\n\n\n# Recommendations for Project Open Data\nhttps://project-open-data.cio.gov/schema/\n\n1. Data Dictionary not defined, only defined as things that are not data dictionares.\nShould define what is meant by data dictionary, and even recommend a format & example for it, because the formats vary.\n\n(I am researching good data dictionaries and haven't found any excellent ones yet.)\n\n\n2. Provide a good example, vegetables is not a real link (although I like it.)\n\nField # dataDictionary\nCardinality (0,1)\nRequired No (Documentation that is not specifically a data dictionary belongs in “references”)\nAccepted Values String (URL)\nUsage Notes -\nExample {\"dataDictionary\":\"http://www.agency.gov/vegetables/dictionary.html\"}" }, { "alpha_fraction": 0.5068432688713074, "alphanum_fraction": 0.5147902965545654, "avg_line_length": 24.738636016845703, "blob_id": "6f98d6ac6c8fae7fad5687116e8fa2c482e61633", "content_id": "d2c65c924e086fd6a62d2a9432270fea015229cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2265, "license_type": "no_license", "max_line_length": 67, "num_lines": 88, "path": "/datatools/chopCSV/chopCSV.py", "repo_name": "chachasikes/DataTrain", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport sys, os\nimport random\n\n# Get length of file.\ndef file_len(fname):\n with open(fname) as f:\n for i, l in enumerate(f):\n pass\n return i + 1\n\n# Read file and return cropped file, or random sample.\ndef process_file(file_path, limit, is_random):\n # Total number lines\n f = open(file_path, 'r')\n lines = f.readlines()\n line_count = file_len(file_path)\n print \"Total number lines: \" + str(line_count)\n\n count = 0\n text = ''\n print bool(is_random)\n if bool(is_random):\n sample = random.sample(lines, int(limit))\n for line in sample:\n if count < int(limit):\n if count == 0:\n text = lines[0]\n else:\n text = text + line\n count = count + 1\n else:\n for line in lines:\n if count < int(limit):\n text = text + line\n count = count + 1\n\n print \"Saved new file with \" + str(limit) + \" rows at: \"\n f.close()\n return text\n\n# Save sample as file.\ndef save_sample(text, output_file_name):\n current_directory = os.path.dirname(os.path.realpath(__file__))\n print current_directory + \"/\" + output_file_name\n fout = open(\"output/\" + output_file_name,\"w\")\n fout.seek(0)\n fout.write(text)\n fout.truncate()\n fout.close()\n\n# Main program. Read system arguments, read file, make output file.\ndef main():\n # Create list of files.\n file_list = []\n \n if len(sys.argv) > 1:\n input_path = str(sys.argv[1])\n\n if input_path.endswith(\".csv\"):\n file_list.append(file)\n\n if sys.argv[2]:\n output_file_name = str(sys.argv[2])\n else:\n \"No output file name given\" \n\n if len(sys.argv) > 3:\n limit = str(sys.argv[3])\n else:\n limit = 100\n\n\n if len(sys.argv) > 4:\n random = str(sys.argv[4])\n else:\n random = false\n\n csv_sample = process_file(input_path,limit,random)\n save_sample(csv_sample, output_file_name)\n\n else:\n \"File supplied not CSV\"\n\n else: \n print \"No file given\"\n\nmain()\n" } ]
28
NiklasGustafsson/TorchSharp
https://github.com/NiklasGustafsson/TorchSharp
9f32f0e5fdabc7e274c63e30b802be756e553dce
c343981a849b872cae5f6d2c5621e446b9d4c724
8252096be0bed498be0be068f5e0d7bc2a1c8873
refs/heads/main
2023-08-16T22:06:53.496017
2023-08-16T12:49:36
2023-08-16T12:49:36
350,446,116
2
2
MIT
2021-03-22T18:19:58
2022-12-21T21:23:27
2023-05-11T01:52:20
C#
[ { "alpha_fraction": 0.579688310623169, "alphanum_fraction": 0.5816993713378906, "avg_line_length": 33.894737243652344, "blob_id": "dc6642da8bac695da6d9561b1107e4a76d007c7f", "content_id": "f820cae575d520b0faeea69bc01e5142146730c7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1989, "license_type": "permissive", "max_line_length": 130, "num_lines": 57, "path": "/src/TorchSharp/NN/Shuffle/ChannelShuffle.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a ChannelShuffle module.\n /// </summary>\n public sealed class ChannelShuffle : torch.nn.Module<Tensor, Tensor>\n {\n internal ChannelShuffle(long groups) : base(nameof(ChannelShuffle))\n {\n this.groups = groups;\n }\n private long groups;\n\n public override Tensor forward(Tensor tensor)\n {\n return tensor.channel_shuffle(groups);\n }\n\n public override string GetName()\n {\n return typeof(ChannelShuffle).Name;\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Divide the channels in a tensor into g groups and rearrange them.\n ///\n /// See: https://pytorch.org/docs/1.10/generated/torch.nn.ChannelShuffle.html#channelshuffle\n /// </summary>\n /// <param name=\"groups\">The number of groups to divide channels in.</param>\n /// <returns></returns>\n public static ChannelShuffle ChannelShuffle(long groups)\n {\n return new ChannelShuffle(groups);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5412596464157104, "alphanum_fraction": 0.552996039390564, "avg_line_length": 46.63194274902344, "blob_id": "b16606fd0d515332e8eb5053d611fcce6f4268d7", "content_id": "bec75b98b969df154d60131758079f60b216e267", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 13718, "license_type": "permissive", "max_line_length": 159, "num_lines": 288, "path": "/src/TorchSharp/Utils/Histogram.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp.Utils\n{\n // https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/histograms.py\n internal static class Histogram\n {\n public static (Tensor hist, Tensor bin_edges) histogram(Tensor input, HistogramBinSelector bins, (double min, double max)? range, bool density = false)\n {\n input = RavelAndCheckWeights(input.cpu());\n (Tensor bin_edges, (double, double, int) uniform_bins) = GetBinEdges(input, bins, range);\n ScalarType ntype = ScalarType.Int32;\n int block = 65536;\n\n\n (double first_edge, double last_edge, int n_equal_bins) = uniform_bins;\n Tensor n = zeros(n_equal_bins, ntype);\n Tensor norm = n_equal_bins / subtract(last_edge, first_edge);\n\n for (int i = 0; i < input.shape[0]; i += block) {\n Tensor tmp_a = input[TensorIndex.Slice(i, i + block)];\n Tensor keep = (tmp_a >= first_edge);\n keep &= (tmp_a <= last_edge);\n if (keep.sum().item<long>() != tmp_a.numel())\n tmp_a = tmp_a.masked_select(keep);\n\n tmp_a = tmp_a.to_type(bin_edges.dtype);\n Tensor f_indices = subtract(tmp_a, first_edge) * norm;\n Tensor indices = f_indices.to_type(ScalarType.Int64);\n indices[indices == n_equal_bins] -= 1;\n\n Tensor decrement = tmp_a < bin_edges[indices];\n indices[decrement] -= 1;\n Tensor increment = ((tmp_a >= bin_edges[indices + 1]) & (indices != n_equal_bins - 1));\n indices[increment] += 1;\n n += bincount(indices, minlength: n_equal_bins).to_type(ntype);\n }\n\n if (density) {\n Tensor db = diff(bin_edges).to_type(ScalarType.Float32);\n return (n / db / n.sum(), bin_edges);\n }\n return (n, bin_edges);\n }\n\n /// <summary>\n /// Computes the bins used internally by `histogram`.\n /// </summary>\n /// <param name=\"a\"> Ravelled data array </param>\n /// <param name=\"bins\"> Forwarded arguments from `histogram`. </param>\n /// <param name=\"range\"> Ravelled weights array, or None </param>\n /// <returns></returns>\n private static (Tensor, (double, double, int)) GetBinEdges(Tensor a, HistogramBinSelector bins, (double min, double max)? range)\n {\n (double first_edge, double last_edge) = GetOuterEdges(a, range);\n if (range is not null) {\n Tensor keep = (a >= first_edge);\n keep &= (a <= last_edge);\n if (keep.sum().item<long>() != a.numel())\n a = a.masked_select(keep);\n }\n\n int n_equal_bins;\n if (a.numel() == 0)\n n_equal_bins = 1;\n else {\n if (a.dtype != ScalarType.Float64)\n a = a.to_type(ScalarType.Float64);\n Tensor width = histBinSelectors[bins](a, range);\n if ((width > 0).item<bool>())\n n_equal_bins = ceil(subtract(last_edge, first_edge) / width).to_type(ScalarType.Int32).item<int>();\n else\n n_equal_bins = 1;\n }\n\n Tensor bin_edges = linspace(first_edge, last_edge, n_equal_bins + 1, ScalarType.Float64, requires_grad: true);\n return (bin_edges, (first_edge, last_edge, n_equal_bins));\n }\n\n /// <summary>\n /// Determine the outer bin edges to use, from either the data or the range argument\n /// </summary>\n /// <param name=\"a\"></param>\n /// <param name=\"range\"></param>\n /// <returns></returns>\n /// <exception cref=\"ArgumentException\"></exception>\n private static (double, double) GetOuterEdges(Tensor a, (double min, double max)? range)\n {\n double first_edge, last_edge;\n if (range is not null) {\n (first_edge, last_edge) = range.Value;\n if (first_edge > last_edge)\n throw new ArgumentException(\"max must be larger than min in range parameter.\");\n if (double.IsInfinity(first_edge) || double.IsNaN(first_edge) || double.IsInfinity(last_edge) || double.IsNaN(last_edge))\n throw new ArgumentException($\"supplied range of [{first_edge}, {last_edge}] is not finite\");\n } else if (a.numel() == 0) {\n (first_edge, last_edge) = (0, 1);\n } else {\n (first_edge, last_edge) = (a.min().to_type(ScalarType.Float64).item<double>(), a.max().to_type(ScalarType.Float64).item<double>());\n if (double.IsInfinity(first_edge) || double.IsNaN(first_edge) || double.IsInfinity(last_edge) || double.IsNaN(last_edge))\n throw new ArgumentException($\"autodetected range of [{first_edge}, {last_edge}] is not finite\");\n }\n\n if (first_edge == last_edge)\n (first_edge, last_edge) = (first_edge - 0.5, last_edge + 0.5);\n return (first_edge, last_edge);\n }\n\n /// <summary>\n /// Check a and weights have matching shapes, and ravel both\n ///\n /// https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/histograms.py#L283\n /// </summary>\n /// <param name=\"input\"></param>\n /// <returns></returns>\n private static Tensor RavelAndCheckWeights(Tensor input)\n {\n if (input.dtype == ScalarType.Bool)\n input = input.to_type(ScalarType.Int8);\n input = input.ravel();\n\n return input;\n }\n\n #region hist_bin\n private static Dictionary<HistogramBinSelector, Func<Tensor, (double min, double max)?, Tensor>> histBinSelectors\n = new Dictionary<HistogramBinSelector, Func<Tensor, (double min, double max)?, Tensor>>()\n {\n { HistogramBinSelector.Stone, HistBinStone },\n { HistogramBinSelector.Doane, HistBinDoane },\n { HistogramBinSelector.Rice, HistBinRice },\n { HistogramBinSelector.Scott, HistBinScott },\n { HistogramBinSelector.Sqrt, HistBinSqrt },\n { HistogramBinSelector.Sturges, HistBinSturges },\n };\n\n /// <summary>\n /// Square root histogram bin estimator.\n ///\n /// Bin width is inversely proportional to the data size. Used by many\n /// programs for its simplicity.\n ///\n /// https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/histograms.py#L32\n /// </summary>\n /// <param name=\"x\"> Input data that is to be histogrammed, trimmed to range. May not be empty. </param>\n /// <param name=\"_\"></param>\n /// <returns> An estimate of the optimal bin width for the given data. </returns>\n private static Tensor HistBinSqrt(Tensor x, (double min, double max)? _)\n => Ptp(x) / sqrt(x.numel());\n\n /// <summary>\n /// Sturges histogram bin estimator.\n ///\n /// A very simplistic estimator based on the assumption of normality of\n /// the data.This estimator has poor performance for non-normal data,\n /// which becomes especially obvious for large data sets.The estimate\n /// depends only on size of the data.\n ///\n /// https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/histograms.py#L53\n /// </summary>\n /// <param name=\"x\"> Input data that is to be histogrammed, trimmed to range. May not be empty. </param>\n /// <param name=\"_\"></param>\n /// <returns> An estimate of the optimal bin width for the given data. </returns>\n private static Tensor HistBinSturges(Tensor x, (double min, double max)? _)\n => Ptp(x) / (log2(x.numel()) + 1);\n\n /// <summary>\n /// Rice histogram bin estimator.\n ///\n /// Another simple estimator with no normality assumption. It has better\n /// performance for large data than Sturges, but tends to overestimate\n /// the number of bins. The number of bins is proportional to the cube\n /// root of data size (asymptotically optimal). The estimate depends\n /// only on size of the data.\n ///\n /// https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/histograms.py#L76\n /// </summary>\n /// <param name=\"x\"> Input data that is to be histogrammed, trimmed to range. May not be empty. </param>\n /// <param name=\"_\"></param>\n /// <returns> An estimate of the optimal bin width for the given data. </returns>\n private static Tensor HistBinRice(Tensor x, (double min, double max)? _)\n => Ptp(x) / (2 * pow(x.numel(), 1.0 / 3.0));\n\n /// <summary>\n /// Scott histogram bin estimator.\n ///\n /// The binwidth is proportional to the standard deviation of the data\n /// and inversely proportional to the cube root of data size\n /// (asymptotically optimal).\n ///\n /// https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/histograms.py#L100\n /// </summary>\n /// <param name=\"x\"> Input data that is to be histogrammed, trimmed to range. May not be empty. </param>\n /// <param name=\"_\"></param>\n /// <returns> An estimate of the optimal bin width for the given data. </returns>\n private static Tensor HistBinScott(Tensor x, (double min, double max)? _)\n => Math.Pow(24.0 * Math.Pow(Math.PI, 0.5) / x.numel(), 1.0 / 3.0) * std(x, false);\n\n /// <summary>\n /// Histogram bin estimator based on minimizing the estimated integrated squared error (ISE).\n ///\n /// The number of bins is chosen by minimizing the estimated ISE against the unknown true distribution.\n /// The ISE is estimated using cross-validation and can be regarded as a generalization of Scott's rule.\n /// https://en.wikipedia.org/wiki/Histogram#Scott.27s_normal_reference_rule\n /// \n /// This paper by Stone appears to be the origination of this rule.\n /// http://digitalassets.lib.berkeley.edu/sdtr/ucb/text/34.pdf\n ///\n /// https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/histograms.py#L122\n /// </summary>\n /// <param name=\"x\"> Input data that is to be histogrammed, trimmed to range. May not be empty. </param>\n /// <param name=\"range\"> The lower and upper range of the bins. </param>\n /// <returns> An estimate of the optimal bin width for the given data. </returns>\n private static Tensor HistBinStone(Tensor x, (double min, double max)? range)\n {\n long n = x.numel();\n Tensor ptp_x = Ptp(x);\n if (n <= 1 || (ptp_x == 0).item<bool>())\n return 0;\n\n double Jhat(int nbins)\n {\n Tensor hh = ptp_x / nbins;\n Tensor pk = torch.histogram(x, bins: nbins, range: range).hist / n;\n return ((2 - (n + 1) * pk.dot(pk)) / hh).to_type(ScalarType.Float64).item<double>();\n }\n\n int nbinsUpperBound = Math.Max(100, Convert.ToInt32(Math.Sqrt(n)));\n int nbins = 0;\n double jhatTemp = double.PositiveInfinity;\n foreach (int item in Enumerable.Range(1, nbinsUpperBound + 1)) {\n double jhat = Jhat(item);\n if (jhat < jhatTemp) {\n jhatTemp = jhat;\n nbins = item;\n }\n }\n return ptp_x / nbins;\n }\n\n /// <summary>\n /// Doane's histogram bin estimator.\n ///\n /// Improved version of Sturges' formula which works better for\n /// non-normal data. See\n /// stats.stackexchange.com/questions/55134/doanes-formula-for-histogram-binning\n ///\n /// https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/histograms.py#L164\n /// </summary>\n /// <param name=\"x\"> Input data that is to be histogrammed, trimmed to range. May not be empty. </param>\n /// <param name=\"_\"></param>\n /// <returns> An estimate of the optimal bin width for the given data. </returns>\n private static Tensor HistBinDoane(Tensor x, (double min, double max)? _)\n {\n long size = x.numel();\n if (size > 2) {\n Tensor sg1 = sqrt(6.0 * (size - 2) / ((size + 1.0) * (size + 3)));\n Tensor sigma = x.std();\n if ((sigma > 0.0).item<bool>()) {\n Tensor temp = x - x.mean();\n temp = true_divide(temp, sigma);\n temp = float_power(temp, 3);\n Tensor g1 = temp.mean();\n return Ptp(x) / (1.0 + log2(size) + log2(1.0 + absolute(g1) / sg1));\n }\n }\n return 0.0;\n }\n #endregion\n\n /// <summary>\n /// This implementation avoids the problem of signed integer arrays having a\n /// peak-to-peak value that cannot be represented with the array's data type.\n /// This function returns an value for signed integer arrays.\n ///\n /// https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/histograms.py#L22\n /// </summary>\n /// <param name=\"input\"></param>\n /// <returns></returns>\n private static Tensor Ptp(Tensor input)\n => subtract(input.max(), input.min());\n }\n}\n" }, { "alpha_fraction": 0.5765171647071838, "alphanum_fraction": 0.581134557723999, "avg_line_length": 47.90322494506836, "blob_id": "3cf7aa6ce150e34123514fd8f9e6fc47a418fc21", "content_id": "002d9beb2a1dfb6de8138779dfb5b9f20b942529", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1516, "license_type": "permissive", "max_line_length": 152, "num_lines": 31, "path": "/src/TorchSharp/NN/OneHot.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class nn\n {\n public static partial class functional\n {\n /// <summary>\n /// Takes LongTensor with index values of shape (*) and returns a tensor of shape (*, num_classes) that have zeros\n /// everywhere except where the index of last dimension matches the corresponding value of the input tensor, in which case it will be 1.\n /// </summary>\n /// <param name=\"x\">Category values of any shape</param>\n /// <param name=\"num_classes\">Total number of classes.\n /// If set to -1, the number of classes will be inferred as one greater than the largest class value in the input tensor</param>\n /// <returns></returns>\n public static Tensor one_hot(Tensor x, long num_classes = -1)\n {\n if (x.dtype != ScalarType.Int64) throw new ArgumentException(\"OneHot input tensor must have elements of type Int64\");\n var res = THSNN_one_hot(x.Handle, num_classes);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6079510450363159, "alphanum_fraction": 0.6106014251708984, "avg_line_length": 48.04999923706055, "blob_id": "9d19f3a2be7c947ca2161f9d3db47750d5605e5e", "content_id": "e85cf9adedb3907930819c446b109a444e143eb8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4905, "license_type": "permissive", "max_line_length": 220, "num_lines": 100, "path": "/src/TorchSharp/Distributions/Weibull.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n using static torch.distributions;\n\n namespace Modules\n {\n /// <summary>\n /// Samples from a two-parameter Weibull distribution.\n /// </summary>\n public class Weibull : TransformedDistribution\n {\n internal Weibull(Tensor scale, Tensor concentration, Tensor concentration_reciprocal, Distribution base_distribution, torch.distributions.transforms.Transform[] transforms, torch.Generator generator = null) :\n base(base_distribution, transforms, generator)\n {\n this.scale = scale;\n this.concentration = concentration;\n this.concentration_reciprocal = concentration_reciprocal;\n }\n\n private Tensor scale;\n private Tensor concentration;\n private Tensor concentration_reciprocal;\n\n public override Tensor mean =>\n WrappedTensorDisposeScope(() => scale * torch.exp(torch.lgamma(1 + concentration_reciprocal)));\n\n public override Tensor mode =>\n WrappedTensorDisposeScope(() => scale * ((concentration - 1) / concentration).pow(concentration_reciprocal));\n\n public override Tensor variance =>\n WrappedTensorDisposeScope(() =>\n scale.pow(2) * (torch.exp(torch.lgamma(1 + 2 * concentration_reciprocal)) - torch.exp(2 * torch.lgamma(1 + concentration_reciprocal)))\n );\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n public override Tensor entropy() =>\n torch.WrappedTensorDisposeScope(() => euler_constant * (1 - concentration_reciprocal) + torch.log(scale * concentration_reciprocal) + 1);\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n public override Distribution expand(Size batch_shape, Distribution instance = null)\n {\n var cExp = concentration.expand(batch_shape);\n var cExpR = cExp.reciprocal();\n var nScale = scale.expand(batch_shape);\n\n var transforms = new torch.distributions.transforms.Transform[] {\n new distributions.transforms.PowerTransform(cExpR),\n new torch.distributions.transforms.AffineTransform(0, nScale)\n };\n\n var newDistribution = ((instance == null)\n ? new Weibull(nScale, cExp, cExpR, base_distribution.expand(batch_shape), transforms, generator)\n : instance) as Weibull;\n return newDistribution;\n }\n }\n }\n\n\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Samples from a two-parameter Weibull distribution.\n /// </summary>\n /// <param name=\"concentration\">Concentration parameter of distribution (k/shape).</param>\n /// <param name=\"scale\">Scale parameter of the distribution.</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Weibull Weibull(Tensor scale, Tensor concentration, torch.Generator generator = null)\n {\n var locScale = torch.broadcast_tensors(scale, concentration);\n scale = locScale[0].alias().DetachFromDisposeScope();\n concentration = locScale[1].alias().DetachFromDisposeScope();\n var concentration_reciprocal = concentration.reciprocal();\n\n var base_dist = Exponential(torch.ones_like(scale), generator);\n var transforms = new torch.distributions.transforms.Transform[] {\n new torch.distributions.transforms.PowerTransform(exponent: concentration_reciprocal),\n new torch.distributions.transforms.AffineTransform(0, -torch.ones_like(scale))\n };\n return new Weibull(scale, concentration, concentration_reciprocal, base_dist, transforms, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 25.733333587646484, "blob_id": "bc2955eff95ae662a7f6769ab474ff413d4b8e34", "content_id": "4721c34b3aadbfdfcbdceeedd5298a6c31e4e754", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 400, "license_type": "permissive", "max_line_length": 130, "num_lines": 15, "path": "/src/TorchAudio/ResamplingMethod.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n /// <summary>\n /// Resampling method\n /// </summary>\n public enum ResamplingMethod\n {\n sinc_interpolation,\n kaiser_window\n }\n }\n}" }, { "alpha_fraction": 0.5194174647331238, "alphanum_fraction": 0.5206310749053955, "avg_line_length": 23.264705657958984, "blob_id": "bd8a178e9a2fcf833c1093dbec009388d3ebc380", "content_id": "98994fb2aafd882a05f66014cea8f79416d250aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 824, "license_type": "permissive", "max_line_length": 130, "num_lines": 34, "path": "/src/TorchVision/HorizontalFlip.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class HorizontalFlip : ITransform\n {\n internal HorizontalFlip()\n {\n }\n\n public Tensor call(Tensor input)\n {\n return input.flip(-1);\n }\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Flip the image horizontally.\n /// </summary>\n /// <returns></returns>\n static public ITransform HorizontalFlip()\n {\n return new HorizontalFlip();\n }\n }\n }\n}" }, { "alpha_fraction": 0.6583850979804993, "alphanum_fraction": 0.6677018404006958, "avg_line_length": 31.299999237060547, "blob_id": "b184bd7fa55def0a6837624b95307b75d9dd940c", "content_id": "61e8fba631ab37509f5bf4c89cdadf9a788d4172", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 322, "license_type": "permissive", "max_line_length": 130, "num_lines": 10, "path": "/src/TorchSharp/Tensor/Enums/compute_mode.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nnamespace TorchSharp\n{\n public enum compute_mode\n {\n use_mm_for_euclid_dist_if_necessary = 0,\n use_mm_for_euclid_dist = 1,\n donot_use_mm_for_euclid_dist = 2\n }\n}" }, { "alpha_fraction": 0.5763434767723083, "alphanum_fraction": 0.5806084871292114, "avg_line_length": 45.893333435058594, "blob_id": "4a159ecade26f7eccda61e2064220689fdcc26e4", "content_id": "424da18d5c7789a634d0d03b41255d4a45fedc58", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3517, "license_type": "permissive", "max_line_length": 139, "num_lines": 75, "path": "/src/TorchSharp/NN/Pooling/LPPool1d.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a LPPool1D module.\n /// </summary>\n public sealed class LPPool1d : torch.nn.Module<Tensor, Tensor>\n {\n internal LPPool1d(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_LPPool1d_forward(handle.DangerousGetHandle(), tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies a 1D power-average pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"norm_type\">The LP norm (exponent)</param>\n /// <param name=\"kernelSize\">The size of the window</param>\n /// <param name=\"stride\">The stride of the window. Default value is kernel_size</param>\n /// <param name=\"ceil_mode\">Use ceil instead of floor to compute the output shape</param>\n /// <returns></returns>\n public static LPPool1d LPPool1d(double norm_type, long kernelSize, long? stride = null, bool ceil_mode = false)\n {\n return stride.HasValue ?\n LPPool1d(norm_type, new long[] { kernelSize }, new long[] { stride.Value }, ceil_mode) :\n LPPool1d(norm_type, new long[] { kernelSize }, null);\n }\n\n /// <summary>\n /// Applies a 1D power-average pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"norm_type\">The LP norm (exponent)</param>\n /// <param name=\"kernelSize\">The size of the window</param>\n /// <param name=\"strides\">The stride of the window. Default value is kernel_size</param>\n /// <param name=\"ceil_mode\">Use ceil instead of floor to compute the output shape</param>\n /// <returns></returns>\n private static LPPool1d LPPool1d(double norm_type, long[] kernelSize, long[] strides = null, bool ceil_mode = false)\n {\n unsafe {\n fixed (long* pkernelSize = kernelSize, pstrides = strides) {\n var handle = THSNN_LPPool1d_ctor(norm_type, (IntPtr)pkernelSize, (IntPtr)pstrides, ceil_mode, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new LPPool1d(handle, boxedHandle);\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.4348173439502716, "alphanum_fraction": 0.438812792301178, "avg_line_length": 39.80745315551758, "blob_id": "4bd0bc2cf22bbd2f81ce53bbeb99bc8b0f53daa6", "content_id": "0c4aa26f57b0487737df613c52f34494c554a763", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 26280, "license_type": "permissive", "max_line_length": 198, "num_lines": 644, "path": "/src/TorchSharp/Distributions/Constraints.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace TorchSharp\n{\n\n public static partial class torch\n {\n public static partial class distributions\n {\n public static partial class constraints\n {\n /// <summary>\n /// Abstract base class for constraints.\n /// \n /// A constraint object represents a region over which a variable is valid, e.g. within which a variable can be optimized.\n /// </summary>\n /// <remarks>\n /// // It's not ideal to use a '_' first in a public .NET type name, but that's what Pytorch does for all contraint types.\n /// </remarks>\n public abstract class Constraint\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"is_discrete\">Whether constrained space is discrete.</param>\n /// <param name=\"event_dim\">\n /// Number of rightmost dimensions that together define an event.\n /// The check() method will remove this many dimensions when computing validity.\n /// </param>\n protected Constraint(bool is_discrete, int event_dim)\n {\n this.is_discrete = is_discrete;\n this.event_dim = event_dim;\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n protected Constraint() : this(false, 0)\n {\n }\n\n /// <summary>\n /// Returns a byte tensor of sample_shape + batch_shape indicating whether each event in value satisfies this constraint.\n /// </summary>\n /// <param name=\"value\"></param>\n /// <returns></returns>\n public abstract Tensor check(Tensor value);\n\n /// <summary>\n /// Whether constrained space is discrete.\n /// </summary>\n public virtual bool is_discrete { get; protected set; }\n\n /// <summary>\n /// Number of rightmost dimensions that together define an event.\n /// The check() method will remove this many dimensions when computing validity.\n /// </summary>\n public virtual int event_dim { get; protected set; }\n\n public override string ToString()\n {\n return this.GetType().Name + \"()\";\n }\n }\n\n /// <summary>\n /// Placeholder for variables whose support depends on other variables.\n /// These variables obey no simple coordinate-wise constraints.\n /// </summary>\n public class _Dependent : Constraint\n {\n public _Dependent(bool is_discrete = false, int event_dim = 0) : base(is_discrete, event_dim) { }\n\n public override Tensor check(Tensor value)\n {\n throw new ArgumentException(\"Cannot determine validity of dependent constraint\");\n }\n }\n\n /// <summary>\n /// Wraps a constraint by aggregating over ``reinterpreted_batch_ndims``-many\n /// dims in :meth:`check`, so that an event is valid only if all its\n /// independent entries are valid.\n /// </summary>\n public class _IndependentConstraint : Constraint\n {\n public _IndependentConstraint(Constraint base_constraint, int reinterpreted_batch_ndims)\n {\n\n }\n\n public override Tensor check(Tensor value)\n {\n throw new NotImplementedException();\n }\n\n public override string ToString()\n {\n return this.GetType().Name + \"()\";\n }\n\n public Constraint base_constraint { get; private set; }\n\n /// <summary>\n /// Whether constrained space is discrete.\n /// </summary>\n public override bool is_discrete { get => base_constraint.is_discrete; }\n\n /// <summary>\n /// Number of rightmost dimensions that together define an event.\n /// The check() method will remove this many dimensions when computing validity.\n /// </summary>\n public override int event_dim { get => base_constraint.event_dim; }\n\n }\n\n /// <summary>\n /// Constrain to the two values {0, 1}.\n /// </summary>\n public class _Boolean : Constraint\n {\n public _Boolean() : base(true, 0) { }\n\n public override Tensor check(Tensor value) => (value == 0) | (value == 1);\n }\n\n /// <summary>\n /// Constrain to one-hot vectors.\n /// </summary>\n public class _OneHot : Constraint\n {\n public _OneHot() : base(true, 1) { }\n\n public override Tensor check(Tensor value)\n {\n var is_boolean = (value == 0) | (value == 1);\n var is_normalized = value.sum(-1).eq(1);\n return is_boolean.all(-1) & is_normalized;\n }\n }\n\n /// <summary>\n /// Constrain to an integer interval [lower_bound, upper_bound].\n /// </summary>\n public class _IntegerInterval : Constraint\n {\n public _IntegerInterval(long lower_bound, long upper_bound) : base(true, 0)\n {\n this.lower_bound = lower_bound;\n this.upper_bound = upper_bound;\n }\n\n public long lower_bound { get; private set; }\n\n public long upper_bound { get; private set; }\n\n public override Tensor check(Tensor value)\n {\n return (value % 1 == 0) & (lower_bound <= value) & (value <= upper_bound);\n }\n\n public override string ToString()\n {\n return $\"{GetType().Name}(lower_bound={lower_bound},upper_bound={upper_bound})\";\n }\n }\n\n /// <summary>\n /// Constrain to an integer interval [-inf, upper_bound].\n /// </summary>\n public class _IntegerLessThan : Constraint\n {\n public _IntegerLessThan(long upper_bound) : base(true, 0)\n {\n this.upper_bound = upper_bound;\n }\n\n public long upper_bound { get; private set; }\n\n public override Tensor check(Tensor value)\n {\n return (value % 1 == 0) & (value <= upper_bound);\n }\n\n public override string ToString()\n {\n return $\"{GetType().Name}(upper_bound={upper_bound})\";\n }\n }\n\n /// <summary>\n /// Constrain to an integer interval [lower_bound, inf].\n /// </summary>\n public class _IntegerGreaterThan : Constraint\n {\n public _IntegerGreaterThan(long lower_bound) : base(true, 0)\n {\n this.lower_bound = lower_bound;\n }\n\n public long lower_bound { get; private set; }\n\n public override Tensor check(Tensor value)\n {\n return (value % 1 == 0) & (lower_bound <= value);\n }\n\n public override string ToString()\n {\n return $\"{GetType().Name}(lower_bound={lower_bound})\";\n }\n }\n\n /// <summary>\n /// Trivially constrain to the extended real numbers [-inf, inf].\n /// </summary>\n public class _Real : Constraint\n {\n public _Real() : base(false, 0) { }\n\n public override Tensor check(Tensor value) => value.eq(value); // False only for NaN.\n }\n\n /// <summary>\n /// Constrain to an interval [lower_bound, upper_bound].\n /// </summary>\n public class _Interval : Constraint\n {\n public _Interval(double lower_bound, double upper_bound) : base(true, 0)\n {\n this.lower_bound = lower_bound;\n this.upper_bound = upper_bound;\n }\n\n public double lower_bound { get; private set; }\n\n public double upper_bound { get; private set; }\n\n public override Tensor check(Tensor value)\n {\n return (lower_bound <= value) & (value <= upper_bound);\n }\n\n public override string ToString()\n {\n return $\"{GetType().Name}(lower_bound={lower_bound},upper_bound={upper_bound})\";\n }\n }\n\n /// <summary>\n /// Constrain to an interval [lower_bound, upper_bound).\n /// </summary>\n public class _HalfOpenInterval : Constraint\n {\n public _HalfOpenInterval(double lower_bound, double upper_bound) : base(true, 0)\n {\n this.lower_bound = lower_bound;\n this.upper_bound = upper_bound;\n }\n\n public double lower_bound { get; private set; }\n\n public double upper_bound { get; private set; }\n\n public override Tensor check(Tensor value)\n {\n return (lower_bound <= value) & (value < upper_bound);\n }\n\n public override string ToString()\n {\n return $\"{GetType().Name}(lower_bound={lower_bound},upper_bound={upper_bound})\";\n }\n }\n\n /// <summary>\n /// Constrain to an interval (lower_bound, inf].\n /// </summary>\n public class _GreaterThan : Constraint\n {\n public _GreaterThan(double lower_bound) : base(true, 0)\n {\n this.lower_bound = lower_bound;\n }\n\n public double lower_bound { get; private set; }\n\n public override Tensor check(Tensor value)\n {\n return (lower_bound < value);\n }\n\n public override string ToString()\n {\n return $\"{GetType().Name}(lower_bound={lower_bound})\";\n }\n }\n\n /// <summary>\n /// Constrain to an interval [lower_bound, inf].\n /// </summary>\n public class _GreaterThanEq : Constraint\n {\n public _GreaterThanEq(double lower_bound) : base(true, 0)\n {\n this.lower_bound = lower_bound;\n }\n\n public double lower_bound { get; private set; }\n\n public override Tensor check(Tensor value)\n {\n return (lower_bound <= value);\n }\n\n public override string ToString()\n {\n return $\"{GetType().Name}(lower_bound={lower_bound})\";\n }\n }\n\n /// <summary>\n /// Constrain to an integer interval [-inf, upper_bound).\n /// </summary>\n public class _LessThan : Constraint\n {\n public _LessThan(double upper_bound) : base(true, 0)\n {\n this.upper_bound = upper_bound;\n }\n\n public double upper_bound { get; private set; }\n\n public override Tensor check(Tensor value)\n {\n return (value < upper_bound);\n }\n\n public override string ToString()\n {\n return $\"{GetType().Name}(upper_bound={upper_bound})\";\n }\n }\n\n /// <summary>\n /// Constrain to the unit simplex in the innermost (rightmost) dimension.\n /// Specifically: `x >= 0` and `x.sum(-1) == 1`.\n /// </summary>\n public class _Simplex : Constraint\n {\n public _Simplex() : base(false, 1) { }\n\n public override Tensor check(Tensor value)\n {\n var is_positive = value >= 0;\n return is_positive.all(dim: -1) & ((value.sum(-1) - 1).abs() < 1e-6);\n }\n }\n\n /// <summary>\n /// Constrain to nonnegative integer values summing to at most an upper bound.\n /// </summary>\n public class _Multinomial : Constraint\n {\n public _Multinomial(long upper_bound) : base(true, 1)\n {\n this.upper_bound = upper_bound;\n }\n\n public long upper_bound { get; private set; }\n\n public override Tensor check(Tensor x)\n {\n return (x >= 0).all(dim: -1) & (x.sum(dim: -1) <= upper_bound);\n }\n\n public override string ToString()\n {\n return $\"{GetType().Name}(upper_bound={upper_bound})\";\n }\n }\n\n /// <summary>\n /// Constrain to lower-triangular square matrices.\n /// </summary>\n public class _LowerTriangular : Constraint\n {\n public _LowerTriangular() : base(false, 2) { }\n\n public override Tensor check(Tensor value)\n {\n var tril = value.tril();\n var newshape = new long[value.shape.Length - 1];\n var i = 0;\n for (; i < value.shape.Length - 2; i++) newshape[i] = value.shape[i];\n newshape[i] = -1;\n return (tril == value).view(newshape).min(-1).values;\n }\n }\n\n /// <summary>\n /// Constrain to lower-triangular square matrices with positive diagonals.\n /// </summary>\n public class _LowerCholesky : Constraint\n {\n public _LowerCholesky() : base(false, 2) { }\n\n public override Tensor check(Tensor value)\n {\n var value_tril = value.tril();\n var newshape = new long[value.shape.Length - 1];\n var i = 0;\n for (; i < value.shape.Length - 2; i++) newshape[i] = value.shape[i];\n newshape[i] = -1;\n\n var lower_triangular = (value_tril == value).view(newshape).min(-1).values;\n var positive_diagonal = (value.diagonal(dim1: -2, dim2: -1) > 0).min(-1).values;\n return lower_triangular & positive_diagonal;\n }\n }\n\n /// <summary>\n /// Constrain to lower-triangular square matrices with positive diagonals and each\n /// row vector being of unit length.\n /// </summary>\n public class _CorrCholesky : Constraint\n {\n public _CorrCholesky() : base(false, 2) { }\n\n public override Tensor check(Tensor value)\n {\n var tol = torch.finfo(value.dtype).eps * value.size(-1) * 10; // 10 is an adjustable fudge factor\n var row_norm = torch.linalg.norm(value.detach(), dims: new[] { -1L });\n var unit_row_norm = (row_norm - 1.0).abs().le(tol).all(dim: -1);\n return lc.check(value) & unit_row_norm;\n }\n\n private _LowerCholesky lc = new _LowerCholesky();\n }\n\n /// <summary>\n /// Constrain to square matrices.\n /// </summary>\n public class _Square : Constraint\n {\n public _Square() : base(false, 2) { }\n\n public override Tensor check(Tensor value)\n {\n var newshape = new long[value.shape.Length - 2];\n var i = 0;\n for (; i < value.shape.Length - 2; i++) newshape[i] = value.shape[i];\n\n return torch.full(\n size: newshape,\n value: (value.shape[value.shape.Length - 2] == value.shape[value.shape.Length - 1]),\n dtype: torch.@bool,\n device: value.device);\n }\n }\n\n /// <summary>\n /// Constrain to symmetric square matrices.\n /// </summary>\n public class _Symmetric : _Square\n {\n\n public override Tensor check(Tensor value)\n {\n var square_check = base.check(value);\n if (!square_check.all().item<bool>())\n return square_check;\n\n return value.isclose(value.mT, atol: 1e-6).all(-2).all(-1);\n }\n }\n\n /// <summary>\n /// Constrain to positive-semidefinite matrices.\n /// </summary>\n public class _PositiveSemiDefinite : _Symmetric\n {\n public override Tensor check(Tensor value)\n {\n var sym_check = base.check(value);\n if (!sym_check.all().item<bool>())\n return sym_check;\n return torch.linalg.eigvalsh(value).ge(0).all(-1);\n }\n }\n\n /// <summary>\n /// Constrain to positive-definite matrices.\n /// </summary>\n public class _PositiveDefinite : _Symmetric\n {\n public override Tensor check(Tensor value)\n {\n var sym_check = base.check(value);\n if (!sym_check.all().item<bool>())\n return sym_check;\n return torch.linalg.cholesky_ex(value).info.eq(0);\n }\n }\n\n /// <summary>\n /// Constraint functor that applies a sequence of constraints cseq at the submatrices at dimension dim,\n /// each of size lengths[dim], in a way compatible with torch.cat().\n /// </summary>\n public class _Cat : Constraint\n {\n public _Cat(IList<Constraint> cseq, long dim = 0, IList<long> lengths = null)\n {\n this.cseq = cseq;\n if (lengths == null) {\n lengths = Enumerable.Repeat(1L, cseq.Count).ToList();\n }\n this.lengths = lengths;\n this.dim = dim;\n }\n\n public override Tensor check(Tensor value)\n {\n var checks = new List<Tensor>();\n long start = 0;\n for (int i = 0; i < cseq.Count; i++) {\n var length = lengths[i];\n var constr = cseq[i];\n var v = value.narrow(dim, start, length);\n checks.Add(constr.check(v));\n start = start + length;\n }\n return torch.cat(checks, dim);\n }\n\n public override bool is_discrete { get => cseq.Any(c => c.is_discrete); }\n\n public override int event_dim { get => cseq.Select(c => c.event_dim).Max(); }\n\n private IList<Constraint> cseq;\n private IList<long> lengths;\n private long dim;\n }\n /// <summary>\n /// Constraint functor that applies a sequence of constraints cseq at the submatrices at dimension dim,\n /// each of size lengths[dim], in a way compatible with torch.cat().\n /// </summary>\n public class _Stack : Constraint\n {\n public _Stack(IList<Constraint> cseq, int dim = 0)\n {\n this.cseq = cseq;\n this.dim = dim;\n }\n\n public override Tensor check(Tensor value)\n {\n var vs = Enumerable.Range(0, (int)value.size(dim)).Select(i => value.select(dim, i)).ToList();\n return torch.stack(Enumerable.Range(0, vs.Count).Select(i => cseq[i].check(vs[i])));\n }\n\n public override bool is_discrete { get => cseq.Any(c => c.is_discrete); }\n\n public override int event_dim {\n get {\n var dim = cseq.Select(c => c.event_dim).Max();\n\n if (this.dim + dim < 0)\n dim += 1;\n\n return dim;\n }\n }\n\n private IList<Constraint> cseq;\n private int dim;\n }\n\n\n // Public interface\n\n public static _Dependent dependent = new _Dependent();\n\n public static _IndependentConstraint independent(Constraint base_constraint, int reinterpreted_batch_ndims) => new _IndependentConstraint(base_constraint, reinterpreted_batch_ndims);\n\n public static _Boolean boolean = new _Boolean();\n\n public static _OneHot one_hot = new _OneHot();\n\n public static _IntegerGreaterThan nonnegative_integer = new _IntegerGreaterThan(0);\n\n public static _IntegerGreaterThan positive_integer = new _IntegerGreaterThan(1);\n\n public static _IntegerInterval integer_interval(long lb, long ub) => new _IntegerInterval(lb, ub);\n\n public static _Real real = new _Real();\n\n public static _IndependentConstraint real_vector = independent(real, 1);\n\n public static _GreaterThan positive = new _GreaterThan(0.0);\n\n public static _GreaterThanEq nonnegative = new _GreaterThanEq(0.0);\n\n public static _GreaterThan greater_than(double lower_bound) => new _GreaterThan(lower_bound);\n\n public static _GreaterThanEq greater_than_eq(double lower_bound) => new _GreaterThanEq(lower_bound);\n\n public static _LessThan less_than(double upper_bound) => new _LessThan(upper_bound);\n\n public static _Multinomial multinomial(long upper_bound) => new _Multinomial(upper_bound);\n\n public static _Interval unit_interval = new _Interval(0.0, 1.0);\n\n public static _Interval interval(double lower_bound, double upper_bound) => new _Interval(lower_bound, upper_bound);\n\n public static _HalfOpenInterval half_open_interval(double lower_bound, double upper_bound) => new _HalfOpenInterval(lower_bound, upper_bound);\n\n public static _Simplex simplex = new _Simplex();\n\n public static _LowerTriangular lower_triangular = new _LowerTriangular();\n\n public static _LowerCholesky lower_cholesky = new _LowerCholesky();\n\n public static _CorrCholesky corr_cholesky = new _CorrCholesky();\n\n public static _Square square = new _Square();\n\n public static _Symmetric symmetric = new _Symmetric();\n\n public static _PositiveSemiDefinite positive_semidefinite = new _PositiveSemiDefinite();\n\n public static _PositiveDefinite positive_definite = new _PositiveDefinite();\n\n public static _Cat cat(IList<Constraint> cseq, long dim = 0, IList<long> lengths = null) => new _Cat(cseq, dim, lengths);\n\n public static _Stack stack(IList<Constraint> cseq, int dim = 0) => new _Stack(cseq, dim);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.724047064781189, "alphanum_fraction": 0.729131281375885, "avg_line_length": 55.49357604980469, "blob_id": "5fb8e36a159d1e848460f94553714ec1910c1d35", "content_id": "efeaec1b39afa5b447abb4589b9a19077394b658", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 74741, "license_type": "permissive", "max_line_length": 420, "num_lines": 1323, "path": "/src/TorchSharp/PInvoke/LibTorchSharp.THSNN.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp.PInvoke\n{\n#pragma warning disable CA2101\n internal static partial class NativeMethods\n {\n [DllImport(\"LibTorchSharp\", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]\n internal static extern void THSNN_Module_save(\n torch.nn.Module.HType handle,\n [MarshalAs(UnmanagedType.LPStr)] string location);\n\n [DllImport(\"LibTorchSharp\", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]\n [return: MarshalAs(UnmanagedType.LPStr)]\n internal static extern string THSNN_Module_name(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]\n internal static extern IntPtr THSNN_custom_module(\n [MarshalAs(UnmanagedType.LPStr)] string name,\n ForwardFunctionC forward,\n out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern torch.nn.utils.rnn.PackedSequence.HType THSNN_RNN_forward_with_packed_input(torch.nn.Module.HType module, torch.nn.utils.rnn.PackedSequence.HType input, IntPtr h_0, out IntPtr h_n);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern torch.nn.utils.rnn.PackedSequence.HType THSNN_pack_padded_sequence(IntPtr input, IntPtr lengths, [MarshalAs(UnmanagedType.U1)] bool batch_first, [MarshalAs(UnmanagedType.U1)] bool enforce_sorted);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern torch.nn.utils.rnn.PackedSequence.HType THSNN_pack_sequence(IntPtr[] sequences, int sequences_len, [MarshalAs(UnmanagedType.U1)] bool enforce_sorted);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern torch.nn.utils.rnn.PackedSequence.HType THSNN_LSTM_forward_with_packed_input(torch.nn.Module.HType module, torch.nn.utils.rnn.PackedSequence.HType input, IntPtr h_0, IntPtr c_0, out IntPtr h_n, out IntPtr c_n);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern torch.nn.utils.rnn.PackedSequence.HType THSNN_GRU_forward_with_packed_input(torch.nn.Module.HType module, torch.nn.utils.rnn.PackedSequence.HType input, IntPtr h_0, out IntPtr h_n);\n\n [DllImport(\"LibTorchSharp\")]\n // align_corners -- 0=None, 1=true, 2=false\n internal static extern IntPtr THSNN_Upsample_ctor(IntPtr size, int size_length, IntPtr scale_factor, int scale_factor_length, byte mode, byte align_corners, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n // align_corners -- 0=None, 1=true, 2=false\n internal static extern IntPtr THSNN_interpolate(IntPtr input, IntPtr size, int size_len, IntPtr scale_factor, int scale_factor_len, byte mode, byte align_corners, [MarshalAs(UnmanagedType.U1)] bool recompute_scale_factor);\n\n [DllImport(\"LibTorchSharp\")]\n // align_corners -- 0=None, 1=true, 2=false\n internal static extern IntPtr THSNN_grid_sample(IntPtr input, IntPtr grid, byte mode, byte padding_mode, byte align_corners);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AlphaDropout_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AlphaDropout_ctor(double p, [MarshalAs(UnmanagedType.U1)] bool inplace, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_alpha_dropout(IntPtr input, double p, [MarshalAs(UnmanagedType.U1)] bool training, [MarshalAs(UnmanagedType.U1)] bool inplace);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Bilinear_forward(torch.nn.Module.HType module, IntPtr input1, IntPtr input2);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Bilinear_bias(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Bilinear_set_bias(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Bilinear_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Bilinear_set_weight(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Bilinear_ctor(long in1_features, long in2_features, long output_size, [MarshalAs(UnmanagedType.U1)] bool bias, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_functional_bilinear(IntPtr input1, IntPtr input2, IntPtr weights, IntPtr bias);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_CosineSimilarity_ctor(long dim, double eps, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_CosineSimilarity_forward(torch.nn.Module.HType module, IntPtr input1, IntPtr input2);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_dropout(IntPtr input, double p, [MarshalAs(UnmanagedType.U1)] bool training, [MarshalAs(UnmanagedType.U1)] bool inplace);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_dropout2d(IntPtr input, double p, [MarshalAs(UnmanagedType.U1)] bool training, [MarshalAs(UnmanagedType.U1)] bool inplace);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Dropout_ctor(double p, [MarshalAs(UnmanagedType.U1)] bool inplace, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Dropout_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Dropout1d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Dropout1d_ctor(double p, [MarshalAs(UnmanagedType.U1)] bool inplace, out IntPtr pBoxedModule);\n\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Dropout2d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Dropout2d_ctor(double p, [MarshalAs(UnmanagedType.U1)] bool inplace, out IntPtr pBoxedModule);\n\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Embedding_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Embedding_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Embedding_set_weight(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Embedding_ctor(long num_embeddings, long embedding_dims, long padding_idx, [MarshalAs(UnmanagedType.U1)] bool hasPI, double max_norm, [MarshalAs(UnmanagedType.U1)] bool hasMN, double norm_type, [MarshalAs(UnmanagedType.U1)] bool scale_grad_by_freq, [MarshalAs(UnmanagedType.U1)] bool sparse, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Embedding_from_pretrained(IntPtr embeddings, [MarshalAs(UnmanagedType.U1)] bool freeze, long padding_idx, [MarshalAs(UnmanagedType.U1)] bool hasPI, double max_norm, [MarshalAs(UnmanagedType.U1)] bool hasMN, double norm_type, [MarshalAs(UnmanagedType.U1)] bool scale_grad_by_freq, [MarshalAs(UnmanagedType.U1)] bool sparse, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Dropout3d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Dropout3d_ctor(double p, [MarshalAs(UnmanagedType.U1)] bool inplace, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_dropout3d(IntPtr input, double p, [MarshalAs(UnmanagedType.U1)] bool training, [MarshalAs(UnmanagedType.U1)] bool inplace);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_EmbeddingBag_forward(torch.nn.Module.HType module, IntPtr tensor, IntPtr offsets, IntPtr per_sample_weights);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_EmbeddingBag_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_EmbeddingBag_set_weight(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_EmbeddingBag_ctor(long num_embeddings, long embedding_dims, double max_norm, [MarshalAs(UnmanagedType.U1)] bool hasMN, double norm_type, [MarshalAs(UnmanagedType.U1)] bool scale_grad_by_freq, long mode, [MarshalAs(UnmanagedType.U1)] bool sparse, [MarshalAs(UnmanagedType.U1)] bool include_last_offset, long padding_idx, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_EmbeddingBag_from_pretrained(IntPtr embeddings, [MarshalAs(UnmanagedType.U1)] bool freeze, double max_norm, [MarshalAs(UnmanagedType.U1)] bool hasMN, double norm_type, [MarshalAs(UnmanagedType.U1)] bool scale_grad_by_freq, long mode, [MarshalAs(UnmanagedType.U1)] bool sparse, [MarshalAs(UnmanagedType.U1)] bool include_last_offset, long padding_idx, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_FeatureAlphaDropout_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_FeatureAlphaDropout_ctor(double p, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_feature_alpha_dropout(IntPtr input, double p, [MarshalAs(UnmanagedType.U1)] bool training, [MarshalAs(UnmanagedType.U1)] bool inplace);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_fold(IntPtr input, long out1, long out2, long kernel1, long kernel2, long stride1, long stride, long pad1, long pad2, long dil1, long dil2);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_unfold(IntPtr input, long kernel1, long kernel2, long stride1, long stride, long pad1, long pad2, long dil1, long dil2);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_cross_entropy(IntPtr srct, IntPtr trgt, IntPtr wgt, long ignore_index, [MarshalAs(UnmanagedType.U1)] bool hasII, long reduction, double smooting);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_binary_cross_entropy(IntPtr srct, IntPtr trgt, IntPtr wgt, long reduction);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_binary_cross_entropy_with_logits(IntPtr srct, IntPtr trgt, IntPtr wgt, long reduction, IntPtr posWeights);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_cosine_embedding_loss(IntPtr input1, IntPtr input2, IntPtr trgt, double margin, long reduction);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ctc_loss(IntPtr log_probs, IntPtr targets, IntPtr input_lengths, IntPtr target_lengths, long blank, [MarshalAs(UnmanagedType.U1)] bool zero_infinity, long reduction);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_hinge_embedding_loss(IntPtr input, IntPtr trgt, double margin, long reduction);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_huber_loss(IntPtr input, IntPtr trgt, double delta, long reduction);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_margin_ranking_loss(IntPtr input1, IntPtr input2, IntPtr target, double margin, long reduction);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_multilabel_margin_loss(IntPtr input, IntPtr target, long reduction);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_multilabel_soft_margin_loss(IntPtr input, IntPtr target, IntPtr weight, long reduction);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_multi_margin_loss(IntPtr input, IntPtr target, long p, double margin, IntPtr weight, long reduction);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_mse_loss(IntPtr srct, IntPtr trgt, long reduction);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_l1_loss(IntPtr srct, IntPtr trgt, long reduction);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_nll_loss(IntPtr srct, IntPtr trgt, IntPtr wgt, long reduction);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_poisson_loss(IntPtr srct, IntPtr trgt, [MarshalAs(UnmanagedType.U1)] bool logInput, [MarshalAs(UnmanagedType.U1)] bool full, float eps, long reduction);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_kl_div_loss(IntPtr input, IntPtr target, long reduction, [MarshalAs(UnmanagedType.U1)] bool logTarget);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_smooth_l1_loss(IntPtr srct, IntPtr trgt, long reduction, double beta);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_soft_margin_loss(IntPtr srct, IntPtr trgt, long reduction);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_triplet_margin_loss(IntPtr anchor, IntPtr positive, IntPtr negative, double margin, long p, double eps, [MarshalAs(UnmanagedType.U1)] bool swap, long reduction);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_triplet_margin_with_distance_loss(IntPtr anchor, IntPtr positive, IntPtr negative, DistanceFunctionNative? distance_function, double margin, [MarshalAs(UnmanagedType.U1)] bool swap, long reduction);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Optimizer_dispose(torch.optim.Optimizer.HType handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Optimizer_zero_grad(torch.optim.Optimizer.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Optimizer_step(torch.optim.Optimizer.HType module, torch.optim.Optimizer.LossClosure closure);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Optimizer_getParameters(torch.optim.Optimizer.HType module, AllocatePinnedArray allocator);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Module_dispose(torch.nn.Module.HType handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Module_to_device_dtype(torch.nn.Module.HType module, sbyte dtype, long deviceType, long deviceIndex);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Module_to_device(torch.nn.Module.HType module, long deviceType, long deviceIndex);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Module_to_dtype(torch.nn.Module.HType module, sbyte dtype);\n\n [DllImport(\"LibTorchSharp\", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]\n internal static extern IntPtr THSNN_Module_load([MarshalAs(UnmanagedType.LPStr)] string location);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Module_train(torch.nn.Module.HType module, [MarshalAs(UnmanagedType.U1)] bool on);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Module_eval(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n [return: MarshalAs(UnmanagedType.U1)]\n internal static extern bool THSNN_Module_is_training(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Module_zero_grad(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Module_get_named_parameters(torch.nn.Module.HType module, AllocatePinnedArray allocator1, AllocatePinnedArray allocator2);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Module_get_named_buffers(torch.nn.Module.HType module, AllocatePinnedArray allocator1, AllocatePinnedArray allocator2);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Module_get_parameters(torch.nn.Module.HType module, AllocatePinnedArray allocator, [MarshalAs(UnmanagedType.U1)] bool recurse);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_AnyModule_dispose(torch.nn.BoxedModule.HType handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_RNN_forward(torch.nn.Module.HType module, IntPtr input, IntPtr h_0, out IntPtr h_n);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_RNN_flatten_parameters(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_RNN_bias_ih(torch.nn.Module.HType module, long idx);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_RNN_bias_hh(torch.nn.Module.HType module, long idx);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_RNN_set_bias_ih(torch.nn.Module.HType module, IntPtr tensor, long idx);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_RNN_set_bias_hh(torch.nn.Module.HType module, IntPtr tensor, long idx);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_RNN_weight_ih(torch.nn.Module.HType module, long idx);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_RNN_weight_hh(torch.nn.Module.HType module, long idx);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_RNN_set_weight_ih(torch.nn.Module.HType module, IntPtr tensor, long idx);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_RNN_set_weight_hh(torch.nn.Module.HType module, IntPtr tensor, long idx);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_RNN_ctor(long input_size, long hidden_size, long num_layers, long nonlinearity, [MarshalAs(UnmanagedType.U1)] bool bias, [MarshalAs(UnmanagedType.U1)] bool batchFirst, double dropout, [MarshalAs(UnmanagedType.U1)] bool bidirectional, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_RNNCell_forward(torch.nn.Module.HType module, IntPtr input, IntPtr h_0);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_RNNCell_bias_ih(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_RNNCell_set_bias_ih(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_RNNCell_bias_hh(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_RNNCell_set_bias_hh(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_RNNCell_weight_ih(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_RNNCell_set_weight_ih(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_RNNCell_weight_hh(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_RNNCell_set_weight_hh(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_RNNCell_ctor(long input_size, long hidden_size, long nonlinearity, [MarshalAs(UnmanagedType.U1)] bool bias, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Linear_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Linear_bias(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Linear_set_bias(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Linear_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Linear_set_weight(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Linear_ctor(long input_size, long output_size, [MarshalAs(UnmanagedType.U1)] bool bias, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_functional_linear(IntPtr input, IntPtr weights, IntPtr bias);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Flatten_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Flatten_ctor(long startDim, long endDim, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Identity_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Identity_ctor(out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LSTMCell_forward(torch.nn.Module.HType module, IntPtr input, IntPtr h_0, IntPtr c_0, out IntPtr c_n);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LSTMCell_bias_ih(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_LSTMCell_set_bias_ih(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LSTMCell_bias_hh(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_LSTMCell_set_bias_hh(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LSTMCell_weight_ih(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_LSTMCell_set_weight_ih(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LSTMCell_weight_hh(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_LSTMCell_set_weight_hh(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LSTMCell_ctor(long input_size, long hidden_size, [MarshalAs(UnmanagedType.U1)] bool bias, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_PackedSequence_dispose(IntPtr handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_PackedSequence_data(torch.nn.utils.rnn.PackedSequence.HType handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_PackedSequence_batch_sizes(torch.nn.utils.rnn.PackedSequence.HType handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_PackedSequence_sorted_indices(torch.nn.utils.rnn.PackedSequence.HType handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_PackedSequence_unsorted_indices(torch.nn.utils.rnn.PackedSequence.HType handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_pad_packed_sequence(torch.nn.utils.rnn.PackedSequence.HType sequence, [MarshalAs(UnmanagedType.U1)] bool batch_first, double padding_value, long total_length, out IntPtr res1, out IntPtr res2);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_pad_sequence(IntPtr[] sequences, int sequences_len, [MarshalAs(UnmanagedType.U1)] bool batch_first, double padding_value);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_MultiheadAttention_forward(torch.nn.Module.HType module, IntPtr query, IntPtr key, IntPtr value, IntPtr key_padding_mask, [MarshalAs(UnmanagedType.U1)] bool need_weights, IntPtr attn_mask, out IntPtr res1, out IntPtr res2);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_MultiheadAttention_ctor(long embeded_dim, long num_heads, double dropout, [MarshalAs(UnmanagedType.U1)] bool bias, [MarshalAs(UnmanagedType.U1)] bool add_bias_kv, [MarshalAs(UnmanagedType.U1)] bool add_zero_attn, long kdim, long vdim, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_one_hot(IntPtr self, long num_classes);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_PairwiseDistance_forward(torch.nn.Module.HType module, IntPtr input1, IntPtr input2);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_PairwiseDistance_ctor(double p, double eps, [MarshalAs(UnmanagedType.U1)] bool keep_dim, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_PixelUnshuffle_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_PixelUnshuffle_ctor(long downscaleFactor, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_PixelShuffle_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_PixelShuffle_ctor(long upscaleFactor, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_GRUCell_forward(torch.nn.Module.HType module, IntPtr input, IntPtr h_0);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_GRUCell_bias_ih(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_GRUCell_set_bias_ih(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_GRUCell_bias_hh(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_GRUCell_set_bias_hh(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_GRUCell_weight_ih(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_GRUCell_set_weight_ih(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_GRUCell_weight_hh(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_GRUCell_set_weight_hh(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_GRUCell_ctor(long input_size, long hidden_size, [MarshalAs(UnmanagedType.U1)] bool bias, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LSTM_forward(torch.nn.Module.HType module, IntPtr input, IntPtr h_0, IntPtr c_0, out IntPtr h_n, out IntPtr c_n);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_LSTM_flatten_parameters(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LSTM_ctor(long input_size, long hidden_size, long num_layers, [MarshalAs(UnmanagedType.U1)] bool bias, [MarshalAs(UnmanagedType.U1)] bool batchFirst, double dropout, [MarshalAs(UnmanagedType.U1)] bool bidirectional, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_GRU_flatten_parameters(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_GRU_ctor(long input_size, long hidden_size, long num_layers, [MarshalAs(UnmanagedType.U1)] bool bias, [MarshalAs(UnmanagedType.U1)] bool batchFirst, double dropout, [MarshalAs(UnmanagedType.U1)] bool bidirectional, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_GRU_forward(torch.nn.Module.HType module, IntPtr input, IntPtr h_0, out IntPtr h_n);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LBFGS_ctor(IntPtr parameters, int len, double learningRate, long max_iter, long max_eval, double tolerange_grad, double tolerance_change, long history_size);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_LBFGS_set_lr(torch.optim.Optimizer.HType optimizer, double lr);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Sequential_ctor();\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Transformer_forward(torch.nn.Module.HType module, IntPtr src, IntPtr tgt, IntPtr src_mask, IntPtr tgt_mask, IntPtr memory_mask, IntPtr src_key_padding_mask, IntPtr tgt_key_padding_mask, IntPtr memory_key_padding_mask);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Transformer_ctor(long d_model, long nhead, long num_encoder_layers, long num_decoder_layers, long dim_feedforward, double dropout, long activation, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_TransformerDecoder_forward(torch.nn.Module.HType module, IntPtr tgt, IntPtr memory, IntPtr tgt_mask, IntPtr memory_mask, IntPtr tgt_key_padding_mask, IntPtr memory_key_padding_mask);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_TransformerDecoder_ctor(torch.nn.Module.HType decoder_layer, long num_layers, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_TransformerDecoderLayer_forward(torch.nn.Module.HType module, IntPtr tgt, IntPtr memory, IntPtr tgt_mask, IntPtr memory_mask, IntPtr tgt_key_padding_mask, IntPtr memory_key_padding_mask);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_TransformerDecoderLayer_ctor(long d_model, long nhead, long dim_feedforward, double dropout, long activation, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_TransformerEncoderLayer_forward(torch.nn.Module.HType module, IntPtr src, IntPtr src_mask, IntPtr src_key_padding_mask);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_TransformerEncoderLayer_ctor(long d_model, long nhead, long dim_feedforward, double dropout, long activation, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Upsample_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_TransformerEncoder_ctor(torch.nn.Module.HType encoder_layer, long num_layers, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_TransformerEncoder_forward(torch.nn.Module.HType module, IntPtr src, IntPtr src_mask, IntPtr src_key_padding_mask);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_pad(IntPtr input, IntPtr pad, int pad_length, byte mode, double value);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_affine_grid(IntPtr theta, IntPtr size, int size_len, [MarshalAs(UnmanagedType.U1)] bool align_corners);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_CELU_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_CELU_ctor(double alpha, [MarshalAs(UnmanagedType.U1)] bool inplace, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LeakyReLU_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LeakyReLU_ctor(double negative_slope, [MarshalAs(UnmanagedType.U1)] bool inplace, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LogSoftmax_forward(torch.nn.Module.HType handle, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LogSoftmax_ctor(long dim, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm3d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm3d_bias(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_InstanceNorm3d_set_bias(torch.nn.Module.HType module, IntPtr bias);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm3d_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_InstanceNorm3d_set_weight(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_InstanceNorm3d_reset_stats(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm3d_get_mean(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm3d_get_var(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm3d_get_batches(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_InstanceNorm3d_set_mean(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_InstanceNorm3d_set_var(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm3d_ctor(long features, double eps, double momentum, [MarshalAs(UnmanagedType.U1)] bool affine, [MarshalAs(UnmanagedType.U1)] bool track_running_stats, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LayerNorm_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LayerNorm_bias(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_LayerNorm_set_bias(torch.nn.Module.HType module, IntPtr bias);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LayerNorm_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_LayerNorm_set_weight(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LayerNorm_ctor(IntPtr norm_shape, long norm_shape_len, double eps, [MarshalAs(UnmanagedType.U1)] bool elementwise_affine, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm2d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm2d_bias(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_InstanceNorm2d_set_bias(torch.nn.Module.HType module, IntPtr bias);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm2d_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_InstanceNorm2d_set_weight(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_InstanceNorm2d_reset_stats(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm2d_get_mean(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm2d_get_var(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm2d_get_batches(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_InstanceNorm2d_set_mean(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_InstanceNorm2d_set_var(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm2d_ctor(long features, double eps, double momentum, [MarshalAs(UnmanagedType.U1)] bool affine, [MarshalAs(UnmanagedType.U1)] bool track_running_stats, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm1d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm1d_bias(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_InstanceNorm1d_set_bias(torch.nn.Module.HType module, IntPtr bias);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm1d_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_InstanceNorm1d_set_weight(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_InstanceNorm1d_reset_stats(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm1d_get_mean(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm1d_get_var(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm1d_get_batches(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_InstanceNorm1d_set_mean(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_InstanceNorm1d_set_var(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_InstanceNorm1d_ctor(long features, double eps, double momentum, [MarshalAs(UnmanagedType.U1)] bool affine, [MarshalAs(UnmanagedType.U1)] bool track_running_stats, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Conv1d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Conv1d_bias(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Conv1d_set_bias(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Conv1d_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Conv1d_set_weight(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Conv1d_ctor(long inputChannel, long outputChannel, long kernelSize, long stride, long padding, long dilation, long paddingMode, long groups, [MarshalAs(UnmanagedType.U1)] bool bias, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Conv2d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Conv2d_bias(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Conv2d_set_bias(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Conv2d_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Conv2d_set_weight(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Conv2d_ctor(long inputChannel, long outputChannel, long kernelSize, long stride, long padding, long dilation, long paddingMode, long groups, [MarshalAs(UnmanagedType.U1)] bool bias, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Conv2d_ctor_1(long inputChannel, long outputChannel, long kernelSizeX, long kernelSizeY, long strideX, long strideY, long paddingX, long paddingY, long dilationX, long dilationY, long paddingMode, long groups, [MarshalAs(UnmanagedType.U1)] bool bias, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Conv3d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Conv3d_bias(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Conv3d_set_bias(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Conv3d_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_Conv3d_set_weight(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Conv3d_ctor(long inputChannel, long outputChannel, long kernelSize, long stride, long padding, long dilation, long paddingMode, long groups, [MarshalAs(UnmanagedType.U1)] bool bias, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Conv3d_ctor_1(long inputChannel, long outputChannel, long kernelSizeX, long kernelSizeY, long kernelSizeZ, long strideX, long strideY, long strideZ, long paddingX, long paddingY, long paddingZ, long dilationX, long dilationY, long dilationZ, long paddingMode, long groups, [MarshalAs(UnmanagedType.U1)] bool bias, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConvTranspose1d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConvTranspose1d_bias(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_ConvTranspose1d_set_bias(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConvTranspose1d_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_ConvTranspose1d_set_weight(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConvTranspose1d_ctor(long inputChannel, long outputChannel, long kernelSize, long stride, long padding, long outputPadding, long dilation, long paddingMode, long groups, [MarshalAs(UnmanagedType.U1)] bool bias, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConvTranspose3d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConvTranspose3d_bias(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_ConvTranspose3d_set_bias(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConvTranspose3d_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_ConvTranspose3d_set_weight(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConvTranspose3d_ctor(long inputChannel, long outputChannel, long kernelSize, long stride, long padding, long outputPadding, long dilation, long paddingMode, long groups, [MarshalAs(UnmanagedType.U1)] bool bias, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm1d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm1d_bias(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_BatchNorm1d_set_bias(torch.nn.Module.HType module, IntPtr bias);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm1d_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_BatchNorm1d_set_weight(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_BatchNorm1d_reset_stats(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm1d_get_mean(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm1d_get_var(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm1d_get_batches(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_BatchNorm1d_set_mean(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_BatchNorm1d_set_var(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm1d_ctor(long features, double eps, double momentum, [MarshalAs(UnmanagedType.U1)] bool affine, [MarshalAs(UnmanagedType.U1)] bool track_running_stats, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_GroupNorm_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_GroupNorm_bias(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_GroupNorm_set_bias(torch.nn.Module.HType module, IntPtr bias);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_GroupNorm_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_GroupNorm_set_weight(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_GroupNorm_ctor(long num_groups, long num_channels, double eps, [MarshalAs(UnmanagedType.U1)] bool affine, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Unflatten_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Unflatten_ctor(long dim, IntPtr shape, long shape_len, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_batch_norm(IntPtr input, IntPtr running_mean, IntPtr running_var, IntPtr weight, IntPtr bias, [MarshalAs(UnmanagedType.U1)] bool training, double momentum, double eps);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_group_norm(IntPtr input, long num_groups, IntPtr weight, IntPtr bias, double eps);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_instance_norm(IntPtr input, IntPtr running_mean, IntPtr running_var, IntPtr weight, IntPtr bias, [MarshalAs(UnmanagedType.U1)] bool use_input_stats, double momentum, double eps);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern unsafe IntPtr THSNN_layer_norm(IntPtr input, long* normalized_shape, long normalized_shape_len, IntPtr weight, IntPtr bias, double eps);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_local_response_norm(IntPtr input, long size, double alpha, double beta, double k);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConvTranspose2d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConvTranspose2d_bias(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_ConvTranspose2d_set_bias(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConvTranspose2d_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_ConvTranspose2d_set_weight(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConvTranspose2d_ctor(long inputChannel, long outputChannel, long kernelSize, long stride, long padding, long outputPadding, long dilation, long paddingMode, long groups, [MarshalAs(UnmanagedType.U1)] bool bias, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm2d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm2d_bias(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_BatchNorm2d_set_bias(torch.nn.Module.HType module, IntPtr bias);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm2d_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_BatchNorm2d_set_weight(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_BatchNorm2d_reset_stats(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm2d_get_mean(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm2d_get_var(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm2d_get_batches(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_BatchNorm2d_set_mean(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_BatchNorm2d_set_var(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm2d_ctor(long features, double eps, double momentum, [MarshalAs(UnmanagedType.U1)] bool affine, [MarshalAs(UnmanagedType.U1)] bool track_running_stats, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm3d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm3d_bias(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_BatchNorm3d_set_bias(torch.nn.Module.HType module, IntPtr bias);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm3d_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_BatchNorm3d_set_weight(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_BatchNorm3d_reset_stats(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm3d_get_mean(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm3d_get_var(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm3d_get_batches(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_BatchNorm3d_set_mean(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_BatchNorm3d_set_var(torch.nn.Module.HType module, IntPtr weight);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_BatchNorm3d_ctor(long features, double eps, double momentum, [MarshalAs(UnmanagedType.U1)] bool affine, [MarshalAs(UnmanagedType.U1)] bool track_running_stats, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_MaxPool1d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_MaxPool1d_forward_with_indices(torch.nn.Module.HType module, IntPtr tensor, out IntPtr indices);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_MaxPool1d_ctor(IntPtr pkernelSize, IntPtr pStrides, IntPtr pPadding, IntPtr pDilation, [MarshalAs(UnmanagedType.U1)] bool ceilMode, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_MaxUnpool3d_forward(torch.nn.Module.HType module, IntPtr tensor, IntPtr indices, IntPtr outSize, int outputSizeLength);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_MaxUnpool3d_ctor(IntPtr pkernelSize, int kernelSizeLength, IntPtr pstrides, int stridesLength, IntPtr pPadding, int paddingLength, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ELU_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ELU_ctor(double alpha, [MarshalAs(UnmanagedType.U1)] bool inplace, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_GELU_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_GELU_ctor(out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_GLU_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_GLU_ctor(long dim, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Hardshrink_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Hardshrink_ctor(double lambd, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Hardtanh_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Hardtanh_ctor(double min_val, double max_val, [MarshalAs(UnmanagedType.U1)] bool inplace, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Mish_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Mish_ctor(out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_PReLU_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_PReLU_ctor(long nparams, double init, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_PReLU_weight(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSNN_PReLU_set_weight(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReLU_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReLU_ctor([MarshalAs(UnmanagedType.U1)] bool inplace, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReLU6_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReLU6_ctor([MarshalAs(UnmanagedType.U1)] bool inplace, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_RReLU_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_RReLU_ctor(double lower, double upper, [MarshalAs(UnmanagedType.U1)] bool inplace, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_scaled_dot_product_attention(IntPtr query, IntPtr key, IntPtr value, IntPtr attention_mask, double p, [MarshalAs(UnmanagedType.U1)] bool casual);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_SELU_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_SELU_ctor([MarshalAs(UnmanagedType.U1)] bool inplace, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Sigmoid_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Sigmoid_ctor(out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_SiLU_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_SiLU_ctor(out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Softmax_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Softmax_ctor(long dim, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Softmax2d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Softmax2d_ctor(out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Softmin_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Softmin_ctor(long dim, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Softplus_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Softplus_ctor(double beta, double threshold, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Softshrink_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Softshrink_ctor(double lambd, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Softsign_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Softsign_ctor(out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Tanh_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Tanh_ctor(out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Tanhshrink_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Tanhshrink_ctor(out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Threshold_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_Threshold_ctor(double threshold, double value, [MarshalAs(UnmanagedType.U1)] bool inplace, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LocalResponseNorm_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LocalResponseNorm_ctor(long size, double alpha, double beta, double k, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConstantPad1d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConstantPad1d_ctor(double value, long padding, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConstantPad1d_ctor_tuple(double value, long padding_left, long padding_right, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConstantPad2d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConstantPad2d_ctor(double value, long padding, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConstantPad2d_ctor_tuple(double value, long padding_left, long padding_right, long padding_top, long padding_bottom, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConstantPad3d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConstantPad3d_ctor(double value, long padding, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ConstantPad3d_ctor_tuple(double value, long padding_left, long padding_right, long padding_top, long padding_bottom, long padding_front, long padding_back, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReflectionPad1d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReflectionPad1d_ctor(long padding, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReflectionPad1d_ctor_tuple(long padding_left, long padding_right, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReflectionPad2d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReflectionPad2d_ctor(long padding, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReflectionPad2d_ctor_tuple(long padding_left, long padding_right, long padding_top, long padding_bottom, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReflectionPad3d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReflectionPad3d_ctor(long padding, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReflectionPad3d_ctor_tuple(long padding_left, long padding_right, long padding_top, long padding_bottom, long padding_front, long padding_back, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReplicationPad1d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReplicationPad1d_ctor(long padding, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReplicationPad1d_ctor_tuple(long padding_left, long padding_right, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReplicationPad2d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReplicationPad2d_ctor(long padding, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReplicationPad2d_ctor_tuple(long padding_left, long padding_right, long padding_top, long padding_bottom, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReplicationPad3d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReplicationPad3d_ctor(long padding, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ReplicationPad3d_ctor_tuple(long padding_left, long padding_right, long padding_top, long padding_bottom, long padding_front, long padding_back, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ZeroPad2d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ZeroPad2d_ctor(long padding, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_ZeroPad2d_ctor_tuple(long padding_left, long padding_right, long padding_top, long padding_bottom, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AdaptiveAvgPool1d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AdaptiveAvgPool1d_ctor(IntPtr psizes, int length, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AdaptiveAvgPool2d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AdaptiveAvgPool2d_ctor(IntPtr psizes, int length, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AdaptiveAvgPool3d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AdaptiveAvgPool3d_ctor(IntPtr psizes, int length, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AdaptiveMaxPool1d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AdaptiveMaxPool1d_ctor(IntPtr psizes, int length, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AdaptiveMaxPool2d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AdaptiveMaxPool2d_ctor(IntPtr psizes, int length, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AdaptiveMaxPool3d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AdaptiveMaxPool3d_ctor(IntPtr psizes, int length, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AvgPool1d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AvgPool1d_ctor(IntPtr pkernelSize, IntPtr pstrides, IntPtr ppadding, [MarshalAs(UnmanagedType.U1)] bool ceil_mode, [MarshalAs(UnmanagedType.U1)] bool count_include_pad, long divisor_override, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AvgPool2d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AvgPool2d_ctor(IntPtr pkernelSize, int kernelSizeLength, IntPtr pstrides, int stridesLength, IntPtr ppadding, int paddingLength, [MarshalAs(UnmanagedType.U1)] bool ceil_mode, [MarshalAs(UnmanagedType.U1)] bool count_include_pad, long divisor_override, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AvgPool3d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_AvgPool3d_ctor(IntPtr pkernelSize, int kernelSizeLength, IntPtr pstrides, int stridesLength, IntPtr ppadding, int paddingLength, [MarshalAs(UnmanagedType.U1)] bool ceil_mode, [MarshalAs(UnmanagedType.U1)] bool count_include_pad, long divisor_override, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_FractionalMaxPool2d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_FractionalMaxPool2d_forward_with_indices(torch.nn.Module.HType module, IntPtr tensor, out IntPtr indices);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_FractionalMaxPool2d_ctor(IntPtr pkernelSize, int kernelSizeLength, IntPtr pOutputSize, int sizeLength, IntPtr pOutputRatio, int ratioLength, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_FractionalMaxPool3d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_FractionalMaxPool3d_forward_with_indices(torch.nn.Module.HType module, IntPtr tensor, out IntPtr indices);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_FractionalMaxPool3d_ctor(IntPtr pkernelSize, int kernelSizeLength, IntPtr pOutputSize, int sizeLength, IntPtr pOutputRatio, int ratioLength, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LPPool1d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LPPool1d_ctor(double norm_type, IntPtr pkernelSize, IntPtr pstrides, [MarshalAs(UnmanagedType.U1)] bool ceil_mode, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LPPool2d_forward(IntPtr module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_LPPool2d_ctor(double norm_type, IntPtr pkernelSize, int kernelSizeLength, IntPtr pstrides, int stridesLength, [MarshalAs(UnmanagedType.U1)] bool ceil_mode, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_MaxPool2d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_MaxPool2d_forward_with_indices(torch.nn.Module.HType module, IntPtr tensor, out IntPtr indices);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_MaxPool2d_ctor(IntPtr pkernelSize, int kernelSizeLength, IntPtr pstrides, int stridesLength, IntPtr pPadding, int paddingLength, IntPtr pDilation, int dilationLength, [MarshalAs(UnmanagedType.U1)] bool ceilMode, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_MaxPool3d_forward(torch.nn.Module.HType module, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_MaxPool3d_forward_with_indices(torch.nn.Module.HType module, IntPtr tensor, out IntPtr indices);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_MaxPool3d_ctor(IntPtr pkernelSize, int kernelSizeLength, IntPtr pstrides, int stridesLength, IntPtr pPadding, int paddingLength, IntPtr pDilation, int dilationLength, [MarshalAs(UnmanagedType.U1)] bool ceilMode, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_MaxUnpool1d_forward(torch.nn.Module.HType module, IntPtr tensor, IntPtr indices, IntPtr outSize);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_MaxUnpool1d_ctor(IntPtr pkernelSize, IntPtr pStrides, IntPtr pPadding, out IntPtr pBoxedModule);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_MaxUnpool2d_forward(torch.nn.Module.HType module, IntPtr tensor, IntPtr indices, IntPtr outSize, int outputSizeLength);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSNN_MaxUnpool2d_ctor(IntPtr pkernelSize, int kernelSizeLength, IntPtr pstrides, int stridesLength, IntPtr pPadding, int paddingLength, out IntPtr pBoxedModule);\n }\n#pragma warning restore CA2101\n}\n" }, { "alpha_fraction": 0.491913378238678, "alphanum_fraction": 0.49916040897369385, "avg_line_length": 49.28888702392578, "blob_id": "d3e50c633a00b5643035cb061f8c7e95fe041587", "content_id": "623f332b3a15e94c5923257d1117b1fd569e56d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 11315, "license_type": "permissive", "max_line_length": 129, "num_lines": 225, "path": "/src/TorchVision/Utils.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing static TorchSharp.torch;\nusing static TorchSharp.torchvision.io;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static class utils\n {\n /// <summary>\n /// Make a grid of images.\n /// </summary>\n /// <param name=\"tensors\">A list of images all of the same size.</param>\n /// <param name=\"nrow\">Number of images displayed in each row of the grid.\n /// The final grid size is (B / nrow, nrow). Default: 8.</param>\n /// <param name=\"padding\">Amount of padding. Default: 2.</param>\n /// <param name=\"normalize\">If true, shift the image to the range (0, 1),\n /// by the min and max values specified by value_range. Default: false.</param>\n /// <param name=\"value_range\">Tuple (min, max) where min and max are numbers,\n /// then these numbers are used to normalize the image. By default, min and max\n /// are computed from the tensor.</param>\n /// <param name=\"scale_each\">If true, scale each image in the batch of\n /// images separately rather than the (min, max) over all images. Default: false.</param>\n /// <param name=\"pad_value\">Value for the padded pixels. Default: 0.</param>\n /// <returns>The tensor containing grid of images.</returns>\n public static Tensor make_grid(\n IEnumerable<Tensor> tensors,\n long nrow = 8,\n int padding = 2,\n bool normalize = false,\n (double low, double high)? value_range = null,\n bool scale_each = false,\n double pad_value = 0.0f)\n {\n return make_grid(torch.stack(tensors, dim: 0), nrow, padding, normalize, value_range, scale_each, pad_value);\n }\n\n /// <summary>\n /// Make a grid of images.\n /// </summary>\n /// <param name=\"tensor\">4D mini-batch Tensor of shape (B x C x H x W).</param>\n /// <param name=\"nrow\">Number of images displayed in each row of the grid.\n /// The final grid size is (B / nrow, nrow). Default: 8.</param>\n /// <param name=\"padding\">Amount of padding. Default: 2.</param>\n /// <param name=\"normalize\">If true, shift the image to the range (0, 1),\n /// by the min and max values specified by value_range. Default: false.</param>\n /// <param name=\"value_range\">Tuple (min, max) where min and max are numbers,\n /// then these numbers are used to normalize the image. By default, min and max\n /// are computed from the tensor.</param>\n /// <param name=\"scale_each\">If true, scale each image in the batch of\n /// images separately rather than the (min, max) over all images. Default: false.</param>\n /// <param name=\"pad_value\">Value for the padded pixels. Default: 0.</param>\n /// <returns>The tensor containing grid of images.</returns>\n public static Tensor make_grid(\n Tensor tensor,\n long nrow = 8,\n int padding = 2,\n bool normalize = false,\n (double low, double high)? value_range = null,\n bool scale_each = false,\n double pad_value = 0.0f)\n {\n using var _ = torch.NewDisposeScope();\n\n if (tensor.Dimensions == 2) // Single image H x W\n {\n tensor = tensor.unsqueeze(0);\n }\n if (tensor.Dimensions == 3) // Single image\n {\n if (tensor.size(0) == 1) // Convert single channel to 3 channel\n {\n tensor = torch.cat(new[] { tensor, tensor, tensor }, 0);\n }\n tensor = tensor.unsqueeze(0);\n }\n if (tensor.Dimensions == 4 && tensor.size(1) == 1) // Single channel images\n {\n tensor = torch.cat(new[] { tensor, tensor, tensor }, 1);\n }\n\n if (normalize == true)\n {\n tensor = tensor.clone(); // avoid modifying tensor in-place\n void norm_ip(Tensor img, double low, double high)\n {\n img.clamp_(min: low, max: high);\n img.sub_(low).div_(Math.Max(high - low, 1e-5));\n }\n\n void norm_range(Tensor t, (double low, double high)? range)\n {\n if (range.HasValue)\n {\n var (low, high) = value_range.Value;\n norm_ip(t, low, high);\n }\n else\n {\n norm_ip(t, t.min().ToSingle(), t.max().ToSingle());\n }\n }\n\n if (scale_each == true)\n {\n for (long i = 0; i < tensor.size(0); ++i)\n {\n norm_range(tensor[i], value_range);\n }\n }\n else\n {\n norm_range(tensor, value_range);\n }\n }\n\n if (tensor.size(0) == 1) {\n tensor = tensor.squeeze(0);\n return tensor.MoveToOuterDisposeScope();\n }\n\n var nmaps = tensor.size(0);\n var xmaps = Math.Min(nrow, nmaps);\n var ymaps = (long)Math.Ceiling((double)nmaps / xmaps);\n var width = tensor.size(3) + padding;\n var height = tensor.size(2) + padding;\n var num_channels = tensor.size(1);\n\n var grid = tensor.new_full(new[] { num_channels, height * ymaps + padding, width * xmaps + padding }, pad_value);\n var k = 0L;\n for (long y = 0; y < ymaps; ++y)\n {\n for (long x = 0; x < xmaps; ++x)\n {\n if (k > nmaps) break;\n grid.narrow(1, y * height, height - padding).narrow(\n 2, x * width + padding, width - padding\n ).copy_(tensor[k]);\n ++k;\n }\n }\n\n return grid.MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Save a given Tensor into an image file.\n /// </summary>\n /// <param name=\"tensor\">Image to be saved. If given a mini-batch tensor,\n /// saves the tensor as a grid of images by calling make_grid.</param>\n /// <param name=\"filename\">A file name</param>\n /// <param name=\"format\">The format to use is not determined from the\n /// filename extension this parameter should always be used.</param>\n /// <param name=\"nrow\">Number of images displayed in each row of the grid.\n /// The final grid size is (B / nrow, nrow). Default: 8.</param>\n /// <param name=\"padding\">Amount of padding. Default: 2.</param>\n /// <param name=\"normalize\">If true, shift the image to the range (0, 1),\n /// by the min and max values specified by value_range. Default: false.</param>\n /// <param name=\"value_range\">Tuple (min, max) where min and max are numbers,\n /// then these numbers are used to normalize the image. By default, min and max\n /// are computed from the tensor.</param>\n /// <param name=\"scale_each\">If true, scale each image in the batch of\n /// images separately rather than the (min, max) over all images. Default: false.</param>\n /// <param name=\"pad_value\">Value for the padded pixels. Default: 0.</param>\n /// <param name=\"imager\">Imager to use instead of DefaultImager. Default: null</param>\n public static void save_image(\n Tensor tensor,\n string filename,\n ImageFormat format,\n long nrow = 8,\n int padding = 2,\n bool normalize = false,\n (double low, double high)? value_range = null,\n bool scale_each = false,\n double pad_value = 0.0f,\n Imager imager = null)\n {\n using var filestream = new FileStream(filename, FileMode.OpenOrCreate);\n save_image(tensor, filestream, format, nrow, padding, normalize, value_range, scale_each, pad_value, imager);\n }\n\n /// <summary>\n /// Save a given Tensor into an image file.\n /// </summary>\n /// <param name=\"tensor\">Image to be saved. If given a mini-batch tensor,\n /// saves the tensor as a grid of images by calling make_grid.</param>\n /// <param name=\"filestream\">A file stream</param>\n /// <param name=\"format\">The format to use is not determined from the\n /// filename extension this parameter should always be used.</param>\n /// <param name=\"nrow\">Number of images displayed in each row of the grid.\n /// The final grid size is (B / nrow, nrow). Default: 8.</param>\n /// <param name=\"padding\">Amount of padding. Default: 2.</param>\n /// <param name=\"normalize\">If true, shift the image to the range (0, 1),\n /// by the min and max values specified by value_range. Default: false.</param>\n /// <param name=\"value_range\">Tuple (min, max) where min and max are numbers,\n /// then these numbers are used to normalize the image. By default, min and max\n /// are computed from the tensor.</param>\n /// <param name=\"scale_each\">If true, scale each image in the batch of\n /// images separately rather than the (min, max) over all images. Default: false.</param>\n /// <param name=\"pad_value\">Value for the padded pixels. Default: 0.</param>\n /// <param name=\"imager\">Imager to use instead of DefaultImager. Default: null</param>\n public static void save_image(\n Tensor tensor,\n Stream filestream,\n ImageFormat format,\n long nrow = 8,\n int padding = 2,\n bool normalize = false,\n (double low, double high)? value_range = null,\n bool scale_each = false,\n double pad_value = 0.0f,\n Imager imager = null)\n {\n using var _ = torch.NewDisposeScope();\n var grid = make_grid(tensor, nrow, padding, normalize, value_range, scale_each, pad_value);\n // Add 0.5 after unnormalizing to [0, 255] to round to nearest integer\n var narr = grid.mul(255).add_(0.5).clamp_(0, 255).to(uint8, CPU);\n (imager ?? DefaultImager).EncodeImage(narr, format, filestream);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.496349036693573, "alphanum_fraction": 0.5023730993270874, "avg_line_length": 42.832000732421875, "blob_id": "10bb8eca4461847d3a2357c21461267e0113cea1", "content_id": "7c03c8e411b33a04a7dc195b0180693b13eae3f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5478, "license_type": "permissive", "max_line_length": 149, "num_lines": 125, "path": "/src/TorchVision/dsets/Utils.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing ICSharpCode.SharpZipLib.GZip;\nusing ICSharpCode.SharpZipLib.Tar;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Text;\n\n// A number of implementation details in this file have been translated from the Python version of torchvision,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/vision/blob/b78d98bb152ffb9c0c0f5365f59f475c70b1784e/torchvision/datasets/utils.py\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/vision/blob/main/LICENSE\n//\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class datasets\n {\n public static partial class utils\n {\n /// <summary>\n /// Download a Google Drive file and place it in root.\n /// </summary>\n /// <param name=\"file_id\">id of file to be downloaded</param>\n /// <param name=\"root\">Directory to place downloaded file in</param>\n /// <param name=\"filename\">Name to save the file under. If null, use the id of the file.</param>\n /// <param name=\"md5\">MD5 checksum of the download. If null, do not check</param>\n public static void download_file_from_google_drive(\n string file_id, string root, string? filename = null, string? md5 = null)\n {\n io.GDriveDownload.DownloadFileFromGoogleDrive(file_id, root, filename, md5);\n }\n\n private static void ExtractTar(string from_path, string to_path)\n {\n using (var fileStream = File.OpenRead(from_path)) {\n using (var inputStream = new GZipInputStream(fileStream)) {\n using (TarArchive tarArchive = TarArchive.CreateInputTarArchive(inputStream, Encoding.UTF8)) {\n tarArchive.ExtractContents(to_path);\n }\n }\n }\n }\n\n private static void ExtractZip(string from_path, string to_path)\n {\n ZipFile.ExtractToDirectory(from_path, to_path);\n }\n\n /// <summary>\n /// Extract an archive.\n ///\n /// The archive type and a possible compression is automatically detected from the file name.If the file is compressed\n /// but not an archive the call is dispatched to :func:`decompress`.\n /// </summary>\n /// <param name=\"from_path\">Path to the file to be extracted.</param>\n /// <param name=\"to_path\"> Path to the directory the file will be extracted to.If omitted, the directory of the file is used.</param>\n /// <param name=\"remove_finished\">If ``True``, remove the file after the extraction.</param>\n /// <returns>Path to the directory the file was extracted to.</returns>\n /// <exception cref=\"InvalidDataException\"></exception>\n /// <exception cref=\"ArgumentException\"></exception>\n public static string extract_archive(string from_path, string? to_path = null, bool remove_finished = false)\n {\n if (to_path is null) {\n to_path = Path.GetDirectoryName(from_path);\n if (to_path is null) {\n throw new InvalidDataException();\n }\n }\n\n if (Path.GetExtension(from_path) == \".zip\") {\n ExtractZip(from_path, to_path);\n } else if (from_path.EndsWith(\".tar.gz\")) {\n ExtractTar(from_path, to_path);\n } else {\n throw new ArgumentException();\n }\n\n if (remove_finished) {\n File.Delete(from_path);\n }\n\n return to_path;\n }\n\n private static string IterableToStr(IList<string> iterable)\n {\n return \"'\" + string.Join(\"', '\", iterable) + \"'\";\n }\n\n internal static string VerifyStrArg(\n string value,\n string? arg = null,\n IList<string>? valid_values = null,\n string? custom_msg = null)\n {\n if (valid_values is null) {\n return value;\n }\n\n if (!valid_values.Contains(value)) {\n string msg;\n if (custom_msg is not null) {\n msg = custom_msg;\n } else {\n msg = string.Format(\n \"Unknown value '{0}' for argument {1}. Valid values are {2}.\",\n value, arg, IterableToStr(valid_values));\n }\n throw new ArgumentException(msg);\n }\n\n return value;\n }\n }\n }\n }\n}" }, { "alpha_fraction": 0.5809458494186401, "alphanum_fraction": 0.5897189974784851, "avg_line_length": 59.79166793823242, "blob_id": "a66883da7330e945b023281ed7b3e1c752613883", "content_id": "7fbfa371a5e5f8ca1274cd63e3c802e94ec6eb6a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7295, "license_type": "permissive", "max_line_length": 195, "num_lines": 120, "path": "/src/TorchSharp/NN/Pooling/FractionalMaxPool2d.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a FractionalMaxPool2D module.\n /// </summary>\n public sealed class FractionalMaxPool2d : torch.nn.Module<Tensor, Tensor>\n {\n internal FractionalMaxPool2d(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_FractionalMaxPool2d_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public (Tensor Values, Tensor Indices) forward_with_indices(Tensor tensor)\n {\n var res = THSNN_FractionalMaxPool2d_forward_with_indices(handle, tensor.Handle, out var indices);\n if (res == IntPtr.Zero || indices == IntPtr.Zero) { torch.CheckForErrors(); }\n return (new Tensor(res), new Tensor(indices));\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies a 2D fractional max pooling over an input signal composed of several input planes.\n ///\n /// Fractional MaxPooling is described in detail in the paper Fractional MaxPooling by Ben Graham,\n /// see: https://arxiv.org/abs/1412.6071\n /// </summary>\n /// <param name=\"kernel_size\">The size of the sliding window, must be > 0.</param>\n /// <param name=\"output_size\">The target output size of the image of the form oH x oW. Can be a tuple (oH, oW) or a single number oH for a square image oH x oH</param>\n /// <param name=\"output_ratio\">If one wants to have an output size as a ratio of the input size, this option can be given. This has to be a number or tuple in the range (0, 1)</param>\n /// <returns></returns>\n public static FractionalMaxPool2d FractionalMaxPool2d(long kernel_size, long? output_size = null, double? output_ratio = null)\n {\n var pSize = output_size.HasValue ? new long[] { output_size.Value, output_size.Value } : null;\n var pRatio = output_ratio.HasValue ? new double[] { output_ratio.Value, output_ratio.Value } : null;\n return FractionalMaxPool2d(new long[] { kernel_size, kernel_size }, pSize, pRatio);\n }\n\n /// <summary>\n /// Applies a 2D fractional max pooling over an input signal composed of several input planes.\n ///\n /// Fractional MaxPooling is described in detail in the paper Fractional MaxPooling by Ben Graham,\n /// see: https://arxiv.org/abs/1412.6071\n /// </summary>\n /// <param name=\"kernel_size\">The size of the sliding window, must be > 0.</param>\n /// <param name=\"output_size\">The target output size of the image of the form oH x oW. Can be a tuple (oH, oW) or a single number oH for a square image oH x oH</param>\n /// <param name=\"output_ratio\">If one wants to have an output size as a ratio of the input size, this option can be given. This has to be a number or tuple in the range (0, 1)</param>\n /// <returns></returns>\n public static FractionalMaxPool2d FractionalMaxPool2d((long, long) kernel_size, (long, long)? output_size = null, (double, double)? output_ratio = null)\n {\n var pSize = output_size.HasValue ? new long[] { output_size.Value.Item1, output_size.Value.Item2 } : null;\n var pRatio = output_ratio.HasValue ? new double[] { output_ratio.Value.Item1, output_ratio.Value.Item2 } : null;\n return FractionalMaxPool2d(new long[] { kernel_size.Item1, kernel_size.Item2 }, pSize, pRatio);\n }\n\n /// <summary>\n /// Applies a 2D fractional max pooling over an input signal composed of several input planes.\n ///\n /// Fractional MaxPooling is described in detail in the paper Fractional MaxPooling by Ben Graham,\n /// see: https://arxiv.org/abs/1412.6071\n /// </summary>\n /// <param name=\"kernel_size\">The size of the sliding window, must be > 0.</param>\n /// <param name=\"output_size\">The target output size of the image of the form oH x oW. Can be a tuple (oH, oW) or a single number oH for a square image oH x oH</param>\n /// <param name=\"output_ratio\">If one wants to have an output size as a ratio of the input size, this option can be given. This has to be a number or tuple in the range (0, 1)</param>\n /// <returns></returns>\n public static FractionalMaxPool2d FractionalMaxPool2d(long[] kernel_size, long[] output_size = null, double[] output_ratio = null)\n {\n if (kernel_size == null || kernel_size.Length != 2)\n throw new ArgumentException(\"Kernel size must contain two elements.\");\n if (output_size != null && output_size.Length != 2)\n throw new ArgumentException(\"output_size must contain two elements.\");\n if (output_ratio != null && output_ratio.Length != 2)\n throw new ArgumentException(\"output_ratio must contain two elements.\");\n if (output_size == null && output_ratio == null)\n throw new ArgumentNullException(\"Only one of output_size and output_ratio may be specified.\");\n if (output_size != null && output_ratio != null)\n throw new ArgumentNullException(\"FractionalMaxPool2d requires specifying either an output size, or a pooling ratio.\");\n\n unsafe {\n fixed (long* pkernelSize = kernel_size, pSize = output_size) {\n fixed (double* pRatio = output_ratio) {\n var handle = THSNN_FractionalMaxPool2d_ctor(\n (IntPtr)pkernelSize, kernel_size.Length,\n (IntPtr)pSize, (output_size == null ? 0 : output_size.Length),\n (IntPtr)pRatio, (output_ratio == null ? 0 : output_ratio.Length),\n out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new FractionalMaxPool2d(handle, boxedHandle);\n }\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5725051760673523, "alphanum_fraction": 0.5847193598747253, "avg_line_length": 45.93902587890625, "blob_id": "d9db89f2063cd64749a113e672ead87206fd3d3a", "content_id": "80d32bf23060b4ae8743d26cc965a1787525f40c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3848, "license_type": "permissive", "max_line_length": 183, "num_lines": 82, "path": "/src/TorchVision/RandomResizedCrop.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class RandomResizedCrop : ITransform\n {\n public RandomResizedCrop(int height, int width, double scaleMin, double scaleMax, double ratioMin, double ratioMax)\n {\n this.height = height;\n this.width = width;\n this.scaleMax = scaleMax;\n this.scaleMin = scaleMin;\n this.ratioMax = ratioMax;\n this.ratioMin = ratioMin;\n }\n\n public Tensor call(Tensor input)\n {\n var hoffset = input.Dimensions - 2;\n var iHeight = input.shape[hoffset];\n var iWidth = input.shape[hoffset + 1];\n\n var scale = scaleMax - scaleMin;\n\n var random = new Random();\n\n // First, figure out how high and wide the crop should be.\n\n var randomScale = Math.Min(random.NextDouble() * scale + scaleMin, 1); // Preserves the aspect ratio.\n\n var h = iHeight * randomScale;\n var w = iWidth * randomScale;\n\n // Then, place the top and left corner at a random location,\n // so that the crop doesn't go outside the image boundaries.\n\n var top = (int)Math.Floor((iHeight - h) * random.NextDouble());\n var left = (int)Math.Floor((iWidth - w) * random.NextDouble());\n\n return new ResizedCrop(top, left, (int)Math.Floor(h), (int)Math.Floor(w), height, width).call(input);\n }\n\n private int height, width;\n private double scaleMin, scaleMax;\n private double ratioMin, ratioMax;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Crop a random portion of image and resize it to a given size. \n /// </summary>\n /// <param name=\"height\">Expected output height of the crop</param>\n /// <param name=\"width\">Expected output width of the crop</param>\n /// <param name=\"scaleMin\">Lower bounds for the random area of the crop</param>\n /// <param name=\"scaleMax\">Upper bounds for the random area of the crop</param>\n /// <param name=\"ratioMin\">Lower bounds for the random aspect ratio of the crop</param>\n /// <param name=\"ratioMax\">Upper bounds for the random aspect ratio of the crop</param>\n static public ITransform RandomResizedCrop(int height, int width, double scaleMin = 0.08, double scaleMax = 1.0, double ratioMin = 0.75, double ratioMax = 1.3333333333333)\n {\n return new RandomResizedCrop(height, width, scaleMin, scaleMax, ratioMin, ratioMax);\n }\n\n /// <summary>\n /// Crop a random portion of image and resize it to a given size. \n /// </summary>\n /// <param name=\"size\">Expected output size of the crop</param>\n /// <param name=\"scaleMin\">Lower for the random area of the crop</param>\n /// <param name=\"scaleMax\">Upper bounds for the random area of the crop</param>\n /// <param name=\"ratioMin\">Lower bounds for the random aspect ratio of the crop</param>\n /// <param name=\"ratioMax\">Upper bounds for the random aspect ratio of the crop</param>\n static public ITransform RandomResizedCrop(int size, double scaleMin = 0.08, double scaleMax = 1.0, double ratioMin = 0.75, double ratioMax = 1.3333333333333)\n {\n return RandomResizedCrop(size, size, scaleMin, scaleMax, ratioMin, ratioMax);\n }\n }\n }\n}" }, { "alpha_fraction": 0.4970722198486328, "alphanum_fraction": 0.5018364191055298, "avg_line_length": 52.17745590209961, "blob_id": "94b67c2591044c58c00a6aa130ae2fc19478deea", "content_id": "1048af5610d30f9b0a72b5b913eb5688dc96ece7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 47675, "license_type": "permissive", "max_line_length": 253, "num_lines": 896, "path": "/src/TorchSharp/JIT/ScriptModule.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing TorchSharp.PInvoke;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class jit\n {\n /// <summary>\n /// This class represents a TorchScript module.\n /// </summary>\n public class ScriptModule : nn.Module\n {\n internal ScriptModule(IntPtr handle) : base(new HType(handle, true, THSJIT_Module_dispose), null)\n {\n }\n\n protected override (string name, TorchSharp.Modules.Parameter parameter)[] _named_parameters()\n {\n using var pa = new PinnedArray<IntPtr>();\n using var sa = new PinnedArray<IntPtr>();\n THSJIT_Module_named_parameters(handle, pa.CreateArray, sa.CreateArray);\n CheckForErrors();\n var ptrArray = pa.Array;\n var strArray = sa.Array;\n\n return ptrArray.Select((x, i) => (Marshal.PtrToStringAnsi(strArray[i]), new TorchSharp.Modules.Parameter(x))).ToArray();\n }\n\n protected override (string name, Tensor buffer)[] _named_buffers()\n {\n using var pa = new PinnedArray<IntPtr>();\n using var sa = new PinnedArray<IntPtr>();\n THSJIT_Module_named_buffers(handle, pa.CreateArray, sa.CreateArray);\n CheckForErrors();\n var ptrArray = pa.Array;\n var strArray = sa.Array;\n\n return ptrArray.Select((x, i) => (Marshal.PtrToStringAnsi(strArray[i]), new Tensor(x))).ToArray();\n }\n\n /// <summary>\n /// Returns an enumerable of all modules in the network, yielding both the name of the module as well as the module itself.\n /// </summary>\n /// <returns>(string, Module) – Tuple of name and module</returns>\n public override IEnumerable<(string name, nn.Module module)> named_modules()\n {\n using var pa = new PinnedArray<IntPtr>();\n using var sa = new PinnedArray<IntPtr>();\n THSJIT_Module_named_modules(handle, pa.CreateArray, sa.CreateArray);\n CheckForErrors();\n var ptrArray = pa.Array;\n var strArray = sa.Array;\n\n return ptrArray.Select((x, i) => (Marshal.PtrToStringAnsi(strArray[i]), new ScriptModule(x) as nn.Module)).Where(m => !string.IsNullOrEmpty(m.Item1));\n }\n\n /// <summary>\n /// Returns an enumerable of immediate children modules, yielding both the name of the module as well as the module itself.\n /// </summary>\n /// <returns>(string, Module) – Tuple containing a name and child module</returns>\n public override IEnumerable<(string name, nn.Module module)> named_children()\n {\n using var pa = new PinnedArray<IntPtr>();\n using var sa = new PinnedArray<IntPtr>();\n THSJIT_Module_named_children(handle, pa.CreateArray, sa.CreateArray);\n CheckForErrors();\n var ptrArray = pa.Array;\n var strArray = sa.Array;\n\n return ptrArray.Select((x, i) => (Marshal.PtrToStringAnsi(strArray[i]), new ScriptModule(x) as nn.Module));\n }\n\n public int GetNumberOfInputs()\n {\n return THSJIT_Module_num_inputs(handle);\n }\n\n public int GetNumberOfOutputs()\n {\n return THSJIT_Module_num_outputs(handle);\n }\n\n /// <summary>\n /// Sets the module in evaluation mode.\n /// </summary>\n /// <remarks>\n /// Any script module that was created using torch.jit.trace() will be unaffected. The behavior of such\n /// modules will be captured when traced.\n /// </remarks>\n public override void train(bool on = true)\n {\n THSJIT_Module_train(handle, on);\n CheckForErrors();\n }\n\n /// <summary>\n /// Sets the module in evaluation mode.\n /// </summary>\n /// <remarks>\n /// Any script module that was created using torch.jit.trace() will be unaffected. The behavior of such\n /// modules will be captured when traced.\n /// </remarks>\n public override void eval()\n {\n THSJIT_Module_eval(handle);\n CheckForErrors();\n }\n\n /// <summary>\n /// Check whether the module is set to training or evaluation mode.\n /// </summary>\n public override bool training {\n get {\n var res = THSJIT_Module_is_training(handle);\n CheckForErrors();\n return res;\n }\n }\n\n protected internal override nn.Module _to(Device device, ScalarType dtype)\n {\n if (device.type != DeviceType.CUDA) { device = new Device(device.type, -1); };\n\n if (device.type == DeviceType.CUDA && !torch.cuda.is_available()) throw new InvalidOperationException(\"CUDA is not available.\");\n\n\n InitializeDeviceType(device.type);\n THSJIT_Module_to_device_dtype(handle, (sbyte)dtype, (int)device.type, device.index);\n CheckForErrors();\n\n _toEpilog(device, dtype);\n\n return this;\n }\n\n /// <summary>\n /// Moves the parameters and buffers.\n /// </summary>\n /// <param name=\"deviceType\">The device type, e.g. 'CPU' or 'CUDA'.</param>\n /// <param name=\"deviceIndex\">The optional device index.</param>\n /// <returns></returns>\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1)\n {\n if (deviceType != DeviceType.CUDA) deviceIndex = -1;\n\n if (deviceType == DeviceType.CUDA && !torch.cuda.is_available()) throw new InvalidOperationException(\"CUDA is not available.\");\n\n if (deviceType != _deviceType || deviceIndex != _deviceIndex) {\n\n InitializeDeviceType(deviceType);\n THSJIT_Module_to_device(handle, (int)deviceType, deviceIndex);\n CheckForErrors();\n\n _toEpilog(deviceType, deviceIndex);\n }\n\n Debug.Assert(_deviceType == DeviceType.CUDA || _deviceIndex == -1);\n\n return this;\n }\n\n private DeviceType _deviceType = DeviceType.CPU;\n private int _deviceIndex = -1;\n\n /// <summary>\n /// Convert the parameters and buffers.\n /// </summary>\n /// <returns></returns>\n protected internal override nn.Module _to(ScalarType dtype)\n {\n THSJIT_Module_to_dtype(handle, (sbyte)dtype);\n CheckForErrors();\n\n _toEpilog(dtype);\n\n return this;\n }\n\n#if false // These functions \"work,\" but the native code doesn't seem to find any interesting information.\n\n public Type GetInputType(int index)\n {\n var type = new Type(THSJIT_Module_getInputType(handle, index), Type.TypeKind.AnyType);\n\n return GetType(type);\n }\n\n public Type GetOutputType(int index)\n {\n var type = new Type(THSJIT_getOutputType(handle, index), Type.TypeKind.AnyType);\n\n return GetType(type);\n }\n\n private Type GetType(Type type)\n {\n switch (type.Kind) {\n case Type.TypeKind.TensorType:\n var dynamic = type.AsTensorType();\n type.Dispose();\n return dynamic;\n //case Type.TypeKind.DimensionedTensorType:\n // var tensor = type.AsTensorType();\n // type.Dispose();\n // return tensor;\n default:\n return type;\n }\n }\n#endif\n\n /// <summary>\n /// Invoke the 'forward' function of the script with any number of arguments.\n /// </summary>\n /// <param name=\"objs\"></param>\n /// <returns></returns>\n /// <remarks>\n /// Only certain types can currently be passed:\n /// 1. Tensor\n /// 2. Scalar\n /// 3. int/long\n /// 4. double/float\n /// 5. bool\n ///\n /// Only certain types can currently be returned:\n /// 1. Tensor / Scalar\n /// 2. Tuple of Tensor / Scalar\n /// 3. Array (Python list) of Tensor / Scalar\n ///\n /// For returned types, if the number of values returned in a tuple is greaterh than 5, it is returned as an array, instead.\n /// If a tuple contains both tensors and scalars, it is returned as an object[].\n /// </remarks>\n /// <exception cref=\"NotImplementedException\"></exception>\n public object call(params object[] objs)\n {\n TensorOrScalar[] ptrArray = null;\n sbyte typeCode = 0;\n\n using (var parray = new IndexedPinnedArrays<TensorOrScalar>()) {\n\n var tRefsHandle = DetermineArgumentTypeRefs(objs, out var count, parray);\n\n var allocated = parray.Count;\n\n THSJIT_Module_forward(handle, tRefsHandle, count, parray.CreateArray, out typeCode, allocated);\n torch.CheckForErrors();\n ptrArray = parray[allocated];\n\n return ProcessReturnValue(name, parray, ptrArray, typeCode);\n }\n }\n\n /// <summary>\n /// Invoke a function from the script module.\n /// </summary>\n /// <param name=\"name\">The name of the function.</param>\n /// <param name=\"objs\">Function arguments.</param>\n /// <remarks>\n /// Only certain types can currently be passed:\n /// 1. Tensor\n /// 2. Scalar\n /// 3. int/long\n /// 4. double/float\n /// 5. bool\n /// 6. 'null' object\n /// \n /// Only certain types can currently be returned:\n /// 1. Tensor / Scalar\n /// 2. Tuple of Tensor / Scalar\n /// 3. Array (Python list) of Tensor / Scalar\n /// 4. null object\n ///\n /// For returned types, if the number of values returned in a tuple is greaterh than 5, it is returned as an array, instead.\n /// If a tuple contains both tensors and scalars, it is returned as an object[].\n /// </remarks>\n public object invoke(string name, params object[] objs)\n {\n if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(\"method name\");\n\n TensorOrScalar[] ptrArray = null;\n sbyte typeCode = 0;\n\n using (var parray = new IndexedPinnedArrays<TensorOrScalar>()) {\n\n var tRefsHandle = DetermineArgumentTypeRefs(objs, out var count, parray);\n\n var allocated = parray.Count;\n\n THSJIT_Module_invoke(handle, name, tRefsHandle, count, parray.CreateArray, out typeCode, allocated);\n torch.CheckForErrors();\n ptrArray = parray[allocated];\n\n return ProcessReturnValue(name, parray, ptrArray, typeCode);\n }\n }\n\n internal static IntPtr DetermineArgumentTypeRefs(object[] objs, out int count, IndexedPinnedArrays<TensorOrScalar> pinned)\n {\n count = objs.Length;\n var tensorRefs = new TensorOrScalar[count];\n var result = pinned.CreateArray(pinned.Count, tensorRefs);\n\n for (var idx = 0; idx < objs.Length; idx++) {\n switch (objs[idx]) {\n case Tensor t:\n tensorRefs[idx].Handle = t.Handle;\n tensorRefs[idx].TypeCode = 0;\n break;\n case Scalar s:\n tensorRefs[idx].Handle = s.Handle;\n tensorRefs[idx].TypeCode = 1;\n break;\n case float f:\n tensorRefs[idx].Handle = ((Scalar)f).Handle;\n tensorRefs[idx].TypeCode = 1;\n break;\n case double d:\n tensorRefs[idx].Handle = ((Scalar)d).Handle;\n tensorRefs[idx].TypeCode = 1;\n break;\n case bool i:\n tensorRefs[idx].Handle = (IntPtr)(i ? 1L : 0L);\n tensorRefs[idx].TypeCode = 2;\n break;\n case int i:\n tensorRefs[idx].Handle = (IntPtr)i;\n tensorRefs[idx].TypeCode = 3;\n break;\n case long l:\n tensorRefs[idx].Handle = ((Scalar)l).Handle;\n tensorRefs[idx].TypeCode = 1;\n // The MacOS version of Clang doesn't like the use of int64_t, so pass as a Scalar instance, instead.\n //tensorRefs[idx].Handle = (IntPtr)l;\n //tensorRefs[idx].TypeCode = 4;\n break;\n case Tensor[] tensors: {\n tensorRefs[idx].Handle = DetermineArgumentTypeRefs(tensors, out var _, pinned);\n tensorRefs[idx].TypeCode = 5;\n tensorRefs[idx].ArrayIndex = tensors.Length;\n }\n break;\n default:\n if (objs[idx] is null) {\n tensorRefs[idx].Handle = IntPtr.Zero;\n tensorRefs[idx].TypeCode = 8;\n } else {\n throw new NotImplementedException($\"Passing arguments of type {objs[idx].GetType().Name} to TorchScript.\");\n }\n break;\n }\n }\n\n return result;\n }\n\n internal static object ProcessReturnValue(string name, IndexedPinnedArrays<TensorOrScalar> pinned, TensorOrScalar[] ptrArray, long typeCode)\n {\n switch (typeCode) {\n default:\n // Nothing.\n throw new NotImplementedException($\"ScriptModule.{name}() returning something else than a tensor, a tuple of tensors, or list of tensors. TypeCode: {typeCode}\");\n case 1:\n // Tensor\n return new Tensor(ptrArray[0].Handle);\n case 2:\n // Tuple\n switch (ptrArray.Length) {\n case 1:\n return new Tensor(ptrArray[0].Handle);\n case 2:\n return (new Tensor(ptrArray[0].Handle), new Tensor(ptrArray[1].Handle));\n case 3:\n return (new Tensor(ptrArray[0].Handle), new Tensor(ptrArray[1].Handle), new Tensor(ptrArray[2].Handle));\n case 4:\n return (new Tensor(ptrArray[0].Handle), new Tensor(ptrArray[1].Handle), new Tensor(ptrArray[2].Handle), new Tensor(ptrArray[3].Handle));\n case 5:\n return (new Tensor(ptrArray[0].Handle), new Tensor(ptrArray[1].Handle), new Tensor(ptrArray[2].Handle), new Tensor(ptrArray[3].Handle), new Tensor(ptrArray[4].Handle));\n default: {\n // Too long a tuple, return as a list, instead.\n var result = new Tensor[ptrArray.Length];\n for (var i = 0; i < ptrArray.Length; i++) {\n result[i] = new Tensor(ptrArray[i].Handle);\n }\n return result;\n }\n }\n case 3: {\n // List of tensors\n var result = new Tensor[ptrArray.Length];\n for (var i = 0; i < ptrArray.Length; i++) {\n result[i] = new Tensor(ptrArray[i].Handle);\n }\n return result;\n }\n case 4:\n // Scalar\n return new Scalar(ptrArray[0].Handle);\n case 5:\n // Scalar tuple\n switch (ptrArray.Length) {\n case 1:\n return new Scalar(ptrArray[0].Handle);\n case 2:\n return (new Scalar(ptrArray[0].Handle), new Scalar(ptrArray[1].Handle));\n case 3:\n return (new Scalar(ptrArray[0].Handle), new Scalar(ptrArray[1].Handle), new Scalar(ptrArray[2].Handle));\n case 4:\n return (new Scalar(ptrArray[0].Handle), new Scalar(ptrArray[1].Handle), new Scalar(ptrArray[2].Handle), new Scalar(ptrArray[3].Handle));\n case 5:\n return (new Scalar(ptrArray[0].Handle), new Scalar(ptrArray[1].Handle), new Scalar(ptrArray[2].Handle), new Scalar(ptrArray[3].Handle), new Scalar(ptrArray[4].Handle));\n default: {\n // Too long a tuple, return as a list, instead.\n var result = new Scalar[ptrArray.Length];\n for (var i = 0; i < ptrArray.Length; i++) {\n result[i] = new Scalar(ptrArray[i].Handle);\n }\n return result;\n }\n }\n case 6: {\n // List of scalars\n var result = new Scalar[ptrArray.Length];\n for (var i = 0; i < ptrArray.Length; i++) {\n result[i] = new Scalar(ptrArray[i].Handle);\n }\n return result;\n }\n case 7: {\n // List of scalars and tensors\n var result = new object[ptrArray.Length];\n for (var i = 0; i < ptrArray.Length; i++) {\n switch(ptrArray[i].TypeCode) {\n case 0:\n result[i] = new Tensor(ptrArray[i].Handle);\n break;\n case 8:\n result[i] = null;\n break;\n case 4:\n result[i] = new Scalar(ptrArray[i].Handle);\n break;\n default:\n throw new NotImplementedException($\"ScriptModule.{name}() returning something else than a tensor/scalar, a tuple of tensors/scalars, or list of tensors/scalars.\");\n }\n }\n return result;\n }\n case 8:\n // The value 'null' of any reference type\n return null;\n\n case 10: {\n switch (ptrArray.Length) {\n case 1:\n return ProcessReturnValue(name, pinned, ptrArray[0]);\n case 2:\n return (ProcessReturnValue(name, pinned, ptrArray[0]),\n ProcessReturnValue(name, pinned, ptrArray[1]));\n case 3:\n return (ProcessReturnValue(name, pinned, ptrArray[0]),\n ProcessReturnValue(name, pinned, ptrArray[1]),\n ProcessReturnValue(name, pinned, ptrArray[2]));\n case 4:\n return (ProcessReturnValue(name, pinned, ptrArray[0]),\n ProcessReturnValue(name, pinned, ptrArray[1]),\n ProcessReturnValue(name, pinned, ptrArray[2]),\n ProcessReturnValue(name, pinned, ptrArray[3]));\n case 5:\n return (ProcessReturnValue(name, pinned, ptrArray[0]),\n ProcessReturnValue(name, pinned, ptrArray[1]),\n ProcessReturnValue(name, pinned, ptrArray[2]),\n ProcessReturnValue(name, pinned, ptrArray[3]),\n ProcessReturnValue(name, pinned, ptrArray[4]));\n default: {\n // Too long a tuple, return as a list, instead.\n var result = new Scalar[ptrArray.Length];\n for (var i = 0; i < ptrArray.Length; i++) {\n result[i] = new Scalar(ptrArray[i].Handle);\n }\n return result;\n }\n }\n }\n case 9: {\n // List of anything\n var result = new object[ptrArray.Length];\n for (var i = 0; i < ptrArray.Length; i++) {\n result[i] = ProcessReturnValue(name, pinned, ptrArray[i]);\n }\n return result;\n }\n }\n }\n\n internal static object ProcessReturnValue(string name, IndexedPinnedArrays<TensorOrScalar> pinned, TensorOrScalar value)\n {\n switch (value.TypeCode) {\n case 0:\n return new Tensor(value.Handle);\n case 4:\n return new Scalar(value.Handle);\n case 8:\n return null;\n default:\n return ProcessReturnValue(name, pinned, pinned[(int)value.ArrayIndex], value.TypeCode);\n }\n\n throw new NotImplementedException($\"ScriptModule.{name}() returning something else than a tensor/scalar, a tuple of tensors/scalars, or list of tensors/scalars.\");\n }\n\n /// <summary>\n /// Invoke a function from the script module.\n /// </summary>\n /// <typeparam name=\"TResult\">The return type of the TorchScript function.</typeparam>\n /// <param name=\"name\">The name of the function.</param>\n /// <param name=\"inputs\">Function arguments.</param>\n /// <remarks>\n /// Only certain types can currently be passed:\n /// 1. Tensor\n /// 2. Scalar\n /// 3. int/long\n /// 4. double/float\n /// 5. bool\n ///\n /// Only certain types can currently be returned:\n /// 1. Tensor / Scalar\n /// 2. Tuple of Tensor / Scalar\n /// 3. Array (Python list) of Tensor / Scalar\n ///\n /// For returned types, if the number of values returned in a tuple is greaterh than 5, it is returned as an array, instead.\n /// If a tuple contains both tensors and scalars, it is returned as an object[].\n /// </remarks>\n public TResult invoke<TResult>(string name, params object[] inputs) => (TResult)invoke(name, inputs);\n\n /// <summary>\n /// Invoke a function from the script module.\n /// </summary>\n /// <typeparam name=\"T\">The type of all function arguments.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the TorchScript function.</typeparam>\n /// <param name=\"name\">The name of the function.</param>\n /// <param name=\"inputs\">Function arguments.</param>\n /// <remarks>\n /// Only certain types can currently be passed:\n /// 1. Tensor\n /// 2. Scalar\n /// 3. int/long\n /// 4. double/float\n /// 5. bool\n ///\n /// Only certain types can currently be returned:\n /// 1. Tensor / Scalar\n /// 2. Tuple of Tensor / Scalar\n /// 3. Array (Python list) of Tensor / Scalar\n ///\n /// For returned types, if the number of values returned in a tuple is greaterh than 5, it is returned as an array, instead.\n /// If a tuple contains both tensors and scalars, it is returned as an object[].\n /// </remarks>\n public TResult invoke<T, TResult>(string name, params T[] inputs) => (TResult)invoke(name, inputs);\n }\n\n /// <summary>\n /// A script module taking any number of tensors as input\n /// </summary>\n /// <typeparam name=\"TResult\">The return type of the module.</typeparam>\n public class ScriptModule<TResult> : ScriptModule, torch.nn.IModule<Tensor[], TResult>\n {\n internal ScriptModule(IntPtr handle) : base(handle) { }\n\n /// <summary>\n /// Invoke the 'forward' function of the script with one tensor as its argument\n /// </summary>\n /// <remarks>\n /// Only certain types can currently be passed:\n /// 1. Tensor\n /// 2. Scalar\n /// 3. int/long\n /// 4. double/float\n /// 5. bool\n ///\n /// Only certain types can currently be returned:\n /// 1. Tensor / Scalar\n /// 2. Tuple of Tensor / Scalar\n /// 3. Array (Python list) of Tensor / Scalar\n ///\n /// For returned types, if the number of values returned in a tuple is greaterh than 5, it is returned as an array, instead.\n /// If a tuple contains both tensors and scalars, it is returned as an object[].\n /// </remarks>\n public TResult call(params Tensor[] tensor)\n {\n return (TResult)base.call(tensor);\n }\n }\n\n /// <summary>\n /// A script module taking a single argument.\n /// </summary>\n /// <typeparam name=\"T\">The argument type.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module.</typeparam>\n public class ScriptModule<T, TResult> : ScriptModule, torch.nn.IModule<T, TResult>\n {\n internal ScriptModule(IntPtr handle) : base(handle) { }\n\n /// <summary>\n /// Invoke the 'forward' function of the script with one tensor as its argument\n /// </summary>\n /// <remarks>\n /// Only certain types can currently be passed:\n /// 1. Tensor\n /// 2. Scalar\n /// 3. int/long\n /// 4. double/float\n /// 5. bool\n ///\n /// Only certain types can currently be returned:\n /// 1. Tensor / Scalar\n /// 2. Tuple of Tensor / Scalar\n /// 3. Array (Python list) of Tensor / Scalar\n ///\n /// For returned types, if the number of values returned in a tuple is greaterh than 5, it is returned as an array, instead.\n /// If a tuple contains both tensors and scalars, it is returned as an object[].\n /// </remarks>\n public TResult call(T tensor)\n {\n return (TResult)base.call(tensor);\n }\n }\n\n /// <summary>\n /// A script module taking two arguments.\n /// </summary>\n /// <typeparam name=\"T1\">The first argument type.</typeparam>\n /// <typeparam name=\"T2\">The second argument type.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module.</typeparam>\n public class ScriptModule<T1, T2, TResult> : ScriptModule, torch.nn.IModule<T1, T2, TResult>\n {\n internal ScriptModule(IntPtr handle) : base(handle) { }\n\n /// <summary>\n /// Invoke the 'forward' function of the script with one tensor as its argument\n /// </summary>\n /// <remarks>\n /// Only certain types can currently be passed:\n /// 1. Tensor\n /// 2. Scalar\n /// 3. int/long\n /// 4. double/float\n /// 5. bool\n ///\n /// Only certain types can currently be returned:\n /// 1. Tensor / Scalar\n /// 2. Tuple of Tensor / Scalar\n /// 3. Array (Python list) of Tensor / Scalar\n ///\n /// For returned types, if the number of values returned in a tuple is greaterh than 5, it is returned as an array, instead.\n /// If a tuple contains both tensors and scalars, it is returned as an object[].\n /// </remarks>\n public TResult call(T1 input1, T2 input2)\n {\n return (TResult)base.call(input1, input2);\n }\n }\n\n /// <summary>\n /// Load a ScriptModule or ScriptFunction previously saved with torch.jit.save\n /// </summary>\n /// <param name=\"filename\">The file name of the module.</param>\n /// <param name=\"device_type\">The device type, e.g. 'CPU' or 'CUDA'.</param>\n /// <param name=\"device_index\">The optional device index.</param>\n /// <returns>A ScriptModule instance, whether the script originated as a module or function.</returns>\n /// <remarks>\n /// All previously saved modules, no matter their device, are first loaded onto CPU, and then are moved to the devices they were saved from.If this fails (e.g.because the run time system doesn’t have certain devices), an exception is raised.\n /// </remarks>\n /// <exception cref=\"System.IO.FileNotFoundException\">Raised if the file is not found.</exception>\n public static ScriptModule load(string filename, DeviceType device_type = DeviceType.CPU, long device_index = -1)\n {\n return new ScriptModule(_load(filename, device_type, device_index));\n }\n\n /// <summary>\n /// Load a ScriptModule or ScriptFunction previously saved with torch.jit.save\n /// </summary>\n /// <param name=\"filename\">The file name of the module.</param>\n /// <param name=\"map_location\">The device type where the script module should be loaded.</param>\n /// <returns>A ScriptModule instance, whether the script originated as a module or function.</returns>\n /// <remarks>\n /// All previously saved modules, no matter their device, are first loaded onto CPU, and then are moved to the devices they were saved from.If this fails (e.g.because the run time system doesn’t have certain devices), an exception is raised.\n /// </remarks>\n public static ScriptModule load(string filename, Device map_location)\n {\n return new ScriptModule(_load(filename, map_location.type, map_location.index));\n }\n\n /// <summary>\n /// Load a ScriptModule or ScriptFunction previously saved with torch.jit.save\n /// </summary>\n /// <param name=\"filename\">The file name of the module.</param>\n /// <param name=\"map_location\">The device type where the script module should be loaded.</param>\n /// <returns>A ScriptModule instance, whether the script originated as a module or function.</returns>\n /// <remarks>\n /// All previously saved modules, no matter their device, are first loaded onto CPU, and then are moved to the devices they were saved from.If this fails (e.g.because the run time system doesn’t have certain devices), an exception is raised.\n /// </remarks>\n public static ScriptModule load(string filename, string map_location)\n {\n return load(filename, new Device(map_location));\n }\n\n /// <summary>\n /// Load a ScriptModule or ScriptFunction previously saved with torch.jit.save\n /// </summary>\n /// <typeparam name=\"TResult\">The return type of the module.</typeparam>\n /// <param name=\"filename\">The file name of the module.</param>\n /// <param name=\"device_type\">The device type, e.g. 'CPU' or 'CUDA'.</param>\n /// <param name=\"device_index\">The optional device index.</param>\n /// <returns>A ScriptModule instance, whether the script originated as a module or function.</returns>\n /// <remarks>\n /// All previously saved modules, no matter their device, are first loaded onto CPU, and then are moved to the devices they were saved from.If this fails (e.g.because the run time system doesn’t have certain devices), an exception is raised.\n /// </remarks>\n /// <exception cref=\"System.IO.FileNotFoundException\">Raised if the file is not found.</exception>\n public static ScriptModule<TResult> load<TResult>(string filename, DeviceType device_type = DeviceType.CPU, long device_index = -1)\n {\n return new ScriptModule<TResult>(_load(filename, device_type, device_index));\n }\n\n /// <summary>\n /// Load a ScriptModule or ScriptFunction previously saved with torch.jit.save\n /// </summary>\n /// <typeparam name=\"TResult\">The return type of the module.</typeparam>\n /// <param name=\"filename\">The file name of the module.</param>\n /// <param name=\"map_location\">The device type where the script module should be loaded.</param>\n /// <returns>A ScriptModule instance, whether the script originated as a module or function.</returns>\n /// <remarks>\n /// All previously saved modules, no matter their device, are first loaded onto CPU, and then are moved to the devices they were saved from.If this fails (e.g.because the run time system doesn’t have certain devices), an exception is raised.\n /// </remarks>\n public static ScriptModule<TResult> load<TResult>(string filename, Device map_location)\n {\n return new ScriptModule<TResult>(_load(filename, map_location.type, map_location.index));\n }\n\n /// <summary>\n /// Load a ScriptModule or ScriptFunction previously saved with torch.jit.save\n /// </summary>\n /// <typeparam name=\"TResult\">The return type of the module.</typeparam>\n /// <param name=\"filename\">The file name of the module.</param>\n /// <param name=\"map_location\">The device type where the script module should be loaded.</param>\n /// <returns>A ScriptModule instance, whether the script originated as a module or function.</returns>\n /// <remarks>\n /// All previously saved modules, no matter their device, are first loaded onto CPU, and then are moved to the devices they were saved from.If this fails (e.g.because the run time system doesn’t have certain devices), an exception is raised.\n /// </remarks>\n public static ScriptModule<TResult> load<TResult>(string filename, string map_location)\n {\n return load<TResult>(filename, new Device(map_location));\n }\n\n /// <summary>\n /// Load a ScriptModule or ScriptFunction previously saved with torch.jit.save\n /// </summary>\n /// <typeparam name=\"T1\">The argument type.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module.</typeparam>\n /// <param name=\"filename\">The file name of the module.</param>\n /// <param name=\"device_type\">The device type, e.g. 'CPU' or 'CUDA'.</param>\n /// <param name=\"device_index\">The optional device index.</param>\n /// <returns>A ScriptModule instance, whether the script originated as a module or function.</returns>\n /// <remarks>\n /// All previously saved modules, no matter their device, are first loaded onto CPU, and then are moved to the devices they were saved from.If this fails (e.g.because the run time system doesn’t have certain devices), an exception is raised.\n /// </remarks>\n /// <exception cref=\"System.IO.FileNotFoundException\">Raised if the file is not found.</exception>\n public static ScriptModule<T1, TResult> load<T1, TResult>(string filename, DeviceType device_type = DeviceType.CPU, long device_index = -1)\n {\n return new ScriptModule<T1, TResult>(_load(filename, device_type, device_index));\n }\n\n /// <summary>\n /// Load a ScriptModule or ScriptFunction previously saved with torch.jit.save\n /// </summary>\n /// <typeparam name=\"T1\">The argument type.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module.</typeparam>\n /// <param name=\"filename\">The file name of the module.</param>\n /// <param name=\"map_location\">The device type where the script module should be loaded.</param>\n /// <returns>A ScriptModule instance, whether the script originated as a module or function.</returns>\n /// <remarks>\n /// All previously saved modules, no matter their device, are first loaded onto CPU, and then are moved to the devices they were saved from.If this fails (e.g.because the run time system doesn’t have certain devices), an exception is raised.\n /// </remarks>\n public static ScriptModule<T1, TResult> load<T1, TResult>(string filename, Device map_location)\n {\n return new ScriptModule<T1, TResult>(_load(filename, map_location.type, map_location.index));\n }\n\n /// <summary>\n /// Load a ScriptModule or ScriptFunction previously saved with torch.jit.save\n /// </summary>\n /// <typeparam name=\"T1\">The argument type.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module.</typeparam>\n /// <param name=\"filename\">The file name of the module.</param>\n /// <param name=\"map_location\">The device type where the script module should be loaded.</param>\n /// <returns>A ScriptModule instance, whether the script originated as a module or function.</returns>\n /// <remarks>\n /// All previously saved modules, no matter their device, are first loaded onto CPU, and then are moved to the devices they were saved from.If this fails (e.g.because the run time system doesn’t have certain devices), an exception is raised.\n /// </remarks>\n public static ScriptModule<T1, TResult> load<T1, TResult>(string filename, string map_location)\n {\n return load<T1, TResult>(filename, new Device(map_location));\n }\n\n /// <summary>\n /// Load a ScriptModule or ScriptFunction previously saved with torch.jit.save\n /// </summary>\n /// <typeparam name=\"T1\">The first argument type.</typeparam>\n /// <typeparam name=\"T2\">The second argument type.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module.</typeparam>\n /// <param name=\"filename\">The file name of the module.</param>\n /// <param name=\"device_type\">The device type, e.g. 'CPU' or 'CUDA'.</param>\n /// <param name=\"device_index\">The optional device index.</param>\n /// <returns>A ScriptModule instance, whether the script originated as a module or function.</returns>\n /// <remarks>\n /// All previously saved modules, no matter their device, are first loaded onto CPU, and then are moved to the devices they were saved from.If this fails (e.g.because the run time system doesn’t have certain devices), an exception is raised.\n /// </remarks>\n /// <exception cref=\"System.IO.FileNotFoundException\">Raised if the file is not found.</exception>\n public static ScriptModule<T1, T2, TResult> load<T1, T2, TResult>(string filename, DeviceType device_type = DeviceType.CPU, long device_index = -1)\n {\n return new ScriptModule<T1, T2, TResult>(_load(filename, device_type, device_index));\n }\n\n /// <summary>\n /// Load a ScriptModule or ScriptFunction previously saved with torch.jit.save\n /// </summary>\n /// <typeparam name=\"T1\">The first argument type.</typeparam>\n /// <typeparam name=\"T2\">The second argument type.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module.</typeparam>\n /// <param name=\"filename\">The file name of the module.</param>\n /// <param name=\"map_location\">The device type where the script module should be loaded.</param>\n /// <returns>A ScriptModule instance, whether the script originated as a module or function.</returns>\n /// <remarks>\n /// All previously saved modules, no matter their device, are first loaded onto CPU, and then are moved to the devices they were saved from.If this fails (e.g.because the run time system doesn’t have certain devices), an exception is raised.\n /// </remarks>\n public static ScriptModule<T1, T2, TResult> load<T1, T2, TResult>(string filename, Device map_location)\n {\n return new ScriptModule<T1, T2, TResult>(_load(filename, map_location.type, map_location.index));\n }\n\n /// <summary>\n /// Load a ScriptModule or ScriptFunction previously saved with torch.jit.save\n /// </summary>\n /// <typeparam name=\"T1\">The first argument type.</typeparam>\n /// <typeparam name=\"T2\">The second argument type.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module.</typeparam>\n /// <param name=\"filename\">The file name of the module.</param>\n /// <param name=\"map_location\">The device type where the script module should be loaded.</param>\n /// <returns>A ScriptModule instance, whether the script originated as a module or function.</returns>\n /// <remarks>\n /// All previously saved modules, no matter their device, are first loaded onto CPU, and then are moved to the devices they were saved from.If this fails (e.g.because the run time system doesn’t have certain devices), an exception is raised.\n /// </remarks>\n public static ScriptModule<T1, T2, TResult> load<T1, T2, TResult>(string filename, string map_location)\n {\n return load<T1, T2, TResult>(filename, new Device(map_location));\n }\n\n private static IntPtr _load(string filename, DeviceType device_type, long device_index)\n {\n if (!System.IO.File.Exists(filename))\n throw new System.IO.FileNotFoundException(filename);\n\n if (device_type != DeviceType.CUDA) device_index = -1;\n\n if (device_type == DeviceType.CUDA && !torch.cuda.is_available()) throw new InvalidOperationException(\"CUDA is not available.\");\n\n var result = THSJIT_load(filename, (long)device_type, device_index);\n if (result == IntPtr.Zero)\n CheckForErrors();\n return result;\n }\n\n /// <summary>\n /// Save an offline version of a previously loaded script module.\n ///\n /// The saved module serializes all of the methods, submodules, parameters, and attributes of this module.\n /// It can be loaded into the C++ API using torch::jit::load(filename) or into the .NET API with torch.jit.load().\n /// </summary>\n /// <param name=\"module\">The script module to save.</param>\n /// <param name=\"filename\">The file name of the module.</param>\n public static void save(ScriptModule module, string filename)\n {\n THSJIT_save(module.handle, filename);\n CheckForErrors();\n }\n\n }\n }\n}\n" }, { "alpha_fraction": 0.55967777967453, "alphanum_fraction": 0.5726097226142883, "avg_line_length": 40.377193450927734, "blob_id": "87f01e76eaebda0068ea5300fd0613d0935a1f76", "content_id": "b1736b10af745cdac1e6e3a18f9ca34e2826a1f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4717, "license_type": "permissive", "max_line_length": 130, "num_lines": 114, "path": "/src/Examples/Tensorboard.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Threading.Tasks;\nusing SixLabors.ImageSharp;\nusing SixLabors.ImageSharp.PixelFormats;\nusing SkiaSharp;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp.Examples\n{\n public static class Tensorboard\n {\n private static string imagePath = \"TensorboardExample/Images\";\n internal static async Task Main(string[] args)\n {\n await DownloadExampleData(\"https://agirls.aottercdn.com/media/0d532b3f-0196-466a-96e1-7c6db56d0142.gif\");\n var device = cuda.is_available() ? CUDA : CPU;\n var writer = utils.tensorboard.SummaryWriter(\"tensorboard\");\n Console.WriteLine($\"Running Tensorboard on {device.type}\");\n AddText(writer);\n AddImageUsePath(writer);\n AddImageUseTensor(writer, device);\n AddVideo(writer, device);\n AddHistogram(writer, device);\n }\n\n private static void AddHistogram(Modules.SummaryWriter writer, Device device)\n {\n for (int i = 0; i < 10; i++) {\n Tensor x = randn(1000, device: device);\n writer.add_histogram(\"AddHistogram\", x + i, i);\n }\n }\n\n private static void AddText(Modules.SummaryWriter writer)\n {\n writer.add_text(\"AddText\", \"step_1\", 1);\n writer.add_text(\"AddText\", \"step_2\", 2);\n writer.add_text(\"AddText\", \"step_3\", 3);\n writer.add_text(\"AddText\", \"step_4\", 4);\n writer.add_text(\"AddText\", \"step_5\", 5);\n }\n\n private static void AddImageUsePath(Modules.SummaryWriter writer)\n {\n var imagesPath = Directory.GetFiles(imagePath);\n for (var i = 0; i < imagesPath.Length; i++) {\n writer.add_img(\"AddImageUsePath\", imagesPath[i], i);\n }\n }\n\n private static void AddImageUseTensor(Modules.SummaryWriter writer, Device device)\n {\n var images = Directory.GetFiles(imagePath).Select(item => SKBitmap.Decode(item)).ToArray();\n using var d = NewDisposeScope();\n for (var i = 0; i < images.Length; i++) {\n var tensor = SKBitmapToTensor(images[i], device);\n writer.add_img(\"AddImageUseTensor\", tensor, i, dataformats: \"CHW\");\n images[i].Dispose();\n }\n }\n\n private static void AddVideo(Modules.SummaryWriter writer, Device device)\n {\n var images = Directory.GetFiles(imagePath).Select(item => SKBitmap.Decode(item)).ToArray();\n using var d = NewDisposeScope();\n var tensor = stack(images.Select(item => SKBitmapToTensor(item, device)).ToArray());\n tensor = stack(new Tensor[] { tensor, tensor, tensor, tensor, tensor, tensor, tensor, tensor, tensor, tensor });\n foreach (var image in images)\n image.Dispose();\n writer.add_video(\"AddVideo\", tensor, 1, 10);\n writer.add_video(\"AddVideo\", tensor, 2, 10);\n writer.add_video(\"AddVideo\", tensor, 3, 10);\n }\n\n private static Tensor SKBitmapToTensor(SKBitmap skBitmap, Device device)\n {\n var width = skBitmap.Width;\n var height = skBitmap.Height;\n var hwcData = new byte[4, height, width];\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width; x++) {\n var color = skBitmap.GetPixel(x, y);\n hwcData[0, y, x] = color.Red;\n hwcData[1, y, x] = color.Green;\n hwcData[2, y, x] = color.Blue;\n hwcData[3, y, x] = color.Alpha;\n }\n }\n\n return tensor(hwcData, ScalarType.Byte, device);\n }\n\n private static async Task DownloadExampleData(string url)\n {\n if (Directory.Exists(imagePath))\n Directory.Delete(imagePath, true);\n Directory.CreateDirectory(imagePath);\n using var client = new HttpClient();\n\n using var message = await client.GetAsync(url);\n using var stream = await message.Content.ReadAsStreamAsync();\n using var animatedImage = Image.Load<Rgba32>(stream);\n for (var i = 0; i < animatedImage.Frames.Count; i++) {\n var pngFilename = Path.Combine(imagePath, $\"frame_{i}.png\");\n using var pngImage = animatedImage.Frames.CloneFrame(i);\n pngImage.SaveAsPng(pngFilename);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5763546824455261, "alphanum_fraction": 0.5927750468254089, "avg_line_length": 40.305084228515625, "blob_id": "f589f3f33a08169ee87b3b43bdb2c224fec76be1", "content_id": "62f44b6b8c5fe2b58bdaaa9951036199b893bbb8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2436, "license_type": "permissive", "max_line_length": 130, "num_lines": 59, "path": "/src/TorchVision/models/Utils.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchvision,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/vision/blob/6ebbdfe8a6b47e1f6d6164b0c86ac48839281602/torchvision/models/_utils.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/vision/blob/main/LICENSE\n//\n\n// Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ==============================================================================\n\nusing System;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class models\n {\n internal static partial class _utils\n {\n /// <summary>\n /// This function is taken from the original tf repo.\n /// It ensures that all layers have a channel number that is divisible by 8\n /// It can be seen here:\n /// https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py\n /// </summary>\n internal static long _make_divisible(double v, long divisor, long? min_value = null)\n {\n if (!min_value.HasValue) {\n min_value = divisor;\n }\n var new_v = Math.Max(min_value.Value, (long)(v + divisor / 2.0) / divisor * divisor);\n // Make sure that round down does not go down by more than 10%.\n if (new_v < 0.9 * v) {\n new_v += divisor;\n }\n return new_v;\n }\n }\n }\n }\n}" }, { "alpha_fraction": 0.54841548204422, "alphanum_fraction": 0.54841548204422, "avg_line_length": 28.153846740722656, "blob_id": "670f70b04e3caf4d518614f697194eb1f7520d8c", "content_id": "ce02d56de466c8efce0f67475e7045395cb20e87", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1136, "license_type": "permissive", "max_line_length": 130, "num_lines": 39, "path": "/src/TorchVision/Posterize.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class Posterize : ITransform\n {\n internal Posterize(int bits)\n {\n this.bits = bits;\n }\n\n public Tensor call(Tensor input)\n {\n return transforms.functional.posterize(input, bits);\n }\n\n protected int bits;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Posterize the image by reducing the number of bits for each color channel. \n /// </summary>\n /// <param name=\"bits\">Number of high-order bits to keep for each channel.</param>\n /// <returns></returns>\n /// <remarks>The tensor must be an integer tensor.</remarks>\n static public ITransform Posterize(int bits)\n {\n return new Posterize(bits);\n }\n }\n }\n}" }, { "alpha_fraction": 0.5193594694137573, "alphanum_fraction": 0.533819317817688, "avg_line_length": 36.693695068359375, "blob_id": "fdc8fb26eccd93cd0063ec5697cb4028303e58ee", "content_id": "f17af4df5bbb6deed748b9657109ccff7622c534", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8368, "license_type": "permissive", "max_line_length": 150, "num_lines": 222, "path": "/src/Examples/ImageTransforms.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.IO;\nusing SkiaSharp;\nusing static TorchSharp.torch;\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp.Examples\n{\n public class ImageTransforms\n {\n internal static void Main(string[] args)\n {\n var images = new string[] {\n //\n // Find some PNG (or JPEG, etc.) files, download them, and then put their file paths here.\n //\n };\n\n const string outputPathPrefix = /* Add the very first part of your repo path here. */ @\"\\TorchSharp\\output-\";\n var tensors = LoadImages(images, 4, 3, 256, 256);\n\n var first = tensors[0];\n\n int n = 0;\n\n // First, use the transform version.\n\n var transform = torchvision.transforms.Compose(\n torchvision.transforms.ConvertImageDtype(ScalarType.Float32),\n //torchvision.transforms.ColorJitter(.5f, .5f, .5f, .25f),\n torchvision.transforms.ConvertImageDtype(ScalarType.Byte),\n torchvision.transforms.Resize(256, 256)\n );\n\n var second = transform.call(first);\n\n for (; n < second.shape[0]; n++) {\n\n var image = second[n]; // CxHxW\n var channels = image.shape[0];\n\n using (var stream = File.OpenWrite(outputPathPrefix + n + \".png\")) {\n var bitmap = GetBitmapFromBytes(image.data<byte>().ToArray(), 256, 256, channels == 1 ? SKColorType.Gray8 : SKColorType.Bgra8888);\n bitmap.Encode(stream, SKEncodedImageFormat.Png, 100);\n }\n }\n\n // Then the functional API version.\n\n second = torchvision.transforms.functional.convert_image_dtype(first);\n // Have to do this to make sure that everything's in the right format before saving.\n second = torchvision.transforms.functional.convert_image_dtype(second, dtype: ScalarType.Byte);\n second = torchvision.transforms.functional.equalize(second);\n second = torchvision.transforms.functional.resize(second, 256, 256);\n\n for (n = 0; n < second.shape[0]; n++) {\n\n var image = second[n]; // CxHxW\n var channels = image.shape[0];\n\n using (var stream = File.OpenWrite(outputPathPrefix + (n + first.shape[0]) + \".png\")) {\n var bitmap = GetBitmapFromBytes(image.data<byte>().ToArray(), 256, 256, channels == 1 ? SKColorType.Gray8 : SKColorType.Bgra8888);\n bitmap.Encode(stream, SKEncodedImageFormat.Png, 100);\n }\n }\n }\n\n private static List<Tensor> LoadImages(IList<string> images, int batchSize, int channels, int height, int width)\n {\n List<Tensor> tensors = new List<Tensor>();\n\n var imgSize = channels * height * width;\n bool shuffle = false;\n\n Random rnd = new Random();\n var indices = !shuffle ?\n Enumerable.Range(0, images.Count).ToArray() :\n Enumerable.Range(0, images.Count).OrderBy(c => rnd.Next()).ToArray();\n\n\n // Go through the data and create tensors\n for (var i = 0; i < images.Count;) {\n\n var take = Math.Min(batchSize, Math.Max(0, images.Count - i));\n\n if (take < 1) break;\n\n var dataTensor = torch.zeros(new long[] { take, imgSize }, ScalarType.Byte);\n\n // Take\n for (var j = 0; j < take; j++) {\n var idx = indices[i++];\n var lblStart = idx * (1 + imgSize);\n var imgStart = lblStart + 1;\n\n using (var stream = new SKManagedStream(File.OpenRead(images[idx])))\n using (var bitmap = SKBitmap.Decode(stream)) {\n using (var inputTensor = torch.tensor(GetBytesWithoutAlpha(bitmap))) {\n\n Tensor finalized = inputTensor;\n\n var nz = inputTensor.count_nonzero().item<long>();\n\n if (bitmap.Width != width || bitmap.Height != height) {\n var t = inputTensor.reshape(1, channels, bitmap.Height, bitmap.Width);\n finalized = torchvision.transforms.functional.resize(t, height, width).reshape(imgSize);\n }\n\n dataTensor.index_put_(finalized, TensorIndex.Single(j));\n }\n }\n }\n\n tensors.Add(dataTensor.reshape(take, channels, height, width));\n dataTensor.Dispose();\n }\n\n return tensors;\n }\n\n private static byte[] GetBytesWithoutAlpha(SKBitmap bitmap)\n {\n var height = bitmap.Height;\n var width = bitmap.Width;\n\n var inputBytes = bitmap.Bytes;\n\n if (bitmap.ColorType == SKColorType.Gray8)\n return inputBytes;\n\n if (bitmap.BytesPerPixel != 4 && bitmap.BytesPerPixel != 1)\n throw new ArgumentException(\"Conversion only supports grayscale and ARGB\");\n\n var channelLength = height * width;\n\n var channelCount = 3;\n\n int inputBlue = 0, inputGreen = 0, inputRed = 0;\n int outputRed = 0, outputGreen = channelLength, outputBlue = channelLength * 2;\n\n switch (bitmap.ColorType) {\n case SKColorType.Bgra8888:\n inputBlue = 0;\n inputGreen = 1;\n inputRed = 2;\n break;\n\n default:\n throw new NotImplementedException($\"Conversion from {bitmap.ColorType} to bytes\");\n }\n var outBytes = new byte[channelCount * channelLength];\n\n for (int i = 0, j = 0; i < channelLength; i += 1, j += 4) {\n outBytes[outputRed + i] = inputBytes[inputRed + j];\n outBytes[outputGreen + i] = inputBytes[inputGreen + j];\n outBytes[outputBlue + i] = inputBytes[inputBlue + j];\n }\n\n return outBytes;\n }\n\n private static SKBitmap GetBitmapFromBytes(byte[] inputBytes, int height, int width, SKColorType colorType)\n {\n var result = new SKBitmap();\n\n var channelLength = height * width;\n\n var channelCount = 0;\n\n int inputRed = 0, inputGreen = channelLength, inputBlue = channelLength * 2;\n int outputBlue = 0, outputGreen = 0, outputRed = 0, outputAlpha = 0;\n\n switch (colorType) {\n case SKColorType.Bgra8888:\n outputBlue = 0;\n outputGreen = 1;\n outputRed = 2;\n outputAlpha = 3;\n channelCount = 3;\n break;\n\n case SKColorType.Gray8:\n channelCount = 1;\n break;\n\n default:\n throw new NotImplementedException($\"Conversion from {colorType} to bytes\");\n }\n\n byte[] outBytes = null;\n\n if (channelCount == 1) {\n\n // Greyscale\n\n outBytes = inputBytes;\n } else {\n\n outBytes = new byte[(channelCount + 1) * channelLength];\n\n for (int i = 0, j = 0; i < channelLength; i += 1, j += 4) {\n outBytes[outputRed + j] = inputBytes[inputRed + i];\n outBytes[outputGreen + j] = inputBytes[inputGreen + i];\n outBytes[outputBlue + j] = inputBytes[inputBlue + i];\n outBytes[outputAlpha + j] = 255;\n }\n }\n\n // pin the managed array so that the GC doesn't move it\n var gcHandle = GCHandle.Alloc(outBytes, GCHandleType.Pinned);\n\n // install the pixels with the color type of the pixel data\n var info = new SKImageInfo(width, height, colorType, SKAlphaType.Unpremul);\n result.InstallPixels(info, gcHandle.AddrOfPinnedObject(), info.RowBytes, delegate { gcHandle.Free(); }, null);\n\n return result;\n }\n }\n}\n" }, { "alpha_fraction": 0.5183297395706177, "alphanum_fraction": 0.5279356837272644, "avg_line_length": 57.85769271850586, "blob_id": "85c14395ea3ad306cb5bbc3dfe854281d3db3e27", "content_id": "5c7e8a1214722835e2c164138283b1dddaed584d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 15303, "license_type": "permissive", "max_line_length": 302, "num_lines": 260, "path": "/src/TorchSharp/NN/Pooling/MaxPool2D.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Linq;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a MaxPool2D module.\n /// </summary>\n public sealed class MaxPool2d : torch.nn.Module<Tensor, Tensor>\n {\n internal MaxPool2d(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_MaxPool2d_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n public (Tensor Values, Tensor Indices) forward_with_indices(Tensor tensor)\n {\n var res = THSNN_MaxPool2d_forward_with_indices(handle, tensor.Handle, out var indices);\n if (res == IntPtr.Zero || indices == IntPtr.Zero) { torch.CheckForErrors(); }\n return (new Tensor(res), new Tensor(indices));\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies a 2D max pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"kernelSize\">The size of the sliding window, must be > 0.</param>\n /// <param name=\"stride\">The stride of the sliding window, must be > 0. Default value is kernel_size.</param>\n /// <param name=\"padding\">Implicit negative infinity padding to be added on both sides, must be >= 0 and less than or equal to kernel_size / 2</param>\n /// <param name=\"dilation\">The stride between elements within a sliding window, must be > 0.</param>\n /// <param name=\"ceilMode\">If true, will use ceil instead of floor to compute the output shape. This ensures that every element in the input tensor is covered by a sliding window.</param>\n /// <returns></returns>\n public static unsafe MaxPool2d MaxPool2d(long kernelSize, long? stride = null, long? padding = null, long? dilation = null, bool ceilMode = false)\n {\n long svalue = stride.HasValue ? stride.Value : kernelSize;\n long pvalue = padding.HasValue ? padding.Value : 0;\n long dvalue = dilation.HasValue ? dilation.Value : 1;\n\n long* pStride = stackalloc long[2] { svalue, svalue };\n long* pPadding = stackalloc long[2] { pvalue, pvalue };\n long* pDilation = stackalloc long[2] { dvalue, dvalue };\n\n long* pkernelSize = stackalloc long[2] { kernelSize, kernelSize };\n\n var handle = THSNN_MaxPool2d_ctor((IntPtr)pkernelSize, 2, (IntPtr)pStride, 2, (IntPtr)pPadding, 2, (IntPtr)pDilation, 2, ceilMode, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new MaxPool2d(handle, boxedHandle);\n }\n\n /// <summary>\n /// Applies a 2D max pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"kernelSize\">The size of the sliding window, must be > 0.</param>\n /// <param name=\"stride\">The stride of the sliding window, must be > 0. Default value is kernel_size.</param>\n /// <param name=\"padding\">Implicit negative infinity padding to be added on both sides, must be >= 0 and less than or equal to kernel_size / 2</param>\n /// <param name=\"dilation\">The stride between elements within a sliding window, must be > 0.</param>\n /// <param name=\"ceilMode\">If true, will use ceil instead of floor to compute the output shape. This ensures that every element in the input tensor is covered by a sliding window.</param>\n /// <returns></returns>\n public static unsafe MaxPool2d MaxPool2d((long, long) kernelSize, (long, long)? stride = null, (long, long)? padding = null, (long, long)? dilation = null, bool ceilMode = false)\n {\n long svalue1 = stride != null ? stride.Value.Item1 : kernelSize.Item1;\n long svalue2 = stride != null ? stride.Value.Item2 : kernelSize.Item2;\n long pvalue1 = padding != null ? padding.Value.Item1 : 0;\n long pvalue2 = padding != null ? padding.Value.Item2 : 0;\n long dvalue1 = dilation != null ? dilation.Value.Item1 : 1;\n long dvalue2 = dilation != null ? dilation.Value.Item2 : 1;\n\n long* pStride = stackalloc long[2] { svalue1, svalue2 };\n long* pPadding = stackalloc long[2] { pvalue1, pvalue2 };\n long* pDilation = stackalloc long[2] { dvalue1, dvalue2 };\n\n long* pkernelSize = stackalloc long[2] { kernelSize.Item1, kernelSize.Item2 };\n\n var handle = THSNN_MaxPool2d_ctor((IntPtr)pkernelSize, 2, (IntPtr)pStride, 2, (IntPtr)pPadding, 2, (IntPtr)pDilation, 2, ceilMode, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new MaxPool2d(handle, boxedHandle);\n }\n\n /// <summary>\n /// Applies a 2D max pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"kernelSize\">The size of the sliding window, must be > 0.</param>\n /// <param name=\"strides\">The stride of the sliding window, must be > 0. Default value is kernel_size.</param>\n /// <param name=\"padding\">Implicit negative infinity padding to be added on both sides, must be >= 0 and less than or equal to kernel_size / 2</param>\n /// <param name=\"dilation\">The stride between elements within a sliding window, must be > 0.</param>\n /// <param name=\"ceilMode\">If true, will use ceil instead of floor to compute the output shape. This ensures that every element in the input tensor is covered by a sliding window.</param>\n /// <returns></returns>\n public static unsafe MaxPool2d MaxPool2d(long[] kernelSize, long[] strides = null, long[] padding = null, long[] dilation = null, bool ceilMode = false)\n {\n fixed (long* pkernelSize = kernelSize, pstrides = strides, pPadding = padding, pDilation = dilation) {\n var handle = THSNN_MaxPool2d_ctor((IntPtr)pkernelSize, kernelSize.Length, (IntPtr)pstrides, (strides == null ? 0 : strides.Length), (IntPtr)pPadding, (padding == null ? 0 : padding.Length), (IntPtr)pDilation, (dilation == null ? 0 : dilation.Length), ceilMode, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new MaxPool2d(handle, boxedHandle);\n }\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Applies a 2D max pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"kernelSize\"></param>\n /// <param name=\"strides\"></param>\n /// <param name=\"padding\"></param>\n /// <param name=\"dilation\"></param>\n /// <param name=\"ceil_mode\"></param>\n /// <returns></returns>\n public static Tensor max_pool2d(Tensor input, long[] kernelSize, long[] strides = null,\n long[] padding = null, long[] dilation = null, bool ceil_mode = false)\n {\n strides = strides ?? kernelSize.Select(x => 1L).ToArray();\n padding = padding ?? kernelSize.Select(x => 0L).ToArray();\n dilation = dilation ?? kernelSize.Select(x => 1L).ToArray();\n unsafe {\n fixed (long* pkernelSize = kernelSize, pstrides = strides, ppadding = padding, pdilation = dilation) {\n var res =\n THSTensor_max_pool2d(input.Handle,\n (IntPtr)pkernelSize, kernelSize.Length,\n (IntPtr)pstrides, strides.Length,\n (IntPtr)ppadding, padding.Length,\n (IntPtr)pdilation, dilation.Length,\n ceil_mode);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Applies a 2D max pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"kernelSize\"></param>\n /// <param name=\"stride\"></param>\n /// <param name=\"padding\"></param>\n /// <param name=\"dilation\"></param>\n /// <param name=\"ceil_mode\"></param>\n /// <returns></returns>\n public static unsafe Tensor max_pool2d(Tensor input, long kernelSize, long? stride = null,\n long? padding = null, long? dilation = null, bool ceil_mode = false)\n {\n long svalue = stride.HasValue ? stride.Value : kernelSize;\n long pvalue = padding.HasValue ? padding.Value : 0;\n long dvalue = dilation.HasValue ? dilation.Value : 1;\n\n long* pStride = stackalloc long[2] { svalue, svalue };\n long* pPadding = stackalloc long[2] { pvalue, pvalue };\n long* pDilation = stackalloc long[2] { dvalue, dvalue };\n\n long* pkernelSize = stackalloc long[2] { kernelSize, kernelSize };\n\n var res = THSTensor_max_pool2d(input.Handle,\n (IntPtr)pkernelSize, 2,\n (IntPtr)pStride, 2,\n (IntPtr)pPadding, 2,\n (IntPtr)pDilation, 2,\n ceil_mode);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Applies a 2D max pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"kernelSize\"></param>\n /// <param name=\"stride\"></param>\n /// <param name=\"padding\"></param>\n /// <param name=\"dilation\"></param>\n /// <param name=\"ceil_mode\"></param>\n /// <returns></returns>\n public static unsafe Tensor max_pool2d(Tensor input, (long, long) kernelSize, (long, long)? stride = null,\n (long, long)? padding = null, (long, long)? dilation = null, bool ceil_mode = false)\n {\n long svalue1 = stride != null ? stride.Value.Item1 : kernelSize.Item1;\n long svalue2 = stride != null ? stride.Value.Item2 : kernelSize.Item2;\n long pvalue1 = padding != null ? padding.Value.Item1 : 0;\n long pvalue2 = padding != null ? padding.Value.Item2 : 0;\n long dvalue1 = dilation != null ? dilation.Value.Item1 : 1;\n long dvalue2 = dilation != null ? dilation.Value.Item2 : 1;\n\n long* pStride = stackalloc long[2] { svalue1, svalue2 };\n long* pPadding = stackalloc long[2] { pvalue1, pvalue2 };\n long* pDilation = stackalloc long[2] { dvalue1, dvalue2 };\n\n long* pkernelSize = stackalloc long[2] { kernelSize.Item1, kernelSize.Item2 };\n\n var res = THSTensor_max_pool2d(input.Handle,\n (IntPtr)pkernelSize, 2,\n (IntPtr)pStride, 2,\n (IntPtr)pPadding, 2,\n (IntPtr)pDilation, 2,\n ceil_mode);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Applies a 2D max pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"kernelSize\"></param>\n /// <param name=\"strides\"></param>\n /// <param name=\"padding\"></param>\n /// <param name=\"dilation\"></param>\n /// <param name=\"ceil_mode\"></param>\n /// <returns></returns>\n public static (Tensor output, Tensor indices) max_pool2d_with_indices(Tensor input, long[] kernelSize, long[] strides = null,\n long[] padding = null, long[] dilation = null, bool ceil_mode = false)\n {\n strides = strides ?? kernelSize.Select(x => 1L).ToArray();\n padding = padding ?? kernelSize.Select(x => 0L).ToArray();\n dilation = dilation ?? kernelSize.Select(x => 1L).ToArray();\n IntPtr[] ptrArray;\n\n using (var pa = new PinnedArray<IntPtr>()) {\n unsafe {\n fixed (long* pkernelSize = kernelSize, pstrides = strides, ppadding = padding, pdilation = dilation) {\n THSTensor_max_pool2d_with_indices(input.Handle,\n pa.CreateArray,\n (IntPtr)pkernelSize, kernelSize.Length,\n (IntPtr)pstrides, strides.Length,\n (IntPtr)ppadding, padding.Length,\n (IntPtr)pdilation, dilation.Length,\n ceil_mode);\n torch.CheckForErrors();\n }\n }\n ptrArray = pa.Array;\n }\n return (new Tensor(ptrArray[0]), new Tensor(ptrArray[1]));\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5946969985961914, "alphanum_fraction": 0.6032196879386902, "avg_line_length": 31, "blob_id": "481df313a8e1a18d61b74be79e92d01038fd6dfd", "content_id": "d1a36278c533c5b7a345edf081810f4dd452d261", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1056, "license_type": "permissive", "max_line_length": 121, "num_lines": 33, "path": "/src/Examples/IOReadWrite.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System;\n\nnamespace TorchSharp.Examples\n{\n class IOReadWrite\n {\n internal static void Main(string[] args)\n {\n torchvision.io.DefaultImager = new torchvision.io.SkiaImager();\n\n var filename = args[0];\n\n Console.WriteLine($\"Reading file {filename}\");\n\n var img = torchvision.io.read_image(filename, torchvision.io.ImageReadMode.GRAY);\n\n Console.WriteLine($\"Image has {img.shape[0]} colour channels with dimensions {img.shape[1]}x{img.shape[2]}\");\n\n var transformed = torchvision.transforms.Compose(\n //torchvision.transforms.Invert(),\n torchvision.transforms.HorizontalFlip(),\n //torchvision.transforms.CenterCrop(256),\n torchvision.transforms.Rotate(50)\n ).call(img);\n\n var out_file = \"image_transformed.jpg\";\n\n torchvision.io.write_image(transformed, out_file, torchvision.ImageFormat.Jpeg);\n\n Console.WriteLine($\"Wrote file {out_file}\");\n }\n }\n}\n" }, { "alpha_fraction": 0.704081654548645, "alphanum_fraction": 0.7052153944969177, "avg_line_length": 43.150001525878906, "blob_id": "2b651afb27fc39cfe7debf93ea0a8419cff5871c", "content_id": "205f94c422580cef49be3aded7cd57907a2efdfc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 882, "license_type": "permissive", "max_line_length": 114, "num_lines": 20, "path": "/src/TorchSharp/Utils/ObjectReferenceEqualityComparer.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections.Generic;\nusing System.Runtime.CompilerServices;\n\nnamespace TorchSharp.Utils\n{\n /// <summary>\n /// A generic object comparerer that would only use object's reference,\n /// ignoring any <see cref=\"IEquatable{T}\"/> or <see cref=\"object.Equals(object)\"/> overrides.\n /// This should be replaced with the official ReferenceEqualityComparer as soon as the TorchSharp uses .NET 6.\n /// </summary>\n public class ReferenceEqualityComparer<T> : EqualityComparer<T>\n where T : class\n {\n private static IEqualityComparer<T> _defaultComparer;\n public new static IEqualityComparer<T> Default => _defaultComparer ??= new ReferenceEqualityComparer<T>();\n public override bool Equals(T x, T y) => ReferenceEquals(x, y);\n public override int GetHashCode(T obj) => RuntimeHelpers.GetHashCode(obj);\n }\n}" }, { "alpha_fraction": 0.4921130836009979, "alphanum_fraction": 0.4954659640789032, "avg_line_length": 56.056522369384766, "blob_id": "565ff5396364bfd0c12ec0ae8e94db9cbca72915", "content_id": "149eca23c273cdf24ebbd4489e359a8d8ab41408", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 13129, "license_type": "permissive", "max_line_length": 203, "num_lines": 230, "path": "/src/TorchSharp/NN/Upsample.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using Modules;\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Upsamples a given multi-channel 1D (temporal), 2D (spatial) or 3D (volumetric) data.\n /// The input data is assumed to be of the form minibatch x channels x[optional depth] x[optional height] x width.\n /// Hence, for spatial inputs, we expect a 4D Tensor and for volumetric inputs, we expect a 5D Tensor.\n /// </summary>\n /// <param name=\"size\">Output spatial sizes</param>\n /// <param name=\"scale_factor\">Multiplier for spatial size. Has to match input size</param>\n /// <param name=\"mode\">The upsampling algorithm: one of 'nearest', 'linear', 'bilinear', 'bicubic' and 'trilinear'. Default: 'nearest'</param>\n /// <param name=\"alignCorners\">If true, the corner pixels of the input and output tensors are aligned, and thus preserving the values at those pixels.\n /// This only has effect when mode is 'linear', 'bilinear', or 'trilinear'. Default: false</param>\n /// <returns></returns>\n public static Upsample Upsample(long[]? size = null, double[]? scale_factor = null, UpsampleMode mode = UpsampleMode.Nearest, bool? alignCorners = null)\n {\n unsafe {\n fixed (long* psize = size) {\n fixed (double* pSF = scale_factor) {\n byte ac = (byte)((alignCorners.HasValue) ? (alignCorners.Value ? 1 : 2) : 0);\n var res = THSNN_Upsample_ctor((IntPtr)psize, size is null ? 0 : size.Length, (IntPtr)pSF, scale_factor is null ? 0 : scale_factor.Length, (byte)mode, ac, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Upsample(res, boxedHandle);\n }\n }\n }\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Upsamples a given multi-channel 1D (temporal), 2D (spatial) or 3D (volumetric) data.\n /// The input data is assumed to be of the form minibatch x channels x[optional depth] x[optional height] x width.\n /// Hence, for spatial inputs, we expect a 4D Tensor and for volumetric inputs, we expect a 5D Tensor.\n /// </summary>\n /// <param name=\"x\">Input tensor</param>\n /// <param name=\"size\">Output spatial sizes</param>\n /// <param name=\"scale_factor\">Multiplier for spatial size. Has to match input size</param>\n /// <param name=\"mode\">The upsampling algorithm: one of 'nearest', 'linear', 'bilinear', 'bicubic' and 'trilinear'. Default: 'nearest'</param>\n /// <param name=\"alignCorners\">If true, the corner pixels of the input and output tensors are aligned, and thus preserving the values at those pixels.\n /// This only has effect when mode is 'linear', 'bilinear', or 'trilinear'. Default: false</param>\n /// <returns></returns>\n public static Tensor upsample(Tensor x, long[]? size = null, double[]? scale_factor = null, UpsampleMode mode = UpsampleMode.Nearest, bool alignCorners = false)\n {\n using (var d = nn.Upsample(size, scale_factor, mode, alignCorners)) {\n return d.call(x);\n }\n }\n\n\n /// <summary>\n /// Upsamples the input, using nearest neighbours’ pixel values.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"outputSize\"></param>\n /// <param name=\"scaleFactor\"></param>\n /// <returns></returns>\n public static Tensor upsample_nearest1d(Tensor input, long? outputSize, double? scaleFactor)\n {\n var outputSizes = outputSize.HasValue ? new long[] { outputSize.Value } : null;\n var outputSizesLength = outputSize.HasValue ? 1 : 0;\n var scaleFactors = scaleFactor.HasValue ? new double[] { scaleFactor.Value } : null;\n var scaleFactorsLength = scaleFactor.HasValue ? 1 : 0;\n unsafe {\n fixed (long* poutputSizes = outputSizes) {\n fixed (double* pscaleFactors = scaleFactors) {\n var res =\n THSTensor_upsample_nearest1d(input.Handle,\n (IntPtr)poutputSizes, outputSizesLength,\n (IntPtr)pscaleFactors, scaleFactorsLength);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n\n public static Tensor upsample_nearest1d_backward(Tensor grad_output, long? outputSize, long inputSize, double? scaleFactor)\n {\n var outputSizes = outputSize.HasValue ? new long[] { outputSize.Value } : null;\n var outputSizesLength = outputSize.HasValue ? 1 : 0;\n var inputSizes = new long[] { inputSize };\n var scaleFactors = scaleFactor.HasValue ? new double[] { scaleFactor.Value } : null;\n var scaleFactorsLength = scaleFactor.HasValue ? 1 : 0;\n unsafe {\n fixed (long* poutputSizes = outputSizes, pinputSizes = inputSizes) {\n fixed (double* pscaleFactors = scaleFactors) {\n var res =\n THSTensor_upsample_nearest1d_backward(grad_output.Handle,\n (IntPtr)poutputSizes, outputSizesLength,\n (IntPtr)pinputSizes, inputSizes.Length,\n (IntPtr)pscaleFactors, scaleFactorsLength);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n\n /// <summary>\n /// Upsamples the input, using nearest neighbours’ pixel values.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"outputSizes\"></param>\n /// <param name=\"scaleFactors\"></param>\n /// <returns></returns>\n public static Tensor upsample_nearest2d(Tensor input, long[]? outputSizes = null, double[]? scaleFactors = null)\n {\n var outputSizesLength = outputSizes == null ? 0 : outputSizes.Length;\n var scaleFactorsLength = scaleFactors == null ? 0 : scaleFactors.Length;\n unsafe {\n fixed (long* poutputSizes = outputSizes) {\n fixed (double* pscaleFactors = scaleFactors) {\n var res =\n THSTensor_upsample_nearest2d(input.Handle,\n (IntPtr)poutputSizes, outputSizesLength,\n (IntPtr)pscaleFactors, scaleFactorsLength);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n\n public static Tensor upsample_nearest2d_backward(Tensor grad_output, long[] inputSizes, long[]? outputSizes = null, double[]? scaleFactors = null)\n {\n var outputSizesLength = outputSizes == null ? 0 : outputSizes.Length;\n var scaleFactorsLength = scaleFactors == null ? 0 : scaleFactors.Length;\n unsafe {\n fixed (long* poutputSizes = outputSizes, pinputSizes = inputSizes) {\n fixed (double* pscaleFactors = scaleFactors) {\n var res =\n THSTensor_upsample_nearest2d_backward(grad_output.Handle,\n (IntPtr)poutputSizes, outputSizesLength,\n (IntPtr)pinputSizes, inputSizes.Length,\n (IntPtr)pscaleFactors, scaleFactorsLength);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n\n public static Tensor upsample_nearest3d_backward(Tensor grad_output, long[] inputSizes, long[]? outputSizes = null, double[]? scaleFactors = null)\n {\n var outputSizesLength = outputSizes == null ? 0 : outputSizes.Length;\n var scaleFactorsLength = scaleFactors == null ? 0 : scaleFactors.Length;\n unsafe {\n fixed (long* poutputSizes = outputSizes, pinputSizes = inputSizes) {\n fixed (double* pscaleFactors = scaleFactors) {\n var res =\n THSTensor_upsample_nearest3d_backward(grad_output.Handle,\n (IntPtr)poutputSizes, outputSizesLength,\n (IntPtr)pinputSizes, inputSizes.Length,\n (IntPtr)pscaleFactors, scaleFactorsLength);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n\n /// <summary>\n /// Upsamples the input, using nearest neighbours’ pixel values.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"outputSizes\"></param>\n /// <param name=\"scaleFactors\"></param>\n /// <returns></returns>\n public static Tensor upsample_nearest3d(Tensor input, long[]? outputSizes = null, double[]? scaleFactors = null)\n {\n var outputSizesLength = outputSizes == null ? 0 : outputSizes.Length;\n var scaleFactorsLength = scaleFactors == null ? 0 : scaleFactors.Length;\n unsafe {\n fixed (long* poutputSizes = outputSizes) {\n fixed (double* pscaleFactors = scaleFactors) {\n var res =\n THSTensor_upsample_nearest3d(input.Handle,\n (IntPtr)poutputSizes, outputSizesLength,\n (IntPtr)pscaleFactors, scaleFactorsLength);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n }\n }\n }\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent an Upsample module.\n /// </summary>\n public sealed class Upsample : torch.nn.Module<Tensor, Tensor>\n {\n internal Upsample(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n /// <summary>\n /// Forward pass.\n /// </summary>\n /// <param name=\"tensor\">Input tensor</param>\n /// <returns></returns>\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_Upsample_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n}\n" }, { "alpha_fraction": 0.5745007395744324, "alphanum_fraction": 0.5794931054115295, "avg_line_length": 40.33333206176758, "blob_id": "366a75813ff0d0bc2a4dfd151942758407b0368a", "content_id": "5583c61cfcd6319981d3a7a9755e4b396e79b82b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2604, "license_type": "permissive", "max_line_length": 149, "num_lines": 63, "path": "/src/TorchSharp/Distributions/Chi2.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// A Gamma distribution parameterized by a single shape parameter.\n /// </summary>\n public class Chi2 : Gamma\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"df\">Shape parameter of the distribution</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n public Chi2(Tensor df, torch.Generator generator = null) : base(df * 0.5, torch.tensor(0.5), generator)\n {\n }\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is Chi2))\n throw new ArgumentException(\"expand(): 'instance' must be a Chi2 distribution\");\n\n if (instance == null) {\n instance = new Chi2(concentration, generator);\n }\n return base.expand(batch_shape, instance);\n }\n\n public Tensor df => concentration * 2;\n }\n }\n\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a Gamma distribution parameterized by a single shape parameter.\n /// </summary>\n /// <param name=\"df\">Shape parameter of the distribution</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Chi2 Chi2(Tensor df, torch.Generator generator = null)\n {\n return new Chi2(df, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5546642541885376, "alphanum_fraction": 0.5611974596977234, "avg_line_length": 45.5076904296875, "blob_id": "096e94f3413948a711906417763e1d15e96fd175", "content_id": "7fee61dfa820cbcbe83cd258abc8508f962aad6d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 12092, "license_type": "permissive", "max_line_length": 167, "num_lines": 260, "path": "/src/TorchVision/dsets/MNIST.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing TorchSharp.Utils;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.utils.data;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class datasets\n {\n /// <summary>\n /// MNIST Dataset\n /// http://yann.lecun.com/exdb/mnist/\n /// </summary>\n /// <param name=\"root\">Root directory of dataset where the MNIST .gz data files exist.</param>\n /// <param name=\"train\">If true, creates dataset from the 'train' files, otherwise from the 't10k' files.</param>\n /// <param name=\"download\">\n /// If true, downloads the dataset from the internet and puts it in root directory.\n /// If the dataset is already downloaded, it is not downloaded again.\n /// </param>\n /// <param name=\"target_transform\">A function/transform that takes in the target and transforms it.</param>\n /// <returns>An iterable dataset.</returns>\n public static Dataset MNIST(string root, bool train, bool download = false, torchvision.ITransform target_transform = null)\n {\n return new Modules.MNIST(root, train, download, target_transform);\n }\n\n /// <summary>\n /// Fashion-MNIST Dataset\n /// https://github.com/zalandoresearch/fashion-mnist/raw/master/data/fashion/\n /// </summary>\n /// <param name=\"root\">Root directory of dataset where the MNIST .gz data files exist.</param>\n /// <param name=\"train\">If true, creates dataset from the 'train' files, otherwise from the 't10k' files.</param>\n /// <param name=\"download\">\n /// If true, downloads the dataset from the internet and puts it in root directory.\n /// If the dataset is already downloaded, it is not downloaded again.\n /// </param>\n /// <param name=\"target_transform\">A function/transform that takes in the target and transforms it.</param>\n /// <returns>An iterable dataset.</returns>\n public static Dataset FashionMNIST(string root, bool train, bool download = false, torchvision.ITransform target_transform = null)\n {\n return new Modules.FashionMNIST(root, train, download, target_transform);\n }\n\n /// <summary>\n /// Kuzushiji-MNIST Dataset (https://github.com/rois-codh/kmnist)\n /// </summary>\n /// <param name=\"root\">Root directory of dataset where the KMNIST .gz data files exist.</param>\n /// <param name=\"train\">If true, creates dataset from the 'train' files, otherwise from the 't10k' files.</param>\n /// <param name=\"download\">\n /// If true, downloads the dataset from the internet and puts it in root directory.\n /// If the dataset is already downloaded, it is not downloaded again.\n /// </param>\n /// <param name=\"target_transform\">A function/transform that takes in the target and transforms it.</param>\n /// <returns>An iterable dataset.</returns>\n public static Dataset KMNIST(string root, bool train, bool download = false, torchvision.ITransform target_transform = null)\n {\n return new Modules.KMNIST(root, train, download, target_transform);\n }\n }\n }\n\n namespace Modules\n {\n /// <summary>\n /// Data reader utility for datasets that follow the MNIST data set's layout:\n ///\n /// A number of single-channel (grayscale) images are laid out in a flat file with four 32-bit integers at the head.\n /// The format is documented at the bottom of the page at: http://yann.lecun.com/exdb/mnist/\n /// </summary>\n internal class MNIST : DatasetHelper\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"root\">Path to the folder containing the image files.</param>\n /// <param name=\"train\">The file name prefix, either 'train' or 't10k' (the latter being the test data set).</param>\n /// <param name=\"download\"></param>\n /// <param name=\"transform\">Transform for input MNIST image</param>\n public MNIST(string root, bool train, bool download = false, torchvision.ITransform transform = null) :\n this(root, \"mnist\", train ? \"train\" : \"t10k\", \"http://yann.lecun.com/exdb/mnist/\", download, transform)\n {\n }\n\n protected MNIST(string root, string datasetName, string prefix, string baseUrl, bool download, torchvision.ITransform transform)\n {\n if (download) Download(root, baseUrl, datasetName);\n\n this.transform = transform;\n\n#if NETSTANDARD2_0_OR_GREATER\n var datasetPath = NSPath.Join(root, datasetName, \"test_data\");\n#else\n var datasetPath = Path.Join(root, datasetName, \"test_data\");\n#endif // NETSTANDARD2_0_OR_GREATER\n\n var dataPath = Path.Combine(datasetPath, prefix + \"-images-idx3-ubyte\");\n var labelPath = Path.Combine(datasetPath, prefix + \"-labels-idx1-ubyte\");\n\n var count = -1;\n var height = 0;\n var width = 0;\n\n byte[] dataBytes = null;\n byte[] labelBytes = null;\n\n using (var file = File.Open(dataPath, FileMode.Open, FileAccess.Read, FileShare.Read))\n using (var rdr = new System.IO.BinaryReader(file)) {\n\n var reader = new BigEndianReader(rdr);\n var x = reader.ReadInt32(); // Magic number\n count = reader.ReadInt32();\n\n height = reader.ReadInt32();\n width = reader.ReadInt32();\n\n // Read all the data into memory.\n dataBytes = reader.ReadBytes(height * width * count);\n }\n\n using (var file = File.Open(labelPath, FileMode.Open, FileAccess.Read, FileShare.Read))\n using (var rdr = new System.IO.BinaryReader(file)) {\n\n var reader = new BigEndianReader(rdr);\n var x = reader.ReadInt32(); // Magic number\n var lblcnt = reader.ReadInt32();\n\n if (lblcnt != count) throw new InvalidDataException(\"Image data and label counts are different.\");\n\n // Read all the data into memory.\n labelBytes = reader.ReadBytes(lblcnt);\n }\n\n var imgSize = height * width;\n\n // Go through the data and create tensors\n\n // A previous version of this relied on LINQ expressions, but it was about 20% slower.\n\n for (var i = 0; i < count; i++) {\n var imgStart = i * imgSize;\n var floats = new float[imgSize];\n for (int j = 0; j < imgSize; j++)\n {\n floats[j] = dataBytes[j+imgStart] / 256.0f;\n }\n data.Add(tensor(floats, new long[] { width, height }));\n\n labels.Add(tensor(labelBytes[i], int64));\n }\n }\n\n private void Download(string root, string baseUrl, string dataset)\n {\n#if NETSTANDARD2_0_OR_GREATER\n var datasetPath = NSPath.Join(root, dataset);\n#else\n var datasetPath = Path.Join(root, dataset);\n#endif // NETSTANDARD2_0_OR_GREATER\n\n var sourceDir = datasetPath;\n var targetDir = Path.Combine(datasetPath, \"test_data\");\n\n if (!Directory.Exists(sourceDir)) {\n Directory.CreateDirectory(sourceDir);\n }\n\n DownloadFile(\"train-images-idx3-ubyte.gz\", sourceDir, baseUrl);\n DownloadFile(\"train-labels-idx1-ubyte.gz\", sourceDir, baseUrl);\n DownloadFile(\"t10k-images-idx3-ubyte.gz\", sourceDir, baseUrl);\n DownloadFile(\"t10k-labels-idx1-ubyte.gz\", sourceDir, baseUrl);\n\n if (!Directory.Exists(targetDir)) {\n Directory.CreateDirectory(targetDir);\n }\n\n DecompressFile(\"train-images-idx3-ubyte\", sourceDir, targetDir);\n DecompressFile(\"train-labels-idx1-ubyte\", sourceDir, targetDir);\n DecompressFile(\"t10k-images-idx3-ubyte\", sourceDir, targetDir);\n DecompressFile(\"t10k-labels-idx1-ubyte\", sourceDir, targetDir);\n }\n\n private static void DecompressFile(string file, string sourceDir, string targetDir)\n {\n var filePath = Path.Combine(targetDir, file);\n if (!File.Exists(filePath))\n Utils.Decompress.DecompressGZipFile(Path.Combine(sourceDir, file + \".gz\"), targetDir);\n }\n\n private torchvision.ITransform transform;\n\n /// <summary>\n /// Size of dataset\n /// </summary>\n public override long Count => data.Count;\n\n private List<Tensor> data = new();\n private List<Tensor> labels = new();\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n data.ForEach(d => d.Dispose());\n labels.ForEach(d => d.Dispose());\n }\n }\n\n /// <summary>\n /// Get tensor according to index\n /// </summary>\n /// <param name=\"index\">Index for tensor</param>\n /// <returns>Tensors of index. DataLoader will catenate these tensors as batchSize * 784 for image, batchSize * 1 for label</returns>\n public override Dictionary<string, Tensor> GetTensor(long index)\n {\n var rdic = new Dictionary<string, Tensor>();\n if (transform is not null)\n rdic.Add(\"data\", transform.call(data[(int)index].unsqueeze(0).unsqueeze(0)).squeeze(0));\n else rdic.Add(\"data\", data[(int)index].unsqueeze(0));\n rdic.Add(\"label\", labels[(int)index]);\n return rdic;\n }\n }\n\n internal class FashionMNIST : MNIST\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"root\">Path to the folder containing the image files.</param>\n /// <param name=\"train\">The file name prefix, either 'train' or 't10k' (the latter being the test data set).</param>\n /// <param name=\"download\"></param>\n /// <param name=\"transform\">Transform for input MNIST image</param>\n public FashionMNIST(string root, bool train, bool download = false, torchvision.ITransform transform = null) :\n base(root, \"fashion-mnist\", train ? \"train\" : \"t10k\", \"https://github.com/zalandoresearch/fashion-mnist/raw/master/data/fashion/\", download, transform)\n {\n }\n }\n\n internal class KMNIST : MNIST\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"root\">Path to the folder containing the image files.</param>\n /// <param name=\"train\">The file name prefix, either 'train' or 't10k' (the latter being the test data set).</param>\n /// <param name=\"download\"></param>\n /// <param name=\"transform\">Transform for input MNIST image</param>\n public KMNIST(string root, bool train, bool download = false, torchvision.ITransform transform = null) :\n base(root, \"kmnist\", train ? \"train\" : \"t10k\", \"http://codh.rois.ac.jp/kmnist/dataset/kmnist/\", download, transform)\n {\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5542635917663574, "alphanum_fraction": 0.5542635917663574, "avg_line_length": 26.157894134521484, "blob_id": "1aa4f25d7ed5d9ff66feedd490d1e7d6fbfaf2c7", "content_id": "9a523a102a41071d43c94050dbb2e9c60837828e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 516, "license_type": "permissive", "max_line_length": 130, "num_lines": 19, "path": "/src/TorchAudio/FeatureExtractorNormMode.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n public static partial class models\n {\n /// <summary>\n /// Normalization mode of feature extractor\n /// </summary>\n public enum FeatureExtractorNormMode\n {\n group_norm,\n layer_norm\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6343148946762085, "alphanum_fraction": 0.6364350318908691, "avg_line_length": 55.599998474121094, "blob_id": "6e6ca0ed900c2a5f4d70b21cc6f980e1a7c86470", "content_id": "6892d2b69bf68953cf74b7660ea45ab4f0c1e645", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 12738, "license_type": "permissive", "max_line_length": 217, "num_lines": 225, "path": "/src/TorchSharp/Tensor/torch.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n // This file contains methods that are manipulating Tensors, and are not also defined on the Tensor class.\n public static partial class torch\n {\n /// <summary>\n /// Computes the Cholesky decomposition of a symmetric positive-definite matrix 'input' or for batches of symmetric positive-definite matrices.\n /// </summary>\n /// <param name=\"input\">The input matrix</param>\n /// <param name=\"upper\">If upper is true, the returned matrix U is upper-triangular. If upper is false, the returned matrix L is lower-triangular</param>\n /// <returns></returns>\n public static Tensor cholesky(Tensor input, bool upper) => input.cholesky(upper);\n\n /// <summary>\n /// Returns the matrix norm or vector norm of a given tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor norm(Tensor input) => input.norm();\n\n /// <summary>\n /// Concatenates the given sequence of tensors along the given axis (dimension).\n /// </summary>\n /// <param name=\"tensors\">A sequence of tensors of the same type. Non-empty tensors provided must have the same shape, except in the cat dimension.</param>\n /// <param name=\"axis\">The dimension over which the tensors are concatenated</param>\n /// <returns></returns>\n /// <remarks> All tensors must either have the same shape (except in the concatenating dimension) or be empty.</remarks>\n public static Tensor concatenate(IList<Tensor> tensors, long axis = 0) => torch.cat(tensors, axis);\n\n /// <summary>\n /// Returns a tensor with all the dimensions of input of size 1 removed. When dim is given, a squeeze operation is done only in the given dimension.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">If given, the input will be squeezed only in this dimension</param>\n /// <returns></returns>\n public static Tensor squeeze(Tensor input, long? dim = null) => input.squeeze(dim);\n\n /// <summary>\n /// Modifies (in-place) a tensor with all the dimensions of input of size 1 removed. When dim is given, a squeeze operation is done only in the given dimension.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">If given, the input will be squeezed only in this dimension</param>\n /// <returns></returns>\n public static Tensor squeeze_(Tensor input, long? dim = null) => input.squeeze_(dim);\n\n /// <summary>\n /// Creates a new tensor by horizontally stacking the input tensors.\n /// </summary>\n /// <param name=\"tensors\">A list of input tensors.</param>\n /// <returns></returns>\n /// <remarks>Equivalent to torch.hstack(tensors), except each zero or one dimensional tensor t in tensors is first reshaped into a (t.numel(), 1) column before being stacked horizontally.</remarks>\n public static Tensor column_stack(IList<Tensor> tensors)\n {\n using var parray = new PinnedArray<IntPtr>();\n IntPtr tensorsRef = parray.CreateArray(tensors.Select(p => p.Handle).ToArray());\n\n var res = THSTensor_column_stack(tensorsRef, parray.Array.Length);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Creates a new tensor by horizontally stacking the input tensors.\n /// </summary>\n /// <param name=\"tensors\">A list of input tensors.</param>\n /// <returns></returns>\n /// <remarks>Equivalent to torch.hstack(tensors), except each zero or one dimensional tensor t in tensors is first reshaped into a (t.numel(), 1) column before being stacked horizontally.</remarks>\n public static Tensor column_stack(params Tensor[] tensors) => column_stack((IList<Tensor>)tensors);\n\n /// <summary>\n /// Stack tensors in sequence vertically (row wise).\n /// </summary>\n /// <param name=\"tensors\"></param>\n /// <returns></returns>\n public static Tensor row_stack(IList<Tensor> tensors)\n {\n using var parray = new PinnedArray<IntPtr>();\n IntPtr tensorsRef = parray.CreateArray(tensors.Select(p => p.Handle).ToArray());\n\n var res = THSTensor_row_stack(tensorsRef, parray.Array.Length);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Stack tensors in sequence vertically (row wise).\n /// </summary>\n /// <param name=\"tensors\"></param>\n /// <returns></returns>\n public static Tensor row_stack(params Tensor[] tensors) => row_stack((IList<Tensor>)tensors);\n\n /// <summary>\n /// Removes a tensor dimension.\n /// </summary>\n /// <param name=\"tensor\">The input tensor</param>\n /// <param name=\"dim\">The dimension to remove.</param>\n /// <returns>An array of all slices along a given dimension, already without it.</returns>\n public static Tensor[] unbind(Tensor tensor, int dim = 0) => tensor.unbind(dim);\n\n /// <summary>\n /// Adds all values from the tensor other into input at the indices specified in the index tensor in a similar fashion as scatter_().\n /// For each value in src, it is added to an index in self which is specified by its index in src for dimension != dim and by the\n /// corresponding value in index for dimension = dim.\n /// </summary>\n public static Tensor scatter_add_(Tensor input, long dim, Tensor index, Tensor src) => input.scatter_add_(dim, index, src);\n\n public static Tensor clamp_max(Tensor input, Scalar max) => input.clamp_max(max);\n\n public static Tensor clamp_max_(Tensor input, Scalar max) => input.clamp_max(max);\n\n public static Tensor clamp_min(Tensor input, Scalar min) => input.clamp_min(min);\n\n public static Tensor clamp_min_(Tensor input, Scalar min) => input.clamp_min(min);\n\n /// <summary>\n /// Expands the dimension dim of the self tensor over multiple dimensions of sizes given by sizes.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">Dimension to unflatten.</param>\n /// <param name=\"sizes\">New shape of the unflattened dimension.</param>\n public static Tensor unflatten(Tensor input, long dim, params long[] sizes) => input.unflatten(dim, sizes);\n\n /// <summary>\n /// Expands the dimension dim of the self tensor over multiple dimensions of sizes given by sizes.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">Dimension to unflatten.</param>\n /// <param name=\"sizes\">New shape of the unflattened dimension.</param>\n public static Tensor unflatten(Tensor input, long dim, Size sizes) => input.unflatten(dim, sizes.Shape);\n\n public static Tensor _standard_gamma(Tensor input, Generator? generator = null)\n {\n var res = THSTensor_standard_gamma_(input.Handle, generator is null ? IntPtr.Zero : generator.Handle);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n public static Tensor _sample_dirichlet(Tensor input, Generator? generator = null)\n {\n var res = THSTensor_sample_dirichlet_(input.Handle, generator is null ? IntPtr.Zero : generator.Handle);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Fills the elements of the input tensor with value value by selecting the indices in the order given in index.\n ///\n /// For example, if dim == 0, index[i] == j, and alpha=-1, then the ith row of source is subtracted from the jth row of the input tensor.\n /// The dimth dimension of source must have the same size as the length of index(which must be a vector), and all other dimensions must match self, or an error will be raised.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">Dimension along which to index</param>\n /// <param name=\"index\">Indices of source to select from, should have dtype either torch.int64 or torch.int32</param>\n /// <param name=\"value\">The scalar multiplier for source</param>\n /// <returns></returns>\n public static Tensor index_fill(Tensor input, long dim, Tensor index, Scalar value) => input.index_fill(dim, index, value);\n\n /// <summary>\n /// Fills, in place, the elements of the input tensor with value value by selecting the indices in the order given in index.\n ///\n /// For example, if dim == 0, index[i] == j, and alpha=-1, then the ith row of source is subtracted from the jth row of the input tensor.\n /// The dimth dimension of source must have the same size as the length of index(which must be a vector), and all other dimensions must match self, or an error will be raised.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">Dimension along which to index</param>\n /// <param name=\"index\">Indices of source to select from, should have dtype either torch.int64 or torch.int32</param>\n /// <param name=\"value\">The scalar multiplier for source</param>\n /// <returns></returns>\n public static Tensor index_fill_(Tensor input, long dim, Tensor index, Scalar value) => input.index_fill_(dim, index, value);\n\n /// <summary>\n /// Returns true if the input is a conjugated tensor, i.e. its conjugate bit is set to True.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static bool is_conj(Tensor input) => input.is_conj();\n\n /// <summary>\n /// Calculates the standard deviation and mean of all elements in the tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n public static (Tensor std, Tensor mean) std_mean(Tensor input, bool unbiased = true) => input.std_mean(unbiased);\n\n /// <summary>\n /// Mutates the tensor to be filled with random values taken from a uniform distribution in [0, 1).\n /// </summary>\n public static Tensor rand_out(Tensor input, params long[] sizes) => input.randn_out(sizes);\n\n /// <summary>\n /// Mutates the tensor to be filled with random values taken from a normal distribution with mean 0 and variance 1.\n /// </summary>\n public static Tensor randint_out(Tensor input, long high, long[] sizes) => input.randint_out(high, sizes);\n\n /// <summary>\n /// Returns a tensor with the same size as input that is filled with random numbers from a normal distribution with mean 0 and variance 1.\n /// </summary>\n public static Tensor randn_like(Tensor input, ScalarType? dtype = null, Device? device = null, bool requires_grad = false) => input.randn_like(dtype, device, requires_grad);\n\n /// <summary>\n /// Returns a tensor with the same shape as Tensor input filled with random integers generated uniformly in the range [low,high).\n /// </summary>\n public static Tensor randint_like(Tensor input, long low, long high, ScalarType? dtype = null, Device? device = null, bool requires_grad = false) => input.randint_like(low, high, dtype, device, requires_grad);\n\n /// <summary>\n /// Mutates the tensor to be a 1-D tensor of size [n] with a random permutation of [0, n).\n /// </summary>\n [Obsolete(\"This doesn't exist in PyTorch.\")]\n public static Tensor randperm_out(Tensor input, long n) => torch.randperm(n, input);\n\n /// <summary>\n /// Draws a binomial distribution given a trial count and probabilities.\n /// </summary>\n /// <param name=\"count\">Trial count</param>\n /// <param name=\"probs\">Probability vector</param>\n /// <param name=\"generator\">Optional random number generator</param>\n /// <returns></returns>\n public static Tensor binomial(Tensor count, Tensor probs, Generator? generator = null) => count.binomial(probs, generator);\n }\n}\n" }, { "alpha_fraction": 0.5608370900154114, "alphanum_fraction": 0.5614349842071533, "avg_line_length": 40.8125, "blob_id": "e2ed7a9ea7ec2984d9efcdd2ee0d190ae0e0e42a", "content_id": "d90f2f6359bc49f69b2cf51e30730d1bdad56c0e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3345, "license_type": "permissive", "max_line_length": 171, "num_lines": 80, "path": "/src/TorchSharp/NN/TransformerEncoder.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n public sealed class TransformerEncoder : torch.nn.Module<Tensor, Tensor ,Tensor, Tensor>, torch.nn.IModule<Tensor,Tensor, Tensor>, torch.nn.IModule<Tensor, Tensor>\n {\n public enum Activations\n {\n ReLU = 0,\n GELU = 1\n }\n\n internal TransformerEncoder(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n /// <summary>\n /// Pass the input through the encoder layers in turn.\n /// </summary>\n /// <param name=\"src\">The sequence to the encoder (required).</param>\n /// <param name=\"src_mask\">The additive mask for the src sequence (optional).</param>\n /// <param name=\"src_key_padding_mask\">The ByteTensor mask for src keys per batch (optional).</param>\n /// <returns></returns>\n public override Tensor forward(Tensor src, Tensor src_mask, Tensor src_key_padding_mask)\n {\n var res = THSNN_TransformerEncoder_forward(handle,\n src.Handle,\n src_mask?.Handle ?? IntPtr.Zero,\n src_key_padding_mask?.Handle ?? IntPtr.Zero);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Pass the input through the encoder layers in turn.\n /// </summary>\n /// <param name=\"src\">The sequence to the encoder (required).</param>\n /// <param name=\"src_mask\">The additive mask for the src sequence (optional).</param>\n /// <returns></returns>\n public Tensor call(Tensor src, Tensor src_mask)\n {\n return base.call(src, src_mask, null);\n }\n\n /// <summary>\n /// Pass the input through the encoder layers in turn.\n /// </summary>\n /// <param name=\"src\">The sequence to the encoder (required).</param>\n /// <returns></returns>\n public Tensor call(Tensor src)\n {\n return base.call(src, null, null);\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// TransformerEncoder is a stack of N encoder layers\n /// </summary>\n /// <param name=\"encoder_layer\">An instance of the TransformerEncoderLayer class (required).</param>\n /// <param name=\"num_layers\">The number of sub-encoder-layers in the encoder (required).</param>\n /// <returns></returns>\n public static TransformerEncoder TransformerEncoder(TransformerEncoderLayer encoder_layer, long num_layers)\n {\n var res = THSNN_TransformerEncoder_ctor(encoder_layer.handle, num_layers, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new TransformerEncoder(res, boxedHandle);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6534584760665894, "alphanum_fraction": 0.6840459108352661, "avg_line_length": 31.325841903686523, "blob_id": "9cbb83476ee65e5f26719fcafe6eb4f7281c7c01", "content_id": "13c1c9f0bc4e2c880fb576fd8f89292f2aefddde", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2877, "license_type": "permissive", "max_line_length": 148, "num_lines": 89, "path": "/src/Native/LibTorchSharp/crc32c.h", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "/* Part of CRC-32C library: https://crc32c.machinezoo.com/ */\n/*\n Copyright (c) 2013 - 2014, 2016 Mark Adler, Robert Vazan, Max Vysokikh\n\n This software is provided 'as-is', without any express or implied\n warranty. In no event will the author be held liable for any damages\n arising from the use of this software.\n\n Permission is granted to anyone to use this software for any purpose,\n including commercial applications, and to alter it and redistribute it\n freely, subject to the following restrictions:\n\n 1. The origin of this software must not be misrepresented; you must not\n claim that you wrote the original software. If you use this software\n in a product, an acknowledgment in the product documentation would be\n appreciated but is not required.\n 2. Altered source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n 3. This notice may not be removed or altered from any source distribution.\n*/\n\n#ifndef CRC32C_H\n#define CRC32C_H\n\n#if defined(__GNUC__) || defined(__GNUG__)\n#define CRC32C_GCC\n#elif defined(_MSC_VER)\n#define CRC32C_MSC\n#endif\n\n// ALTERED SOURCE VERSION\n//\n// Per #2 in the copyright notice above:\n//\n// The definition of CRC32C_API has been altered from the original.\n\n#ifndef _WIN32\n#define CRC32C_API __attribute__((visibility(\"default\")))\n#else\n#define CRC32C_API __declspec(dllexport)\n#endif\n\n#include <stdint.h>\n#include <stddef.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*\n Computes CRC-32C (Castagnoli) checksum. Uses Intel's CRC32 instruction if it is available.\n Otherwise it uses a very fast software fallback.\n*/\nCRC32C_API uint32_t crc32c_append(\n uint32_t crc, /* Initial CRC value. Typically it's 0. */\n /* You can supply non-trivial initial value here. */\n /* Initial value can be used to chain CRC from multiple buffers. */\n const uint8_t *input, /* Data to be put through the CRC algorithm. */\n size_t length); /* Length of the data in the input buffer. */\n\n\n/*\n\tSoftware fallback version of CRC-32C (Castagnoli) checksum.\n*/\nCRC32C_API uint32_t crc32c_append_sw(uint32_t crc, const uint8_t *input, size_t length);\n\n/*\n\tHardware version of CRC-32C (Castagnoli) checksum. Will fail, if CPU does not support related instructions. Use a crc32c_append version instead of.\n*/\nCRC32C_API uint32_t crc32c_append_hw(uint32_t crc, const uint8_t *input, size_t length);\n\n/*\n\tChecks is hardware version of CRC-32C is available.\n*/\nCRC32C_API int crc32c_hw_available();\n\n#ifndef __cplusplus\n/*\n Initializes the CRC-32C library. Should be called only by C users to enable hardware version for crc32c_append.\n*/\nCRC32C_API void crc32c_init();\n#endif\n\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n" }, { "alpha_fraction": 0.5698798894882202, "alphanum_fraction": 0.581599771976471, "avg_line_length": 39.630950927734375, "blob_id": "7e19d66eea3dd039f830ee66fcacff989ab8ee3f", "content_id": "239083d4b556f3841809663cb4a4e42f8634b7dd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3413, "license_type": "permissive", "max_line_length": 176, "num_lines": 84, "path": "/src/TorchSharp/Distributions/GumbEL.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n using static torch.distributions;\n\n namespace Modules\n {\n /// <summary>\n /// Samples from a Gumbel Distribution.\n /// </summary>\n public class Gumbel : TransformedDistribution\n {\n internal Gumbel(Tensor loc, Tensor scale, Distribution base_distribution, torch.distributions.transforms.Transform[] transforms, torch.Generator generator = null) :\n base(base_distribution, transforms, generator)\n {\n var locScale = torch.broadcast_tensors(loc, scale);\n this.batch_shape = loc.size();\n this.loc = locScale[0].DetachFromDisposeScope();\n this.scale = locScale[1].DetachFromDisposeScope();\n }\n\n private Tensor loc;\n private Tensor scale;\n\n public override Tensor mean => WrappedTensorDisposeScope(() => loc + scale * euler_constant);\n\n public override Tensor mode => loc;\n\n public override Tensor variance => stddev.pow(2);\n\n public override Tensor stddev => pioversqrtsix * scale;\n\n public override Tensor log_prob(Tensor value)\n {\n using var _ = NewDisposeScope(); \n var y = (loc - value) / scale;\n return ((y - y.exp()) - scale.log()).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n public override Tensor entropy() => WrappedTensorDisposeScope(() => scale.log() + (1 + euler_constant));\n\n private readonly double pioversqrtsix = 1.282549830161864095544036359671; // Math.PI / Math.Sqrt(6);\n }\n }\n\n\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Samples from a Gumbel Distribution.\n /// </summary>\n /// <param name=\"loc\">Location parameter of the distribution.</param>\n /// <param name=\"scale\">Scale parameter of the distribution.</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Gumbel Gumbel(Tensor loc, Tensor scale, torch.Generator generator = null)\n {\n var locScale = torch.broadcast_tensors(loc, scale);\n loc = locScale[0];\n scale = locScale[1];\n\n var finfo = torch.finfo(loc.dtype);\n\n var base_dist = Uniform(torch.full_like(loc, finfo.tiny), torch.full_like(loc, 1 - finfo.eps), generator);\n var transforms = new torch.distributions.transforms.Transform[] {\n new torch.distributions.transforms.LogTransform(),\n new torch.distributions.transforms.AffineTransform(0, -torch.ones_like(scale)),\n new torch.distributions.transforms.LogTransform(),\n new torch.distributions.transforms.AffineTransform(loc, -scale)\n };\n return new Gumbel(loc, scale, base_dist, transforms, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6957463622093201, "alphanum_fraction": 0.6976171731948853, "avg_line_length": 29.772727966308594, "blob_id": "4825d0f5dfdf435f8da130f9b7a11cc77fc4dba1", "content_id": "21b2e14a9806745bc5254ce4635234e5065ad18b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10156, "license_type": "permissive", "max_line_length": 130, "num_lines": 330, "path": "/src/Native/LibTorchSharp/THSActivation.cpp", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#include \"THSNN.h\"\n\n#include <torch/nn/init.h>\n\nNNModule THSNN_CELU_ctor(const double alpha, const bool inplace, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::CELUOptions().alpha(alpha).inplace(inplace);\n res = create_module<torch::nn::CELUImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_CELU_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::CELU>()->forward(*tensor));\n}\n\nNNModule THSNN_ELU_ctor(const double alpha, const bool inplace, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ELUOptions().alpha(alpha).inplace(inplace);\n res = create_module<torch::nn::ELUImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_ELU_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::ELU>()->forward(*tensor));\n}\n\nNNModule THSNN_GELU_ctor(NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n res = create_module<torch::nn::GELUImpl>(outAsAnyModule);\n );\n}\n\nTensor THSNN_GELU_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::GELU>()->forward(*tensor));\n}\n\nNNModule THSNN_GLU_ctor(const int64_t dim, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::GLUOptions().dim(dim);\n res = create_module<torch::nn::GLUImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_GLU_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::GLU>()->forward(*tensor));\n}\n\nNNModule THSNN_Hardshrink_ctor(const double lambda, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::HardshrinkOptions(lambda);\n res = create_module<torch::nn::HardshrinkImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Hardshrink_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Hardshrink>()->forward(*tensor));\n}\n\nNNModule THSNN_Hardtanh_ctor(const double min_val, const double max_val, const bool inplace, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::HardtanhOptions()\n .min_val(min_val)\n .max_val(max_val)\n .inplace(inplace);\n res = create_module<torch::nn::HardtanhImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Hardtanh_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Hardtanh>()->forward(*tensor));\n}\n\n\nNNModule THSNN_LeakyReLU_ctor(const double negative_sloope, const bool inplace, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::LeakyReLUOptions().negative_slope(negative_sloope).inplace(inplace);\n res = create_module<torch::nn::LeakyReLUImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_LeakyReLU_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::LeakyReLU>()->forward(*tensor));\n}\n\nNNModule THSNN_LogSoftmax_ctor(int64_t dim, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::LogSoftmaxOptions(dim);\n res = create_module<torch::nn::LogSoftmaxImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_LogSoftmax_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::LogSoftmax>()->forward(*tensor));\n}\n\nNNModule THSNN_Mish_ctor(NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n res = create_module<torch::nn::MishImpl>(outAsAnyModule);\n );\n}\n\nTensor THSNN_Mish_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Mish>()->forward(*tensor));\n}\n\nNNModule THSNN_PReLU_ctor(const int64_t nparams, const double init, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::PReLUOptions().num_parameters(nparams).init(init);\n res = create_module<torch::nn::PReLUImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_PReLU_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::PReLU>()->forward(*tensor));\n}\n\nTensor THSNN_PReLU_weight(const NNModule module)\n{\n return get_weight<torch::nn::PReLU>(module);\n}\n\nvoid THSNN_PReLU_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::PReLU>(module, weight);\n}\n\nNNModule THSNN_ReLU_ctor(bool inplace, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ReLUOptions(inplace);\n res = create_module<torch::nn::ReLUImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_ReLU_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::ReLU>()->forward(*tensor));\n}\n\nNNModule THSNN_RReLU_ctor(const double lower, const double upper, const bool inplace, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::RReLUOptions().lower(lower).upper(upper).inplace(inplace);\n res = create_module<torch::nn::RReLUImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_RReLU_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::RReLU>()->forward(*tensor));\n}\n\nNNModule THSNN_ReLU6_ctor(bool inplace, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ReLU6Options(inplace);\n res = create_module<torch::nn::ReLU6Impl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_ReLU6_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::ReLU6>()->forward(*tensor));\n}\n\nNNModule THSNN_SELU_ctor(bool inplace, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::SELUOptions(inplace);\n res = create_module<torch::nn::SELUImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_SELU_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::SELU>()->forward(*tensor));\n}\n\nNNModule THSNN_Sigmoid_ctor(NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n res = create_module<torch::nn::SigmoidImpl>(outAsAnyModule);\n );\n}\n\nTensor THSNN_Sigmoid_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Sigmoid>()->forward(*tensor));\n}\n\nNNModule THSNN_SiLU_ctor(NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n res = create_module<torch::nn::SiLUImpl>(outAsAnyModule);\n );\n}\n\nTensor THSNN_SiLU_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::SiLU>()->forward(*tensor));\n}\n\nNNModule THSNN_Softmax2d_ctor(NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n res = create_module<torch::nn::Softmax2dImpl>(outAsAnyModule);\n );\n}\n\nTensor THSNN_Softmax2d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Softmax2d>()->forward(*tensor));\n}\n\nNNModule THSNN_Softmax_ctor(const int64_t dim, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::SoftmaxOptions(dim);\n res = create_module<torch::nn::SoftmaxImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Softmax_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Softmax>()->forward(*tensor));\n}\n\nNNModule THSNN_Softmin_ctor(const int64_t dim, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::SoftminOptions(dim);\n res = create_module<torch::nn::SoftminImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Softmin_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Softmin>()->forward(*tensor));\n}\n\nNNModule THSNN_Softplus_ctor(const double beta, const double threshold, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::SoftplusOptions().beta(beta).threshold(threshold);\n res = create_module<torch::nn::SoftplusImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Softplus_forward(const NNModule module, const Tensor tensor) {\n CATCH_TENSOR((*module)->as<torch::nn::Softplus>()->forward(*tensor));\n}\n\nNNModule THSNN_Softshrink_ctor(const double lambda, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::SoftshrinkOptions().lambda(lambda);\n res = create_module<torch::nn::SoftshrinkImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Softshrink_forward(const NNModule module, const Tensor tensor) {\n CATCH_TENSOR((*module)->as<torch::nn::Softshrink>()->forward(*tensor));\n}\n\nNNModule THSNN_Softsign_ctor(NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n res = create_module<torch::nn::SoftsignImpl>(outAsAnyModule);\n );\n}\n\nTensor THSNN_Softsign_forward(const NNModule module, const Tensor tensor) {\n CATCH_TENSOR((*module)->as<torch::nn::Softsign>()->forward(*tensor));\n}\n\nNNModule THSNN_Tanh_ctor(NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n res = create_module<torch::nn::TanhImpl>(outAsAnyModule);\n );\n}\n\nTensor THSNN_Tanh_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Tanh>()->forward(*tensor));\n}\n\nNNModule THSNN_Tanhshrink_ctor(NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n res = create_module<torch::nn::TanhshrinkImpl>(outAsAnyModule);\n );\n}\n\nTensor THSNN_Tanhshrink_forward(const NNModule module, const Tensor tensor) {\n CATCH_TENSOR((*module)->as<torch::nn::Tanhshrink>()->forward(*tensor));\n}\n\nNNModule THSNN_Threshold_ctor(const double threshold, const double value, const bool inplace, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ThresholdOptions(threshold, value).inplace(inplace);\n res = create_module<torch::nn::ThresholdImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Threshold_forward(const NNModule module, const Tensor tensor) {\n CATCH_TENSOR((*module)->as<torch::nn::Threshold>()->forward(*tensor));\n}\n\n" }, { "alpha_fraction": 0.5740630626678467, "alphanum_fraction": 0.5778073072433472, "avg_line_length": 44.57735061645508, "blob_id": "e61166188c99a32362d9f7d6581df88ee1dfb7b5", "content_id": "8b5ffd362e99fda7d1576e00dd70be89f3070adb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 28577, "license_type": "permissive", "max_line_length": 207, "num_lines": 627, "path": "/src/TorchSharp/Tensor/TensorExtensionMethods.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing static TorchSharp.Utils.LEB128Codec;\n\nnamespace TorchSharp\n{\n using static torch;\n\n public enum TensorStringStyle\n {\n Metadata, // Print only shape, dtype, and device\n Julia, // Print tensor in the style of Julia\n Numpy, // Print tensor in the style of NumPy\n CSharp, // Print tensor in the style of CSharp\n Default, // Pick up the style to use from torch.TensorStringStyle\n }\n\n public static partial class torch\n {\n /// <summary>\n /// The default string formatting style used by ToString(), print(), and str()\n /// </summary>\n public static TensorStringStyle TensorStringStyle {\n get {\n return _style;\n }\n set {\n\n if (value == TensorStringStyle.Default)\n throw new ArgumentException(\"The style cannot be set to 'Default'\");\n _style = value;\n }\n }\n\n /// <summary>\n /// Set options for printing.\n /// </summary>\n /// <param name=\"precision\">Number of digits of precision for floating point output.</param>\n /// <param name=\"linewidth\">The number of characters per line for the purpose of inserting line breaks (default = 100).</param>\n /// <param name=\"newLine\">The string to use to represent new-lines. Starts out as 'Environment.NewLine'</param>\n /// <param name=\"sci_mode\">Enable scientific notation.</param>\n /// <param name=\"maxRows\">The maximum number of rows prrinted.</param>\n /// <param name=\"maxColumns\">The maximum number of columns prrinted.</param>\n public static void set_printoptions(\n int precision,\n int? linewidth = null,\n string? newLine = null,\n bool sci_mode = false,\n int? maxRows = null,\n int? maxColumns = null)\n {\n torch.floatFormat = sci_mode ? $\"E{precision}\" : $\"F{precision}\";\n if (newLine is not null)\n torch.newLine = newLine;\n if (linewidth.HasValue)\n torch.lineWidth = linewidth.Value;\n if (maxRows.HasValue)\n torch.maxRows = maxRows.Value;\n if (maxColumns.HasValue)\n torch.maxColumns = maxColumns.Value;\n }\n\n /// <summary>\n /// Set options for printing.\n /// </summary>\n /// <param name=\"style\">The default string formatting style used by ToString(), print(), and str()</param>\n /// <param name=\"floatFormat\">\n /// The format string to use for floating point values.\n /// See: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings\n /// </param>\n /// <param name=\"linewidth\">The number of characters per line for the purpose of inserting line breaks (default = 100).</param>\n /// <param name=\"newLine\">The string to use to represent new-lines. Starts out as 'Environment.NewLine'</param>\n /// <param name=\"maxRows\">The maximum number of rows prrinted.</param>\n /// <param name=\"maxColumns\">The maximum number of columns prrinted.</param>\n public static void set_printoptions(\n TensorStringStyle? style = null,\n string? floatFormat = null,\n int? linewidth = null,\n string? newLine = null,\n int? maxRows = null,\n int? maxColumns = null)\n {\n if (style.HasValue)\n torch._style = style.Value;\n if (floatFormat is not null)\n torch.floatFormat = floatFormat;\n if (newLine is not null)\n torch.newLine = newLine;\n if (linewidth.HasValue)\n torch.lineWidth = linewidth.Value;\n if (maxRows.HasValue)\n torch.maxRows = maxRows.Value;\n if (maxColumns.HasValue)\n torch.maxColumns = maxColumns.Value;\n }\n\n public const TensorStringStyle julia = TensorStringStyle.Julia;\n public const TensorStringStyle numpy = TensorStringStyle.Numpy;\n public const TensorStringStyle csharp = TensorStringStyle.CSharp;\n\n private static TensorStringStyle _style = TensorStringStyle.Julia;\n\n internal static string floatFormat = \"g5\";\n internal static string newLine = Environment.NewLine;\n internal static int lineWidth = 100;\n internal static int maxRows = 6;\n internal static int maxColumns = 6;\n }\n\n /// <summary>\n /// A few extensions to the Tensor type.\n /// </summary>\n public static class TensorExtensionMethods\n {\n /// <summary>\n /// Convert to a parameter.\n /// </summary>\n /// <param name=\"tensor\">A tensor.</param>\n /// <returns></returns>\n public static Modules.Parameter AsParameter(this Tensor tensor)\n {\n return new Modules.Parameter(tensor);\n }\n\n /// <summary>\n /// Get a string representation of the tensor.\n /// </summary>\n /// <param name=\"tensor\">The input tensor.</param>\n /// <param name=\"fltFormat\">\n /// The format string to use for floating point values.\n /// See: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings\n /// </param>\n /// <param name=\"width\">The width of each line of the output string.</param>\n /// <param name=\"newLine\">The newline string to use, defaults to system default.</param>\n /// <param name=\"cultureInfo\">The culture info to be used when formatting the numbers.</param>\n /// <param name=\"style\">\n /// The style to use -- either 'default,' 'metadata,' 'julia,' or 'numpy'\n /// </param>\n /// <remarks>\n /// This method does exactly the same as ToString(bool, string, int), but is shorter,\n /// looks more like Python 'str' and doesn't require a style argument in order\n /// to discriminate.\n ///\n /// Primarily intended for use in interactive notebooks.\n /// </remarks>\n public static string str(this Tensor tensor, string? fltFormat = null, int? width = null, string? newLine = \"\\n\", CultureInfo? cultureInfo = null, TensorStringStyle style = TensorStringStyle.Default)\n {\n return tensor.ToString(style, fltFormat, width, cultureInfo, newLine);\n }\n\n /// <summary>\n /// Get a Julia-style string representation of the tensor.\n /// </summary>\n /// <param name=\"tensor\">The input tensor.</param>\n /// <param name=\"fltFormat\">\n /// The format string to use for floating point values.\n /// See: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings\n /// </param>\n /// <param name=\"width\">The width of each line of the output string.</param>\n /// <param name=\"newLine\">The newline string to use, defaults to system default.</param>\n /// <param name=\"cultureInfo\">The culture info to be used when formatting the numbers.</param>\n /// <returns></returns>\n /// <remarks>\n /// This method does exactly the same as str(TensorStringStyle.Julia, ...) but is shorter,\n /// looks more like Python 'str' and doesn't require a style argument in order\n /// to discriminate.\n ///\n /// Primarily intended for use in interactive notebooks.\n /// </remarks>\n public static string jlstr(this Tensor tensor, string? fltFormat = null, int? width = null, string? newLine = \"\\n\", CultureInfo? cultureInfo = null)\n {\n return tensor.ToString(TensorStringStyle.Julia, fltFormat, width, cultureInfo, newLine);\n }\n\n /// <summary>\n /// Get a metadata string representation of the tensor.\n /// Creating metadata string will ignore fltFormat, etc. so this method will not accept them as parameter.\n /// </summary>\n /// <param name=\"tensor\">The input tensor.</param>\n /// <returns></returns>\n /// <remarks>\n /// This method does exactly the same as str(TensorStringStyle.Metadata, ...) but is shorter,\n /// looks more like Python 'str' and doesn't require a style argument in order\n /// to discriminate.\n ///\n /// Primarily intended for use in interactive notebooks.\n /// </remarks>\n public static string metastr(this Tensor tensor)\n {\n return tensor.ToString(TensorStringStyle.Metadata);\n }\n\n /// <summary>\n /// Get a numpy-style string representation of the tensor.\n /// </summary>\n /// <param name=\"tensor\">The input tensor.</param>\n /// <param name=\"fltFormat\">\n /// The format string to use for floating point values.\n /// See: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings\n /// </param>\n /// <param name=\"width\">The width of each line of the output string.</param>\n /// <param name=\"newLine\">The newline string to use, defaults to system default.</param>\n /// <param name=\"cultureInfo\">The culture info to be used when formatting the numbers.</param>\n /// <returns></returns>\n /// <remarks>\n /// This method does exactly the same as str(TensorStringStyle.Numpy, ...) but is shorter,\n /// looks more like Python 'str()' and doesn't require a style argument in order\n /// to discriminate.\n ///\n /// Primarily intended for use in interactive notebooks.\n /// </remarks>\n public static string npstr(this Tensor tensor, string? fltFormat = \"g5\", int? width = 100, string? newLine = \"\\n\", CultureInfo? cultureInfo = null)\n {\n return tensor.ToString(TensorStringStyle.Numpy, fltFormat, width, cultureInfo, newLine);\n }\n\n /// <summary>\n /// Get a C#-style string representation of the tensor.\n /// </summary>\n /// <param name=\"tensor\">The input tensor.</param>\n /// <param name=\"fltFormat\">\n /// The format string to use for floating point values.\n /// See: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings\n /// </param>\n /// <param name=\"width\">The width of each line of the output string.</param>\n /// <param name=\"newLine\">The newline string to use, defaults to system default.</param>\n /// <param name=\"cultureInfo\">The culture info to be used when formatting the numbers.</param>\n /// <returns></returns>\n /// <remarks>\n /// This method does exactly the same as str(TensorStringStyle.CSharp, ...) but is shorter,\n /// looks more like Python 'str()' and doesn't require a style argument in order\n /// to discriminate.\n ///\n /// Primarily intended for use in interactive notebooks.\n /// </remarks>\n public static string cstr(this Tensor tensor, string? fltFormat = \"g5\", int? width = 100, string? newLine = \"\\n\", CultureInfo? cultureInfo = null)\n {\n return tensor.ToString(TensorStringStyle.CSharp, fltFormat, width, cultureInfo, newLine);\n }\n\n /// <summary>\n /// Uses Console.WriteLine to print a tensor expression on stdout. This is intended for\n /// interactive notebook use, primarily.\n /// </summary>\n /// <param name=\"t\">The input tensor.</param>\n /// <param name=\"fltFormat\">\n /// The format string to use for floating point values.\n /// See: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings\n /// </param>\n /// <param name=\"width\">The width of each line of the output string.</param>\n /// <param name=\"newLine\">The newline string to use, defaults to system default.</param>\n /// <param name=\"cultureInfo\">The culture info to be used when formatting the numbers.</param>\n /// <param name=\"style\">\n /// The style to use -- either 'default,' 'metadata,' 'julia,' or 'numpy'\n /// </param>\n /// <returns></returns>\n public static Tensor print(this Tensor t, string? fltFormat = \"g5\", int? width = 100, string? newLine = \"\", CultureInfo? cultureInfo = null, TensorStringStyle style = TensorStringStyle.Default)\n {\n Console.WriteLine(t.ToString(style, fltFormat, width, cultureInfo, newLine));\n return t;\n }\n\n /// <summary>\n /// Indicates whether the element type of a given tensor is integral.\n /// </summary>\n /// <param name=\"tensor\">The input tensor.</param>\n /// <returns></returns>\n internal static bool IsIntegral(this Tensor tensor)\n {\n return IsIntegral(tensor.dtype);\n }\n\n public static ReadOnlySpan<int> IntShape(this Tensor tensor)\n {\n var shape = tensor.shape;\n var int_shape = new int[shape.Length];\n for (var i = 0; i < shape.Length; ++i) int_shape[i] = (int)shape[i];\n return int_shape;\n }\n\n /// <summary>\n /// Indicates whether a given element type is integral.\n /// </summary>\n /// <param name=\"type\">The input type.</param>\n /// <returns></returns>\n internal static bool IsIntegral(this ScalarType type)\n {\n switch (type) {\n case ScalarType.Byte:\n case ScalarType.Int8:\n case ScalarType.Int16:\n case ScalarType.Int32:\n case ScalarType.Int64:\n case ScalarType.Bool:\n return true;\n default:\n return false;\n }\n }\n\n /// <summary>\n /// Indicates whether a given element type is real.\n /// </summary>\n /// <param name=\"type\">The input type.</param>\n /// <returns></returns>\n /// <remarks>\n /// Complex numbers are not real, and thus will return 'false'\n /// </remarks>\n internal static bool IsFloatingPoint(this ScalarType type)\n {\n switch (type) {\n case ScalarType.BFloat16:\n case ScalarType.Float16:\n case ScalarType.Float32:\n case ScalarType.Float64:\n return true;\n default:\n return false;\n }\n }\n\n /// <summary>\n /// Indicates whether a given element type is complex.\n /// </summary>\n /// <param name=\"type\">The input type.</param>\n /// <returns></returns>\n /// <remarks>\n /// Complex numbers are not real, and thus will return 'false'\n /// </remarks>\n internal static bool IsComplex(this ScalarType type)\n {\n switch (type) {\n case ScalarType.ComplexFloat32:\n case ScalarType.ComplexFloat64:\n return true;\n default:\n return false;\n }\n }\n\n /// <summary>\n /// Save the tensor in a .NET-specific format.\n /// </summary>\n /// <param name=\"tensor\"></param>\n /// <param name=\"writer\"></param>\n public static void Save(this Tensor tensor, System.IO.BinaryWriter writer)\n {\n bool copied = false;\n\n if (tensor.device_type != DeviceType.CPU) {\n tensor = tensor.to(CPU);\n copied = true;\n }\n\n // First, write the type\n writer.Encode((int)tensor.dtype); // 4 bytes\n // Then, the shape.\n writer.Encode(tensor.shape.Length); // 4 bytes\n foreach (var s in tensor.shape) writer.Encode(s); // n * 8 bytes\n // Then, the data\n#if NETSTANDARD2_0_OR_GREATER\n // TODO: NETSTANDARD2_0_OR_GREATER Try to optimize to avoid the allocation\n writer.Write(tensor.bytes.ToArray()); // ElementSize * NumberOfElements\n#else\n writer.Write(tensor.bytes); // ElementSize * NumberOfElements\n#endif // NETSTANDARD2_0_OR_GREATER\n\n if (copied) tensor.Dispose();\n }\n\n /// <summary>\n /// Load the tensor using a .NET-specific format.\n /// </summary>\n /// <param name=\"tensor\">The tensor into which to load serialized data.</param>\n /// <param name=\"reader\">A BinaryReader instance</param>\n /// <param name=\"skip\">If true, the data will be read from the stream, but not copied to the target tensor.</param>\n /// <remarks>\n /// Using a skip list only prevents tensors in the target module from being modified, it\n /// does not alter the logic related to checking for matching tensor element types.\n /// </remarks>\n public static void Load(this Tensor tensor, System.IO.BinaryReader reader, bool skip = false)\n {\n // First, read the type\n var type = (ScalarType)reader.Decode();\n\n if (type != tensor.dtype)\n throw new ArgumentException(\"Mismatched tensor data types while loading. Make sure that the model you are loading into is exactly the same as the origin.\");\n\n // Then, the shape\n var shLen = reader.Decode();\n long[] loadedShape = new long[shLen];\n\n long totalSize = 1;\n for (int i = 0; i < shLen; ++i) {\n loadedShape[i] = reader.Decode();\n totalSize *= loadedShape[i];\n }\n\n if (!skip && !loadedShape.SequenceEqual(tensor.shape))\n // We only care about this if the bytes will be written to the tensor.\n throw new ArgumentException(\"Mismatched tensor shape while loading. Make sure that the model you are loading into is exactly the same as the origin.\");\n\n //\n // TODO: Fix this so that you can read large tensors. Right now, they are limited to 2GB\n //\n if (totalSize > int.MaxValue)\n throw new NotImplementedException(\"Loading tensors larger than 2GB\");\n\n // This needs to be done even if the tensor is skipped, since we have to advance the input stream.\n var bytes = reader.ReadBytes((int)(totalSize * tensor.ElementSize));\n\n if (!skip) {\n var device = tensor.device;\n if (device.type != DeviceType.CPU) tensor.to(CPU);\n tensor.bytes = bytes;\n tensor.to(device);\n }\n }\n\n public static void Load(ref Tensor tensor, System.IO.BinaryReader reader, bool skip = false)\n {\n // First, read the type\n var type = (ScalarType)reader.Decode();\n\n // Then, the shape\n var shLen = reader.Decode();\n long[] loadedShape = new long[shLen];\n\n long totalSize = 1;\n for (int i = 0; i < shLen; ++i) {\n loadedShape[i] = reader.Decode();\n totalSize *= loadedShape[i];\n }\n\n //\n // TODO: Fix this so that you can read large tensors. Right now, they are limited to 2GB\n //\n if (totalSize > int.MaxValue)\n throw new NotImplementedException(\"Loading tensors larger than 2GB\");\n\n if (tensor is null) {\n // If the tensor doesn't exist, initialize by zeros unless\n // it's going to be loaded from the stream.\n tensor = skip\n ? torch.zeros(loadedShape, dtype: type)\n : torch.empty(loadedShape, dtype: type);\n } else if (!skip && !loadedShape.SequenceEqual(tensor.shape)) {\n // We only care about this if the bytes will be written to the tensor.\n throw new ArgumentException(\"Mismatched tensor shape while loading. Make sure that the model you are loading into is exactly the same as the origin.\");\n }\n\n // This needs to be done even if the tensor is skipped, since we have to advance the input stream.\n var bytes = reader.ReadBytes((int)(totalSize * tensor.ElementSize));\n\n if (!skip) {\n var device = tensor.device;\n if (device.type != DeviceType.CPU) tensor.to(CPU);\n tensor.bytes = bytes;\n tensor.to(device);\n }\n }\n\n /// <summary>\n /// Creating a tensor form an array of data.\n /// </summary>\n /// <typeparam name=\"T\">The .NET element type.</typeparam>\n /// <param name=\"rawArray\">Input data.</param>\n /// <param name=\"dimensions\">The shape of the tensor that is created.</param>\n /// <param name=\"doCopy\">Perform a copy rather than using the array as backing storage for the tensor.</param>\n /// <param name=\"requires_grad\">If true, the tensor must track its gradients.</param>\n /// <returns></returns>\n public static Tensor ToTensor<T>(this T[] rawArray, long[] dimensions, bool doCopy = false, bool requires_grad = false)\n {\n var array = doCopy ? (T[])rawArray.Clone() : rawArray;\n\n return true switch {\n true when typeof(T) == typeof(byte) => tensor((array as byte[])!, dimensions,\n requires_grad: requires_grad),\n true when typeof(T) == typeof(sbyte) => tensor((array as sbyte[])!, dimensions,\n requires_grad: requires_grad),\n true when typeof(T) == typeof(short) => tensor((array as short[])!, dimensions,\n requires_grad: requires_grad),\n true when typeof(T) == typeof(int) => tensor((array as int[])!, dimensions,\n requires_grad: requires_grad),\n true when typeof(T) == typeof(long) => tensor((array as long[])!, dimensions,\n requires_grad: requires_grad),\n true when typeof(T) == typeof(double) => tensor((array as double[])!, dimensions,\n requires_grad: requires_grad),\n true when typeof(T) == typeof(float) => tensor((array as float[])!, dimensions,\n requires_grad: requires_grad),\n true when typeof(T) == typeof(bool) => tensor((array as bool[])!, dimensions,\n requires_grad: requires_grad),\n _ => throw new NotImplementedException($\"Creating tensor of type {typeof(T)} is not supported.\")\n };\n }\n\n /// <summary>\n /// Creating a tensor from a scalar value.\n /// </summary>\n /// <typeparam name=\"T\">The .NET element type.</typeparam>\n /// <param name=\"scalar\">Scalar input value</param>\n /// <param name=\"device\">The device to place the tensor on.</param>\n /// <param name=\"requires_grad\">If true, the tensor must track its gradients.</param>\n /// <returns></returns>\n public static Tensor ToTensor<T>(this T scalar, Device? device = null, bool requires_grad = false) where T : struct\n {\n if (requires_grad && typeof(T) != typeof(float) && typeof(T) != typeof(double)) {\n throw new ArgumentException(nameof(requires_grad), \"Only floating point types support gradients.\");\n }\n\n if (typeof(T) == typeof(byte))\n return tensor((byte)(object)scalar, uint8, device, requires_grad);\n if (typeof(T) == typeof(sbyte))\n return tensor((sbyte)(object)scalar, int8, device, requires_grad);\n if (typeof(T) == typeof(short))\n return tensor((short)(object)scalar, int16, device, requires_grad);\n if (typeof(T) == typeof(int))\n return tensor((int)(object)scalar, int32, device, requires_grad);\n if (typeof(T) == typeof(long))\n return tensor((long)(object)scalar, int64, device, requires_grad);\n if (typeof(T) == typeof(float))\n return tensor((float)(object)scalar, float32, device, requires_grad);\n if (typeof(T) == typeof(double))\n return tensor((double)(object)scalar, float64, device, requires_grad);\n throw new NotImplementedException($\"Creating tensor of type {typeof(T)} is not supported.\");\n }\n\n /// <summary>\n /// Explicitly convert a singleton tensor to a .NET scalar value.\n /// </summary>\n /// <param name=\"value\">The input tensor</param>\n public static (float Real, float Imaginary) ToComplexFloat32(this Tensor value) => value.ToScalar().ToComplexFloat32();\n\n /// <summary>\n /// Explicitly convert a singleton tensor to a .NET scalar value.\n /// </summary>\n /// <param name=\"value\">The input tensor</param>\n public static System.Numerics.Complex ToComplexFloat64(this Tensor value) => value.ToScalar().ToComplexFloat64();\n\n#if NET6_0_OR_GREATER\n /// <summary>\n /// Explicitly convert a singleton tensor to a .NET scalar value.\n /// </summary>\n /// <param name=\"value\">The input tensor</param>\n public static Half ToHalf(this Tensor value) => value.ToScalar().ToHalf();\n#endif\n\n /// <summary>\n /// Explicitly convert a singleton tensor to a .NET scalar value.\n /// </summary>\n /// <param name=\"value\">The input tensor</param>\n public static float ToSingle(this Tensor value) => value.ToScalar().ToSingle();\n\n /// <summary>\n /// Explicitly convert a singleton tensor to a .NET scalar value.\n /// </summary>\n /// <param name=\"value\">The input tensor</param>\n public static double ToDouble(this Tensor value) => value.ToScalar().ToDouble();\n\n /// <summary>\n /// Explicitly convert a singleton tensor to a .NET scalar value.\n /// </summary>\n /// <param name=\"value\">The input tensor</param>\n public static sbyte ToSByte(this Tensor value) => value.ToScalar().ToSByte();\n\n /// <summary>\n /// Explicitly convert a singleton tensor to a .NET scalar value.\n /// </summary>\n /// <param name=\"value\">The input tensor</param>\n public static byte ToByte(this Tensor value) => value.ToScalar().ToByte();\n\n /// <summary>\n /// Explicitly convert a singleton tensor to a .NET scalar value.\n /// </summary>\n /// <param name=\"value\">The input tensor</param>\n public static short ToInt16(this Tensor value) => value.ToScalar().ToInt16();\n\n /// <summary>\n /// Explicitly convert a singleton tensor to a .NET scalar value.\n /// </summary>\n /// <param name=\"value\">The input tensor</param>\n public static int ToInt32(this Tensor value) => value.ToScalar().ToInt32();\n\n /// <summary>\n /// Explicitly convert a singleton tensor to a .NET scalar value.\n /// </summary>\n /// <param name=\"value\">The input tensor</param>\n public static long ToInt64(this Tensor value) => value.ToScalar().ToInt64();\n\n /// <summary>\n /// Explicitly convert a singleton tensor to a .NET scalar value.\n /// </summary>\n /// <param name=\"value\">The input tensor</param>\n public static bool ToBoolean(this Tensor value) => value.ToScalar().ToBoolean();\n\n\n /// <summary>\n /// Explicitly convert a singleton tensor to a .NET scalar value.\n /// </summary>\n /// <param name=\"value\">The input tensor</param>\n public static (float Real, float Imaginary) ToComplex32(this Tensor value) => value.ToScalar().ToComplexFloat32();\n\n /// <summary>\n /// Explicitly convert a singleton tensor to a .NET scalar value.\n /// </summary>\n /// <param name=\"value\">The input tensor</param>\n public static System.Numerics.Complex ToComplex64(this Tensor value) => value.ToScalar().ToComplexFloat64();\n\n /// <summary>\n /// Multiply the dimensions of a tensor shape to provide a complete size.\n /// </summary>\n /// <param name=\"shape\">The shape.</param>\n /// <returns></returns>\n public static long TotalSize(this IEnumerable<long> shape)\n {\n long result = 1;\n foreach (var sz in shape) {\n result *= sz;\n }\n return result;\n }\n }\n}\n" }, { "alpha_fraction": 0.4054102599620819, "alphanum_fraction": 0.4857393801212311, "avg_line_length": 39.48113250732422, "blob_id": "26245a406d58251ceaf07e9edad9824a2a57d6d6", "content_id": "cefbf0ac06f85965f8f7f3067307dad50e91e6fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 55783, "license_type": "permissive", "max_line_length": 158, "num_lines": 1378, "path": "/test/TorchSharpTest/TestDistributions.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.distributions;\n\nusing Xunit;\nusing System;\n\n#nullable enable\n\nnamespace TorchSharp\n{\n [Collection(\"Sequential\")]\n public class TestDistributions\n {\n [Fact]\n public void TestUniform()\n {\n var dist = Uniform(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(3.5));\n Assert.True(torch.tensor(new[] { 2, 1.875, 1.825, }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.75, 0.88020833, 0.93520833 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 1.0986123, 1.178655, 1.2089603 }).allclose(dist.entropy(), rtol: 1e-3, atol: 1e-4));\n Assert.True(torch.tensor(new[] { 0.16666667, 0.2307692308, 0.2537313433 }).allclose(dist.cdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { 3.5000, 3.5000, 3.5000 }).allclose(dist.icdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { -1.0986123, -1.178655, -1.2089603 }).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d >= 0 && d < 3.5));\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d >= 0 && d < 3.5));\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d >= 0 && d < 3.5));\n }\n }\n\n [Fact]\n public void TestUniformGen()\n {\n var gen = new Generator(4711);\n\n var dist = Uniform(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(3.5), gen);\n Assert.True(torch.tensor(new[] { 2, 1.875, 1.825, }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.75, 0.88020833, 0.93520833 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 1.0986123, 1.178655, 1.2089603 }).allclose(dist.entropy(), rtol: 1e-3, atol: 1e-4));\n Assert.True(torch.tensor(new[] { 0.16666667, 0.2307692308, 0.2537313433 }).allclose(dist.cdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { 3.5000, 3.5000, 3.5000 }).allclose(dist.icdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { -1.0986123, -1.178655, -1.2089603 }).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d >= 0 && d < 3.5));\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d >= 0 && d < 3.5));\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d >= 0 && d < 3.5));\n }\n }\n\n [Fact]\n public void TestNormal()\n {\n var dist = Normal(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }), torch.tensor(new[] { 0.15, 0.05, 0.25 }));\n Assert.True(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.0225, 0.0025, 0.0625 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }).allclose(dist.mode));\n\n Assert.True(torch.tensor(new[] { -4.5774, -110.4232, -26.9126 }).allclose(dist.log_prob(torch.arange(3))));\n Assert.True(torch.tensor(new[] { -0.478181, -1.576794, 0.032644 }).allclose(dist.entropy(), rtol: 1e-3, atol: 1e-4));\n\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestNormalGen()\n {\n var gen = new Generator(4711);\n\n var dist = Normal(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }), torch.tensor(new[] { 0.15, 0.05, 0.25 }), gen);\n Assert.True(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.0225, 0.0025, 0.0625 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }).allclose(dist.mode));\n\n Assert.True(torch.tensor(new[] { -4.5774, -110.4232, -26.9126 }).allclose(dist.log_prob(torch.arange(3))));\n Assert.True(torch.tensor(new[] { -0.478181, -1.576794, 0.032644 }).allclose(dist.entropy()));\n\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestHalfNormal()\n {\n var dist = HalfNormal(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }));\n Assert.True(torch.tensor(new[] { 0.39894228, 0.19947114, 0.11968268 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.0, 0.0, 0.0 }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { 0.090845057, 0.022711264, 0.0081760551 }).allclose(dist.variance));\n\n Assert.True(torch.tensor(new[] { 0.9544997, 0.9999366, 0.99999999 }).allclose(dist.cdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { 0.032644172, -0.66050301, -1.1713286 }).allclose(dist.entropy()));\n Assert.True(torch.tensor(new[] { -1.5326442, -6.839497, -20.550894 }).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestHalfNormalGen()\n {\n var dist = HalfNormal(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }), new Generator(4711));\n Assert.True(torch.tensor(new[] { 0.39894228, 0.19947114, 0.11968268 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.0, 0.0, 0.0 }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { 0.090845057, 0.022711264, 0.0081760551 }).allclose(dist.variance));\n\n Assert.True(torch.tensor(new[] { 0.9544997, 0.9999366, 0.99999999 }).allclose(dist.cdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { 0.032644172, -0.66050301, -1.1713286 }).allclose(dist.entropy()));\n Assert.True(torch.tensor(new[] { -1.5326442, -6.839497, -20.550894 }).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestHalfCauchy()\n {\n var dist = HalfCauchy(torch.tensor(new[] { 0.5, 0.25, 0.15 }));\n Assert.True(torch.tensor(new[] { 0.0, 0.0, 0.0 }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { 0.70483276, 0.84404174, 0.90521372 }).allclose(dist.cdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { -11438666, -5719333, -3431599.8 }).allclose(dist.icdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { 1.1447299, 0.45158271, -0.059242918 }).allclose(dist.entropy()));\n Assert.True(torch.tensor(new[] { -1.3678734, -1.8985017, -2.3709533 }).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestHalfCauchyGen()\n {\n var dist = HalfCauchy(torch.tensor(new[] { 0.5, 0.25, 0.15 }), new Generator(4711));\n Assert.True(torch.tensor(new[] { 0.0, 0.0, 0.0 }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { 0.70483276, 0.84404174, 0.90521372 }).allclose(dist.cdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { -11438666, -5719333, -3431599.8 }).allclose(dist.icdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { 1.1447299, 0.45158271, -0.059242918 }).allclose(dist.entropy()));\n Assert.True(torch.tensor(new[] { -1.3678734, -1.8985017, -2.3709533 }).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestPareto()\n {\n var dist = Pareto(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(1.0));\n Assert.True(torch.tensor(new[] { 0.5, 0.25, 0.15, }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { 0.5000, 0.7500, 0.8500 }).allclose(dist.cdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { 1.3068528, 0.61370564, 0.10288002 }).allclose(dist.entropy()));\n Assert.True(torch.tensor(new[] { -0.69314718, -1.3862944, -1.89712 }).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestParetoGen()\n {\n var dist = Pareto(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(1.0), new Generator(4711));\n Assert.True(torch.tensor(new[] { 0.5, 0.25, 0.15, }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { 0.5000, 0.7500, 0.8500 }).allclose(dist.cdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { 1.3068528, 0.61370564, 0.10288002 }).allclose(dist.entropy()));\n Assert.True(torch.tensor(new[] { -0.69314718, -1.3862944, -1.89712 }).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestLogNormal()\n {\n var dist = LogNormal(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(0.5));\n Assert.True(torch.tensor(new[] { 1.868246, 1.4549914, 1.3165307 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 1.2840254, 1, 0.90483742 }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { 0.99134611, 0.60128181, 0.49228791 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 1.2257914, 0.97579135, 0.87579135 }).allclose(dist.entropy()));\n Assert.True(torch.tensor(new[] { 0.15865525, 0.308537538, 0.38208857 }).allclose(dist.cdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity }).allclose(dist.icdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { -0.72579135, -0.35079135, -0.27079135 }).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestLogNormalGen()\n {\n var dist = LogNormal(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(0.5), new Generator(4711));\n Assert.True(torch.tensor(new[] { 1.868246, 1.4549914, 1.3165307 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 1.2840254, 1, 0.90483742 }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { 0.99134611, 0.60128181, 0.49228791 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 1.2257914, 0.97579135, 0.87579135 }).allclose(dist.entropy()));\n Assert.True(torch.tensor(new[] { 0.15865525, 0.308537538, 0.38208857 }).allclose(dist.cdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity }).allclose(dist.icdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { -0.72579135, -0.35079135, -0.27079135 }).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestGumbel()\n {\n var dist = Gumbel(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(3.5));\n Assert.True(torch.tensor(new[] { 2.5202548, 2.2702548, 2.1702548 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.5, 0.25, 0.15 }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { 20.150442, 20.150442, 20.150442 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 2.8299786, 2.8299786, 2.8299786 }).allclose(dist.entropy()));\n Assert.True(torch.tensor(new[] { 0.42026160, 0.44614211, 0.456400959 }).allclose(dist.cdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { -2.26249801, -2.274166429, -2.28000367 }).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestGumbelGen()\n {\n var dist = Gumbel(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(3.5), new Generator(4711));\n Assert.True(torch.tensor(new[] { 2.5202548, 2.2702548, 2.1702548 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.5, 0.25, 0.15 }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { 20.150442, 20.150442, 20.150442 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 2.8299786, 2.8299786, 2.8299786 }).allclose(dist.entropy()));\n Assert.True(torch.tensor(new[] { 0.42026160, 0.44614211, 0.456400959 }).allclose(dist.cdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { -2.26249801, -2.274166429, -2.28000367 }).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestLaplace()\n {\n var dist = Laplace(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(0.5));\n Assert.True(torch.tensor(new[] { 0.5, 0.25, 0.15 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.5, 0.25, 0.15 }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { 0.5, 0.5, 0.5 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 1.0, 1.0, 1.0 }).allclose(dist.entropy()));\n Assert.True(torch.tensor(new[] { 0.81606028, 0.88843492, 0.90865824 }).allclose(dist.cdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity }).allclose(dist.icdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { -1, -1.5, -1.7 }).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestLaplaceGen()\n {\n var gen = new Generator(4711);\n\n var dist = Laplace(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(0.5), gen);\n Assert.True(torch.tensor(new[] { 0.5, 0.25, 0.15 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.5, 0.25, 0.15 }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { 0.5, 0.5, 0.5 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 1.0, 1.0, 1.0 }).allclose(dist.entropy()));\n Assert.True(torch.tensor(new[] { 0.81606028, 0.88843492, 0.90865824 }).allclose(dist.cdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity }).allclose(dist.icdf(torch.ones(3))));\n Assert.True(torch.tensor(new[] { -1, -1.5, -1.7 }).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestPoisson()\n {\n var dist = Poisson(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }));\n Assert.True(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 0.0, 0.0, 0.0 }).allclose(dist.mode));\n\n var log_prob = dist.log_prob(torch.arange(3));\n\n Assert.True(torch.tensor(new[] { -0.5000, -1.6363, -4.6374 }).allclose(log_prob));\n\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestPoissonGen()\n {\n var gen = new Generator(4711);\n var dist = Poisson(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }), gen);\n Assert.True(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 0.0, 0.0, 0.0 }).allclose(dist.mode));\n\n var log_prob = dist.log_prob(torch.arange(3));\n\n Assert.True(torch.tensor(new[] { -0.5000, -1.6363, -4.6374 }).allclose(log_prob));\n\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestBernoulli()\n {\n var dist = Bernoulli(torch.tensor(new[] { 0.5, 0.25, 0.15 }));\n Assert.True(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.2500, 0.1875, 0.1275 }).allclose(dist.variance, rtol: 1e-3, atol: 1e-4));\n Assert.True(torch.tensor(new[] { -0.69314718, -1.38629436, -1.897119984 }).allclose(dist.log_prob(torch.ones(3).to(torch.float64))));\n Assert.True(torch.tensor(new[] { 0.693147181, 0.5623351446, 0.4227090878 }).allclose(dist.entropy()));\n\n {\n var sample = dist.sample();\n\n Assert.Single(sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d == 0 || d == 1));\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d == 0 || d == 1));\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d == 0 || d == 1));\n }\n }\n\n [Fact]\n public void TestBernoulliGen()\n {\n var gen = new Generator(4711);\n var dist = Bernoulli(torch.tensor(new[] { 0.5, 0.25, 0.15 }), generator: gen);\n Assert.True(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.2500, 0.1875, 0.1275 }).allclose(dist.variance, rtol: 1e-3, atol: 1e-4));\n Assert.True(torch.tensor(new[] { -0.69314718, -1.38629436, -1.897119984 }).allclose(dist.log_prob(torch.ones(3).to(torch.float64))));\n Assert.True(torch.tensor(new[] { 0.693147181, 0.5623351446, 0.4227090878 }).allclose(dist.entropy()));\n\n {\n var sample = dist.sample();\n\n Assert.Single(sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d == 0 || d == 1));\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d == 0 || d == 1));\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d == 0 || d == 1));\n }\n }\n\n [Fact]\n public void TestLogitRelaxedBernoulli()\n {\n var temp = torch.rand(3, dtype: ScalarType.Float64);\n\n var dist = LogitRelaxedBernoulli(temp, torch.rand(3, dtype: ScalarType.Float64));\n {\n var sample = dist.sample();\n\n Assert.Single(sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestLogitRelaxedBernoulliGen()\n {\n var gen = new Generator(4711);\n var temp = torch.rand(3, dtype: ScalarType.Float64);\n\n var dist = LogitRelaxedBernoulli(temp, torch.rand(3, dtype: ScalarType.Float64), generator: gen);\n {\n var sample = dist.sample();\n\n Assert.Single(sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestRelaxedBernoulli()\n {\n var temp = torch.rand(3, dtype: ScalarType.Float64);\n\n var dist = RelaxedBernoulli(temp, torch.rand(3, dtype: ScalarType.Float64));\n {\n var sample = dist.sample();\n\n Assert.Single(sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestRelaxedBernoulliGen()\n {\n var gen = new Generator(4711);\n var temp = torch.rand(3, dtype: ScalarType.Float64);\n\n var dist = RelaxedBernoulli(temp, torch.rand(3, dtype: ScalarType.Float64), generator: gen);\n {\n var sample = dist.sample();\n\n Assert.Single(sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestBeta()\n {\n var dist = Beta(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(0.15f));\n Assert.True(torch.tensor(new[] { 0.769230762, 0.62499999, 0.5000 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 1.0, 1.0, 1.0 }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { 0.10758472, 0.16741072, 0.192307691 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { -3.0250008, -2.72106057, -3.4215678 }).allclose(dist.entropy()));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestBetaGen()\n {\n var gen = new Generator(4711);\n var dist = Beta(torch.rand(3, 3) * 0.5f, torch.tensor(0.5f), gen);\n {\n var sample = dist.sample();\n var entropy = dist.entropy();\n\n Assert.Equal(new long[] { 3, 3 }, sample.shape);\n Assert.Equal(new long[] { 3, 3 }, entropy.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestBinomial()\n {\n var dist = Binomial(torch.tensor(100), torch.tensor(new[] { 0.25, 0.25, 0.15 }));\n Assert.True(torch.tensor(new[] { 25.0, 25.0, 15.0 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 18.7500, 18.7500, 12.7500 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 25.0, 25.0, 15.0 }).allclose(dist.mode));\n\n var log_prob = dist.log_prob(torch.arange(3));\n\n Assert.True(torch.tensor(new[] { -28.7682, -25.2616, -11.2140 }).allclose(log_prob));\n\n {\n var sample = dist.sample();\n\n Assert.Single(sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d >= 0 && d <= 100));\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d >= 0 && d <= 100));\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d >= 0 && d <= 100));\n }\n }\n\n [Fact]\n public void TestBinomialGen()\n {\n var gen = new Generator(4711);\n var dist = Binomial(torch.tensor(100), torch.tensor(new[] { 0.25, 0.25, 0.15 }), generator: gen);\n Assert.True(torch.tensor(new[] { 25.0, 25.0, 15.0 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 18.7500, 18.7500, 12.7500 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 25.0, 25.0, 15.0 }).allclose(dist.mode));\n\n var log_prob = dist.log_prob(torch.arange(3));\n\n Assert.True(torch.tensor(new[] { -28.7682, -25.2616, -11.2140 }).allclose(log_prob));\n\n {\n var sample = dist.sample();\n\n Assert.Single(sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d >= 0 && d <= 100));\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d >= 0 && d <= 100));\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d >= 0 && d <= 100));\n }\n }\n\n [Fact]\n public void TestNegativeBinomial()\n {\n var dist = NegativeBinomial(torch.tensor(100), torch.tensor(new[] { 0.25, 0.25, 0.15 }));\n Assert.True(torch.tensor(new[] { 33.3333, 33.3333, 17.6471 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 44.4444, 44.4444, 20.7612 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 33.0, 33.0, 17.0 }).allclose(dist.mode));\n\n var log_prob = dist.log_prob(torch.arange(3));\n\n Assert.True(torch.tensor(new[] { -28.7682, -25.5493, -11.5190 }).allclose(log_prob));\n\n {\n var sample = dist.sample();\n\n Assert.Single(sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d >= 0 && d <= 100));\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d >= 0 && d <= 100));\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n Assert.All<double>(sample.data<double>().ToArray(), d => Assert.True(d >= 0 && d <= 100));\n }\n }\n\n [Fact]\n public void TestCategorical()\n {\n var gen = new Generator(4711);\n var categories = 7;\n var dist = Categorical(torch.rand(3, categories, dtype: ScalarType.Float64));\n {\n var sample = dist.sample();\n\n Assert.Single(sample.shape);\n Assert.Equal(3, sample.shape[0]);\n Assert.All<long>(sample.data<long>().ToArray(), l => Assert.True(l >= 0 && l < categories));\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n Assert.All<long>(sample.data<long>().ToArray(), l => Assert.True(l >= 0 && l < categories));\n }\n }\n\n\n [Fact]\n public void TestCategoricalGen()\n {\n var gen = new Generator(4711);\n var categories = 7;\n var dist = Categorical(torch.rand(3, categories, dtype: ScalarType.Float64), generator: gen);\n {\n var sample = dist.sample();\n\n Assert.Single(sample.shape);\n Assert.Equal(3, sample.shape[0]);\n Assert.All<long>(sample.data<long>().ToArray(), l => Assert.True(l >= 0 && l < categories));\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n Assert.All<long>(sample.data<long>().ToArray(), l => Assert.True(l >= 0 && l < categories));\n }\n }\n\n [Fact]\n public void TestOneHotCategorical()\n {\n var categories = 7;\n var dist = OneHotCategorical(torch.rand(3, categories, dtype: ScalarType.Float64));\n {\n var sample = dist.sample();\n\n Assert.Equal(2, sample.ndim);\n Assert.Equal(3, sample.shape[0]);\n Assert.Equal(categories, sample.shape[1]);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(4, sample.ndim);\n Assert.Equal(new long[] { 2, 3, 3, 7 }, sample.shape);\n }\n }\n\n\n [Fact]\n public void TestOneHotCategoricalGen()\n {\n var gen = new Generator(4711);\n var categories = 7;\n var dist = OneHotCategorical(torch.rand(3, categories, dtype: ScalarType.Float64, generator: gen));\n {\n var sample = dist.sample();\n\n Assert.Equal(2, sample.ndim);\n Assert.Equal(3, sample.shape[0]);\n Assert.Equal(categories, sample.shape[1]);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(4, sample.ndim);\n Assert.Equal(new long[] { 2, 3, 3, 7 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestCauchy()\n {\n var dist = Cauchy(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(new[] { 0.05, 0.10, 0.15 }));\n\n Assert.True(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { -2.7641, -2.8896, -2.7475 }).allclose(dist.log_prob(torch.ones(3))));\n Assert.True(torch.tensor(new[] { -0.46470802658, 0.22843915398, 0.633904262 }).allclose(dist.entropy()));\n\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestCauchyGen()\n {\n var gen = new Generator(4711);\n var dist = Cauchy(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(new[] { 0.05, 0.10, 0.15 }), gen);\n Assert.True(torch.tensor(new[] { 0.5000, 0.2500, 0.1500 }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { -2.7641, -2.8896, -2.7475 }).allclose(dist.log_prob(torch.ones(3))));\n Assert.True(torch.tensor(new[] { -0.46470802658, 0.22843915398, 0.633904262 }).allclose(dist.entropy()));\n\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestChi2()\n {\n var dist = Chi2(torch.tensor(new[] { 0.5, 0.25, 0.15 }));\n Assert.True(torch.tensor(new[] { 0.5, 0.25, 0.15 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 1, 0.5, 0.3 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { -1.9613093, -2.6060618, -3.1034275, }).allclose(dist.log_prob(torch.ones(3))));\n Assert.True(torch.tensor(new[] { -0.9394204, -4.502366, -9.439412 }).allclose(dist.entropy()));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestChi2Gen()\n {\n var gen = new Generator(4711);\n var dist = Chi2(torch.tensor(new[] { 0.5, 0.25, 0.15 }), gen);\n Assert.True(torch.tensor(new[] { 0.5, 0.25, 0.15 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 1, 0.5, 0.3 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { -1.9613093, -2.6060618, -3.1034275, }).allclose(dist.log_prob(torch.ones(3))));\n Assert.True(torch.tensor(new[] { -0.9394204, -4.502366, -9.439412 }).allclose(dist.entropy()));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestDirichlet()\n {\n var dist = Dirichlet(torch.tensor(new[] { 0.5, 0.25, 0.15 }));\n Assert.True(torch.tensor(new[] { 0.55555556, 0.27777778, 0.16666667, }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.12995452, 0.10558804, 0.073099415 }).allclose(dist.variance));\n Assert.True(torch.tensor(-4.9130).allclose(dist.entropy()));\n Assert.True(torch.tensor(-3.621825).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestDirichletGen()\n {\n var gen = new Generator(4711);\n var dist = Dirichlet(torch.tensor(new[] { 0.5, 0.25, 0.15 }), gen);\n Assert.True(torch.tensor(new[] { 0.55555556, 0.27777778, 0.16666667, }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.12995452, 0.10558804, 0.073099415 }).allclose(dist.variance));\n Assert.True(torch.tensor(-4.9130).allclose(dist.entropy()));\n Assert.True(torch.tensor(-3.621825).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestExponential()\n {\n var dist = Exponential(torch.tensor(new[] { 0.5, 0.25, 0.15 }));\n Assert.True(torch.tensor(new[] { 2, 4, 6.6666667, }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.0, 0.0, 0.0 }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { 0.25, 0.0625, 0.0225 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 1.6931472, 2.3862944, 2.89712 }).allclose(dist.entropy()));\n Assert.True(torch.tensor(new[] { -1.1931472, -1.6362944, -2.04712 }).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestExponentialGen()\n {\n var gen = new Generator(4711);\n var dist = Exponential(torch.tensor(new[] { 0.5, 0.25, 0.15 }), gen);\n Assert.True(torch.tensor(new[] { 2, 4, 6.6666667, }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 0.0, 0.0, 0.0 }).allclose(dist.mode));\n Assert.True(torch.tensor(new[] { 0.25, 0.0625, 0.0225 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { 1.6931472, 2.3862944, 2.89712 }).allclose(dist.entropy()));\n Assert.True(torch.tensor(new[] { -1.1931472, -1.6362944, -2.04712 }).allclose(dist.log_prob(torch.ones(3))));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestFisherSnedecor()\n {\n var dist = FisherSnedecor(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(2.0));\n Assert.True(torch.tensor(new[] { -2.0117974, -2.4718776, -2.8622819 }).allclose(dist.log_prob(torch.ones(3))));\n Assert.Throws<NotImplementedException>(() => dist.entropy());\n Assert.Throws<NotImplementedException>(() => dist.cdf(torch.ones(3)));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestFisherSnedecorGen()\n {\n var gen = new Generator(4711);\n var dist = FisherSnedecor(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(2.0), gen);\n Assert.True(torch.tensor(new[] { -2.0117974, -2.4718776, -2.8622819 }).allclose(dist.log_prob(torch.ones(3))));\n Assert.Throws<NotImplementedException>(() => dist.entropy());\n Assert.Throws<NotImplementedException>(() => dist.cdf(torch.ones(3)));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestGamma()\n {\n var dist = Gamma(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(0.5f));\n Assert.True(torch.tensor(new[] { 1, 0.5, 0.3 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 2, 1, 0.6 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { -1.4189385, -1.9613093, -2.4317859 }).allclose(dist.log_prob(torch.ones(3))));\n Assert.True(torch.tensor(new[] { 0.7837571, -0.9394204, -3.296883, }).allclose(dist.entropy()));\n {\n var sample = dist.sample();\n var entropy = dist.entropy();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestGammaGen()\n {\n var gen = new Generator(4711);\n var dist = Gamma(torch.tensor(new[] { 0.5, 0.25, 0.15 }), torch.tensor(0.5f), gen);\n Assert.True(torch.tensor(new[] { 1, 0.5, 0.3 }).allclose(dist.mean));\n Assert.True(torch.tensor(new[] { 2, 1, 0.6 }).allclose(dist.variance));\n Assert.True(torch.tensor(new[] { -1.4189385, -1.9613093, -2.4317859 }).allclose(dist.log_prob(torch.ones(3))));\n Assert.True(torch.tensor(new[] { 0.7837571, -0.9394204, -3.296883, }).allclose(dist.entropy()));\n {\n var sample = dist.sample();\n var entropy = dist.entropy();\n\n Assert.Equal(new long[] { 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestGeometric()\n {\n var dist = Geometric(torch.rand(3, 3));\n {\n var sample = dist.sample();\n var entropy = dist.entropy();\n\n Assert.Equal(new long[] { 3, 3 }, sample.shape);\n Assert.Equal(new long[] { 3, 3 }, entropy.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestGeometricGen()\n {\n var gen = new Generator(4711);\n var dist = Geometric(torch.rand(3, 3), generator: gen);\n {\n var sample = dist.sample();\n var entropy = dist.entropy();\n\n Assert.Equal(new long[] { 3, 3 }, sample.shape);\n Assert.Equal(new long[] { 3, 3 }, entropy.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestMultinomial()\n {\n var categories = 17;\n var dist = Multinomial(100, torch.rand(3, categories));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3, categories }, sample.shape);\n Assert.All<float>(sample.data<float>().ToArray(), d => Assert.True(d >= 0 && d <= 100));\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, categories }, sample.shape);\n Assert.All<float>(sample.data<float>().ToArray(), d => Assert.True(d >= 0 && d <= 100));\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, categories }, sample.shape);\n Assert.All<float>(sample.data<float>().ToArray(), d => Assert.True(d >= 0 && d <= 100));\n }\n }\n\n [Fact]\n public void TestMultinomialGen()\n {\n var gen = new Generator(4711);\n var categories = 17;\n var dist = Multinomial(100, torch.rand(3, categories), generator: gen);\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3, categories }, sample.shape);\n Assert.All<float>(sample.data<float>().ToArray(), d => Assert.True(d >= 0 && d <= 100));\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, categories }, sample.shape);\n Assert.All<float>(sample.data<float>().ToArray(), d => Assert.True(d >= 0 && d <= 100));\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, categories }, sample.shape);\n Assert.All<float>(sample.data<float>().ToArray(), d => Assert.True(d >= 0 && d <= 100));\n }\n }\n\n [Fact]\n public void TestMultivariateNormal()\n {\n var bs = 2;\n var dist = torch.distributions.MultivariateNormal(torch.zeros(bs), precision_matrix: torch.eye(bs));\n {\n var sample = dist.sample(2, 2);\n\n Assert.Equal(new long[] { bs, 2, 2 }, sample.shape);\n }\n {\n torch.manual_seed(0);\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { bs, 3, 2 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { bs, 3, 3, 3, 2 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestWeibull()\n {\n var dist = Weibull(torch.ones(3, 3), torch.ones(3, 3));\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3, 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3 }, sample.shape);\n }\n }\n\n [Fact]\n public void TestWeibullGen()\n {\n var gen = new Generator(4711);\n var dist = Weibull(torch.ones(3, 3), torch.ones(3, 3), generator: gen);\n {\n var sample = dist.sample();\n\n Assert.Equal(new long[] { 3, 3 }, sample.shape);\n }\n {\n var sample = dist.sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3 }, sample.shape);\n }\n {\n var sample = dist.expand(new long[] { 3, 3, 3 }).sample(2, 3);\n\n Assert.Equal(new long[] { 2, 3, 3, 3, 3 }, sample.shape);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.7812061905860901, "alphanum_fraction": 0.7812061905860901, "avg_line_length": 36.47368240356445, "blob_id": "1d5d928688d07546f66d56d8f0e15b2d14ab5320", "content_id": "e7dda7beb5c021da730a640bd8c3580a0c5074d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 713, "license_type": "permissive", "max_line_length": 116, "num_lines": 19, "path": "/docfx/index.md", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "\nTorchSharp are .NET bindings to the Torch library published here:\n\nhttps://pytorch.org/get-started/locally/\n\nThis surfaces the C++ library as a strongly-typed .NET API.\n\n## Getting Started\n\nCheck the [GitHub project page](https://github.com/dotnet/TorchSharp) for TorchSharp.\n\nThen, start by reading up on [creating your own modules](articles/modules.md).\n\n## Tips and Tricks\n\n[Some thoughts](articles/memory.md) on how to manage memory well in your TorchSharp training code.\n\nAn intruction on how to [share model](articles/saveload.md) weights between applications, whether in Python or .NET.\n\nLoading existing TorchScript files is now supported and described in [Loading TorchScript](articles/torchscript.md).\n" }, { "alpha_fraction": 0.74205482006073, "alphanum_fraction": 0.7609589099884033, "avg_line_length": 52.67647171020508, "blob_id": "bd6dd7245bf74e90d73aa89a9ae3d6cbf78d0e65", "content_id": "c3a836465d1ce860eff386f0e101e59bac8ae4dc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7300, "license_type": "permissive", "max_line_length": 391, "num_lines": 136, "path": "/README.md", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "[![Gitter](https://badges.gitter.im/dotnet/TorchSharp.svg)](https://gitter.im/dotnet/TorchSharp?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)\n<br/>\n[![Build Status](https://dotnet.visualstudio.com/TorchSharp/_apis/build/status/dotnet.TorchSharp?branchName=main)](https://dotnet.visualstudio.com/TorchSharp/_build/latest?definitionId=174&branchName=main)\n<br/>\n[![TorchSharp](https://img.shields.io/nuget/vpre/TorchSharp.svg?cacheSeconds=3600&label=TorchSharp%20nuget)](https://www.nuget.org/packages/TorchSharp)<br/>\n[![TorchAudio](https://img.shields.io/nuget/vpre/TorchAudio.svg?cacheSeconds=3600&label=TorchAudio%20nuget)](https://www.nuget.org/packages/TorchAudio)<br/>\n[![TorchVision](https://img.shields.io/nuget/vpre/TorchVision.svg?cacheSeconds=3600&label=TorchVision%20nuget)](https://www.nuget.org/packages/TorchVision)<br/>\n[![TorchSharp-cpu](https://img.shields.io/nuget/vpre/TorchSharp-cpu.svg?cacheSeconds=3600&label=TorchSharp-cpu%20nuget)](https://www.nuget.org/packages/TorchSharp-cpu)\n[![TorchSharp-cuda-windows](https://img.shields.io/nuget/vpre/TorchSharp-cuda-windows.svg?cacheSeconds=3600&label=TorchSharp-cuda-windows%20nuget)](https://www.nuget.org/packages/TorchSharp-cuda-windows)\n[![TorchSharp-cuda-linux](https://img.shields.io/nuget/vpre/TorchSharp-cuda-linux.svg?cacheSeconds=3600&label=TorchSharp-cuda-linux%20nuget)](https://www.nuget.org/packages/TorchSharp-cuda-linux)<br/>\n<br/>\nPlease check the [Release Notes](RELEASENOTES.md) file for news on what's been updated in each new release.\n\n__TorchSharp is now in the .NET Foundation!__\n\nIf you are using TorchSharp from NuGet, you should be using a version >= 0.98.3 of TorchSharp, and >= 1.12.0 of the libtorch-xxx redistributable packages. We recommend using one of the 'bundled' packages: TorchSharp-cpu, TorchSharp-cuda-windows, or TorchSharp-cuda-linux. They will pull in the right libtorch backends.\n\n__TorchSharp examples has their own home!__\n\nHead over to the [TorchSharp Examples Repo](https://github.com/dotnet/TorchSharpExamples) for convenient access to existing and upcoming examples.\n\n__IMPORTANT NOTES:__\n\nWhen targeting __.NET FX__ on Windows, the project configuration must be set to 'x64' rather than 'Any CPU' for anything that depends on TorchSharp.\n\nAs we build up to a v1.0 release, we will continue to make breaking changes, but only when we consider it necessary for usability. Similarity to the PyTorch experience is a primary design tenet, and we will continue on that path.\n\n# TorchSharp\n\nTorchSharp is a .NET library that provides access to the library that powers PyTorch. It is part of the .NET Foundation.\n\nThe focus is to bind the API surfaced by libtorch with a particular focus on tensors. The design intent is to stay as close as possible to the Pytorch experience, while still taking advantage of the benefits of the .NET static type system where it makes sense. For example: method overloading is relied on when Pytorch defines multiple valid types for a particular parameter.\n\nThe technology is a \"wrapper library\": no more, no less. [DiffSharp](https://github.com/DiffSharp/DiffSharp/) uses this\nrepository extensively and has been a major factor in iterating support.\n\nThings that you can try:\n\n```csharp\nusing TorchSharp;\nusing static TorchSharp.torch.nn;\n\nvar lin1 = Linear(1000, 100);\nvar lin2 = Linear(100, 10);\nvar seq = Sequential((\"lin1\", lin1), (\"relu1\", ReLU()), (\"drop1\", Dropout(0.1)), (\"lin2\", lin2));\n\nvar x = torch.randn(64, 1000);\nvar y = torch.randn(64, 10);\n\nvar optimizer = torch.optim.Adam(seq.parameters());\n\nfor (int i = 0; i < 10; i++) {\n var eval = seq.forward(x);\n var output = functional.mse_loss(eval, y, Reduction.Sum);\n\n optimizer.zero_grad();\n\n output.backward();\n\n optimizer.step();\n}\n```\n\n## A Few Things to Know\n\nWhile the intent has been to stay close to the Pytorch experience, there are some peculiarities to take note of:\n\n1. We have disregarded .NET naming conventions in favor of Python where it impacts the experience. We know this will feel wrong to some, but after a lot of deliberation, we decided to follow the lead of the SciSharp community and embrace naming similarity with Python over .NET tradition. We believe this will make it easier to take Python-based examples and snippets and apply them in .NET.\n\n2. In order to make a constructor call look more the Pytorch code, each class has a factory method with the same name. Because we cannot have a method and a class with the same name in a scope, we moved the class declarations to a nested scope 'Modules.'\n\n For example:\n\n ```csharp\n\n Module conv1 = Conv1d(...);\n\n ```\n creates an instance of `Modules.Conv1d`, which has 'torch.Module' as its base class.\n\n3. C# uses ':' when passing a named parameter, while F# and Python uses '=', and Pytorch functions have enough parameters to encourage passing them by name. This means that you cannot simply copy a lot of code into C#.\n\n4. There are a number of APIs where Pytorch encodes what are effectively enum types as strings. We have chosen to use proper .NET enumeration types in most cases.\n\n5. The type `torch.device` is `torch.Device` in TorchSharp. We felt that using all-lowercase for a class type was one step too far. The device object constructors, which is what you use most of the time, are still called `device()`\n\n\n# Memory management\n\nSee [docfx/articles/memory.md](docfx/articles/memory.md).\n\n# Download\n\nTorchSharp is distributed via the NuGet gallery: https://www.nuget.org/packages/TorchSharp/\n\nTo use TorchSharp, you also need one of the LibTorch backend packages: https://www.nuget.org/packages?q=libtorch, specifically one of\n\n* `libtorch-cpu-linux-x64` (CPU, Linux)\n\n* `libtorch-cpu-win-x64` (CPU, Windows)\n\n* `libtorch-cpu-osx-x64` (CPU, OSX)\n\n* `libtorch-cpu` (CPU, references all three, larger download but simpler)\n\n* `libtorch-cuda-11.7-linux-x64` (CPU/CUDA 11.3, Linux)\n\n > NOTE: Due to the presence of very large native binaries, using the `libtorch-cuda-11.7-linux-x64` package requires\n > .NET 6, e.g. .NET SDK version `6.0.100-preview.5.21302.13` or greater.\n\n* `libtorch-cuda-11.7-win-x64` (CPU/CUDA 11.3, Windows)\n\nAlternatively you can access the libtorch native binaries via direct reference to existing local native\nbinaries of LibTorch installed through other means (for example, by installing [PyTorch](https://pytorch.org/) using a Python package manager). You will have to add an explicit load of the relevant native library, for example:\n\n```csharp\n using System.Runtime.InteropServices;\n NativeLibrary.Load(\"/home/gunes/anaconda3/lib/python3.8/site-packages/torch/lib/libtorch.so\")\n```\n\n# Code of Conduct\nThis project has adopted the code of conduct defined by the Contributor Covenant to clarify expected behavior in our community.\nFor more information see the [.NET Foundation Code of Conduct](https://dotnetfoundation.org/code-of-conduct).\n\n# Developing and Contributing\n\nSee [DEVGUIDE.md](DEVGUIDE.md) and [CONTRIBUTING.md](CONTRIBUTING.md).\n\n<a href=\"https://github.com/dotnet/TorchSharp/graphs/contributors\">\n <img src=\"https://contrib.rocks/image?repo=dotnet/TorchSharp\" />\n</a>\n\n# Uses\n\n[DiffSharp](https://github.com/DiffSharp/DiffSharp/) also uses this\nrepository extensively and has been a major factor in iterating support.\n" }, { "alpha_fraction": 0.5457543134689331, "alphanum_fraction": 0.5507007241249084, "avg_line_length": 42.32143020629883, "blob_id": "df2dae985ee1ee03da16d487c4936028ebb33d70", "content_id": "27ec1bb44bf57748de582b67a49c3cdbaf34da34", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3639, "license_type": "permissive", "max_line_length": 182, "num_lines": 84, "path": "/src/TorchVision/Normalize.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class Normalize : ITransform, IDisposable\n {\n internal Normalize(double[] means, double[] stdevs, ScalarType dtype = ScalarType.Float32, torch.Device? device = null)\n {\n if (means is null) throw new ArgumentNullException(nameof(means));\n if (stdevs is null) throw new ArgumentNullException(nameof(stdevs));\n if (means.Length != stdevs.Length)\n throw new ArgumentException($\"{nameof(means)} and {nameof(stdevs)} must be the same length in call to Normalize\");\n if (means.Length != 1 && means.Length != 3)\n throw new ArgumentException($\"Since they correspond to the number of channels in an image, {nameof(means)} and {nameof(stdevs)} must both be either 1 or 3 long\");\n\n this.means = means.ToTensor(new long[] { 1, means.Length, 1, 1 }); // Assumes NxCxHxW\n this.stdevs = stdevs.ToTensor(new long[] { 1, stdevs.Length, 1, 1 }); // Assumes NxCxHxW\n\n if (dtype != ScalarType.Float64) {\n this.means = this.means.to_type(dtype);\n this.stdevs = this.stdevs.to_type(dtype);\n }\n\n if (device != null && device.type != DeviceType.CPU) {\n this.means = this.means.to(device);\n this.stdevs = this.stdevs.to(device);\n }\n }\n\n public Tensor call(Tensor input)\n {\n if (means.size(1) != input.size(1)) throw new ArgumentException(\"The number of channels is not equal to the number of means and standard deviations\");\n return (input - means) / stdevs;\n }\n\n private Tensor means;\n private Tensor stdevs;\n bool disposedValue;\n\n protected virtual void Dispose(bool disposing)\n {\n if (!disposedValue) {\n means?.Dispose();\n stdevs?.Dispose();\n disposedValue = true;\n }\n }\n\n ~Normalize()\n {\n // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method\n Dispose(disposing: false);\n }\n\n public void Dispose()\n {\n // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method\n Dispose(disposing: true);\n GC.SuppressFinalize(this);\n }\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Normalize a float tensor image with mean and standard deviation.\n /// </summary>\n /// <param name=\"means\">Sequence of means for each channel.</param>\n /// <param name=\"stdevs\">Sequence of standard deviations for each channel.</param>\n /// <param name=\"dtype\">Bool to make this operation inplace.</param>\n /// <param name=\"device\">The device to place the output tensor on.</param>\n /// <returns></returns>\n static public ITransform Normalize(double[] means, double[] stdevs, ScalarType dtype = ScalarType.Float32, torch.Device? device = null)\n {\n return new Normalize(means, stdevs, dtype, device);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5594344735145569, "alphanum_fraction": 0.5599448680877686, "avg_line_length": 59.84782791137695, "blob_id": "90ea4b1df94f430accb62facc997c1932b9d509e", "content_id": "691d24b7f5479080f88309fa748f78bde6080d3d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 19593, "license_type": "permissive", "max_line_length": 172, "num_lines": 322, "path": "/src/TorchVision/IO/Image.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System.IO;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class io\n {\n /// <summary>\n /// <cref>Imager</cref> to be used when a <cref>torchvision.io</cref> image method's <c>imager</c> is unspecified.\n /// </summary>\n public static Imager DefaultImager { get; set; } = new NotImplementedImager();\n\n /// <summary>\n /// Abstract class providing a generic way to decode and encode images as <cref>Tensor</cref>s.\n /// Used by <cref>torchvision.io</cref> image methods.\n /// </summary>\n public abstract class Imager\n {\n /// <summary>\n /// Decode the contents of an image file and returns the result as a <cref>Tensor</cref>.\n /// </summary>\n /// <param name=\"stream\">Stream to read from.</param>\n /// <param name=\"mode\">Image read mode.</param>\n /// <remarks>\n /// The image format is detected from image file contents.\n /// </remarks>\n /// <returns>\n /// <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.\n /// </returns>\n public abstract Tensor DecodeImage(Stream stream, ImageReadMode mode = ImageReadMode.UNCHANGED);\n\n /// <summary>\n /// Decode the contents of a byte array and returns the result as a <cref>Tensor</cref>.\n /// </summary>\n /// <param name=\"data\">byte array to decode from.</param>\n /// <param name=\"mode\">Image read mode.</param>\n /// <remarks>\n /// The image format is detected from image file contents.\n /// </remarks>\n /// <returns>\n /// <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.\n /// </returns>\n public abstract Tensor DecodeImage(byte[] data, ImageReadMode mode = ImageReadMode.UNCHANGED);\n\n /// <summary>\n /// Asynchronously decode the contents of an image file and returns the result as a <cref>Tensor</cref>.\n /// </summary>\n /// <param name=\"stream\">Stream to read from.</param>\n /// <param name=\"mode\">Image read mode.</param>\n /// <param name=\"cancellationToken\">Cancellation token.</param>\n /// <remarks>\n /// The image format is detected from image file contents.\n /// </remarks>\n /// <returns>\n /// <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.\n /// </returns>\n public virtual Task<Tensor> DecodeImageAsync(Stream stream, ImageReadMode mode = ImageReadMode.UNCHANGED, CancellationToken cancellationToken = default)\n {\n // Default implementation -- just do things synchronously.\n var t = DecodeImage(stream, mode);\n return Task<Tensor>.FromResult(t);\n }\n\n /// <summary>\n /// Encodes a <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c> into a stream.\n /// </summary>\n /// <param name=\"image\"><cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.</param>\n /// <param name=\"format\">Image format.</param>\n /// <param name=\"stream\">Stream to write to.</param>\n public abstract void EncodeImage(Tensor image, ImageFormat format, Stream stream);\n\n /// <summary>\n /// Encodes a <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c> into a stream.\n /// </summary>\n /// <param name=\"image\"><cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.</param>\n /// <param name=\"format\">Image format.</param>\n /// <returns>The encoded image as a byte array.</returns>\n public abstract byte[] EncodeImage(Tensor image, ImageFormat format);\n\n /// <summary>\n /// Asynchronously encodes a <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c> into a stream.\n /// </summary>\n /// <param name=\"image\"><cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.</param>\n /// <param name=\"format\">Image format.</param>\n /// <param name=\"stream\">Stream to write to.</param>\n /// <param name=\"cancellationToken\">Cancellation token.</param>\n public virtual Task EncodeImageAsync(Tensor image, ImageFormat format, Stream stream, CancellationToken cancellationToken = default)\n {\n // Default implementation -- just do things synchronously.\n EncodeImage(image, format, stream);\n return Task.CompletedTask;\n }\n }\n\n /// <summary>\n /// Support for various modes while reading images. Affects the returned <cref>Tensor</cref>'s <c>color_channels</c>.\n /// </summary>\n public enum ImageReadMode\n {\n /// <summary>\n /// Read as is. Returned <cref>Tensor</cref>'s color_channels depend on the <cref>ImageFormat</cref>.\n /// </summary>\n UNCHANGED,\n /// <summary>\n /// Read as grayscale. Return <cref>Tensor</cref> with <c>color_channels = 1 </c>.\n /// </summary>\n GRAY,\n /// <summary>\n /// Read as grayscale with transparency. Return <cref>Tensor</cref> with <c>color_channels = 2 </c>.\n /// </summary>\n GRAY_ALPHA,\n /// <summary>\n /// Read as RGB. Return <cref>Tensor</cref> with <c>color_channels = 3 </c>.\n /// </summary>\n RGB,\n /// <summary>\n /// Read as RGB with transparency. Return <cref>Tensor</cref> with <c>color_channels = 4 </c>.\n /// </summary>\n RGB_ALPHA\n }\n\n /// <summary>\n /// Reads an image file and returns the result as a <cref>Tensor</cref>.\n /// </summary>\n /// <param name=\"filename\">Path to the image.</param>\n /// <param name=\"mode\">Image read mode.</param>\n /// <param name=\"imager\"><cref>Imager</cref> to be use. Will use <cref>DefaultImager</cref> if null.</param>\n /// <returns>\n /// <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c> and <c>dtype = uint8</c>.\n /// </returns>\n public static Tensor read_image(string filename, ImageReadMode mode = ImageReadMode.UNCHANGED, Imager imager = null)\n {\n using (FileStream stream = File.Open(filename, FileMode.Open))\n return (imager ?? DefaultImager).DecodeImage(stream, mode);\n }\n\n /// <summary>\n /// Reads an image file and returns the result as a <cref>Tensor</cref>.\n /// </summary>\n /// <param name=\"stream\">Stream to read from.</param>\n /// <param name=\"mode\">Image read mode.</param>\n /// <param name=\"imager\"><cref>Imager</cref> to be use. Will use <cref>DefaultImager</cref> if null.</param>\n /// <returns>\n /// <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c> and <c>dtype = uint8</c>.\n /// </returns>\n public static Tensor read_image(Stream stream, ImageReadMode mode = ImageReadMode.UNCHANGED, Imager imager = null)\n {\n return (imager ?? DefaultImager).DecodeImage(stream, mode);\n }\n\n /// <summary>\n /// Asynchronously reads an image file and returns the result as a <cref>Tensor</cref>.\n /// </summary>\n /// <param name=\"filename\">Path to the image.</param>\n /// <param name=\"mode\">Read mode.</param>\n /// <param name=\"imager\"><cref>Imager</cref> to be use. Will use <cref>DefaultImager</cref> if null.</param>\n /// <returns>\n /// A task that represents the asynchronous read operation.\n /// The value of the TResult parameter is a <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c> and <c>dtype = uint8</c>.\n /// </returns>\n public static async Task<Tensor> read_image_async(string filename, ImageReadMode mode = ImageReadMode.UNCHANGED, Imager imager = null)\n {\n\n using (FileStream stream = File.Open(filename, FileMode.Open))\n return await (imager ?? DefaultImager).DecodeImageAsync(stream, mode);\n }\n\n /// <summary>\n /// Asynchronously reads an image file and returns the result as a <cref>Tensor</cref>.\n /// </summary>\n /// <param name=\"stream\">Stream to read from.</param>\n /// <param name=\"mode\">Read mode.</param>\n /// <param name=\"imager\"><cref>Imager</cref> to be use. Will use <cref>DefaultImager</cref> if null.</param>\n /// <returns>\n /// A task that represents the asynchronous read operation.\n /// The value of the TResult parameter is a <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c> and <c>dtype = uint8</c>.\n /// </returns>\n public static async Task<Tensor> read_image_async(Stream stream, ImageReadMode mode = ImageReadMode.UNCHANGED, Imager imager = null)\n {\n return await (imager ?? DefaultImager).DecodeImageAsync(stream, mode);\n }\n\n /// <summary>\n /// Write a image <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c> into a file.\n /// </summary>\n /// <param name=\"image\"><cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.</param>\n /// <param name=\"filename\">Path to the file.</param>\n /// <param name=\"format\">Image format.</param>\n /// <param name=\"imager\"><cref>Imager</cref> to be use. Will use <cref>DefaultImager</cref> if null.</param>\n public static void write_image(Tensor image, string filename, ImageFormat format, Imager imager = null)\n {\n if (image.dtype != ScalarType.Byte) throw new System.ArgumentException(\"Image tensors must be 'byte' tensors when passed to 'write_image()'.\");\n using (FileStream stream = File.Open(filename, FileMode.OpenOrCreate))\n (imager ?? DefaultImager).EncodeImage(image, format, stream);\n }\n\n /// <summary>\n /// Write a PNG image <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c> into a file.\n /// </summary>\n /// <param name=\"image\"><cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.</param>\n /// <param name=\"filename\">Path to the file.</param>\n /// <param name=\"imager\"><cref>Imager</cref> to be use. Will use <cref>DefaultImager</cref> if null.</param>\n public static void write_png(Tensor image, string filename, Imager imager = null)\n {\n write_image(image, filename, ImageFormat.Png, imager);\n }\n\n /// <summary>\n /// Write a JPEG image <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c> into a file.\n /// </summary>\n /// <param name=\"image\"><cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.</param>\n /// <param name=\"filename\">Path to the file.</param>\n /// <param name=\"imager\"><cref>Imager</cref> to be use. Will use <cref>DefaultImager</cref> if null.</param>\n public static void write_jpeg(Tensor image, string filename, Imager imager = null)\n {\n write_image(image, filename, ImageFormat.Jpeg, imager);\n }\n\n /// <summary>\n /// Write a image <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c> into a file.\n /// </summary>\n /// <param name=\"image\"><cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.</param>\n /// <param name=\"stream\">Stream to write to.</param>\n /// <param name=\"format\">Image format.</param>\n /// <param name=\"imager\"><cref>Imager</cref> to be use. Will use <cref>DefaultImager</cref> if null.</param>\n public static void write_image(Tensor image, Stream stream, ImageFormat format, Imager imager = null)\n {\n if (image.dtype != ScalarType.Byte) throw new System.ArgumentException(\"Image tensors must be 'byte' tensors when passed to 'write_image()'.\");\n (imager ?? DefaultImager).EncodeImage(image, format, stream);\n }\n\n /// <summary>\n /// Write a PNG image <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c> into a file.\n /// </summary>\n /// <param name=\"image\"><cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.</param>\n /// <param name=\"stream\">Stream to write to.</param>\n /// <param name=\"imager\"><cref>Imager</cref> to be use. Will use <cref>DefaultImager</cref> if null.</param>\n public static void write_png(Tensor image, Stream stream, Imager imager = null)\n {\n write_image(image, stream, ImageFormat.Png, imager);\n }\n\n /// <summary>\n /// Write a JPEG image <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c> into a file.\n /// </summary>\n /// <param name=\"image\"><cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.</param>\n /// <param name=\"stream\">Stream to write to.</param>\n /// <param name=\"imager\"><cref>Imager</cref> to be use. Will use <cref>DefaultImager</cref> if null.</param>\n public static void write_jpeg(Tensor image, Stream stream, Imager imager = null)\n {\n write_image(image, stream, ImageFormat.Jpeg, imager);\n }\n\n /// <summary>\n /// Asynchronously write a image <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c> into a file.\n /// </summary>\n /// <param name=\"image\"><cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.</param>\n /// <param name=\"filename\">Path to the file.</param>\n /// <param name=\"format\">Image format.</param>\n /// <param name=\"imager\"><cref>Imager</cref> to be use. Will use <cref>DefaultImager</cref> if null.</param>\n public static async Task write_image_async(Tensor image, string filename, ImageFormat format, Imager imager = null)\n {\n if (image.dtype != ScalarType.Byte) throw new System.ArgumentException(\"Image tensors must be 'byte' tensors when passed to 'write_image()'.\");\n using (FileStream stream = File.Open(filename, FileMode.OpenOrCreate))\n await (imager ?? DefaultImager).EncodeImageAsync(image, format, stream);\n }\n\n /// <summary>\n /// Asynchronously write a image <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c> into a file.\n /// </summary>\n /// <param name=\"image\"><cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.</param>\n /// <param name=\"stream\">Stream to write to.</param>\n /// <param name=\"format\">Image format.</param>\n /// <param name=\"cancellationToken\">Cancellation token</param>\n /// <param name=\"imager\"><cref>Imager</cref> to be use. Will use <cref>DefaultImager</cref> if null.</param>\n public static async Task write_image_async(Tensor image, Stream stream, ImageFormat format, CancellationToken cancellationToken = default, Imager imager = null)\n {\n if (image.dtype != ScalarType.Byte) throw new System.ArgumentException(\"Image tensors must be 'byte' tensors when passed to 'write_image()'.\");\n await (imager ?? DefaultImager).EncodeImageAsync(image, format, stream);\n }\n\n /// <summary>\n /// Encodes a <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>\n /// into a image <cref>Tensor</cref> buffer.\n /// </summary>\n /// <param name=\"image\"><cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.</param>\n /// <param name=\"format\">Image format.</param>\n /// <param name=\"imager\"><cref>Imager</cref> to be use. Will use <cref>DefaultImager</cref> if null.</param>\n /// <returns>A one dimensional <c>uint8</c> <cref>Tensor</cref> that contains the raw bytes of <c>image</c> encoded in the provided format.</returns>\n public static Tensor encode_image(Tensor image, ImageFormat format, Imager imager = null)\n {\n if (image.dtype != ScalarType.Byte) throw new System.ArgumentException(\"Image tensors must be 'byte' tensors when passed to 'encode_image()'.\");\n using (var stream = new MemoryStream()) {\n (imager ?? DefaultImager).EncodeImage(image, format, stream);\n return stream.ToArray();\n }\n }\n\n /// <summary>\n /// Decodes an image <cref>Tensor</cref> buffer into a <cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.\n /// </summary>\n /// <param name=\"image\">A one dimensional <c>uint8</c> <cref>Tensor</cref> that contains the raw bytes of an image.</param>\n /// <param name=\"mode\">Decode mode.</param>\n /// <param name=\"imager\"><cref>Imager</cref> to be use. Will use <cref>DefaultImager</cref> if null.</param>\n /// <returns><cref>Tensor</cref> with <c>shape = [color_channels, image_height, image_width]</c>.</returns>\n public static Tensor decode_image(Tensor image, ImageReadMode mode = ImageReadMode.UNCHANGED, Imager imager = null)\n {\n if (image.dtype != ScalarType.Byte) throw new System.ArgumentException(\"Image tensors must be 'byte' tensors when passed to 'decode_image()'.\");\n using (var stream = new MemoryStream()) {\n (imager ?? DefaultImager).DecodeImage(stream, mode);\n return stream.ToArray();\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.4548049867153168, "alphanum_fraction": 0.48809829354286194, "avg_line_length": 49.892784118652344, "blob_id": "b25763e3c30de41cce907d6b5fd4985aaec5b796", "content_id": "ae9099ad8c9b1c4f8bacbc0f8a73022c5833ed48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 50791, "license_type": "permissive", "max_line_length": 160, "num_lines": 998, "path": "/test/TorchSharpTest/PointwiseTensorMath.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Linq;\nusing Xunit;\nusing static TorchSharp.torch;\n\n#nullable enable\n\nnamespace TorchSharp\n{\n [Collection(\"Sequential\")]\n public class PointwiseTensorMath\n {\n [Fact]\n [TestOf(nameof(Tensor))]\n public void TestArithmeticOperatorsFloat16()\n {\n // Float16 arange_cuda not available on cuda in LibTorch 1.8.0\n // Float16 arange_cpu not available on cuda in LibTorch 1.8.0\n foreach (var device in new Device[] { torch.CPU, torch.CUDA }) {\n if (device.type != DeviceType.CUDA || torch.cuda.is_available()) {\n var c1 = torch.ones(new long[] { 10, 10 }, float16, device: device);\n var c2 = torch.ones(new long[] { 10, 10 }, float16, device: device);\n var c3 = torch.ones(new long[] { 10, 10 }, float16, device: device);\n#if NET6_0_OR_GREATER\n Func<Tensor, long, long, Half> getFunc = (tt, i, j) => tt[i, j].ToHalf();\n\n // scalar-tensor operators\n TestOneTensor(c1, c2, getFunc, getFunc, a => a + (Half)0.5, a => (Half)((double)a + 0.5f));\n TestOneTensor(c1, c2, getFunc, getFunc, a => (Half)0.5 + a, a => (Half)(0.5 + (double)a));\n TestOneTensor(c1, c2, getFunc, getFunc, a => a - (Half)0.5, a => (Half)((double)a - 0.5));\n TestOneTensor(c1, c2, getFunc, getFunc, a => a * (Half)0.5, a => (Half)((double)a * 0.5f));\n TestOneTensor(c1, c2, getFunc, getFunc, a => (Half)0.5 * a, a => (Half)(0.5f * (double)a));\n TestOneTensor(c1, c2, getFunc, getFunc, a => a / (Half)0.5, a => (Half)((double)a / 0.5f));\n\n TestOneTensor(c1, c2, getFunc, getFunc, a => a.add((Half)0.5), a => (Half)((double)a + 0.5f));\n TestOneTensor(c1, c2, getFunc, getFunc, a => a.sub((Half)0.5), a => (Half)((double)a - 0.5f));\n TestOneTensor(c1, c2, getFunc, getFunc, a => a.mul((Half)0.5), a => (Half)((double)a * 0.5f));\n TestOneTensor(c1, c2, getFunc, getFunc, a => a.div((Half)0.5), a => (Half)((double)a / 0.5f));\n\n TestOneTensorInPlace(c1, c2, getFunc, a => a.add_((Half)0.5), a => (Half)((double)a + 0.5f));\n TestOneTensorInPlace(c1, c2, getFunc, a => a.sub_((Half)0.5), a => (Half)((double)a - 0.5f));\n TestOneTensorInPlace(c1, c2, getFunc, a => a.mul_((Half)0.5), a => (Half)((double)a * 0.5f));\n TestOneTensorInPlace(c1, c2, getFunc, a => a.div_((Half)0.5), a => (Half)((double)a / 0.5f));\n\n // tensor-tensor operators\n TestTwoTensor(c1, c2, c3, getFunc, getFunc, (a, b) => a + b, (a, b) => (Half)((double)a + (double)b));\n TestTwoTensor(c1, c2, c3, getFunc, getFunc, (a, b) => a - b, (a, b) => (Half)((double)a - (double)b));\n TestTwoTensor(c1, c2, c3, getFunc, getFunc, (a, b) => a * b, (a, b) => (Half)((double)a * (double)b));\n TestTwoTensor(c1, c2, c3, getFunc, getFunc, (a, b) => a / b, (a, b) => (Half)((double)a / (double)b));\n\n TestTwoTensor(c1, c2, c3, getFunc, getFunc, (a, b) => a.add(b), (a, b) => (Half)((double)a + (double)b));\n TestTwoTensor(c1, c2, c3, getFunc, getFunc, (a, b) => a.sub(b), (a, b) => (Half)((double)a - (double)b));\n TestTwoTensor(c1, c2, c3, getFunc, getFunc, (a, b) => a.mul(b), (a, b) => (Half)((double)a * (double)b));\n TestTwoTensor(c1, c2, c3, getFunc, getFunc, (a, b) => a.div(b), (a, b) => (Half)((double)a / (double)b));\n\n TestTwoTensorInPlace(c1, c2, c3, getFunc, (a, b) => a.add_(b), (a, b) => (Half)((double)a + (double)b));\n TestTwoTensorInPlace(c1, c2, c3, getFunc, (a, b) => a.sub_(b), (a, b) => (Half)((double)a - (double)b));\n TestTwoTensorInPlace(c1, c2, c3, getFunc, (a, b) => a.mul_(b), (a, b) => (Half)((double)a * (double)b));\n TestTwoTensorInPlace(c1, c2, c3, getFunc, (a, b) => a.div_(b), (a, b) => (Half)((double)a / (double)b));\n#else\n Func<Tensor, long, long, float> getFunc = (tt, i, j) => tt[i, j].ToSingle();\n\n // scalar-tensor operators\n TestOneTensor(c1, c2, getFunc, getFunc, a => a + 0.5f, a => a + 0.5f);\n TestOneTensor(c1, c2, getFunc, getFunc, a => 0.5f + a, a => 0.5f + a);\n TestOneTensor(c1, c2, getFunc, getFunc, a => a - 0.5f, a => a - 0.5f);\n TestOneTensor(c1, c2, getFunc, getFunc, a => a * 0.5f, a => a * 0.5f);\n TestOneTensor(c1, c2, getFunc, getFunc, a => 0.5f * a, a => 0.5f * a);\n TestOneTensor(c1, c2, getFunc, getFunc, a => a / 0.5f, a => a / 0.5f);\n\n TestOneTensor(c1, c2, getFunc, getFunc, a => a.add(0.5f), a => a + 0.5f);\n TestOneTensor(c1, c2, getFunc, getFunc, a => a.sub(0.5f), a => a - 0.5f);\n TestOneTensor(c1, c2, getFunc, getFunc, a => a.mul(0.5f), a => a * 0.5f);\n TestOneTensor(c1, c2, getFunc, getFunc, a => a.div(0.5f), a => a / 0.5f);\n\n TestOneTensorInPlace(c1, c2, getFunc, a => a.add_(0.5f), a => a + 0.5f);\n TestOneTensorInPlace(c1, c2, getFunc, a => a.sub_(0.5f), a => a - 0.5f);\n TestOneTensorInPlace(c1, c2, getFunc, a => a.mul_(0.5f), a => a * 0.5f);\n TestOneTensorInPlace(c1, c2, getFunc, a => a.div_(0.5f), a => a / 0.5f);\n\n // tensor-tensor operators\n TestTwoTensor(c1, c2, c3, getFunc, getFunc, (a, b) => a + b, (a, b) => a + b);\n TestTwoTensor(c1, c2, c3, getFunc, getFunc, (a, b) => a - b, (a, b) => a - b);\n TestTwoTensor(c1, c2, c3, getFunc, getFunc, (a, b) => a * b, (a, b) => a * b);\n TestTwoTensor(c1, c2, c3, getFunc, getFunc, (a, b) => a / b, (a, b) => a / b);\n\n TestTwoTensor(c1, c2, c3, getFunc, getFunc, (a, b) => a.add(b), (a, b) => a + b);\n TestTwoTensor(c1, c2, c3, getFunc, getFunc, (a, b) => a.sub(b), (a, b) => a - b);\n TestTwoTensor(c1, c2, c3, getFunc, getFunc, (a, b) => a.mul(b), (a, b) => a * b);\n TestTwoTensor(c1, c2, c3, getFunc, getFunc, (a, b) => a.div(b), (a, b) => a / b);\n\n TestTwoTensorInPlace(c1, c2, c3, getFunc, (a, b) => a.add_(b), (a, b) => a + b);\n TestTwoTensorInPlace(c1, c2, c3, getFunc, (a, b) => a.sub_(b), (a, b) => a - b);\n TestTwoTensorInPlace(c1, c2, c3, getFunc, (a, b) => a.mul_(b), (a, b) => a * b);\n TestTwoTensorInPlace(c1, c2, c3, getFunc, (a, b) => a.div_(b), (a, b) => a / b);\n#endif\n }\n }\n }\n\n#if false\n [Fact]\n [TestOf(nameof(Tensor))]\n public void TestArithmeticOperatorsBFloat16()\n {\n // BFloat16 arange_cuda not available on cuda in LibTorch 1.8.0\n // BFloat16 arange_cpu not available on cuda in LibTorch 1.8.0\n foreach (var device in new Device[] { torch.CPU, torch.CUDA }) {\n if (device.type != DeviceType.CUDA || torch.cuda.is_available()) {\n var c1 = torch.ones(new long[] { 10, 10 }, bfloat16, device: device);\n var c2 = torch.ones(new long[] { 10, 10 }, bfloat16, device: device);\n var c3 = torch.ones(new long[] { 10, 10 }, bfloat16, device: device);\n Func<Tensor, long, long, float> getFunc = (tt, i, j) => tt[i, j].ToSingle();\n // scalar-tensor operators\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a + 0.5f, a => a + 0.5f);\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => 0.5f + a, a => 0.5f + a);\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a - 0.5f, a => a - 0.5f);\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a * 0.5f, a => a * 0.5f);\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => 0.5f * a, a => 0.5f * a);\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a / 0.5f, a => a / 0.5f);\n\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.add(0.5f), a => a + 0.5f);\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.sub(0.5f), a => a - 0.5f);\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.mul(0.5f), a => a * 0.5f);\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.div(0.5f), a => a / 0.5f);\n\n TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.add_(0.5f), a => a + 0.5f);\n TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.sub_(0.5f), a => a - 0.5f);\n TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.mul_(0.5f), a => a * 0.5f);\n TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.div_(0.5f), a => a / 0.5f);\n\n // tensor-tensor operators\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a + b, (a, b) => a + b);\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a - b, (a, b) => a - b);\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a * b, (a, b) => a * b);\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a / b, (a, b) => a / b);\n\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.add(b), (a, b) => a + b);\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.sub(b), (a, b) => a - b);\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.mul(b), (a, b) => a * b);\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.div(b), (a, b) => a / b);\n\n TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.add_(b), (a, b) => a + b);\n TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.sub_(b), (a, b) => a - b);\n TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.mul_(b), (a, b) => a * b);\n TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.div_(b), (a, b) => a / b);\n }\n }\n }\n#endif\n\n [Fact]\n [TestOf(nameof(Tensor))]\n public void TestArithmeticOperatorsFloat32()\n {\n foreach (var device in new Device[] { torch.CPU, torch.CUDA }) {\n if (device.type != DeviceType.CUDA || torch.cuda.is_available()) {\n var c1 = torch.arange(0, 10, float32, device: device).expand(new long[] { 10, 10 });\n var c2 = torch.arange(10, 0, -1, float32, device: device).expand(new long[] { 10, 10 });\n var c3 = torch.ones(new long[] { 10, 10 }, float32, device: device);\n Func<Tensor, long, long, float> getFunc = (tt, i, j) => tt[i, j].ToSingle();\n // scalar-tensor operators\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a + 0.5f, a => a + 0.5f);\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => 0.5f + a, a => 0.5f + a);\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a - 0.5f, a => a - 0.5f);\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a * 0.5f, a => a * 0.5f);\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => 0.5f * a, a => 0.5f * a);\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a / 0.5f, a => a / 0.5f);\n\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.add(0.5f), a => a + 0.5f);\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.sub(0.5f), a => a - 0.5f);\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.mul(0.5f), a => a * 0.5f);\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.div(0.5f), a => a / 0.5f);\n\n TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.add_(0.5f), a => a + 0.5f);\n TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.sub_(0.5f), a => a - 0.5f);\n TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.mul_(0.5f), a => a * 0.5f);\n TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.div_(0.5f), a => a / 0.5f);\n\n // tensor-tensor operators\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a + b, (a, b) => a + b);\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a - b, (a, b) => a - b);\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a * b, (a, b) => a * b);\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a / b, (a, b) => a / b);\n\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.add(b), (a, b) => a + b);\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.sub(b), (a, b) => a - b);\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.mul(b), (a, b) => a * b);\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.div(b), (a, b) => a / b);\n\n TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.add_(b), (a, b) => a + b);\n TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.sub_(b), (a, b) => a - b);\n TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.mul_(b), (a, b) => a * b);\n TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.div_(b), (a, b) => a / b);\n }\n }\n }\n\n [Fact]\n [TestOf(nameof(Tensor))]\n public void TestArithmeticOperatorsFloat64()\n {\n foreach (var device in new Device[] { torch.CPU, torch.CUDA }) {\n if (device.type != DeviceType.CUDA || torch.cuda.is_available()) {\n var c1 = torch.arange(0, 10, float64, device: device).expand(new long[] { 10, 10 });\n var c2 = torch.arange(10, 0, -1, float64, device: device).expand(new long[] { 10, 10 });\n var c3 = torch.ones(new long[] { 10, 10 }, float64, device: device);\n Func<Tensor, long, long, double> getFunc = (tt, i, j) => tt[i, j].ToDouble();\n // scalar-tensor operators\n TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => a + 0.5, a => a + 0.5);\n TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => 0.5 + a, a => 0.5 + a);\n TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => a - 0.5, a => a - 0.5);\n TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => a * 0.5, a => a * 0.5);\n TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => 0.5 * a, a => 0.5 * a);\n TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => a / 0.5, a => a / 0.5);\n\n TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => a.add(0.5), a => a + 0.5);\n TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => a.sub(0.5), a => a - 0.5);\n TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => a.mul(0.5), a => a * 0.5);\n TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => a.div(0.5), a => a / 0.5);\n\n TestOneTensorInPlace<double>(c1, c2, getFunc, a => a.add_(0.5), a => a + 0.5);\n TestOneTensorInPlace<double>(c1, c2, getFunc, a => a.sub_(0.5), a => a - 0.5);\n TestOneTensorInPlace<double>(c1, c2, getFunc, a => a.mul_(0.5), a => a * 0.5);\n TestOneTensorInPlace<double>(c1, c2, getFunc, a => a.div_(0.5), a => a / 0.5);\n\n // tensor-tensor operators\n TestTwoTensor<double, double>(c1, c2, c3, getFunc, getFunc, (a, b) => a + b, (a, b) => a + b);\n TestTwoTensor<double, double>(c1, c2, c3, getFunc, getFunc, (a, b) => a - b, (a, b) => a - b);\n TestTwoTensor<double, double>(c1, c2, c3, getFunc, getFunc, (a, b) => a * b, (a, b) => a * b);\n TestTwoTensor<double, double>(c1, c2, c3, getFunc, getFunc, (a, b) => a / b, (a, b) => a / b);\n\n TestTwoTensor<double, double>(c1, c2, c3, getFunc, getFunc, (a, b) => a.add(b), (a, b) => a + b);\n TestTwoTensor<double, double>(c1, c2, c3, getFunc, getFunc, (a, b) => a.sub(b), (a, b) => a - b);\n TestTwoTensor<double, double>(c1, c2, c3, getFunc, getFunc, (a, b) => a.mul(b), (a, b) => a * b);\n TestTwoTensor<double, double>(c1, c2, c3, getFunc, getFunc, (a, b) => a.div(b), (a, b) => a / b);\n\n TestTwoTensorInPlace<double>(c1, c2, c3, getFunc, (a, b) => a.add_(b), (a, b) => a + b);\n TestTwoTensorInPlace<double>(c1, c2, c3, getFunc, (a, b) => a.sub_(b), (a, b) => a - b);\n TestTwoTensorInPlace<double>(c1, c2, c3, getFunc, (a, b) => a.mul_(b), (a, b) => a * b);\n TestTwoTensorInPlace<double>(c1, c2, c3, getFunc, (a, b) => a.div_(b), (a, b) => a / b);\n }\n }\n }\n\n [Fact]\n [TestOf(nameof(Tensor))]\n public void TestArithmeticOperatorsComplexFloat64()\n {\n foreach (var device in new Device[] { torch.CPU, torch.CUDA }) {\n if (device.type != DeviceType.CUDA || torch.cuda.is_available()) {\n var c1 = torch.arange(0, 10, complex128, device: device).expand(new long[] { 10, 10 });\n var c2 = torch.arange(10, 0, -1, complex128, device: device).expand(new long[] { 10, 10 });\n var c3 = torch.ones(new long[] { 10, 10 }, complex128, device: device);\n Func<Tensor, long, long, System.Numerics.Complex> getFunc = (tt, i, j) => tt[i, j].ToComplexFloat64();\n // scalar-tensor operators\n TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => a + 0.5, a => a + 0.5);\n TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => 0.5 + a, a => 0.5 + a);\n TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => a - 0.5, a => a - 0.5);\n TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => a * 0.5, a => a * 0.5);\n TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => 0.5 * a, a => 0.5 * a);\n TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => a / 0.5, a => a / 0.5);\n\n TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => a.add(0.5), a => a + 0.5);\n TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => a.sub(0.5), a => a - 0.5);\n TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => a.mul(0.5), a => a * 0.5);\n TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => a.div(0.5), a => a / 0.5);\n\n TestOneTensorInPlace<System.Numerics.Complex>(c1, c2, getFunc, a => a.add_(0.5), a => a + 0.5);\n TestOneTensorInPlace<System.Numerics.Complex>(c1, c2, getFunc, a => a.sub_(0.5), a => a - 0.5);\n TestOneTensorInPlace<System.Numerics.Complex>(c1, c2, getFunc, a => a.mul_(0.5), a => a * 0.5);\n TestOneTensorInPlace<System.Numerics.Complex>(c1, c2, getFunc, a => a.div_(0.5), a => a / 0.5);\n\n // tensor-tensor operators\n TestTwoTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, c3, getFunc, getFunc, (a, b) => a + b, (a, b) => a + b);\n TestTwoTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, c3, getFunc, getFunc, (a, b) => a - b, (a, b) => a - b);\n TestTwoTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, c3, getFunc, getFunc, (a, b) => a * b, (a, b) => a * b);\n // Rounding errors make this test volatile\n //TestTwoTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, c3, getFunc, getFunc, (a, b) => a / b, (a, b) => a / b);\n\n TestTwoTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, c3, getFunc, getFunc, (a, b) => a.add(b), (a, b) => a + b);\n TestTwoTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, c3, getFunc, getFunc, (a, b) => a.sub(b), (a, b) => a - b);\n TestTwoTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, c3, getFunc, getFunc, (a, b) => a.mul(b), (a, b) => a * b);\n // Rounding errors make this test volatile\n //TestTwoTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, c3, getFunc, getFunc, (a, b) => a.div(b), (a, b) => a / b);\n\n TestTwoTensorInPlace<System.Numerics.Complex>(c1, c2, c3, getFunc, (a, b) => a.add_(b), (a, b) => a + b);\n TestTwoTensorInPlace<System.Numerics.Complex>(c1, c2, c3, getFunc, (a, b) => a.sub_(b), (a, b) => a - b);\n TestTwoTensorInPlace<System.Numerics.Complex>(c1, c2, c3, getFunc, (a, b) => a.mul_(b), (a, b) => a * b);\n // Rounding errors make this test volatile\n //TestTwoTensorInPlace<System.Numerics.Complex>(c1, c2, c3, getFunc, (a, b) => a.div_(b), (a, b) => a / b);\n }\n }\n }\n\n [Fact]\n [TestOf(nameof(Tensor))]\n public void TestComparisonOperatorsFloat32()\n {\n foreach (var device in new Device[] { torch.CPU, torch.CUDA }) {\n if (device.type != DeviceType.CUDA || torch.cuda.is_available()) {\n var c1 = torch.arange(0, 10, float32, device: device).expand(new long[] { 10, 10 });\n var c2 = torch.arange(10, 0, -1, float32, device: device).expand(new long[] { 10, 10 });\n var c3 = torch.ones(new long[] { 10, 10 }, float32, device: device);\n Func<Tensor, long, long, float> getFunc = (tt, i, j) => tt[i, j].ToSingle();\n Func<Tensor, long, long, bool> getFuncBool = (tt, i, j) => tt[i, j].ToBoolean();\n // scalar-tensor operators\n TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => a == 5.0f, a => a == 5.0f);\n TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => a != 5.0f, a => a != 5.0f);\n TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.eq_(5.0f), a => a == 5.0f ? 1.0f : 0.0f);\n TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.ne_(5.0f), a => a != 5.0f ? 1.0f : 0.0f);\n\n TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => a < 5.0f, a => a < 5.0f);\n TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => 5.0f < a, a => 5.0f < a);\n TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => a <= 5.0f, a => a <= 5.0f);\n TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => 5.0f <= a, a => 5.0f <= a);\n TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => a > 5.0f, a => a > 5.0f);\n TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => 5.0f > a, a => 5.0f > a);\n TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => a >= 5.0f, a => a >= 5.0f);\n TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => 5.0f >= a, a => 5.0f >= a);\n\n TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.lt_(5.0f), a => a < 5.0f ? 1.0f : 0.0f);\n TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.le_(5.0f), a => a <= 5.0f ? 1.0f : 0.0f);\n TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.gt_(5.0f), a => a > 5.0f ? 1.0f : 0.0f);\n TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.ge_(5.0f), a => a >= 5.0f ? 1.0f : 0.0f);\n\n TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a % 5.0f, a => a % 5.0f);\n TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.remainder_(5.0f), a => a % 5.0f);\n\n // tensor-tensor operators\n TestTwoTensor<float, bool>(c1, c2, c3, getFunc, getFuncBool, (a, b) => a == b, (a, b) => a == b);\n TestTwoTensor<float, bool>(c1, c2, c3, getFunc, getFuncBool, (a, b) => a != b, (a, b) => a != b);\n TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.eq_(b), (a, b) => a == b ? 1.0f : 0.0f);\n TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.ne_(b), (a, b) => a != b ? 1.0f : 0.0f);\n\n TestTwoTensor<float, bool>(c1, c2, c3, getFunc, getFuncBool, (a, b) => a < b, (a, b) => a < b);\n TestTwoTensor<float, bool>(c1, c2, c3, getFunc, getFuncBool, (a, b) => a <= b, (a, b) => a <= b);\n TestTwoTensor<float, bool>(c1, c2, c3, getFunc, getFuncBool, (a, b) => a > b, (a, b) => a > b);\n TestTwoTensor<float, bool>(c1, c2, c3, getFunc, getFuncBool, (a, b) => a >= b, (a, b) => a >= b);\n\n TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.lt_(b), (a, b) => a < b ? 1.0f : 0.0f);\n TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.le_(b), (a, b) => a <= b ? 1.0f : 0.0f);\n TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.gt_(b), (a, b) => a > b ? 1.0f : 0.0f);\n TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.ge_(b), (a, b) => a >= b ? 1.0f : 0.0f);\n\n TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a % b, (a, b) => a % b);\n TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.remainder_(b), (a, b) => a % b);\n }\n }\n }\n\n private void TestOneTensor<Tin, Tout>(\n Tensor c1,\n Tensor c2,\n Func<Tensor, long, long, Tin> getFuncIn,\n Func<Tensor, long, long, Tout> getFuncOut,\n Func<Tensor, Tensor> tensorFunc,\n Func<Tin, Tout> scalarFunc)\n {\n var x = c1 * c2;\n var y = tensorFunc(x);\n\n for (int i = 0; i < 10; i++) {\n for (int j = 0; j < 10; j++) {\n var xv = getFuncIn(x, i, j);\n var yv = getFuncOut(y, i, j);\n Assert.Equal<Tout>(yv, scalarFunc(xv));\n }\n }\n }\n\n private void TestOneTensorInPlace<Tin>(\n Tensor c1,\n Tensor c2,\n Func<Tensor, long, long, Tin> getFuncIn,\n Func<Tensor, Tensor> tensorFunc,\n Func<Tin, Tin> scalarFunc)\n {\n\n var x = c1 * c2;\n var xClone = x.clone();\n var y = tensorFunc(x);\n\n for (int i = 0; i < 10; i++) {\n for (int j = 0; j < 10; j++) {\n var xClonev = getFuncIn(xClone, i, j);\n var xv = getFuncIn(x, i, j);\n var yv = getFuncIn(y, i, j);\n Assert.Equal(yv, scalarFunc(xClonev));\n Assert.Equal(yv, xv);\n }\n }\n }\n\n private void TestTwoTensor<Tin, Tout>(\n Tensor c1,\n Tensor c2,\n Tensor c3,\n Func<Tensor, long, long, Tin> getFuncIn,\n Func<Tensor, long, long, Tout> getFuncOut,\n Func<Tensor, Tensor, Tensor> tensorFunc,\n Func<Tin, Tin, Tout> scalarFunc)\n {\n\n var x = c1 * c3;\n var y = c2 * c3;\n\n var z = tensorFunc(x, y);\n\n for (int i = 0; i < 10; i++) {\n for (int j = 0; j < 10; j++) {\n var xv = getFuncIn(x, i, j);\n var yv = getFuncIn(y, i, j);\n var zv = getFuncOut(z, i, j);\n Assert.Equal(zv, scalarFunc(xv, yv));\n }\n }\n }\n\n private void TestTwoTensorInPlace<Tin>(\n Tensor c1,\n Tensor c2,\n Tensor c3,\n Func<Tensor, long, long, Tin> getFuncIn,\n Func<Tensor, Tensor, Tensor> tensorFunc,\n Func<Tin, Tin, Tin> scalarFunc) where Tin : unmanaged\n {\n\n var x = c1 * c3;\n var xClone = x.clone();\n var y = c2 * c3;\n\n var z = tensorFunc(x, y);\n\n if (x.device_type == DeviceType.CPU) {\n var xData = x.data<Tin>();\n var yData = y.data<Tin>();\n var zData = z.data<Tin>();\n\n Assert.True(xData == zData);\n }\n\n for (int i = 0; i < 10; i++) {\n for (int j = 0; j < 10; j++) {\n var xClonev = getFuncIn(xClone, i, j);\n var xv = getFuncIn(x, i, j);\n var yv = getFuncIn(y, i, j);\n var zv = getFuncIn(z, i, j);\n Assert.Equal(zv, scalarFunc(xClonev, yv));\n Assert.Equal(zv, xv);\n }\n }\n }\n\n [Fact]\n [TestOf(nameof(Tensor.eq))]\n [TestOf(nameof(Tensor.ne))]\n [TestOf(nameof(Tensor.lt))]\n [TestOf(nameof(Tensor.gt))]\n [TestOf(nameof(Tensor.le))]\n public void TestComparison()\n {\n var A = torch.tensor(new float[] { 1.2f, 3.4f, 1.4f, 3.3f }).reshape(2, 2);\n var B = torch.tensor(new float[] { 1.3f, 3.3f });\n Assert.Equal(new bool[] { false, false, false, true }, A.eq(B).data<bool>().ToArray());\n Assert.Equal(new bool[] { false, false, false, true }, torch.eq(A, B).data<bool>().ToArray());\n Assert.Equal(new bool[] { true, true, true, false }, A.ne(B).data<bool>().ToArray());\n Assert.Equal(new bool[] { true, true, true, false }, torch.ne(A, B).data<bool>().ToArray());\n Assert.Equal(new bool[] { true, false, false, false }, A.lt(B).data<bool>().ToArray());\n Assert.Equal(new bool[] { true, false, false, false }, torch.lt(A, B).data<bool>().ToArray());\n Assert.Equal(new bool[] { true, false, false, true }, A.le(B).data<bool>().ToArray());\n Assert.Equal(new bool[] { true, false, false, true }, torch.le(A, B).data<bool>().ToArray());\n Assert.Equal(new bool[] { false, true, true, false }, A.gt(B).data<bool>().ToArray());\n Assert.Equal(new bool[] { false, true, true, false }, torch.gt(A, B).data<bool>().ToArray());\n Assert.Equal(new bool[] { false, true, true, true }, A.ge(B).data<bool>().ToArray());\n Assert.Equal(new bool[] { false, true, true, true }, torch.ge(A, B).data<bool>().ToArray());\n }\n\n [Fact]\n [TestOf(nameof(Tensor.frexp))]\n public void TestFrexp()\n {\n var x = torch.arange(9, float32);\n var r = x.frexp();\n\n Assert.Equal(new float[] { 0.0000f, 0.5000f, 0.5000f, 0.7500f, 0.5000f, 0.6250f, 0.7500f, 0.8750f, 0.5000f }, r.Mantissa.data<float>().ToArray());\n Assert.Equal(new int[] { 0, 1, 2, 2, 3, 3, 3, 3, 4 }, r.Exponent.data<int>().ToArray());\n }\n\n [Fact]\n [TestOf(nameof(Tensor.deg2rad))]\n public void Deg2RadTest()\n {\n var data = new float[] { 1.0f, 2.0f, 3.0f };\n var expected = data.Select(angl => (angl * MathF.PI) / 180.0f).ToArray();\n var res = torch.tensor(data).deg2rad();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.clamp))]\n public void ClampTest1()\n {\n var data = torch.rand(3, 3, 3) * 10;\n var cl = data.clamp(1, 5);\n\n Assert.All(cl.data<float>().ToArray(), d => Assert.True(d >= 1.0f && d <= 5.0f));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.clamp))]\n public void ClampTest2()\n {\n var data = torch.rand(3, 3, 3) * 10;\n var cl = data.clamp(torch.ones(3, 3, 3), torch.ones(3, 3, 3) * 5);\n\n Assert.All(cl.data<float>().ToArray(), d => Assert.True(d >= 1.0f && d <= 5.0f));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.clamp))]\n public void ClampTest3()\n {\n var data = torch.rand(3, 3, 3) * 10;\n var cl = torch.clamp(data, 1, 5);\n\n Assert.All(cl.data<float>().ToArray(), d => Assert.True(d >= 1.0f && d <= 5.0f));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.clamp))]\n public void ClampTest4()\n {\n var data = torch.rand(3, 3, 3) * 10;\n var cl = torch.clamp(data, torch.ones(3, 3, 3), torch.ones(3, 3, 3) * 5);\n\n Assert.All(cl.data<float>().ToArray(), d => Assert.True(d >= 1.0f && d <= 5.0f));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.rad2deg))]\n public void Rad2DegTest()\n {\n var data = new float[] { 1.0f, 2.0f, 3.0f };\n var expected = data.Select(angl => (angl * 180.0f) / MathF.PI).ToArray();\n var res = torch.tensor(data).rad2deg();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.abs))]\n public void AbsTest()\n {\n var data = torch.arange(-10.0f, 10.0f, 1.0f);\n var expected = data.data<float>().ToArray().Select(MathF.Abs).ToArray();\n var res = data.abs();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.abs))]\n public void AbsTestC32()\n {\n var data = torch.rand(new long[] { 25 }, complex64);\n var expected = data.data<(float R, float I)>().ToArray().Select(c => MathF.Sqrt(c.R * c.R + c.I * c.I)).ToArray();\n var res = data.abs();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.abs))]\n public void AbsTestC64()\n {\n var data = torch.rand(new long[] { 25 }, complex128);\n var expected = data.data<System.Numerics.Complex>().ToArray().Select(c => Math.Sqrt(c.Real * c.Real + c.Imaginary * c.Imaginary)).ToArray<double>();\n var res = data.abs();\n Assert.True(res.allclose(torch.tensor(expected, float64)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.angle))]\n public void AngleTestC32()\n {\n var data = torch.randn(new long[] { 25 }, complex64);\n var expected = data.data<(float R, float I)>().ToArray().Select(c => {\n var x = c.R;\n var y = c.I;\n return (x > 0 || y != 0) ? 2 * MathF.Atan(y / (MathF.Sqrt(x * x + y * y) + x)) : (x < 0 && y == 0) ? MathF.PI : 0;\n }).ToArray();\n var res = data.angle();\n Assert.True(res.allclose(torch.tensor(expected), rtol: 1e-03, atol: 1e-05));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.angle))]\n public void AngleTestC64()\n {\n var data = torch.randn(new long[] { 25 }, complex128);\n var expected = data.data<System.Numerics.Complex>().ToArray().Select(c => {\n var x = c.Real;\n var y = c.Imaginary;\n return (x > 0 || y != 0) ? 2 * Math.Atan(y / (Math.Sqrt(x * x + y * y) + x)) : (x < 0 && y == 0) ? Math.PI : 0;\n }).ToArray<double>();\n var res = data.angle();\n Assert.True(res.allclose(torch.tensor(expected, float64), rtol: 1e-03, atol: 1e-05));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.sqrt))]\n public void SqrtTest()\n {\n var data = new float[] { 1.0f, 2.0f, 3.0f };\n var expected = data.Select(MathF.Sqrt).ToArray();\n var res = torch.tensor(data).sqrt();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.sin))]\n public void SinTest()\n {\n var data = new float[] { 1.0f, 2.0f, 3.0f };\n var expected = data.Select(MathF.Sin).ToArray();\n var res = torch.tensor(data).sin();\n Assert.True(res.allclose(torch.tensor(expected)));\n res = torch.sin(torch.tensor(data));\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.cos))]\n public void CosTest()\n {\n var data = new float[] { 1.0f, 2.0f, 3.0f };\n var expected = data.Select(MathF.Cos).ToArray();\n var res = torch.tensor(data).cos();\n Assert.True(res.allclose(torch.tensor(expected)));\n res = torch.cos(torch.tensor(data));\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.i0))]\n public void I0Test()\n {\n var data = torch.arange(0, 5, 1, float32);\n var expected = new float[] { 0.99999994f, 1.266066f, 2.27958512f, 4.88079262f, 11.3019209f };\n var res = data.i0();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.hypot))]\n public void HypotTest()\n {\n var a = new float[] { 1.0f, 2.0f, 3.0f };\n var b = new float[] { 1.0f, 2.0f, 3.0f };\n var expected = a.Select(x => MathF.Sqrt(2.0f) * x).ToArray();\n var res = torch.tensor(a).hypot(torch.tensor(b));\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.tan))]\n public void TanTest()\n {\n var data = new float[] { 1.0f, 2.0f, 3.0f };\n var expected = data.Select(MathF.Tan).ToArray();\n var res = torch.tensor(data).tan();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.sinh))]\n public void SinhTest()\n {\n var data = new float[] { 1.0f, 2.0f, 3.0f };\n var expected = data.Select(MathF.Sinh).ToArray();\n var res = torch.tensor(data).sinh();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.cosh))]\n public void CoshTest()\n {\n var data = new float[] { 1.0f, 2.0f, 3.0f };\n var expected = data.Select(MathF.Cosh).ToArray();\n var res = torch.tensor(data).cosh();\n var tmp = res.data<Single>();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.tanh))]\n public void TanhTest()\n {\n var data = new float[] { 1.0f, 2.0f, 3.0f };\n var expected = data.Select(MathF.Tanh).ToArray();\n var res = torch.tensor(data).tanh();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.asinh))]\n public void ArcSinhTest()\n {\n var data = new float[] { -0.1f, 0.0f, 0.1f };\n var expected = data.Select(MathF.Asinh).ToArray();\n var res = torch.tensor(data).asinh();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.acosh))]\n public void ArcCoshTest()\n {\n var data = new float[] { 1.0f, 2.0f, 3.0f };\n var expected = data.Select(MathF.Acosh).ToArray();\n var res = torch.tensor(data).acosh();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.atanh))]\n public void ArcTanhTest()\n {\n var data = new float[] { -0.1f, 0.0f, 0.1f };\n var expected = data.Select(MathF.Atanh).ToArray();\n var res = torch.tensor(data).atanh();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.asin))]\n public void AsinTest()\n {\n var data = new float[] { 1.0f, 0.2f, -0.1f };\n var expected = data.Select(MathF.Asin).ToArray();\n {\n var res = torch.tensor(data).asin();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n {\n var res = torch.tensor(data).arcsin();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n }\n\n [Fact]\n [TestOf(nameof(Tensor.acos))]\n public void AcosTest()\n {\n var data = new float[] { 1.0f, 0.2f, -0.1f };\n var expected = data.Select(MathF.Acos).ToArray();\n {\n var res = torch.tensor(data).acos();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n {\n var res = torch.tensor(data).arccos();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n }\n\n [Fact]\n [TestOf(nameof(Tensor.atan))]\n public void AtanTest()\n {\n var data = new float[] { 1.0f, 0.2f, -0.1f };\n var expected = data.Select(MathF.Atan).ToArray();\n {\n var res = torch.tensor(data).atan();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n {\n var res = torch.tensor(data).arctan();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n }\n\n [Fact]\n [TestOf(nameof(Tensor.log))]\n public void LogTest()\n {\n var data = new float[] { 1.0f, 2.0f, 3.0f };\n var expected = data.Select(x => MathF.Log(x)).ToArray();\n var res = torch.tensor(data).log();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.log10))]\n public void Log10Test()\n {\n var data = new float[] { 1.0f, 2.0f, 3.0f };\n var expected = data.Select(MathF.Log10).ToArray();\n var res = torch.tensor(data).log10();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.log2))]\n public void Log2Test()\n {\n var data = new float[] { 1.0f, 2.0f, 32.0f };\n var expected = data.Select(MathF.Log2).ToArray();\n var res = torch.tensor(data).log2();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.logaddexp))]\n public void LogAddExpTest()\n {\n var x = new float[] { 1.0f, 2.0f, 3.0f };\n var y = new float[] { 4.0f, 5.0f, 6.0f };\n var expected = new float[x.Length];\n for (int i = 0; i < x.Length; i++) {\n expected[i] = MathF.Log(MathF.Exp(x[i]) + MathF.Exp(y[i]));\n }\n var res = torch.tensor(x).logaddexp(torch.tensor(y));\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.logaddexp2))]\n public void LogAddExp2Test()\n {\n var x = new float[] { 1.0f, 2.0f, 3.0f };\n var y = new float[] { 4.0f, 5.0f, 6.0f };\n var expected = new float[x.Length];\n for (int i = 0; i < x.Length; i++) {\n expected[i] = MathF.Log(MathF.Pow(2.0f, x[i]) + MathF.Pow(2.0f, y[i]), 2.0f);\n }\n var res = torch.tensor(x).logaddexp2(torch.tensor(y));\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.reciprocal))]\n public void ReciprocalTest()\n {\n var x = torch.ones(new long[] { 10, 10 });\n x.fill_(4.0f);\n var y = x.reciprocal();\n\n Assert.All(x.data<float>().ToArray(), a => Assert.Equal(4.0f, a));\n Assert.All(y.data<float>().ToArray(), a => Assert.Equal(0.25f, a));\n\n x.reciprocal_();\n Assert.All(x.data<float>().ToArray(), a => Assert.Equal(0.25f, a));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.exp2))]\n public void Exp2Test()\n {\n var x = new float[] { 1.0f, 2.0f, 3.0f };\n var expected = new float[] { 2.0f, 4.0f, 8.0f };\n var res = torch.tensor(x).exp2();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.floor))]\n public void FloorTest()\n {\n var data = new float[] { 1.1f, 2.0f, 3.1f };\n var expected = data.Select(MathF.Floor).ToArray();\n var input = torch.tensor(data);\n var res = input.floor();\n Assert.True(res.allclose(torch.tensor(expected)));\n\n input.floor_();\n Assert.True(input.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.floor_divide))]\n public void FloorDivideTest()\n {\n var data = new float[] { 1.1f, 2.0f, 3.1f };\n var expected = data.Select(d => MathF.Floor(d / 2)).ToArray();\n var input = torch.tensor(data);\n var res = input.floor_divide(2.0f);\n Assert.True(res.allclose(torch.tensor(expected)));\n\n input.floor_divide_(2.0f);\n Assert.True(input.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.trunc))]\n public void TruncTest()\n {\n var input = torch.randn(new long[] { 25 });\n var expected = input.data<float>().ToArray().Select(MathF.Truncate).ToArray();\n var res = input.trunc();\n Assert.True(res.allclose(torch.tensor(expected)));\n\n input.trunc_();\n Assert.True(input.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.ceil))]\n public void CeilTest()\n {\n var data = new float[] { 1.1f, 2.0f, 3.1f };\n var expected = data.Select(MathF.Ceiling).ToArray();\n var input = torch.tensor(data);\n var res = input.ceil();\n Assert.True(res.allclose(torch.tensor(expected)));\n\n input.ceil_();\n Assert.True(res.allclose(torch.tensor(expected)));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.round))]\n public void RoundTest()\n {\n var rnd = new Random();\n var data = Enumerable.Range(1, 100).Select(i => (float)rnd.NextDouble() * 10000).ToArray();\n\n {\n var expected = data.Select(x => MathF.Round(x)).ToArray();\n var input = torch.tensor(data);\n var res = input.round();\n Assert.True(res.allclose(torch.tensor(expected)));\n\n input.round_();\n Assert.True(input.allclose(torch.tensor(expected)));\n }\n {\n var expected = data.Select(x => MathF.Round(x * 10.0f) / 10.0f).ToArray();\n var input = torch.tensor(data);\n var res = input.round(1);\n Assert.True(res.allclose(torch.tensor(expected)));\n\n input.round_(1);\n Assert.True(input.allclose(torch.tensor(expected)));\n }\n {\n var expected = data.Select(x => MathF.Round(x * 100.0f) / 100.0f).ToArray();\n var input = torch.tensor(data);\n var res = input.round(2);\n Assert.True(res.allclose(torch.tensor(expected)));\n\n input.round_(2);\n Assert.True(input.allclose(torch.tensor(expected)));\n }\n {\n var expected = data.Select(x => MathF.Round(x * 0.1f) / 0.1f).ToArray();\n var input = torch.tensor(data);\n var res = input.round(-1);\n Assert.True(res.allclose(torch.tensor(expected)));\n\n input.round_(-1);\n Assert.True(input.allclose(torch.tensor(expected)));\n }\n {\n var expected = data.Select(x => MathF.Round(x * 0.01f) / 0.01f).ToArray();\n var input = torch.tensor(data);\n var res = input.round(-2);\n Assert.True(res.allclose(torch.tensor(expected)));\n\n input.round_(-2);\n Assert.True(input.allclose(torch.tensor(expected)));\n }\n }\n\n [Fact]\n [TestOf(nameof(torch.round))]\n [TestOf(nameof(torch.round_))]\n public void RoundTestWithDecimals()\n {\n const long n = 7L;\n var i = eye(n); // identity matrix\n var a = rand(new[] { n, n });\n var b = linalg.inv(a);\n\n // check non-inline version\n var r0 = round(matmul(a, b), 2L);\n var r1 = round(matmul(b, a), 3L);\n Assert.True(i.allclose(r0), \"round() failed\");\n Assert.True(i.allclose(r1), \"round() failed\");\n\n // check inline version\n var r0_ = matmul(a, b).round_(2L);\n var r1_ = matmul(b, a).round_(3L);\n Assert.True(i.allclose(r0_), \"round_() failed\");\n Assert.True(i.allclose(r1_), \"round_() failed\");\n }\n }\n}\n" }, { "alpha_fraction": 0.5193738341331482, "alphanum_fraction": 0.5306881666183472, "avg_line_length": 49.8110237121582, "blob_id": "4d83b250d6733947c9a6ddd787b1753e2497ca0a", "content_id": "2b20d3bdc9a4cd9f21de535f0487945e3c4ad8f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6452, "license_type": "permissive", "max_line_length": 130, "num_lines": 127, "path": "/src/TorchAudio/Models.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n public static partial class models\n {\n /// <summary>\n /// Tacotron2 model based on the implementation from\n /// Nvidia https://github.com/NVIDIA/DeepLearningExamples/.\n /// </summary>\n /// <param name=\"mask_padding\">Use mask padding</param>\n /// <param name=\"n_mels\">Number of mel bins</param>\n /// <param name=\"n_symbol\">Number of symbols for the input text</param>\n /// <param name=\"n_frames_per_step\">Number of frames processed per step, only 1 is supported</param>\n /// <param name=\"symbol_embedding_dim\">Input embedding dimension</param>\n /// <param name=\"encoder_n_convolution\">Number of encoder convolutions</param>\n /// <param name=\"encoder_kernel_size\">Encoder kernel size</param>\n /// <param name=\"encoder_embedding_dim\">Encoder embedding dimension</param>\n /// <param name=\"decoder_rnn_dim\">Number of units in decoder LSTM</param>\n /// <param name=\"decoder_max_step\">Maximum number of output mel spectrograms</param>\n /// <param name=\"decoder_dropout\">Dropout probability for decoder LSTM</param>\n /// <param name=\"decoder_early_stopping\">Continue decoding after all samples are finished</param>\n /// <param name=\"attention_rnn_dim\">Number of units in attention LSTM</param>\n /// <param name=\"attention_hidden_dim\">Dimension of attention hidden representation</param>\n /// <param name=\"attention_location_n_filter\">Number of filters for attention model</param>\n /// <param name=\"attention_location_kernel_size\">Kernel size for attention model</param>\n /// <param name=\"attention_dropout\">Dropout probability for attention LSTM</param>\n /// <param name=\"prenet_dim\">Number of ReLU units in prenet layers</param>\n /// <param name=\"postnet_n_convolution\">Number of postnet convolutions</param>\n /// <param name=\"postnet_kernel_size\">Postnet kernel size</param>\n /// <param name=\"postnet_embedding_dim\">Postnet embedding dimension</param>\n /// <param name=\"gate_threshold\">Probability threshold for stop token</param>\n /// <returns>Tacotron2 model</returns>\n public static Modules.Tacotron2 Tacotron2(\n bool mask_padding = false,\n int n_mels = 80,\n int n_symbol = 148,\n int n_frames_per_step = 1,\n int symbol_embedding_dim = 512,\n int encoder_embedding_dim = 512,\n int encoder_n_convolution = 3,\n int encoder_kernel_size = 5,\n int decoder_rnn_dim = 1024,\n int decoder_max_step = 2000,\n double decoder_dropout = 0.1,\n bool decoder_early_stopping = true,\n int attention_rnn_dim = 1024,\n int attention_hidden_dim = 128,\n int attention_location_n_filter = 32,\n int attention_location_kernel_size = 31,\n double attention_dropout = 0.1,\n int prenet_dim = 256,\n int postnet_n_convolution = 5,\n int postnet_kernel_size = 5,\n int postnet_embedding_dim = 512,\n double gate_threshold = 0.5)\n {\n return new Modules.Tacotron2(\n \"tacotron2\",\n mask_padding,\n n_mels,\n n_symbol,\n n_frames_per_step,\n symbol_embedding_dim,\n encoder_embedding_dim,\n encoder_n_convolution,\n encoder_kernel_size,\n decoder_rnn_dim,\n decoder_max_step,\n decoder_dropout,\n decoder_early_stopping,\n attention_rnn_dim,\n attention_hidden_dim,\n attention_location_n_filter,\n attention_location_kernel_size,\n attention_dropout,\n prenet_dim,\n postnet_n_convolution,\n postnet_kernel_size,\n postnet_embedding_dim,\n gate_threshold);\n }\n\n /// <summary>\n /// WaveRNN model based on the implementation from `fatchord https://github.com/fatchord/WaveRNN`.\n /// </summary>\n /// <param name=\"upsample_scales\">The list of upsample scales.</param>\n /// <param name=\"n_classes\">The number of output classes.</param>\n /// <param name=\"hop_length\">The number of samples between the starts of consecutive frames.</param>\n /// <param name=\"n_res_block\">The number of ResBlock in stack.</param>\n /// <param name=\"n_rnn\">The dimension of RNN layer.</param>\n /// <param name=\"n_fc\">The dimension of fully connected layer.</param>\n /// <param name=\"kernel_size\">The number of kernel size in the first Conv1d layer.</param>\n /// <param name=\"n_freq\">The number of bins in a spectrogram.</param>\n /// <param name=\"n_hidden\">The number of hidden dimensions of resblock.</param>\n /// <param name=\"n_output\">The number of output dimensions of melresnet.</param>\n /// <returns>The WaveRNN model</returns>\n public static Modules.WaveRNN WaveRNN(\n long[] upsample_scales,\n int n_classes,\n int hop_length,\n int n_res_block = 10,\n int n_rnn = 512,\n int n_fc = 512,\n int kernel_size = 5,\n int n_freq = 128,\n int n_hidden = 128,\n int n_output = 128)\n {\n return new Modules.WaveRNN(\n \"wavernn\",\n upsample_scales,\n n_classes,\n hop_length,\n n_res_block,\n n_rnn,\n n_fc,\n kernel_size,\n n_freq,\n n_hidden,\n n_output);\n }\n }\n }\n}" }, { "alpha_fraction": 0.39836984872817993, "alphanum_fraction": 0.39836984872817993, "avg_line_length": 39.06122589111328, "blob_id": "0be7c010607895aad1bfdf3de67a7b2ebe4e1275", "content_id": "78b53e7ff1a0b7a271913b0ce427f5313c9e9e72", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3926, "license_type": "permissive", "max_line_length": 130, "num_lines": 98, "path": "/src/TorchSharp/NN/Utils/PackedSequence.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Runtime.InteropServices;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class nn\n {\n public static partial class utils\n {\n public static partial class rnn\n {\n /// <summary>\n /// A packed batch of variable length sequences.\n /// </summary>\n public sealed class PackedSequence : IDisposable\n {\n /// <summary>\n /// Class wrapping PyTorch's packedsequence object reference.\n /// </summary>\n internal sealed class HType : SafeHandle\n {\n public HType(IntPtr preexistingHandle, bool ownsHandle)\n : base(IntPtr.Zero, ownsHandle)\n {\n SetHandle(preexistingHandle);\n }\n\n public override bool IsInvalid => handle == IntPtr.Zero;\n\n // This is just for marshalling\n internal HType() : base(IntPtr.Zero, true)\n {\n }\n\n protected override bool ReleaseHandle()\n {\n THSNN_PackedSequence_dispose(handle);\n return true;\n }\n }\n\n /// <summary>\n /// The packed sequences\n /// </summary>\n public readonly Tensor data;\n\n /// <summary>\n /// Batch size at each sequence step\n /// </summary>\n public readonly Tensor batch_sizes;\n\n /// <summary>\n /// The sorted indices\n /// </summary>\n public readonly Tensor sorted_indices;\n\n /// <summary>\n /// The original indices\n /// </summary>\n public readonly Tensor unsorted_indices;\n private HType handle;\n\n internal PackedSequence(HType handle)\n {\n this.handle = handle;\n this.data = new Tensor(THSNN_PackedSequence_data(handle));\n this.batch_sizes = new Tensor(THSNN_PackedSequence_batch_sizes(handle));\n this.sorted_indices = new Tensor(THSNN_PackedSequence_sorted_indices(handle));\n this.unsorted_indices = new Tensor(THSNN_PackedSequence_unsorted_indices(handle));\n }\n\n internal HType Handle => handle;\n\n /// <summary>\n /// Releases the storage.\n /// </summary>\n public void Dispose()\n {\n this.data.Dispose();\n this.batch_sizes.Dispose();\n this.sorted_indices.Dispose();\n this.unsorted_indices.Dispose();\n\n if (handle != null && !handle.IsInvalid) {\n handle.Dispose();\n handle.SetHandleAsInvalid();\n }\n }\n}\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.561834990978241, "alphanum_fraction": 0.5684632658958435, "avg_line_length": 44.14173126220703, "blob_id": "562d61ae5d3ff7fb0c91269fd317266b13f0cc03", "content_id": "b90f26a1e15b94512467c9056c85c8abe4d0f72f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5733, "license_type": "permissive", "max_line_length": 203, "num_lines": 127, "path": "/src/TorchSharp/Tensor/Factories/ones.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torch\n {\n /// <summary>\n /// Create a new tensor filled with ones\n /// </summary>\n public static Tensor ones(long[] size, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _ones(size, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new tensor filled with ones\n /// </summary>\n public static Tensor ones(ReadOnlySpan<long> size, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _ones(size, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 1-D tensor filled with ones\n /// </summary>\n public static Tensor ones(long size, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _ones(stackalloc long[] { size }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 2-D tensor filled with ones\n /// </summary>\n public static Tensor ones(long rows, long columns, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _ones(stackalloc long[] { rows, columns }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 3-D tensor filled with ones\n /// </summary>\n public static Tensor ones(long dim0, long dim1, long dim2, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _ones(stackalloc long[] { dim0, dim1, dim2 }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 4-D tensor filled with ones\n /// </summary>\n public static Tensor ones(long dim0, long dim1, long dim2, long dim3, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _ones(stackalloc long[] { dim0, dim1, dim2, dim3 }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 1-D tensor filled with ones\n /// </summary>\n public static Tensor ones(int size, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _ones(stackalloc long[] { size }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 2-D tensor filled with ones\n /// </summary>\n public static Tensor ones(int rows, int columns, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _ones(stackalloc long[] { rows, columns }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 3-D tensor filled with ones\n /// </summary>\n public static Tensor ones(int dim0, int dim1, int dim2, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _ones(stackalloc long[] { dim0, dim1, dim2 }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 4-D tensor filled with ones\n /// </summary>\n public static Tensor ones(int dim0, int dim1, int dim2, int dim3, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _ones(stackalloc long[] { dim0, dim1, dim2, dim3 }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Returns a tensor filled with the scalar value 1, with the same size as input.\n /// </summary>\n public static Tensor ones_like(Tensor input, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null) => input.ones_like(dtype, device, requires_grad);\n\n /// <summary>\n /// Create a new tensor filled with ones\n /// </summary>\n private static Tensor _ones(ReadOnlySpan<long> size, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n device = InitializeDevice(device);\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n dtype = get_default_dtype();\n }\n\n unsafe {\n fixed (long* psizes = size) {\n var handle = THSTensor_ones((IntPtr)psizes, size.Length, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_ones((IntPtr)psizes, size.Length, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n var result = new Tensor(handle);\n\n if (names != null && names.Length > 0) {\n\n result.rename_(names);\n }\n\n return result;\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.599662184715271, "alphanum_fraction": 0.599662184715271, "avg_line_length": 27.238094329833984, "blob_id": "fcc80b30bbf53709bc8b739fa5319eda719136f2", "content_id": "420ca40773ed2e53a23dd86c60bb728fb3928fce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 592, "license_type": "permissive", "max_line_length": 130, "num_lines": 21, "path": "/src/TorchSharp/IProgressBar.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\n\nnamespace TorchSharp\n{\n /// <summary>\n /// Interface to implement progress bar.\n /// </summary>\n public interface IProgressBar : IDisposable\n {\n /// <summary>\n /// The current position of the progress bar\n /// </summary>\n public long Value { set; get; }\n\n /// <summary>\n /// The maximum position of the progress bar\n /// </summary>\n public long? Maximum { set; get; }\n }\n}" }, { "alpha_fraction": 0.49848297238349915, "alphanum_fraction": 0.5171367526054382, "avg_line_length": 38.90583038330078, "blob_id": "cb09ea6ed9f1a211bd810f74f26166342dde4d38", "content_id": "4d1665c7e8b0d01c5e848dda5f925293d0639a25", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8899, "license_type": "permissive", "max_line_length": 192, "num_lines": 223, "path": "/src/Examples/ResNet.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\n\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\n\nnamespace TorchSharp.Examples\n{\n /// <summary>\n /// Modified version of ResNet to classify CIFAR10 32x32 images.\n /// </summary>\n class ResNet : Module<Tensor, Tensor>\n {\n // The code here is is loosely based on https://github.com/kuangliu/pytorch-cifar/blob/master/models/resnet.py\n // Licence and copypright notice at: https://github.com/kuangliu/pytorch-cifar/blob/master/LICENSE\n\n private readonly Module<Tensor, Tensor> layers;\n private int in_planes = 64;\n\n public static ResNet ResNet18(int numClasses, Device device = null)\n {\n return new ResNet(\n \"ResNet18\",\n (name, in_planes, planes, stride) => new BasicBlock(name, in_planes, planes, stride),\n BasicBlock.expansion, new int[] { 2, 2, 2, 2 },\n 10,\n device); \n }\n\n public static ResNet ResNet34(int numClasses, Device device = null)\n {\n return new ResNet(\n \"ResNet34\",\n (name, in_planes, planes, stride) => new BasicBlock(name, in_planes, planes, stride),\n BasicBlock.expansion, new int[] { 3, 4, 6, 3 },\n 10,\n device);\n }\n\n public static ResNet ResNet50(int numClasses, Device device = null)\n {\n return new ResNet(\n \"ResNet50\",\n (name, in_planes, planes, stride) => new Bottleneck(name, in_planes, planes, stride),\n Bottleneck.expansion, new int[] { 3, 4, 6, 3 },\n 10,\n device);\n }\n\n public static ResNet ResNet101(int numClasses, Device device = null)\n {\n return new ResNet(\n \"ResNet101\",\n (name, in_planes, planes, stride) => new Bottleneck(name, in_planes, planes, stride),\n Bottleneck.expansion, new int[] { 3, 4, 23, 3 },\n 10,\n device);\n }\n\n public static ResNet ResNet152(int numClasses, Device device = null)\n {\n return new ResNet(\n \"ResNet152\",\n (name, in_planes, planes, stride) => new Bottleneck(name, in_planes, planes, stride),\n Bottleneck.expansion, new int[] { 3, 4, 36, 3 },\n 10,\n device);\n }\n\n public ResNet(string name, Func<string, int,int,int,Module<Tensor, Tensor>> block, int expansion, IList<int> num_blocks, int numClasses, Device device = null) : base(name)\n {\n var modules = new List<(string, Module<Tensor, Tensor>)>();\n\n modules.Add(($\"conv2d-first\", Conv2d(3, 64, kernelSize: 3, stride: 1, padding: 1, bias: false)));\n modules.Add(($\"bnrm2d-first\", BatchNorm2d(64)));\n modules.Add(($\"relu-first\", ReLU(inplace:true)));\n MakeLayer(modules, block, expansion, 64, num_blocks[0], 1);\n MakeLayer(modules, block, expansion, 128, num_blocks[1], 2);\n MakeLayer(modules, block, expansion, 256, num_blocks[2], 2);\n MakeLayer(modules, block, expansion, 512, num_blocks[3], 2);\n modules.Add((\"avgpool\", AvgPool2d(new long[] { 4, 4 })));\n modules.Add((\"flatten\", Flatten()));\n modules.Add(($\"linear\", Linear(512 * expansion, numClasses)));\n\n layers = Sequential(modules);\n\n RegisterComponents();\n\n if (device != null && device.type == DeviceType.CUDA)\n this.to(device);\n }\n\n private void MakeLayer(List<(string, Module<Tensor, Tensor>)> modules, Func<string, int, int, int, Module<Tensor, Tensor>> block, int expansion, int planes, int num_blocks, int stride)\n {\n var strides = new List<int>();\n strides.Add(stride);\n for (var i = 0; i < num_blocks-1; i++) { strides.Add(1); }\n\n for (var i = 0; i < strides.Count; i++) {\n var s = strides[i];\n modules.Add(($\"blck-{planes}-{i}\", block($\"blck-{planes}-{i}\", in_planes, planes, s)));\n in_planes = planes * expansion;\n }\n }\n\n public override Tensor forward(Tensor input)\n {\n return layers.forward(input);\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n layers.Dispose();\n ClearModules();\n }\n base.Dispose(disposing);\n }\n\n class BasicBlock : Module<Tensor, Tensor>\n {\n public BasicBlock (string name, int in_planes, int planes, int stride) : base(name)\n {\n var modules = new List<(string, Module<Tensor, Tensor>)>();\n\n modules.Add(($\"{name}-conv2d-1\", Conv2d(in_planes, planes, kernelSize: 3, stride: stride, padding: 1, bias: false)));\n modules.Add(($\"{name}-bnrm2d-1\", BatchNorm2d(planes)));\n modules.Add(($\"{name}-relu-1\", ReLU(inplace: true)));\n modules.Add(($\"{name}-conv2d-2\", Conv2d(planes, planes, kernelSize: 3, stride: 1, padding: 1, bias: false)));\n modules.Add(($\"{name}-bnrm2d-2\", BatchNorm2d(planes)));\n\n layers = Sequential(modules);\n\n if (stride != 1 || in_planes != expansion*planes) {\n shortcut = Sequential(\n ($\"{name}-conv2d-3\", Conv2d(in_planes, expansion * planes, kernelSize: 1, stride: stride, bias: false)),\n ($\"{name}-bnrm2d-3\", BatchNorm2d(expansion * planes)));\n }\n else {\n shortcut = Sequential();\n }\n\n modules.Add(($\"{name}-relu-2\", ReLU(inplace: true)));\n\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor t)\n {\n var x = layers.forward(t);\n var y = shortcut.forward(t);\n return x.add_(y).relu_();\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n layers.Dispose();\n shortcut.Dispose();\n ClearModules();\n }\n base.Dispose(disposing);\n }\n\n public static int expansion = 1;\n\n private readonly Module<Tensor, Tensor> layers;\n private readonly Module<Tensor, Tensor> shortcut;\n }\n\n class Bottleneck : Module<Tensor, Tensor>\n {\n public Bottleneck(string name, int in_planes, int planes, int stride) : base(name)\n {\n var modules = new List<(string, Module<Tensor, Tensor>)>();\n\n modules.Add(($\"{name}-conv2d-1\", Conv2d(in_planes, planes, kernelSize: 1, bias: false)));\n modules.Add(($\"{name}-bnrm2d-1\", BatchNorm2d(planes)));\n modules.Add(($\"{name}relu-1\", ReLU(inplace:true)));\n modules.Add(($\"{name}-conv2d-2\", Conv2d(planes, planes, kernelSize: 3, stride: stride, padding: 1, bias: false)));\n modules.Add(($\"{name}-bnrm2d-2\", BatchNorm2d(planes)));\n modules.Add(($\"{name}relu-2\", ReLU(inplace: true)));\n modules.Add(($\"{name}-conv2d-3\", Conv2d(planes, expansion * planes, kernelSize: 1, bias: false)));\n modules.Add(($\"{name}-bnrm2d-3\", BatchNorm2d(expansion * planes)));\n\n layers = Sequential(modules);\n\n if (stride != 1 || in_planes != expansion * planes) {\n shortcut = Sequential(\n ($\"{name}-conv2d-4\", Conv2d(in_planes, expansion * planes, kernelSize: 1, stride: stride, bias: false)),\n ($\"{name}-bnrm2d-4\", BatchNorm2d(expansion * planes)));\n } else {\n shortcut = Sequential();\n }\n\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor t)\n {\n var x = layers.forward(t);\n using var y = shortcut.forward(t);\n return x.add_(y).relu_();\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n layers.Dispose();\n shortcut.Dispose();\n ClearModules();\n }\n base.Dispose(disposing);\n }\n\n public static int expansion = 4;\n\n private readonly Module<Tensor, Tensor> layers;\n private readonly Module<Tensor, Tensor> shortcut;\n }\n }\n}\n" }, { "alpha_fraction": 0.5612648129463196, "alphanum_fraction": 0.5626673698425293, "avg_line_length": 43.061798095703125, "blob_id": "793488beb749a87efdf464eda231b99e0f2a3715", "content_id": "81bbd64ea1b585fba2f6a98dc4f72abd36500960", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7843, "license_type": "permissive", "max_line_length": 192, "num_lines": 178, "path": "/src/TorchSharp/Distributions/TransformedDistribution.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using System.Linq;\n using static torch.distributions;\n\n namespace Modules\n {\n /// <summary>\n /// Extension of the Distribution class, which applies a sequence of Transforms to a base distribution.\n /// </summary>\n public class TransformedDistribution : Distribution\n {\n protected Distribution base_distribution;\n private torch.distributions.transforms.Transform[] transforms;\n private torch.distributions.transforms.Transform[] reverse_transforms;\n\n public TransformedDistribution(torch.Generator generator = null) : base(generator)\n {\n }\n\n public TransformedDistribution(Distribution base_distribution, torch.distributions.transforms.Transform transform, torch.Generator generator = null) :\n this(base_distribution, new torch.distributions.transforms.Transform[] { transform}, generator)\n {\n _init(base_distribution, transforms);\n }\n\n public TransformedDistribution(Distribution base_distribution, IEnumerable<torch.distributions.transforms.Transform> transforms, torch.Generator generator = null) : base(generator)\n {\n _init(base_distribution, transforms.ToArray());\n }\n\n protected void _init(Distribution base_distribution, torch.distributions.transforms.Transform[] transforms)\n {\n this.transforms = transforms;\n this.reverse_transforms = transforms.Reverse().ToArray();\n\n var base_shape = base_distribution.batch_shape.Concat(base_distribution.event_shape).ToArray();\n var base_event_dim = base_distribution.event_shape.Length;\n var transform = new distributions.transforms.ComposeTransform(transforms.ToArray());\n var domain_event_dim = transform.domain.event_dim;\n var shape = transform.forward_shape(base_shape);\n var expanded_base_shape = transform.inverse_shape(shape);\n\n if (base_shape != expanded_base_shape) {\n var base_batch_shape = expanded_base_shape.Take(expanded_base_shape.Length - base_event_dim).ToArray();\n base_distribution = base_distribution.expand(base_batch_shape);\n }\n\n var reinterpreted_batch_ndims = domain_event_dim - base_event_dim;\n if (reinterpreted_batch_ndims > 0) {\n //base_distribution = new distributions.Inde\n }\n\n this.base_distribution = base_distribution;\n\n var event_dim = transform.codomain.event_dim;\n event_dim += (base_event_dim - domain_event_dim > 0) ? base_event_dim - domain_event_dim : 0;\n\n var cut = shape.Length - event_dim;\n this.batch_shape = shape.Take(cut).ToArray();\n this.event_shape = shape.Skip(cut).ToArray();\n }\n\n public override Tensor mean => new Tensor(IntPtr.Zero);\n\n public override Tensor mode => base.mode;\n\n public override Tensor variance => new Tensor(IntPtr.Zero);\n\n public override Tensor stddev => base.stddev;\n\n public override Tensor cdf(Tensor value)\n {\n using var scope = torch.NewDisposeScope();\n foreach (var transform in reverse_transforms) {\n value = transform._inverse(value);\n }\n value = base_distribution.cdf(value);\n value = monotonize_cdf(value);\n return value.MoveToOuterDisposeScope();\n }\n\n public override Tensor entropy()\n {\n throw new NotImplementedException();\n }\n\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is TransformedDistribution))\n throw new ArgumentException(\"expand(): 'instance' must be a TransformedDistribution distribution\");\n\n var shape = batch_shape.Concat(event_shape).ToArray();\n foreach (var t in reverse_transforms) {\n shape = t.inverse_shape(shape);\n }\n int baseLen = shape.Length - base_distribution.event_shape.Length;\n var base_batch_shape = new long[baseLen];\n for (var i = 0; i < baseLen; i++) base_batch_shape[i] = shape[i];\n\n var newDistribution = ((instance == null) ?\n new TransformedDistribution(base_distribution.expand(base_batch_shape), transforms) :\n instance) as TransformedDistribution;\n\n newDistribution.batch_shape = batch_shape;\n newDistribution.event_shape = event_shape;\n if (newDistribution == instance) {\n newDistribution.transforms = transforms;\n newDistribution.base_distribution = base_distribution.expand(base_batch_shape);\n }\n return newDistribution;\n }\n\n public override Tensor icdf(Tensor value)\n {\n using var scope = torch.NewDisposeScope();\n value = monotonize_cdf(value);\n value = base_distribution.icdf(value);\n foreach (var transform in transforms) {\n value = transform.forward(value);\n }\n return value.MoveToOuterDisposeScope();\n }\n\n public override Tensor log_prob(Tensor value)\n {\n using var scope = torch.NewDisposeScope();\n var event_dim = event_shape.Length;\n Tensor lp = 0.0;\n var y = value;\n foreach (var t in reverse_transforms) {\n var x = t._inverse(y);\n event_dim += t.domain.event_dim - t.codomain.event_dim;\n lp = lp - distributions.transforms.Transform._sum_rightmost(t.log_abs_det_jacobian(x, y), event_dim - t.domain.event_dim);\n y = x;\n }\n lp = lp + distributions.transforms.Transform._sum_rightmost(base_distribution.log_prob(y), event_dim - base_distribution.event_shape.Length);\n return lp.MoveToOuterDisposeScope();\n }\n\n public override Tensor rsample(params long[] sample_shape)\n {\n using var scope = torch.NewDisposeScope();\n using var _ = torch.no_grad();\n var x = base_distribution.rsample(sample_shape);\n foreach (var t in transforms) {\n x = t.forward(x);\n }\n return x.MoveToOuterDisposeScope();\n }\n\n public override Tensor sample(params long[] sample_shape)\n {\n using var scope = torch.NewDisposeScope();\n using var _ = torch.no_grad();\n var x = base_distribution.sample(sample_shape);\n foreach (var t in transforms) {\n x = t.forward(x);\n }\n return x.MoveToOuterDisposeScope();\n }\n\n private Tensor monotonize_cdf(Tensor value)\n {\n Tensor sign = 1;\n foreach (var transform in transforms) {\n sign = sign * transform.sign;\n }\n return sign * (value - 0.5) + 0.5;\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6270833611488342, "alphanum_fraction": 0.6445833444595337, "avg_line_length": 36.5, "blob_id": "c6ace6e0fdff07f6c0e450e010f7467b4a309bd7", "content_id": "8fe98587a98489ae5cc72f45e12cb85fbdc5b5c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2400, "license_type": "permissive", "max_line_length": 130, "num_lines": 64, "path": "/src/TorchSharp/Utils/CRC32C.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// Note: the native implementation of CRC32C has the following copyright / license notice:\n\n/* Part of CRC-32C library: https://crc32c.machinezoo.com/ */\n/*\n Copyright (c) 2013 - 2014, 2016 Mark Adler, Robert Vazan, Max Vysokikh\n\n This software is provided 'as-is', without any express or implied\n warranty. In no event will the author be held liable for any damages\n arising from the use of this software.\n\n Permission is granted to anyone to use this software for any purpose,\n including commercial applications, and to alter it and redistribute it\n freely, subject to the following restrictions:\n\n 1. The origin of this software must not be misrepresented; you must not\n claim that you wrote the original software. If you use this software\n in a product, an acknowledgment in the product documentation would be\n appreciated but is not required.\n 2. Altered source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n 3. This notice may not be removed or altered from any source distribution.\n*/\n\nusing System;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp.Utils\n{\n public static class CRC32C\n {\n /// <summary>\n /// Compule the CRC32C value for a byte array.\n /// </summary>\n /// <param name=\"data\">A byte array.</param>\n public static unsafe uint process(byte[] data)\n {\n fixed (byte* ptr = data) {\n return crc32c_append(0, (IntPtr)ptr, (ulong)data.Length);\n }\n }\n\n /// <summary>\n /// Compule the CRC32C value for a 32-bit integer.\n /// </summary>\n /// <param name=\"data\">A byte array.</param>\n public static unsafe uint process(int data)\n {\n fixed (int* ptr = stackalloc int[] { data })\n return crc32c_append(0, (IntPtr)ptr, (ulong)sizeof(int));\n }\n\n /// <summary>\n /// Compule the CRC32C value for a 64-bit integer.\n /// </summary>\n /// <param name=\"data\">A byte array.</param>\n public static unsafe uint process(long data)\n {\n fixed (long* ptr = stackalloc long[] { data })\n return crc32c_append(0, (IntPtr)ptr, (ulong)sizeof(long));\n }\n }\n}\n" }, { "alpha_fraction": 0.6931216716766357, "alphanum_fraction": 0.7037037014961243, "avg_line_length": 45.20000076293945, "blob_id": "c7738b495a150866afc3bafdec1371851f4c8c78", "content_id": "8920a141a85c73f0e136562f31f67a1af34654ff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2079, "license_type": "permissive", "max_line_length": 136, "num_lines": 45, "path": "/src/TorchSharp/PInvoke/LibTorchSharp.THSCuda.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp.PInvoke\n{\n internal static partial class NativeMethods\n {\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSCuda_manual_seed(long seed);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSCuda_manual_seed_all(long seed);\n\n [DllImport(\"LibTorchSharp\")]\n [return: MarshalAs(UnmanagedType.U1)]\n internal static extern bool THSBackend_cublas_get_allow_tf32();\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSBackend_cublas_set_allow_tf32([MarshalAs(UnmanagedType.U1)] bool flag);\n\n [DllImport(\"LibTorchSharp\")]\n [return: MarshalAs(UnmanagedType.U1)]\n internal static extern bool THSBackend_cudnn_get_allow_tf32();\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSBackend_cudnn_set_allow_tf32([MarshalAs(UnmanagedType.U1)] bool flag);\n\n [DllImport(\"LibTorchSharp\")]\n [return: MarshalAs(UnmanagedType.U1)]\n internal static extern bool THSBackend_cuda_get_allow_fp16_reduced_precision_reduction();\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSBackend_cuda_set_allow_fp16_reduced_precision_reduction([MarshalAs(UnmanagedType.U1)] bool flag);\n\n [DllImport(\"LibTorchSharp\")]\n [return: MarshalAs(UnmanagedType.U1)]\n internal static extern bool THSBackend_cuda_get_enable_flash_sdp();\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSBackend_cuda_set_enable_flash_sdp([MarshalAs(UnmanagedType.U1)] bool flag);\n\n [DllImport(\"LibTorchSharp\")]\n [return: MarshalAs(UnmanagedType.U1)]\n internal static extern bool THSBackend_cuda_get_enable_math_sdp();\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSBackend_cuda_set_enable_math_sdp([MarshalAs(UnmanagedType.U1)] bool flag);\n }\n}\n" }, { "alpha_fraction": 0.5758683681488037, "alphanum_fraction": 0.5865560173988342, "avg_line_length": 42.35975646972656, "blob_id": "0eecd3028b7ecbf00ae2c2a87a216d079875db58", "content_id": "52f27cd50948f6a9dfe42df734eb1f871f61184a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7111, "license_type": "permissive", "max_line_length": 173, "num_lines": 164, "path": "/src/Examples.Utils/ImagerSharp.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System;\nusing System.IO;\nusing System.Runtime.CompilerServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing SixLabors.ImageSharp;\nusing SixLabors.ImageSharp.Formats;\nusing SixLabors.ImageSharp.Formats.Jpeg;\nusing SixLabors.ImageSharp.Formats.Png;\nusing SixLabors.ImageSharp.PixelFormats;\nusing static TorchSharp.torch;\nusing static TorchSharp.torchvision;\n\nnamespace TorchSharp.Examples.Utils\n{\n /// <summary>\n /// <cref>Imager</cref> implemented using ImageSharp.\n /// </summary>\n public sealed class ImagerSharp : io.Imager\n {\n private Tensor ToTensor<TPixel>(Stream stream) where TPixel : unmanaged, IPixel<TPixel>\n {\n var image = Image.Load<TPixel>(stream);\n var channels = Unsafe.SizeOf<TPixel>();\n byte[] imageBytes = new byte[image.Height * image.Width * channels];\n image.CopyPixelDataTo(imageBytes);\n return tensor(imageBytes, new long[] { image.Height, image.Width, channels }).permute(2, 0, 1);\n }\n\n private async Task<Tensor> ToTensorAsync<TPixel>(Stream stream, CancellationToken token) where TPixel : unmanaged, IPixel<TPixel>\n {\n var image = await Image.LoadAsync<TPixel>(stream, token);\n var channels = Unsafe.SizeOf<TPixel>();\n byte[] imageBytes = new byte[image.Height * image.Width * channels];\n image.CopyPixelDataTo(imageBytes);\n return tensor(imageBytes, new long[] { image.Height, image.Width, channels }).permute(2, 0, 1);\n }\n\n private void FromTensor<TPixel>(Tensor t, ImageFormat format, Stream stream) where TPixel : unmanaged, IPixel<TPixel>\n {\n var shape = t.shape;\n var tt = t.reshape(new long[] { shape[0] * shape[1] * shape[2] });\n var image = Image.LoadPixelData<TPixel>(tt.data<byte>().ToArray(), (int)shape[1], (int)shape[0]);\n IImageEncoder encoder = format switch {\n ImageFormat.Png => new PngEncoder(),\n ImageFormat.Jpeg => new JpegEncoder(),\n _ => throw new ArgumentException(\"Cannot encode to Unknown format\"),\n };\n encoder.Encode(image, stream);\n }\n\n private Task FromTensorAsync<TPixel>(Tensor t, ImageFormat format, Stream stream, CancellationToken token) where TPixel : unmanaged, IPixel<TPixel>\n {\n var shape = t.shape;\n var tt = t.reshape(new long[] { shape[0] * shape[1] * shape[2] });\n var image = Image.LoadPixelData<TPixel>(tt.data<byte>().ToArray(), (int)shape[1], (int)shape[0]);\n IImageEncoder encoder = format switch {\n ImageFormat.Png => new PngEncoder(),\n ImageFormat.Jpeg => new JpegEncoder(),\n _ => throw new ArgumentException(\"Cannot encode to Unknown format\"),\n };\n return encoder.EncodeAsync(image, stream, token);\n }\n\n public override async Task<Tensor> DecodeImageAsync(Stream stream, io.ImageReadMode mode = io.ImageReadMode.UNCHANGED, CancellationToken cancellationToken = default)\n {\n switch (mode) {\n case io.ImageReadMode.UNCHANGED:\n var format = Image.DetectFormat(stream);\n if (format is PngFormat) {\n return await ToTensorAsync<Rgba32>(stream, cancellationToken);\n } else {\n return await ToTensorAsync<Rgb24>(stream, cancellationToken);\n }\n case io.ImageReadMode.RGB_ALPHA:\n return await ToTensorAsync<Rgba32>(stream, cancellationToken);\n case io.ImageReadMode.RGB:\n return await ToTensorAsync<Rgb24>(stream, cancellationToken);\n case io.ImageReadMode.GRAY_ALPHA:\n return await ToTensorAsync<La16>(stream, cancellationToken);\n case io.ImageReadMode.GRAY:\n return await ToTensorAsync<L8>(stream, cancellationToken);\n default: throw new NotImplementedException();\n }\n }\n\n public override Tensor DecodeImage(Stream stream, io.ImageReadMode mode = io.ImageReadMode.UNCHANGED)\n {\n switch (mode) {\n case io.ImageReadMode.UNCHANGED:\n var format = Image.DetectFormat(stream);\n if (format is PngFormat) {\n return ToTensor<Rgba32>(stream);\n } else {\n return ToTensor<Rgb24>(stream);\n }\n case io.ImageReadMode.RGB_ALPHA:\n return ToTensor<Rgba32>(stream);\n case io.ImageReadMode.RGB:\n return ToTensor<Rgb24>(stream);\n case io.ImageReadMode.GRAY_ALPHA:\n return ToTensor<La16>(stream);\n case io.ImageReadMode.GRAY:\n return ToTensor<L8>(stream);\n default: throw new NotImplementedException();\n }\n }\n\n public override void EncodeImage(Tensor image, ImageFormat format, Stream stream)\n {\n Tensor permuted = image.permute(1, 2, 0);\n switch (image.shape[0]) {\n case 1:\n FromTensor<L8>(permuted, format, stream);\n break;\n case 2:\n FromTensor<L16>(permuted, format, stream);\n break;\n case 3:\n FromTensor<Rgb24>(permuted, format, stream);\n break;\n case 4:\n FromTensor<Rgba32>(permuted, format, stream);\n break;\n default:\n throw new ArgumentException(\"image tensor must have a colour channel of 1,2,3 or 4\");\n }\n }\n\n public override async Task EncodeImageAsync(Tensor image, ImageFormat format, Stream stream, CancellationToken cancellationToken = default)\n {\n Tensor permuted = image.permute(1, 2, 0);\n switch (image.shape[0]) {\n case 1:\n await FromTensorAsync<L8>(permuted, format, stream, cancellationToken);\n break;\n case 2:\n await FromTensorAsync<L16>(permuted, format, stream, cancellationToken);\n break;\n case 3:\n await FromTensorAsync<Rgb24>(permuted, format, stream, cancellationToken);\n break;\n case 4:\n await FromTensorAsync<Rgba32>(permuted, format, stream, cancellationToken);\n break;\n default:\n throw new ArgumentException(\"image tensor must have a colour channel of 1,2,3 or 4\");\n }\n }\n\n public override Tensor DecodeImage(byte[] data, io.ImageReadMode mode = io.ImageReadMode.UNCHANGED)\n {\n using var memStream = new MemoryStream(data);\n return DecodeImage(memStream, mode);\n }\n\n public override byte[] EncodeImage(Tensor image, ImageFormat format)\n {\n using var memStream = new MemoryStream();\n EncodeImage(image, format, memStream);\n return memStream.ToArray();\n }\n }\n}\n" }, { "alpha_fraction": 0.5566746592521667, "alphanum_fraction": 0.560511589050293, "avg_line_length": 54.353981018066406, "blob_id": "f15ed733fb1b751c47802f7efa809a9641ca7479", "content_id": "9cd0b3f3f2f148d25f55647e70cfaaf846a6a63a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6255, "license_type": "permissive", "max_line_length": 222, "num_lines": 113, "path": "/src/TorchSharp/NN/Pooling/AvgPool1D.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a AvgPool1D module.\n /// </summary>\n public sealed class AvgPool1d : torch.nn.Module<Tensor, Tensor>\n {\n internal AvgPool1d(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_AvgPool1d_forward(handle.DangerousGetHandle(), tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies a 1D average pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"kernelSize\">The size of the window</param>\n /// <param name=\"stride\">The stride of the window. Default value is kernel_size</param>\n /// <param name=\"padding\">implicit zero padding to be added on both sides</param>\n /// <param name=\"ceil_mode\">Whether to use ceil instead of floor to compute the output shape</param>\n /// <param name=\"count_include_pad\">Whether to include the zero-padding in the averaging calculation</param>\n /// <param name=\"divisor_override\">If specified, it will be used as divisor, otherwise size of the pooling region will be used</param>\n public static AvgPool1d AvgPool1d(long kernelSize, long? stride = null, long padding = 0, bool ceil_mode = false, bool count_include_pad = true, long? divisor_override = null)\n {\n return stride.HasValue ?\n AvgPool1d(new long[] { kernelSize }, new long[] { stride.Value }, new long[] { padding }, ceil_mode, count_include_pad, divisor_override.HasValue ? divisor_override.Value : 0) :\n AvgPool1d(new long[] { kernelSize }, null, new long[] { padding }, ceil_mode, count_include_pad, divisor_override.HasValue ? divisor_override.Value : 0);\n }\n\n /// <summary>\n /// Applies a 1D average pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"kernelSize\">The size of the window</param>\n /// <param name=\"strides\">The stride of the window. Default value is kernel_size</param>\n /// <param name=\"padding\">implicit zero padding to be added on both sides</param>\n /// <param name=\"ceil_mode\">Whether to use ceil instead of floor to compute the output shape</param>\n /// <param name=\"count_include_pad\">Whether to include the zero-padding in the averaging calculation</param>\n /// <param name=\"divisor_override\">If specified, it will be used as divisor, otherwise size of the pooling region will be used</param>\n private static AvgPool1d AvgPool1d(long[] kernelSize, long[] strides = null, long[] padding = null, bool ceil_mode = false, bool count_include_pad = true, long? divisor_override = null)\n {\n unsafe {\n fixed (long* pkernelSize = kernelSize, pstrides = strides, ppadding = padding) {\n var handle = THSNN_AvgPool1d_ctor((IntPtr)pkernelSize, (IntPtr)pstrides, (IntPtr)ppadding, ceil_mode, count_include_pad, divisor_override.HasValue ? divisor_override.Value : 0, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new AvgPool1d(handle, boxedHandle);\n }\n }\n }\n\n public static partial class functional\n {\n\n /// <summary>\n /// Applies a 1D average pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"kernelSize\"></param>\n /// <param name=\"stride\"></param>\n /// <param name=\"padding\"></param>\n /// <param name=\"ceil_mode\"></param>\n /// <param name=\"count_include_pad\"></param>\n /// <returns></returns>\n public static Tensor avg_pool1d(Tensor input, long kernelSize, long? stride = null,\n long? padding = null, bool ceil_mode = false, bool count_include_pad = true)\n {\n var kernelSizes = new long[] { kernelSize };\n var strides = new long[] { stride ?? 1 };\n var paddings = new long[] { padding ?? 0 };\n unsafe {\n fixed (long* pkernelSize = kernelSizes, pstrides = strides, ppadding = paddings) {\n var res =\n THSTensor_avg_pool1d(input.Handle,\n (IntPtr)pkernelSize, kernelSizes.Length,\n (IntPtr)pstrides, strides.Length,\n (IntPtr)ppadding, paddings.Length,\n ceil_mode,\n count_include_pad);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6544735431671143, "alphanum_fraction": 0.6544735431671143, "avg_line_length": 50.89743423461914, "blob_id": "bab664a71c62dfa9cd73cf13f34c722d060a5823", "content_id": "0a10586af87a562da326077d5cbafd01eb6af399", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2025, "license_type": "permissive", "max_line_length": 131, "num_lines": 39, "path": "/src/TorchSharp/Tensor/Tensor.Operators.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n // this file contains operator overloads\n public partial class Tensor\n {\n public static Tensor operator +(Tensor left, Tensor right) => left.add(right);\n public static Tensor operator +(Tensor left, Scalar right) => left.add(right);\n public static Tensor operator +(Scalar left, Tensor right) => right.add(left);\n\n public static Tensor operator *(Tensor left, Tensor right) => left.mul(right);\n public static Tensor operator *(Tensor left, Scalar right) => left.mul(right);\n public static Tensor operator *(Scalar left, Tensor right) => right.mul(left);\n\n public static Tensor operator -(Tensor left, Tensor right) => left.sub(right);\n public static Tensor operator -(Tensor left, Scalar right) => left.sub(right);\n public static Tensor operator -(Scalar left, Tensor right) => right.negative().add(left);\n\n public static Tensor operator /(Tensor left, Tensor right) => left.div(right);\n public static Tensor operator /(Tensor left, Scalar right) => left.div(right);\n public static Tensor operator /(Scalar left, Tensor right) => right.reciprocal().mul(left);\n\n public static Tensor operator %(Tensor left, Tensor right) => left.remainder(right);\n public static Tensor operator %(Tensor left, Scalar right) => left.remainder(right);\n\n public static Tensor operator &(Tensor left, Tensor right) => left.bitwise_and(right);\n\n public static Tensor operator |(Tensor left, Tensor right) => left.bitwise_or(right);\n\n public static Tensor operator ^(Tensor left, Tensor right) => left.bitwise_xor(right);\n\n public static Tensor operator ~(Tensor left) => left.bitwise_not();\n }\n }\n}" }, { "alpha_fraction": 0.4836462438106537, "alphanum_fraction": 0.4851812422275543, "avg_line_length": 32.60714340209961, "blob_id": "579ae51cd0b580b53c12195bdc22c84052693b2d", "content_id": "89402fd412033e55831b12a85ef5b84ca569f634", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8469, "license_type": "permissive", "max_line_length": 130, "num_lines": 252, "path": "/src/TorchSharp/NN/ModuleDict.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Linq;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing static TorchSharp.torch.nn;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// Holds parameters in a dictionary.\n /// \n /// ModuleDict can be indexed like a regular dictionary, but the modules it\n /// contains are properly registered, and will be visible by all Module methods.\n ///\n /// ModuleDict is an ordered dictionary that respects the order of insertion, and\n /// in update(), the order of the merged OrderedDict or another ModuleDict (the argument to update()).\n /// </summary>\n public class ModuleDict<T> : Module, IDictionary<string, T>, IList<(string, T)> where T : Module\n {\n public ModuleDict() : base(nameof(ModuleDict))\n {\n }\n\n /// <summary>\n /// Remove all items from the ParameterDict.\n /// </summary>\n public void clear()\n {\n _list.Clear();\n _dict.Clear();\n }\n\n /// <summary>\n /// Return an enumeration of the ParameterDict key/value pairs.\n /// </summary>\n /// <returns></returns>\n public IEnumerator<(string, T)> items() => _list.GetEnumerator();\n\n /// <summary>\n /// Return the ParameterDict keys.\n /// </summary>\n /// <returns></returns>\n public IEnumerable<string> keys() => _dict.Keys;\n\n protected override void RegisterComponents()\n {\n if (_registered) return;\n\n for (int i = 0; i < _list.Count; i++) {\n register_module($\"{_list[i].Item1}\", _list[i].Item2);\n }\n _registered = true;\n }\n\n private bool _registered = false;\n\n /// <summary>\n /// Return the ParameterDict values.\n /// </summary>\n /// <returns></returns>\n public IEnumerable<T> values() => _dict.Values;\n\n public (string, T) this[int index] {\n get => _list[index];\n set {\n var name = value.Item1;\n _list[index] = value;\n _dict[name] = value.Item2;\n }\n }\n\n public bool IsReadOnly => false;\n\n public ICollection<string> Keys => _list.Select(kv => kv.Item1).ToList();\n\n public ICollection<T> Values => _list.Select(kv => kv.Item2).ToList();\n\n public int Count => _dict.Count;\n\n public T this[string key] {\n get => _dict[key];\n set {\n _dict[key] = value;\n var idx = _list.FindIndex(kv => kv.Item1.Equals(key));\n _list[idx] = (key, value);\n }\n }\n\n public void Add((string, T) item)\n {\n _dict.Add(item.Item1, item.Item2);\n _list.Add(item);\n }\n\n public void Add(string key, T value)\n {\n _dict.Add(key, value);\n _list.Add((key, value));\n }\n\n public void Add(KeyValuePair<string, T> item)\n {\n _dict.Add(item.Key, item.Value);\n _list.Add((item.Key, item.Value));\n }\n\n public bool Contains((string, T) item)\n {\n return _list.Contains(item);\n }\n\n public void CopyTo((string, T)[] array, int arrayIndex)\n {\n _list.CopyTo(array, arrayIndex);\n }\n\n public int IndexOf((string, T) item)\n {\n return _list.IndexOf(item);\n }\n\n public void Insert(int index, (string, T) item)\n {\n _dict.Add(item.Item1, item.Item2);\n _list.Insert(index, item);\n }\n\n public bool Remove((string, T) item)\n {\n _dict.Remove(item.Item1);\n return _list.Remove(item);\n }\n\n public void RemoveAt(int index)\n {\n if (index >= _list.Count) throw new IndexOutOfRangeException();\n var (n, p) = _list[index];\n _list.RemoveAt(index);\n _dict.Remove(n);\n }\n\n public bool ContainsKey(string key)\n {\n return _dict.ContainsKey(key);\n }\n\n public bool Remove(string key)\n {\n var value = _dict[key];\n return _dict.Remove(key) && _list.Remove((key, value));\n }\n\n public bool TryGetValue(string key, [MaybeNullWhen(false)] out T value)\n {\n return _dict.TryGetValue(key, out value);\n }\n\n public void Clear()\n {\n _dict.Clear();\n _list.Clear();\n }\n\n public bool Contains(KeyValuePair<string, T> item)\n {\n return _dict.ContainsKey(item.Key);\n }\n\n public void CopyTo(KeyValuePair<string, T>[] array, int arrayIndex)\n {\n throw new NotImplementedException();\n }\n\n public bool Remove(KeyValuePair<string, T> item)\n {\n return _dict.Remove(item.Key);\n }\n\n public IEnumerator<(string, T)> GetEnumerator()\n {\n return _list.GetEnumerator();\n }\n\n IEnumerator<KeyValuePair<string, T>> IEnumerable<KeyValuePair<string, T>>.GetEnumerator()\n {\n throw new NotImplementedException();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return ((IEnumerable<KeyValuePair<string, T>>)this).GetEnumerator();\n }\n\n private List<(string, T)> _list = new List<(string, T)>();\n private Dictionary<string, T> _dict = new Dictionary<string, T>();\n };\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Create a ModuleDict instance from an array of modules.\n /// </summary>\n /// <param name=\"modules\">A list of (name,module) tuples.</param>\n /// <returns></returns>\n /// <remarks>\n /// ModuleDict can be indexed like a regular dictionary, but the modules it\n /// contains are properly registered, and will be visible by all Module methods.\n ///\n /// ModuleDict is an ordered dictionary that respects the order of insertion, and\n /// in update(), the order of the merged OrderedDict or another ModuleDict (the argument to update()).\n /// </remarks>\n public static ModuleDict<Module> ModuleDict(params (string, Module)[] modules)\n {\n var result = new ModuleDict<Module>();\n foreach (var (n, m) in modules) {\n result.Add((n, m));\n }\n return result;\n }\n\n /// <summary>\n /// Create a ModuleDict instance from an array of modules.\n /// </summary>\n /// <param name=\"modules\">A list of (name,module) tuples.</param>\n /// <returns></returns>\n /// <remarks>\n /// ModuleDict can be indexed like a regular dictionary, but the modules it\n /// contains are properly registered, and will be visible by all Module methods.\n ///\n /// ModuleDict is an ordered dictionary that respects the order of insertion, and\n /// in update(), the order of the merged OrderedDict or another ModuleDict (the argument to update()).\n /// </remarks>\n public static ModuleDict<T> ModuleDict<T>(params (string, T)[] modules) where T: Module\n {\n var result = new ModuleDict<T>();\n foreach (var (n, m) in modules) {\n result.Add((n, m));\n }\n return result;\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6134146451950073, "alphanum_fraction": 0.6134146451950073, "avg_line_length": 24.625, "blob_id": "c05a07833f4663be083ba35f5c8756dfa8ca6f67", "content_id": "be28d12e6aad6f430c96dee92fda18308ee7a872", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1640, "license_type": "permissive", "max_line_length": 101, "num_lines": 64, "path": "/src/TorchSharp/Utils/NotebookFormattingSupport.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace TorchSharp.Utils\n{\n /// <summary>\n /// Class used to identify the formatting logic for Tensors when using .NET Interactive.\n /// </summary>\n [AttributeUsage(AttributeTargets.Class)]\n public class TypeFormatterSourceAttribute : Attribute\n {\n public TypeFormatterSourceAttribute(Type formatterSourceType)\n {\n FormatterSourceType = formatterSourceType;\n }\n\n public Type FormatterSourceType { get; }\n }\n\n internal class TypeFormatterSource\n {\n public IEnumerable<object> CreateTypeFormatters()\n {\n yield return new TensorPlainTextFormatter();\n yield return new TensorHTMLFormatter();\n }\n }\n\n internal class TensorPlainTextFormatter\n {\n public string MimeType => \"text/plain\";\n\n public bool Format(object instance, TextWriter writer)\n {\n if (instance is not torch.Tensor result) {\n return false;\n }\n\n writer.Write(result.ToString(TensorStringStyle.Default));\n\n return true;\n }\n }\n\n internal class TensorHTMLFormatter\n {\n public string MimeType => \"text/html\";\n\n public bool Format(object instance, TextWriter writer)\n {\n if (instance is not torch.Tensor result) {\n return false;\n }\n\n writer.Write(\"<div><pre>\" + result.ToString(TensorStringStyle.Default) + \"</pre></div>\");\n\n return true;\n }\n }\n}\n" }, { "alpha_fraction": 0.5134429335594177, "alphanum_fraction": 0.5295370817184448, "avg_line_length": 46.39130401611328, "blob_id": "b5ddd342adbfc5abd98ed8cd7a4b39eb5cb96a61", "content_id": "2179b0fde9fae04ceea1217c4bc76129dd45ce7b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 64309, "license_type": "permissive", "max_line_length": 162, "num_lines": 1357, "path": "/src/TorchAudio/Modules/Wav2Vec2Components.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchaudio,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/audio/blob/76fca37ac8941b72a509a6e58d623632efe04543/torchaudio/models/wav2vec2/components.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/audio/blob/main/LICENSE\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Linq;\n\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\nusing static TorchSharp.torchaudio.models;\n\n#nullable enable\nnamespace TorchSharp.Modules\n{\n public partial class Wav2Vec2Model : nn.Module<Tensor, Tensor?, (Tensor, Tensor?)>\n {\n /// <summary>\n /// Layer norm with transpose\n /// </summary>\n private class LayerNorm : Module<Tensor, Tensor>\n {\n public readonly long[] normalized_shape;\n public readonly Parameter weight;\n public readonly Parameter bias;\n public readonly double eps;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n weight.Dispose();\n bias.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public LayerNorm(\n string name,\n long[] normalized_shape,\n double eps = 1e-05,\n bool elementwise_affine = true) : base(name)\n {\n this.normalized_shape = normalized_shape;\n this.weight = torch.nn.Parameter(torch.ones(normalized_shape));\n this.bias = torch.nn.Parameter(torch.zeros(normalized_shape));\n this.eps = eps;\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor input)\n {\n var x = input.transpose(-2, -1);\n x = nn.functional.layer_norm(x, this.normalized_shape, this.weight, this.bias, this.eps);\n x = x.transpose(-2, -1);\n return x;\n }\n }\n\n /// <summary>\n /// Convolution unit of FeatureExtractor\n /// </summary>\n private class ConvLayerBlock : Module<Tensor, Tensor?, (Tensor, Tensor?)>\n {\n public readonly Module<Tensor, Tensor> conv;\n public readonly long kernel_size;\n public readonly Module<Tensor, Tensor>? layer_norm;\n public readonly long stride;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n conv.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public ConvLayerBlock(\n string name,\n long in_channels,\n long out_channels,\n long kernel_size,\n long stride,\n bool bias,\n Module<Tensor, Tensor>? layer_norm) : base(name)\n {\n this.kernel_size = kernel_size;\n this.stride = stride;\n this.layer_norm = layer_norm;\n this.conv = nn.Conv1d(\n inputChannel: in_channels,\n outputChannel: out_channels,\n kernelSize: kernel_size,\n stride: stride,\n bias: bias);\n RegisterComponents();\n }\n\n /// <param name=\"x\">Shape: ``[batch, in_channels, in_frame]``</param>\n /// <param name=\"length\">Shape ``[batch, ]``</param>\n /// <returns>\n /// Shape ``[batch, out_channels, out_frames]``.\n /// Shape ``[batch, ]``.\n /// </returns>\n public override (Tensor, Tensor?) forward(\n Tensor x,\n Tensor? length)\n {\n x = this.conv.call(x);\n if (this.layer_norm != null) {\n x = this.layer_norm.call(x);\n }\n x = nn.functional.gelu(x);\n\n if (length is not null) {\n length = torch.div(length - this.kernel_size, this.stride, rounding_mode: RoundingMode.floor) + 1;\n // When input length is 0, the resulting length can be negative. So fix it here.\n length = torch.maximum(torch.zeros_like(length), length);\n }\n return (x, length);\n }\n }\n\n /// <summary>\n /// Extract features from audio\n /// </summary>\n internal class FeatureExtractor : Module<Tensor, Tensor?, (Tensor, Tensor?)>\n {\n public readonly ModuleList<Module<Tensor, Tensor?, (Tensor, Tensor?)>> conv_layers;\n\n /// <param name=\"name\"></param>\n /// <param name=\"conv_layers\">convolution layers</param>\n public FeatureExtractor(\n string name,\n ModuleList<Module<Tensor, Tensor?, (Tensor, Tensor?)>> conv_layers) : base(name)\n {\n this.conv_layers = conv_layers;\n RegisterComponents();\n }\n\n /// <param name=\"x\">Input Tensor representing a batch of audio, shape: ``[batch, time]``.</param>\n /// <param name=\"length\">Valid length of each input sample. shape: ``[batch, ]``.</param>\n /// <returns>\n /// The resulting feature, shape: ``[batch, frame, feature]``\n /// Valid length of each output sample. shape: ``[batch, ]``.\n /// </returns>\n /// <exception cref=\"ArgumentException\"></exception>\n public override (Tensor, Tensor?) forward(Tensor x, Tensor? length)\n {\n if (x.ndim != 2) {\n throw new ArgumentException(\"Expected the input Tensor to be 2D (batch, time), but received {list(x.shape)}\");\n }\n\n x = x.unsqueeze(1); // (batch, channel==1, frame)\n foreach (var layer in this.conv_layers) {\n var conv_layer = (ConvLayerBlock)layer;\n (x, length) = conv_layer.call(x, length); // (batch, feature, frame)\n }\n x = x.transpose(1, 2); // (batch, frame, feature)\n return (x, length);\n }\n }\n\n /// <summary>\n /// Layer that connects FeatureExtractor and Encoder\n /// </summary>\n private class FeatureProjection : Module<Tensor, Tensor>\n {\n public readonly Module<Tensor, Tensor> dropout;\n public readonly Module<Tensor, Tensor> layer_norm;\n public readonly Module<Tensor, Tensor> projection;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n dropout.Dispose();\n layer_norm.Dispose();\n projection.Dispose();\n }\n base.Dispose(disposing);\n }\n\n /// <summary>\n /// Projects features to encoder dimension.\n /// </summary>\n /// <param name=\"name\"></param>\n /// <param name=\"in_features\">Input feature dim.</param>\n /// <param name=\"out_features\">Output feature dim.</param>\n /// <param name=\"dropout\">Dropout probability.</param>\n public FeatureProjection(\n string name,\n long in_features,\n long out_features,\n double dropout) : base(name)\n {\n this.layer_norm = nn.LayerNorm(new long[] { in_features });\n this.projection = nn.Linear(\n in_features,\n out_features);\n this.dropout = nn.Dropout(dropout);\n RegisterComponents();\n }\n\n /// <param name=\"x\">Feature Tensor. shape: ``[batch, frame, in_feature]``</param>\n /// <returns>Projected features. ``[batch, frame, out_feature]``.</returns>\n public override Tensor forward(Tensor x)\n {\n x = this.layer_norm.call(x);\n x = this.projection.call(x);\n x = this.dropout.call(x);\n return x;\n }\n }\n\n /// <summary>\n /// Positional embedding which is placed at the beginning of Transformer.\n /// </summary>\n internal class ConvolutionalPositionalEmbedding : Module<Tensor, Tensor>\n {\n public readonly Module<Tensor, Tensor> conv;\n public readonly long embed_dim;\n public readonly long num_remove;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n conv.Dispose();\n }\n base.Dispose(disposing);\n }\n\n /// <param name=\"name\"></param>\n /// <param name=\"embed_dim\">Feature dimension of the input Tensor.</param>\n /// <param name=\"kernel_size\">The number of frames to be use.</param>\n /// <param name=\"groups\">The number of groups in feature dimensions.</param>\n public ConvolutionalPositionalEmbedding(\n string name,\n long embed_dim,\n long kernel_size,\n long groups) : base(name)\n {\n this.embed_dim = embed_dim;\n // TODO: Replace when nn.utils.weight_norm() is supported.\n // https://github.com/dotnet/TorchSharp/issues/357\n // this.conv = nn.Conv1d(inputChannel: embed_dim, outputChannel: embed_dim, kernelSize: kernel_size, padding: kernel_size / 2, groups: groups);\n // this.conv = nn.utils.weight_norm(this.conv, name: \"weight\", dim: 2);\n this.conv = new WeightNormConv1d(\n \"WeightNormConv1d\",\n in_channels: embed_dim,\n out_channels: embed_dim,\n kernel_size: kernel_size,\n padding: kernel_size / 2,\n groups: groups);\n this.num_remove = kernel_size % 2 == 0 ? 1 : 0;\n RegisterComponents();\n }\n\n /// <param name=\"x\">shape ``[batch, frame, feature]``.</param>\n /// <returns>The resulting feature. Shape ``[batch, frame, feature]``.</returns>\n public override Tensor forward(Tensor x)\n {\n x = x.transpose(-2, -1);\n x = this.conv.call(x);\n if (this.num_remove > 0) {\n x = x[TensorIndex.Ellipsis, TensorIndex.Slice(null, -this.num_remove)];\n }\n x = torch.nn.functional.gelu(x);\n x = x.transpose(-2, -1);\n return x;\n }\n\n private class WeightNormConv1d : Module<Tensor, Tensor>\n {\n private readonly Parameter weight_g;\n private readonly Parameter weight_v;\n private readonly Parameter bias;\n private readonly long padding;\n private readonly long groups;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n weight_g.Dispose();\n weight_v.Dispose();\n bias.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public WeightNormConv1d(string name, long in_channels, long out_channels, long kernel_size, long padding, long groups) : base(name)\n {\n this.weight_g = Parameter(\n torch.empty(\n new long[] { 1, in_channels / groups, kernel_size },\n dtype: torch.float32));\n this.weight_v = Parameter(\n torch.empty(\n new long[] { out_channels, in_channels / groups, kernel_size },\n dtype: torch.float32));\n this.bias = Parameter(torch.empty(out_channels, dtype: torch.float32));\n this.padding = padding;\n this.groups = groups;\n this.RegisterComponents();\n this.reset_parameters();\n }\n\n public void reset_parameters()\n {\n var weight = torch.empty_like(this.weight_v);\n init.kaiming_uniform_(weight, Math.Sqrt(5));\n using (torch.no_grad()) {\n this.weight_g.set_(torch.sqrt(torch.square(weight).sum(dim: new long[] { 0, 1 }, keepdim: true)));\n this.weight_v.set_(weight / this.weight_g);\n }\n var fan_in = this.weight_v.size(1);\n var bound = 1.0 / Math.Sqrt(fan_in);\n init.uniform_(this.bias, -bound, bound);\n }\n\n public override Tensor forward(Tensor input)\n {\n var weight_v_norm = torch.linalg.norm(weight_v, dims: new long[] { 0, 1 }, keepdim: true);\n var weight = torch.mul(weight_v / weight_v_norm, weight_g);\n return nn.functional.conv1d(input, weight, bias, padding: this.padding, groups: this.groups);\n }\n }\n }\n\n /// <summary>\n /// Multihead Self Attention module\n /// </summary>\n private class SelfAttention : Module<Tensor, Tensor?, Tensor>\n {\n public readonly Module<Tensor, Tensor> dropout;\n public readonly long embed_dim;\n public readonly long head_dim;\n public readonly Module<Tensor, Tensor> k_proj;\n public readonly long num_heads;\n public readonly Module<Tensor, Tensor> out_proj;\n public readonly Module<Tensor, Tensor> q_proj;\n public readonly double scaling;\n public readonly Module<Tensor, Tensor> v_proj;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n dropout.Dispose();\n k_proj.Dispose();\n out_proj.Dispose();\n q_proj.Dispose();\n v_proj.Dispose();\n }\n base.Dispose(disposing);\n }\n\n /// <param name=\"name\"></param>\n /// <param name=\"embed_dim\">Total dimension of the model.</param>\n /// <param name=\"num_heads\">The number of heads.</param>\n /// <param name=\"dropout\">Dropout probabiliry on attn_output_weights. Default: ``0.0``</param>\n /// <exception cref=\"ArgumentException\"></exception>\n public SelfAttention(\n string name,\n long embed_dim,\n long num_heads,\n double dropout = 0.0) : base(name)\n {\n var head_dim = embed_dim / num_heads;\n if (head_dim * num_heads != embed_dim) {\n throw new ArgumentException($\"`embed_dim ({embed_dim})` is not divisible by `num_heads ({num_heads})`\");\n }\n this.embed_dim = embed_dim;\n this.num_heads = num_heads;\n this.dropout = torch.nn.Dropout(dropout);\n this.head_dim = head_dim;\n\n this.scaling = Math.Pow(this.head_dim, -0.5);\n\n this.k_proj = nn.Linear(embed_dim, embed_dim, hasBias: true);\n this.v_proj = nn.Linear(embed_dim, embed_dim, hasBias: true);\n this.q_proj = nn.Linear(embed_dim, embed_dim, hasBias: true);\n this.out_proj = nn.Linear(embed_dim, embed_dim, hasBias: true);\n RegisterComponents();\n }\n\n /// <param name=\"x\">shape: ``[batch_size, sequence_length, embed_dim]``.</param>\n /// <param name=\"attention_mask\">shape: ``[batch_size, 1, sequence_length, sequence_length]``</param>\n /// <returns>The resulting tensor. shape: ``[batch, sequence_length, embed_dim]``</returns>\n /// <exception cref=\"ArgumentException\"></exception>\n public override Tensor forward(Tensor x, Tensor? attention_mask)\n {\n if (x.ndim != 3 || x.shape[2] != this.embed_dim) {\n throw new ArgumentException(\"The expected input shape is (batch, sequence, embed_dim=={self.embed_dim}). Found {x.shape}.\");\n }\n var batch_size = x.size(0);\n var length = x.size(1);\n var embed_dim = x.size(2);\n if (attention_mask is not null) {\n var shape_ = new long[] { batch_size, 1, length, length };\n if (attention_mask.dim() != shape_.Length ||\n attention_mask.size(0) != shape_[0] ||\n attention_mask.size(1) != shape_[1] ||\n attention_mask.size(2) != shape_[2] ||\n attention_mask.size(3) != shape_[3]) {\n throw new ArgumentException($\"The expected attention mask shape is {shape_}. Found {attention_mask.size()}.\");\n }\n }\n\n var shape = new long[] { batch_size, length, this.num_heads, this.head_dim };\n var q = this.q_proj.call(x).view(shape).transpose(2, 1); // B, nH, L, Hd\n var k = this.k_proj.call(x).view(shape).permute(0, 2, 3, 1); // B, nH, Hd, L\n var v = this.v_proj.call(x).view(shape).transpose(2, 1); // B, nH, L, Hd\n\n var weights = this.scaling * torch.matmul(q, k); // B, nH, L, L\n if (attention_mask is not null) {\n weights += attention_mask;\n }\n\n weights = torch.nn.functional.softmax(weights, dim: -1);\n weights = this.dropout.call(weights);\n\n var output = torch.matmul(weights, v); // B, nH, L, Hd\n output = output.transpose(2, 1).reshape(batch_size, length, embed_dim);\n\n output = this.out_proj.call(output);\n return output;\n }\n\n public new Tensor call(Tensor x, Tensor? attention_mask = null)\n {\n return base.call(x, attention_mask);\n }\n }\n\n /// <summary>\n /// Layer that follows attention layer in encoder layer.\n /// </summary>\n private class FeedForward : Module<Tensor, Tensor>\n {\n public readonly Module<Tensor, Tensor> intermediate_dense;\n public readonly Module<Tensor, Tensor> intermediate_dropout;\n public readonly Module<Tensor, Tensor> output_dense;\n public readonly Module<Tensor, Tensor> output_dropout;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n intermediate_dense.Dispose();\n intermediate_dropout.Dispose();\n output_dense.Dispose();\n output_dropout.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public FeedForward(\n string name,\n long io_features,\n long intermediate_features,\n double intermediate_dropout,\n double output_dropout) : base(name)\n {\n this.intermediate_dense = nn.Linear(io_features, intermediate_features);\n this.intermediate_dropout = nn.Dropout(intermediate_dropout);\n this.output_dense = nn.Linear(intermediate_features, io_features);\n this.output_dropout = nn.Dropout(output_dropout);\n RegisterComponents();\n }\n\n /// <param name=\"x\">shape: `(batch, sequence_length, io_features)`</param>\n /// <returns>shape: `(batch, sequence_length, io_features)`</returns>\n public override Tensor forward(Tensor x)\n {\n x = this.intermediate_dense.call(x);\n x = torch.nn.functional.gelu(x);\n x = this.intermediate_dropout.call(x);\n\n x = this.output_dense.call(x);\n x = this.output_dropout.call(x);\n return x;\n }\n }\n\n /// <summary>\n /// A layer unit in encoder. Combines multihead self attention and feed forward.\n /// </summary>\n private class EncoderLayer : Module<Tensor, Tensor?, Tensor>\n {\n public readonly SelfAttention attention;\n public readonly Module<Tensor, Tensor> dropout;\n public readonly Module<Tensor, Tensor> feed_forward;\n public readonly Module<Tensor, Tensor> final_layer_norm;\n public readonly Module<Tensor, Tensor> layer_norm;\n public bool layer_norm_first;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n dropout.Dispose();\n feed_forward.Dispose();\n final_layer_norm.Dispose();\n layer_norm.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public EncoderLayer(\n string name,\n SelfAttention attention,\n double dropout,\n bool layer_norm_first,\n Module<Tensor, Tensor> feed_forward) : base(name)\n {\n this.attention = attention;\n this.dropout = nn.Dropout(dropout);\n this.layer_norm = nn.LayerNorm(new long[] { attention.embed_dim });\n this.layer_norm_first = layer_norm_first;\n this.feed_forward = feed_forward;\n this.final_layer_norm = nn.LayerNorm(new long[] { attention.embed_dim });\n RegisterComponents();\n }\n\n /// <param name=\"x\">shape: `(batch, sequence_length, embed_dim)`</param>\n /// <param name=\"attention_mask\">shape: `(batch, 1, sequence_length, sequence_length)`</param>\n /// <returns></returns>\n public override Tensor forward(\n Tensor x,\n Tensor? attention_mask = null)\n {\n var residual = x;\n\n if (this.layer_norm_first) {\n x = this.layer_norm.call(x);\n }\n\n x = this.attention.call(x, attention_mask);\n x = this.dropout.call(x);\n x = residual + x;\n\n if (this.layer_norm_first) {\n x = x + this.feed_forward.call(this.final_layer_norm.call(x));\n } else {\n x = this.layer_norm.call(x);\n x = this.final_layer_norm.call(x + this.feed_forward.call(x));\n }\n return x;\n }\n }\n\n internal class Transformer : Module<Tensor, Tensor?, Tensor>\n {\n public readonly Module<Tensor, Tensor> dropout;\n public readonly double layer_drop;\n public readonly Module<Tensor, Tensor> layer_norm;\n public readonly bool layer_norm_first;\n public readonly ModuleList<Module<Tensor, Tensor?, Tensor>> layers;\n\n public ConvolutionalPositionalEmbedding pos_conv_embed;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n dropout.Dispose();\n layer_norm.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public Transformer(\n string name,\n ConvolutionalPositionalEmbedding pos_conv_embed,\n double dropout,\n ModuleList<Module<Tensor, Tensor?, Tensor>> layers,\n bool layer_norm_first,\n double layer_drop) : base(name)\n {\n this.pos_conv_embed = pos_conv_embed;\n this.layer_norm = nn.LayerNorm(new long[] { pos_conv_embed.embed_dim });\n this.layer_norm_first = layer_norm_first;\n this.layer_drop = layer_drop;\n this.dropout = nn.Dropout(dropout);\n this.layers = layers;\n RegisterComponents();\n }\n\n public Tensor _preprocess(Tensor x)\n {\n x = x + this.pos_conv_embed.call(x);\n\n if (this.layer_norm_first) {\n x = this.layer_norm.call(x);\n }\n\n x = this.dropout.call(x);\n return x;\n }\n\n public override Tensor forward(\n Tensor x,\n Tensor? attention_mask = null)\n {\n x = this._preprocess(x);\n foreach (var layer in this.layers) {\n if (!(this.training && torch.rand(1).item<float>() <= this.layer_drop)) {\n x = ((nn.Module<Tensor, Tensor?, Tensor>)layer).call(x, attention_mask);\n }\n }\n\n if (!this.layer_norm_first) {\n x = this.layer_norm.call(x);\n }\n\n return x;\n }\n\n public new Tensor call(Tensor x, Tensor? attention_mask = null) => base.call(x, attention_mask);\n\n public Tensor[] get_intermediate_outputs(\n Tensor x,\n Tensor? attention_mask = null,\n int? num_layers = null)\n {\n if (num_layers != null) {\n if (!(0 < num_layers && num_layers <= this.layers.Count)) {\n throw new ArgumentException($\"`num_layers` must be between [1, {this.layers.Count}]\");\n }\n }\n var ret = new List<Tensor>();\n x = this._preprocess(x);\n foreach (var layer in this.layers) {\n x = ((nn.Module<Tensor, Tensor?, Tensor>)layer).call(x, attention_mask);\n ret.Add(x);\n if (num_layers != null && ret.Count >= num_layers) {\n return ret.ToArray();\n }\n }\n return ret.ToArray();\n }\n }\n\n internal class Encoder : Module<Tensor, Tensor?, Tensor>\n {\n public readonly Module<Tensor, Tensor> feature_projection;\n public readonly Transformer transformer;\n\n public Encoder(\n string name,\n Module<Tensor, Tensor> feature_projection,\n Transformer transformer) : base(name)\n {\n this.feature_projection = feature_projection;\n this.transformer = transformer;\n RegisterComponents();\n }\n\n public (Tensor, Tensor?) _preprocess(\n Tensor features,\n Tensor? lengths = null)\n {\n var x = this.feature_projection.call(features);\n\n Tensor? mask = null;\n if (lengths is not null) {\n var batch_size = x.size(0);\n var max_len = x.size(1);\n // create mask for padded elements and zero-out them\n mask = torch.arange(max_len, device: lengths.device).expand(batch_size, max_len) >= lengths[TensorIndex.Colon, TensorIndex.None];\n x[mask] = 0.0;\n // extend the mask to attention shape and set weight\n mask = -10000.0 * mask[TensorIndex.Colon, TensorIndex.None, TensorIndex.None, TensorIndex.Colon].to(type: features.dtype);\n mask = mask.expand(batch_size, 1, max_len, max_len);\n }\n return (x, mask);\n }\n\n public override Tensor forward(\n Tensor features,\n Tensor? lengths = null)\n {\n var (x, mask) = this._preprocess(features, lengths);\n x = this.transformer.call(x, attention_mask: mask);\n return x;\n }\n\n public Tensor[] extract_features(\n Tensor features,\n Tensor? lengths = null,\n int? num_layers = null)\n {\n var (x, masks) = this._preprocess(features, lengths);\n return this.transformer.get_intermediate_outputs(x, attention_mask: masks, num_layers: num_layers);\n }\n }\n\n /// <summary>\n /// See Also:\n /// * Original implementation\n /// https:///github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L666-L733\n /// * \"extractor_mode\"\n /// - Def and base:\n /// https:///github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L38-L45\n /// - Large:\n /// https:///github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L52\n /// * \"conv_feature_layers\"\n /// - Def, base and large:\n /// https:///github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L94-L100\n /// * \"conv_bias\"\n /// - Def and base:\n /// https:///github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L101-L103\n /// - Large:\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L61\n /// If \"group_norm\", then a single normalization is applied\n /// </summary>\n /// <param name=\"norm_mode\">Either \"group_norm\" or \"layer_norm\".\n /// If \"group_norm\", then a single normalization is applied\n /// in the first convolution block. Otherwise, all the convolution\n /// blocks will have layer normalization.\n /// This option corresponds to \"extractor_mode\" from fairseq.\n /// Expected values are \"group_norm\" for Base arch, and\n /// \"layer_norm\" for Large arch.</param>\n /// <param name=\"shapes\">Configuration of convolution layers. List of convolution configuration,\n /// i.e. ``[(output_channel, kernel_size, stride), ...]``\n /// This option corresponds to \"conv_feature_layers\" from fairseq.\n /// Expected values are\n /// ``[(512, 10, 5)] + [(512, 3, 2)] * 4 + [(512, 2, 2)] * 2``\n /// for all the architectures.</param>\n /// <param name=\"bias\">Whether to include bias term to each convolution operation.\n /// This option corresponds to \"conv_bias\" from fairseq.\n /// Expected values are False for Base arch, and True for Large arch.</param>\n /// <returns></returns>\n /// <exception cref=\"ArgumentException\"></exception>\n internal static FeatureExtractor _get_feature_extractor(FeatureExtractorNormMode norm_mode, long[][] shapes, bool bias)\n {\n var blocks = ModuleList<Module<Tensor, Tensor?, (Tensor, Tensor?)>> ();\n long in_channels = 1;\n for (int i = 0; i < shapes.Length; i++) {\n var shape = shapes[i];\n var out_channels = shape[0];\n var kernel_size = shape[1];\n var stride = shape[2];\n Module<Tensor, Tensor>? normalization = null;\n if (norm_mode == FeatureExtractorNormMode.group_norm && i == 0) {\n normalization = nn.GroupNorm(\n num_groups: out_channels,\n num_channels: out_channels,\n affine: true);\n } else if (norm_mode == FeatureExtractorNormMode.layer_norm) {\n normalization = new Wav2Vec2Model.LayerNorm(\n \"LayerNorm\",\n normalized_shape: new long[] { out_channels },\n elementwise_affine: true);\n }\n blocks.Add(\n new ConvLayerBlock(\n \"ConvlayerBlock\",\n in_channels: in_channels,\n out_channels: out_channels,\n kernel_size: kernel_size,\n stride: stride,\n bias: bias,\n layer_norm: normalization));\n in_channels = out_channels;\n }\n return new FeatureExtractor(\"FeatureExtractor\", blocks);\n }\n\n /// <summary>\n /// See Also:\n /// * \"encoder_embed_dim\"\n /// - Def and base\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L49-L51\n /// - Large\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L64\n /// * \"dropout_input\"\n /// - Def, base and large\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L75-L78\n /// * \"conv_pos\"\n /// - Def, base and large\n /// NOTE: The description is wrong.\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L204-L207\n /// - Usage\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L756\n /// * \"conv_pos_groups\"\n /// - Def, base and large\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L208-L211\n /// * \"encoder_layers\"\n /// - Def and base\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L46-L48\n /// - Large\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L63\n /// * \"encoder_attention_heads\"\n /// - Def and base\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L55-L57\n /// - Large\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L66\n /// * \"attention_dropout\"\n /// - Def and base\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L66-L68\n /// - Large\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L60\n /// * \"encoder_ffn_embed_dim\"\n /// - Def and base\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L52-L54\n /// - Large\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L65\n /// * \"activation_dropout\"\n /// - Def\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L69-L71\n /// - Base\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/finetuning/base_960h.yaml#L55\n /// - Large\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/finetuning/vox_960h.yaml#L55\n /// * \"dropout\"\n /// - Def and base\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L63-L65\n /// - Large\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L59\n /// * \"layer_norm_first\"\n /// - Def and base\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L91-L93\n /// - Large\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/pretraining/wav2vec2_large_librivox.yaml#L53\n /// * \"layerdrop\"\n /// - Def\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L72-L74\n /// - Base\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/finetuning/base_960h.yaml#L54\n /// - Large\n /// https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/examples/wav2vec/config/finetuning/vox_960h.yaml#L54\n /// </summary>\n /// <param name=\"in_features\">in_features (int): The number of input features.</param>\n /// <param name=\"embed_dim\">The dimension of embedding.\n /// This option corresponds to \"encoder_embed_dim\" from fairseq.\n /// Expected values are 768 for Base arch, and 1024 for Large arch.</param>\n /// <param name=\"dropout_input\">The dropout probability applied after the input feature is projected\n /// to ``embed_dim``.\n /// This option corresponds to \"dropout_input\" from fairseq.\n /// Expected values are 0.1 for both Base and Large arch.</param>\n /// <param name=\"pos_conv_kernel\">The kernel size of convolutional positional embeddings.\n /// This option corresponds to \"conv_pos\" from fairseq.\n /// Expected values are 128 for both Base and Large arch.</param>\n /// <param name=\"pos_conv_groups\">The number of groups of convolutional positional embeddings.\n /// This option corresponds to \"conv_pos_groups\" from fairseq.\n /// Expected values are 16 for both Base and Large arch.</param>\n /// <param name=\"num_layers\">The number of self attention layers in transformer block.\n /// This option corresponds to \"encoder_layers\" from fairseq.\n /// Expected values are 12 for Base and 24 for Large arch.</param>\n /// <param name=\"num_heads\">The number of heads in self attention layers.\n /// This option corresponds to \"encoder_attention_heads\" from fairseq.\n /// Expected values are 12 for Base and 16 for Large arch.</param>\n /// <param name=\"attention_dropout\">The dropout probability applied after softmax in self-attention layer.\n /// This option corresponds to \"attention_dropout\" from fairseq.\n /// Expected values are 0.1 for Base and 0.0 for Large arch.</param>\n /// <param name=\"ff_interm_features\">The dimension of hidden features in feed forward layer.\n /// This option corresponds to \"encoder_ffn_embed_dim\" from fairseq.\n /// Expected values are 3072 for Base and 4096 for Large arch.</param>\n /// <param name=\"ff_interm_dropout\">The dropout probability applied in feedforward layer.\n /// This option correspinds to \"activation_dropout\" from fairseq.\n /// Expected values are 0.1 for both Base and Large arch.</param>\n /// <param name=\"dropout\">The dropout probability applied at the end of feed forward layer.\n /// This option corresponds to \"dropout\" from fairseq.\n /// Expected values are 0.1 for Base and 0.0 for Large arch.</param>\n /// <param name=\"layer_norm_first\">Control the order of layer norm in transformer layer and each encoder layer.\n /// If True, in transformer layer, layer norm is applied before features are fed\n /// to encoder layers. In encoder layer, two layer norms are applied before and after\n /// self attention.\n /// If False, in transformer layer, layer norm is applied after features are fed\n /// to encoder layers. In encoder layer, two layer norms are applied after self\n /// attention, before and after feed forward.\n /// This option corresponds to \"layer_norm_first\" from fairseq.\n /// Expected values are False for Base and True for Large arch.</param>\n /// <param name=\"layer_drop\">Probability to drop each encoder layer during training.\n /// This option corresponds to \"layerdrop\" from fairseq.\n /// Expected values are 0.1 for both Base and Large arch.</param>\n /// <returns></returns>\n internal static Encoder _get_encoder(\n long in_features,\n long embed_dim,\n double dropout_input,\n long pos_conv_kernel,\n long pos_conv_groups,\n long num_layers,\n long num_heads,\n double attention_dropout,\n long ff_interm_features,\n double ff_interm_dropout,\n double dropout,\n bool layer_norm_first,\n double layer_drop)\n {\n var feature_projection = new FeatureProjection(\"featureprojection\", in_features, embed_dim, dropout_input);\n var pos_conv = new ConvolutionalPositionalEmbedding(\"convolutionalpositionalembedding\", embed_dim, pos_conv_kernel, pos_conv_groups);\n\n // Original impl\n // https://github.com/pytorch/fairseq/blob/425c36eafff535fe7337f8bdd5ace22ebacc78cb/fairseq/models/wav2vec/wav2vec2.py#L768-L782\n var encoder_layers = ModuleList<Module<Tensor, Tensor?, Tensor>>();\n for (long i = 0; i < num_layers; i++) {\n var attention = new SelfAttention(\n \"SelfAttention\",\n embed_dim: embed_dim,\n num_heads: num_heads,\n dropout: attention_dropout);\n var feed_forward = new FeedForward(\n \"FeedForward\",\n io_features: embed_dim,\n intermediate_features: ff_interm_features,\n intermediate_dropout: ff_interm_dropout,\n output_dropout: dropout);\n encoder_layers.append(\n new EncoderLayer(\n \"EncoderLayer\",\n attention: attention,\n dropout: dropout,\n layer_norm_first: layer_norm_first,\n feed_forward: feed_forward));\n }\n var transformer = new Transformer(\n \"Transformer\",\n pos_conv_embed: pos_conv,\n dropout: dropout,\n layers: encoder_layers,\n layer_norm_first: !layer_norm_first,\n layer_drop: layer_drop);\n return new Encoder(\"Encoder\", feature_projection, transformer);\n }\n\n /// <summary>\n /// Computes random mask spans for a given shape.\n /// </summary>\n /// <param name=\"shape\">The shape for which to compute masks.\n /// The first element is batch size and second is the number of frames.</param>\n /// <param name=\"padding_mask\">The padding mask of the same dimension as shape,\n /// which will prevent masking padded elements.</param>\n /// <param name=\"mask_prob\">Probability for each token to be chosen as start of the span to be masked.\n /// This will be multiplied by number of timesteps divided by length of mask span to mask\n /// approximately this percentage of all elements. However due to overlaps, the actual number\n /// will be smaller (unless no_overlap is True).</param>\n /// <param name=\"mask_length\"></param>\n /// <param name=\"mask_type\">How to compute mask lengths. Options: [``static``, ``uniform``, ``normal``, ``poisson``].\n /// ``static``: Fixed size\n /// ``uniform``: Sample from uniform distribution [mask_other, mask_length*2]\n /// ``normal``: Sample from normal distribution with mean ``mask_length`` and stdev ``mask_other``.\n /// ``poisson``: Sample from possion distribution with lambda = ``mask_length``.</param>\n /// <param name=\"mask_other\"></param>\n /// <param name=\"min_masks\">Minimum number of masked spans.</param>\n /// <param name=\"no_overlap\">If false, will switch to an alternative recursive algorithm\n /// that prevents spans from overlapping.</param>\n /// <param name=\"min_space\">How many frames to keep unmasked between spans (Only used if no_overlap is true).</param>\n /// <returns>The mask indices of dimension `[batch, frame]`.</returns>\n /// <exception cref=\"Exception\"></exception>\n private static Tensor _compute_mask_indices(\n long[] shape,\n Tensor? padding_mask,\n double mask_prob,\n long mask_length,\n string mask_type = \"static\",\n double mask_other = 0.0,\n long min_masks = 0,\n bool no_overlap = false,\n long min_space = 0)\n {\n long min_len;\n var batch_size = shape[0];\n var frame = shape[1];\n var mask = torch.full(new long[] { batch_size, frame }, false);\n // add a random number for probabilistic rounding\n var all_num_mask = (long)(mask_prob * frame / mask_length + torch.rand(1));\n\n all_num_mask = Math.Max(min_masks, all_num_mask);\n\n var mask_idcs = new List<Tensor>();\n for (long i = 0; i < batch_size; i++) {\n Tensor mask_idc;\n Tensor lengths;\n long num_mask;\n long sz;\n\n if (padding_mask is not null) {\n sz = frame - padding_mask[i].@long().sum().item<long>();\n // add a random number for probabilistic rounding\n num_mask = (long)((mask_prob * sz / mask_length) + torch.rand(1));\n num_mask = Math.Max(min_masks, num_mask);\n } else {\n sz = frame;\n num_mask = all_num_mask;\n }\n\n if (mask_type == \"static\") {\n lengths = torch.full(new long[] { num_mask }, mask_length);\n } else if (mask_type == \"uniform\") {\n lengths = torch.randint((long)mask_other, mask_length * 2 + 1, size: new long[] { num_mask });\n } else if (mask_type == \"normal\") {\n lengths = torch.normal(mask_length, mask_other, size: new long[] { num_mask });\n lengths = torch.maximum(torch.ones(1), torch.round(lengths)).@int();\n } else if (mask_type == \"poisson\") {\n // torch.poisson() of PyTorch doesn't accept the argument `size'.\n throw new Exception($\"unsupported mask selection: {mask_type}\");\n // lengths = torch.poisson(mask_length, size: new long[] { num_mask });\n // lengths = torch.round(lengths).@int();\n } else {\n throw new Exception($\"unknown mask selection: {mask_type}\");\n }\n\n if (lengths.sum().item<int>() == 0) {\n lengths[0] = Math.Min(mask_length, sz - 1);\n }\n\n if (no_overlap) {\n var mask_idc_data = new List<long>();\n\n List<(long, long)> arrange(long s, long e, long length, long keep_length)\n {\n long span_start = torch.randint(s, e - length, dtype: torch.int64, size: new long[] { 1 }).item<long>();\n for (long i = 0; i < length; i++) {\n mask_idc_data.Add(span_start + i);\n }\n var new_parts = new List<(long, long)>();\n if (span_start - s - min_space >= keep_length) {\n new_parts.Add((s, span_start - min_space + 1));\n }\n if (e - span_start - keep_length - min_space > keep_length) {\n new_parts.Add((span_start + length + min_space, e));\n }\n return new_parts;\n }\n\n var parts = new List<(long, long)> { (0, sz) };\n var min_length = torch.min(lengths).item<long>();\n foreach (var length in lengths.data<long>().OrderByDescending(x => x)) {\n var lens = torch.tensor((\n from p in parts\n select p.Item2 - p.Item1).ToArray(), dtype: torch.int64);\n lens[lens < length + min_space] = 0;\n long l_sum = lens.sum().item<long>();\n if (l_sum == 0) {\n break;\n }\n var probs = lens / l_sum;\n var c = (int)torch.distributions.Categorical(probs).sample().item<long>();\n var (s, e) = parts[c];\n parts.RemoveAt(c);\n parts.AddRange(arrange(s, e, length, min_length));\n }\n mask_idc = torch.tensor(mask_idc_data.ToArray());\n } else {\n min_len = torch.min(lengths).item<long>();\n if (sz - min_len <= num_mask) {\n min_len = sz - num_mask - 1;\n }\n\n mask_idc = torch.multinomial(torch.ones(new long[] { sz - min_len }), num_samples: num_mask, replacement: false);\n\n mask_idc = torch.tensor((\n from j in Enumerable.Range(0, (int)mask_idc.size(0))\n from offset in Enumerable.Range(0, (int)lengths[j].item<long>())\n select (mask_idc[j].item<long>() + offset)).ToArray());\n }\n\n mask_idcs.Add(mask_idc[mask_idc < sz].unique().Item1);\n }\n\n min_len = (from m in mask_idcs select m.size(0)).Min();\n for (int i = 0; i < mask_idcs.Count; i++) {\n var mask_idc = mask_idcs[i];\n if (mask_idc.size(0) > min_len) {\n mask_idc = torch.index_select(\n mask_idc,\n 0,\n torch.multinomial(\n torch.ones(new long[] { mask_idc.shape[0] }),\n num_samples: min_len,\n replacement: false));\n }\n mask[i, mask_idc] = true;\n }\n\n return mask;\n }\n\n /// <summary>\n /// Generate the padding mask given the padded input and the lengths Tensors.\n /// </summary>\n /// <param name=\"input\">The padded Tensor of dimension `[batch, max_len, frequency]`.</param>\n /// <param name=\"lengths\">The lengths Tensor of dimension `[batch,]`.</param>\n /// <returns>The padding mask.</returns>\n internal static Tensor _get_padding_mask(Tensor input, Tensor lengths)\n {\n var batch_size = input.size(0);\n var max_len = input.size(1);\n var mask = torch.arange(max_len, device: lengths.device).expand(batch_size, max_len) >= lengths[TensorIndex.Colon, TensorIndex.None];\n return mask;\n }\n\n /// <summary>\n /// Generate the masks for masked prediction.\n /// </summary>\n internal class MaskGenerator : Module<Tensor, Tensor?, (Tensor, Tensor?)>\n {\n public readonly long mask_channel_length;\n public readonly long mask_channel_min_space;\n public readonly double mask_channel_other;\n public readonly double mask_channel_prob;\n public readonly string mask_channel_selection;\n public readonly Parameter mask_embedding;\n public readonly long mask_length;\n public readonly long mask_min_space;\n public readonly double mask_other;\n public readonly double mask_prob;\n public readonly string mask_selection;\n public readonly bool no_mask_channel_overlap;\n public readonly bool no_mask_overlap;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n mask_embedding.Dispose();\n }\n base.Dispose(disposing);\n }\n\n /// <param name=\"name\"></param>\n /// <param name=\"encoder_embed_dim\">The dimension of the transformer embedding output.</param>\n /// <param name=\"mask_prob\">Probability for each token to be chosen as start of the span to be masked.\n /// This will be multiplied by number of timesteps divided by length of mask span to mask\n /// approximately this percentage of all elements. However due to overlaps, the actual number\n /// will be smaller (unless no_overlap is True).</param>\n /// <param name=\"mask_selection\">How to choose the mask length.\n /// Options: [``static``, ``uniform``, ``normal``, ``poisson``].</param>\n /// <param name=\"mask_other\">Secondary mask argument (used for more complex distributions).</param>\n /// <param name=\"mask_length\">The lengths of the mask.</param>\n /// <param name=\"no_mask_overlap\">Whether to allow masks to overlap.</param>\n /// <param name=\"mask_min_space\">Minimum space between spans (if no overlap is enabled).</param>\n /// <param name=\"mask_channel_prob\">The probability of replacing a feature with 0.</param>\n /// <param name=\"mask_channel_selection\">How to choose the mask length for channel masking.\n /// Options: [``static``, ``uniform``, ``normal``, ``poisson``].</param>\n /// <param name=\"mask_channel_other\">Secondary mask argument for channel masking(used for more complex distributions).</param>\n /// <param name=\"mask_channel_length\">Minimum space between spans (if no overlap is enabled) for channel masking.</param>\n /// <param name=\"no_mask_channel_overlap\">Whether to allow channel masks to overlap.</param>\n /// <param name=\"mask_channel_min_space\">Minimum space between spans for channel masking(if no overlap is enabled).</param>\n public MaskGenerator(\n string name,\n long encoder_embed_dim,\n double mask_prob,\n string mask_selection,\n double mask_other,\n long mask_length,\n bool no_mask_overlap,\n long mask_min_space,\n double mask_channel_prob,\n string mask_channel_selection,\n double mask_channel_other,\n long mask_channel_length,\n bool no_mask_channel_overlap,\n long mask_channel_min_space) : base(name)\n {\n this.mask_prob = mask_prob;\n this.mask_selection = mask_selection;\n this.mask_other = mask_other;\n this.mask_length = mask_length;\n this.no_mask_overlap = no_mask_overlap;\n this.mask_min_space = mask_min_space;\n this.mask_channel_prob = mask_channel_prob;\n this.mask_channel_selection = mask_channel_selection;\n this.mask_channel_other = mask_channel_other;\n this.mask_channel_length = mask_channel_length;\n this.no_mask_channel_overlap = no_mask_channel_overlap;\n this.mask_channel_min_space = mask_channel_min_space;\n this.mask_embedding = Parameter(torch.empty(encoder_embed_dim, dtype: torch.float32));\n torch.nn.init.uniform_(this.mask_embedding);\n RegisterComponents();\n }\n\n /// <param name=\"x\">The encoded representations after feature extraction module.</param>\n /// <param name=\"padding_mask\">The padding mask of the same dimension as shape,\n /// which will prevent masking padded elements.</param>\n /// <returns>\n /// The feature representations after masking.\n /// The generated mask indices.\n /// </returns>\n public override (Tensor, Tensor?) forward(Tensor x, Tensor? padding_mask)\n {\n Tensor? mask_indices;\n var B = x.size(0);\n var T = x.size(1);\n var C = x.size(2);\n if (this.mask_prob > 0) {\n mask_indices = _compute_mask_indices(\n new long[] { B, T },\n padding_mask,\n this.mask_prob,\n this.mask_length,\n this.mask_selection,\n this.mask_other,\n min_masks: 2,\n no_overlap: this.no_mask_overlap,\n min_space: this.mask_min_space);\n mask_indices = mask_indices.to(x.device);\n x[mask_indices] = this.mask_embedding;\n } else {\n mask_indices = null;\n }\n\n if (this.mask_channel_prob > 0) {\n var mask_channel_indices = _compute_mask_indices(\n new long[] { B, C },\n null,\n this.mask_channel_prob,\n this.mask_channel_length,\n this.mask_channel_selection,\n this.mask_channel_other,\n no_overlap: this.no_mask_channel_overlap,\n min_space: this.mask_channel_min_space);\n mask_channel_indices = mask_channel_indices.to(x.device).unsqueeze(1).expand(-1, T, -1);\n x[mask_channel_indices] = 0;\n }\n\n return (x, mask_indices);\n }\n }\n\n /// <summary>\n /// Compute the logits of the embeddings.\n /// </summary>\n /// <param name=\"proj_x\">The projected masked representations of dimension `[batch, frame, final_dim]`.</param>\n /// <param name=\"target\">The target Tensor of dimension `[batch, frame, final_dim]`.</param>\n /// <param name=\"label_embeddings\">The trainable embeddings of target of dimension `[num_class, final_dim]`.</param>\n /// <returns>The logits of the inputs.</returns>\n private static Tensor _compute_logits(\n Tensor proj_x,\n Tensor target,\n Tensor label_embeddings)\n {\n var logit_temp = 0.1;\n var pos = torch.index_select(label_embeddings, 0, target.@long());\n var negs = label_embeddings.unsqueeze(1).expand(-1, proj_x.size(0), -1);\n var neg_is_pos = (pos == negs).all(-1);\n pos = pos.unsqueeze(0);\n var targets = torch.cat(new Tensor[] { pos, negs }, dim: 0);\n\n var logits = torch.nn.functional.cosine_similarity(proj_x.@float(), targets.@float(), dim: -1).type_as(proj_x);\n logits /= logit_temp;\n if (neg_is_pos.any().item<bool>()) {\n logits[1][neg_is_pos] = double.NegativeInfinity;\n }\n logits = logits.transpose(0, 1); // (num_x, num_cls+1)\n return logits;\n }\n\n /// <summary>\n /// Generate the logits of masked and unmasked inputs.\n /// </summary>\n internal class LogitGenerator : Module<Tensor, Tensor, Tensor, Tensor, (Tensor?, Tensor?)>\n {\n public readonly Module<Tensor, Tensor> final_proj;\n public readonly Tensor label_embeddings;\n public readonly bool skip_masked;\n public readonly bool skip_nomask;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n final_proj.Dispose();\n label_embeddings.Dispose();\n }\n base.Dispose(disposing);\n }\n\n /// <param name=\"name\"></param>\n /// <param name=\"encoder_embed_dim\">The dimension of the transformer embedding output.</param>\n /// <param name=\"num_classes\">The number of classes in the labels.</param>\n /// <param name=\"final_dim\">Project final representations and targets to `final_dim`.</param>\n /// <param name=\"skip_masked\">If true, skip computing losses over masked frames.</param>\n /// <param name=\"skip_nomask\">If true, skip computing losses over unmasked frames.</param>\n public LogitGenerator(\n string name,\n long encoder_embed_dim,\n long num_classes,\n long final_dim,\n bool skip_masked,\n bool skip_nomask) : base(name)\n {\n this.label_embeddings = Parameter(torch.empty(new long[] { num_classes, final_dim }, dtype: torch.float32));\n torch.nn.init.uniform_(this.label_embeddings);\n this.final_proj = torch.nn.Linear(encoder_embed_dim, final_dim);\n this.skip_masked = skip_masked;\n this.skip_nomask = skip_nomask;\n RegisterComponents();\n }\n\n /// <param name=\"x\">The feature representation of the last transformer layer.</param>\n /// <param name=\"label\"> The label Tensor of dimension `[batch, frame]`.</param>\n /// <param name=\"mask_m\">The masked indices of dimension `[batch, frame]`.</param>\n /// <param name=\"mask_u\">The unmasked indices of dimension `[batch, frame]`.</param>\n /// <returns>\n /// The logits of masked frames. Tensor of dimension `[masked_frame, final_dim]`.\n /// The logits of unmasked frames. Tensor of dimension `[unmasked_frame, final_dim]`.\n /// </returns>\n public override (Tensor?, Tensor?) forward(Tensor x, Tensor label, Tensor mask_m, Tensor mask_u)\n {\n Tensor? logit_u;\n Tensor? logit_m;\n var proj_x = this.final_proj.call(x);\n if (this.skip_masked) {\n logit_m = null;\n } else {\n var proj_x_m = proj_x[mask_m];\n var label_m = label[mask_m];\n logit_m = _compute_logits(proj_x_m, label_m, this.label_embeddings);\n }\n\n if (this.skip_nomask) {\n logit_u = null;\n } else {\n var proj_x_u = proj_x[mask_u];\n var label_u = label[mask_u];\n logit_u = _compute_logits(proj_x_u, label_u, this.label_embeddings);\n }\n return (logit_m, logit_u);\n }\n }\n\n#if true\n // TODO: https://github.com/dotnet/TorchSharp/issues/606\n internal static class GradMultiply\n {\n public static Tensor apply(Tensor x, double scale)\n {\n return x;\n }\n }\n#else\n internal class GradMultiply : torch.autograd.Function\n {\n private double scale;\n\n public static Tensor forward(GradMultiply ctx, Tensor x, double scale)\n {\n ctx.scale = scale;\n var res = x.@new(x);\n return res;\n }\n\n public static (Tensor, object?) backward(GradMultiply ctx, Tensor grad)\n {\n return (grad * ctx.scale, null);\n }\n }\n#endif\n }\n}" }, { "alpha_fraction": 0.6117035150527954, "alphanum_fraction": 0.6660597920417786, "avg_line_length": 21.10344886779785, "blob_id": "cc7561fb06511df8e8424892f4cf099489dd1554", "content_id": "57ef8430be0966ac83124c30dadc4fec66375eee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3845, "license_type": "permissive", "max_line_length": 129, "num_lines": 174, "path": "/test/TorchSharpTest/optim.py", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "# Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#\n# This file is used to regenerate the optimizer state_dict test files,\n# where PyTorch optimizer state is transferred to TorchSharp.\n#\n# Execute this from the command line in the $/tests/TorchSharpTest directory.\n\n\nimport torch\nimport shutil\n\nshutil.copy2('../../src/Python/exportsd.py', 'exportsd.py')\n\nimport exportsd\n\nlin1 = torch.nn.Linear(10,10)\nlin2 = torch.nn.Linear(10,10)\n\ninput = torch.rand(4,10)\n\n# SGD\n\noptim = torch.optim.SGD(lin1.parameters(), lr=0.001, momentum=0.1)\n\noutput = lin1(input).sum()\noutput.backward()\n\noptim.step()\n\nf = open(\"sgd1.dat\", \"wb\")\nexportsd.save_sgd(optim, f)\nf.close()\n\n# ASGD\n\noptim = torch.optim.ASGD(lin1.parameters(), lr=0.001, alpha=0.65, t0=1e5, lambd=1e-3)\n\noutput = lin1(input).sum()\noutput.backward()\n\noptim.step()\n\nf = open(\"asgd1.dat\", \"wb\")\nexportsd.save_asgd(optim, f)\nf.close()\n\n\n# RMSprop\n\nseq = torch.nn.Sequential(lin1, lin2)\n\n\noptim = torch.optim.RMSprop(lin1.parameters(), lr=0.001, momentum=0.1)\noptim.add_param_group({'params': lin2.parameters(), 'lr': 0.01, 'momentum' : 0, 'centered': True})\n\noutput = seq(input).sum()\noutput.backward()\n\noptim.step()\n\nf = open(\"rmsprop1.dat\", \"wb\")\nexportsd.save_rmsprop(optim, f)\nf.close()\n\n# Rprop\n\noptim = torch.optim.Rprop(lin1.parameters(), lr=0.001, etas=(0.35, 1.5), step_sizes=(1e-5, 5))\noptim.add_param_group({'params': lin2.parameters(), 'lr': 0.01, 'etas': (0.45, 1.5), 'step_sizes': (1e-5, 5), 'maximize': True})\n\noutput = seq(input).sum()\noutput.backward()\n\noptim.step()\n\nf = open(\"rprop1.dat\", \"wb\")\nexportsd.save_rprop(optim, f)\nf.close()\n\n# Adam\n\noptim = torch.optim.Adam(lin1.parameters(), lr=0.001, betas=(0.8, 0.9))\noptim.add_param_group({'params': lin2.parameters(), 'lr': 0.01, 'betas' : (0.7, 0.79), 'amsgrad': True})\n\noutput = seq(input).sum()\noutput.backward()\n\noptim.step()\n\nf = open(\"adam1.dat\", \"wb\")\nexportsd.save_adam(optim, f)\nf.close()\n\n# AdamW\n\noptim = torch.optim.AdamW(lin1.parameters(), lr=0.001, betas=(0.8, 0.9))\noptim.add_param_group({'params': lin2.parameters(), 'lr': 0.01, 'betas' : (0.7, 0.79), 'amsgrad': True})\n\noutput = seq(input).sum()\noutput.backward()\n\noptim.step()\n\nf = open(\"adamw1.dat\", \"wb\")\nexportsd.save_adamw(optim, f)\nf.close()\n\n# NAdam\n\noptim = torch.optim.NAdam(lin1.parameters(), lr=0.001, betas=(0.8, 0.9))\noptim.add_param_group({'params': lin2.parameters(), 'lr': 0.01, 'betas' : (0.7, 0.79), 'weight_decay': 0.3})\n\noutput = seq(input).sum()\noutput.backward()\n\noptim.step()\n\nf = open(\"nadam1.dat\", \"wb\")\nexportsd.save_nadam(optim, f)\nf.close()\n\n# RAdam\n\noptim = torch.optim.RAdam(lin1.parameters(), lr=0.001, betas=(0.8, 0.9))\noptim.add_param_group({'params': lin2.parameters(), 'lr': 0.01, 'betas' : (0.7, 0.79), 'weight_decay': 0.3})\n\noutput = seq(input).sum()\noutput.backward()\n\noptim.step()\n\nf = open(\"radam1.dat\", \"wb\")\nexportsd.save_radam(optim, f)\nf.close()\n\n# Adamax\n\noptim = torch.optim.Adamax(lin1.parameters(), lr=0.001, betas=(0.8, 0.9))\noptim.add_param_group({'params': lin2.parameters(), 'lr': 0.01, 'betas' : (0.7, 0.79), 'weight_decay' : 0.3})\n\noutput = seq(input).sum()\noutput.backward()\n\noptim.step()\n\nf = open(\"adamax1.dat\", \"wb\")\nexportsd.save_adamax(optim, f)\nf.close()\n\n# Adadelta\n\noptim = torch.optim.Adadelta(lin1.parameters(), lr=0.001, rho=0.85, weight_decay=0.3)\noptim.add_param_group({'params': lin2.parameters(), 'lr': 0.01, 'rho' : 0.79, 'maximize': True})\n\noutput = seq(input).sum()\noutput.backward()\n\noptim.step()\n\nf = open(\"adadelta1.dat\", \"wb\")\nexportsd.save_adadelta(optim, f)\nf.close()\n\n# Adagrad\n\noptim = torch.optim.Adagrad(lin1.parameters(), lr=0.001, lr_decay=0.85, weight_decay=0.3)\n\noutput = seq(input).sum()\noutput.backward()\n\noptim.step()\n\nf = open(\"adagrad1.dat\", \"wb\")\nexportsd.save_adagrad(optim, f)\nf.close()" }, { "alpha_fraction": 0.7681818008422852, "alphanum_fraction": 0.7863636612892151, "avg_line_length": 72.33333587646484, "blob_id": "d8a18130a01f5db76922392f758dd42fc0b5056c", "content_id": "6500791e3099af4c4e45047d05d70a671e80441f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 222, "license_type": "permissive", "max_line_length": 178, "num_lines": 3, "path": "/src/TorchSharp/GlobalSuppressions.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Style\", \"IDE1006:Naming Styles\", Justification = \"Solution uses Python naming conventions\", Scope = \"namespaceanddescendants\", Target = \"TorchSharp\")]\n" }, { "alpha_fraction": 0.7155542373657227, "alphanum_fraction": 0.7226277589797974, "avg_line_length": 42.28338623046875, "blob_id": "35b02df0b5dcd71af9f531394a7fc55f7061c1c5", "content_id": "9a098be990cd9ddfec55a656feed222c93ee1ecb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 13325, "license_type": "permissive", "max_line_length": 477, "num_lines": 307, "path": "/docfx/articles/memory.md", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "# Memory Management\n\nThree approaches are available for memory management. Technique 1 is the default and simplest way to program. It is the recommended starting point.\n\n- If having trouble with CPU memory you may have to resort to technique 2 or 3.\n\n- If having trouble with GPU memory you may have to resort to technique 2 or 3.\n\nIn both cases, you may want to experiment with using a smaller batch size -- temporary tensor values produced by computation on the training data is the main memory problem, and they are in most cases proportional to the batch size. A smaller batch size means more batches, which will take longer, but can often speed up training convergence.\n\nNote DiffSharp (which uses TorchSharp) relies on techniques 1.\n\n> Most of the examples included will use technique #1, doing frequent explicit calls to GC.Collect() in the training code -- if not after each batch in the training loop, at least after each epoch.\n\n## Technique 1. Automatic disposal via Garbage Collection\n\nIn this technique all tensors (CPU and GPU) are implicitly disposed via .NET finalizers. Just allocate new tensors to your heart's content, and let GC take care of them. It will only work for small models that do not require a lot of memory. If you do use this approach, you may want to place a call to `GC.Collect()` after each mini-batch of data. It is generally not sufficient to do it at the end of each epoch.\n\n👍 Simple\n\n👎 The .NET GC doesn't know about the memory pressure from CPU tensors, so failure may happen if large tensors can't be allocated\n\n👎 The .NET GC doesn't know about GPU resources.\n\n👎 Native operations that allocate temporaries, whether on CPU or GPU, may fail -- the GC scheme implemented by TorchSharp only works when the allocation is initiated by .NET code.\n\n\n## Technique 2. Explicit disposal via 'using var x = ...' (C#) or 'use x = ...' (F#)\n\nThis technique is more cumbersome, but will result in better performance and have a higher memory ceiling. For many non-trivial models, it is more or less required in order to train on a GPU.\n\n👍 Specific lifetime management of all resources.\n\n👎 Cumbersome, requiring lots of using statements in your code.\n\n👎 You must know when to dispose.\n\n👎 Temporaries are not covered by this approach, so to maximize the benefit, you may have to store all temporaries to variables and dispose.\n\n__Note__: Even with this approach, it is a good idea to place a call to `GC.Collect()` after each mini-batch of data. There may be temporaries that were overlooked, or inconvenient to pull out, or ones where the lifetime was unclear; calling `GC.Collect()` will catch them.\n\n\n### Returning Fresh References\n\nIt is important to understand that all TorchSharp \"tensors\" (type Tensor) are actually \"tensor aliases\", referring to a C++ tensor. When a C++ tensor is created and returned to .NET as a tensor alias, and the reference count on the C++ tensor is incremented. When you call `Dispose()` on the TorchSharp tensor alias (that is, type Tensor), it is decremented. If the tensor alias is finalized instead, the decrement happens implicitly.\n\nTo enable this technique, all operations that return one or more TorchSharp `Tensor`s should return \"fresh\" Tensor aliases (though that doesn't always mean freshly copied C++ tensors). This is true even for in-place, destructive operations like `add_()`, which overwrites the underlying native tensor with data, but still returns a fresh tensor alias to that same tensor. \n\nThus, when you write methods and functions that take and produce type Tensor, for example in the `forward()` method of a model, you should always make sure to return a fresh alias. Most of the time, this happens automatically, because the last action of your code will normally be to call another tensor function, which itself will be returning a fresh alias, but there are cases when it's not, especially when returning input tensors or tensors stored in some lookaside table.\n\nFor example, consider a function that returns its input if its one-dimensional, otherwise it returns a reshaped version:\n\n```C#\nTensor flatten(Tensor input) {\n if (input.shape.Length == 1)\n return input.alias();\n else\n return input.reshape(input.numel()); \n}\n```\n\nThe `alias()` function avoids doing a clone of the tensor, but still returns a fresh tensor. I you simply return `input`, the caller won't know whether both input and output should be disposed, so the protocol is to always return a fresh tensor.\n\n### Disposing Tensor\n\nIn order to manage native storage, in particular GPU storage, it is necessary to do some explicit memory management for all temporaries, especially ones that are involved in a model's computation chain.\n\nHere are the simple guidance rules:\n\n1. Create a variable for each computed Tensor.\n\n2. Use the `using` (C#) or `use` (F#) syntax to declare the variable.\n\n3. Don't call Dispose on the input of a function. Let the caller handle its lifetime.\n\nFor example, consider this expression from the 'TextClassification' example:\n\n```C#\ntotal_acc += (predicted_labels.argmax(1) == labels).sum().to(torch.CPU).item<long>();\n```\n\nThere are lots of hidden temporaries in this relatively innocuous expression. In this particular case, it's involved in figuring out whether a prediction was accurate or not, so it's not going to be super-impactful on memory (the tensors are small), but it's still illustrative. A version where all temporaries are pulled out looks like this:\n\n```C#\nusing var am = predicted_labels.argmax(1);\nusing var eq = am == labels;\nusing var sum = eq.sum();\nusing var moved = sum.to(torch.CPU);\n\ntotal_acc += moved.item<long>();\n```\n\nThe most essential places to do explicit memory management is in any function that might be involved with data preparation or the model computation, since the tensors are big and repeatedly used.\n\nSome additional examples, in F# this time:\n\n```fsharp\n\nlet myTensorFunction0(input: Tensor) =\n input.alias()\n\nlet myTensorFunction1() =\n if today then \n table[4].alias() \n else\n table[5].alias() \n\nlet myTensorFunction2(input: Tensor) =\n input.add(tensor(1))\n\nlet myTensorFunction3(input: Tensor) =\n use tmp = input.add(tensor(1))\n tmp.add(tensor(1))\n\nlet myTensorFunction4(input: Tensor) =\n use tmp1 = input.add(tensor(1))\n use tmp2 = input.add(tensor(1))\n tmp2.add(tensor(1))\n\nlet myTensorFunction5(go: bool, input: Tensor) =\n if go then\n use tmp1 = input.add(tensor(1))\n use tmp2 = input.add(tensor(1))\n tmp2.add(tensor(1))\n else\n input.alias()\n \nlet myTensorFunction5(go: bool, input: Tensor) =\n if go then \n use tmp1 = input.add_(tensor(1)) // NOTE: even for in-place mutations\n use tmp2 = input.add_(tensor(1)) // NOTE: even for in-place mutations\n tmp2.add(tensor(1))\n else\n input.alias()\n```\n\n### Use 'Sequential' when possible.\n\nRather than passing tensor arguments between neural network layers inside a custom module's `forward()`, you should rely on the 'Sequential' layer collection, which will be efficient at memory management.\n\nIt may not be ideal when first experimenting with a model and trying to debug it, but once you are done with that and move on to a full training data set, it is advisable.\n\n## Technique 3: torch.NewDisposeScope()\n\nThis approach, which was added in TorchSharp 0.95.4, makes it easier to dispose of tensors, without the non-determinism of technique 1, or the many temporaries of technique 2. It has most of the advantages of technique 2, and the code elegance of technique 1.\n\n👍 Specific lifetime management of all resources, but in groups.\n\n👍 Temporaries __are__ covered by this approach.\n\n👎 You don't have fine-grained control over when each tensor is reclaimed. All tensors created while a scope is in effect are disposed at once.\n\n👎 It's a new code pattern, not widely used with other libraries.\n\nLet's look at an example, similar to the earlier, technique 2 example:\n\n```C#\nusing (var d = torch.NewDisposeScope()) {\n\n total_acc += (predicted_labels.argmax(1) == labels).sum().cpu().item<long>();\n\n ...\n}\n```\n\nWhat happens here, is that all tensors that are created while `d` is alive will be disposed when `d` is disposed. This includes temporaries, so you don't have to do anything special to get them to be disposed. (There's a problem with this simplistic example, which will be discussed later.)\n\nIn F#, it would look like:\n\n```F#\nuse d = torch.NewDisposeScope()\n\ntotal_acc <- total_acc + (predicted_labels.argmax(1) == labels).sum().cpu().item<long>()\n```\n\nIf you need to dispose some tensors before the scope is disposed, you can use `DisposeEverything()`, or `DisposeEverythingBut(...)` if you want to exclude a few tensors from disposal. These can be useful when tensor lifetimes aren't cleanly nested in dynamic scopes. \n\n__NOTE: It is absolutely essential for the proper functioning of dynamic dispose scopes that the scope is created with a 'using' statemen (C#) or 'use' expression (F#).__\n\nIt's important to note that these scopes are dynamic -- if any functions are called, the tensors inside them are also registered and disposed, unless there's a nested scope within those functions.\n\nIt is advisable to place a dispose scope around your training and test code, and in any library code that can be called from contexts that do not have dispose scopes. \n\nThat said, you should use dispose scope very carefully: having _too few_ scope raises the pressure on native memory, which is particularly bad for GPUs. Having too _many_ scopes, managing too few temporaries, will add runtime overhead to computations. For example, it may be better to put a scope outside an inner loop that contains multiple computations than to place it inside the loop. There is no single best answer.\n\n\n### Passing Tensors Out of Scopes\n\nAny tensor that needs to survive the dynamic dispose scope must be either removed from management completely, or promoted to a nesting (outer) scope.\n\nFor example, if a tensor variable `tensor` is overwritten in a scope, there are two problems:\n\n1. The tensor held in `tensor` will be overwritten. Since it's not created within the scope, the scope will not dispose of it. A nesting scope must be added to managed the lifetime of all tensors kept in `tensor`:\n\n```C#\nusing (var d0 = torch.NewDisposeScope()) {\n\n var tensor = torch.zeros(...)\n\n for ( ... ) {\n ...\n using (var d1 = torch.NewDisposeScope()) {\n\n var x = ...;\n tensor += x.log();\n ...\n }\n }\n}\n```\n\n2. The new tensor that is placed in `tensor` will be disposed when the scope is exited. Since the static scope of `tensor` is not the same as the dynamic scope where it is created, there's a problem.\n\nThis is probably not what you intended, so the tensor needs to be either detached, or moved to an outer scope (if one exists).\n\nFor example:\n\n```C#\nusing (var d0 = torch.NewDisposeScope()) {\n\n var tensor = torch.zeros(...)\n\n for ( ... ) {\n ...\n using (var d1 = torch.NewDisposeScope()) {\n\n var x = ...;\n tensor = (tensor + x.log()).MoveToOuterDisposeScope();\n ...\n }\n }\n}\n```\n\nSometimes, less is more -- a simple solution is to have fewer nested scopes:\n\n```C#\nusing (var d0 = torch.NewDisposeScope()) {\n\n var tensor = torch.zeros(...)\n\n for ( ... ) {\n ...\n var x = ...;\n tensor += x.log();\n ...\n }\n}\n```\n\nbut sometimes, you still have to move the tensor out, for example when you return a tensor from a method:\n\n```C#\npublic Tensor foo() {\n using (var d0 = torch.NewDisposeScope()) {\n\n var tensor = torch.zeros(...)\n\n foreach ( ... ) {\n ...\n var x = ...;\n tensor += x.log();\n ...\n }\n\n return tensor.MoveToOuterDisposeScope();\n }\n}\n```\n\nThese examples show how to move a tensor up one level in the stack of scopes. To completely remove a tensor from scoped management, use `DetatchFromDisposeScope()` instead of `MoveToOuterDisposeScope()`.\n\nEven with this technique, it is a good practice to use `Sequential` when possible.\n<br/>\n\n### torch.WrappedTensorDisposeScope\n\nA conveniece method was added in 0.97.3 -- it is useful for wrapping a complex expression with multiple temporaries without having to set up a scope explicitly.\n\nIt is defined as:\n\n```C#\npublic static Tensor WrappedTensorDisposeScope(Func<Tensor> expr)\n{\n using var scope = torch.NewDisposeScope();\n var result = expr();\n return result.MoveToOuterDisposeScope();\n}\n```\n\nThis is particularly useful in one-line functions and properties, such as in this example from the the Pareto distribution class:\n\n```C#\npublic override Tensor entropy() => torch.WrappedTensorDisposeScope(() => ((scale / alpha).log() + (1 + alpha.reciprocal())));\n\n```\n\n\n## Links and resources\n\nThese articles might give you ides about techniques to use to analyse memory. The code is in python but generally will translate across:\n\n* https://gitmemory.com/issue/pytorch/pytorch/31252/565550016\n\n* https://discuss.pytorch.org/t/how-to-debug-causes-of-gpu-memory-leaks/6741\n\n* https://discuss.pytorch.org/t/i-run-out-of-memory-after-a-certain-amount-of-batches-when-training-a-resnet18/1911\n\n" }, { "alpha_fraction": 0.6080678701400757, "alphanum_fraction": 0.609610915184021, "avg_line_length": 54.32926940917969, "blob_id": "e166e8f8c404dccfb4a7cd146081a4ccdfa1e653", "content_id": "cc6dcf0222b4c7f35f7e8d60fb40fed18a17b287", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9075, "license_type": "permissive", "max_line_length": 269, "num_lines": 164, "path": "/src/TorchSharp/Tensor/torch.SpectralOps.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\n\nusing System;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n // https://pytorch.org/docs/stable/torch#spectral-ops\n public static partial class torch\n {\n // https://pytorch.org/docs/stable/generated/torch.stft\n /// <summary>\n /// Returns a tensor containing the result of Short-time Fourier transform (STFT).\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"n_fft\">The size of Fourier transform</param>\n /// <param name=\"hop_length\">The hop length</param>\n /// <param name=\"win_length\">The window length</param>\n /// <param name=\"window\">The window function</param>\n /// <param name=\"center\">Whether the t-th frame is centered around t * hop_window, or not.</param>\n /// <param name=\"pad_mode\">The padding mode used when center is true.</param>\n /// <param name=\"normalized\">Whether the output is normalized, or not.</param>\n /// <param name=\"onesided\">Whether the output is onesided or not.</param>\n /// <param name=\"return_complex\">Whether a complex tensor is returned, or not.</param>\n /// <returns>A tensor containing the result of Short-time Fourier transform (STFT).</returns>\n public static Tensor stft(Tensor input, long n_fft, long hop_length = -1, long win_length = -1, Tensor? window = null, bool center = true, PaddingModes pad_mode = PaddingModes.Reflect, bool normalized = false, bool? onesided = null, bool? return_complex = null)\n => input.stft(n_fft, hop_length, win_length, window, center, pad_mode, normalized, onesided, return_complex);\n\n // https://pytorch.org/docs/stable/generated/torch.istft\n /// <summary>\n /// Returns a tensor containing the result of Inverse Short-time Fourier transform.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"n_fft\">The size of Fourier transform</param>\n /// <param name=\"hop_length\">The hop length</param>\n /// <param name=\"win_length\">The window length</param>\n /// <param name=\"window\">The window function</param>\n /// <param name=\"center\">Whether the t-th frame is centered around t * hop_window, or not.</param>\n /// <param name=\"normalized\">Whether the output is normalized, or not.</param>\n /// <param name=\"onesided\">Whether the output is onesided or not.</param>\n /// <param name=\"length\">The length of the output tensor.</param>\n /// <param name=\"return_complex\">Whether a complex tensor is returned, or not.</param>\n /// <returns>A tensor containing the result of Inverse Short-time Fourier transform</returns>\n public static Tensor istft(Tensor input, long n_fft, long hop_length = -1, long win_length = -1, Tensor? window = null, bool center = true, bool normalized = false, bool? onesided = null, long length = -1, bool return_complex = false)\n => input.istft(n_fft, hop_length, win_length, window, center, normalized, onesided, length, return_complex);\n\n // https://pytorch.org/docs/stable/generated/torch.bartlett_window\n /// <summary>\n /// Bartlett window function.\n /// </summary>\n public static Tensor bartlett_window(long len, bool periodic = true, ScalarType? dtype = null, Device? device = null, bool requires_grad = false)\n {\n device = InitializeDevice(device);\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n dtype = get_default_dtype();\n }\n if (!dtype.Value.IsFloatingPoint()) throw new ArgumentException(\"Only floating point types are supported.\");\n\n var handle = THSTensor_bartlett_window(len, periodic, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_bartlett_window(len, periodic, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(handle);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.blackman_window\n /// <summary>\n /// Blackman window function.\n /// </summary>\n public static Tensor blackman_window(long len, bool periodic = true, ScalarType? dtype = null, Device? device = null, bool requires_grad = false)\n {\n device = InitializeDevice(device);\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n dtype = get_default_dtype();\n }\n if (!dtype.Value.IsFloatingPoint()) throw new ArgumentException(\"Only floating point types are supported.\");\n\n var handle = THSTensor_blackman_window(len, periodic, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_blackman_window(len, periodic, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(handle);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.hamming_window\n\n /// <summary>\n /// Hamming window function.\n /// </summary>\n public static Tensor hamming_window(long len, bool periodic = true, float alpha = 0.54f, float beta = 0.46f, ScalarType? dtype = null, Device? device = null, bool requires_grad = false)\n {\n device = InitializeDevice(device);\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n dtype = get_default_dtype();\n }\n if (!dtype.Value.IsFloatingPoint()) throw new ArgumentException(\"Only floating point types are supported.\");\n\n var handle = THSTensor_hamming_window(len, periodic, alpha, beta, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_hamming_window(len, periodic, alpha, beta, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(handle);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.hann_window\n /// <summary>\n /// Hann window function.\n /// </summary>\n public static Tensor hann_window(long len, bool periodic = true, ScalarType? dtype = null, Device? device = null, bool requires_grad = false)\n {\n device = InitializeDevice(device);\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n dtype = get_default_dtype();\n }\n if (!dtype.Value.IsFloatingPoint()) throw new ArgumentException(\"Only floating point types are supported.\");\n\n var handle = THSTensor_hann_window(len, periodic, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_hann_window(len, periodic, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(handle);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.kaiser_window\n /// <summary>\n /// Computes the Kaiser window with window length window_length and shape parameter beta.\n /// </summary>\n public static Tensor kaiser_window(long len, bool periodic = true, float beta = 12.0f, ScalarType? dtype = null, Device? device = null, bool requires_grad = false)\n {\n device = InitializeDevice(device);\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n dtype = get_default_dtype();\n }\n if (!dtype.Value.IsFloatingPoint()) throw new ArgumentException(\"Only floating point types are supported.\");\n\n var handle = THSTensor_kaiser_window(len, periodic, beta, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_kaiser_window(len, periodic, beta, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(handle);\n }\n }\n}" }, { "alpha_fraction": 0.5896599888801575, "alphanum_fraction": 0.5929203629493713, "avg_line_length": 38.75925827026367, "blob_id": "29a41668d7b390a540937f7fa77d4b27757b8e24", "content_id": "b1568938c865170a111f7908180e744d23425752", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2147, "license_type": "permissive", "max_line_length": 130, "num_lines": 54, "path": "/src/TorchSharp/NN/Flatten.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a dropout module for 2d/3d convolutational layers.\n /// </summary>\n public sealed class Flatten : torch.nn.Module<Tensor, Tensor>\n {\n internal Flatten(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_Flatten_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Flattens a contiguous range of dims into a tensor. For use with Sequential.\n /// </summary>\n /// <param name=\"startDim\">First dim to flatten (default = 1).</param>\n /// <param name=\"endDim\">Last dim to flatten (default = -1).</param>\n /// <returns></returns>\n public static Flatten Flatten(long startDim = 1, long endDim = -1)\n {\n var handle = THSNN_Flatten_ctor(startDim, endDim, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Flatten(handle, boxedHandle);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5165091156959534, "alphanum_fraction": 0.5413853526115417, "avg_line_length": 54.17155838012695, "blob_id": "553112166e2dcd4df08b2fc824f7472fb9204057", "content_id": "8438e36c8cc9e5574f89b36a813188dd96c25e96", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 24441, "license_type": "permissive", "max_line_length": 164, "num_lines": 443, "path": "/src/TorchVision/models/VGG.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System.Collections.Generic;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class models\n {\n /// <summary>\n /// VGG-11 without batch-norm layers\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"dropout\">The dropout ratio.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.vgg11(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n /// as the skip list when loading.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.VGG vgg11(int num_classes = 1000, float dropout = 0.5f, string? weights_file = null, bool skipfc = true, Device? device = null)\n {\n return new Modules.VGG(\"VGG11\", num_classes, false, dropout, weights_file, skipfc, device);\n }\n\n /// <summary>\n /// VGG-11 with batch-norm layers\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"dropout\">The dropout ratio.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.vgg11_bn(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n /// as the skip list when loading.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.VGG vgg11_bn(int num_classes = 1000, float dropout = 0.5f, string? weights_file = null, bool skipfc = true, Device? device = null)\n {\n return new Modules.VGG(\"VGG11\", num_classes, true, dropout, weights_file, skipfc, device);\n }\n\n /// <summary>\n /// VGG-13 without batch-norm layers\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"dropout\">The dropout ratio.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.vgg13(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n /// as the skip list when loading.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.VGG vgg13(int num_classes = 1000, float dropout = 0.5f, string? weights_file = null, bool skipfc = true, Device? device = null)\n {\n return new Modules.VGG(\"VGG13\", num_classes, false, dropout, weights_file, skipfc, device);\n }\n\n /// <summary>\n /// VGG-13 with batch-norm layers\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"dropout\">The dropout ratio.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.vgg13_bn(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n /// as the skip list when loading.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.VGG vgg13_bn(int num_classes = 1000, float dropout = 0.5f, string? weights_file = null, bool skipfc = true, Device? device = null)\n {\n return new Modules.VGG(\"VGG13\", num_classes, true, dropout, weights_file, skipfc, device);\n }\n\n /// <summary>\n /// VGG-16 without batch-norm layers\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"dropout\">The dropout ratio.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.vgg16(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n /// as the skip list when loading.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.VGG vgg16(int num_classes = 1000, float dropout = 0.5f, string? weights_file = null, bool skipfc = true, Device? device = null)\n {\n return new Modules.VGG(\"VGG16\", num_classes, false, dropout, weights_file, skipfc, device);\n }\n\n /// <summary>\n /// VGG-16 with batch-norm layers\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"dropout\">The dropout ratio.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.vgg16_bn(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n /// as the skip list when loading.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.VGG vgg16_bn(int num_classes = 1000, float dropout = 0.5f, string? weights_file = null, bool skipfc = true, Device? device = null)\n {\n return new Modules.VGG(\"VGG16\", num_classes, true, dropout, weights_file, skipfc, device);\n }\n\n /// <summary>\n /// VGG-19 without batch-norm layers\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"dropout\">The dropout ratio.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.vgg19(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n /// as the skip list when loading.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.VGG vgg19(int num_classes = 1000, float dropout = 0.5f, string? weights_file = null, bool skipfc = true, Device? device = null)\n {\n return new Modules.VGG(\"VGG19\", num_classes, false, dropout, weights_file, skipfc, device);\n }\n\n /// <summary>\n /// VGG-19 with batch-norm layers\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"dropout\">The dropout ratio.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.vgg19_bn(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n /// as the skip list when loading.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.VGG vgg19_bn(int num_classes = 1000, float dropout = 0.5f, string? weights_file = null, bool skipfc = true, Device? device = null)\n {\n return new Modules.VGG(\"VGG19\", num_classes, true, dropout, weights_file, skipfc, device);\n }\n }\n }\n\n namespace Modules\n {\n public class VGG : Module<Tensor, Tensor>\n {\n // The code here is based on\n // https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py\n // Licence and copypright notice at: https://github.com/pytorch/vision/blob/main/LICENSE\n\n private readonly Dictionary<string, long[]> _channels = new Dictionary<string, long[]>() {\n { \"VGG11\", new long[] { 64, 0, 128, 0, 256, 256, 0, 512, 512, 0, 512, 512, 0 } },\n { \"VGG13\", new long[] { 64, 64, 0, 128, 128, 0, 256, 256, 0, 512, 512, 0, 512, 512, 0 } },\n { \"VGG16\", new long[] { 64, 64, 0, 128, 128, 0, 256, 256, 256, 0, 512, 512, 512, 0, 512, 512, 512, 0 } },\n { \"VGG19\", new long[] { 64, 64, 0, 128, 128, 0, 256, 256, 256, 256, 0, 512, 512, 512, 512, 0, 512, 512, 512, 512, 0 } }\n };\n\n private readonly Module<Tensor, Tensor> features;\n private readonly Module<Tensor, Tensor> avgpool;\n private readonly Module<Tensor, Tensor> classifier;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n features.Dispose();\n avgpool.Dispose();\n classifier.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public VGG(string name,\n int numClasses,\n bool batch_norm,\n float dropout = 0.5f,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null) : base(name)\n {\n var layers = new List<Module<Tensor, Tensor>>();\n\n var channels = _channels[name];\n\n long in_channels = 3;\n\n for (var i = 0; i < channels.Length; i++) {\n\n if (channels[i] == 0) {\n layers.Add(MaxPool2d(kernelSize: 2, stride: 2));\n } else {\n layers.Add(Conv2d(in_channels, channels[i], kernelSize: 3, padding: 1));\n if (batch_norm) {\n layers.Add(BatchNorm2d(channels[i]));\n }\n layers.Add(ReLU(inplace: true));\n in_channels = channels[i];\n }\n }\n\n features = Sequential(layers);\n\n avgpool = AdaptiveAvgPool2d(new[] { 7L, 7L });\n\n classifier = Sequential(\n Linear(512 * 7 * 7, 4096),\n ReLU(true),\n Dropout(p: dropout),\n Linear(4096, 4096),\n ReLU(true),\n Dropout(p: dropout),\n Linear(4096, numClasses)\n );\n\n RegisterComponents();\n\n if (string.IsNullOrEmpty(weights_file)) {\n\n foreach (var (_, m) in named_modules()) {\n switch (m) {\n // This test must come before the Tensor test\n case TorchSharp.Modules.Conv2d conv:\n torch.nn.init.kaiming_normal_(conv.weight, mode: init.FanInOut.FanOut, nonlinearity: init.NonlinearityType.ReLU);\n if (conv.bias is not null && !conv.bias.IsInvalid) {\n torch.nn.init.constant_(conv.bias, 0);\n }\n break;\n case TorchSharp.Modules.BatchNorm2d bn:\n torch.nn.init.constant_(bn.weight, 1);\n torch.nn.init.constant_(bn.bias, 0);\n break;\n case TorchSharp.Modules.Linear ln:\n torch.nn.init.normal_(ln.weight, 0, 0.01);\n torch.nn.init.constant_(ln.bias, 0);\n break;\n }\n }\n } else {\n\n foreach (var (_, m) in named_modules()) {\n switch (m) {\n // This test must come before the Tensor test\n case TorchSharp.Modules.Linear ln:\n torch.nn.init.normal_(ln.weight, 0, 0.01);\n torch.nn.init.constant_(ln.bias, 0);\n break;\n }\n }\n\n this.load(weights_file, skip: skipfc ? new[] { \"classifier.6.weight\", \"classifier.6.bias\" } : null);\n }\n\n if (device != null && device.type == DeviceType.CUDA)\n this.to(device);\n }\n\n public override Tensor forward(Tensor input)\n {\n using (var _ = NewDisposeScope()) {\n input = features.call(input);\n input = avgpool.call(input).flatten(1);\n return classifier.call(input).MoveToOuterDisposeScope();\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.547451913356781, "alphanum_fraction": 0.5544705390930176, "avg_line_length": 32.783504486083984, "blob_id": "6595721bc86c2997112ce217b9845db0462d83f4", "content_id": "22f3b7787810dcd309a8e5f8651df967216c1476", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3277, "license_type": "permissive", "max_line_length": 130, "num_lines": 97, "path": "/src/TorchAudio/Transforms/InverseSpectrogram.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\nusing static TorchSharp.torchaudio;\n\n// A number of implementation details in this file have been translated from the Python version of torchaudio,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/audio/blob/bb77cbebb620a46fdc0dc7e6dae2253eef3f37e2/torchaudio/transforms/_transforms.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/audio/blob/main/LICENSE\n//\n\nnamespace TorchSharp.Transforms\n{\n public sealed class InverseSpectrogram : nn.Module<Tensor, Tensor>, nn.IModule<Tensor, long?, Tensor>, ITransform\n {\n private readonly long n_fft;\n private readonly long win_length;\n private readonly long hop_length;\n private readonly long pad;\n private readonly Tensor window;\n private readonly bool normalized;\n private readonly bool center;\n private readonly PaddingModes pad_mode;\n private readonly bool onesided;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n window.Dispose();\n }\n base.Dispose(disposing);\n }\n\n internal InverseSpectrogram(\n string name,\n long n_fft = 400,\n long? win_length = null,\n long? hop_length = null,\n long pad = 0,\n WindowFunction window_fn = null,\n Tensor window = null,\n bool normalized = false,\n bool center = true,\n PaddingModes pad_mode = PaddingModes.Reflect,\n bool onesided = true) : base(name)\n {\n this.n_fft = n_fft;\n if (win_length.HasValue) {\n this.win_length = win_length.Value;\n } else {\n this.win_length = n_fft;\n }\n if (hop_length.HasValue) {\n this.hop_length = hop_length.Value;\n } else {\n this.hop_length = this.win_length / 2;\n }\n this.pad = pad;\n if (window is not null) {\n this.window = window;\n } else if (window_fn != null) {\n this.window = window_fn(this.win_length);\n } else {\n this.window = torch.hann_window(this.win_length);\n }\n this.normalized = normalized;\n this.center = center;\n this.pad_mode = pad_mode;\n this.onesided = onesided;\n }\n\n public override Tensor forward(Tensor input)\n {\n return call(input, null);\n }\n\n public Tensor call(Tensor input, long? length = null)\n {\n return torchaudio.functional.inverse_spectrogram(\n spectrogram: input,\n length: length,\n pad: pad,\n window: window,\n n_fft: n_fft,\n hop_length: hop_length,\n win_length: win_length,\n normalized: normalized,\n center: center,\n pad_mode: pad_mode,\n onesided: onesided);\n }\n }\n}\n" }, { "alpha_fraction": 0.6636179089546204, "alphanum_fraction": 0.670223593711853, "avg_line_length": 28.81818199157715, "blob_id": "796079dae25df75cd8aed6e0bffbbbe2d0bcaea5", "content_id": "cdbf754f77235dd5cbac07721310b946ef084160", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1968, "license_type": "permissive", "max_line_length": 130, "num_lines": 66, "path": "/src/Native/LibTorchSharp/THSAutograd.cpp", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#include \"THSAutograd.h\"\n\n#include \"torch/torch.h\"\n\nbool THSAutograd_isGradEnabled()\n{\n bool result = torch::autograd::GradMode::is_enabled();\n return result;\n}\n\nvoid THSAutograd_setGrad(bool enabled)\n{\n torch::autograd::GradMode::set_enabled(enabled);\n}\n\nbool THSAutograd_isAnomalyEnabled()\n{\n bool result = torch::autograd::AnomalyMode::is_enabled();\n return result;\n}\n\nbool THSAutograd_shouldCheckNaN()\n{\n return torch::autograd::AnomalyMode::should_check_nan();\n}\n\nvoid THSAutograd_setAnomaly(bool enabled, bool check_nan)\n{\n torch::autograd::AnomalyMode::set_enabled(enabled, check_nan);\n}\n\nvoid THSAutograd_grad(\n Tensor* outputs, const int64_t oLength,\n Tensor* inputs, const int64_t iLength,\n Tensor* grad_outs, const int64_t gLength,\n bool retain_graph, bool create_graph, bool allow_unused,\n Tensor* (*allocator)(size_t length))\n{\n auto res = torch::autograd::grad(\n toTensors<at::Tensor>((torch::Tensor**)outputs, oLength),\n toTensors<at::Tensor>((torch::Tensor**)inputs, iLength),\n toTensors<at::Tensor>((torch::Tensor**)grad_outs, gLength),\n retain_graph, create_graph, allow_unused);\n\n const size_t sz = res.size();\n\n Tensor* result = allocator(sz);\n for (size_t i = 0; i < sz; i++)\n result[i] = ResultTensor(res[i]);\n}\n\nvoid THSAutograd_backward(\n Tensor* tensors, const int64_t tLength,\n Tensor* grad_tensors, const int64_t gtLength,\n bool retain_graph, bool create_graph,\n Tensor* inputs, const int64_t iLength)\n{\n CATCH(\n torch::autograd::backward(\n toTensors<at::Tensor>((torch::Tensor**)tensors, tLength),\n toTensors<at::Tensor>((torch::Tensor**)grad_tensors, gtLength),\n retain_graph, create_graph,\n toTensors<at::Tensor>((torch::Tensor**)inputs, iLength));\n );\n}\n" }, { "alpha_fraction": 0.5957894921302795, "alphanum_fraction": 0.6085965037345886, "avg_line_length": 45.721309661865234, "blob_id": "d386e7b82851400e625ed9b4c6d6ed646a6da182", "content_id": "7c6e121c8d5878ad1d0b32741069e278d9c47b44", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5700, "license_type": "permissive", "max_line_length": 130, "num_lines": 122, "path": "/src/TorchAudio/Modules/HuBERTPretrainModel.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchaudio,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/audio/blob/76fca37ac8941b72a509a6e58d623632efe04543/torchaudio/models/wav2vec2/model.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/audio/blob/main/LICENSE\n//\n\nusing System;\nusing System.IO;\n\nusing static TorchSharp.torch;\n\n#nullable enable\nnamespace TorchSharp.Modules\n{\n /// <summary>\n /// HuBERT pre-train model for training from scratch.\n /// \n /// Note:\n /// To build the model, please use one of the factory functions in\n /// `[hubert_pretrain_base, hubert_pretrain_large, hubert_pretrain_xlarge]`.\n /// </summary>\n public class HuBERTPretrainModel : nn.Module<Tensor, Tensor, Tensor?, (Tensor?, Tensor?, Tensor)>\n {\n private readonly Wav2Vec2Model wav2vec2;\n private readonly Wav2Vec2Model.MaskGenerator mask_generator;\n private readonly Wav2Vec2Model.LogitGenerator logit_generator;\n private readonly double? feature_grad_mult;\n\n /// <param name=\"name\"></param>\n /// <param name=\"wav2vec2\"></param>\n /// <param name=\"mask_generator\">Mask generator that generates the mask for masked prediction during the training.</param>\n /// <param name=\"logit_generator\">Logit generator that predicts the logits of the masked and unmasked inputs.</param>\n /// <param name=\"feature_grad_mult\">The factor to scale the convolutional feature extraction layer gradients by.\n /// If ``None``, the gradients of feature extraction layers are not affected.\n /// The scale factor will not affect the forward pass.</param>\n internal HuBERTPretrainModel(\n string name,\n Wav2Vec2Model wav2vec2,\n Wav2Vec2Model.MaskGenerator mask_generator,\n Wav2Vec2Model.LogitGenerator logit_generator,\n double? feature_grad_mult) : base(name)\n {\n this.wav2vec2 = wav2vec2;\n this.mask_generator = mask_generator;\n this.logit_generator = logit_generator;\n if (feature_grad_mult != null && !(0.0 < feature_grad_mult.Value && feature_grad_mult.Value < 1.0)) {\n throw new ArgumentException(\n $\"The value of `feature_grad_mult` must be ``null``or between (0, 1). Found {feature_grad_mult}\");\n }\n this.feature_grad_mult = feature_grad_mult;\n RegisterComponents();\n }\n\n /// <summary>\n /// Compute the sequence of probability distribution over labels.\n /// </summary>\n /// <param name=\"waveforms\">Audio tensor of dimension `[batch, frames]`.</param>\n /// <param name=\"labels\">Label for pre-training. A Tensor of dimension `[batch, frames]`.</param>\n /// <param name=\"audio_lengths\">Indicates the valid length of each audio in the batch.\n /// Shape: `[batch, ]`.\n /// When the ``waveforms`` contains audios with different durations,\n /// by providing ``lengths`` argument, the model will compute\n /// the corresponding valid output lengths and apply proper mask in\n /// transformer attention layer.\n /// If ``None``, it is assumed that all the audio in ``waveforms``\n /// have valid length. Default: ``None``.</param>\n /// <returns>\n /// The masked sequences of probability distribution (in logit).\n /// Shape: `(masked_frames, num labels)`.\n /// The unmasked sequence of probability distribution (in logit).\n /// Shape: `(unmasked_frames, num labels)`.\n /// Tensor\n /// The feature mean value for additional penalty loss.\n /// Shape: `(1,)`.\n /// </returns>\n public override (Tensor?, Tensor?, Tensor) forward(\n Tensor waveforms,\n Tensor labels,\n Tensor? audio_lengths = null)\n {\n Tensor mask_u;\n Tensor mask_m;\n Tensor? padding_mask;\n var (x, lengths) = this.wav2vec2.feature_extractor.call(waveforms, audio_lengths);\n if (this.feature_grad_mult != null && this.feature_grad_mult < 1.0) {\n x = Wav2Vec2Model.GradMultiply.apply(x, this.feature_grad_mult.Value);\n }\n var features_pen = x.@float().pow(2).mean();\n if (lengths is not null) {\n padding_mask = Wav2Vec2Model._get_padding_mask(x, lengths);\n } else {\n padding_mask = null;\n }\n Tensor? attention_mask;\n Tensor? mask;\n (x, attention_mask) = this.wav2vec2.encoder._preprocess(x, lengths);\n (x, mask) = this.mask_generator.call(x, padding_mask);\n if (mask is null) throw new InvalidDataException();\n x = this.wav2vec2.encoder.transformer.call(x, attention_mask: attention_mask);\n if (x.shape[1] != labels.shape[1]) {\n throw new ArgumentException(\"The length of label must match that of HuBERT model output\");\n }\n if (padding_mask is not null) {\n mask_m = torch.logical_and(~padding_mask, mask);\n mask_u = torch.logical_and(~padding_mask, ~mask_m);\n } else {\n mask_m = mask;\n mask_u = ~mask_m;\n }\n\n var (logit_m, logit_u) = this.logit_generator.call(x, labels, mask_m, mask_u);\n\n return (logit_m, logit_u, features_pen);\n }\n }\n}\n" }, { "alpha_fraction": 0.4402332305908203, "alphanum_fraction": 0.44081631302833557, "avg_line_length": 27.58333396911621, "blob_id": "7383742948b59e6c5e0d57a20b1c823f6d705dee", "content_id": "7aea914661c75f697c833ad23ca851a3bedd4169", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1715, "license_type": "permissive", "max_line_length": 130, "num_lines": 60, "path": "/src/Examples.Utils/TorchText.Data.Utils.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Text.RegularExpressions;\n\nnamespace TorchText.Data\n{\n public static partial class Utils\n {\n public static Func<string, IEnumerable<string>> get_tokenizer(string name)\n {\n if (name == \"basic_english\") return BasicEnglish;\n throw new NotImplementedException($\"The '{name}' text tokenizer is not implemented.\");\n }\n\n private static string[] _patterns = new string []{\n \"\\'\",\n \"\\\"\",\n \"\\\\.\",\n \"<br \\\\/>\",\n \",\",\n \"\\\\(\",\n \"\\\\)\",\n \"\\\\!\",\n \"\\\\?\",\n \"\\\\;\",\n \"\\\\:\",\n \"\\\\\\\\\",\n \"\\\\s+\",\n };\n private static string[] _replacements = new string[] {\n \" \\\\' \",\n \"\",\n \" . \",\n \" \",\n \" , \",\n \" ( \",\n \" ) \",\n \" ! \",\n \" ? \",\n \" \",\n \" \",\n \" \",\n \" \"\n };\n\n private static IEnumerable<string> BasicEnglish(string input)\n {\n if (_patterns.Length != _replacements.Length)\n throw new InvalidProgramException(\"internal error: patterns and replacements are not the same length\");\n\n input = input.Trim().ToLowerInvariant();\n\n for (var i = 0; i < _patterns.Length; ++i) {\n input = Regex.Replace(input, _patterns[i], _replacements[i]);\n }\n return input.Split(' ');\n }\n }\n}\n" }, { "alpha_fraction": 0.5373831987380981, "alphanum_fraction": 0.5373831987380981, "avg_line_length": 24.969696044921875, "blob_id": "669691ad9b79009d24fedf6e67fee84e5781ad94", "content_id": "acc0c7aad07b133735bb6d9591c3a7befad9f193", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 856, "license_type": "permissive", "max_line_length": 130, "num_lines": 33, "path": "/src/TorchVision/AutoContrast.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class AutoContrast : ITransform\n {\n internal AutoContrast()\n {\n }\n\n public Tensor call(Tensor input)\n {\n return transforms.functional.autocontrast(input);\n }\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Autocontrast the pixels of the given image\n /// </summary>\n /// <returns></returns>\n static public ITransform AutoContrast()\n {\n return new AutoContrast();\n }\n }\n }\n}" }, { "alpha_fraction": 0.5645561218261719, "alphanum_fraction": 0.5662819743156433, "avg_line_length": 46.0609130859375, "blob_id": "c5696468d92846d4e1465cca823e193540044f54", "content_id": "b65b5327065ef565f5fda16241d6cb8168c3d3b3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9271, "license_type": "permissive", "max_line_length": 166, "num_lines": 197, "path": "/src/TorchSharp/Distributions/ExpRelaxedCategorical.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n using static torch.distributions;\n\n namespace Modules\n {\n /// <summary>\n /// Creates a ExpRelaxedCategorical parameterized by `temperature`, and either `probs` or `logits` (but not both).\n /// Returns the log of a point in the simplex.\n /// </summary>\n public class ExpRelaxedCategorical : Distribution\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"temperature\">Relaxation temperature</param>\n /// <param name=\"probs\">the probability of sampling `1`</param>\n /// <param name=\"logits\">the log-odds of sampling `1`</param>\n /// <param name=\"generator\"></param>\n internal ExpRelaxedCategorical(Tensor temperature, Tensor probs = null, Tensor logits = null, torch.Generator generator = null) :\n base(generator)\n {\n this._categorical = Categorical(probs, logits, generator);\n this._probs = probs?.alias().DetachFromDisposeScope();\n this._logits = logits?.alias().DetachFromDisposeScope();\n this._temperature = temperature.alias().DetachFromDisposeScope();\n base._init(_categorical.batch_shape, _categorical.event_shape);\n }\n\n private Tensor _probs;\n private Tensor _logits;\n private Tensor _temperature;\n private Categorical _categorical;\n\n /// <summary>\n /// The probability of sampling 1\n /// </summary>\n public Tensor probs {\n get {\n return _categorical.probs;\n }\n }\n\n /// <summary>\n /// The log-odds of sampling 1\n /// </summary>\n public Tensor logits {\n get {\n return _categorical.logits;\n }\n }\n\n public Tensor temperature {\n get {\n return _temperature;\n }\n }\n\n public override Tensor mean => new Tensor(IntPtr.Zero);\n\n public override Tensor mode => base.mode;\n\n public override Tensor variance => new Tensor(IntPtr.Zero);\n\n public override Tensor stddev => base.stddev;\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n /// <returns></returns>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is ExpRelaxedCategorical))\n throw new ArgumentException(\"expand(): 'instance' must be a ExpRelaxedCategorical distribution\");\n\n var newDistribution = ((instance == null) ? new ExpRelaxedCategorical(temperature, _probs, _logits, generator) : instance) as ExpRelaxedCategorical;\n\n newDistribution.batch_shape = batch_shape;\n if (newDistribution == instance) {\n newDistribution._temperature = _temperature;\n newDistribution._categorical = _categorical.expand(batch_shape) as Categorical;\n }\n return newDistribution;\n }\n\n /// <summary>\n /// The shape of the input parameter.\n /// </summary>\n public long[] param_shape {\n get {\n return _categorical.param_shape;\n }\n }\n\n public override Tensor sample(params long[] sample_shape)\n {\n return rsample(sample_shape);\n }\n\n public override Tensor rsample(params long[] sample_shape)\n {\n using var _ = torch.NewDisposeScope();\n var shape = ExtendedShape(sample_shape);\n var uniforms = ClampProbs(torch.rand(shape, dtype: _logits.dtype, device: _logits.device));\n var gumbels = -((-(uniforms.log())).log());\n var scores = (_logits + gumbels) / _temperature;\n return (scores - scores.logsumexp(dim: -1, keepdim: true)).MoveToOuterDisposeScope();\n }\n\n public override Tensor log_prob(Tensor value)\n {\n using var _ = torch.NewDisposeScope();\n float K = _categorical.num_events;\n var logitsValue = broadcast_tensors(_logits, value);\n var logits = logitsValue[0];\n value = logitsValue[1];\n var log_scale = (torch.full_like(_temperature, K).lgamma() - _temperature.log().mul(-(K - 1)));\n var score = logits - value.mul(_temperature);\n score = (score - score.logsumexp(dim: -1, keepdim: true)).sum(-1);\n return (score + log_scale).MoveToOuterDisposeScope();\n }\n\n public override Tensor entropy()\n {\n throw new NotImplementedException();\n }\n }\n\n }\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a ExpRelaxedCategorical parameterized by `temperature`, and either `probs` or `logits` (but not both).\n /// Returns the log of a point in the simplex.\n /// </summary>\n /// <param name=\"temperature\">Relaxation temperature</param>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static ExpRelaxedCategorical ExpRelaxedCategorical(Tensor temperature, Tensor probs = null, Tensor logits = null, torch.Generator generator = null)\n {\n return new ExpRelaxedCategorical(temperature, probs, logits, generator);\n }\n\n /// <summary>\n /// Creates a ExpRelaxedCategorical parameterized by `temperature`, and either `probs` or `logits` (but not both).\n /// Returns the log of a point in the simplex.\n /// </summary>\n /// <param name=\"temperature\">Relaxation temperature</param>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static ExpRelaxedCategorical ExpRelaxedCategorical(Tensor temperature, float? probs, float? logits, torch.Generator generator = null)\n {\n if (probs.HasValue && !logits.HasValue)\n return new ExpRelaxedCategorical(temperature, torch.tensor(probs.Value), null, generator);\n else if (!probs.HasValue && logits.HasValue)\n return new ExpRelaxedCategorical(temperature, null, torch.tensor(logits.Value), generator);\n else\n throw new ArgumentException(\"One and only one of 'probs' and logits should be provided.\");\n }\n\n\n /// <summary>\n /// Creates a ExpRelaxedCategorical parameterized by `temperature`, and either `probs` or `logits` (but not both).\n /// Returns the log of a point in the simplex.\n /// </summary>\n /// <param name=\"temperature\">Relaxation temperature</param>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static ExpRelaxedCategorical ExpRelaxedCategorical(Tensor temperature, double? probs, double? logits, torch.Generator generator = null)\n {\n if (probs.HasValue && !logits.HasValue)\n return new ExpRelaxedCategorical(temperature, torch.tensor(probs.Value), null, generator);\n else if (!probs.HasValue && logits.HasValue)\n return new ExpRelaxedCategorical(temperature, null, torch.tensor(logits.Value), generator);\n else\n throw new ArgumentException(\"One and only one of 'probs' and 'logits' should be non-null\");\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.602291464805603, "alphanum_fraction": 0.6483959555625916, "avg_line_length": 52.48039245605469, "blob_id": "b74ed739802619c547cbc7ae7f5cb380579009db", "content_id": "81ea280a6b5d60bd68977faa810e4130ff63029b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10910, "license_type": "permissive", "max_line_length": 199, "num_lines": 204, "path": "/src/Native/LibTorchSharp/THSFFT.cpp", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#include \"THSTensor.h\"\n\n#include <iostream>\n#include <fstream>\n\nTensor THSTensor_fft(const Tensor tensor, const int64_t n, const int64_t dim, int8_t norm)\n{\n auto nArg = (n == -1 ? c10::optional<int64_t>() : c10::optional<int64_t>(n));\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n CATCH_TENSOR(torch::fft::fft(*tensor, nArg, dim, normArg));\n}\n\nTensor THSTensor_ifft(const Tensor tensor, const int64_t n, const int64_t dim, int8_t norm)\n{\n auto nArg = (n == -1 ? c10::optional<int64_t>() : c10::optional<int64_t>(n));\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n CATCH_TENSOR(torch::fft::ifft(*tensor, nArg, dim, normArg));\n}\n\nTensor THSTensor_fft2(const Tensor tensor, const int64_t* s, const int64_t* dim, int8_t norm)\n{\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n auto sArg = (s == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(s, 2));\n auto dArg = (dim == nullptr) ? c10::IntArrayRef({-2, -1}) : c10::IntArrayRef(dim, 2);\n\n CATCH_TENSOR(torch::fft::fft2(*tensor, sArg, dArg, normArg));\n}\n\nTensor THSTensor_ifft2(const Tensor tensor, const int64_t* s, const int64_t* dim, int8_t norm)\n{\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n auto sArg = (s == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(s, 2));\n auto dArg = (dim == nullptr) ? c10::IntArrayRef({ -2, -1 }) : c10::IntArrayRef(dim, 2);\n\n CATCH_TENSOR(torch::fft::ifft2(*tensor, sArg, dArg, normArg));\n}\n\nTensor THSTensor_fftn(const Tensor tensor, const int64_t* s, const int s_length, const int64_t* dim, const int dim_length, int8_t norm)\n{\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n auto sArg = (s == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(s, s_length));\n auto dArg = (dim == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(dim, dim_length));\n\n CATCH_TENSOR(torch::fft::fftn(*tensor, sArg, dArg, normArg));\n}\n\nTensor THSTensor_ifftn(const Tensor tensor, const int64_t* s, const int s_length, const int64_t* dim, const int dim_length, int8_t norm)\n{\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n auto sArg = (s == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(s, s_length));\n auto dArg = (dim == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(dim, dim_length));\n\n CATCH_TENSOR(torch::fft::ifftn(*tensor, sArg, dArg, normArg));\n}\n\nTensor THSTensor_hfft(const Tensor tensor, const int64_t n, const int64_t dim, int8_t norm)\n{\n auto nArg = (n == -1 ? c10::optional<int64_t>() : c10::optional<int64_t>(n));\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n CATCH_TENSOR(torch::fft::hfft(*tensor, nArg, dim, normArg));\n}\n\nTensor THSTensor_hfft2(const Tensor tensor, const int64_t* s, const int64_t* dim, int8_t norm)\n{\n auto sArg = (s == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(s, 2));\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n auto dArg = (dim == nullptr) ? c10::IntArrayRef({ -2, -1 }) : c10::IntArrayRef(dim, 2);\n CATCH_TENSOR(torch::fft::hfft2(*tensor, sArg, dArg, normArg));\n}\n\nTensor THSTensor_hfftn(const Tensor tensor, const int64_t* s, const int s_length, const int64_t* dim, const int dim_length, int8_t norm)\n{\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n auto sArg = (s == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(s, s_length));\n c10::IntArrayRef dArg = (dim == nullptr) ? c10::IntArrayRef({-2, -1}) : c10::IntArrayRef(dim, dim_length);\n\n CATCH_TENSOR(torch::fft::hfftn(*tensor, sArg, dArg, normArg));\n}\n\nTensor THSTensor_ihfft(const Tensor tensor, const int64_t n, const int64_t dim, int8_t norm)\n{\n auto nArg = (n == -1 ? c10::optional<int64_t>() : c10::optional<int64_t>(n));\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n CATCH_TENSOR(torch::fft::ihfft(*tensor, nArg, dim, normArg));\n}\n\nTensor THSTensor_ihfft2(const Tensor tensor, const int64_t* s, const int64_t* dim, int8_t norm)\n{\n auto sArg = (s == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(s, 2));\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n auto dArg = (dim == nullptr) ? c10::IntArrayRef({ -2, -1 }) : c10::IntArrayRef(dim, 2);\n CATCH_TENSOR(torch::fft::ihfft2(*tensor, sArg, dArg, normArg));\n}\n\nTensor THSTensor_ihfftn(const Tensor tensor, const int64_t* s, const int s_length, const int64_t* dim, const int dim_length, int8_t norm)\n{\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n auto sArg = (s == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(s, s_length));\n c10::IntArrayRef dArg = (dim == nullptr) ? c10::IntArrayRef({ -2, -1 }) : c10::IntArrayRef(dim, dim_length);\n\n CATCH_TENSOR(torch::fft::ihfftn(*tensor, sArg, dArg, normArg));\n}\n\nTensor THSTensor_rfft(const Tensor tensor, const int64_t n, const int64_t dim, int8_t norm)\n{\n auto nArg = (n == -1 ? c10::optional<int64_t>() : c10::optional<int64_t>(n));\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n CATCH_TENSOR(torch::fft::rfft(*tensor, nArg, dim, normArg));\n}\n\nTensor THSTensor_irfft(const Tensor tensor, const int64_t n, const int64_t dim, int8_t norm)\n{\n auto nArg = (n == -1 ? c10::optional<int64_t>() : c10::optional<int64_t>(n));\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n CATCH_TENSOR(torch::fft::irfft(*tensor, nArg, dim, normArg));\n}\n\nTensor THSTensor_rfft2(const Tensor tensor, const int64_t* s, const int64_t* dim, int8_t norm)\n{\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n auto sArg = (s == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(s, 2));\n auto dArg = (dim == nullptr) ? c10::IntArrayRef({ -2, -1 }) : c10::IntArrayRef(dim, 2);\n\n CATCH_TENSOR(torch::fft::rfft2(*tensor, sArg, dArg, normArg));\n}\n\nTensor THSTensor_irfft2(const Tensor tensor, const int64_t* s, const int64_t* dim, int8_t norm)\n{\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n auto sArg = (s == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(s, 2));\n auto dArg = (dim == nullptr) ? c10::IntArrayRef({ -2, -1 }) : c10::IntArrayRef(dim, 2);\n\n CATCH_TENSOR(torch::fft::irfft2(*tensor, sArg, dArg, normArg));\n}\n\nTensor THSTensor_rfftn(const Tensor tensor, const int64_t* s, const int s_length, const int64_t* dim, const int dim_length, int8_t norm)\n{\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n auto sArg = (s == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(s, s_length));\n auto dArg = (dim == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(dim, dim_length));\n\n CATCH_TENSOR(torch::fft::rfftn(*tensor, sArg, dArg, normArg));\n}\n\nTensor THSTensor_irfftn(const Tensor tensor, const int64_t* s, const int s_length, const int64_t* dim, const int dim_length, int8_t norm)\n{\n auto normArg = (norm == 0) ? \"backward\" : (norm == 1) ? \"forward\" : \"ortho\";\n auto sArg = (s == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(s, s_length));\n auto dArg = (dim == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(dim, dim_length));\n\n CATCH_TENSOR(torch::fft::irfftn(*tensor, sArg, dArg, normArg));\n}\n\nTensor THSTensor_fftfreq(const int64_t n, const double d, const int8_t scalar_type, const int device_type, const int device_index, const bool requires_grad)\n{\n auto options = at::TensorOptions()\n .dtype(at::ScalarType(scalar_type))\n .device(c10::Device((c10::DeviceType)device_type, (c10::DeviceIndex)device_index))\n .requires_grad(requires_grad);\n\n CATCH_TENSOR(d == 0.0 ? torch::fft::fftfreq(n, options) : torch::fft::fftfreq(n, d, options));\n}\n\nTensor THSTensor_rfftfreq(const int64_t n, const double d, const int8_t scalar_type, const int device_type, const int device_index, const bool requires_grad)\n{\n auto options = at::TensorOptions()\n .dtype(at::ScalarType(scalar_type))\n .device(c10::Device((c10::DeviceType)device_type, (c10::DeviceIndex)device_index))\n .requires_grad(requires_grad);\n\n CATCH_TENSOR(d == 0.0 ? torch::fft::rfftfreq(n, options) : torch::fft::rfftfreq(n, d, options));\n}\n\nTensor THSTensor_fftshift(const Tensor tensor, const int64_t* dim, const int dim_length)\n{\n auto dArg = (dim == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(dim, dim_length));\n CATCH_TENSOR(torch::fft::fftshift(*tensor, dArg));\n}\n\nTensor THSTensor_ifftshift(const Tensor tensor, const int64_t* dim, const int dim_length)\n{\n auto dArg = (dim == nullptr) ? c10::nullopt : c10::optional<c10::IntArrayRef>(c10::IntArrayRef(dim, dim_length));\n CATCH_TENSOR(torch::fft::ifftshift(*tensor, dArg));\n}\n\nTensor THSTensor_stft(const Tensor x, int64_t n_fft, int64_t hop_length, int64_t win_length, const Tensor window, bool normalized, int64_t onesided, bool return_complex)\n{\n auto _hop_length = hop_length == -1 ? c10::optional<int64_t>() : c10::optional<int64_t>(hop_length);\n auto _win_length = win_length == -1 ? c10::optional<int64_t>() : c10::optional<int64_t>(win_length);\n auto _window = window == nullptr ? c10::optional<at::Tensor>() : *window;\n auto _onesided = (onesided == -1) ? c10::optional<bool>() : c10::optional<bool>((bool)onesided);\n CATCH_TENSOR(x->stft(n_fft, _hop_length, _win_length, _window, normalized, _onesided, return_complex));\n}\n\nTensor THSTensor_istft(const Tensor x, int64_t n_fft, int64_t hop_length, int64_t win_length, const Tensor window, bool center, bool normalized, int64_t onesided, int64_t length, bool return_complex)\n{\n auto _hop_length = hop_length == -1 ? c10::optional<int64_t>() : c10::optional<int64_t>(hop_length);\n auto _win_length = win_length == -1 ? c10::optional<int64_t>() : c10::optional<int64_t>(win_length);\n auto _window = window == nullptr ? c10::optional<at::Tensor>() : *window;\n auto _length = length == -1 ? c10::optional<int64_t>() : c10::optional<int64_t>(length);\n auto _onesided = (onesided == -1) ? c10::optional<bool>() : c10::optional<bool>((bool)onesided);\n CATCH_TENSOR(x->istft(n_fft, _hop_length, _win_length, _window, center, normalized, _onesided, _length, return_complex));\n}\n" }, { "alpha_fraction": 0.7039856910705566, "alphanum_fraction": 0.7039856910705566, "avg_line_length": 39.599998474121094, "blob_id": "1045f3329b8230c45e5f4936aa26ff3b0ddc8a5e", "content_id": "7da11e592d6ca8f9c5fec779197148b41af99306", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2233, "license_type": "permissive", "max_line_length": 130, "num_lines": 55, "path": "/src/TorchSharp/PInvoke/LibTorchSharp.THSInit.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp.PInvoke\n{\n internal static partial class NativeMethods\n {\n [DllImport(\"LibTorchSharp\")]\n internal static extern double THSInit_calculate_gain(long nonlinearity, double param);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSInit_constant_(IntPtr tensor, IntPtr value);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSInit_dirac_(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSInit_eye_(IntPtr matrix);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSInit_normal_(IntPtr tensor, double mean, double std);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSInit_trunc_normal_(IntPtr tensor, double mean, double std, double a, double b);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSInit_ones_(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSInit_orthogonal_(IntPtr tensor, double gain);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSInit_sparse_(IntPtr tensor, double sparsity, double std);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSInit_uniform_(IntPtr tensor, double low, double high);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSInit_kaiming_normal_(IntPtr tensor, double a, long mode, long nonlinearity);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSInit_kaiming_uniform_(IntPtr tensor, double a, long mode, long nonlinearity);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSInit_xavier_normal_(IntPtr tensor, double gain);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSInit_xavier_uniform_(IntPtr tensor, double gain);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSInit_zeros_(IntPtr tensor);\n }\n}\n" }, { "alpha_fraction": 0.554710328578949, "alphanum_fraction": 0.555295467376709, "avg_line_length": 36.173912048339844, "blob_id": "3ce4d056f7608640886c8e1afe99afd95a6e7647", "content_id": "c47b0b35fc3ca4628201b966d83f0c306bf21e66", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1713, "license_type": "permissive", "max_line_length": 130, "num_lines": 46, "path": "/src/TorchVision/Crop.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class Crop : ITransform\n {\n internal Crop(int top, int left, int height, int width)\n {\n this.top = top;\n this.left = left;\n this.height = height;\n this.width = width;\n }\n\n public Tensor call(Tensor input)\n {\n return input.crop(top, left, height, width);\n }\n\n private int top, left, height, width;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Crop an image at specified location and output size. The image is expected to have […, H, W] shape,\n /// where … means an arbitrary number of leading dimensions. If image size is smaller than output size along any edge,\n /// image is padded with 0 and then cropped.\n /// </summary>\n /// <param name=\"top\">Vertical component of the top left corner of the crop box.</param>\n /// <param name=\"left\">Horizontal component of the top left corner of the crop box.</param>\n /// <param name=\"height\">The height of the crop box.</param>\n /// <param name=\"width\">The width of the crop box.</param>\n /// <returns></returns>\n static public ITransform Crop(int top, int left, int height, int width)\n {\n return new Crop(top, left, height, width);\n }\n }\n }\n}" }, { "alpha_fraction": 0.6487455368041992, "alphanum_fraction": 0.6612903475761414, "avg_line_length": 31.823530197143555, "blob_id": "56ade3653a565ae0cda25064731e85b74b2fc77e", "content_id": "439644b2d3aecf5beb28cc37af4b9276ce2b7186", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 558, "license_type": "permissive", "max_line_length": 142, "num_lines": 17, "path": "/src/TorchSharp/Utils/StringEncoder.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System.Text;\n\nnamespace TorchSharp.Utils\n{\n internal static class StringEncoder\n {\n private static readonly Encoding s_utfEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false);\n\n internal static byte[] GetNullTerminatedUTF8ByteArray(string input)\n {\n var bytes = new byte[s_utfEncoding.GetMaxByteCount(input.Length)+1];\n var len = s_utfEncoding.GetBytes(input, 0, input.Length, bytes, 0);\n bytes[len] = 0;\n return bytes;\n }\n }\n}\n" }, { "alpha_fraction": 0.6319724917411804, "alphanum_fraction": 0.6337670087814331, "avg_line_length": 70.13829803466797, "blob_id": "68016c0a4035315d91b09dc574b1695ed80691b3", "content_id": "da1f0fbe9d5dd559f31a4bcab37212b0884c470e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6691, "license_type": "permissive", "max_line_length": 278, "num_lines": 94, "path": "/src/TorchSharp/NN/Embedding.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n public sealed class Embedding : torch.nn.Module<Tensor, Tensor>\n {\n internal Embedding(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n public override Tensor forward(Tensor input)\n {\n var res = THSNN_Embedding_forward(handle, input.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public Parameter? weight {\n get {\n var res = THSNN_Embedding_weight(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n set {\n THSNN_Embedding_set_weight(handle, value is null ? IntPtr.Zero : value.Handle);\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"weight\", value);\n }\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// A simple lookup table that stores embeddings of a fixed dictionary and size.\n /// This module is often used to store word embeddings and retrieve them using indices. The input to the module is a list of indices, and the output is the corresponding word embeddings.\n /// </summary>\n /// <param name=\"num_embeddings\">Size of the dictionary of embeddings, the vocabulary size.</param>\n /// <param name=\"embedding_dims\">The size of each embedding vector</param>\n /// <param name=\"padding_idx\">If given, pads the output with the embedding vector at padding_idx (initialized to zeros) whenever it encounters the index.</param>\n /// <param name=\"max_norm\">If given, each embedding vector with norm larger than max_norm is renormalized to have norm max_norm.</param>\n /// <param name=\"norm_type\">The p of the p-norm to compute for the max_norm option. Default 2.</param>\n /// <param name=\"scale_grad_by_freq\">If given, this will scale gradients by the inverse of frequency of the words in the mini-batch. Default: false.</param>\n /// <param name=\"sparse\">If true, gradient w.r.t. weight matrix will be a sparse tensor. Default: false</param>\n /// <param name=\"device\">The desired device of the parameters and buffers in this module</param>\n /// <param name=\"dtype\">The desired floating point or complex dtype of the parameters and buffers in this module</param>\n /// <returns></returns>\n /// <remarks>Keep in mind that only a limited number of optimizers support sparse gradients: currently it’s optim.SGD (CUDA and CPU), optim.SparseAdam (CUDA and CPU) and optim.Adagrad (CPU)</remarks>\n public static Embedding Embedding(long num_embeddings, long embedding_dims, long? padding_idx = null, double? max_norm = null, double norm_type = 2.0, bool scale_grad_by_freq = false, bool sparse = false, Device? device = null, ScalarType? dtype = null)\n {\n var res = THSNN_Embedding_ctor(num_embeddings, embedding_dims,\n padding_idx.HasValue ? padding_idx.Value : -1, padding_idx.HasValue,\n max_norm.HasValue ? max_norm.Value : 0.0, max_norm.HasValue,\n norm_type, scale_grad_by_freq, sparse, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Embedding(res, boxedHandle).MoveModule<Embedding>(device,dtype);\n }\n\n /// <summary>\n /// A simple lookup table that stores embeddings of a fixed dictionary and size.\n /// This module is often used to store word embeddings and retrieve them using indices. The input to the module is a list of indices, and the output is the corresponding word embeddings.\n /// </summary>\n /// <param name=\"embeddings\">FloatTensor containing weights for the Embedding in two dimensions. First dimension is being passed to Embedding as num_embeddings, second as embedding_dim.</param>\n /// <param name=\"freeze\">If true (the default), the tensor does not get updated in the learning</param>\n /// <param name=\"padding_idx\">If given, pads the output with the embedding vector at padding_idx (initialized to zeros) whenever it encounters the index.</param>\n /// <param name=\"max_norm\">If given, each embedding vector with norm larger than max_norm is renormalized to have norm max_norm.</param>\n /// <param name=\"norm_type\">The p of the p-norm to compute for the max_norm option. Default 2.</param>\n /// <param name=\"scale_grad_by_freq\">If given, this will scale gradients by the inverse of frequency of the words in the mini-batch. Default: false.</param>\n /// <param name=\"sparse\">If true, gradient w.r.t. weight matrix will be a sparse tensor. Default: false</param>\n /// <param name=\"device\">The desired device of the parameters and buffers in this module</param>\n /// <param name=\"dtype\">The desired floating point or complex dtype of the parameters and buffers in this module</param>\n /// <returns></returns>\n /// <remarks>Keep in mind that only a limited number of optimizers support sparse gradients: currently it’s optim.SGD (CUDA and CPU), optim.SparseAdam (CUDA and CPU) and optim.Adagrad (CPU)</remarks>\n public static Embedding Embedding_from_pretrained(Tensor embeddings, bool freeze = true, long? padding_idx = null, double? max_norm = null, double norm_type = 2.0, bool scale_grad_by_freq = false, bool sparse = false, Device? device = null, ScalarType? dtype = null)\n {\n var res = THSNN_Embedding_from_pretrained(embeddings.Handle, freeze,\n padding_idx.HasValue ? padding_idx.Value : -1, padding_idx.HasValue,\n max_norm.HasValue ? max_norm.Value : 0.0, max_norm.HasValue,\n norm_type, scale_grad_by_freq, sparse, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Embedding(res, boxedHandle).MoveModule<Embedding>(device, dtype);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6640316247940063, "alphanum_fraction": 0.6719367504119873, "avg_line_length": 24.399999618530273, "blob_id": "04276fdee0b36ce05fce7204bd9d1a61119d31f4", "content_id": "be870ca426990dfd73094f126f864fda17c29dd6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 255, "license_type": "permissive", "max_line_length": 131, "num_lines": 10, "path": "/src/TorchSharp/Tensor/Enums/Float32MatmulPrecision.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nnamespace TorchSharp\n{\n public enum Float32MatmulPrecision\n {\n highest,\n high,\n medium\n }\n}" }, { "alpha_fraction": 0.5307591557502747, "alphanum_fraction": 0.5314136147499084, "avg_line_length": 28.97058868408203, "blob_id": "560a98336d4759021059ba0bfd441f1060bfb4c3", "content_id": "a266a128e706ee0419ef69201b94b1d21f0c7f04", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3056, "license_type": "permissive", "max_line_length": 130, "num_lines": 102, "path": "/src/TorchSharp/Utils/IndexedPinnedArrays.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp\n{\n /// <summary>\n /// Allocator of T[] that pins the memory and handles unpinning.\n /// Modified version of PinnedArray, this class allows multiple arrays to be handled\n /// and unpinned together. Each array is identified by an integer index.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n internal sealed class IndexedPinnedArrays<T> : IDisposable where T : struct\n {\n private List<GCHandle> handles = new List<GCHandle>();\n private List<T[]> arrays = new List<T[]>();\n\n public int Count {\n get { return arrays.Count; }\n }\n\n public T[] this[int idx] {\n get {\n return arrays[idx];\n }\n set {\n ExtendHandlesList(idx);\n arrays[idx] = value;\n }\n }\n\n public IntPtr CreateArray(int index, int length)\n {\n this[index] = new T[length];\n\n // try... finally trick to be sure that the code isn't interrupted by asynchronous exceptions\n try {\n } finally {\n handles[index] = GCHandle.Alloc(this[index], GCHandleType.Pinned);\n }\n\n return handles[index].AddrOfPinnedObject();\n }\n\n public IntPtr CreateArray(int index, IntPtr length)\n {\n return CreateArray(index, (int)length);\n }\n\n public IntPtr CreateArray(int index, T[] array)\n {\n this[index] = array;\n\n // try... finally trick to be sure that the code isn't interrupted by asynchronous exceptions\n try {\n } finally {\n handles[index] = GCHandle.Alloc(array, GCHandleType.Pinned);\n }\n\n return handles[index].AddrOfPinnedObject();\n }\n\n public void Dispose()\n {\n foreach (var array in arrays)\n foreach (var val in array) {\n (val as IDisposable)?.Dispose();\n }\n FreeHandles();\n }\n\n ~IndexedPinnedArrays()\n {\n FreeHandles();\n }\n\n private void ExtendHandlesList(int idx)\n {\n if (idx >= handles.Count) {\n var extras = idx - handles.Count + 1;\n for (var i = 0; i < extras; i++) {\n handles.Add(default(GCHandle));\n arrays.Add(default(T[]));\n }\n }\n }\n\n private void FreeHandles()\n {\n foreach (var handle in handles) {\n if (handle.IsAllocated) {\n handle.Free();\n }\n }\n }\n }\n\n [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\n public delegate IntPtr AllocateIndexedPinnedArray(int id, IntPtr length);\n}" }, { "alpha_fraction": 0.4888888895511627, "alphanum_fraction": 0.48956915736198425, "avg_line_length": 30.056337356567383, "blob_id": "db7b424d1e7580d60db94e406e447594f521151d", "content_id": "6e12388ad7c04cb7f3a0fe4ed7bf2b06fb189c58", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4410, "license_type": "permissive", "max_line_length": 154, "num_lines": 142, "path": "/src/TorchSharp/NN/ModuleList.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System.Collections;\nusing System.Collections.Generic;\nusing static TorchSharp.torch.nn;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// Holds modules in a list.\n /// ModuleList can be indexed like a regular list, but modules it contains are properly registered, and will be visible by all Module methods.\n /// </summary>\n public class ModuleList<T> : Module, IList<T> where T: Module\n {\n public ModuleList(params T[] modules) : base(nameof(ModuleList))\n {\n if (modules != null && modules.Length > 0) {\n _list.AddRange(modules);\n }\n }\n\n protected override void RegisterComponents()\n {\n if (_registered) return;\n\n for (int i = 0; i < _list.Count; i++) {\n register_module($\"{i}\", _list[i]);\n }\n _registered = true;\n }\n\n private bool _registered = false;\n\n public T this[int index] {\n get => _list[index];\n set => _list[index] = value;\n }\n\n public int Count => _list.Count;\n\n public bool IsReadOnly => false;\n\n public void Add(T item)\n {\n _list.Add(item);\n }\n\n /// <summary>\n /// Appends zero or more parameters to the end of the list.\n /// </summary>\n public void append(params T[] parameters)\n {\n if (parameters != null && parameters.Length > 0) {\n _list.AddRange(parameters);\n }\n }\n\n public void Clear()\n {\n _list.Clear();\n }\n\n public bool Contains(T item)\n {\n return _list.Contains(item);\n }\n\n public void CopyTo(T[] array, int arrayIndex)\n {\n _list.CopyTo(array, arrayIndex);\n }\n\n /// <summary>\n /// Appends parameters from an enumeration to the end of the list.\n /// </summary>\n /// <param name=\"modules\"></param>\n public void extend(IEnumerable<T> modules)\n {\n _list.AddRange(modules);\n }\n\n public IEnumerator<T> GetEnumerator()\n {\n return _list.GetEnumerator();\n }\n\n public int IndexOf(T item)\n {\n return _list.IndexOf(item);\n }\n\n public void Insert(int index, T item)\n {\n _list.Insert(index, item);\n }\n\n public bool Remove(T item)\n {\n return _list.Remove(item);\n }\n\n public void RemoveAt(int index)\n {\n _list.RemoveAt(index);\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n private List<T> _list = new List<T>();\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Create a ModuleList instance from an array of modules.\n /// </summary>\n /// <param name=\"modules\">A list of modules.</param>\n /// <remarks>\n /// ModuleList can be indexed like a regular list, but modules it contains are properly registered, and will be visible by all Module methods.\n /// </remarks>\n public static ModuleList<Module> ModuleList(params Module[] modules) => new ModuleList<Module>(modules);\n\n /// <summary>\n /// Create a ModuleList instance from an array of modules.\n /// </summary>\n /// <param name=\"modules\">A list of modules.</param>\n /// <remarks>\n /// ModuleList can be indexed like a regular list, but modules it contains are properly registered, and will be visible by all Module methods.\n /// </remarks>\n public static ModuleList<T> ModuleList<T>(params T[] modules) where T : Module => new ModuleList<T>(modules);\n }\n }\n}\n" }, { "alpha_fraction": 0.5707030892372131, "alphanum_fraction": 0.5756229162216187, "avg_line_length": 52.3983039855957, "blob_id": "74c26008748dadefd102624a017f2c0d6ecdae02", "content_id": "7575c6169297af5991e6a5f5bb610005a108e84c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6301, "license_type": "permissive", "max_line_length": 180, "num_lines": 118, "path": "/src/TorchSharp/NN/Unfold.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using System.Security.Cryptography;\n using Modules;\n\n namespace Modules\n {\n public sealed class Unfold : torch.nn.Module<Tensor, Tensor>\n {\n internal Unfold((long, long) kernel_size, (long, long) dilation, (long, long) padding, (long, long) stride) : base(nameof(Unfold))\n {\n this.kernelSize = kernel_size;\n this.dilation = dilation;\n this.padding = padding;\n this.stride = stride;\n }\n\n public override Tensor forward(Tensor tensor)\n {\n return torch.nn.functional.unfold(tensor, kernelSize, dilation, padding, stride);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n\n private (long, long) kernelSize;\n private (long, long) dilation;\n private (long, long) padding;\n private (long, long) stride;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Extracts sliding local blocks from a batched input tensor.\n /// </summary>\n /// <param name=\"kernel_size\">The size of the sliding blocks</param>\n /// <param name=\"dilation\">A parameter that controls the stride of elements within the neighborhood.</param>\n /// <param name=\"padding\">Implicit zero padding to be added on both sides of input.</param>\n /// <param name=\"stride\">The stride of the sliding blocks in the input spatial dimensions.</param>\n /// <remarks>Currently, only 4-D input tensors (batched image-like tensors) are supported.</remarks>\n public unsafe static Unfold Unfold(long kernel_size, long dilation = 1, long padding = 0, long stride = 1)\n {\n return new Unfold((kernel_size, kernel_size), (dilation, dilation), (padding, padding), (stride, stride));\n }\n\n /// <summary>\n /// Extracts sliding local blocks from a batched input tensor.\n /// </summary>\n /// <param name=\"kernel_size\">The size of the sliding blocks</param>\n /// <param name=\"dilation\">A parameter that controls the stride of elements within the neighborhood.</param>\n /// <param name=\"padding\">Implicit zero padding to be added on both sides of input.</param>\n /// <param name=\"stride\">The stride of the sliding blocks in the input spatial dimensions.</param>\n /// <remarks>Currently, only 4-D input tensors (batched image-like tensors) are supported.</remarks>\n public unsafe static Unfold Unfold((long, long) kernel_size, (long, long)? dilation = null, (long, long)? padding = null, (long, long)? stride = null)\n {\n dilation ??= (1, 1);\n stride ??= (1, 1);\n padding ??= (0, 0);\n\n return new Unfold(kernel_size, dilation.Value, padding.Value, stride.Value);\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Extracts sliding local blocks from a batched input tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor. Must be 4-D (batched images).</param>\n /// <param name=\"kernel_size\">The size of the sliding blocks</param>\n /// <param name=\"dilation\">A parameter that controls the stride of elements within the neighborhood.</param>\n /// <param name=\"padding\">Implicit zero padding to be added on both sides of input.</param>\n /// <param name=\"stride\">The stride of the sliding blocks in the input spatial dimensions.</param>\n public unsafe static Tensor unfold(Tensor input, long kernel_size, long dilation = 1, long padding = 0, long stride = 1)\n {\n var res = THSNN_unfold(input.Handle, kernel_size, kernel_size, stride, stride, padding, padding, dilation, dilation);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Extracts sliding local blocks from a batched input tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor. Must be 4-D (batched images).</param>\n /// <param name=\"kernel_size\">The size of the sliding blocks</param>\n /// <param name=\"dilation\">A parameter that controls the stride of elements within the neighborhood.</param>\n /// <param name=\"padding\">Implicit zero padding to be added on both sides of input.</param>\n /// <param name=\"stride\">The stride of the sliding blocks in the input spatial dimensions.</param>\n public unsafe static Tensor unfold(Tensor input, (long, long) kernel_size, (long, long)? dilation = null, (long, long)? padding = null, (long, long)? stride = null)\n {\n dilation ??= (1, 1);\n stride ??= (1, 1);\n padding ??= (0, 0);\n\n var res = THSNN_unfold(input.Handle,\n kernel_size.Item1, kernel_size.Item2,\n stride.Value.Item1, stride.Value.Item2,\n padding.Value.Item1, padding.Value.Item2,\n dilation.Value.Item1, dilation.Value.Item2);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.47071465849876404, "alphanum_fraction": 0.47071465849876404, "avg_line_length": 31.086206436157227, "blob_id": "6a4db713467c7a6e4044a837288b99875b58f0bb", "content_id": "31395a918b23624c3875c502cf9fc006107e62ba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1861, "license_type": "permissive", "max_line_length": 130, "num_lines": 58, "path": "/src/TorchSharp/JIT/Type/TensorType.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class jit\n {\n public sealed class TensorType : Type\n {\n internal TensorType(IntPtr handle) : base(handle, TypeKind.TensorType)\n {\n this.handle = new HType(handle, true, TypeKind.TensorType);\n }\n\n internal TensorType(Type type) : base()\n {\n handle = type.handle;\n type.handle = new HType(IntPtr.Zero, true, TypeKind.TensorType);\n type.Dispose();\n }\n\n public ScalarType GetScalarType()\n {\n return (ScalarType)THSJIT_TensorType_dtype(handle);\n }\n\n /// <summary>\n /// Retrieves the sizes of all dimensions of the tensor.\n /// </summary>\n public long[] size()\n {\n long[] ptrArray;\n\n using (var pa = new PinnedArray<long>()) {\n THSJIT_TensorType_sizes(handle, pa.CreateArray);\n CheckForErrors();\n ptrArray = pa.Array;\n }\n\n return ptrArray;\n }\n\n public int GetDimensions()\n {\n return THSJIT_getDimensionedTensorTypeDimensions(handle);\n }\n\n public string GetDevice()\n {\n return THSJIT_getDimensionedTensorDevice(handle);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.4978165924549103, "alphanum_fraction": 0.5, "avg_line_length": 21.950000762939453, "blob_id": "38f6fdba7803615e410f38a99a77887aeefe1df5", "content_id": "5af1b21d4b7518c0107d99bae1906701e07d13f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 458, "license_type": "permissive", "max_line_length": 130, "num_lines": 20, "path": "/src/TorchAudio/AudioFormat.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n /// <summary>\n /// Audio format\n /// </summary>\n public enum AudioFormat\n {\n WAV,\n MP3,\n FLAC,\n OGG,\n OPUS,\n SPHERE,\n AMR_NB\n }\n }\n}" }, { "alpha_fraction": 0.4525687098503113, "alphanum_fraction": 0.46666666865348816, "avg_line_length": 45.5, "blob_id": "a0c81d142e541bac57691b7b46d31f9763c6f3a3", "content_id": "987f022f73d8616e233f2754dd809e2ec30899b9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4185, "license_type": "permissive", "max_line_length": 240, "num_lines": 90, "path": "/src/TorchVision/Ops.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\nusing System.Collections.Generic;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class ops\n {\n public static Tensor sigmoid_focal_loss(Tensor inputs, Tensor targets, float alpha = 0.25f, float gamma = 2.0f, nn.Reduction reduction = nn.Reduction.None)\n {\n using (var _ = torch.NewDisposeScope()) {\n\n var p = torch.sigmoid(inputs);\n var ce_loss = nn.functional.binary_cross_entropy_with_logits(inputs, targets, reduction: reduction);\n var p_t = p * targets + (1 - p) * (1 - targets);\n\n var loss = ce_loss * (1 - p_t).pow(gamma);\n\n if (alpha >= 0) {\n var alpha_t = alpha * targets + (1 - alpha) * (1 - targets);\n loss = alpha_t * loss;\n }\n\n if (reduction == nn.Reduction.Mean) {\n loss = loss.mean();\n } else if (reduction == nn.Reduction.Sum) {\n loss = loss.sum();\n }\n\n return loss.MoveToOuterDisposeScope();\n }\n }\n\n /// <summary>\n /// Performs non-maximum suppression (NMS) on the boxes according to their intersection-over-union (IoU). NMS iteratively removes lower scoring boxes which have an IoU greater than iou_threshold with another(higher scoring) box.\n /// </summary>\n /// <param name=\"boxes\">Boxes (Tensor[N, 4]) to perform NMS on. They are expected to be in (left, top, right, down) format.</param>\n /// <param name=\"scores\">Scores (Tensor[N]) for each one of the boxes.</param>\n /// <param name=\"iou_threshold\">Discards all overlapping boxes with IoU > iou_threshold.</param>\n /// <returns>The indices (Tensor) of the elements that have been kept by NMS, sorted in decreasing order of scores.</returns>\n public static Tensor nms(Tensor boxes, Tensor scores, double iou_threshold = 0.5)\n {\n using (var _ = torch.NewDisposeScope()) {\n var x1 = boxes.select(1, 0);\n var y1 = boxes.select(1, 1);\n var x2 = boxes.select(1, 2);\n var y2 = boxes.select(1, 3);\n var areas = (x2 - x1) * (y2 - y1);\n var (_, order) = scores.sort(0, descending: true);\n\n var keep = new List<long>();\n while (order.numel() > 0) {\n long i;\n if (order.numel() == 1) {\n i = order.cpu().item<long>();\n keep.Add(i);\n break;\n } else {\n i = order[0].cpu().item<long>();\n keep.Add(i);\n }\n\n var indices = torch.arange(1, order.shape[0], dtype: ScalarType.Int64);\n order = order[indices];\n var xx1 = x1[order].clamp(min: x1[i]);\n var yy1 = y1[order].clamp(min: y1[i]);\n var xx2 = x2[order].clamp(max: x2[i]);\n var yy2 = y2[order].clamp(max: y2[i]);\n var inter = (xx2 - xx1).clamp(min: 0) * (yy2 - yy1).clamp(min: 0);\n\n var iou = inter / (areas[i] + areas[order] - inter);\n var idx = (iou <= iou_threshold).nonzero().squeeze();\n if (idx.numel() == 0) {\n break;\n }\n\n order = order[idx];\n }\n\n var ids = torch.from_array(keep.ToArray()).to_type(ScalarType.Int64).to(device: boxes.device);\n return ids.MoveToOuterDisposeScope();\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5684428215026855, "alphanum_fraction": 0.5856683254241943, "avg_line_length": 44.35416793823242, "blob_id": "37b2503eff09b602118f85d565f5f2cce9492d45", "content_id": "77f711d44b409edbf1c1a6dfa2539f063ae6bdac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4354, "license_type": "permissive", "max_line_length": 136, "num_lines": 96, "path": "/src/TorchSharp/Distributions/Kumaraswamy.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n using static torch.distributions;\n\n namespace Modules\n {\n public class Kumaraswamy : TransformedDistribution\n {\n internal Kumaraswamy(Tensor concentration1, Tensor concentration0, torch.Generator generator = null) : base(generator)\n {\n var c1c0 = broadcast_tensors(concentration1, concentration0);\n this.concentration1 = c1c0[0].DetachFromDisposeScope();\n this.concentration0 = c1c0[1].DetachFromDisposeScope();\n\n _init(Uniform(torch.full_like(this.concentration0, 0), torch.full_like(this.concentration0, 1)),\n new distributions.transforms.Transform[] {\n new torch.distributions.transforms.PowerTransform(exponent: this.concentration0.reciprocal()),\n new torch.distributions.transforms.AffineTransform(loc:1.0, scale:-1.0),\n new torch.distributions.transforms.PowerTransform(exponent: this.concentration1.reciprocal())\n });\n }\n\n public Tensor concentration1 { get; private set; }\n\n public Tensor concentration0 { get; private set; }\n\n public override Tensor mean => moments(concentration1, concentration0, 1);\n\n public override Tensor mode {\n get {\n using var _ = torch.NewDisposeScope();\n var log_mode = concentration0.reciprocal() * (-concentration0).log1p() - (-concentration0 * concentration1).log1p();\n log_mode[(concentration0 < 1) | (concentration1 < 1)] = double.NaN;\n return log_mode.exp().MoveToOuterDisposeScope();\n }\n }\n\n public override Tensor variance => moments(concentration1, concentration0, 2) - torch.pow(mean, 2);\n\n public override Tensor entropy()\n {\n using var _ = torch.NewDisposeScope();\n var t1 = (1 - concentration1.reciprocal());\n var t0 = (1 - concentration0.reciprocal());\n var H0 = torch.digamma(concentration0 + 1) + euler_constant;\n return (t0 + t1 * H0 - torch.log(concentration1) - torch.log(concentration0)).MoveToOuterDisposeScope();\n }\n\n public override Distribution expand(Size batch_shape, Distribution instance = null)\n {\n var newDistribution = ((instance == null)\n ? new Kumaraswamy(concentration1.expand(batch_shape), concentration0.expand(batch_shape), generator)\n : instance) as Kumaraswamy;\n\n if (newDistribution == instance) {\n newDistribution.concentration0 = concentration0.expand(batch_shape);\n newDistribution.concentration1 = concentration1.expand(batch_shape);\n }\n return base.expand(batch_shape, newDistribution);\n }\n\n private Tensor moments(Tensor a, Tensor b, int n)\n {\n using var _ = torch.NewDisposeScope();\n var arg1 = 1 + n / a;\n var log_value = torch.lgamma(arg1) + torch.lgamma(b) - torch.lgamma(arg1 + b);\n return (b * torch.exp(log_value)).MoveToOuterDisposeScope();\n }\n }\n }\n\n\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Samples from a Kumaraswamy distribution.\n /// </summary>\n /// <param name=\"concentration1\">1st concentration parameter of the distribution</param>\n /// <param name=\"concentration0\">2nd concentration parameter of the distribution</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Kumaraswamy Kumaraswamy(Tensor concentration1, Tensor concentration0, torch.Generator generator = null)\n {\n \n return new Kumaraswamy(concentration1, concentration0, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5536637306213379, "alphanum_fraction": 0.5588324666023254, "avg_line_length": 40.632911682128906, "blob_id": "8c811e67fb20ecee36caa6408a68cb5b0c528a32", "content_id": "28966487438889f9f06186301a65db1963d176d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3289, "license_type": "permissive", "max_line_length": 130, "num_lines": 79, "path": "/src/TorchSharp/NN/Activation/RReLU.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a RReLU module.\n /// </summary>\n public sealed class RReLU : torch.nn.Module<Tensor, Tensor>\n {\n internal RReLU(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_RReLU_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public override string GetName()\n {\n return typeof(RReLU).Name;\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Randomized Rectified Linear Unit\n /// </summary>\n /// <param name=\"lower\">Lower bound of the uniform distribution. Default: 1/8</param>\n /// <param name=\"upper\">Upper bound of the uniform distribution. Default: 1/3</param>\n /// <param name=\"inplace\">Do the operation in-place. Default: False</param>\n /// <returns></returns>\n public static RReLU RReLU(double lower = one_eighth, double upper = one_third, bool inplace = false)\n {\n var handle = THSNN_RReLU_ctor(lower, upper, inplace, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new RReLU(handle, boxedHandle);\n }\n\n private const double one_eighth = 1.0 / 8.0;\n private const double one_third = 1.0 / 3.0;\n\n public static partial class functional\n {\n /// <summary>\n /// Randomized Rectified Linear Unit\n /// </summary>\n /// <param name=\"x\">The input tensor</param>\n /// <param name=\"lower\">Lower bound of the uniform distribution. Default: 1/8</param>\n /// <param name=\"upper\">Upper bound of the uniform distribution. Default: 1/3</param>\n /// <param name=\"inplace\">Do the operation in-place. Default: False</param>\n /// <returns></returns>\n public static Tensor rrelu(Tensor x, double lower, double upper, bool inplace = false)\n {\n using (var m = nn.RReLU(lower, upper, inplace)) {\n return m.call(x);\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5682742595672607, "alphanum_fraction": 0.5732132196426392, "avg_line_length": 44.893333435058594, "blob_id": "c1e6b19d5cab8dc429b643ae91b8d26c650935fd", "content_id": "2d8d7e908da6354761e5bc2a922f70f78ead8ca5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3442, "license_type": "permissive", "max_line_length": 162, "num_lines": 75, "path": "/src/TorchSharp/NN/Pooling/MaxUnpool1d.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a MaxUnpool1D module.\n /// </summary>\n public sealed class MaxUnpool1d : torch.nn.Module<Tensor, Tensor, long[], Tensor>\n {\n internal MaxUnpool1d(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor, Tensor indices, long[] output_size = null)\n {\n unsafe {\n fixed (long* pOutSize = output_size) {\n var res = THSNN_MaxUnpool1d_forward(handle, tensor.Handle, indices.Handle, (IntPtr)pOutSize);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n public new Tensor call(Tensor tensor, Tensor indices, long[] output_size = null)\n {\n return base.call(tensor, indices, output_size);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies a 1D max pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"kernelSize\">The size of the sliding window, must be > 0.</param>\n /// <param name=\"stride\">The stride of the sliding window, must be > 0. Default value is kernel_size.</param>\n /// <param name=\"padding\">Implicit negative infinity padding to be added on both sides, must be >= 0 and less than or equal to kernel_size / 2</param>\n /// <returns></returns>\n public static MaxUnpool1d MaxUnpool1d(long kernelSize, long? stride = null, long? padding = null)\n {\n var pStride = stride.HasValue ? new long[] { stride.Value } : null;\n var pPadding = padding.HasValue ? new long[] { padding.Value } : null;\n return MaxUnpool1d(new long[] { kernelSize }, pStride, pPadding);\n }\n\n private static MaxUnpool1d MaxUnpool1d(long[] kernelSize, long[] strides = null, long[] padding = null)\n {\n unsafe {\n fixed (long* pkernelSize = kernelSize, pstrides = strides, pPadding = padding) {\n var handle = THSNN_MaxUnpool1d_ctor((IntPtr)pkernelSize, (IntPtr)pstrides, (IntPtr)pPadding, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new MaxUnpool1d(handle, boxedHandle);\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5577172636985779, "alphanum_fraction": 0.5629053115844727, "avg_line_length": 34.04545593261719, "blob_id": "18eb8ed14989b1fca9ac861265e60ddb77be9e34", "content_id": "68abb553c3e4bed28825656b628b52e17365a625", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1542, "license_type": "permissive", "max_line_length": 130, "num_lines": 44, "path": "/src/TorchVision/AdjustSharpness.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class AdjustSharpness : ITransform\n {\n internal AdjustSharpness(double sharpness)\n {\n if (sharpness < 0.0)\n throw new ArgumentException($\"The sharpness factor ({sharpness}) must be non-negative.\");\n this.sharpness = sharpness;\n }\n\n public Tensor call(Tensor input)\n {\n return transforms.functional.adjust_sharpness(input, sharpness);\n }\n\n private double sharpness;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Adjust the sharpness of the image. \n /// </summary>\n /// <param name=\"sharpness\">\n /// How much to adjust the sharpness. Can be any non negative number.\n /// 0 gives a blurred image, 1 gives the original image while 2 increases the sharpness by a factor of 2.\n /// </param>\n /// <returns></returns>\n static public ITransform AdjustSharpness(double sharpness)\n {\n if (sharpness < 0.0)\n throw new ArgumentException(\"Negative sharpness factor\");\n return new AdjustSharpness(sharpness);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6791037321090698, "alphanum_fraction": 0.6887807846069336, "avg_line_length": 28.77503776550293, "blob_id": "3013dc56507137965c01bcc9a83f43b566a4d010", "content_id": "6d0e6d97e98f6b4cfbcc0448407f308390cc1fb2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 19324, "license_type": "permissive", "max_line_length": 208, "num_lines": 649, "path": "/src/Native/LibTorchSharp/THSNormalization.cpp", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#include \"THSNN.h\"\n\n#include <torch/nn/init.h>\n\nNNModule THSNN_BatchNorm1d_ctor(const int64_t features, const double eps, const double momentum, const bool affine, const bool track_running_stats, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::BatchNorm1dOptions(features)\n .eps(eps)\n .momentum(momentum)\n .affine(affine)\n .track_running_stats(track_running_stats);\n\n res = create_module<torch::nn::BatchNorm1dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_BatchNorm1d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::BatchNorm1d>()->forward(*tensor));\n}\n\nNNModule THSNN_BatchNorm2d_ctor(const int64_t features, const double eps, const double momentum, const bool affine, const bool track_running_stats, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::BatchNorm2dOptions(features)\n .eps(eps)\n .momentum(momentum)\n .affine(affine)\n .track_running_stats(track_running_stats);\n\n res = create_module<torch::nn::BatchNorm2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_BatchNorm2d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::BatchNorm2d>()->forward(*tensor));\n}\n\nNNModule THSNN_BatchNorm3d_ctor(const int64_t features, const double eps, const double momentum, const bool affine, const bool track_running_stats, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::BatchNorm3dOptions(features)\n .eps(eps)\n .momentum(momentum)\n .affine(affine)\n .track_running_stats(track_running_stats);\n\n res = create_module<torch::nn::BatchNorm3dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_BatchNorm3d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::BatchNorm3d>()->forward(*tensor));\n}\n\nNNModule THSNN_GroupNorm_ctor(const int64_t num_groups, const int64_t num_channels, const double eps, const bool affine, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::GroupNormOptions(num_groups, num_channels).eps(eps).affine(affine);\n res = create_module<torch::nn::GroupNormImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_GroupNorm_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::GroupNorm>()->forward(*tensor));\n}\n\nTensor THSNN_GroupNorm_bias(const NNModule module)\n{\n return get_bias<torch::nn::GroupNorm>(module);\n}\n\nvoid THSNN_GroupNorm_set_bias(const NNModule module, const Tensor bias)\n{\n set_bias<torch::nn::GroupNorm>(module, bias);\n}\n\nTensor THSNN_GroupNorm_weight(const NNModule module)\n{\n return get_weight<torch::nn::GroupNorm>(module);\n}\n\nvoid THSNN_GroupNorm_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::GroupNorm>(module, weight);\n}\n\n\nNNModule THSNN_InstanceNorm1d_ctor(const int64_t features, const double eps, const double momentum, const bool affine, const bool track_running_stats, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::InstanceNorm1dOptions(features)\n .eps(eps)\n .momentum(momentum)\n .affine(affine)\n .track_running_stats(track_running_stats);\n\n res = create_module<torch::nn::InstanceNorm1dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_InstanceNorm1d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::InstanceNorm1d>()->forward(*tensor));\n}\n\nNNModule THSNN_InstanceNorm2d_ctor(const int64_t features, const double eps, const double momentum, const bool affine, const bool track_running_stats, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::InstanceNorm2dOptions(features)\n .eps(eps)\n .momentum(momentum)\n .affine(affine)\n .track_running_stats(track_running_stats);\n\n res = create_module<torch::nn::InstanceNorm2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_InstanceNorm2d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::InstanceNorm2d>()->forward(*tensor));\n}\n\nNNModule THSNN_InstanceNorm3d_ctor(const int64_t features, const double eps, const double momentum, const bool affine, const bool track_running_stats, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::InstanceNorm3dOptions(features)\n .eps(eps)\n .momentum(momentum)\n .affine(affine)\n .track_running_stats(track_running_stats);\n\n res = create_module<torch::nn::InstanceNorm3dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_InstanceNorm3d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::InstanceNorm3d>()->forward(*tensor));\n}\n\nNNModule THSNN_LayerNorm_ctor(const int64_t* norm_shape, const int64_t norm_shape_len, const double eps, const bool elementwise_affine, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n std::vector<int64_t> normalized_shape;\n for (int64_t i = 0; i < norm_shape_len; ++i)\n {\n normalized_shape.push_back(norm_shape[i]);\n }\n auto opts = torch::nn::LayerNormOptions(normalized_shape).eps(eps).elementwise_affine(elementwise_affine);\n res = create_module<torch::nn::LayerNormImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_LayerNorm_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::LayerNorm>()->forward(*tensor));\n}\n\nTensor THSNN_LayerNorm_bias(const NNModule module)\n{\n return get_bias<torch::nn::LayerNorm>(module);\n}\n\nvoid THSNN_LayerNorm_set_bias(const NNModule module, const Tensor bias)\n{\n set_bias<torch::nn::LayerNorm>(module, bias);\n}\n\nTensor THSNN_LayerNorm_weight(const NNModule module)\n{\n return get_weight<torch::nn::LayerNorm>(module);\n}\n\nvoid THSNN_LayerNorm_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::LayerNorm>(module, weight);\n}\n\n\nNNModule THSNN_LocalResponseNorm_ctor(const int64_t size, const double alpha, const double beta, const double k, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::LocalResponseNormOptions(size)\n .alpha(alpha)\n .beta(beta)\n .k(k);\n res = create_module<torch::nn::LocalResponseNormImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_LocalResponseNorm_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::LocalResponseNorm>()->forward(*tensor));\n}\n\nvoid THSNN_BatchNorm1d_reset_stats(const NNModule module)\n{\n CATCH((*module)->as<torch::nn::BatchNorm1d>()->reset_running_stats(););\n}\n\nTensor THSNN_BatchNorm1d_get_mean(const NNModule module)\n{\n CATCH(\n auto m = (*module)->as<torch::nn::BatchNorm1d>()->running_mean;\n return m.defined() ? ResultTensor(m) : nullptr;\n );\n return nullptr;\n}\n\nTensor THSNN_BatchNorm1d_get_var(const NNModule module)\n{\n CATCH(\n auto v = (*module)->as<torch::nn::BatchNorm1d>()->running_var;\n return v.defined() ? ResultTensor(v) : nullptr;\n );\n return nullptr;\n}\n\nTensor THSNN_BatchNorm1d_get_batches(const NNModule module)\n{\n CATCH(\n auto v = (*module)->as<torch::nn::BatchNorm1d>()->num_batches_tracked;\n return v.defined() ? ResultTensor(v) : nullptr;\n );\n return nullptr;\n}\n\nvoid THSNN_BatchNorm1d_set_mean(const NNModule module, const Tensor bias)\n{\n CATCH(\n (*module)->as<torch::nn::BatchNorm1d>()->running_mean = *bias;\n );\n}\n\nvoid THSNN_BatchNorm1d_set_var(const NNModule module, const Tensor bias)\n{\n CATCH(\n (*module)->as<torch::nn::BatchNorm1d>()->running_var = *bias;\n );\n}\n\nTensor THSNN_BatchNorm1d_bias(const NNModule module)\n{\n return get_bias<torch::nn::BatchNorm1d>(module);\n}\n\nvoid THSNN_BatchNorm1d_set_bias(const NNModule module, const Tensor bias)\n{\n set_bias<torch::nn::BatchNorm1d>(module, bias);\n}\n\nTensor THSNN_BatchNorm1d_weight(const NNModule module)\n{\n return get_weight<torch::nn::BatchNorm1d>(module);\n}\n\nvoid THSNN_BatchNorm1d_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::BatchNorm1d>(module, weight);\n}\n\nvoid THSNN_BatchNorm2d_reset_stats(const NNModule module)\n{\n CATCH((*module)->as<torch::nn::BatchNorm2d>()->reset_running_stats(););\n}\n\nTensor THSNN_BatchNorm2d_get_mean(const NNModule module)\n{\n CATCH(\n auto m = (*module)->as<torch::nn::BatchNorm2d>()->running_mean;\n return m.defined() ? ResultTensor(m) : nullptr;\n );\n return nullptr;\n}\n\nTensor THSNN_BatchNorm2d_get_var(const NNModule module)\n{\n CATCH(\n auto v = (*module)->as<torch::nn::BatchNorm2d>()->running_var;\n return v.defined() ? ResultTensor(v) : nullptr;\n );\n return nullptr;\n}\n\nTensor THSNN_BatchNorm2d_get_batches(const NNModule module)\n{\n CATCH(\n auto v = (*module)->as<torch::nn::BatchNorm2d>()->num_batches_tracked;\n return v.defined() ? ResultTensor(v) : nullptr;\n );\n return nullptr;\n}\n\nvoid THSNN_BatchNorm2d_set_mean(const NNModule module, const Tensor bias)\n{\n CATCH(\n (*module)->as<torch::nn::BatchNorm2d>()->running_mean = *bias;\n );\n}\n\nvoid THSNN_BatchNorm2d_set_var(const NNModule module, const Tensor bias)\n{\n CATCH(\n (*module)->as<torch::nn::BatchNorm2d>()->running_var = *bias;\n );\n}\n\nTensor THSNN_BatchNorm2d_bias(const NNModule module)\n{\n return get_bias<torch::nn::BatchNorm2d>(module);\n}\n\nvoid THSNN_BatchNorm2d_set_bias(const NNModule module, const Tensor bias)\n{\n set_bias<torch::nn::BatchNorm2d>(module, bias);\n}\n\nTensor THSNN_BatchNorm2d_weight(const NNModule module)\n{\n return get_weight<torch::nn::BatchNorm2d>(module);\n}\n\nvoid THSNN_BatchNorm2d_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::BatchNorm2d>(module, weight);\n}\n\nvoid THSNN_BatchNorm3d_reset_stats(const NNModule module)\n{\n CATCH((*module)->as<torch::nn::BatchNorm3d>()->reset_running_stats(););\n}\n\nTensor THSNN_BatchNorm3d_get_mean(const NNModule module)\n{\n CATCH(\n auto m = (*module)->as<torch::nn::BatchNorm3d>()->running_mean;\n return m.defined() ? ResultTensor(m) : nullptr;\n );\n return nullptr;\n}\n\nTensor THSNN_BatchNorm3d_get_var(const NNModule module)\n{\n CATCH(\n auto v = (*module)->as<torch::nn::BatchNorm3d>()->running_var;\n return v.defined() ? ResultTensor(v) : nullptr;\n );\n return nullptr;\n}\n\nTensor THSNN_BatchNorm3d_get_batches(const NNModule module)\n{\n CATCH(\n auto v = (*module)->as<torch::nn::BatchNorm3d>()->num_batches_tracked;\n return v.defined() ? ResultTensor(v) : nullptr;\n );\n return nullptr;\n}\n\nvoid THSNN_BatchNorm3d_set_mean(const NNModule module, const Tensor bias)\n{\n CATCH(\n (*module)->as<torch::nn::BatchNorm3d>()->running_mean = *bias;\n );\n}\n\nvoid THSNN_BatchNorm3d_set_var(const NNModule module, const Tensor bias)\n{\n CATCH(\n (*module)->as<torch::nn::BatchNorm3d>()->running_var = *bias;\n );\n}\n\nTensor THSNN_BatchNorm3d_bias(const NNModule module)\n{\n return get_bias<torch::nn::BatchNorm3d>(module);\n}\n\nvoid THSNN_BatchNorm3d_set_bias(const NNModule module, const Tensor bias)\n{\n set_bias<torch::nn::BatchNorm3d>(module, bias);\n}\n\nTensor THSNN_BatchNorm3d_weight(const NNModule module)\n{\n return get_weight<torch::nn::BatchNorm3d>(module);\n}\n\nvoid THSNN_BatchNorm3d_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::BatchNorm3d>(module, weight);\n}\n\nvoid THSNN_InstanceNorm1d_reset_stats(const NNModule module)\n{\n CATCH((*module)->as<torch::nn::InstanceNorm1d>()->reset_running_stats(););\n}\n\nTensor THSNN_InstanceNorm1d_get_mean(const NNModule module)\n{\n CATCH(\n auto m = (*module)->as<torch::nn::InstanceNorm1d>()->running_mean;\n return m.defined() ? ResultTensor(m) : nullptr;\n );\n return nullptr;\n}\n\nTensor THSNN_InstanceNorm1d_get_var(const NNModule module)\n{\n CATCH(\n auto v = (*module)->as<torch::nn::InstanceNorm1d>()->running_var;\n return v.defined() ? ResultTensor(v) : nullptr;\n );\n return nullptr;\n}\n\nTensor THSNN_InstanceNorm1d_get_batches(const NNModule module)\n{\n CATCH(\n auto v = (*module)->as<torch::nn::InstanceNorm1d>()->num_batches_tracked;\n return v.defined() ? ResultTensor(v) : nullptr;\n );\n return nullptr;\n}\n\nvoid THSNN_InstanceNorm1d_set_mean(const NNModule module, const Tensor bias)\n{\n CATCH(\n (*module)->as<torch::nn::InstanceNorm1d>()->running_mean = *bias;\n );\n}\n\nvoid THSNN_InstanceNorm1d_set_var(const NNModule module, const Tensor bias)\n{\n CATCH(\n (*module)->as<torch::nn::InstanceNorm1d>()->running_var = *bias;\n );\n}\n\nTensor THSNN_InstanceNorm1d_bias(const NNModule module)\n{\n return get_bias<torch::nn::InstanceNorm1d>(module);\n}\n\nvoid THSNN_InstanceNorm1d_set_bias(const NNModule module, const Tensor bias)\n{\n set_bias<torch::nn::InstanceNorm1d>(module, bias);\n}\n\nTensor THSNN_InstanceNorm1d_weight(const NNModule module)\n{\n return get_weight<torch::nn::InstanceNorm1d>(module);\n}\n\nvoid THSNN_InstanceNorm1d_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::InstanceNorm1d>(module, weight);\n}\n\nvoid THSNN_InstanceNorm2d_reset_stats(const NNModule module)\n{\n CATCH((*module)->as<torch::nn::InstanceNorm2d>()->reset_running_stats(););\n}\n\nTensor THSNN_InstanceNorm2d_get_mean(const NNModule module)\n{\n CATCH(\n auto m = (*module)->as<torch::nn::InstanceNorm2d>()->running_mean;\n return m.defined() ? ResultTensor(m) : nullptr;\n );\n return nullptr;\n}\n\nTensor THSNN_InstanceNorm2d_get_var(const NNModule module)\n{\n CATCH(\n auto v = (*module)->as<torch::nn::InstanceNorm2d>()->running_var;\n return v.defined() ? ResultTensor(v) : nullptr;\n );\n return nullptr;\n}\n\nTensor THSNN_InstanceNorm2d_get_batches(const NNModule module)\n{\n CATCH(\n auto v = (*module)->as<torch::nn::InstanceNorm2d>()->num_batches_tracked;\n return v.defined() ? ResultTensor(v) : nullptr;\n );\n return nullptr;\n}\n\nvoid THSNN_InstanceNorm2d_set_mean(const NNModule module, const Tensor bias)\n{\n CATCH(\n (*module)->as<torch::nn::InstanceNorm2d>()->running_mean = *bias;\n );\n}\n\nvoid THSNN_InstanceNorm2d_set_var(const NNModule module, const Tensor bias)\n{\n CATCH(\n (*module)->as<torch::nn::InstanceNorm2d>()->running_var = *bias;\n );\n}\n\nTensor THSNN_InstanceNorm2d_bias(const NNModule module)\n{\n return get_bias<torch::nn::InstanceNorm2d>(module);\n}\n\nvoid THSNN_InstanceNorm2d_set_bias(const NNModule module, const Tensor bias)\n{\n set_bias<torch::nn::InstanceNorm2d>(module, bias);\n}\n\nTensor THSNN_InstanceNorm2d_weight(const NNModule module)\n{\n return get_weight<torch::nn::InstanceNorm2d>(module);\n}\n\nvoid THSNN_InstanceNorm2d_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::InstanceNorm2d>(module, weight);\n}\n\nvoid THSNN_InstanceNorm3d_reset_stats(const NNModule module)\n{\n CATCH((*module)->as<torch::nn::InstanceNorm3d>()->reset_running_stats(););\n}\n\nTensor THSNN_InstanceNorm3d_get_mean(const NNModule module)\n{\n CATCH(\n auto m = (*module)->as<torch::nn::InstanceNorm3d>()->running_mean;\n return m.defined() ? ResultTensor(m) : nullptr;\n );\n return nullptr;\n}\n\nTensor THSNN_InstanceNorm3d_get_var(const NNModule module)\n{\n CATCH(\n auto v = (*module)->as<torch::nn::InstanceNorm3d>()->running_var;\n return v.defined() ? ResultTensor(v) : nullptr;\n );\n return nullptr;\n}\n\nTensor THSNN_InstanceNorm3d_get_batches(const NNModule module)\n{\n CATCH(\n auto v = (*module)->as<torch::nn::InstanceNorm3d>()->num_batches_tracked;\n return v.defined() ? ResultTensor(v) : nullptr;\n );\n return nullptr;\n}\n\nvoid THSNN_InstanceNorm3d_set_mean(const NNModule module, const Tensor bias)\n{\n CATCH(\n (*module)->as<torch::nn::InstanceNorm3d>()->running_mean = *bias;\n );\n}\n\nvoid THSNN_InstanceNorm3d_set_var(const NNModule module, const Tensor bias)\n{\n CATCH(\n (*module)->as<torch::nn::InstanceNorm3d>()->running_var = *bias;\n );\n}\n\nTensor THSNN_InstanceNorm3d_bias(const NNModule module)\n{\n return get_bias<torch::nn::InstanceNorm3d>(module);\n}\n\nvoid THSNN_InstanceNorm3d_set_bias(const NNModule module, const Tensor bias)\n{\n set_bias<torch::nn::InstanceNorm3d>(module, bias);\n}\n\nTensor THSNN_InstanceNorm3d_weight(const NNModule module)\n{\n return get_weight<torch::nn::InstanceNorm3d>(module);\n}\n\nvoid THSNN_InstanceNorm3d_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::InstanceNorm3d>(module, weight);\n}\n\nTensor THSNN_batch_norm(const Tensor input, Tensor running_mean, const Tensor running_var, const Tensor weight, const Tensor bias, const bool training, const double momentum, const double eps)\n{\n auto opts = torch::nn::functional::BatchNormFuncOptions()\n .training(training)\n .momentum(momentum)\n .eps(eps);\n if (weight != nullptr) opts.weight(*weight);\n if (bias != nullptr) opts.bias(*bias);\n CATCH_TENSOR(torch::nn::functional::batch_norm(*input, *running_mean, *running_var, opts));\n}\n\nTensor THSNN_group_norm(const Tensor input, const int64_t num_groups, const Tensor weight, const Tensor bias, const double eps)\n{\n auto opts = torch::nn::functional::GroupNormFuncOptions(num_groups)\n .eps(eps);\n if (weight != nullptr) opts.weight(*weight);\n if (bias != nullptr) opts.bias(*bias);\n CATCH_TENSOR(torch::nn::functional::group_norm(*input, opts));\n}\n\nTensor THSNN_instance_norm(const Tensor input, const Tensor running_mean, const Tensor running_var, const Tensor weight, const Tensor bias, const bool use_input_stats, const double momentum, const double eps)\n{\n auto opts = torch::nn::functional::InstanceNormFuncOptions()\n .use_input_stats(use_input_stats)\n .momentum(momentum)\n .eps(eps);\n if (running_mean != nullptr) opts.running_mean(*running_mean);\n if (running_var != nullptr) opts.running_var(*running_var);\n if (weight != nullptr) opts.weight(*weight);\n if (bias != nullptr) opts.bias(*bias);\n CATCH_TENSOR(torch::nn::functional::instance_norm(*input, opts));\n}\n\nTensor THSNN_layer_norm(const Tensor input, const int64_t* normalized_shape, const int64_t normalized_shape_len, const Tensor weight, const Tensor bias, const double eps)\n{\n auto opts = torch::nn::functional::LayerNormFuncOptions(\n std::vector<int64_t>(normalized_shape, normalized_shape + normalized_shape_len))\n .eps(eps);\n if (weight != nullptr) opts.weight(*weight);\n if (bias != nullptr) opts.bias(*bias);\n CATCH_TENSOR(torch::nn::functional::layer_norm(*input, opts));\n}\n\nTensor THSNN_local_response_norm(const Tensor input, const int64_t size, const double alpha, const double beta, const double k)\n{\n auto opts = torch::nn::functional::LocalResponseNormFuncOptions(size)\n .alpha(alpha)\n .beta(beta)\n .k(k);\n CATCH_TENSOR(torch::nn::functional::local_response_norm(*input, opts));\n}\n" }, { "alpha_fraction": 0.49947553873062134, "alphanum_fraction": 0.5054195523262024, "avg_line_length": 45.8934440612793, "blob_id": "6e1b9f7bce99738dcb0de128dc2f3ab995999265", "content_id": "5890fa39ca0435b54c207b5edff438d196250e13", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5720, "license_type": "permissive", "max_line_length": 183, "num_lines": 122, "path": "/src/TorchSharp/Hub.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.IO;\nusing System.Net.Http;\nusing System.Security.Cryptography;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class hub\n {\n private static Func<bool, IProgressBar> createProgressBarFunc = null;\n\n /// <summary>\n /// Set a function to create a progress bar.\n /// </summary>\n /// <param name=\"func\">A progress bar function or null to set default the console progress bar</param>\n public static void set_create_progress_bar_func(Func<bool, IProgressBar> func)\n {\n createProgressBarFunc = func;\n }\n\n /// <summary>\n /// Create a progress bar.\n /// </summary>\n /// <param name=\"hidden\">Make a hidden progress bar.</param>\n /// <returns>A progress bar</returns>\n public static IProgressBar CreateProgressBar(bool hidden)\n {\n IProgressBar progress_bar;\n if (createProgressBarFunc == null) {\n progress_bar = new ConsoleProgressBar(hidden);\n } else {\n progress_bar = createProgressBarFunc(hidden);\n }\n return progress_bar;\n }\n\n /// <summary>\n /// Download the url to a file \n /// </summary>\n /// <param name=\"url\">The URL to download</param>\n /// <param name=\"dst\">The file path to download the URL into</param>\n /// <param name=\"hash_prefix\">If non null, the SHA256 hash of downloaded content must match this prefix</param>\n /// <param name=\"progress\">whether or not to display a progress bar to stderr</param>\n /// <exception cref=\"InvalidDataException\">SHA256 hash doesn't match</exception>\n public static void download_url_to_file(string url, string dst, string hash_prefix = null, bool progress = true)\n {\n try {\n Task.Run(async () => {\n await download_url_to_file_async(url, dst, hash_prefix, progress);\n }).Wait();\n } catch (AggregateException ex) {\n throw ex.InnerException;\n }\n }\n\n /// <summary>\n /// Download the url to a file \n /// </summary>\n /// <param name=\"url\">The URL to download</param>\n /// <param name=\"dst\">The file path to download the URL into</param>\n /// <param name=\"cancellationToken\">A cancellation token</param>\n /// <param name=\"hash_prefix\">If non null, the SHA256 hash of downloaded content must match this prefix</param>\n /// <param name=\"progress\">whether or not to display a progress bar to stderr</param>\n /// <exception cref=\"InvalidDataException\">SHA256 hash doesn't match</exception>\n public static async Task download_url_to_file_async(string url, string dst, string hash_prefix = null, bool progress = true, CancellationToken cancellationToken = default)\n {\n try {\n using (var progress_bar = CreateProgressBar(!progress))\n using (var httpClient = new HttpClient())\n using (var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken)) {\n response.EnsureSuccessStatusCode();\n progress_bar.Maximum = response.Content.Headers.ContentLength;\n using (var writer = File.OpenWrite(dst)) {\n byte[] buffer = new byte[64 * 1024];\n if (progress) {\n var reader = await response.Content.ReadAsStreamAsync();\n while (true) {\n int ret = await reader.ReadAsync(buffer, 0, buffer.Length, cancellationToken);\n if (ret == 0) break;\n await writer.WriteAsync(buffer, 0, ret, cancellationToken);\n progress_bar.Value += ret;\n }\n } else {\n await response.Content.CopyToAsync(writer);\n }\n }\n }\n } catch (Exception) {\n if (File.Exists(dst)) {\n File.Delete(dst);\n }\n throw;\n }\n\n string fileHash = GetFileChecksum(dst);\n if (hash_prefix != null && !fileHash.StartsWith(hash_prefix)) {\n throw new InvalidDataException($\"invalid hash value (expected \\\"{hash_prefix}\\\", got \\\"{fileHash}\\\"\");\n }\n }\n\n private static string GetFileChecksum(string path)\n {\n using (SHA256 sha256 = SHA256.Create()) {\n using (var stream = File.OpenRead(path)) {\n var hashValue = sha256.ComputeHash(stream);\n var sb = new StringBuilder();\n foreach (var value in hashValue) {\n sb.Append($\"{value:x2}\");\n }\n return sb.ToString();\n }\n }\n }\n }\n }\n}" }, { "alpha_fraction": 0.5187896490097046, "alphanum_fraction": 0.5192776918411255, "avg_line_length": 38.403846740722656, "blob_id": "6b8b343c12438371835421952aadb89f0dd87a23", "content_id": "f8b7ac7e9721a4464f29703f3f5e8d8e8d143c50", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2049, "license_type": "permissive", "max_line_length": 130, "num_lines": 52, "path": "/src/TorchSharp/Distributions/ExponentialFamily.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Base class for all distributions in the exponential family.\n /// </summary>\n public abstract class ExponentialFamily : Distribution\n {\n protected ExponentialFamily(torch.Generator generator) : base(generator)\n {\n }\n\n protected abstract IList<Tensor> NaturalParams { get; }\n\n protected virtual Tensor LogNormalizer(params Tensor[] parameters)\n {\n throw new NotImplementedException();\n }\n\n protected abstract Tensor MeanCarrierMeasure { get; }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n public override Tensor entropy()\n {\n // Method to compute the entropy using Bregman divergence of the log normalizer.\n using var _ = NewDisposeScope();\n var result = -MeanCarrierMeasure;\n var nparams = NaturalParams.Select(p => p.detach().requires_grad_()).ToArray();\n var lg_normal = LogNormalizer(nparams);\n var gradients = torch.autograd.grad(new Tensor[] { lg_normal.sum() }, nparams, create_graph: true);\n result += lg_normal;\n for (int i = 0; i < gradients.Count; i++) {\n var np = nparams[i];\n var g = gradients[i];\n result -= np * g;\n }\n return result.MoveToOuterDisposeScope();\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5200901627540588, "alphanum_fraction": 0.5263025760650635, "avg_line_length": 48.28395080566406, "blob_id": "ee0304572d954b16c435775b6cf80e6e683f49f2", "content_id": "c8177e0a44874f3490ec41a8f8bba094ff92bed3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 19961, "license_type": "permissive", "max_line_length": 251, "num_lines": 405, "path": "/src/TorchSharp/Optimizers/RMSprop.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\n\n\nnamespace TorchSharp\n{\n using System.Data;\n using System.IO;\n using Modules;\n\n public static partial class torch\n {\n public static partial class optim\n {\n\n /// <summary>\n /// Implements the RMSprop algorithm.\n ///\n /// Proposed by G.Hinton in his course.\n /// https://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize</param>\n /// <param name=\"lr\">Learning rate (default: 1e-2)</param>\n /// <param name=\"eps\">Term added to the denominator to improve numerical stability (default: 1e-8)</param>\n /// <param name=\"alpha\">Smoothing constant (default: 0.99)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"momentum\">Momentum factor (default: 0)</param>\n /// <param name=\"centered\">if true, compute the centered RMSProp, the gradient is normalized by an estimation of its variance</param>\n /// <param name=\"maximize\">Maximize the params based on the objective, instead of minimizing.</param>\n public static RMSProp RMSProp(IEnumerable<Parameter> parameters, double lr = 0.01, double alpha = 0.99, double eps = 1e-8, double weight_decay = 0, double momentum = 0, bool centered = false, bool maximize = false)\n {\n return new RMSProp(parameters, lr, alpha, eps, weight_decay, momentum, centered, maximize);\n }\n\n /// <summary>\n /// Implements the RMSprop algorithm.\n ///\n /// Proposed by G.Hinton in his course.\n /// https://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize</param>\n /// <param name=\"lr\">Learning rate (default: 1e-2)</param>\n /// <param name=\"eps\">Term added to the denominator to improve numerical stability (default: 1e-8)</param>\n /// <param name=\"alpha\">Smoothing constant (default: 0.99)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"momentum\">Momentum factor (default: 0)</param>\n /// <param name=\"centered\">if true, compute the centered RMSProp, the gradient is normalized by an estimation of its variance</param>\n /// <param name=\"maximize\">Maximize the params based on the objective, instead of minimizing.</param>\n public static RMSProp RMSProp(IEnumerable<(string name, Parameter parameter)> parameters, double lr = 0.01, double alpha = 0.99, double eps = 1e-8, double weight_decay = 0, double momentum = 0, bool centered = false, bool maximize = false)\n {\n return new RMSProp(parameters.Select(np => np.parameter), lr, alpha, eps, weight_decay, momentum, centered, maximize);\n }\n\n /// <summary>\n /// Implements the RMSprop algorithm.\n ///\n /// Proposed by G.Hinton in his course.\n /// https://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize</param>\n /// <param name=\"lr\">Learning rate (default: 1e-2)</param>\n /// <param name=\"eps\">Term added to the denominator to improve numerical stability (default: 1e-8)</param>\n /// <param name=\"alpha\">Smoothing constant (default: 0.99)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"momentum\">Momentum factor (default: 0)</param>\n /// <param name=\"centered\">if true, compute the centered RMSProp, the gradient is normalized by an estimation of its variance</param>\n /// <param name=\"maximize\">Maximize the params based on the objective, instead of minimizing.</param>\n public static RMSProp RMSProp(IEnumerable<RMSProp.ParamGroup> parameters, double lr = 0.01, double alpha = 0.99, double eps = 1e-8, double weight_decay = 0, double momentum = 0, bool centered = false, bool maximize = false)\n {\n return new RMSProp(parameters, lr, alpha, eps, weight_decay, momentum, centered, maximize);\n }\n }\n }\n\n namespace Modules\n {\n using static torch.optim;\n\n public class RMSProp : OptimizerHelper, IMomentum\n {\n\n /// <summary>\n /// Implements RMSprop algorithm.\n ///\n /// Proposed by G.Hinton in his course.\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the parameters collection.</param>\n /// <param name=\"lr\">Learning rate</param>\n /// <param name=\"alpha\">Smoothing constant.</param>\n /// <param name=\"momentum\">Momentum factor (default: 0)</param>\n /// <param name=\"eps\">Term added to the denominator to improve numerical stability</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"centered\">if ``True``, compute the centered RMSProp, the gradient is normalized by an estimation of its variance</param>\n /// <param name=\"maximize\">Maximize the params based on the objective, instead of minimizing.</param>\n public RMSProp(IEnumerable<Parameter> parameters, double lr = 1e-3, double alpha = 0.99, double eps = 1e-8, double weight_decay = 0, double momentum = 0.0, bool centered = false, bool maximize = false)\n : this(new ParamGroup[] { new ParamGroup { Parameters = parameters } }, lr, alpha, eps, weight_decay, momentum, centered, maximize)\n {\n }\n\n /// <summary>\n /// Implements RMSprop algorithm.\n ///\n /// Proposed by G.Hinton in his course.\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the parameters collection.</param>\n /// <param name=\"lr\">Learning rate</param>\n /// <param name=\"alpha\">Smoothing constant.</param>\n /// <param name=\"momentum\">Momentum factor (default: 0)</param>\n /// <param name=\"eps\">Term added to the denominator to improve numerical stability</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"centered\">if ``True``, compute the centered RMSProp, the gradient is normalized by an estimation of its variance</param>\n /// <param name=\"maximize\">Maximize the params based on the objective, instead of minimizing.</param>\n public RMSProp(IEnumerable<ParamGroup> parameters, double lr = 1e-3, double alpha = 0.99, double eps = 1e-8, double weight_decay = 0, double momentum = 0.0, bool centered = false, bool maximize = false)\n {\n if (lr < 0) throw new ArgumentException($\"Invalid learning rate: {lr}\");\n if (eps < 0) throw new ArgumentException($\"Invalid ε: {eps}\");\n if (alpha < 0) throw new ArgumentException($\"Invalid alpha: {alpha}\");\n if (momentum < 0.0) throw new ArgumentException($\"Invalid momentum value: {momentum}\");\n if (weight_decay < 0.0) throw new ArgumentException($\"Invalid weight_decay value: {weight_decay}\");\n\n var options = new Options {\n LearningRate = lr,\n InitialLearningRate = lr,\n maximize = maximize,\n eps = eps,\n alpha = alpha,\n momentum = momentum,\n centered = centered,\n weight_decay = weight_decay\n };\n\n _defaults = options;\n _parameter_groups = new List<Modules.ParamGroup>();\n\n foreach (var g in parameters) {\n add_param_group(g);\n }\n }\n\n /// <summary>\n /// Performs a single optimization step (parameter update).\n /// </summary>\n /// <param name=\"closure\">A closure that reevaluates the model and returns the loss. Optional for most optimizers.</param>\n /// <returns></returns>\n public override Tensor step(Func<Tensor> closure = null)\n {\n return _step<ParamGroup>(group => {\n\n var options = group.Options as Options;\n var maximize = options.maximize.Value;\n var momentum = options.momentum.Value;\n var alpha = options.alpha.Value;\n var weight_decay = options.weight_decay.Value;\n var centered = options.centered.Value;\n var eps = options.eps.Value;\n var lr = options.LearningRate.Value;\n\n foreach (var param in group.Parameters) {\n\n var state = (State)_state[param.handle];\n\n var grad = param.grad();\n\n if (grad is null) continue;\n\n if (maximize) grad = -grad;\n\n state.step += 1;\n\n if (weight_decay != 0) {\n grad = grad.add(param, alpha: weight_decay);\n }\n\n state.square_avg.mul_(alpha).addcmul_(grad, grad, value: 1 - alpha);\n\n Tensor avg = null;\n\n if (centered) {\n var grad_avg = state.grad_avg;\n grad_avg.mul_(alpha).add_(grad, alpha: 1 - alpha);\n avg = state.square_avg.addcmul(grad_avg, grad_avg, value: -1).sqrt_().add_(eps);\n } else {\n avg = state.square_avg.sqrt().add_(eps);\n }\n\n if (momentum > 0) {\n var buf = state.momentum_buffer;\n buf.mul_(momentum).addcdiv_(grad, avg);\n param.add_(buf, alpha: -lr);\n } else {\n param.addcdiv_(grad, avg, -lr);\n }\n }\n }, closure);\n }\n\n protected override void Dispose(bool disposing)\n {\n base.Dispose(disposing);\n foreach (var kvp in _state) {\n ((State)kvp.Item2).Dispose();\n }\n _state.Clear();\n }\n\n public sealed class State : OptimizerState, IDisposable\n {\n public long step;\n public Tensor square_avg;\n public Tensor momentum_buffer;\n public Tensor grad_avg;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n private void Dispose(bool disposing)\n {\n if (disposing) {\n momentum_buffer?.Dispose();\n square_avg.Dispose();\n grad_avg?.Dispose();\n }\n }\n\n /// <summary>\n /// Move all the state to the indicated device.\n /// </summary>\n /// <param name=\"device\">The device to move all state to.</param>\n public override void to(Device device)\n {\n square_avg = square_avg.to(device);\n momentum_buffer = momentum_buffer?.to(device);\n grad_avg = grad_avg?.to(device);\n }\n\n /// <summary>\n /// Load the optimizer parameter state from a stream.\n /// </summary>\n /// <param name=\"reader\">A binary reader connected to a stream open for reading.</param>\n public override void LoadStateDict(BinaryReader reader)\n {\n step = reader.ReadInt64();\n square_avg.Load(reader);\n LoadConditionalStateTensor(reader, ref momentum_buffer);\n LoadConditionalStateTensor(reader, ref grad_avg);\n }\n /// <summary>\n /// Save the optimizer parameter state to a stream.\n /// </summary>\n /// <param name=\"writer\">A binary writer connected to a stream open for writing.</param>\n public override void SaveStateDict(BinaryWriter writer)\n {\n writer.Write(this.step);\n square_avg.Save(writer);\n SaveConditionalStateTensor(writer, momentum_buffer);\n SaveConditionalStateTensor(writer, grad_avg);\n }\n\n /// <summary>\n /// Load optimizer parameter state from another optimizer.\n /// </summary>\n /// <param name=\"source\">An optimizer state record.</param>\n public override void LoadStateDict(OptimizerState source)\n {\n var st_state = source as State;\n square_avg.Dispose();\n grad_avg.Dispose();\n momentum_buffer.Dispose();\n\n step = st_state.step;\n square_avg = st_state.square_avg;\n grad_avg = st_state.grad_avg;\n momentum_buffer = st_state.momentum_buffer;\n }\n\n /// <summary>\n /// Useful for tests, allows comparison of one state with another.\n /// </summary>\n /// <param name=\"other\">The other optimizer state</param>\n /// <returns></returns>\n public override bool ApproximatelyEquals(OptimizerState other)\n {\n var rhs = other as State;\n return (rhs is not null) && step == rhs.step &&\n square_avg.allclose(rhs.square_avg) &&\n grad_avg.allclose(rhs.grad_avg) &&\n momentum_buffer.allclose(rhs.momentum_buffer);\n }\n }\n\n /// <summary>\n /// Add a param group to the Optimizer s param_groups.\n /// </summary>\n /// <param name=\"param_group\"></param>\n /// <remarks>This can be useful when fine tuning a pre-trained network as frozen layers can be made trainable and added to the Optimizer as training progresses.</remarks>\n public override void add_param_group(Modules.ParamGroup param_group)\n {\n var def = _defaults as Options;\n if (param_group.Options is null) {\n param_group.Options = new Options();\n }\n\n var opt = param_group.Options as Options;\n\n // Make sure all the options are set.\n if (!opt.maximize.HasValue) opt.maximize = def.maximize;\n if (!opt.LearningRate.HasValue) opt.LearningRate = def.LearningRate;\n if (!opt.momentum.HasValue) opt.momentum = def.momentum;\n if (!opt.eps.HasValue) opt.eps = def.eps;\n if (!opt.alpha.HasValue) opt.alpha = def.alpha;\n if (!opt.weight_decay.HasValue) opt.weight_decay = def.weight_decay;\n if (!opt.centered.HasValue) opt.centered = def.centered;\n\n opt.InitialLearningRate = opt.LearningRate.Value;\n\n _parameter_groups.Add(param_group);\n\n foreach (var p in param_group.Parameters) {\n var state = new State();\n _state[p.Handle] = state;\n state.square_avg = torch.zeros_like(p).DetachFromDisposeScope();\n state.grad_avg = torch.zeros_like(p).DetachFromDisposeScope();\n state.momentum_buffer = torch.zeros_like(p).DetachFromDisposeScope();\n }\n }\n public class Options : Modules.OptimizerOptions\n {\n public bool? maximize;\n public double? momentum;\n public double? alpha;\n public double? eps;\n public double? weight_decay;\n public bool? centered;\n\n /// <summary>\n /// Load optimizer options (param-group hyperparameters) from another optimizer.\n /// </summary>\n /// <param name=\"source\">An optimizer options record.</param>\n public override void LoadStateDict(OptimizerOptions source)\n {\n base.LoadStateDict(source);\n var opts = source as Options;\n maximize = opts.maximize;\n momentum = opts.momentum;\n alpha = opts.alpha;\n weight_decay = opts.weight_decay;\n eps = opts.eps;\n centered = opts.centered;\n }\n\n /// <summary>\n /// Load the optimizer options (param-group hyperparameters) from a stream.\n /// </summary>\n /// <param name=\"reader\">A binary reader connected to a stream open for reading.</param>\n public override void LoadStateDict(BinaryReader reader)\n {\n base.LoadStateDict(reader);\n maximize = reader.ReadBoolean();\n momentum = reader.ReadDouble();\n alpha = reader.ReadDouble();\n eps = reader.ReadDouble();\n weight_decay = reader.ReadDouble();\n centered = reader.ReadBoolean();\n }\n\n /// <summary>\n /// Save the optimizer options (param-group hyperparameters) to a stream.\n /// </summary>\n /// <param name=\"writer\">A binary writer connected to a stream open for writing.</param>\n public override void SaveStateDict(BinaryWriter writer)\n {\n base.SaveStateDict(writer);\n writer.Write(maximize.Value);\n writer.Write(momentum.Value);\n writer.Write(alpha.Value);\n writer.Write(eps.Value);\n writer.Write(weight_decay.Value);\n writer.Write(centered.Value);\n }\n }\n\n public class ParamGroup : ParamGroup<Options>, IMomentum\n {\n public ParamGroup() { }\n\n public ParamGroup(IEnumerable<Parameter> parameters, Options options) : base(parameters, options) { }\n\n public ParamGroup(IEnumerable<Parameter> parameters, double lr = 1e-3, double eps = 1e-8, double alpha = 0.99, double weight_decay = 0, double momentum = 0.0, bool centered = false)\n : base(parameters, new RMSProp.Options { LearningRate = lr, eps = eps, alpha = alpha, weight_decay = weight_decay, momentum = momentum, centered = centered })\n {\n }\n\n public double Momentum { get => Options.momentum.Value; set => Options.momentum = value; }\n }\n\n public double Momentum { get => (_defaults as Options).momentum.Value; set => (_defaults as Options).momentum = value; }\n }\n }\n}\n" }, { "alpha_fraction": 0.6516147255897522, "alphanum_fraction": 0.6612610220909119, "avg_line_length": 28.315574645996094, "blob_id": "10a535ed36e7806d532005171fa9e73b874ade3a", "content_id": "388f7594dfc04ae6a47cb3f648f611be5871f3d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7153, "license_type": "permissive", "max_line_length": 142, "num_lines": 244, "path": "/src/Native/LibTorchSharp/THSModule.cpp", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#include \"THSNN.h\"\n\n#include <torch/nn/init.h>\n\n// General Module functions\n\nint THSNN_Module_is_training(NNModule module)\n{\n return (*module)->is_training();\n}\n\nvoid THSNN_Module_train(NNModule module, bool on)\n{\n (*module)->train(on);\n}\n\nconst char* THSNN_Module_name(const NNModule module)\n{\n return make_sharable_string((*module)->name());\n}\n\nvoid THSNN_Module_zero_grad(const NNModule module)\n{\n (*module)->zero_grad();\n}\n\nvoid THSNN_Module_to_device(NNModule module, int64_t device, int64_t index)\n{\n c10::DeviceType dev = c10::kCPU;\n if (device == 1)\n dev = c10::kCUDA;\n (*module)->to(torch::Device(dev, index));\n}\n\nvoid THSNN_Module_to_dtype(NNModule module, int8_t dtype)\n{\n (*module)->to((at::ScalarType)dtype);\n}\n\nvoid THSNN_Module_to_device_dtype(NNModule module, int8_t dtype, int64_t device, int64_t index)\n{\n c10::DeviceType dev = c10::kCPU;\n if (device == 1)\n dev = c10::kCUDA;\n (*module)->to(torch::Device(dev, index), (at::ScalarType)dtype);\n}\n\nvoid THSNN_Module_dispose(const NNModule module)\n{\n delete module; // NOTE: this only deletes the shared_ptr\n}\n\nvoid THSNN_AnyModule_dispose(const NNAnyModule module)\n{\n delete module; // NOTE: this only deletes the shared_ptr\n}\n\n//NNModule THSNN_AnyModule_get(const NNAnyModule module)\n//{\n//\treturn new std::shared_ptr< torch::nn::Module>(&( (*module)->get<torch::nn::Module>()));\n//}\n\n// Sub-module handling, parameters, etc.\n\nvoid THSNN_Module_register_module(const NNModule module, const char* name, const NNModule submodule)\n{\n CATCH(\n (*module)->register_module(name, *submodule);\n );\n}\n\nvoid THSNN_Module_register_parameter(const NNModule module, const char* name, const Tensor tensor, bool requires_grad)\n{\n CATCH(\n (*module)->register_parameter(name, (tensor == nullptr) ? at::Tensor() : *tensor, requires_grad);\n );\n}\n\nvoid THSNN_Module_register_buffer(const NNModule module, const char* name, const Tensor tensor)\n{\n CATCH(\n (*module)->register_buffer(name, *tensor);\n );\n}\n\nint THSNN_Module_has_parameter(const NNModule module, const char* name)\n{\n CATCH_RETURN(int, 0, (*module)->named_parameters().contains(name));\n}\n\nTensor THSNN_Module_get_parameter(const NNModule module, const char* name)\n{\n CATCH_TENSOR(*(*module)->named_parameters().find(name));\n}\n\nvoid THSNN_Module_get_parameters(const NNModule module, Tensor* (*allocator1)(size_t length), bool recurse)\n{\n auto parameters = (*module)->parameters(recurse);\n Tensor* result1 = allocator1(parameters.size());\n\n for (size_t i = 0; i < parameters.size(); i++)\n {\n result1[i] = ResultTensor(parameters[i]);\n }\n}\n\nvoid THSNN_Module_get_named_parameters(const NNModule module, Tensor* (*allocator1)(size_t length), const char** (*allocator2)(size_t length))\n{\n auto parameters = (*module)->named_parameters();\n Tensor* result1 = allocator1(parameters.size());\n const char** result2 = allocator2(parameters.size());\n\n for (size_t i = 0; i < parameters.size(); i++)\n {\n result1[i] = ResultTensor(parameters[i].value());\n result2[i] = make_sharable_string(parameters[i].key());\n }\n}\n\nvoid THSNN_Module_get_named_buffers(const NNModule module, Tensor* (*allocator1)(size_t length), const char** (*allocator2)(size_t length))\n{\n auto buffers = (*module)->named_buffers();\n Tensor* result1 = allocator1(buffers.size());\n const char** result2 = allocator2(buffers.size());\n\n for (size_t i = 0; i < buffers.size(); i++)\n {\n result1[i] = ResultTensor(buffers[i].value());\n result2[i] = make_sharable_string(buffers[i].key());\n }\n}\n\nvoid THSNN_Module_get_named_children(const NNModule module, NNModule* (*allocator1)(size_t length), const char** (*allocator2)(size_t length))\n{\n auto buffers = (*module)->named_children();\n NNModule* result1 = allocator1(buffers.size());\n const char** result2 = allocator2(buffers.size());\n\n for (size_t i = 0; i < buffers.size(); i++)\n {\n result1[i] = new std::shared_ptr<torch::nn::Module>(buffers[i].value());\n result2[i] = make_sharable_string(buffers[i].key());\n }\n}\n\nvoid THSNN_Module_get_named_modules(const NNModule module, NNModule* (*allocator1)(size_t length), const char** (*allocator2)(size_t length))\n{\n auto buffers = (*module)->named_modules();\n NNModule* result1 = allocator1(buffers.size());\n const char** result2 = allocator2(buffers.size());\n\n for (size_t i = 0; i < buffers.size(); i++)\n {\n result1[i] = new std::shared_ptr<torch::nn::Module>(buffers[i].value());\n result2[i] = make_sharable_string(buffers[i].key());\n }\n}\n\nlong THSNN_Module_children_size(const NNModule module)\n{\n return (*module)->children().size();\n}\n\nNNModule THSNN_Module_child(const NNModule module, const int index)\n{\n return new std::shared_ptr<torch::nn::Module>((*module)->children()[index]);\n}\n\n\n// Save and restore\n\nNNModule THSNN_Module_load(const char* location)\n{\n CATCH_RETURN_NNModule(\n auto module = new torch::nn::Module();\n auto input = torch::serialize::InputArchive();\n\n input.load_from(location);\n module->load(input);\n return new std::shared_ptr<torch::nn::Module>(module);\n );\n}\n\nvoid THSNN_Module_save(const NNModule module, const char* location)\n{\n CATCH(\n auto output = torch::serialize::OutputArchive();\n\n (*module)->save(output);\n output.save_to(location);\n );\n}\n\n\n// Wrapper class used to enable .NET definitions ot new modules describing parameters and with delegates to implement forward function\nclass CustomModule : public torch::nn::Module\n{\npublic:\n CustomModule(\n const char* name,\n Tensor(*forward)(Tensor))\n : torch::nn::Module(name), _forward(forward)\n {\n }\n\n Tensor(*_forward)(Tensor);\n\n at::Tensor forward(at::Tensor input) {\n return *(*_forward)(&input);\n }\n\n};\n\nNNModule THSNN_custom_module(const char* name,\n Tensor(*forward)(Tensor),\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto mod = new CustomModule(name, forward);\n\n // Keep a boxed version of the module in case we add it to a Sequential later (the C++ templating means\n // a Module can only be boxed to AnyModule at the point its static type is known).\n if (outAsAnyModule != nullptr)\n {\n auto modShared = new std::shared_ptr<CustomModule>(mod);\n auto wrapped = std::make_shared<torch::nn::AnyModule>(torch::nn::ModuleHolder<CustomModule>(*modShared));\n *outAsAnyModule = new std::shared_ptr<torch::nn::AnyModule>(wrapped);\n }\n res = new std::shared_ptr<torch::nn::Module>((torch::nn::Module*)mod);\n );\n}\n\n#if 0\nstruct TORCH_API ModuleBackWardHook1 : public torch::autograd::FunctionPostHook {\n\n virtual ~ModuleBackWardHook1() { }\n virtual torch::autograd::variable_list operator()(\n const torch::autograd::variable_list& outputs /* grad_inputs */,\n const torch::autograd::variable_list& inputs /* grad_outputs */)\n {\n } \n};\n#endif\n" }, { "alpha_fraction": 0.5029027462005615, "alphanum_fraction": 0.5199840664863586, "avg_line_length": 50.30430221557617, "blob_id": "00c0106fa7e715998f6f792e190e968e9c8aaaea", "content_id": "647e362047e22d2ef451665fb1c6851b226b5c2d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 47713, "license_type": "permissive", "max_line_length": 193, "num_lines": 930, "path": "/src/TorchAudio/Wav2Vec2Models.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchaudio,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/audio/blob/76fca37ac8941b72a509a6e58d623632efe04543/torchaudio/models/wav2vec2/model.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/audio/blob/main/LICENSE\n//\n\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\nusing TorchSharp.Modules;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n public static partial class models\n {\n /// <summary>\n /// Build a custom Wav2Vec2Model\n /// \n /// Note:\n /// The \"feature extractor\" below corresponds to\n /// `ConvFeatureExtractionModel` https://github.com/pytorch/fairseq/blob/dd3bd3c0497ae9a7ae7364404a6b0a4c501780b3/fairseq/models/wav2vec/wav2vec2.py#L736\n /// in the original ``fairseq`` implementation.\n /// This is referred as \"(convolutional) feature encoder\" in the *wav2vec 2.0*\n /// [:footcite:`baevski2020wav2vec`] paper.\n /// \n /// The \"encoder\" below corresponds to `TransformerEncoder` https://github.com/pytorch/fairseq/blob/dd3bd3c0497ae9a7ae7364404a6b0a4c501780b3/fairseq/models/wav2vec/wav2vec2.py#L817,\n /// and this is referred as \"Transformer\" in the paper.\n /// </summary>\n /// <param name=\"extractor_mode\">Operation mode of feature extractor.\n /// Valid values are ``\"group_norm\"`` or ``\"layer_norm\"``.\n /// If ``\"group_norm\"``, then a single normalization is applied\n /// in the first convolution block. Otherwise, all the convolution\n /// blocks will have layer normalization.\n /// \n /// This option corresponds to ``extractor_mode`` from ``fairseq``.\n /// </param>\n /// <param name=\"extractor_conv_layer_config\">\n /// Configuration of convolution layers in feature extractor.\n /// List of convolution configuration,\n /// i.e. ``[(output_channel, kernel_size, stride), ...]``\n /// \n /// If ``None`` is provided, then the following default value is used.\n /// \n /// .. code-block:: python\n /// \n /// [\n /// (512, 10, 5),\n /// (512, 3, 2),\n /// (512, 3, 2),\n /// (512, 3, 2),\n /// (512, 3, 2),\n /// (512, 2, 2),\n /// (512, 2, 2),\n /// ]\n /// \n /// This option corresponds to ``conv_feature_layers`` from ``fairseq``.\n /// </param>\n /// <param name=\"extractor_conv_bias\">\n /// Whether to include bias term to each convolution operation.\n /// </param>\n /// This option corresponds to ``conv_bias`` from ``fairseq``.\n /// <param name=\"encoder_embed_dim\">\n /// The dimension of embedding in encoder.\n /// \n /// This option corresponds to ``encoder_embed_dim`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_projection_dropout\">\n /// The dropout probability applied after the input feature is projected\n /// to ``encoder_embed_dim``.\n /// \n /// This option corresponds to ``dropout_input`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_pos_conv_kernel\">\n /// The kernel size of convolutional positional embeddings.\n /// \n /// This option corresponds to ``conv_pos`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_pos_conv_groups\">\n /// The number of groups of convolutional positional embeddings.\n /// \n /// This option corresponds to ``conv_pos_groups`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_num_layers\">\n /// The number of self attention layers in transformer block.\n /// \n /// This option corresponds to ``encoder_layers`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_num_heads\">\n /// The number of heads in self attention layers.\n /// \n /// This option corresponds to ``encoder_attention_heads`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_attention_dropout\">\n /// The dropout probability applied after softmax in self-attention layer.\n /// \n /// This option corresponds to ``attention_dropout`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_ff_interm_features\">\n /// The dimension of hidden features in feed forward layer.\n /// \n /// This option corresponds to ``encoder_ffn_embed_dim`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_ff_interm_dropout\">\n /// The dropout probability applied in feedforward layer.\n /// \n /// This option correspinds to ``activation_dropout`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_dropout\">\n /// The dropout probability applied at the end of feed forward layer.\n /// \n /// This option corresponds to ``dropout`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_layer_norm_first\">\n /// Control the order of layer norm in transformer layer and each encoder layer.\n /// If True, in transformer layer, layer norm is applied before features are fed\n /// to encoder layers. In encoder layer, two layer norms are applied before and after\n /// self attention.\n /// If False, in transformer layer, layer norm is applied after features are fed\n /// to encoder layers. In encoder layer, two layer norms are applied after self\n /// attention, before and after feed forward.\n /// \n /// This option corresponds to ``layer_norm_first`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_layer_drop\">\n /// Probability to drop each encoder layer during training.\n /// \n /// This option corresponds to ``layerdrop`` from ``fairseq``.\n /// </param>\n /// <param name=\"aux_num_out\">\n /// When provided, attach an extra linear layer on top of encoder, which can be\n /// used for fine-tuning.\n /// </param>\n /// <returns>\n /// The resulting model.\n /// </returns>\n public static Wav2Vec2Model wav2vec2_model(\n FeatureExtractorNormMode extractor_mode,\n long[][]? extractor_conv_layer_config,\n bool extractor_conv_bias,\n int encoder_embed_dim,\n double encoder_projection_dropout,\n int encoder_pos_conv_kernel,\n int encoder_pos_conv_groups,\n int encoder_num_layers,\n int encoder_num_heads,\n double encoder_attention_dropout,\n int encoder_ff_interm_features,\n double encoder_ff_interm_dropout,\n double encoder_dropout,\n bool encoder_layer_norm_first,\n double encoder_layer_drop,\n long? aux_num_out)\n {\n // Overriding the signature so that the return type is correct on Sphinx\n if (extractor_conv_layer_config == null) {\n extractor_conv_layer_config = new long[][] {\n new long[] { 512, 10, 5 },\n\n new long[] { 512, 3, 2 },\n new long[] { 512, 3, 2 },\n new long[] { 512, 3, 2 },\n new long[] { 512, 3, 2 },\n\n new long[] { 512, 2, 2 },\n new long[] { 512, 2, 2 },\n };\n }\n\n var feature_extractor = Wav2Vec2Model._get_feature_extractor(\n extractor_mode, extractor_conv_layer_config, extractor_conv_bias);\n\n var encoder = Wav2Vec2Model._get_encoder(\n in_features: extractor_conv_layer_config[extractor_conv_layer_config.Length - 1][0],\n embed_dim: encoder_embed_dim,\n dropout_input: encoder_projection_dropout,\n pos_conv_kernel: encoder_pos_conv_kernel,\n pos_conv_groups: encoder_pos_conv_groups,\n num_layers: encoder_num_layers,\n num_heads: encoder_num_heads,\n attention_dropout: encoder_attention_dropout,\n ff_interm_features: encoder_ff_interm_features,\n ff_interm_dropout: encoder_ff_interm_dropout,\n dropout: encoder_dropout,\n layer_norm_first: encoder_layer_norm_first,\n layer_drop: encoder_layer_drop);\n Module<Tensor, Tensor>? aux = null;\n if (aux_num_out != null) {\n aux = torch.nn.Linear(inputSize: encoder_embed_dim, outputSize: aux_num_out.Value);\n }\n return new Wav2Vec2Model(\"Wav2Vec2Model\", feature_extractor, encoder, aux);\n }\n\n /// <summary>\n /// Build Wav2Vec2Model with \"base\" architecture from *wav2vec 2.0* [:footcite:`baevski2020wav2vec`]\n /// </summary>\n /// <param name=\"encoder_projection_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_attention_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_ff_interm_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_layer_drop\">See `wav2vec2_model`.</param>\n /// <param name=\"aux_num_out\">See `wav2vec2_model`.</param>\n /// <returns>\n /// The resulting model.\n /// </returns>\n public static Wav2Vec2Model wav2vec2_base(\n double encoder_projection_dropout = 0.1,\n double encoder_attention_dropout = 0.1,\n double encoder_ff_interm_dropout = 0.1,\n double encoder_dropout = 0.1,\n double encoder_layer_drop = 0.1,\n long? aux_num_out = null)\n {\n // Overriding the signature so that the return type is correct on Sphinx\n return wav2vec2_model(\n extractor_mode: FeatureExtractorNormMode.group_norm,\n extractor_conv_layer_config: null,\n extractor_conv_bias: false,\n encoder_embed_dim: 768,\n encoder_projection_dropout: encoder_projection_dropout,\n encoder_pos_conv_kernel: 128,\n encoder_pos_conv_groups: 16,\n encoder_num_layers: 12,\n encoder_num_heads: 12,\n encoder_attention_dropout: encoder_attention_dropout,\n encoder_ff_interm_features: 3072,\n encoder_ff_interm_dropout: encoder_ff_interm_dropout,\n encoder_dropout: encoder_dropout,\n encoder_layer_norm_first: false,\n encoder_layer_drop: encoder_layer_drop,\n aux_num_out: aux_num_out);\n }\n\n /// <summary>\n /// Build Wav2Vec2Model with \"large\" architecture from *wav2vec 2.0* [:footcite:`baevski2020wav2vec`]\n /// </summary>\n /// <param name=\"encoder_projection_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_attention_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_ff_interm_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_layer_drop\">See `wav2vec2_model`.</param>\n /// <param name=\"aux_num_out\">See `wav2vec2_model`.</param>\n /// <returns>\n /// The resulting model.\n /// </returns>\n public static Wav2Vec2Model wav2vec2_large(\n double encoder_projection_dropout = 0.1,\n double encoder_attention_dropout = 0.1,\n double encoder_ff_interm_dropout = 0.1,\n double encoder_dropout = 0.1,\n double encoder_layer_drop = 0.1,\n long? aux_num_out = null)\n {\n // Overriding the signature so that the return type is correct on Sphinx\n return wav2vec2_model(\n extractor_mode: FeatureExtractorNormMode.group_norm,\n extractor_conv_layer_config: null,\n extractor_conv_bias: false,\n encoder_embed_dim: 1024,\n encoder_projection_dropout: encoder_projection_dropout,\n encoder_pos_conv_kernel: 128,\n encoder_pos_conv_groups: 16,\n encoder_num_layers: 24,\n encoder_num_heads: 16,\n encoder_attention_dropout: encoder_attention_dropout,\n encoder_ff_interm_features: 4096,\n encoder_ff_interm_dropout: encoder_ff_interm_dropout,\n encoder_dropout: encoder_dropout,\n encoder_layer_norm_first: false,\n encoder_layer_drop: encoder_layer_drop,\n aux_num_out: aux_num_out);\n }\n\n /// <summary>\n /// Build Wav2Vec2Model with \"large lv-60k\" architecture from *wav2vec 2.0* [:footcite:`baevski2020wav2vec`]\n /// </summary>\n /// <param name=\"encoder_projection_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_attention_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_ff_interm_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_layer_drop\">See `wav2vec2_model`.</param>\n /// <param name=\"aux_num_out\">See `wav2vec2_model`.</param>\n /// <returns>\n /// The resulting model.\n /// </returns>\n public static Wav2Vec2Model wav2vec2_large_lv60k(\n double encoder_projection_dropout = 0.1,\n double encoder_attention_dropout = 0.0,\n double encoder_ff_interm_dropout = 0.1,\n double encoder_dropout = 0.0,\n double encoder_layer_drop = 0.1,\n long? aux_num_out = null)\n {\n // Overriding the signature so that the return type is correct on Sphinx\n return wav2vec2_model(\n extractor_mode: FeatureExtractorNormMode.layer_norm,\n extractor_conv_layer_config: null,\n extractor_conv_bias: true,\n encoder_embed_dim: 1024,\n encoder_projection_dropout: encoder_projection_dropout,\n encoder_pos_conv_kernel: 128,\n encoder_pos_conv_groups: 16,\n encoder_num_layers: 24,\n encoder_num_heads: 16,\n encoder_attention_dropout: encoder_attention_dropout,\n encoder_ff_interm_features: 4096,\n encoder_ff_interm_dropout: encoder_ff_interm_dropout,\n encoder_dropout: encoder_dropout,\n encoder_layer_norm_first: true,\n encoder_layer_drop: encoder_layer_drop,\n aux_num_out: aux_num_out);\n }\n\n /// <summary>\n /// Build HuBERT model with \"base\" architecture from *HuBERT* [:footcite:`hsu2021hubert`]\n /// </summary>\n /// <param name=\"encoder_projection_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_attention_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_ff_interm_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_layer_drop\">See `wav2vec2_model`.</param>\n /// <param name=\"aux_num_out\">See `wav2vec2_model`.</param>\n /// <returns>\n /// The resulting model.\n /// </returns>\n public static Wav2Vec2Model hubert_base(\n double encoder_projection_dropout = 0.1,\n double encoder_attention_dropout = 0.1,\n double encoder_ff_interm_dropout = 0.0,\n double encoder_dropout = 0.1,\n double encoder_layer_drop = 0.05,\n long? aux_num_out = null)\n {\n // Overriding the signature so that the return type is correct on Sphinx\n return wav2vec2_model(\n extractor_mode: FeatureExtractorNormMode.group_norm,\n extractor_conv_layer_config: null,\n extractor_conv_bias: false,\n encoder_embed_dim: 768,\n encoder_projection_dropout: encoder_projection_dropout,\n encoder_pos_conv_kernel: 128,\n encoder_pos_conv_groups: 16,\n encoder_num_layers: 12,\n encoder_num_heads: 12,\n encoder_attention_dropout: encoder_attention_dropout,\n encoder_ff_interm_features: 3072,\n encoder_ff_interm_dropout: encoder_ff_interm_dropout,\n encoder_dropout: encoder_dropout,\n encoder_layer_norm_first: false,\n encoder_layer_drop: encoder_layer_drop,\n aux_num_out: aux_num_out);\n }\n\n /// <summary>\n /// Build HuBERT model with \"large\" architecture from *HuBERT* [:footcite:`hsu2021hubert`]\n /// </summary>\n /// <param name=\"encoder_projection_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_attention_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_ff_interm_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_layer_drop\">See `wav2vec2_model`.</param>\n /// <param name=\"aux_num_out\">See `wav2vec2_model`.</param>\n /// <returns>\n /// The resulting model.\n /// </returns>\n public static Wav2Vec2Model hubert_large(\n double encoder_projection_dropout = 0.0,\n double encoder_attention_dropout = 0.0,\n double encoder_ff_interm_dropout = 0.0,\n double encoder_dropout = 0.0,\n double encoder_layer_drop = 0.0,\n long? aux_num_out = null)\n {\n // Overriding the signature so that the return type is correct on Sphinx\n return wav2vec2_model(\n extractor_mode: FeatureExtractorNormMode.layer_norm,\n extractor_conv_layer_config: null,\n extractor_conv_bias: false,\n encoder_embed_dim: 1024,\n encoder_projection_dropout: encoder_projection_dropout,\n encoder_pos_conv_kernel: 128,\n encoder_pos_conv_groups: 16,\n encoder_num_layers: 24,\n encoder_num_heads: 16,\n encoder_attention_dropout: encoder_attention_dropout,\n encoder_ff_interm_features: 4096,\n encoder_ff_interm_dropout: encoder_ff_interm_dropout,\n encoder_dropout: encoder_dropout,\n encoder_layer_norm_first: true,\n encoder_layer_drop: encoder_layer_drop,\n aux_num_out: aux_num_out);\n }\n\n /// <summary>\n /// Build HuBERT model with \"extra large\" architecture from *HuBERT* [:footcite:`hsu2021hubert`]\n /// </summary>\n /// <param name=\"encoder_projection_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_attention_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_ff_interm_dropout\">See `wav2vec2_model`.</param>\n /// <param name=\"encoder_layer_drop\">See `wav2vec2_model`.</param>\n /// <param name=\"aux_num_out\">See `wav2vec2_model`.</param>\n /// <returns>\n /// The resulting model.\n /// </returns>\n public static Wav2Vec2Model hubert_xlarge(\n double encoder_projection_dropout = 0.0,\n double encoder_attention_dropout = 0.0,\n double encoder_ff_interm_dropout = 0.0,\n double encoder_dropout = 0.0,\n double encoder_layer_drop = 0.0,\n long? aux_num_out = null)\n {\n // Overriding the signature so that the return type is correct on Sphinx\n return wav2vec2_model(\n extractor_mode: FeatureExtractorNormMode.layer_norm,\n extractor_conv_layer_config: null,\n extractor_conv_bias: false,\n encoder_embed_dim: 1280,\n encoder_projection_dropout: encoder_projection_dropout,\n encoder_pos_conv_kernel: 128,\n encoder_pos_conv_groups: 16,\n encoder_num_layers: 48,\n encoder_num_heads: 16,\n encoder_attention_dropout: encoder_attention_dropout,\n encoder_ff_interm_features: 5120,\n encoder_ff_interm_dropout: encoder_ff_interm_dropout,\n encoder_dropout: encoder_dropout,\n encoder_layer_norm_first: true,\n encoder_layer_drop: encoder_layer_drop,\n aux_num_out: aux_num_out);\n }\n\n /// <summary>\n /// Build a custom HuBERTPretrainModel for training from scratch\n /// \n /// Note:\n /// The \"feature extractor\" below corresponds to\n /// `ConvFeatureExtractionModel` https://github.com/pytorch/fairseq/blob/dd3bd3c0497ae9a7ae7364404a6b0a4c501780b3/fairseq/models/wav2vec/wav2vec2.py#L736\n /// in the original ``fairseq`` implementation.\n /// This is referred as \"(convolutional) feature encoder\" in the *wav2vec 2.0*\n /// [:footcite:`baevski2020wav2vec`] paper.\n /// \n /// The \"encoder\" below corresponds to `TransformerEncoder` https://github.com/pytorch/fairseq/blob/dd3bd3c0497ae9a7ae7364404a6b0a4c501780b3/fairseq/models/wav2vec/wav2vec2.py#L817,\n /// and this is referred as \"Transformer\" in the paper.\n /// </summary>\n /// <param name=\"extractor_mode\">\n /// Operation mode of feature extractor.\n /// Valid values are ``\"group_norm\"`` or ``\"layer_norm\"``.\n /// If ``\"group_norm\"``, then a single normalization is applied\n /// in the first convolution block. Otherwise, all the convolution\n /// blocks will have layer normalization.\n /// \n /// This option corresponds to ``extractor_mode`` from ``fairseq``.\n /// </param>\n /// <param name=\"extractor_conv_layer_config\">\n /// Configuration of convolution layers in feature extractor.\n /// List of convolution configuration,\n /// i.e. ``[(output_channel, kernel_size, stride), ...]``\n /// \n /// If ``None`` is provided, then the following default value is used.\n /// \n /// .. code-block:: python\n /// \n /// [\n /// (512, 10, 5),\n /// (512, 3, 2),\n /// (512, 3, 2),\n /// (512, 3, 2),\n /// (512, 3, 2),\n /// (512, 2, 2),\n /// (512, 2, 2),\n /// ]\n /// \n /// This option corresponds to ``conv_feature_layers`` from ``fairseq``.\n /// </param>\n /// <param name=\"extractor_conv_bias\">\n /// Whether to include bias term to each convolution operation.\n /// \n /// This option corresponds to ``conv_bias`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_embed_dim\">\n /// The dimension of embedding in encoder.\n /// \n /// This option corresponds to ``encoder_embed_dim`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_projection_dropout\">\n /// The dropout probability applied after the input feature is projected\n /// to ``encoder_embed_dim``.\n /// \n /// This option corresponds to ``dropout_input`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_pos_conv_kernel\">\n /// The kernel size of convolutional positional embeddings.\n /// \n /// This option corresponds to ``conv_pos`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_pos_conv_groups\">\n /// The number of groups of convolutional positional embeddings.\n /// \n /// This option corresponds to ``conv_pos_groups`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_num_layers\">\n /// The number of self attention layers in transformer block.\n /// \n /// This option corresponds to ``encoder_layers`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_num_heads\">\n /// The number of heads in self attention layers.\n /// \n /// This option corresponds to ``encoder_attention_heads`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_attention_dropout\">\n /// The dropout probability applied after softmax in self-attention layer.\n /// \n /// This option corresponds to ``attention_dropout`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_ff_interm_features\">\n /// The dimension of hidden features in feed forward layer.\n /// \n /// This option corresponds to ``encoder_ffn_embed_dim`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_ff_interm_dropout\">\n /// The dropout probability applied in feedforward layer.\n /// \n /// This option correspinds to ``activation_dropout`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_dropout\">\n /// The dropout probability applied at the end of feed forward layer.\n /// \n /// This option corresponds to ``dropout`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_layer_norm_first\">\n /// Control the order of layer norm in transformer layer and each encoder layer.\n /// If True, in transformer layer, layer norm is applied before features are fed\n /// to encoder layers. In encoder layer, two layer norms are applied before and after\n /// self attention.\n /// If False, in transformer layer, layer norm is applied after features are fed\n /// to encoder layers. In encoder layer, two layer norms are applied after self\n /// attention, before and after feed forward.\n /// \n /// This option corresponds to ``layer_norm_first`` from ``fairseq``.\n /// </param>\n /// <param name=\"encoder_layer_drop\">\n /// Probability to drop each encoder layer during training.\n /// \n /// This option corresponds to ``layerdrop`` from ``fairseq``.\n /// </param>\n /// <param name=\"mask_prob\">\n /// Probability for each token to be chosen as start of the span to be masked. this will be multiplied by\n /// number of timesteps divided by length of mask span to mask approximately this percentage of all elements.\n /// However due to overlaps, the actual number will be smaller (unless no_overlap is True).\n /// \n /// This option corresponds to ``mask_prob`` from ``fairseq``.\n /// </param>\n /// <param name=\"mask_selection\">\n /// How to choose the mask length. Options: [``static``, ``uniform``, ``normal``, ``poisson``].\n /// \n /// This option corresponds to ``mask_selection`` from ``fairseq``.\n /// </param>\n /// <param name=\"mask_other\">\n /// Secondary mask argument (used for more complex distributions).\n /// \n /// This option corresponds to ``mask_other`` from ``fairseq``.\n /// </param>\n /// <param name=\"mask_length\">\n /// The lengths of the mask.\n /// \n /// This option corresponds to ``mask_length`` from ``fairseq``.\n /// </param>\n /// <param name=\"no_mask_overlap\">\n /// Whether to allow masks to overlap.\n /// \n /// This option corresponds to ``no_mask_overlap`` from ``fairseq``.\n /// </param>\n /// <param name=\"mask_min_space\">\n /// Minimum space between spans (if no overlap is enabled).\n /// \n /// This option corresponds to ``mask_min_space`` from ``fairseq``.\n /// </param>\n /// <param name=\"mask_channel_prob\">\n /// The probability of replacing a feature with 0.\n /// \n /// This option corresponds to ``mask_channel_prob`` from ``fairseq``.\n /// </param>\n /// <param name=\"mask_channel_selection\">\n /// How to choose the mask length for channel masking. Options: [``static``, ``uniform``, ``normal``, ``poisson``].\n /// \n /// This option corresponds to ``mask_channel_selection`` from ``fairseq``.\n /// </param>\n /// <param name=\"mask_channel_other\">\n /// Secondary mask argument for channel masking(used for more complex distributions).\n /// \n /// This option corresponds to ``mask_channel_other`` from ``fairseq``.\n /// </param>\n /// <param name=\"mask_channel_length\">\n /// Minimum space between spans (if no overlap is enabled) for channel masking.\n /// \n /// This option corresponds to ``mask_channel_length`` from ``fairseq``.\n /// </param>\n /// <param name=\"no_mask_channel_overlap\">\n /// Whether to allow channel masks to overlap.\n /// \n /// This option corresponds to ``no_mask_channel_overlap`` from ``fairseq``.\n /// </param>\n /// <param name=\"mask_channel_min_space\">\n /// Minimum space between spans for channel masking(if no overlap is enabled).\n /// \n /// This option corresponds to ``mask_channel_min_space`` from ``fairseq``.\n /// </param>\n /// <param name=\"skip_masked\">\n /// If True, skip computing losses over masked frames.\n /// \n /// This option corresponds to ``skip_masked`` from ``fairseq``.\n /// </param>\n /// <param name=\"skip_nomask\">\n /// If True, skip computing losses over unmasked frames.\n /// \n /// This option corresponds to ``skip_nomask`` from ``fairseq``.\n /// </param>\n /// <param name=\"num_classes\">\n /// The number of classes in the labels.\n /// </param>\n /// <param name=\"final_dim\">\n /// Project final representations and targets to `final_dim`.\n /// \n /// This option corresponds to ``final_dim`` from ``fairseq``.\n /// </param>\n /// <param name=\"feature_grad_mult\">\n /// The factor to scale the convolutional feature extraction layer gradients by.\n /// The scale factor will not affect the forward pass.\n /// \n /// This option corresponds to ``feature_grad_mult`` from ``fairseq``.\n /// </param>\n /// <returns>\n /// The resulting model.\n /// </returns>\n public static HuBERTPretrainModel hubert_pretrain_model(\n FeatureExtractorNormMode extractor_mode,\n long[][]? extractor_conv_layer_config,\n bool extractor_conv_bias,\n int encoder_embed_dim,\n double encoder_projection_dropout,\n int encoder_pos_conv_kernel,\n int encoder_pos_conv_groups,\n int encoder_num_layers,\n int encoder_num_heads,\n double encoder_attention_dropout,\n int encoder_ff_interm_features,\n double encoder_ff_interm_dropout,\n double encoder_dropout,\n bool encoder_layer_norm_first,\n double encoder_layer_drop,\n double mask_prob,\n string mask_selection,\n double mask_other,\n int mask_length,\n bool no_mask_overlap,\n int mask_min_space,\n double mask_channel_prob,\n string mask_channel_selection,\n double mask_channel_other,\n long mask_channel_length,\n bool no_mask_channel_overlap,\n int mask_channel_min_space,\n bool skip_masked,\n bool skip_nomask,\n long num_classes,\n int final_dim,\n double? feature_grad_mult)\n {\n // Overriding the signature so that the return type is correct on Sphinx\n if (extractor_conv_layer_config == null) {\n extractor_conv_layer_config = new long[][] {\n new long[] { 512, 10, 5 },\n\n new long[] { 512, 3, 2 },\n new long[] { 512, 3, 2 },\n new long[] { 512, 3, 2 },\n new long[] { 512, 3, 2 },\n\n new long[] { 512, 2, 2 },\n new long[] { 512, 2, 2 },\n };\n }\n\n var feature_extractor = Wav2Vec2Model._get_feature_extractor(\n extractor_mode, extractor_conv_layer_config, extractor_conv_bias);\n var encoder = Wav2Vec2Model._get_encoder(\n in_features: extractor_conv_layer_config[extractor_conv_layer_config.Length - 1][0],\n embed_dim: encoder_embed_dim,\n dropout_input: encoder_projection_dropout,\n pos_conv_kernel: encoder_pos_conv_kernel,\n pos_conv_groups: encoder_pos_conv_groups,\n num_layers: encoder_num_layers,\n num_heads: encoder_num_heads,\n attention_dropout: encoder_attention_dropout,\n ff_interm_features: encoder_ff_interm_features,\n ff_interm_dropout: encoder_ff_interm_dropout,\n dropout: encoder_dropout,\n layer_norm_first: encoder_layer_norm_first,\n layer_drop: encoder_layer_drop);\n var wav2vec2 = new Wav2Vec2Model(\"Wav2Vec2Model\", feature_extractor, encoder);\n var mask_generator = new Wav2Vec2Model.MaskGenerator(\n \"MaskGenerator\",\n encoder_embed_dim,\n mask_prob,\n mask_selection,\n mask_other,\n mask_length,\n no_mask_overlap,\n mask_min_space,\n mask_channel_prob,\n mask_channel_selection,\n mask_channel_other,\n mask_channel_length,\n no_mask_channel_overlap,\n mask_channel_min_space);\n var logit_generator = new Wav2Vec2Model.LogitGenerator(\n \"LogitGenerator\",\n encoder_embed_dim,\n num_classes,\n final_dim,\n skip_masked,\n skip_nomask);\n return new HuBERTPretrainModel(\n \"HuBERTPretrainModel\",\n wav2vec2: wav2vec2,\n mask_generator: mask_generator,\n logit_generator: logit_generator,\n feature_grad_mult: feature_grad_mult);\n }\n\n /// <summary>\n /// Build HuBERTPretrainModel model with \"base\" architecture from *HuBERT* [:footcite:`hsu2021hubert`]\n /// </summary>\n /// <param name=\"encoder_projection_dropout\">See `hubert_pretrain_model`.</param>\n /// <param name=\"encoder_attention_dropout\">See `hubert_pretrain_model`.</param>\n /// <param name=\"encoder_dropout\">See `hubert_pretrain_model`.</param>\n /// <param name=\"encoder_ff_interm_dropout\">See `hubert_pretrain_model`.</param>\n /// <param name=\"encoder_layer_drop\">See `hubert_pretrain_model`.</param>\n /// <param name=\"mask_prob\">See `hubert_pretrain_model`.</param>\n /// <param name=\"mask_channel_prob\">See `hubert_pretrain_model`.</param>\n /// <param name=\"mask_channel_length\">See `hubert_pretrain_model`.</param>\n /// <param name=\"feature_grad_mult\">See `hubert_pretrain_model`.</param>\n /// <param name=\"num_classes\">See `hubert_pretrain_model`.</param>\n /// <returns>\n /// The resulting model.\n /// </returns>\n public static HuBERTPretrainModel hubert_pretrain_base(\n double encoder_projection_dropout = 0.1,\n double encoder_attention_dropout = 0.1,\n double encoder_ff_interm_dropout = 0.0,\n double encoder_dropout = 0.1,\n double encoder_layer_drop = 0.05,\n double mask_prob = 0.8,\n double mask_channel_prob = 0.0,\n long mask_channel_length = 10,\n double? feature_grad_mult = 0.1,\n long num_classes = 100)\n {\n // Overriding the signature so that the return type is correct on Sphinx\n return hubert_pretrain_model(\n extractor_mode: FeatureExtractorNormMode.group_norm,\n extractor_conv_layer_config: null,\n extractor_conv_bias: false,\n encoder_embed_dim: 768,\n encoder_projection_dropout: encoder_projection_dropout,\n encoder_pos_conv_kernel: 128,\n encoder_pos_conv_groups: 16,\n encoder_num_layers: 12,\n encoder_num_heads: 12,\n encoder_attention_dropout: encoder_attention_dropout,\n encoder_ff_interm_features: 3072,\n encoder_ff_interm_dropout: encoder_ff_interm_dropout,\n encoder_dropout: encoder_dropout,\n encoder_layer_norm_first: false,\n encoder_layer_drop: encoder_layer_drop,\n mask_prob: mask_prob,\n mask_selection: \"static\",\n mask_other: 0.0,\n mask_length: 10,\n no_mask_overlap: false,\n mask_min_space: 1,\n mask_channel_prob: mask_channel_prob,\n mask_channel_selection: \"static\",\n mask_channel_other: 0.0,\n mask_channel_length: mask_channel_length,\n no_mask_channel_overlap: false,\n mask_channel_min_space: 1,\n skip_masked: false,\n skip_nomask: false,\n num_classes: num_classes,\n final_dim: 256,\n feature_grad_mult: feature_grad_mult);\n }\n\n /// <summary>\n /// Build HuBERTPretrainModel model for pre-training with \"large\" architecture from *HuBERT* [:footcite:`hsu2021hubert`]\n /// </summary>\n /// <param name=\"encoder_projection_dropout\">See `hubert_pretrain_model`.</param>\n /// <param name=\"encoder_attention_dropout\">See `hubert_pretrain_model`.</param>\n /// <param name=\"encoder_dropout\">See `hubert_pretrain_model`.</param>\n /// <param name=\"encoder_ff_interm_dropout\">See `hubert_pretrain_model`.</param>\n /// <param name=\"encoder_layer_drop\">See `hubert_pretrain_model`.</param>\n /// <param name=\"mask_prob\">See `hubert_pretrain_model`.</param>\n /// <param name=\"mask_channel_prob\">See `hubert_pretrain_model`.</param>\n /// <param name=\"mask_channel_length\">See `hubert_pretrain_model`.</param>\n /// <param name=\"feature_grad_mult\">See `hubert_pretrain_model`.</param>\n /// <returns>\n /// The resulting model.\n /// </returns>\n public static HuBERTPretrainModel hubert_pretrain_large(\n double encoder_projection_dropout = 0.0,\n double encoder_attention_dropout = 0.0,\n double encoder_ff_interm_dropout = 0.0,\n double encoder_dropout = 0.0,\n double encoder_layer_drop = 0.0,\n double mask_prob = 0.8,\n double mask_channel_prob = 0.0,\n long mask_channel_length = 10,\n double? feature_grad_mult = null)\n {\n // Overriding the signature so that the return type is correct on Sphinx\n return hubert_pretrain_model(\n extractor_mode: FeatureExtractorNormMode.layer_norm,\n extractor_conv_layer_config: null,\n extractor_conv_bias: false,\n encoder_embed_dim: 1024,\n encoder_projection_dropout: encoder_projection_dropout,\n encoder_pos_conv_kernel: 128,\n encoder_pos_conv_groups: 16,\n encoder_num_layers: 24,\n encoder_num_heads: 16,\n encoder_attention_dropout: encoder_attention_dropout,\n encoder_ff_interm_features: 4096,\n encoder_ff_interm_dropout: encoder_ff_interm_dropout,\n encoder_dropout: encoder_dropout,\n encoder_layer_norm_first: true,\n encoder_layer_drop: encoder_layer_drop,\n mask_prob: mask_prob,\n mask_selection: \"static\",\n mask_other: 0.0,\n mask_length: 10,\n no_mask_overlap: false,\n mask_min_space: 1,\n mask_channel_prob: mask_channel_prob,\n mask_channel_selection: \"static\",\n mask_channel_other: 0.0,\n mask_channel_length: mask_channel_length,\n no_mask_channel_overlap: false,\n mask_channel_min_space: 1,\n skip_masked: false,\n skip_nomask: false,\n num_classes: 500,\n final_dim: 768,\n feature_grad_mult: feature_grad_mult);\n }\n\n /// <summary>\n /// Build HuBERTPretrainModel model for pre-training with \"extra large\" architecture from *HuBERT* [:footcite:`hsu2021hubert`]\n /// </summary>\n /// <param name=\"encoder_projection_dropout\">See `hubert_pretrain_model`.</param>\n /// <param name=\"encoder_attention_dropout\">See `hubert_pretrain_model`.</param>\n /// <param name=\"encoder_dropout\">See `hubert_pretrain_model`.</param>\n /// <param name=\"encoder_ff_interm_dropout\">See `hubert_pretrain_model`.</param>\n /// <param name=\"encoder_layer_drop\">See `hubert_pretrain_model`.</param>\n /// <param name=\"mask_prob\">See `hubert_pretrain_model`.</param>\n /// <param name=\"mask_channel_prob\">See `hubert_pretrain_model`.</param>\n /// <param name=\"mask_channel_length\">See `hubert_pretrain_model`.</param>\n /// <param name=\"feature_grad_mult\">See `hubert_pretrain_model`.</param>\n /// <returns>\n /// The resulting model.\n /// </returns>\n public static HuBERTPretrainModel hubert_pretrain_xlarge(\n double encoder_projection_dropout = 0.0,\n double encoder_attention_dropout = 0.0,\n double encoder_ff_interm_dropout = 0.0,\n double encoder_dropout = 0.0,\n double encoder_layer_drop = 0.0,\n double mask_prob = 0.8,\n double mask_channel_prob = 0.0,\n long mask_channel_length = 10,\n double? feature_grad_mult = null)\n {\n // Overriding the signature so that the return type is correct on Sphinx\n return hubert_pretrain_model(\n extractor_mode: FeatureExtractorNormMode.layer_norm,\n extractor_conv_layer_config: null,\n extractor_conv_bias: false,\n encoder_embed_dim: 1280,\n encoder_projection_dropout: encoder_projection_dropout,\n encoder_pos_conv_kernel: 128,\n encoder_pos_conv_groups: 16,\n encoder_num_layers: 48,\n encoder_num_heads: 16,\n encoder_attention_dropout: encoder_attention_dropout,\n encoder_ff_interm_features: 5120,\n encoder_ff_interm_dropout: encoder_ff_interm_dropout,\n encoder_dropout: encoder_dropout,\n encoder_layer_norm_first: true,\n encoder_layer_drop: encoder_layer_drop,\n mask_prob: mask_prob,\n mask_selection: \"static\",\n mask_other: 0.0,\n mask_length: 10,\n no_mask_overlap: false,\n mask_min_space: 1,\n mask_channel_prob: mask_channel_prob,\n mask_channel_selection: \"static\",\n mask_channel_other: 0.0,\n mask_channel_length: mask_channel_length,\n no_mask_channel_overlap: false,\n mask_channel_min_space: 1,\n skip_masked: false,\n skip_nomask: false,\n num_classes: 500,\n final_dim: 1024,\n feature_grad_mult: feature_grad_mult);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.4577777683734894, "alphanum_fraction": 0.4624338746070862, "avg_line_length": 46.25, "blob_id": "2e202864b33e19a58835ebec26c1eb0c88abf811", "content_id": "2f8bcd1e4b1dc8f8948e0b6ada7b703d39ad6c29", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4725, "license_type": "permissive", "max_line_length": 232, "num_lines": 100, "path": "/src/TorchSharp/NN/Normalization/Functional.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class nn\n {\n public static partial class functional\n {\n /// <summary>\n /// Applies Batch Normalization for each channel across a batch of data.\n /// </summary>\n public static Tensor batch_norm(Tensor input, Tensor running_mean, Tensor running_var, Tensor weight = null, Tensor bias = null, bool training = false, double momentum = 0.1, double eps = 1e-5)\n {\n var res = THSNN_batch_norm(\n input.Handle,\n running_mean.Handle,\n running_var.Handle,\n weight is not null ? weight.Handle : IntPtr.Zero,\n bias is not null ? bias.Handle : IntPtr.Zero,\n training,\n momentum, eps);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Applies Group Normalization for last certain number of dimensions.\n /// </summary>\n public static Tensor group_norm(Tensor input, long num_groups, Tensor weight = null, Tensor bias = null, double eps = 1e-5)\n {\n var res = THSNN_group_norm(\n input.Handle,\n num_groups,\n weight is not null ? weight.Handle : IntPtr.Zero,\n bias is not null ? bias.Handle : IntPtr.Zero,\n eps);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Applies Instance Normalization for each channel in each data sample in a batch.\n /// </summary>\n public static Tensor instance_norm(Tensor input, Tensor running_mean = null, Tensor running_var = null, Tensor weight = null, Tensor bias = null, bool use_input_stats = true, double momentum = 0.1, double eps = 1e-5)\n {\n var res = THSNN_instance_norm(\n input.Handle,\n running_mean is not null ? running_mean.Handle : IntPtr.Zero,\n running_var is not null ? running_var.Handle : IntPtr.Zero,\n weight is not null ? weight.Handle : IntPtr.Zero,\n bias is not null ? bias.Handle : IntPtr.Zero,\n use_input_stats,\n momentum, eps);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Applies Layer Normalization for last certain number of dimensions.\n /// </summary>\n public static Tensor layer_norm(Tensor input, long[] normalized_shape, Tensor weight = null, Tensor bias = null, double eps = 1e-5)\n {\n IntPtr res;\n unsafe {\n fixed (long* normalized_shape_ptr = normalized_shape) {\n res = THSNN_layer_norm(\n input.Handle,\n normalized_shape_ptr,\n normalized_shape.LongLength,\n weight is not null ? weight.Handle : IntPtr.Zero,\n bias is not null ? bias.Handle : IntPtr.Zero,\n eps);\n }\n }\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Applies Local Normalization.\n /// </summary>\n public static Tensor local_response_norm(Tensor input, long size, double alpha = 0.0001, double beta = 0.75, double k = 1.0)\n {\n var res = THSNN_local_response_norm(input.Handle, size, alpha, beta, k);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.41532114148139954, "alphanum_fraction": 0.4296486973762512, "avg_line_length": 34.7274169921875, "blob_id": "4cfc5bd987a6e41c4c2c76283ca05f85d21a5e98", "content_id": "9514003f2da95ad0d520e24dc6c62b9103c9647d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 22544, "license_type": "permissive", "max_line_length": 157, "num_lines": 631, "path": "/src/TorchSharp/Utils/TensorAccessor.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp.Utils\n{\n /// <summary>\n /// TensorAccessor is used to present the contents of a tensor or tensor view to the .NET world as an ordered collection\n /// of values that integrates well with things like LINQ and foreach loops in the .NET world.\n /// </summary>\n /// <typeparam name=\"T\">The type of the tensor elements.</typeparam>\n public sealed class TensorAccessor<T> : IDisposable, IEnumerable<T> where T : unmanaged\n {\n internal TensorAccessor(torch.Tensor tensor)\n {\n if (tensor.device_type != DeviceType.CPU) {\n throw new InvalidOperationException(\"Reading data from non-CPU memory is not supported. Move or copy the tensor to the cpu before reading.\");\n }\n\n var strides = tensor.stride();\n for (var i = 0; i < strides.Length; i++) {\n if (strides[i] < 0)\n throw new NotImplementedException($\"Negative tensor strides are not currently supported. tensor.strides({i}) == {strides[i]}\");\n }\n\n // Get the data from native code.\n\n unsafe {\n var res = THSTensor_data(tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n // NOTE: there is no safety here.\n _tensor_data_ptr = res;\n }\n\n _tensor = tensor; // Keep the tensor alive now that everything is alright.\n }\n\n public long Count => (_tensor is not null ? _tensor.numel() : 0);\n\n public bool IsReadOnly => false;\n\n public T[] ToArray()\n {\n if (_tensor.ndim < 2)\n return (T[])ToNDArray();\n\n var result = new T[Count];\n CopyTo(result);\n return result;\n }\n\n /// <summary>\n /// Extract tensor data as a multi-dimensional .NET array, with the same number of dimensions as the tensor.\n /// </summary>\n /// <returns>An array object, which should be cast to the concrete array type.</returns>\n public Array ToNDArray()\n {\n var shape = _tensor.shape;\n var strides = _tensor.stride();\n switch (_tensor.ndim) {\n default:\n return ToNDArray(shape, strides);\n case 0:\n unsafe {\n var result = new T[1];\n T* ptr = (T*)_tensor_data_ptr;\n result[0] = ptr[0];\n return result;\n }\n case 1:\n unsafe {\n var result = new T[shape[0]];\n T* ptr = (T*)_tensor_data_ptr;\n for (long i0 = 0, off0 = 0; i0 < shape[0]; i0++, off0 += strides[0]) {\n result[i0] = ptr[off0];\n }\n return result;\n }\n case 2:\n unsafe {\n var result = new T[shape[0], shape[1]];\n T* ptr = (T*)_tensor_data_ptr;\n for (long i0 = 0, off0 = 0; i0 < shape[0]; i0++, off0 += strides[0]) {\n for (long i1 = 0, off1 = off0; i1 < shape[1]; i1++, off1 += strides[1]) {\n result[i0, i1] = ptr[off1];\n }\n }\n return result;\n }\n case 3:\n unsafe {\n var result = new T[shape[0], shape[1], shape[2]];\n T* ptr = (T*)_tensor_data_ptr;\n for (long i0 = 0, off0 = 0; i0 < shape[0]; i0++, off0 += strides[0]) {\n for (long i1 = 0, off1 = off0; i1 < shape[1]; i1++, off1 += strides[1]) {\n for (long i2 = 0, off2 = off1; i2 < shape[2]; i2++, off2 += strides[2]) {\n result[i0, i1, i2] = ptr[off2];\n }\n }\n }\n return result;\n }\n case 4:\n unsafe {\n var result = new T[shape[0], shape[1], shape[2], shape[3]];\n T* ptr = (T*)_tensor_data_ptr;\n for (long i0 = 0, off0 = 0; i0 < shape[0]; i0++, off0 += strides[0]) {\n for (long i1 = 0, off1 = off0; i1 < shape[1]; i1++, off1 += strides[1]) {\n for (long i2 = 0, off2 = off1; i2 < shape[2]; i2++, off2 += strides[2]) {\n for (long i3 = 0, off3 = off2; i3 < shape[3]; i3++, off3 += strides[3]) {\n result[i0, i1, i2, i3] = ptr[off3];\n }\n }\n }\n }\n return result;\n }\n case 5:\n unsafe {\n var result = new T[shape[0], shape[1], shape[2], shape[3], shape[4]];\n T* ptr = (T*)_tensor_data_ptr;\n for (long i0 = 0, off0 = 0; i0 < shape[0]; i0++, off0 += strides[0]) {\n for (long i1 = 0, off1 = off0; i1 < shape[1]; i1++, off1 += strides[1]) {\n for (long i2 = 0, off2 = off1; i2 < shape[2]; i2++, off2 += strides[2]) {\n for (long i3 = 0, off3 = off2; i3 < shape[3]; i3++, off3 += strides[3]) {\n for (long i4 = 0, off4 = off3; i4 < shape[4]; i4++, off4 += strides[4]) {\n result[i0, i1, i2, i3, i4] = ptr[off4];\n }\n }\n }\n }\n }\n return result;\n }\n case 6:\n unsafe {\n var result = new T[shape[0], shape[1], shape[2], shape[3], shape[4], shape[5]];\n T* ptr = (T*)_tensor_data_ptr;\n for (long i0 = 0, off0 = 0; i0 < shape[0]; i0++, off0 += strides[0]) {\n for (long i1 = 0, off1 = off0; i1 < shape[1]; i1++, off1 += strides[1]) {\n for (long i2 = 0, off2 = off1; i2 < shape[2]; i2++, off2 += strides[2]) {\n for (long i3 = 0, off3 = off2; i3 < shape[3]; i3++, off3 += strides[3]) {\n for (long i4 = 0, off4 = off3; i4 < shape[4]; i4++, off4 += strides[4]) {\n for (long i5 = 0, off5 = off4; i5 < shape[5]; i5++, off5 += strides[5]) {\n result[i0, i1, i2, i3, i4, i5] = ptr[off5];\n }\n }\n }\n }\n }\n }\n return result;\n }\n }\n }\n\n private Array ToNDArray(long[] shape, long[] strides)\n {\n Array array = Array.CreateInstance(typeof(T), shape);\n long[] indexes = new long[_tensor.ndim];\n long[] off = new long[_tensor.ndim];\n\n while (true) {\n unsafe {\n T* ptr = (T*)_tensor_data_ptr;\n array.SetValue(ptr[off[array.Rank - 1]], indexes);\n }\n\n for (int i = array.Rank - 1; i >= 0; i--) {\n if (indexes[i] < shape[i] - 1) {\n indexes[i]++;\n off[i] += strides[i];\n for (int j = i; j < array.Rank - 1; j++)\n off[j + 1] = off[j];\n break;\n } else {\n if (i == 0) {\n return array;\n }\n indexes[i] = 0;\n }\n }\n }\n }\n\n /// <summary>\n /// Access elements of the underlying tensor / tensor view.\n /// </summary>\n /// <param name=\"indices\">A linear index into the data.</param>\n /// <returns></returns>\n public T this[params long[] indices] {\n get {\n long index = 0;\n if (indices.Length == 1) {\n index = indices[0];\n validate(index);\n unsafe {\n T* ptr = (T*)_tensor_data_ptr;\n return ptr[TranslateIndex(index, _tensor)];\n }\n } else {\n unsafe {\n T* ptr = (T*)_tensor_data_ptr;\n return ptr[TranslateIndex(indices, _tensor)];\n }\n }\n }\n set {\n long index = 0;\n if (indices.Length == 1) {\n index = indices[0];\n validate(index);\n unsafe {\n T* ptr = (T*)_tensor_data_ptr;\n ptr[TranslateIndex(indices, _tensor)] = value;\n }\n } else {\n unsafe {\n T* ptr = (T*)_tensor_data_ptr;\n ptr[TranslateIndex(indices, _tensor)] = value;\n }\n }\n }\n }\n\n private void validate(long index)\n {\n if (index >= Count) throw new IndexOutOfRangeException();\n }\n\n public void CopyTo(T[] array, int arrayIndex = 0, long tensorIndex = 0)\n {\n int idx = arrayIndex;\n foreach (int offset in GetSubsequentIndices(tensorIndex)) {\n if (idx >= array.Length) break;\n unsafe { array[idx] = ((T*)_tensor_data_ptr)[offset]; }\n idx += 1;\n }\n }\n\n public void CopyFrom(T[] array, int arrayIndex = 0, long tensorIndex = 0)\n {\n int idx = arrayIndex;\n foreach (int offset in GetSubsequentIndices(tensorIndex)) {\n if (idx >= array.Length) break;\n unsafe { ((T*)_tensor_data_ptr)[offset] = array[idx]; }\n idx += 1;\n }\n }\n\n /// <summary>\n /// Translates a linear index within the span represented by the accessor to a linear index\n /// used by the underlying tensor. The two should only be different if the tensor is a view\n /// rather than an allocated tensor.\n /// </summary>\n private static long TranslateIndex(long idx, torch.Tensor tensor)\n {\n if (idx >= tensor.numel() || idx < 0)\n throw new ArgumentOutOfRangeException($\"{idx} in a collection of ${tensor.numel()} elements.\");\n\n if (tensor.is_contiguous() || idx == 0) return idx;\n\n long result = 0;\n var shape = tensor.shape;\n var strides = tensor.stride();\n\n for (var i = shape.Length - 1; i >= 0; i--) {\n idx = Math.DivRem(idx, shape[i], out long s);\n result += s * strides[i];\n }\n\n return result;\n }\n\n private static long TranslateIndex(long[] idx, torch.Tensor tensor)\n {\n long result = 0;\n var shape = tensor.shape;\n var strides = tensor.stride();\n\n for (var i = shape.Length - 1; i >= 0; i--) {\n if (idx[i] >= shape[i] || idx[i] < 0)\n throw new IndexOutOfRangeException($\"{idx[i]} >= {shape[i]} in dimension {i}.\");\n result += idx[i] * strides[i];\n }\n\n return result;\n }\n\n internal static T ReadItemAt(torch.Tensor tensor, long index)\n {\n if (tensor.device_type != DeviceType.CPU) {\n throw new InvalidOperationException(\"Reading data from non-CPU memory is not supported. Move or copy the tensor to the cpu before reading.\");\n }\n\n tensor.ValidateType(typeof(T));\n\n var strides = tensor.stride();\n for (var i = 0; i < strides.Length; i++) {\n if (strides[i] < 0)\n throw new NotImplementedException($\"Negative tensor strides are not currently supported. tensor.strides({i}) == {strides[i]}\");\n }\n\n unsafe {\n var res = THSTensor_data(tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n // NOTE: there is no safety here.\n T* ptr = (T*)res;\n return ptr[TranslateIndex(index, tensor)];\n }\n }\n\n /// <summary>\n /// Compare two tensors element-wise.\n /// </summary>\n /// <param name=\"left\">A tensor</param>\n /// <param name=\"right\">Another tensor</param>\n /// <returns></returns>\n public static bool operator ==(TensorAccessor<T> left, TensorAccessor<T> right)\n {\n if (left.Count != right.Count) return false;\n\n var lEnum = left.GetEnumerator();\n var rEnum = right.GetEnumerator();\n\n while (lEnum.MoveNext() && rEnum.MoveNext()) {\n if (!lEnum.Current.Equals(rEnum.Current))\n return false;\n }\n return true;\n }\n\n /// <summary>\n /// Compare two tensors element-wise.\n /// </summary>\n /// <param name=\"left\">A tensor</param>\n /// <param name=\"right\">Another tensor</param>\n /// <returns></returns>\n public static bool operator !=(TensorAccessor<T> left, TensorAccessor<T> right)\n {\n return !(left == right);\n }\n\n\n private IEnumerable<long> GetSubsequentIndices(long startingIndex)\n {\n if (startingIndex < 0 || startingIndex >= Count)\n throw new ArgumentOutOfRangeException(nameof(startingIndex));\n\n if (Count <= 1) {\n if (Count == 0) {\n return Enumerable.Empty<long>();\n }\n\n return (new long[] { 0 }).AsEnumerable<long>();\n }\n\n if (_tensor.is_contiguous()) {\n return ContiguousIndices(startingIndex);\n }\n\n var stride = _tensor.stride();\n Debug.Assert(stride.Length > 0);\n\n if (stride.Length == 1) {\n return SimpleIndices(startingIndex, stride[0]);\n }\n\n return MultiDimensionIndices(startingIndex);\n }\n\n private IEnumerable<long> MultiDimensionIndices(long startingIndex)\n {\n long[] shape = _tensor.shape;\n long[] stride = _tensor.stride();\n long[] inds = new long[stride.Length];\n\n long index = startingIndex;\n long offset = TranslateIndex(startingIndex, _tensor);\n\n while (true) {\n\n index += 1;\n\n yield return offset;\n\n if (index >= Count) break;\n\n for (int i = inds.Length - 1; ; i--) {\n Debug.Assert(i >= 0);\n offset += stride[i];\n if (++inds[i] < shape[i])\n break;\n\n // Overflow of current dimension so rewind accordingly.\n // Can't overflow the final (left-most) dimension.\n Debug.Assert(i > 0);\n // Note: for perf, this multiplication could be done once up front and cached in an array.\n offset -= inds[i] * stride[i];\n inds[i] = 0;\n }\n }\n }\n\n private IEnumerable<long> SimpleIndices(long startingIndex, long stride)\n {\n long index = startingIndex;\n long offset = TranslateIndex(startingIndex, _tensor);\n\n while (index < Count) {\n yield return offset;\n offset += stride;\n index += 1;\n }\n }\n private IEnumerable<long> ContiguousIndices(long startingIndex)\n {\n // If there was an overload for Enumerable.Range that\n // produced long integers, we wouldn't need this implementation.\n\n long index = startingIndex;\n while (index < Count) {\n yield return index;\n index += 1;\n }\n }\n\n\n /// <summary>\n /// Compare two tensors element-wise.\n /// </summary>\n /// <param name=\"obj\">Another tensor</param>\n /// <returns></returns>\n public override bool Equals(object obj)\n {\n var left = this;\n var right = obj as TensorAccessor<T>;\n if (right == null) return false;\n\n if (left._tensor_data_ptr == right._tensor_data_ptr) return true;\n if (left.Count != right.Count) return false;\n for (long i = 0; i < left.Count; i++) {\n if (!left[i].Equals(right[i])) return false;\n }\n return true;\n }\n\n public override int GetHashCode()\n {\n return base.GetHashCode();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n private void Dispose(bool disposing)\n {\n _tensor_data_ptr = IntPtr.Zero;\n // Clear the tensor that we've been keeping alive.\n _tensor = null;\n }\n\n private torch.Tensor _tensor; // Keeping it alive.\n private IntPtr _tensor_data_ptr;\n\n#if true\n public IEnumerator<T> GetEnumerator()\n {\n if (Count <= 1) {\n if (Count == 0)\n return Enumerable.Empty<T>().GetEnumerator();\n return new T[1] { this[0] }.AsEnumerable<T>().GetEnumerator();\n }\n\n if (_tensor.is_contiguous()) {\n return new SimpleAtorImpl(this, 1);\n }\n\n var stride = _tensor.stride();\n Debug.Assert(stride.Length > 0);\n\n if (stride.Length == 1) {\n return new SimpleAtorImpl(this, stride[0]);\n }\n\n return new GeneralAtorImpl(this, stride);\n }\n\n private class SimpleAtorImpl : IEnumerator<T>\n {\n private TensorAccessor<T> _span;\n private readonly long _count;\n private readonly long _stride;\n\n // State.\n private long _index;\n private long _offset;\n private T _current;\n\n public SimpleAtorImpl(TensorAccessor<T> span, long stride)\n {\n _span = span;\n _count = span.Count;\n Debug.Assert(_count > 0);\n _stride = stride;\n Reset();\n }\n\n public T Current => _current;\n object IEnumerator.Current => Current;\n\n public void Dispose()\n {\n _span = null;\n Reset();\n }\n\n public bool MoveNext()\n {\n if (_index < 0) {\n _index = 0;\n _offset = 0;\n } else if (++_index >= _count) {\n Reset();\n return false;\n } else {\n _offset += _stride;\n }\n\n unsafe { _current = ((T*)_span._tensor_data_ptr)[_offset]; }\n return true;\n }\n\n public void Reset()\n {\n _index = -1;\n _offset = -1;\n _current = default;\n }\n }\n\n private class GeneralAtorImpl : IEnumerator<T>\n {\n private TensorAccessor<T> _span;\n private readonly long _count;\n private readonly long[] _shape;\n private readonly long[] _stride;\n private readonly long[] _inds;\n\n // State.\n private long _index;\n private long _offset;\n\n public GeneralAtorImpl(TensorAccessor<T> span, long[] stride)\n {\n Debug.Assert(stride.Length > 1);\n _span = span;\n _count = span.Count;\n Debug.Assert(_count > 0);\n _shape = span._tensor.shape;\n Debug.Assert(_shape.Length == stride.Length);\n _stride = stride;\n _inds = new long[stride.Length];\n Reset();\n }\n\n public T Current { get; private set; }\n\n object IEnumerator.Current => Current;\n\n public void Dispose()\n {\n // Just clear the span field.\n _span = null;\n }\n\n public bool MoveNext()\n {\n if (_index < 0) {\n _index = 0;\n _offset = 0;\n Array.Clear(_inds, 0, _inds.Length);\n } else if (++_index >= _count) {\n Reset();\n return false;\n } else {\n for (int i = _inds.Length - 1; ; i--) {\n Debug.Assert(i >= 0);\n _offset += _stride[i];\n if (++_inds[i] < _shape[i])\n break;\n\n // Overflow of current dimension so rewind accordingly.\n // Can't overflow the final (left-most) dimension.\n Debug.Assert(i > 0);\n // Note: for perf, this multiplication could be done once up front and cached in an array.\n _offset -= _inds[i] * _stride[i];\n _inds[i] = 0;\n }\n }\n\n unsafe { Current = ((T*)_span._tensor_data_ptr)[_offset]; }\n return true;\n }\n\n public void Reset()\n {\n _index = -1;\n _offset = -1;\n Current = default;\n }\n }\n#else\n public IEnumerator<T> GetEnumerator()\n {\n return new TensorAccessorEnumerator(this);\n }\n#endif\n }\n}\n" }, { "alpha_fraction": 0.5476118922233582, "alphanum_fraction": 0.5522679686546326, "avg_line_length": 32.04218292236328, "blob_id": "90594c3edaceb60dda20ab631a13eead8c8a7713", "content_id": "cf95ac47f017103031032726c2da77f2a17a1322", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 13316, "license_type": "permissive", "max_line_length": 130, "num_lines": 403, "path": "/src/TorchSharp/Scalar.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n /// <summary>\n /// Represents a dynamically typed scalar value to the LibTorch runtime.\n /// </summary>\n public sealed class Scalar : IDisposable\n {\n internal IntPtr Handle {\n get {\n if (handle == IntPtr.Zero)\n throw new InvalidOperationException(\"Scalar invalid -- empty handle.\");\n return handle;\n }\n private set { handle = value; }\n }\n private IntPtr handle;\n\n internal Scalar(IntPtr handle)\n {\n Handle = handle;\n }\n\n /// <summary>\n /// Implicitly convert a .NET scalar value to Scalar\n /// </summary>\n /// <param name=\"value\">The scalar value.</param>\n public static implicit operator Scalar(byte value)\n {\n return value.ToScalar();\n }\n\n /// <summary>\n /// Implicitly convert a .NET scalar value to Scalar\n /// </summary>\n /// <param name=\"value\">The scalar value.</param>\n public static implicit operator Scalar(sbyte value)\n {\n return value.ToScalar();\n }\n\n /// <summary>\n /// Implicitly convert a .NET scalar value to Scalar\n /// </summary>\n /// <param name=\"value\">The scalar value.</param>\n public static implicit operator Scalar(short value)\n {\n return value.ToScalar();\n }\n\n /// <summary>\n /// Implicitly convert a .NET scalar value to Scalar\n /// </summary>\n /// <param name=\"value\">The scalar value.</param>\n public static implicit operator Scalar(int value)\n {\n return value.ToScalar();\n }\n\n /// <summary>\n /// Implicitly convert a .NET scalar value to Scalar\n /// </summary>\n /// <param name=\"value\">The scalar value.</param>\n public static implicit operator Scalar(long value)\n {\n return value.ToScalar();\n }\n\n#if NET6_0_OR_GREATER\n /// <summary>\n /// Implicitly convert a .NET scalar value to Scalar\n /// </summary>\n /// <param name=\"value\">The scalar value.</param>\n public static implicit operator Scalar(Half value)\n {\n return value.ToScalar();\n }\n#endif\n\n /// <summary>\n /// Implicitly convert a .NET scalar value to Scalar\n /// </summary>\n /// <param name=\"value\">The scalar value.</param>\n public static implicit operator Scalar(float value)\n {\n return value.ToScalar();\n }\n\n /// <summary>\n /// Implicitly convert a .NET scalar value to Scalar\n /// </summary>\n /// <param name=\"value\">The scalar value.</param>\n public static implicit operator Scalar(double value)\n {\n return value.ToScalar();\n }\n\n /// <summary>\n /// Implicitly convert a .NET scalar value to Scalar\n /// </summary>\n /// <param name=\"value\">The scalar value.</param>\n public static implicit operator Scalar(bool value)\n {\n return value.ToScalar();\n }\n\n /// <summary>\n /// Implicitly convert a .NET scalar value to Scalar\n /// </summary>\n /// <param name=\"value\">The scalar value.</param>\n public static implicit operator Scalar((float, float) value)\n {\n return value.ToScalar();\n }\n\n /// <summary>\n /// Implicitly convert a .NET scalar value to Scalar\n /// </summary>\n /// <param name=\"value\">The scalar value.</param>\n public static implicit operator Scalar(System.Numerics.Complex value)\n {\n return value.ToScalar();\n }\n\n /// <summary>\n /// Gets the actual type of the Scalar value\n /// </summary>\n public torch.ScalarType Type {\n get {\n return (torch.ScalarType)THSTorch_scalar_type(Handle);\n }\n }\n\n /// <summary>\n /// Finalize the tensor. Releases the tensor and its associated data.\n /// </summary>\n ~Scalar() => Dispose(false);\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n /// <summary>\n /// Implements the .NET Dispose pattern.\n /// </summary>\n void Dispose(bool disposing)\n {\n if (handle != IntPtr.Zero) {\n THSTorch_dispose_scalar(handle);\n handle = IntPtr.Zero;\n }\n }\n }\n\n public static class ScalarExtensionMethods\n {\n /// <summary>\n /// Explcitly construct a Scalar from a .NET scalar.\n /// </summary>\n /// <param name=\"value\">The input scalar value</param>\n public static Scalar ToScalar(this byte value)\n {\n torch.InitializeDeviceType(DeviceType.CPU);\n return new Scalar(THSTorch_uint8_to_scalar(value));\n }\n\n /// <summary>\n /// Explcitly construct a Scalar from a .NET scalar.\n /// </summary>\n /// <param name=\"value\">The input scalar value</param>\n public static Scalar ToScalar(this sbyte value)\n {\n torch.InitializeDeviceType(DeviceType.CPU);\n return new Scalar(THSTorch_int8_to_scalar(value));\n }\n\n /// <summary>\n /// Explcitly construct a Scalar from a .NET scalar.\n /// </summary>\n /// <param name=\"value\">The input scalar value</param>\n public static Scalar ToScalar(this short value)\n {\n torch.InitializeDeviceType(DeviceType.CPU);\n return new Scalar(THSTorch_int16_to_scalar(value));\n }\n\n /// <summary>\n /// Explcitly construct a Scalar from a .NET scalar.\n /// </summary>\n /// <param name=\"value\">The input scalar value</param>\n public static Scalar ToScalar(this int value)\n {\n torch.InitializeDeviceType(DeviceType.CPU);\n return new Scalar(THSTorch_int32_to_scalar(value));\n }\n\n /// <summary>\n /// Explcitly construct a Scalar from a .NET scalar.\n /// </summary>\n /// <param name=\"value\">The input scalar value</param>\n public static Scalar ToScalar(this long value)\n {\n torch.InitializeDeviceType(DeviceType.CPU);\n return new Scalar(THSTorch_int64_to_scalar(value));\n }\n\n /// <summary>\n /// Explcitly construct a Scalar from a .NET scalar.\n /// </summary>\n /// <param name=\"value\">The input scalar value</param>\n public static Scalar ToScalar(this float value)\n {\n torch.InitializeDeviceType(DeviceType.CPU);\n return new Scalar(THSTorch_float32_to_scalar(value));\n }\n\n /// <summary>\n /// Explcitly construct a Scalar from a .NET scalar.\n /// </summary>\n /// <param name=\"value\">The input scalar value</param>\n public static Scalar ToScalar(this double value)\n {\n torch.InitializeDeviceType(DeviceType.CPU);\n return new Scalar(THSTorch_float64_to_scalar(value));\n }\n\n /// <summary>\n /// Explcitly construct a Scalar from a .NET scalar.\n /// </summary>\n /// <param name=\"value\">The input scalar value</param>\n public static Scalar ToScalar(this (float, float) value)\n {\n torch.InitializeDeviceType(DeviceType.CPU);\n return new Scalar(THSTorch_complex32_to_scalar(value.Item1, value.Item2));\n }\n\n /// <summary>\n /// Explcitly construct a Scalar from a .NET scalar.\n /// </summary>\n /// <param name=\"value\">The input scalar value</param>\n public static Scalar ToScalar(this System.Numerics.Complex value)\n {\n torch.InitializeDeviceType(DeviceType.CPU);\n return new Scalar(THSTorch_complex64_to_scalar(value.Real, value.Imaginary));\n }\n\n /// <summary>\n /// Explcitly construct a Scalar from a .NET scalar.\n /// </summary>\n /// <param name=\"value\">The input scalar value</param>\n public static Scalar ToScalar(this bool value)\n {\n torch.InitializeDeviceType(DeviceType.CPU);\n return new Scalar(THSTorch_bool_to_scalar(value));\n }\n\n#if NET6_0_OR_GREATER\n /// <summary>\n /// Explcitly construct a Scalar from a .NET scalar.\n /// </summary>\n /// <param name=\"value\">The input scalar value</param>\n public static Scalar ToScalar(this Half value)\n {\n torch.InitializeDeviceType(DeviceType.CPU);\n return new Scalar(THSTorch_float16_to_scalar((float)value));\n }\n#endif\n\n /// <summary>\n /// Explcitly construct a Scalar from a .NET scalar.\n /// </summary>\n /// <param name=\"value\">The input scalar value</param>\n public static Scalar ToBFloat16Scalar(this float value)\n {\n torch.InitializeDeviceType(DeviceType.CPU);\n return new Scalar(THSTorch_bfloat16_to_scalar(value));\n }\n\n#if NET6_0_OR_GREATER\n /// <summary>\n /// Explicitly convert a Scalar value to a .NET scalar\n /// </summary>\n /// <param name=\"value\">The input value.</param>\n public static Half ToHalf(this Scalar value)\n {\n Half res;\n THSTorch_scalar_to_float16(value.Handle, out res);\n return res;\n }\n#endif\n\n /// <summary>\n /// Explicitly convert a Scalar value to a .NET scalar\n /// </summary>\n /// <param name=\"value\">The input value.</param>\n public static float ToSingle(this Scalar value)\n {\n return THSTorch_scalar_to_float32(value.Handle);\n }\n\n /// <summary>\n /// Explicitly convert a Scalar value to a .NET scalar\n /// </summary>\n /// <param name=\"value\">The input value.</param>\n public static double ToDouble(this Scalar value)\n {\n return THSTorch_scalar_to_float64(value.Handle);\n }\n\n /// <summary>\n /// Explicitly convert a Scalar value to a .NET scalar\n /// </summary>\n /// <param name=\"value\">The input value.</param>\n public static sbyte ToSByte(this Scalar value)\n {\n return THSTorch_scalar_to_int8(value.Handle);\n }\n\n /// <summary>\n /// Explicitly convert a Scalar value to a .NET scalar\n /// </summary>\n /// <param name=\"value\">The input value.</param>\n public static byte ToByte(this Scalar value)\n {\n return THSTorch_scalar_to_uint8(value.Handle);\n }\n\n /// <summary>\n /// Explicitly convert a Scalar value to a .NET scalar\n /// </summary>\n /// <param name=\"value\">The input value.</param>\n public static short ToInt16(this Scalar value)\n {\n return THSTorch_scalar_to_int16(value.Handle);\n }\n\n /// <summary>\n /// Explicitly convert a Scalar value to a .NET scalar\n /// </summary>\n /// <param name=\"value\">The input value.</param>\n public static int ToInt32(this Scalar value)\n {\n return THSTorch_scalar_to_int32(value.Handle);\n }\n\n /// <summary>\n /// Explicitly convert a Scalar value to a .NET scalar\n /// </summary>\n /// <param name=\"value\">The input value.</param>\n public static long ToInt64(this Scalar value)\n {\n return THSTorch_scalar_to_int64(value.Handle);\n }\n\n /// <summary>\n /// Explicitly convert a Scalar value to a .NET scalar\n /// </summary>\n /// <param name=\"value\">The input value.</param>\n public static bool ToBoolean(this Scalar value)\n {\n return THSTorch_scalar_to_bool(value.Handle);\n }\n\n /// <summary>\n /// Explicitly convert a Scalar value to a .NET scalar\n /// </summary>\n /// <param name=\"value\">The input value.</param>\n public static (float Real, float Imaginary) ToComplexFloat32(this Scalar value)\n {\n float[] floatArray;\n\n using (var pa = new PinnedArray<float>()) {\n THSTorch_scalar_to_complex32(value.Handle, pa.CreateArray);\n torch.CheckForErrors();\n floatArray = pa.Array;\n }\n\n return (floatArray[0], floatArray[1]);\n }\n\n /// <summary>\n /// Explicitly convert a Scalar value to a .NET scalar\n /// </summary>\n /// <param name=\"value\">The input value.</param>\n public static System.Numerics.Complex ToComplexFloat64(this Scalar value)\n {\n double[] floatArray;\n\n using (var pa = new PinnedArray<double>()) {\n THSTorch_scalar_to_complex64(value.Handle, pa.CreateArray);\n torch.CheckForErrors();\n floatArray = pa.Array;\n }\n\n return new System.Numerics.Complex(floatArray[0], floatArray[1]);\n }\n }\n}\n" }, { "alpha_fraction": 0.44416046142578125, "alphanum_fraction": 0.4861218333244324, "avg_line_length": 45.34986114501953, "blob_id": "f02e214827122828eb18f9e775b990d92571f576", "content_id": "be2fad4e2924ad40f71ebfb613866ddd7655077d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 16825, "license_type": "permissive", "max_line_length": 235, "num_lines": 363, "path": "/src/TorchVision/models/GoogleNet.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class models\n {\n /// <summary>\n /// ResNet-18\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"transform_input\"></param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"dropout\">The dropout rate for most blocks.</param>\n /// <param name=\"dropout_aux\">The dropout rate for the aux blocks.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.inception_v3(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be 299x299. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.GoogleNet googlenet(\n int num_classes = 1000,\n bool transform_input = false,\n string? weights_file = null,\n bool skipfc = true,\n float dropout = 0.2f,\n float dropout_aux = 0.7f,\n Device? device = null)\n {\n return new Modules.GoogleNet(num_classes, transform_input, weights_file, skipfc, dropout, dropout_aux, device);\n }\n }\n }\n\n namespace Modules\n {\n public class GoogleNet : Module<Tensor, Tensor>\n {\n // The code here is based on\n // https://github.com/pytorch/vision/blob/main/torchvision/models/googlenet.py\n // Licence and copypright notice at: https://github.com/pytorch/vision/blob/main/LICENSE\n\n private readonly Module<Tensor, Tensor> conv1;\n private readonly Module<Tensor, Tensor> maxpool1;\n private readonly Module<Tensor, Tensor> conv2;\n private readonly Module<Tensor, Tensor> conv3;\n private readonly Module<Tensor, Tensor> maxpool2;\n private readonly Module<Tensor, Tensor> inception3a;\n private readonly Module<Tensor, Tensor> inception3b;\n private readonly Module<Tensor, Tensor> maxpool3;\n private readonly Module<Tensor, Tensor> inception4a;\n private readonly Module<Tensor, Tensor> inception4b;\n private readonly Module<Tensor, Tensor> inception4c;\n private readonly Module<Tensor, Tensor> inception4d;\n private readonly Module<Tensor, Tensor> inception4e;\n private readonly Module<Tensor, Tensor> maxpool4;\n private readonly Module<Tensor, Tensor> inception5a;\n private readonly Module<Tensor, Tensor> inception5b;\n //private readonly Module aux1;\n //private readonly Module aux2;\n\n private readonly AdaptiveAvgPool2d avgpool;\n private Dropout dropout;\n private readonly Linear fc;\n\n bool transform_input = false;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n conv1.Dispose(); conv2.Dispose(); conv3.Dispose();\n maxpool1.Dispose(); maxpool2.Dispose(); maxpool3.Dispose(); maxpool4.Dispose();\n inception3a.Dispose(); inception3b.Dispose();\n inception4a.Dispose(); inception5a.Dispose();\n inception4b.Dispose(); inception5b.Dispose();\n inception4c.Dispose(); inception4d.Dispose();\n inception4e.Dispose();\n avgpool.Dispose();\n dropout.Dispose();\n fc.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public GoogleNet(int numClasses = 1000,\n bool transform_input = false,\n string? weights_file = null,\n bool skipfc = true,\n float dropout = 0.2f,\n float dropout_aux = 0.7f,\n Device? device = null) : base(nameof(GoogleNet))\n {\n this.transform_input = transform_input;\n\n conv1 = conv_block(3, 64, kernel_size: 7, stride: 2, padding: 3);\n maxpool1 = MaxPool2d(kernelSize: 3, stride: 2, ceilMode: true);\n conv2 = conv_block(64, 64, kernel_size: 1);\n conv3 = conv_block(64, 192, kernel_size: 3, padding: 1);\n maxpool2 = MaxPool2d(kernelSize: 3, stride: 2, ceilMode: true);\n\n inception3a = inception_block(192, 64, 96, 128, 16, 32, 32);\n inception3b = inception_block(256, 128, 128, 192, 32, 96, 64);\n maxpool3 = nn.MaxPool2d(3, stride: 2, ceilMode: true);\n\n inception4a = inception_block(480, 192, 96, 208, 16, 48, 64);\n inception4b = inception_block(512, 160, 112, 224, 24, 64, 64);\n inception4c = inception_block(512, 128, 128, 256, 24, 64, 64);\n inception4d = inception_block(512, 112, 144, 288, 32, 64, 64);\n inception4e = inception_block(528, 256, 160, 320, 32, 128, 128);\n maxpool4 = nn.MaxPool2d(2, stride: 2, ceilMode: true);\n\n inception5a = inception_block(832, 256, 160, 320, 32, 128, 128);\n inception5b = inception_block(832, 384, 192, 384, 48, 128, 128);\n\n //aux1 = inception_aux_block(512, numClasses, dropout_aux);\n //aux2 = inception_aux_block(528, numClasses, dropout_aux);\n\n avgpool = nn.AdaptiveAvgPool2d((1, 1));\n this.dropout = nn.Dropout(p: dropout);\n fc = nn.Linear(1024, numClasses);\n\n RegisterComponents();\n\n if (string.IsNullOrEmpty(weights_file)) {\n\n foreach (var (_, m) in named_modules()) {\n switch (m) {\n case TorchSharp.Modules.Conv2d conv:\n torch.nn.init.kaiming_normal_(conv.weight, mode: init.FanInOut.FanOut, nonlinearity: init.NonlinearityType.ReLU);\n break;\n case TorchSharp.Modules.BatchNorm2d bn:\n torch.nn.init.constant_(bn.weight, 1);\n torch.nn.init.constant_(bn.bias, 0);\n break;\n }\n }\n } else {\n\n foreach (var (_, m) in named_modules()) {\n switch (m) {\n case TorchSharp.Modules.Linear ln:\n torch.nn.init.normal_(ln.weight, 0, 0.01);\n torch.nn.init.constant_(ln.bias, 0);\n break;\n }\n }\n this.load(weights_file, skip: skipfc ? new[] { \"fc.weight\", \"fc.bias\", \"AuxLogits.fc.weight\", \"AuxLogits.fc.bias\" } : null);\n }\n\n if (device != null && device.type == DeviceType.CUDA)\n this.to(device);\n }\n\n\n private static Module<Tensor, Tensor> conv_block(int in_channels, int out_channels, int kernel_size, int stride = 1, int padding = 0)\n {\n return Sequential(\n (\"conv\", Conv2d(in_channels, out_channels, bias: false, kernelSize: kernel_size, stride: stride, padding: padding)),\n (\"bn\", BatchNorm2d(out_channels, eps: 0.001)),\n (\"relu\", ReLU(true))\n );\n }\n\n private static Module<Tensor, Tensor> conv_block(int in_channels, int out_channels, (long, long) kernel_size, (long, long)? stride = null, (long, long)? padding = null)\n {\n return Sequential(\n (\"conv\", Conv2d(in_channels, out_channels, bias: false, kernelSize: kernel_size, stride: stride, padding: padding)),\n (\"bn\", BatchNorm2d(out_channels, eps: 0.001)),\n (\"relu\", ReLU(true))\n );\n }\n\n private Module<Tensor, Tensor> inception_block(int in_channels, int ch1x1, int ch3x3red, int ch3x3, int ch5x5red, int ch5x5, int pool_proj) => new Inception(in_channels, ch1x1, ch3x3red, ch3x3, ch5x5red, ch5x5, pool_proj);\n private Module<Tensor, Tensor> inception_aux_block(int in_channels, int num_classes, float dropout) => new InceptionAux(in_channels, num_classes, dropout);\n\n public override Tensor forward(Tensor x)\n {\n // Transform\n using (var scope = NewDisposeScope()) {\n if (transform_input) {\n\n var x_ch0 = torch.unsqueeze(x[(null, null), 0], 1) * (0.229f / 0.5f) + (0.485f - 0.5f) / 0.5f;\n var x_ch1 = torch.unsqueeze(x[(null, null), 1], 1) * (0.224f / 0.5f) + (0.456f - 0.5f) / 0.5f;\n var x_ch2 = torch.unsqueeze(x[(null, null), 2], 1) * (0.225f / 0.5f) + (0.406f - 0.5f) / 0.5f;\n x = torch.cat(new[] { x_ch0, x_ch1, x_ch2 }, 1);\n }\n\n // N x 3 x 224 x 224\n x = conv1.call(x);\n // N x 64 x 112 x 112\n x = maxpool1.call(x);\n // N x 64 x 56 x 56\n x = conv2.call(x);\n // N x 64 x 56 x 56\n x = conv3.call(x);\n // N x 192 x 56 x 56\n x = maxpool2.call(x);\n\n // N x 192 x 28 x 28\n x = inception3a.call(x);\n // N x 256 x 28 x 28\n x = inception3b.call(x);\n // N x 480 x 28 x 28\n x = maxpool3.call(x);\n // N x 480 x 14 x 14\n x = inception4a.call(x);\n // N x 512 x 14 x 14\n //Tensor aux1;\n //if (this.aux1 is not null)\n // aux1 = this.aux1.call(x);\n\n x = inception4b.call(x);\n // N x 512 x 14 x 14\n x = inception4c.call(x);\n // N x 512 x 14 x 14\n x = inception4d.call(x);\n // N x 528 x 14 x 14\n //Tensor aux2;\n //if (this.aux2 is not null)\n // aux2 = this.aux2.call(x);\n\n x = inception4e.call(x);\n // N x 832 x 14 x 14\n x = maxpool4.call(x);\n // N x 832 x 7 x 7\n x = inception5a.call(x);\n // N x 832 x 7 x 7\n x = inception5b.call(x);\n // N x 1024 x 7 x 7\n\n x = avgpool.call(x);\n // N x 1024 x 1 x 1\n x = torch.flatten(x, 1);\n // N x 1024\n x = dropout.call(x);\n x = fc.call(x);\n // N x 1000 .call(num_classes);\n\n return x.MoveToOuterDisposeScope();\n }\n }\n\n class Inception : Module<Tensor, Tensor>\n {\n public Inception(int in_channels, int ch1x1, int ch3x3red, int ch3x3, int ch5x5red, int ch5x5, int pool_proj) : base(\"Inception\")\n {\n branch1 = conv_block(in_channels, ch1x1, kernel_size: 1);\n branch2 = nn.Sequential(\n conv_block(in_channels, ch3x3red, kernel_size: 1),\n conv_block(ch3x3red, ch3x3, kernel_size: 3, padding: 1)\n );\n branch3 = nn.Sequential(\n conv_block(in_channels, ch5x5red, kernel_size: 1),\n conv_block(ch5x5red, ch5x5, kernel_size: 3, padding: 1)\n );\n branch4 = nn.Sequential(\n nn.MaxPool2d(kernelSize: 3, stride: 1, padding: 1, ceilMode: true),\n conv_block(in_channels, pool_proj, kernel_size: 1)\n );\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor x)\n {\n using var branch1 = this.branch1.call(x);\n using var branch2 = this.branch2.call(x);\n using var branch3 = this.branch3.call(x);\n using var branch4 = this.branch4.call(x);\n\n var outputs = new[] { branch1, branch2, branch3, branch4 };\n return torch.cat(outputs, 1);\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n branch1.Dispose(); branch2.Dispose(); branch3.Dispose();\n branch4.Dispose();\n }\n base.Dispose(disposing);\n }\n\n private readonly Module<Tensor, Tensor> branch1;\n private readonly Module<Tensor, Tensor> branch2;\n private readonly Module<Tensor, Tensor> branch3;\n private readonly Module<Tensor, Tensor> branch4;\n }\n\n class InceptionAux : Module<Tensor, Tensor>\n {\n private readonly Module<Tensor, Tensor> conv;\n private readonly Module<Tensor, Tensor> fc1;\n private readonly Module<Tensor, Tensor> fc2;\n private readonly Module<Tensor, Tensor> dropout;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n conv.Dispose(); fc1.Dispose(); fc2.Dispose();\n dropout.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public InceptionAux(int in_channels, int num_classes, float dropout = 0.7f) : base(\"InceptionAux\")\n {\n conv = conv_block(in_channels, 128, kernel_size: 1);\n fc1 = nn.Linear(2048, 1024);\n fc2 = nn.Linear(1024, num_classes);\n this.dropout = nn.Dropout(p: dropout);\n\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor x)\n {\n // aux1: N x 512 x 14 x 14, aux2: N x 528 x 14 x 14\n x = functional.adaptive_avg_pool2d(x, 4);\n // aux1: N x 512 x 4 x 4, aux2: N x 528 x 4 x 4\n x = conv.call(x);\n // N x 128 x 4 x 4\n x = torch.flatten(x);\n // N x 2048\n // Adaptive average pooling\n x = functional.relu(fc1.call(x), inplace:true);\n // N x 1024\n x = dropout.call(x);\n // N x 1024\n x = fc2.call(x);\n // N x 1000\n\n return x;\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5854326486587524, "alphanum_fraction": 0.5854326486587524, "avg_line_length": 37.87234115600586, "blob_id": "051e11ecf7a44413afa66d1a1066be5eae358df8", "content_id": "254aa14ccd72201b50669d441bfab849fff35c64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1826, "license_type": "permissive", "max_line_length": 173, "num_lines": 47, "path": "/src/TorchVision/IO/NotImplemented.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System.IO;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class io\n {\n public class NotImplementedImager : Imager\n {\n System.Exception exp = new System.NotImplementedException(\"You need to provide your own DefaultImager or specify the Imager for all image I/O method calls\");\n public override Tensor DecodeImage(Stream image, ImageReadMode mode = ImageReadMode.UNCHANGED)\n {\n throw exp;\n }\n\n public override Tensor DecodeImage(byte[] data, ImageReadMode mode = ImageReadMode.UNCHANGED)\n {\n throw new System.NotImplementedException();\n }\n\n public override Task<Tensor> DecodeImageAsync(Stream stream, ImageReadMode mode = ImageReadMode.UNCHANGED, CancellationToken cancellationToken = default)\n {\n throw exp;\n }\n public override void EncodeImage(Tensor image, ImageFormat format, Stream stream)\n {\n throw exp;\n }\n\n public override byte[] EncodeImage(Tensor image, ImageFormat format)\n {\n throw new System.NotImplementedException();\n }\n\n public override Task EncodeImageAsync(Tensor image, ImageFormat format, Stream stream, CancellationToken cancellationToken = default)\n {\n throw exp;\n }\n }\n }\n }\n}" }, { "alpha_fraction": 0.8109452724456787, "alphanum_fraction": 0.8109452724456787, "avg_line_length": 24.25, "blob_id": "ae30e327ebfa4849ba8e74cbcd4513127c79e406", "content_id": "56333c2e4a772142dd9f056b3d1d38997498976e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 203, "license_type": "permissive", "max_line_length": 58, "num_lines": 8, "path": "/src/TorchSharp/PInvoke/GCHandleDeleter.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System;\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp.PInvoke\n{\n [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\n internal delegate void GCHandleDeleter(IntPtr memory);\n}" }, { "alpha_fraction": 0.5684669613838196, "alphanum_fraction": 0.572912335395813, "avg_line_length": 48.323768615722656, "blob_id": "edbb69927d273f37965e55b59d1099c4bbda8504", "content_id": "d20234aef74d6927312235a04261617957a039c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 24070, "license_type": "permissive", "max_line_length": 250, "num_lines": 488, "path": "/src/TorchSharp/Tensor/Factories/Tensor.Factories.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Collections.Concurrent;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing TorchSharp.Utils;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n /// <summary>\n /// Creates 1-D tensor of size [(stop - start) / step] with values from interval [start, stop) and\n /// common difference step, starting from start\n /// </summary>\n /// <param name=\"start\">The starting value for the set of points.</param>\n /// <param name=\"stop\">The ending value for the set of points</param>\n /// <param name=\"step\">The gap between each pair of adjacent points.</param>\n /// <param name=\"dtype\">the desired data type of returned tensor.\n /// Default: if null, uses a global default (see torch.set_default_tensor_type()).\n /// If dtype is not given, infer the data type from the other input arguments.\n /// If any of start, end, or stop are floating-point, the dtype is inferred to be the default dtype, see get_default_dtype().\n /// Otherwise, the dtype is inferred to be torch.int64.</param>\n /// <param name=\"device\"></param>\n /// <param name=\"requires_grad\"> If autograd should record operations on the returned tensor. Default: false.</param>\n public static Tensor arange(Scalar start, Scalar stop, Scalar step, ScalarType? dtype = null, Device? device = null, bool requires_grad = false)\n {\n device = InitializeDevice(device);\n\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n if (start.Type.IsIntegral() && stop.Type.IsIntegral() && step.Type.IsIntegral()) {\n dtype = ScalarType.Int64;\n } else {\n dtype = get_default_dtype();\n }\n }\n\n if (dtype == ScalarType.ComplexFloat32) {\n return ComplexFloat32Tensor.arange(start, stop, step, device, requires_grad);\n } else if (dtype == ScalarType.ComplexFloat64) {\n return ComplexFloat64Tensor.arange(start, stop, step, device, requires_grad);\n }\n\n var handle = THSTensor_arange(start.Handle, stop.Handle, step.Handle, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_arange(start.Handle, stop.Handle, step.Handle, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(handle);\n }\n\n /// <summary>\n /// Creates 1-D tensor of size [(stop - start) / step] with values from interval [start, stop) and\n\t\t/// common difference step, starting from start\n /// </summary>\n public static Tensor arange(Scalar start, Scalar stop, ScalarType? dtype = null, Device? device = null, bool requires_grad = false)\n {\n return arange(start, stop, 1, dtype, device, requires_grad);\n }\n\n /// <summary>\n /// Creates 1-D tensor of size [(stop - 0)] with values from interval [0, stop), starting from 0\n /// </summary>\n public static Tensor arange(Scalar stop, ScalarType? dtype = null, Device? device = null, bool requires_grad = false)\n {\n return arange(0, stop, 1, dtype, device, requires_grad);\n }\n\n /// <summary>\n /// Create a 2-D tensor with ones on the diagonal and zeros elsewhere.\n /// </summary>\n public static Tensor eye(long rows, long columns = -1L, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n device = InitializeDevice(device);\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n dtype = get_default_dtype();\n }\n\n columns = (columns == -1) ? rows : columns;\n\n var handle = THSTensor_eye(rows, columns, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_eye(rows, columns, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n var result = new Tensor(handle);\n\n if (names != null && names.Length > 0) {\n\n result.rename_(names);\n }\n\n return result;\n }\n\n /// <summary>\n /// Similar to the function above, but the means and standard deviations are shared among all drawn elements. The resulting tensor has size given by size.\n /// </summary>\n /// <param name=\"mean\">The mean for all distributions</param>\n /// <param name=\"std\">The standard deviation for all distributions</param>\n /// <param name=\"size\">A sequence of integers defining the shape of the output tensor.</param>\n /// <param name=\"dtype\"></param>\n /// <param name=\"device\"></param>\n /// <param name=\"requires_grad\"></param>\n /// <param name=\"generator\">An optional random number generator</param>\n /// <param name=\"names\">Names of the dimensions of the tensor.</param>\n /// <returns></returns>\n public static Tensor normal(double mean, double std, ReadOnlySpan<long> size, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, Generator? generator = null, string[]? names = null)\n {\n return randn(size, dtype: dtype, device: device, requires_grad: requires_grad, generator: generator) * std + mean;\n }\n\n private static Tensor _tensor_generic(Array rawArray, ReadOnlySpan<long> dimensions, sbyte origType, ScalarType? dtype, Device? device, bool requires_grad, bool clone = true, string[]? names = null)\n {\n {\n // Validate the sizes before handing over storage to native code...\n var prod = 1L;\n foreach (var sz in dimensions) prod *= sz;\n\n if (origType == (sbyte)ScalarType.ComplexFloat32)\n prod *= 2;\n\n if (prod != rawArray.LongLength)\n throw new ArgumentException($\"mismatched total size creating a tensor from an array: {prod} vs. {rawArray.LongLength}\");\n }\n\n device = InitializeDevice(device);\n\n if (clone) { rawArray = (Array)rawArray.Clone(); }\n\n var dataHandle = GCHandle.Alloc(rawArray, GCHandleType.Pinned);\n var dataArrayAddr = dataHandle.AddrOfPinnedObject();\n var gchp = GCHandle.ToIntPtr(dataHandle);\n TorchSharp.PInvoke.GCHandleDeleter deleter = null!;\n deleter = new TorchSharp.PInvoke.GCHandleDeleter((IntPtr ptr) => {\n GCHandle.FromIntPtr(gchp).Free();\n deleters.TryRemove(deleter, out deleter!);\n });\n deleters.TryAdd(deleter, deleter); // keep the delegate alive\n\n unsafe {\n fixed (long* shape = dimensions) {\n var handle = THSTensor_new(dataArrayAddr, deleter, (IntPtr)shape, dimensions.Length, origType, requires_grad);\n\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_new(dataArrayAddr, deleter, (IntPtr)shape, dimensions.Length, origType, requires_grad);\n }\n\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n var tensor = new Tensor(handle);\n\n var needsConversion = dtype.HasValue && dtype.Value != (ScalarType)origType;\n\n if (device is not null) {\n tensor = needsConversion ? tensor.to(dtype!.Value, device) : tensor.to(device);\n } else if (needsConversion) {\n tensor = tensor.to_type(dtype!.Value);\n }\n if (names != null && names.Length > 0) {\n tensor.rename_(names);\n }\n return tensor;\n }\n }\n }\n\n /// <summary>\n /// Creates a <see cref=\"torch.Tensor\">torch tensor</see> from an arbitrary <see cref=\"Array\">array</see>.\n /// </summary>\n /// <param name=\"rawArray\">The arbitrary array to create the tensor from.</param>\n /// <param name=\"device\">The device where the tensor is to be located. Defaults to 'cpu'.</param>\n /// <returns>A <see cref=\"torch.Tensor\">torch tensor</see></returns>\n /// <remarks>\n /// This function roughly corresponds to torch.from_numpy(). It shares the underlying buffer between the input and output.\n /// torch.tensor() always makes a copy, which can be orders of magnitude slower.\n /// </remarks>\n /// <exception cref=\"InvalidOperationException\">\n /// When <see cref=\"Type.GetElementType()\">Array.GetType().GetElementType()</see> does not return the .NET element type.\n /// </exception>\n /// <exception cref=\"NotSupportedException\">\n /// When <see cref=\"Type.GetElementType()\">Array.GetType().GetElementType()</see> returns an unsupported .NET element type.\n /// Supported element types are <see cref=\"bool\" />, <see cref=\"byte\" />, <see cref=\"sbyte\" />, <see cref=\"short\" />,\n /// <see cref=\"int\" />, <see cref=\"long\" />, <see cref=\"float\" />, <see cref=\"double\" />,\n /// and <see cref=\"System.Numerics.Complex\" />.\n /// </exception>\n /// <example>\n /// Tensor from array of rank 1\n /// <code>\n /// var array = new double[] { { 1, 2, 3, 4, 5, 6, 7, 8 } };\n /// var tensor = torch.from_array(rawArray: array, dtype: ScalarType.Float64, device: Device.CPU, requires_grad: false);\n /// </code>\n /// Tensor from array of rank 2\n /// <code>\n /// var array = new double[,] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };\n /// var tensor = torch.from_array(rawArray: array, dtype: ScalarType.Float64, device: Device.CPU, requires_grad: false);\n /// </code>\n /// Tensor from array of rank 3\n /// <code>\n /// var array = new double[,,] { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };\n /// var tensor = torch.from_array(rawArray: array, dtype: ScalarType.Float64, device: Device.CPU, requires_grad: false);\n /// </code>\n /// </example>\n [Pure]\n public static Tensor from_array(Array rawArray, Device? device = null)\n {\n var t = rawArray.GetType().GetElementType();\n if (t is null) throw new InvalidOperationException($\"{nameof(rawArray)}.GetType().GetElementType() returned null.\");\n if (t == typeof((float, float))) throw new NotImplementedException(\"from_array() for (float,float) elements.\");\n\n var dtype = ToScalarType(t!);\n\n return from_array(rawArray, dtype, device is null ? CPU : device);\n }\n\n /// <summary>\n /// Creates a <see cref=\"torch.Tensor\">torch tensor</see> from an arbitrary <see cref=\"Array\">array</see>.\n /// </summary>\n /// <param name=\"rawArray\">The arbitrary array to create the tensor from.</param>\n /// <param name=\"dtype\">The element type to use in the created tensor. This can be different from the element type of the input.</param>\n /// <param name=\"device\">The device where the tensor is to be located. Defaults to 'cpu'.</param>\n /// <param name=\"requires_grad\"></param>\n /// <param name=\"names\"></param>\n /// <returns></returns>\n /// <exception cref=\"InvalidOperationException\"></exception>\n [Pure]\n public static Tensor from_array(Array rawArray, ScalarType? dtype, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n // enumerates over all dimensions of the arbitrary array\n // and returns the length of the dimension\n [Pure]\n static long[] GetShape(Array arr)\n {\n var shape = new long[arr.Rank];\n for (var dim = 0; dim < arr.Rank; dim++)\n shape[dim] = arr.GetLength(dim);\n return shape;\n }\n var shape = GetShape(rawArray);\n\n var t = rawArray.GetType().GetElementType();\n if (t is null) throw new InvalidOperationException($\"{nameof(rawArray)}.GetType().GetElementType() returned null.\");\n\n // call the existing factory methods to construct the tensor\n\n if (t == typeof((float, float))) return tensor(rawArray.Cast<(float, float)>().ToArray(), shape, dtype, device, requires_grad, names: names);\n\n var origType = ToScalarType(t);\n return _tensor_generic(rawArray, shape, (sbyte)origType, dtype, device, requires_grad, false, names);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.as_tensor\n public static Tensor as_tensor(Array data, ScalarType? dtype = null, Device? device = null) => from_array(data, dtype, device, false);\n\n /// <summary>\n /// Creates a 1-dimensional Tensor from an array of n dimensions.\n ///\n /// Skips the first offset bytes in the buffer, and interprets the rest of the raw bytes as a 1-dimensional tensor of type dtype with count elements.\n /// </summary>\n /// <param name=\"rawArray\">The input array</param>\n /// <param name=\"dtype\">The torch data type.</param>\n /// <param name=\"count\"></param>\n /// <param name=\"offset\"></param>\n /// <param name=\"requires_grad\">Set <value>true</value> if gradients need to be computed for this Tensor; <value>false</value> otherwise.</param>\n /// <returns></returns>\n /// <exception cref=\"ArgumentException\"></exception>\n /// <exception cref=\"IndexOutOfRangeException\"></exception>\n /// <remarks>The returned tensor and buffer share the same memory. Modifications to the tensor will be reflected in the buffer and vice versa.</remarks>\n public static Tensor frombuffer(Array rawArray, ScalarType dtype, long count = -1, long offset = 0, bool requires_grad = false)\n {\n InitializeDeviceType(DeviceType.CPU);\n\n var lLength = rawArray.LongLength;\n\n if (offset < 0 || offset >= lLength) {\n throw new ArgumentException($\"invalid value for 'offset': {offset}\");\n }\n\n if (count < 0) { count = lLength - offset; }\n\n if (count > lLength - offset) {\n throw new IndexOutOfRangeException($\"element count is too large: {count}\");\n }\n\n var t = rawArray.GetType().GetElementType();\n ScalarType origType = ToScalarType(t!);\n\n switch (origType) {\n case ScalarType.Int16:\n offset *= 2;\n break;\n case ScalarType.Int32:\n case ScalarType.Float32:\n offset *= 4;\n break;\n case ScalarType.Int64:\n case ScalarType.Float64:\n offset *= 8;\n break;\n case ScalarType.ComplexFloat64:\n offset *= 16;\n break;\n case ScalarType.ComplexFloat32:\n // Since we are not allowed to make a copy of the buffer, it's currently not\n // feasible to support complex types, which GCHandle.Alloc() doesn't like.\n throw new NotImplementedException(\"frombuffer(ComplexFloat32)\");\n }\n\n var dataHandle = GCHandle.Alloc(rawArray, GCHandleType.Pinned);\n var dataArrayAddr = dataHandle.AddrOfPinnedObject();\n var gchp = GCHandle.ToIntPtr(dataHandle);\n TorchSharp.PInvoke.GCHandleDeleter deleter = null!;\n deleter = new TorchSharp.PInvoke.GCHandleDeleter((IntPtr ptr) => {\n GCHandle.FromIntPtr(gchp).Free();\n deleters.TryRemove(deleter, out deleter!);\n });\n deleters.TryAdd(deleter, deleter); // keep the delegate alive\n\n unsafe {\n var handle = THSTensor_frombuffer(dataArrayAddr, deleter, count, offset, (sbyte)origType, requires_grad);\n\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_frombuffer(dataArrayAddr, deleter, count, offset, (sbyte)origType, requires_grad);\n }\n\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n var tensor = new Tensor(handle);\n\n var needsConversion = dtype != origType;\n\n if (needsConversion) {\n tensor = tensor.to_type(dtype);\n }\n return tensor;\n }\n }\n\n /// <summary>\n /// Create a sparse tensor by indexing into an existing dense tensor.\n /// </summary>\n public static Tensor sparse(Tensor indices, Tensor values, long[] size, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n device = InitializeDevice(device);\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n dtype = values.dtype;\n }\n\n unsafe {\n fixed (long* psizes = size) {\n var handle = THSTensor_sparse(indices.Handle, values.Handle, (IntPtr)psizes, size.Length, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_sparse(indices.Handle, values.Handle, (IntPtr)psizes, size.Length, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n var tensor = new Tensor(handle);\n if (names != null && names.Length > 0) {\n tensor.rename_(names);\n }\n return tensor;\n }\n }\n }\n\n /// <summary>\n /// Constructs a complex tensor with its real part equal to real and its imaginary part equal to imag.\n /// </summary>\n public static Tensor complex(Tensor real, Tensor imag)\n {\n var res = THSTensor_complex(real.Handle, imag.Handle);\n if (res == IntPtr.Zero)\n CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Constructs a complex tensor whose elements are Cartesian coordinates corresponding to the polar coordinates with absolute value 'abs' and angle 'angle'.\n /// </summary>\n public static Tensor polar(Tensor abs, Tensor angle)\n {\n var res = THSTensor_polar(abs.Handle, angle.Handle);\n if (res == IntPtr.Zero)\n CheckForErrors();\n return new Tensor(res);\n }\n\n public static Tensor from_file(string filename, bool? shared = null, long? size = 0, ScalarType? dtype = null, Device? device = null, bool requires_grad = false)\n {\n device = InitializeDevice(device);\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n dtype = get_default_dtype();\n }\n\n var handle = THSTensor_from_file(StringEncoder.GetNullTerminatedUTF8ByteArray(filename), (sbyte)(!shared.HasValue ? -1 : shared.Value ? 1 : 0), size.HasValue ? size.Value : -1, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(handle);\n }\n\n /// <summary>\n /// Create a one-dimensional tensor of size steps whose values are evenly spaced from start to end, inclusive.\n /// </summary>\n public static Tensor linspace(double start, double end, long steps, ScalarType? dtype = null, Device? device = null, bool requires_grad = false)\n {\n device = InitializeDevice(device);\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n dtype = get_default_dtype();\n }\n\n var handle = THSTensor_linspace(start, end, steps, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_linspace(start, end, steps, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(handle);\n }\n\n /// <summary>\n /// Creates a one-dimensional tensor of size steps whose values are evenly spaced from base^start to base^end, inclusive, on a logarithmic scale with base 'base.'\n /// </summary>\n public static Tensor logspace(double start, double end, long steps, double @base = 10, ScalarType? dtype = null, Device? device = null, bool requires_grad = false)\n {\n device = InitializeDevice(device);\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n dtype = get_default_dtype();\n }\n\n var handle = THSTensor_logspace(start, end, steps, @base, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_logspace(start, end, steps, @base, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(handle);\n }\n\n private static void ValidateIntegerRange(long value, ScalarType dtype, string argument)\n {\n switch (dtype) {\n case ScalarType.Byte:\n if (value < byte.MinValue || value > byte.MaxValue)\n throw new ArgumentOutOfRangeException(argument, value, $\"The value is outside the range of {dtype}\");\n break;\n case ScalarType.Int8:\n if (value < sbyte.MinValue || value > sbyte.MaxValue)\n throw new ArgumentOutOfRangeException(argument, value, $\"The value is outside the range of {dtype}\");\n break;\n case ScalarType.Int16:\n if (value < short.MinValue || value > short.MaxValue)\n throw new ArgumentOutOfRangeException(argument, value, $\"The value is outside the range of {dtype}\");\n break;\n case ScalarType.Int32:\n if (value < int.MinValue || value > int.MaxValue)\n throw new ArgumentOutOfRangeException(argument, value, $\"The value is outside the range of {dtype}\");\n break;\n default:\n break;\n }\n }\n\n private static ConcurrentDictionary<TorchSharp.PInvoke.GCHandleDeleter, TorchSharp.PInvoke.GCHandleDeleter> deleters;\n private static ScalarType default_dtype = ScalarType.Float32;\n\n static torch()\n {\n deleters = new ConcurrentDictionary<TorchSharp.PInvoke.GCHandleDeleter, TorchSharp.PInvoke.GCHandleDeleter>();\n }\n }\n}\n" }, { "alpha_fraction": 0.4561717212200165, "alphanum_fraction": 0.4561717212200165, "avg_line_length": 20.538461685180664, "blob_id": "e25b81e1d10c1b85635d13fcc62499a651fc1e57", "content_id": "f6d0f975077e0fef9f2e250f6d34e9ff073b34a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 559, "license_type": "permissive", "max_line_length": 130, "num_lines": 26, "path": "/src/TorchVision/IO/ImageFormat.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n /// <summary>\n /// File format for an image.\n /// </summary>\n public enum ImageFormat\n {\n Unknown,\n Png,\n Jpeg,\n Bmp,\n Gif,\n Tiff,\n Emf,\n Exif,\n Wmf,\n Pbm,\n Tga,\n Webp,\n }\n }\n}" }, { "alpha_fraction": 0.5085046887397766, "alphanum_fraction": 0.5126935839653015, "avg_line_length": 51.87248229980469, "blob_id": "1a8a132d93d296f28561375304f92014979d2535", "content_id": "b4d59b5ea44799a406302cd9b65dcd3912089b39", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7878, "license_type": "permissive", "max_line_length": 199, "num_lines": 149, "path": "/src/TorchSharp/NN/Pooling/MaxPool1D.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Linq;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a MaxPool1D module.\n /// </summary>\n public sealed class MaxPool1d : torch.nn.Module<Tensor, Tensor>\n {\n internal MaxPool1d(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_MaxPool1d_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public (Tensor Values, Tensor Indices) forward_with_indices(Tensor tensor)\n {\n var res = THSNN_MaxPool1d_forward_with_indices(handle, tensor.Handle, out var indices);\n if (res == IntPtr.Zero || indices == IntPtr.Zero) { torch.CheckForErrors(); }\n return (new Tensor(res), new Tensor(indices));\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies a 1D max pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"kernelSize\">The size of the sliding window, must be > 0.</param>\n /// <param name=\"stride\">The stride of the sliding window, must be > 0. Default value is kernel_size.</param>\n /// <param name=\"padding\">Implicit negative infinity padding to be added on both sides, must be >= 0 and less than or equal to kernel_size / 2</param>\n /// <param name=\"dilation\">The stride between elements within a sliding window, must be > 0.</param>\n /// <param name=\"ceilMode\">If true, will use ceil instead of floor to compute the output shape. This ensures that every element in the input tensor is covered by a sliding window.</param>\n /// <returns></returns>\n public static MaxPool1d MaxPool1d(long kernelSize, long? stride = null, long? padding = null, long? dilation = null, bool ceilMode = false)\n {\n var pStride = stride.HasValue ? new long[] { stride.Value } : null;\n var pPadding = padding.HasValue ? new long[] { padding.Value } : null;\n var pDilation = dilation.HasValue ? new long[] { dilation.Value } : null;\n return MaxPool1d(new long[] { kernelSize }, pStride, pPadding, pDilation, ceilMode);\n }\n\n private static MaxPool1d MaxPool1d(long[] kernelSize, long[] strides = null, long[] padding = null, long[] dilation = null, bool ceilMode = false)\n {\n unsafe {\n fixed (long* pkernelSize = kernelSize, pstrides = strides, pPadding = padding, pDilation = dilation) {\n var handle = THSNN_MaxPool1d_ctor((IntPtr)pkernelSize, (IntPtr)pstrides, (IntPtr)pPadding, (IntPtr)pDilation, ceilMode, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new MaxPool1d(handle, boxedHandle);\n }\n }\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Applies a 1D max pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"kernelSize\"></param>\n /// <param name=\"stride\"></param>\n /// <param name=\"padding\"></param>\n /// <param name=\"dilation\"></param>\n /// <param name=\"ceil_mode\"></param>\n /// <returns></returns>\n public static Tensor max_pool1d(Tensor input, long kernelSize, long? stride = null,\n long? padding = null, long? dilation = null, bool ceil_mode = false)\n {\n var kernelSizes = new long[] { kernelSize };\n var strides = new long[] { stride ?? 1 };\n var paddings = new long[] { padding ?? 0 };\n var dilations = new long[] { dilation ?? 1 };\n unsafe {\n fixed (long* pkernelSize = kernelSizes, pstrides = strides, ppadding = paddings, pdilation = dilations) {\n var res =\n THSTensor_max_pool1d(input.Handle,\n (IntPtr)pkernelSize, kernelSizes.Length,\n (IntPtr)pstrides, strides.Length,\n (IntPtr)ppadding, paddings.Length,\n (IntPtr)pdilation, dilations.Length,\n ceil_mode);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Applies a 1D max pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"kernelSize\"></param>\n /// <param name=\"stride\"></param>\n /// <param name=\"padding\"></param>\n /// <param name=\"dilation\"></param>\n /// <param name=\"ceil_mode\"></param>\n /// <returns></returns>\n public static (Tensor output, Tensor indices) max_pool1d_with_indices(Tensor input, long kernelSize, long? stride = null,\n long? padding = null, long? dilation = null, bool ceil_mode = false)\n {\n var kernelSizes = new long[] { kernelSize };\n var strides = new long[] { stride ?? 1 };\n var paddings = new long[] { padding ?? 0 };\n var dilations = new long[] { dilation ?? 1 };\n IntPtr[] ptrArray;\n\n using (var pa = new PinnedArray<IntPtr>()) {\n unsafe {\n fixed (long* pkernelSize = kernelSizes, pstrides = strides, ppadding = paddings, pdilation = dilations) {\n THSTensor_max_pool1d_with_indices(input.Handle,\n pa.CreateArray,\n (IntPtr)pkernelSize, kernelSizes.Length,\n (IntPtr)pstrides, strides.Length,\n (IntPtr)ppadding, paddings.Length,\n (IntPtr)pdilation, dilations.Length,\n ceil_mode);\n torch.CheckForErrors();\n }\n }\n ptrArray = pa.Array;\n }\n return (new Tensor(ptrArray[0]), new Tensor(ptrArray[1]));\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5512006282806396, "alphanum_fraction": 0.5541440844535828, "avg_line_length": 41.74834442138672, "blob_id": "fe54f96d11498a33751ac17fbceb1bbc969c1ee3", "content_id": "3de2d6ea51d04bc545525839a59a4675880c9afc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6459, "license_type": "permissive", "max_line_length": 147, "num_lines": 151, "path": "/src/TorchSharp/Distributions/Poisson.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// A Poisson distribution parameterized by `rate`.\n /// </summary>\n public class Poisson : distributions.ExponentialFamily\n {\n public override Tensor mean => rate;\n\n public override Tensor variance => rate;\n\n public override Tensor mode => rate.floor();\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"rate\">rate = 1 / scale of the distribution (often referred to as 'β')</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n public Poisson(Tensor rate, Generator generator = null) : base(generator)\n {\n var locScale = broadcast_tensors(rate);\n batch_shape = rate.size();\n this.rate = locScale[0].alias().DetachFromDisposeScope();\n }\n\n private Tensor rate;\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n public override Tensor rsample(params long[] sample_shape)\n {\n using var _ = NewDisposeScope();\n var shape = ExtendedShape(sample_shape);\n using(no_grad())\n return torch.poisson(rate.expand(shape), generator: generator).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor log_prob(Tensor value)\n {\n using var _ = NewDisposeScope();\n var bcast = broadcast_tensors(rate, value);\n var r = bcast[0];\n var v = bcast[1];\n return (value.xlogy(r) - r - (value + 1).lgamma()).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns the cumulative density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor cdf(Tensor value)\n {\n return WrappedTensorDisposeScope(() => 1 - exp(-rate * value));\n }\n\n /// <summary>\n /// Returns the inverse cumulative density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor icdf(Tensor value)\n {\n return WrappedTensorDisposeScope(() => -log(1 - value) / rate);\n }\n\n /// <summary>\n /// Returns tensor containing all values supported by a discrete distribution. The result will enumerate over dimension 0, so the shape\n /// of the result will be `(cardinality,) + batch_shape + event_shape` (where `event_shape = ()` for univariate distributions).\n ///\n /// Note that this enumerates over all batched tensors in lock-step `[[0, 0], [1, 1], ...]`. With `expand=False`, enumeration happens\n /// along dim 0, but with the remaining batch dimensions being singleton dimensions, `[[0], [1], ..`\n /// </summary>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is Poisson))\n throw new ArgumentException(\"expand(): 'instance' must be a Poisson distribution\");\n\n var r = rate.expand(batch_shape);\n\n var newDistribution = ((instance == null) ? new Poisson(r, generator) : instance) as Poisson;\n\n newDistribution.batch_shape = batch_shape;\n if (newDistribution == instance) {\n newDistribution.rate = r;\n }\n return newDistribution;\n }\n\n protected override IList<Tensor> NaturalParams => new Tensor[] { rate.log() };\n\n protected override Tensor MeanCarrierMeasure => new Tensor(IntPtr.Zero);\n\n protected override Tensor LogNormalizer(params Tensor[] parameters) => parameters[0].exp();\n }\n\n }\n\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a Poisson distribution parameterized by `rate`.\n /// </summary>\n /// <param name=\"rate\">rate = 1 / scale of the distribution (often referred to as 'β')</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Poisson Poisson(Tensor rate, Generator generator = null)\n {\n return new Poisson(rate, generator);\n }\n\n /// <summary>\n /// Creates a Poisson distribution parameterized by `rate`.\n /// </summary>\n /// <param name=\"rate\">rate = 1 / scale of the distribution (often referred to as 'β')</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Poisson Poisson(float rate, Generator generator = null)\n {\n return new Poisson(tensor(rate), generator);\n }\n\n /// <summary>\n /// Creates a Poisson distribution parameterized by `rate`.\n /// </summary>\n /// <param name=\"rate\">rate = 1 / scale of the distribution (often referred to as 'β')</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Poisson Poisson(double rate, Generator generator = null)\n {\n return new Poisson(tensor(rate), generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.4765501916408539, "alphanum_fraction": 0.49291783571243286, "avg_line_length": 32.79787063598633, "blob_id": "249c575d90f65d23658cc190c246fd5cf605cd79", "content_id": "9c5247c644e8464cabde5c3ba9453155951113b3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3177, "license_type": "permissive", "max_line_length": 130, "num_lines": 94, "path": "/src/TorchSharp/Utils/LEB128Codec.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.IO;\nusing System.Collections.Generic;\n\nnamespace TorchSharp.Utils\n{\n /// <summary>\n /// LEB128 encoder / decoder\n ///\n /// LEB128 is the compression format used by BinaryWriter/Reader to encode string lengths,\n /// and it is convenient to use it for other lengths in the encoding of tensors and module\n /// state dictionaries.\n /// \n /// https://en.wikipedia.org/wiki/LEB128\n /// </summary>\n internal static class LEB128Codec\n {\n /// <summary>\n /// Encode a long value.\n /// </summary>\n /// <param name=\"value\">The input value.</param>\n /// <returns>The encoded value as a sequence of bytes.</returns>\n public static IList<byte> Encode(long value)\n {\n if (value < 0)\n throw new NotImplementedException(\"LEB128 encoding of negative numbers\");\n\n var result = new List<byte>();\n while (true) {\n long b = value & 0x7f;\n value >>= 7;\n if (value == 0) {\n result.Add((byte)b);\n return result;\n }\n result.Add((byte)(b | 0x80));\n }\n }\n\n /// <summary>\n /// Encode a long value into a binary writer.\n /// </summary>\n /// <param name=\"writer\">A BinaryWriter instance</param>\n /// <param name=\"value\">The input value.</param>\n public static void Encode(this BinaryWriter writer, long value)\n {\n if (value < 0)\n throw new NotImplementedException(\"LEB128 encoding of negative numbers\");\n\n while (true) {\n long b = value & 0x7f;\n value >>= 7;\n if (value == 0) {\n writer.Write((byte)b);\n return;\n }\n writer.Write((byte)(b | 0x80));\n }\n }\n\n /// <summary>\n /// Decode a long value from a binary reader\n /// </summary>\n /// <param name=\"reader\">A BinaryReader instance used for input.</param>\n /// <returns>The decoded value</returns>\n public static long Decode(this BinaryReader reader)\n {\n long result = 0;\n for (int i = 0; true; ++i) {\n long b = reader.ReadByte();\n result += ((b & 0x7f) << (i * 7));\n if ((b & 0x80) == 0) break;\n }\n return result;\n }\n\n /// <summary>\n /// Decode a long value from a sequence of bytes\n /// </summary>\n /// <param name=\"input\">A sequence of bytes used for input.</param>\n /// <returns>The decoded value</returns>\n public static long Decode(IList<byte> input)\n {\n long result = 0;\n for (int i = 0; i < input.Count; ++i) {\n long b = input[i];\n result += ((b & 0x7f) << (i * 7));\n if ((b & 0x80) == 0) break;\n }\n return result;\n }\n }\n}\n" }, { "alpha_fraction": 0.49643704295158386, "alphanum_fraction": 0.5002639293670654, "avg_line_length": 45.20731735229492, "blob_id": "e3c8518859e692cb3caacb22b6dbd52518a5b998", "content_id": "aa9ba4ca42e31b078fd6be06ecf1f74f5c22d571", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7578, "license_type": "permissive", "max_line_length": 139, "num_lines": 164, "path": "/src/TorchVision/IO/SkiaSharpImager.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.IO;\nusing System.Runtime.InteropServices;\nusing SkiaSharp;\nusing static TorchSharp.torch;\nusing static TorchSharp.NativeMethods;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class io\n {\n public sealed class SkiaImager : Imager\n {\n\n public SkiaImager(int quality = 75)\n {\n this.quality = quality;\n }\n private int quality;\n\n public override Tensor DecodeImage(byte[] bytes, ImageReadMode mode = ImageReadMode.UNCHANGED)\n {\n using var bitmap = SKBitmap.Decode(bytes);\n return ToTensor(mode, bitmap);\n }\n\n public override Tensor DecodeImage(Stream stream, ImageReadMode mode = ImageReadMode.UNCHANGED)\n {\n using var bitmap = SKBitmap.Decode(stream);\n return ToTensor(mode, bitmap);\n }\n\n public override void EncodeImage(Tensor image, ImageFormat format, Stream stream)\n {\n var skiaFormat = TranslateImageFormat(format); // Better to take the exception early.\n\n var result = new SKBitmap();\n\n var lstIdx = image.shape.Length;\n\n var channels = image.shape[lstIdx - 3];\n var height = image.shape[lstIdx - 2];\n var width = image.shape[lstIdx - 1];\n\n var imageSize = height * width;\n\n var isGrey = channels == 1;\n\n byte[] outBytes = null;\n\n if (isGrey) {\n outBytes = image.bytes.ToArray();\n } else {\n outBytes = new byte[4 * imageSize];\n\n unsafe {\n fixed (byte* input = image.bytes, output = outBytes) {\n THSVision_RGB_BRGA((IntPtr)input, (IntPtr)output, channels, imageSize);\n }\n }\n }\n\n SKColorType colorType = isGrey ? SKColorType.Gray8 : SKColorType.Bgra8888;\n\n // pin the managed array so that the GC doesn't move it\n var gcHandle = GCHandle.Alloc(outBytes, GCHandleType.Pinned);\n\n // install the pixels with the color type of the pixel data\n var info = new SKImageInfo((int)width, (int)height, colorType, SKAlphaType.Unpremul);\n result.InstallPixels(info, gcHandle.AddrOfPinnedObject(), info.RowBytes, delegate { gcHandle.Free(); }, null);\n\n result.Encode(stream, skiaFormat, this.quality);\n stream.Flush();\n }\n\n public override byte[] EncodeImage(Tensor image, ImageFormat format)\n {\n using var memStream = new MemoryStream();\n EncodeImage(image, format, memStream);\n return memStream.ToArray();\n }\n\n private static Tensor ToTensor(ImageReadMode mode, SKBitmap bitmap)\n {\n if (mode == ImageReadMode.UNCHANGED) {\n mode = bitmap.ColorType == SKColorType.Gray8 ? ImageReadMode.GRAY : ImageReadMode.RGB;\n }\n\n if (bitmap.ColorType == SKColorType.Gray8 && mode == ImageReadMode.GRAY)\n return torch.tensor(bitmap.Bytes, 1, bitmap.Height, bitmap.Width);\n\n using var scope = NewDisposeScope();\n\n if (bitmap.ColorType == SKColorType.Gray8 && mode == ImageReadMode.RGB) {\n Tensor t = torch.tensor(bitmap.Bytes, 1, bitmap.Height, bitmap.Width);\n return t.expand(3, bitmap.Height, bitmap.Width).MoveToOuterDisposeScope();\n }\n\n if (bitmap.BytesPerPixel != 4 && bitmap.BytesPerPixel != 1)\n throw new ArgumentException(\"Conversion only supports grayscale and ARGB\");\n\n var imageSize = bitmap.Height * bitmap.Width;\n\n byte[] redBytes = new byte[imageSize], greenBytes = new byte[imageSize], blueBytes = new byte[imageSize];\n byte[] alphaBytes = null;\n\n bool outputGrayScale = mode == ImageReadMode.GRAY_ALPHA || mode == ImageReadMode.GRAY;\n\n Tensor result;\n\n unsafe {\n if (mode == ImageReadMode.GRAY || mode == ImageReadMode.RGB) {\n fixed (byte* inputs = bitmap.Bytes, red = redBytes, blue = blueBytes, green = greenBytes) {\n THSVision_BRGA_RGB((IntPtr)inputs, (IntPtr)red, (IntPtr)green, (IntPtr)blue, 4, imageSize);\n }\n result = torch.vstack( new[] {\n torch.tensor(redBytes, 1, bitmap.Height, bitmap.Width),\n torch.tensor(greenBytes, 1, bitmap.Height, bitmap.Width),\n torch.tensor(blueBytes, 1, bitmap.Height, bitmap.Width) });\n } else if (mode == ImageReadMode.RGB_ALPHA || mode == ImageReadMode.GRAY_ALPHA) {\n alphaBytes = new byte[imageSize];\n fixed (byte* inputs = bitmap.Bytes, red = redBytes, blue = blueBytes, green = greenBytes, alpha = alphaBytes) {\n THSVision_BRGA_RGBA((IntPtr)inputs, (IntPtr)red, (IntPtr)green, (IntPtr)blue, (IntPtr)alpha, 4, imageSize);\n result = torch.vstack(new[] {\n torch.tensor(alphaBytes, 1, bitmap.Height, bitmap.Width),\n torch.tensor(redBytes, 1, bitmap.Height, bitmap.Width),\n torch.tensor(greenBytes, 1, bitmap.Height, bitmap.Width),\n torch.tensor(blueBytes, 1, bitmap.Height, bitmap.Width) });\n }\n } else {\n throw new NotImplementedException();\n }\n }\n\n if (outputGrayScale) {\n result = torchvision.transforms.functional.rgb_to_grayscale(result);\n }\n\n return result.MoveToOuterDisposeScope();\n }\n\n private SKEncodedImageFormat TranslateImageFormat(ImageFormat format)\n {\n switch (format) {\n case ImageFormat.Png:\n return SKEncodedImageFormat.Png;\n case ImageFormat.Jpeg:\n return SKEncodedImageFormat.Jpeg;\n case ImageFormat.Bmp:\n return SKEncodedImageFormat.Bmp;\n case ImageFormat.Gif:\n return SKEncodedImageFormat.Gif;\n case ImageFormat.Webp:\n return SKEncodedImageFormat.Webp;\n }\n throw new NotSupportedException($\"SkiaSharp does not support encoding images in the '{format}' format.\");\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.7265625, "alphanum_fraction": 0.7265625, "avg_line_length": 32.68421173095703, "blob_id": "3268098432601e8d5cff98d71f4d33758005d78b", "content_id": "7cf494b7a7bb569c3602b1f8261ca1c61cc1129d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 640, "license_type": "permissive", "max_line_length": 130, "num_lines": 19, "path": "/src/TorchSharp/PInvoke/LibTorchSharp.THSStorage.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp.PInvoke\n{\n internal static partial class NativeMethods\n {\n [DllImport(\"LibTorchSharp\")]\n internal static extern ulong THSStorage_nbytes(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSStorage_set_nbytes(IntPtr tensor, ulong nbytes);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSStorage_data_ptr(IntPtr tensor);\n }\n}\n" }, { "alpha_fraction": 0.45060285925865173, "alphanum_fraction": 0.46771037578582764, "avg_line_length": 73.02336120605469, "blob_id": "b4d21105bd7862aa9beae83b287e83cfd20ba086", "content_id": "b6e2f5b6e746eb34cc5e3c8f09afec21901fb3d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 15841, "license_type": "permissive", "max_line_length": 236, "num_lines": 214, "path": "/pkg/FileRestitcher/FileRestitcher/FileRestitcher.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System;\nusing System.IO;\n\nnamespace ConsoleApp2\n{\n public class Program\n {\n\n public static void Restitch(string RestitcherPackage)\n {\n // !!!!!!!------------------------------NOTE------------------------------------!!!!!!\n // !!!!!!! This code is manually copied into pkg\\common\\RestitchPackage.targets !!!!!!\n // !!!!!!!------------------------------NOTE------------------------------------!!!!!!\n //\n // vvvvvvvvvvvvvvvvvvvvvvvvvvvvv START HERE vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv\n try {\n if (Directory.Exists(RestitcherPackage)) {\n //System.Console.WriteLine(\"Searching for primary files in {0}\", RestitcherPackage);\n foreach (var p in Directory.EnumerateFiles(RestitcherPackage, \"*\", SearchOption.AllDirectories)) {\n\n var primaryFile = Path.GetFullPath(p);\n //Console.WriteLine(\"Found primary file at {0}\", primaryFile);\n\n // See if there are fragments in the parallel nuget packages. If the primary is \n // some-package-primary\\runtimes\\....\\a.so \n // some-package-primary\\runtimes\\....\\a.so.sha\n // then the expected fragments are\n // some-package-fragment1\\fragments\\....\\a.so \n // some-package-fragment2\\fragments\\....\\a.so \n // some-package-fragment3\\fragments\\....\\a.so \n // some-package-fragment4\\fragments\\....\\a.so \n // some-package-fragment5\\fragments\\....\\a.so \n // some-package-fragment6\\fragments\\....\\a.so \n // some-package-fragment7\\fragments\\....\\a.so \n // some-package-fragment8\\fragments\\....\\a.so \n // some-package-fragment9\\fragments\\....\\a.so \n // some-package-fragment10\\fragments\\....\\a.so \n var shaFile = primaryFile + \".sha\";\n var fragmentFile1 = primaryFile.Replace(\"-primary\", \"-fragment1\").Replace(\"runtimes\", \"fragments\") + \".fragment1\";\n var fragmentFile2 = primaryFile.Replace(\"-primary\", \"-fragment2\").Replace(\"runtimes\", \"fragments\") + \".fragment2\";\n var fragmentFile3 = primaryFile.Replace(\"-primary\", \"-fragment3\").Replace(\"runtimes\", \"fragments\") + \".fragment3\";\n var fragmentFile4 = primaryFile.Replace(\"-primary\", \"-fragment4\").Replace(\"runtimes\", \"fragments\") + \".fragment4\";\n var fragmentFile5 = primaryFile.Replace(\"-primary\", \"-fragment5\").Replace(\"runtimes\", \"fragments\") + \".fragment5\";\n var fragmentFile6 = primaryFile.Replace(\"-primary\", \"-fragment6\").Replace(\"runtimes\", \"fragments\") + \".fragment6\";\n var fragmentFile7 = primaryFile.Replace(\"-primary\", \"-fragment7\").Replace(\"runtimes\", \"fragments\") + \".fragment7\";\n var fragmentFile8 = primaryFile.Replace(\"-primary\", \"-fragment8\").Replace(\"runtimes\", \"fragments\") + \".fragment8\";\n var fragmentFile9 = primaryFile.Replace(\"-primary\", \"-fragment9\").Replace(\"runtimes\", \"fragments\") + \".fragment9\";\n var fragmentFile10 = primaryFile.Replace(\"-primary\", \"-fragment10\").Replace(\"runtimes\", \"fragments\") + \".fragment10\";\n\n if (File.Exists(fragmentFile1)) Console.WriteLine(\"Found fragment file at {0}\", fragmentFile1);\n if (File.Exists(fragmentFile2)) Console.WriteLine(\"Found fragment file at {0}\", fragmentFile2);\n if (File.Exists(fragmentFile3)) Console.WriteLine(\"Found fragment file at {0}\", fragmentFile3);\n if (File.Exists(fragmentFile4)) Console.WriteLine(\"Found fragment file at {0}\", fragmentFile4);\n if (File.Exists(fragmentFile5)) Console.WriteLine(\"Found fragment file at {0}\", fragmentFile5);\n if (File.Exists(fragmentFile6)) Console.WriteLine(\"Found fragment file at {0}\", fragmentFile6);\n if (File.Exists(fragmentFile7)) Console.WriteLine(\"Found fragment file at {0}\", fragmentFile7);\n if (File.Exists(fragmentFile8)) Console.WriteLine(\"Found fragment file at {0}\", fragmentFile8);\n if (File.Exists(fragmentFile9)) Console.WriteLine(\"Found fragment file at {0}\", fragmentFile9);\n if (File.Exists(fragmentFile10)) Console.WriteLine(\"Found fragment file at {0}\", fragmentFile10);\n\n if (File.Exists(fragmentFile1)) {\n var tmpFile = Path.GetTempFileName();\n\n {\n Console.WriteLine(\"Writing restored primary file at {0}\", tmpFile);\n using (var os = File.OpenWrite(tmpFile)) {\n\n Console.WriteLine(\"Writing bytes from {0} to {1}\", primaryFile, tmpFile);\n var primaryBytes = File.ReadAllBytes(primaryFile);\n\n os.Write(primaryBytes, 0, primaryBytes.Length);\n if (File.Exists(fragmentFile1)) {\n Console.WriteLine(\"Writing fragment bytes from {0} to {1}\", fragmentFile1, tmpFile);\n var fragmentBytes1 = File.ReadAllBytes(fragmentFile1);\n os.Write(fragmentBytes1, 0, fragmentBytes1.Length);\n }\n if (File.Exists(fragmentFile2)) {\n Console.WriteLine(\"Writing fragment bytes from {0} to {1}\", fragmentFile2, tmpFile);\n var fragmentBytes2 = File.ReadAllBytes(fragmentFile2);\n os.Write(fragmentBytes2, 0, fragmentBytes2.Length);\n }\n if (File.Exists(fragmentFile3)) {\n Console.WriteLine(\"Writing fragment bytes from {0} to {1}\", fragmentFile3, tmpFile);\n var fragmentBytes3 = File.ReadAllBytes(fragmentFile3);\n os.Write(fragmentBytes3, 0, fragmentBytes3.Length);\n }\n if (File.Exists(fragmentFile4)) {\n Console.WriteLine(\"Writing fragment bytes from {0} to {1}\", fragmentFile4, tmpFile);\n var fragmentBytes4 = File.ReadAllBytes(fragmentFile4);\n os.Write(fragmentBytes4, 0, fragmentBytes4.Length);\n }\n if (File.Exists(fragmentFile5)) {\n Console.WriteLine(\"Writing fragment bytes from {0} to {1}\", fragmentFile5, tmpFile);\n var fragmentBytes5 = File.ReadAllBytes(fragmentFile5);\n os.Write(fragmentBytes5, 0, fragmentBytes5.Length);\n }\n if (File.Exists(fragmentFile6)) {\n Console.WriteLine(\"Writing fragment bytes from {0} to {1}\", fragmentFile6, tmpFile);\n var fragmentBytes6 = File.ReadAllBytes(fragmentFile6);\n os.Write(fragmentBytes6, 0, fragmentBytes6.Length);\n }\n if (File.Exists(fragmentFile7)) {\n Console.WriteLine(\"Writing fragment bytes from {0} to {1}\", fragmentFile7, tmpFile);\n var fragmentBytes7 = File.ReadAllBytes(fragmentFile7);\n os.Write(fragmentBytes7, 0, fragmentBytes7.Length);\n }\n if (File.Exists(fragmentFile8)) {\n Console.WriteLine(\"Writing fragment bytes from {0} to {1}\", fragmentFile8, tmpFile);\n var fragmentBytes8 = File.ReadAllBytes(fragmentFile8);\n os.Write(fragmentBytes8, 0, fragmentBytes8.Length);\n }\n if (File.Exists(fragmentFile9)) {\n Console.WriteLine(\"Writing fragment bytes from {0} to {1}\", fragmentFile9, tmpFile);\n var fragmentBytes9 = File.ReadAllBytes(fragmentFile9);\n os.Write(fragmentBytes9, 0, fragmentBytes9.Length);\n }\n if (File.Exists(fragmentFile10)) {\n Console.WriteLine(\"Writing fragment bytes from {0} to {1}\", fragmentFile10, tmpFile);\n var fragmentBytes10 = File.ReadAllBytes(fragmentFile10);\n os.Write(fragmentBytes10, 0, fragmentBytes10.Length);\n }\n }\n }\n\n var shaExpected = File.Exists(shaFile) ? File.ReadAllText(shaFile) : \"\";\n\n using (var sha256Hash = System.Security.Cryptography.SHA256.Create()) {\n using (var os2 = File.OpenRead(tmpFile)) {\n\n byte[] bytes = sha256Hash.ComputeHash(os2);\n var builder = new System.Text.StringBuilder();\n for (int i = 0; i < bytes.Length; i++) {\n builder.Append(bytes[i].ToString(\"x2\"));\n }\n var shaReconstituted = builder.ToString();\n if (shaExpected != shaReconstituted) {\n string msg =\n $\"Error downloading and reviving packages. Reconsituted file contents have incorrect SHA\\n\\tExpected SHA: ${shaExpected}\\n\\tActual SHA: ${shaReconstituted}\\n\\tFile was reconstituted from:\"\n + $\"\\n\\t{primaryFile} (length ${new FileInfo(primaryFile).Length})\"\n + (File.Exists(fragmentFile1) ? $\"\\n\\t{fragmentFile1} (length ${new FileInfo(fragmentFile1).Length})\" : \"\")\n + (File.Exists(fragmentFile2) ? $\"\\n\\t{fragmentFile2} (length ${new FileInfo(fragmentFile2).Length})\" : \"\")\n + (File.Exists(fragmentFile3) ? $\"\\n\\t{fragmentFile3} (length ${new FileInfo(fragmentFile3).Length})\" : \"\")\n + (File.Exists(fragmentFile4) ? $\"\\n\\t{fragmentFile4} (length ${new FileInfo(fragmentFile4).Length})\" : \"\")\n + (File.Exists(fragmentFile5) ? $\"\\n\\t{fragmentFile5} (length ${new FileInfo(fragmentFile5).Length})\" : \"\")\n + (File.Exists(fragmentFile6) ? $\"\\n\\t{fragmentFile6} (length ${new FileInfo(fragmentFile6).Length})\" : \"\")\n + (File.Exists(fragmentFile7) ? $\"\\n\\t{fragmentFile7} (length ${new FileInfo(fragmentFile7).Length})\" : \"\")\n + (File.Exists(fragmentFile8) ? $\"\\n\\t{fragmentFile8} (length ${new FileInfo(fragmentFile8).Length})\" : \"\")\n + (File.Exists(fragmentFile9) ? $\"\\n\\t{fragmentFile9} (length ${new FileInfo(fragmentFile9).Length})\" : \"\")\n + (File.Exists(fragmentFile10) ? $\"\\n\\t{fragmentFile10} (length ${new FileInfo(fragmentFile10).Length})\" : \"\");\n Console.Error.WriteLine(msg);\n throw new Exception(msg);\n }\n }\n\n }\n\n Console.WriteLine(\"Deleting {0}\", primaryFile);\n File.Delete(primaryFile);\n if (File.Exists(primaryFile))\n throw new Exception(\"wtf?\");\n\n Console.WriteLine(\"Moving {0} --> {1}\", tmpFile, primaryFile);\n File.Move(tmpFile, primaryFile);\n\n Console.WriteLine(\"Deleting {0}\", fragmentFile1);\n File.Delete(fragmentFile1); // free up space and prevent us doing this again \n\n Console.WriteLine(\"Deleting {0}\", fragmentFile2);\n if (File.Exists(fragmentFile2))\n File.Delete(fragmentFile2); // free up space and prevent us doing this again \n\n Console.WriteLine(\"Deleting {0}\", fragmentFile3);\n if (File.Exists(fragmentFile3))\n File.Delete(fragmentFile3); // free up space and prevent us doing this again \n\n Console.WriteLine(\"Deleting {0}\", fragmentFile4);\n if (File.Exists(fragmentFile4))\n File.Delete(fragmentFile4); // free up space and prevent us doing this again \n\n Console.WriteLine(\"Deleting {0}\", fragmentFile5);\n if (File.Exists(fragmentFile5))\n File.Delete(fragmentFile5); // free up space and prevent us doing this again \n\n Console.WriteLine(\"Deleting {0}\", fragmentFile6);\n if (File.Exists(fragmentFile6))\n File.Delete(fragmentFile6); // free up space and prevent us doing this again \n\n Console.WriteLine(\"Deleting {0}\", fragmentFile7);\n if (File.Exists(fragmentFile7))\n File.Delete(fragmentFile7); // free up space and prevent us doing this again \n\n Console.WriteLine(\"Deleting {0}\", fragmentFile8);\n if (File.Exists(fragmentFile8))\n File.Delete(fragmentFile8); // free up space and prevent us doing this again \n\n Console.WriteLine(\"Deleting {0}\", fragmentFile9);\n if (File.Exists(fragmentFile9))\n File.Delete(fragmentFile9); // free up space and prevent us doing this again \n\n Console.WriteLine(\"Deleting {0}\", fragmentFile10);\n if (File.Exists(fragmentFile10))\n File.Delete(fragmentFile10); // free up space and prevent us doing this again \n }\n }\n }\n }\n catch (Exception ex) {\n Console.Error.WriteLine(ex.ToString());\n Console.Error.WriteLine(ex.StackTrace);\n }\n // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ END HERE^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n }\n }\n}\n" }, { "alpha_fraction": 0.628696084022522, "alphanum_fraction": 0.6432380080223083, "avg_line_length": 33.966102600097656, "blob_id": "8b70dca3a288ab65fa0c0bf5ca4de0b7889a62aa", "content_id": "a14815c2818dee57d8c7baed234abb4724a9056f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2063, "license_type": "permissive", "max_line_length": 130, "num_lines": 59, "path": "/src/TorchVision/Ops/Permute.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchvision,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/vision/blob/a4f53308b2d0f1aa9191686e326f45c26053f686/torchvision/ops/misc.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/vision/blob/main/LICENSE\n//\n\nusing System;\nusing System.Linq;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing TorchSharp.Modules;\nusing static TorchSharp.torch;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public sealed class Permute : nn.Module<Tensor, Tensor>\n {\n public Permute(IEnumerable<long> dims) : base(nameof(Permute))\n {\n this.dims = dims.ToArray();\n }\n\n public override Tensor forward(Tensor input)\n {\n return torch.permute(input, dims);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected override nn.Module _to(Device device, ScalarType dtype) => this;\n protected override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected override nn.Module _to(ScalarType dtype) => this;\n\n private long[] dims;\n }\n\n public static partial class ops\n {\n /// <summary>\n /// This module returns a view of the tensor input with its dimensions permuted.\n /// </summary>\n /// <param name=\"dims\">The desired ordering of dimensions</param>\n public static Permute Permute(params long[] dims)\n {\n return new Permute(dims);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5785866975784302, "alphanum_fraction": 0.5837259292602539, "avg_line_length": 56.89256286621094, "blob_id": "550bd4eca832f1d7eeb90979383c81e885f63aa5", "content_id": "5c4de0ff01f100babf53fc64a40c4b741eeec0ed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7005, "license_type": "permissive", "max_line_length": 203, "num_lines": 121, "path": "/src/TorchSharp/NN/Fold.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using System.Security.Cryptography;\n using Modules;\n\n namespace Modules\n {\n public sealed class Fold : torch.nn.Module<Tensor, Tensor>\n {\n internal Fold((long, long) output_size, (long, long) kernel_size, (long, long) dilation, (long, long) padding, (long, long) stride) : base(nameof(Fold))\n {\n this.outputSize = output_size;\n this.kernelSize = kernel_size;\n this.dilation = dilation;\n this.padding = padding;\n this.stride = stride;\n }\n\n public override Tensor forward(Tensor tensor)\n {\n return torch.nn.functional.fold(tensor, outputSize , kernelSize, dilation, padding, stride);\n }\n\n private (long, long) outputSize;\n private (long, long) kernelSize;\n private (long, long) dilation;\n private (long, long) padding;\n private (long, long) stride;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Combines an array of sliding local blocks into a large containing tensor.\n /// </summary>\n /// <param name=\"output_size\">Describes the spatial shape of the large containing tensor of the sliding local blocks.</param>\n /// <param name=\"kernel_size\">The size of the sliding blocks</param>\n /// <param name=\"dilation\">A parameter that controls the stride of elements within the neighborhood.</param>\n /// <param name=\"padding\">Implicit zero padding to be added on both sides of input.</param>\n /// <param name=\"stride\">The stride of the sliding blocks in the input spatial dimensions.</param>\n /// <remarks>Currently, only unbatched (3D) or batched (4D) image-like output tensors are supported.</remarks>\n public unsafe static Fold Fold(long output_size, long kernel_size, long dilation = 1, long padding = 0, long stride = 1)\n {\n return new Fold((output_size, output_size), (kernel_size, kernel_size), (dilation, dilation), (padding, padding), (stride, stride));\n }\n\n /// <summary>\n /// Combines an array of sliding local blocks into a large containing tensor.\n /// </summary>\n /// <param name=\"output_size\">Describes the spatial shape of the large containing tensor of the sliding local blocks.</param>\n /// <param name=\"kernel_size\">The size of the sliding blocks</param>\n /// <param name=\"dilation\">A parameter that controls the stride of elements within the neighborhood.</param>\n /// <param name=\"padding\">Implicit zero padding to be added on both sides of input.</param>\n /// <param name=\"stride\">The stride of the sliding blocks in the input spatial dimensions.</param>\n /// <remarks>Currently, only unbatched (3D) or batched (4D) image-like output tensors are supported.</remarks>\n public unsafe static Fold Fold((long, long) output_size, (long, long) kernel_size, (long, long)? dilation = null, (long, long)? padding = null, (long, long)? stride = null)\n {\n dilation ??= (1, 1);\n stride ??= (1, 1);\n padding ??= (0, 0);\n\n return new Fold(output_size, kernel_size, dilation.Value, padding.Value, stride.Value);\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Combines an array of sliding local blocks into a large containing tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"output_size\">Describes the spatial shape of the large containing tensor of the sliding local blocks.</param>\n /// <param name=\"kernel_size\">The size of the sliding blocks</param>\n /// <param name=\"dilation\">A parameter that controls the stride of elements within the neighborhood.</param>\n /// <param name=\"padding\">Implicit zero padding to be added on both sides of input.</param>\n /// <param name=\"stride\">The stride of the sliding blocks in the input spatial dimensions.</param>\n /// <remarks>Currently, only unbatched (3D) or batched (4D) image-like output tensors are supported.</remarks>\n public unsafe static Tensor fold(Tensor input, long output_size, long kernel_size, long dilation = 1, long padding = 0, long stride = 1)\n {\n var res = THSNN_fold(input.Handle, output_size, output_size, kernel_size, kernel_size, stride, stride, padding, padding, dilation, dilation);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Combines an array of sliding local blocks into a large containing tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"output_size\">Describes the spatial shape of the large containing tensor of the sliding local blocks.</param>\n /// <param name=\"kernel_size\">The size of the sliding blocks</param>\n /// <param name=\"dilation\">A parameter that controls the stride of elements within the neighborhood.</param>\n /// <param name=\"padding\">Implicit zero padding to be added on both sides of input.</param>\n /// <param name=\"stride\">The stride of the sliding blocks in the input spatial dimensions.</param>\n /// <remarks>Currently, only unbatched (3D) or batched (4D) image-like output tensors are supported.</remarks>\n public unsafe static Tensor fold(Tensor input, (long,long) output_size, (long, long) kernel_size, (long, long)? dilation = null, (long, long)? padding = null, (long, long)? stride = null)\n {\n dilation ??= (1, 1);\n stride ??= (1, 1);\n padding ??= (0, 0);\n\n var res = THSNN_fold(input.Handle,\n output_size.Item1, output_size.Item2,\n kernel_size.Item1, kernel_size.Item2,\n stride.Value.Item1, stride.Value.Item2,\n padding.Value.Item1, padding.Value.Item2,\n dilation.Value.Item1, dilation.Value.Item2);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.542768657207489, "alphanum_fraction": 0.545866072177887, "avg_line_length": 42.9476432800293, "blob_id": "fd5df4db9722e65ffafac99a1fa429f70f2fe628", "content_id": "b537a6be4b81d2f7a5feda1a07e8247754289c8c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8394, "license_type": "permissive", "max_line_length": 156, "num_lines": 191, "path": "/src/TorchSharp/Distributions/Normal.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// A Normal (Gaussian) distribution.\n /// </summary>\n public class Normal : distributions.Distribution\n {\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public override Tensor mean => loc;\n\n /// <summary>\n /// The mode of the distribution.\n /// </summary>\n public override Tensor mode => loc;\n\n /// <summary>\n /// The standard deviation of the distribution\n /// </summary>\n public override Tensor stddev => scale;\n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public override Tensor variance => scale.pow(2);\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"loc\">Mode or median of the distribution.</param>\n /// <param name=\"scale\">Standard deviation.</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n public Normal(Tensor loc, Tensor scale, Generator generator = null) : base(generator)\n {\n var locScale = broadcast_tensors(loc, scale);\n this.loc = locScale[0].DetachFromDisposeScope();\n this.scale = locScale[1].DetachFromDisposeScope();\n this.batch_shape = this.loc.size();\n }\n\n private Tensor loc;\n private Tensor scale;\n\n /// <summary>\n /// Generates a sample_shape shaped sample or sample_shape shaped batch of samples if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\"></param>\n public override Tensor sample(params long[] sample_shape)\n {\n var shape = ExtendedShape(sample_shape);\n using (no_grad()) {\n return normal(loc.expand(shape), scale.expand(shape), generator);\n }\n }\n\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n public override Tensor rsample(params long[] sample_shape)\n {\n var shape = ExtendedShape(sample_shape);\n var eps = empty(shape, dtype: loc.dtype, device: loc.device).normal_(generator: generator);\n return loc + eps * scale;\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor log_prob(Tensor value)\n {\n using var _ = NewDisposeScope();\n var v = scale.pow(2);\n var log_scale = scale.log();\n return (-((value - loc).pow(2)) / (2 * v) - log_scale - Math.Log(Math.Sqrt(2 * Math.PI))).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n public override Tensor entropy()\n {\n return WrappedTensorDisposeScope(() =>\n 0.5 + 0.5 * Math.Log(2 * Math.PI) + log(scale)\n );\n }\n\n /// <summary>\n /// Returns the cumulative density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor cdf(Tensor value)\n {\n return WrappedTensorDisposeScope(() =>\n 0.5 * (1 + special.erf((value - loc) * scale.reciprocal() / Math.Sqrt(2)))\n );\n }\n\n /// <summary>\n /// Returns the inverse cumulative density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor icdf(Tensor value)\n {\n return WrappedTensorDisposeScope(() =>\n loc + scale * special.erfinv(2 * value - 1) * Math.Sqrt(2)\n );\n }\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is Normal))\n throw new ArgumentException(\"expand(): 'instance' must be a Normal distribution\");\n\n var newDistribution = ((instance == null) ? new Normal(loc.expand(batch_shape), scale.expand(batch_shape), generator) : instance) as Normal;\n\n newDistribution.batch_shape = batch_shape;\n if (newDistribution == instance) {\n newDistribution.loc = loc.expand(batch_shape);\n newDistribution.scale = scale.expand(batch_shape);\n }\n return newDistribution;\n }\n }\n\n }\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Samples from a Normal (Gaussian) distribution. The distribution of the ratio of\n /// independent normally distributed random variables with means `0` follows a Normal distribution.\n /// </summary>\n /// <param name=\"loc\">Mode or median of the distribution.</param>\n /// <param name=\"scale\">Standard deviation.</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Normal Normal(Tensor loc, Tensor scale, Generator generator = null)\n {\n return new Normal(loc, scale, generator);\n }\n\n /// <summary>\n /// Samples from a Normal (Gaussian) distribution. The distribution of the ratio of\n /// independent normally distributed random variables with means `0` follows a Normal distribution.\n /// </summary>\n /// <param name=\"loc\">Mode or median of the distribution.</param>\n /// <param name=\"scale\">Standard deviation.</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Normal Normal(float loc, float scale = 1.0f, Generator generator = null)\n {\n return new Normal(tensor(loc), tensor(scale), generator);\n }\n\n\n /// <summary>\n /// Samples from a Normal (Gaussian) distribution. The distribution of the ratio of\n /// independent normally distributed random variables with means `0` follows a Normal distribution.\n /// </summary>\n /// <param name=\"loc\">Mode or median of the distribution.</param>\n /// <param name=\"scale\">Standard deviation.</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Normal Normal(double loc, double scale = 1.0, Generator generator = null)\n {\n return new Normal(tensor(loc), tensor(scale), generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5440503358840942, "alphanum_fraction": 0.5450723767280579, "avg_line_length": 55.131683349609375, "blob_id": "148f962c520666c158dd38f9ac4f7fbbdc3a34c9", "content_id": "e11b5661f715b722e7211b3393ec82d24d467ee1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 43067, "license_type": "permissive", "max_line_length": 183, "num_lines": 767, "path": "/src/TorchSharp/LinearAlgebra.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Linq;\nusing System.Collections.Generic;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static class linalg\n {\n /// <summary>\n /// Computes the Cholesky decomposition of a complex Hermitian or real symmetric positive-definite matrix.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <returns></returns>\n public static Tensor cholesky(Tensor input)\n {\n var res = THSLinalg_cholesky(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the Cholesky decomposition of a complex Hermitian or real symmetric positive-definite matrix.\n /// This function skips the(slow) error checking and error message construction of torch.linalg.cholesky(),\n /// instead directly returning the LAPACK error codes as part of a named tuple(L, info).\n /// This makes this function a faster way to check if a matrix is positive-definite, and it provides an opportunity to handle\n /// decomposition errors more gracefully or performantly than torch.linalg.cholesky() does.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"check_errors\">Controls whether to check the content of infos.</param>\n /// <returns></returns>\n public static (Tensor L, Tensor info) cholesky_ex(Tensor input, bool check_errors = false)\n {\n var res = THSLinalg_cholesky_ex(input.Handle, check_errors, out var pInfo);\n if (res == IntPtr.Zero || pInfo == IntPtr.Zero)\n torch.CheckForErrors();\n return (new Tensor(res), new Tensor(pInfo));\n }\n\n public static Tensor cond(Tensor input, int p)\n {\n var res = THSLinalg_cond_int(input.Handle, p);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the condition number of a matrix with respect to a matrix norm.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"p\">The type of the matrix norm to use in the computations</param>\n /// <returns></returns>\n public static Tensor cond(Tensor input, double p)\n {\n var res = THSLinalg_cond_float(input.Handle, p);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the condition number of a matrix with respect to a matrix norm.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"p\">The type of the matrix norm to use in the computations</param>\n public static Tensor cond(Tensor input, string p)\n {\n var res = THSLinalg_cond_str(input.Handle, p);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the condition number of a matrix with respect to a matrix norm.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor cond(Tensor input)\n {\n var res = THSLinalg_cond_none(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Returns the cross product of vectors in dimension dim of input and other.\n /// input and other must have the same size, and the size of their dim dimension should be 3.\n /// </summary>\n public static Tensor cross(Tensor input, Tensor other, long dim = -1)\n {\n var res = THSLinalg_cross(input.Handle, other.Handle, dim);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the determinant of a square matrix.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor det(Tensor input)\n {\n var res = THSLinalg_det(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the sign and natural logarithm of the absolute value of the determinant of a square matrix.\n /// For complex A, it returns the angle and the natural logarithm of the modulus of the determinant, that is, a logarithmic polar decomposition of the determinant.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <returns></returns>\n public static (Tensor, Tensor) slogdet(Tensor input)\n {\n var res = THSLinalg_slogdet(input.Handle, out var logabsdet);\n if (res == IntPtr.Zero || logabsdet == IntPtr.Zero)\n torch.CheckForErrors();\n return (new Tensor(res), new Tensor(logabsdet));\n }\n\n /// <summary>\n /// Returns a partial view of input with the its diagonal elements with respect to dim1 and dim2 appended as a dimension at the end of the shape.\n /// The argument offset controls which diagonal to consider:\n ///\n /// If offset == 0, it is the main diagonal.\n /// If offset &gt; 0, it is above the main diagonal.\n /// If offset &lt; 0, it is below the main diagonal.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"offset\">Which diagonal to consider. Default: 0 (main diagonal).</param>\n /// <param name=\"dim1\">First dimension with respect to which to take diagonal. Default: -1.</param>\n /// <param name=\"dim2\">Second dimension with respect to which to take diagonal. Default: -2.</param>\n /// <remarks>\n /// Applying torch.diag_embed() to the output of this function with the same arguments yields a diagonal matrix with the diagonal entries of the input.\n /// However, torch.diag_embed() has different default dimensions, so those need to be explicitly specified.\n /// </remarks>\n public static Tensor diagonal(Tensor input, int offset = 0, int dim1 = -2, int dim2 = -1) => input.diagonal(offset, dim1, dim2);\n\n /// <summary>\n /// Computes the eigenvalue decomposition of a square matrix if it exists.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <returns></returns>\n public static (Tensor, Tensor) eig(Tensor input)\n {\n var res = THSLinalg_eig(input.Handle, out var vectors);\n if (res == IntPtr.Zero || vectors == IntPtr.Zero)\n torch.CheckForErrors();\n return (new Tensor(res), new Tensor(vectors));\n }\n\n /// <summary>\n /// Computes the eigenvalue decomposition of a complex Hermitian or real symmetric matrix.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"UPLO\">Controls whether to use the upper or lower triangular part of A in the computations. </param>\n /// <returns></returns>\n public static (Tensor, Tensor) eigh(Tensor input, char UPLO = 'L')\n {\n var res = THSLinalg_eigh(input.Handle, (byte)UPLO, out var vectors);\n if (res == IntPtr.Zero || vectors == IntPtr.Zero)\n torch.CheckForErrors();\n return (new Tensor(res), new Tensor(vectors));\n }\n\n /// <summary>\n /// Computes the eigenvalues of a square matrix.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <returns></returns>\n public static Tensor eigvals(Tensor input)\n {\n var res = THSLinalg_eigvals(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the eigenvalues of a complex Hermitian or real symmetric matrix.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"UPLO\">Controls whether to use the upper or lower triangular part of A in the computations. </param>\n /// <returns></returns>\n public static Tensor eigvalsh(Tensor input, char UPLO = 'L')\n {\n var res = THSLinalg_eigvalsh(input.Handle, (byte)UPLO);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the first n columns of a product of Householder matrices.\n /// </summary>\n /// <param name=\"A\">tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"tau\">tensor of shape (*, k) where * is zero or more batch dimensions.</param>\n public static Tensor householder_product(Tensor A, Tensor tau)\n {\n var res = THSLinalg_householder_product(A.Handle, tau.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the inverse of a square matrix if it exists.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <returns></returns>\n /// <remarks>Throws a RuntimeError if the matrix is not invertible.</remarks>\n public static Tensor inv(Tensor input)\n {\n var res = THSLinalg_inv(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the inverse of a square matrix if it is invertible.\n /// Returns a named tuple(inverse, info). inverse contains the result of inverting A and info stores the LAPACK error codes.\n /// If A is not an invertible matrix, or if it’s a batch of matrices and one or more of them is not an invertible matrix,\n /// then info stores a positive integer for the corresponding matrix.The positive integer indicates the diagonal element of\n /// the LU decomposition of the input matrix that is exactly zero. info filled with zeros indicates that the inversion was successful.\n /// If check_errors = True and info contains positive integers, then a RuntimeError is thrown.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"check_errors\">Controls whether to check the content of info. controls whether to check the content of info. </param>\n /// <returns></returns>\n /// <remarks>Throws a RuntimeError if the matrix is not invertible.</remarks>\n public static (Tensor L, Tensor info) inv_ex(Tensor input, bool check_errors = false)\n {\n var res = THSLinalg_cholesky_ex(input.Handle, check_errors, out var pInfo);\n if (res == IntPtr.Zero || pInfo == IntPtr.Zero)\n torch.CheckForErrors();\n return (new Tensor(res), new Tensor(pInfo));\n }\n\n /// <summary>\n /// Computes a solution to the least squares problem of a system of linear equations.\n /// </summary>\n /// <param name=\"input\">lhs tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"other\">rhs tensor of shape (*, m, k) where * is zero or more batch dimensions.</param>\n /// <returns></returns>\n public static (Tensor Solution, Tensor Residuals, Tensor Rank, Tensor SingularValues) lstsq(Tensor input, Tensor other)\n {\n var solution = THSLinalg_lstsq_none(input.Handle, other.Handle, out var residuals, out var rank, out var singularValues);\n if (solution == IntPtr.Zero || residuals == IntPtr.Zero || rank == IntPtr.Zero || singularValues == IntPtr.Zero)\n torch.CheckForErrors();\n return (new Tensor(solution), new Tensor(residuals), new Tensor(rank), new Tensor(singularValues));\n }\n\n /// <summary>\n /// Computes the LU decomposition with partial pivoting of a matrix.\n /// </summary>\n /// <param name=\"input\">Tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"pivot\">Controls whether to compute the LU decomposition with partial pivoting or no pivoting</param>\n /// <returns></returns>\n public static (Tensor P, Tensor L, Tensor U) lu(Tensor input, bool pivot = true)\n {\n var solution = THSLinalg_lu(input.Handle, pivot, out var pL, out var pU);\n if (solution == IntPtr.Zero)\n torch.CheckForErrors();\n return (new Tensor(solution), new Tensor(pL), new Tensor(pU));\n }\n\n /// <summary>\n /// Computes a compact representation of the LU factorization with partial pivoting of a matrix.\n /// </summary>\n /// <param name=\"input\">Tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"pivot\">Controls whether to compute the LU decomposition with partial pivoting or no pivoting</param>\n /// <returns></returns>\n public static (Tensor LU, Tensor? Pivots) lu_factor(Tensor input, bool pivot = true)\n {\n var solution = THSLinalg_lu_factor(input.Handle, pivot, out var pivots);\n if (solution == IntPtr.Zero)\n torch.CheckForErrors();\n return (new Tensor(solution), pivots == IntPtr.Zero ? null : new Tensor(pivots));\n }\n\n /// <summary>\n /// Computes a compact representation of the LU factorization with partial pivoting of a matrix.\n /// </summary>\n /// <param name=\"input\">Tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"hermitian\">Controls whether to consider the input to be Hermitian or symmetric. For real-valued matrices, this switch has no effect.</param>\n /// <returns></returns>\n public static (Tensor LU, Tensor? Pivots) ldl_factor(Tensor input, bool hermitian = true)\n {\n var solution = THSLinalg_ldl_factor(input.Handle, hermitian, out var pivots);\n if (solution == IntPtr.Zero)\n torch.CheckForErrors();\n return (new Tensor(solution), pivots == IntPtr.Zero ? null : new Tensor(pivots));\n }\n\n /// <summary>\n /// Computes a compact representation of the LU factorization with partial pivoting of a matrix.\n /// </summary>\n /// <param name=\"input\">Tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"hermitian\">Controls whether to consider the input to be Hermitian or symmetric. For real-valued matrices, this switch has no effect.</param>\n /// <param name=\"check_errors\">Controls whether to check the content of info and raise an error if it is non-zero.</param>\n /// <returns></returns>\n public static (Tensor LU, Tensor? Pivots, Tensor? Info) ldl_factor_ex(Tensor input, bool hermitian = true, bool check_errors = false)\n {\n var solution = THSLinalg_ldl_factor_ex(input.Handle, hermitian, check_errors, out var pivots, out var info);\n if (solution == IntPtr.Zero)\n torch.CheckForErrors();\n return (new Tensor(solution), pivots == IntPtr.Zero ? null : new Tensor(pivots), info == IntPtr.Zero ? null : new Tensor(info));\n }\n\n /// <summary>\n /// Computes the solution of a system of linear equations using the LDL factorization.\n /// </summary>\n /// <param name=\"LD\">the n times n matrix or the batch of such matrices of size (*, n, n) where * is one or more batch dimensions</param>\n /// <param name=\"pivots\">the pivots corresponding to the LDL factorization of LD</param>\n /// <param name=\"B\">Right-hand side tensor of shape (*, n, k)</param>\n /// <param name=\"hermitian\">Whether to consider the decomposed matrix to be Hermitian or symmetric. For real-valued matrices, this switch has no effect</param>\n /// <returns></returns>\n public static Tensor ldl_solve(Tensor LD, Tensor pivots, Tensor B, bool hermitian = false)\n {\n var res = THSLinalg_ldl_solve(LD.Handle, pivots.Handle, B.Handle, hermitian);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes a solution to the least squares problem of a system of linear equations.\n /// </summary>\n /// <param name=\"input\">lhs tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"other\">rhs tensor of shape (*, m, k) where * is zero or more batch dimensions.</param>\n /// <param name=\"rcond\">Used to determine the effective rank of A. If rcond= None, rcond is set to the machine precision of the dtype of A times max(m, n).</param>\n public static (Tensor Solution, Tensor Residuals, Tensor Rank, Tensor SingularValues) lstsq(Tensor input, Tensor other, double rcond)\n {\n var solution = THSLinalg_lstsq_rcond(input.Handle, other.Handle, rcond, out var residuals, out var rank, out var singularValues);\n if (solution == IntPtr.Zero || residuals == IntPtr.Zero || rank == IntPtr.Zero || singularValues == IntPtr.Zero)\n torch.CheckForErrors();\n return (new Tensor(solution), new Tensor(residuals), new Tensor(rank), new Tensor(singularValues));\n }\n\n /// <summary>\n /// Computes the matrix exponential of a square matrix or of each square matrix in a batch.\n /// </summary>\n public static Tensor matrix_exp(Tensor input) => input.matrix_exp();\n\n /// <summary>\n /// Computes a matrix norm.\n /// </summary>\n /// <param name=\"input\">tensor with two or more dimensions.\n /// By default its shape is interpreted as (*, m, n) where * is zero or more batch dimensions, but this behavior can be controlled using dims.</param>\n /// <param name=\"ord\">Order of norm. Default: \"fro\"</param>\n /// <param name=\"dims\">Dimensions over which to compute the norm.</param>\n /// <param name=\"keepdim\">If set to true, the reduced dimensions are retained in the result as dimensions with size one. </param>\n /// <returns></returns>\n public static Tensor matrix_norm(Tensor input, string ord = \"fro\", long[]? dims = null, bool keepdim = false)\n {\n if (dims == null) dims = new long[] { -2, -1 };\n unsafe {\n fixed (long* pdims = dims) {\n var res = THSLinalg_matrix_norm_fronuc(input.Handle, ord == \"fro\" ? (byte)0 : (byte)1, (IntPtr)pdims, dims.Length, keepdim);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes a matrix norm.\n /// </summary>\n /// <param name=\"input\">tensor with two or more dimensions.\n /// By default its shape is interpreted as (*, m, n) where * is zero or more batch dimensions, but this behavior can be controlled using dims.</param>\n /// <param name=\"ord\">Order of norm.</param>\n /// <param name=\"dims\">Dimensions over which to compute the norm.</param>\n /// <param name=\"keepdim\">If set to true, the reduced dimensions are retained in the result as dimensions with size one. </param>\n /// <returns></returns>\n public static Tensor matrix_norm(Tensor input, double ord, long[]? dims = null, bool keepdim = false)\n {\n if (dims == null) dims = new long[] { -2, -1 };\n unsafe {\n fixed (long* pdims = dims) {\n var res = THSLinalg_matrix_norm(input.Handle, ord.ToScalar().Handle, (IntPtr)pdims, dims.Length, keepdim);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes the numerical rank of a matrix.\n /// The matrix rank is computed as the number of singular values(or eigenvalues in absolute value when hermitian = True) that are greater than the specified tol threshold.\n /// </summary>\n /// <param name=\"input\">Tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"atol\">The absolute tolerance value.</param>\n /// <param name=\"rtol\">The relative tolerance value.</param>\n /// <param name=\"hermitian\">Indicates whether A is Hermitian if complex or symmetric if real</param>\n /// <returns></returns>\n public static Tensor matrix_rank(Tensor input, double? atol = null, double? rtol = null, bool hermitian = false)\n {\n unsafe {\n var res = THSLinalg_matrix_rank(input.Handle, atol ?? double.NegativeInfinity, atol.HasValue, rtol ?? double.NegativeInfinity, rtol.HasValue, hermitian);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n /// <summary>\n /// Computes the numerical rank of a matrix.\n /// The matrix rank is computed as the number of singular values(or eigenvalues in absolute value when hermitian = True) that are greater than the specified tol threshold.\n /// </summary>\n /// <param name=\"input\">Tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"atol\">The absolute tolerance value.</param>\n /// <param name=\"rtol\">The relative tolerance value.</param>\n /// <param name=\"hermitian\">Indicates whether A is Hermitian if complex or symmetric if real</param>\n /// <returns></returns>\n public static Tensor matrix_rank(Tensor input, Tensor atol, Tensor? rtol = null, bool hermitian = false)\n {\n unsafe {\n var res = THSLinalg_matrix_rank_tensor(input.Handle, atol is null ? IntPtr.Zero : atol.Handle, rtol is null ? IntPtr.Zero : rtol.Handle, hermitian);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n /// <summary>\n /// Efficiently multiplies two or more matrices by reordering the multiplications so that the fewest arithmetic operations are performed.\n /// </summary>\n /// <param name=\"tensors\">Two or more tensors to multiply. The first and last tensors may be 1D or 2D. Every other tensor must be 2D.</param>\n /// <returns></returns>\n public static Tensor multi_dot(IList<Tensor> tensors)\n {\n if (tensors.Count == 0) {\n throw new ArgumentException(nameof(tensors));\n }\n if (tensors.Count == 1) {\n return tensors[0];\n }\n\n using (var parray = new PinnedArray<IntPtr>()) {\n IntPtr tensorsRef = parray.CreateArray(tensors.Select(p => p.Handle).ToArray());\n var res = THSLinalg_multi_dot(tensorsRef, parray.Array.Length);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n }\n\n /// <summary>\n /// Computes a vector or matrix norm.\n /// If A is complex valued, it computes the norm of A.abs()\n /// </summary>\n /// <param name=\"input\">Tensor of shape (*, n) or (*, m, n) where * is zero or more batch dimensions</param>\n /// <param name=\"ord\">Order of norm. </param>\n /// <param name=\"dims\">Dimensions over which to compute the vector or matrix norm.</param>\n /// <param name=\"keepdim\">If set to true, the reduced dimensions are retained in the result as dimensions with size one.</param>\n /// <returns></returns>\n public static Tensor norm(Tensor input, string ord, long[]? dims = null, bool keepdim = false)\n {\n unsafe {\n fixed (long* pdims = dims) {\n var res = THSLinalg_norm_str(input.Handle, ord, (IntPtr)pdims, dims is null ? 0 : dims.Length, keepdim);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes a vector or matrix norm.\n /// If A is complex valued, it computes the norm of A.abs()\n /// </summary>\n /// <param name=\"input\">Tensor of shape (*, n) or (*, m, n) where * is zero or more batch dimensions</param>\n /// <param name=\"ord\">Order of norm. </param>\n /// <param name=\"dims\">Dimensions over which to compute the vector or matrix norm.</param>\n /// <param name=\"keepdim\">If set to true, the reduced dimensions are retained in the result as dimensions with size one.</param>\n public static Tensor norm(Tensor input, double ord, long[]? dims = null, bool keepdim = false)\n {\n unsafe {\n fixed (long* pdims = dims) {\n var res = THSLinalg_norm_float(input.Handle, ord, (IntPtr)pdims, dims is null ? 0 : dims.Length, keepdim);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes a vector or matrix norm.\n /// If A is complex valued, it computes the norm of A.abs()\n /// </summary>\n /// <param name=\"input\">Tensor of shape (*, n) or (*, m, n) where * is zero or more batch dimensions</param>\n /// <param name=\"ord\">Order of norm. </param>\n /// <param name=\"dims\">Dimensions over which to compute the vector or matrix norm.</param>\n /// <param name=\"keepdim\">If set to true, the reduced dimensions are retained in the result as dimensions with size one.</param>\n public static Tensor norm(Tensor input, int ord, long[]? dims = null, bool keepdim = false)\n {\n unsafe {\n fixed (long* pdims = dims) {\n var res = THSLinalg_norm_int(input.Handle, ord, (IntPtr)pdims, dims is null ? 0 : dims.Length, keepdim);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes a vector or matrix norm.\n /// If A is complex valued, it computes the norm of A.abs()\n /// </summary>\n /// <param name=\"input\">Tensor of shape (*, n) or (*, m, n) where * is zero or more batch dimensions</param>\n /// <param name=\"dims\">Dimensions over which to compute the vector or matrix norm.</param>\n /// <param name=\"keepdim\">If set to true, the reduced dimensions are retained in the result as dimensions with size one.</param>\n public static Tensor norm(Tensor input, long[]? dims = null, bool keepdim = false)\n {\n unsafe {\n fixed (long* pdims = dims) {\n var res = THSLinalg_norm_opt(input.Handle, (IntPtr)pdims, dims is null ? 0 : dims.Length, keepdim);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes the numerical rank of a matrix.\n /// The matrix rank is computed as the number of singular values(or eigenvalues in absolute value when hermitian = True) that are greater than the specified tol threshold.\n /// </summary>\n /// <param name=\"input\">Tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"atol\">The absolute tolerance value.</param>\n /// <param name=\"rtol\">The relative tolerance value.</param>\n /// <param name=\"hermitian\">Indicates whether A is Hermitian if complex or symmetric if real</param>\n /// <returns></returns>\n public static Tensor pinv(Tensor input, double? atol = null, double? rtol = null, bool hermitian = false)\n {\n unsafe {\n var res = THSLinalg_pinv(input.Handle, atol ?? double.NegativeInfinity, atol.HasValue, rtol ?? double.NegativeInfinity, rtol.HasValue, hermitian);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n /// <summary>\n /// Computes the numerical rank of a matrix.\n /// The matrix rank is computed as the number of singular values(or eigenvalues in absolute value when hermitian = True) that are greater than the specified tol threshold.\n /// </summary>\n /// <param name=\"input\">Tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"atol\">The absolute tolerance value.</param>\n /// <param name=\"rtol\">The relative tolerance value.</param>\n /// <param name=\"hermitian\">Indicates whether A is Hermitian if complex or symmetric if real</param>\n /// <returns></returns>\n public static Tensor pinv(Tensor input, Tensor atol, Tensor? rtol = null, bool hermitian = false)\n {\n unsafe {\n var res = THSLinalg_pinv_tensor(input.Handle, atol is null ? IntPtr.Zero : atol.Handle, rtol is null ? IntPtr.Zero : rtol.Handle, hermitian);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n public enum QRMode\n {\n Reduced = 0,\n Complete = 1,\n R = 2\n }\n\n /// <summary>\n /// Computes the QR decomposition of a matrix.\n /// </summary>\n /// <param name=\"input\">Tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"mode\">Controls the shape of the returned tensors. One of ‘Reduced’, ‘Complete’, ‘R’.</param>\n /// <returns></returns>\n public static (Tensor Q, Tensor R) qr(Tensor input, QRMode mode = QRMode.Reduced)\n {\n var Q = THSLinalg_qr(input.Handle, (byte)mode, out var R);\n if (Q == IntPtr.Zero || R == IntPtr.Zero)\n torch.CheckForErrors();\n return (new Tensor(Q), new Tensor(R));\n }\n\n /// <summary>\n /// Computes the solution of a square system of linear equations with a unique solution.\n /// </summary>\n /// <param name=\"A\">Tensor of shape (*, n, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"B\">Right-hand side tensor of shape (*, n) or (*, n, k) or (n,) or (n, k)</param>\n /// <param name=\"left\">whether to solve the system AX = B or XA = B.</param>\n /// <returns></returns>\n public static Tensor solve(Tensor A, Tensor B, bool left = true)\n {\n var res = THSLinalg_solve(A.Handle, B.Handle, left);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the solution of a square system of linear equations with a unique solution.\n /// </summary>\n /// <param name=\"A\">Ttensor of shape (*, n, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"B\">Right-hand side tensor of shape (*, n) or (*, n, k) or (n,) or (n, k)</param>\n /// <param name=\"left\">whether to solve the system AX = B or XA = B.</param>\n /// <param name=\"check_errors\">controls whether to check the content of infos and raise an error if it is non-zero</param>\n /// <returns></returns>\n public static (Tensor result, Tensor info) solve_ex(Tensor A, Tensor B, bool left = true, bool check_errors = false)\n {\n var res = THSLinalg_solve_ex(A.Handle, B.Handle, left, check_errors, out var infos);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return (new Tensor(res), new Tensor(infos));\n }\n\n /// <summary>\n /// Computes the solution of a square system of linear equations with a unique solution.\n /// </summary>\n /// <param name=\"A\">Tensor of shape (*, n, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"B\">Right-hand side tensor of shape (*, n) or (*, n, k) or (n,) or (n, k)</param>\n /// <param name=\"upper\">Whether A is an upper or lower triangular matrix</param>\n /// <param name=\"left\">Whether to solve the system AX = B or XA = B.</param>\n /// <param name=\"unitriangular\">If true, the diagonal elements of A are assumed to be all equal to 1.</param>\n /// <param name=\"out\">Output tensor. B may be passed as out and the result is computed in-place on B.</param>\n /// <returns></returns>\n public static Tensor solve_triangular(Tensor A, Tensor B, bool upper, bool left = true, bool unitriangular = false, Tensor? @out = null)\n {\n var res = (@out is null)\n ? THSLinalg_solve_triangular(A.Handle, B.Handle, upper, left, unitriangular)\n : THSLinalg_solve_triangular_out(A.Handle, B.Handle, upper, left, unitriangular, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the singular value decomposition (SVD) of a matrix.\n /// </summary>\n /// <param name=\"input\">Tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"fullMatrices\">Controls whether to compute the full or reduced SVD, and consequently, the shape of the returned tensors U and Vh.</param>\n /// <returns></returns>\n public static (Tensor U, Tensor S, Tensor Vh) svd(Tensor input, bool fullMatrices = true)\n {\n var U = THSLinalg_svd(input.Handle, fullMatrices, out var S, out var Vh);\n if (U == IntPtr.Zero || S == IntPtr.Zero || Vh == IntPtr.Zero)\n torch.CheckForErrors();\n return (new Tensor(U), new Tensor(S), new Tensor(Vh));\n }\n\n /// <summary>\n /// Computes the singular values of a matrix.\n /// </summary>\n /// <param name=\"input\">The input matrix</param>\n /// <returns></returns>\n public static Tensor svdvals(Tensor input)\n {\n var res = THSLinalg_svdvals(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the multiplicative inverse of torch.tensordot().\n /// </summary>\n /// <param name=\"input\">Tensor to invert. </param>\n /// <param name=\"ind\">Index at which to compute the inverse of torch.tensordot()</param>\n /// <returns></returns>\n public static Tensor tensorinv(Tensor input, long ind)\n {\n var res = THSLinalg_tensorinv(input.Handle, ind);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the solution X to the system torch.tensordot(A, X) = B.\n /// </summary>\n /// <param name=\"A\">Tensor to solve for. </param>\n /// <param name=\"B\">Another tensor, of shape a.shape[B.dim].</param>\n /// <param name=\"dims\">Dimensions of A to be moved. If None, no dimensions are moved.</param>\n /// <returns></returns>\n public static Tensor tensorsolve(Tensor A, Tensor B, long[] dims)\n {\n unsafe {\n fixed (long* pdims = dims) {\n var res = THSLinalg_tensorsolve(A.Handle, B.Handle, (IntPtr)pdims, dims.Length);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes a vector norm.\n /// </summary>\n /// <param name=\"input\">Tensor, flattened by default, but this behavior can be controlled using dims.</param>\n /// <param name=\"ord\">Order of norm. Default: 2</param>\n /// <param name=\"dims\">Dimensions over which to compute the norm.</param>\n /// <param name=\"keepdim\">If set to true, the reduced dimensions are retained in the result as dimensions with size one. </param>\n /// <returns></returns>\n public static Tensor vector_norm(Tensor input, double ord, long[]? dims = null, bool keepdim = false)\n {\n unsafe {\n fixed (long* pdims = dims) {\n var res = THSLinalg_vector_norm(input.Handle, ord.ToScalar().Handle, (IntPtr)pdims, dims is null ? 0 : dims.Length, keepdim);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Generates a Vandermonde matrix.\n /// </summary>\n /// <param name=\"input\">tensor of shape (*, n) where * is zero or more batch dimensions consisting of vectors.</param>\n /// <param name=\"N\">Number of columns in the output. Default: x.size(-1)</param>\n public static Tensor vander(Tensor input, long? N = null)\n {\n if (!N.HasValue) {\n N = input.shape[input.ndim - 1];\n }\n var res = THSLinalg_vander(input.Handle, N.Value);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the dot product of two batches of vectors along a dimension.\n /// </summary>\n /// <param name=\"x\">First batch of vectors.</param>\n /// <param name=\"y\">Second batch of vectors</param>\n /// <param name=\"dim\">Dimension along which to compute the dot product.</param>\n /// <param name=\"out\">Optional output tensor.</param>\n public static Tensor vecdot(Tensor x, Tensor y, long dim = -1, Tensor? @out = null)\n {\n var res = THSLinalg_vecdot(x.Handle, y.Handle, dim, @out is null ? IntPtr.Zero : @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the solution of a square system of linear equations with a unique solution given an LU decomposition.\n /// </summary>\n /// <param name=\"LU\">Tensor of shape (*, n, n) (or (*, k, k) if left= True) where * is zero or more batch dimensions as returned by lu_factor().</param>\n /// <param name=\"pivots\">Tensor of shape (*, n) (or (*, k) if left= True) where * is zero or more batch dimensions as returned by lu_factor().</param>\n /// <param name=\"B\">Right-hand side tensor of shape (*, n, k).</param>\n /// <param name=\"left\">Whether to solve the system AX=B or XA = B. Default: True.</param>\n /// <param name=\"adjoint\">Whether to solve the adjoint system.</param>\n /// <param name=\"out\">Optional output tensor.</param>\n /// <returns></returns>\n public static Tensor lu_solve(Tensor LU, Tensor pivots, Tensor B, bool left = true, bool adjoint = false, Tensor? @out = null)\n {\n var res = THSLinalg_lu_solve(B.Handle, LU.Handle, pivots.Handle, left, adjoint, @out is null ? IntPtr.Zero : @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.587868869304657, "alphanum_fraction": 0.5880327820777893, "avg_line_length": 44.52238845825195, "blob_id": "eb756ece997bd3c29b6c1ededff0bf228f2c14bb", "content_id": "d7a5895b37598604a86853318d0913ae01a5a1cb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6100, "license_type": "permissive", "max_line_length": 165, "num_lines": 134, "path": "/src/TorchSharp/Distributions/Independent.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using System.Linq;\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// Reinterprets some of the batch dims of a distribution as event dims.\n /// </summary>\n public class Independent : torch.distributions.Distribution\n {\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public override Tensor mean => base_dist.mean;\n\n public override Tensor mode => base_dist.mode;\n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public override Tensor variance => base_dist.variance;\n\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"base_distribution\">A base distribution.</param>\n /// <param name=\"reinterpreted_batch_ndims\">the number of batch dims to reinterpret as event dims</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n public Independent(torch.distributions.Distribution base_distribution, int reinterpreted_batch_ndims, torch.Generator generator = null) : base(generator)\n {\n var shape = base_distribution.batch_shape.Concat(base_distribution.event_shape).ToArray();\n var event_dim = reinterpreted_batch_ndims + base_distribution.event_shape.Length;\n var batch_shape = shape.Take(shape.Length - event_dim).ToArray();\n var event_shape = shape.Skip(shape.Length - event_dim).ToArray();\n\n this.base_dist = base_distribution;\n this.reinterpreted_batch_ndims = reinterpreted_batch_ndims;\n\n _init(batch_shape, event_shape);\n }\n\n private distributions.Distribution base_dist;\n private int reinterpreted_batch_ndims;\n\n /// <summary>\n /// Generates a sample_shape shaped sample or sample_shape shaped batch of samples if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\"></param>\n public override Tensor sample(params long[] sample_shape)\n {\n return base_dist.sample(sample_shape);\n }\n\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n public override Tensor rsample(params long[] sample_shape)\n {\n return base_dist.rsample(sample_shape);\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor log_prob(Tensor value)\n {\n var lp = base_dist.log_prob(value);\n return distributions.transforms.Transform._sum_rightmost(lp, reinterpreted_batch_ndims);\n }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n public override Tensor entropy()\n {\n var ent = base_dist.entropy();\n return distributions.transforms.Transform._sum_rightmost(ent, reinterpreted_batch_ndims);\n }\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is Independent))\n throw new ArgumentException(\"expand(): 'instance' must be a Independent distribution\");\n\n var newDistribution = ((instance == null) ? new Independent(\n base_dist.expand(batch_shape + event_shape.Slice(0, reinterpreted_batch_ndims)),\n reinterpreted_batch_ndims,\n generator) : instance) as Independent;\n\n if (newDistribution == instance) {\n newDistribution._init(batch_shape, event_shape);\n }\n return newDistribution;\n }\n }\n\n }\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Reinterprets some of the batch dims of a distribution as event dims.\n /// This is mainly useful for changing the shape of the result of `log_prob`.\n /// </summary>\n /// <param name=\"base_distribution\">A base distribution.</param>\n /// <param name=\"reinterpreted_batch_dims\">the number of batch dims to reinterpret as event dims</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Independent Independent(Distribution base_distribution, int reinterpreted_batch_dims, torch.Generator generator = null)\n {\n return new Independent(base_distribution, reinterpreted_batch_dims, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5152718424797058, "alphanum_fraction": 0.5328344702720642, "avg_line_length": 42.6533317565918, "blob_id": "5e6d365362f48eca33f312db9a64d49012c25e71", "content_id": "fe754ffe3bb6af6647e8920a48d4733f590d3c82", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6548, "license_type": "permissive", "max_line_length": 149, "num_lines": 150, "path": "/src/TorchSharp/Distributions/FisherSnedecor.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// A Fisher-Snedecor distribution parameterized by `df1` and `df2`.\n /// </summary>\n public class FisherSnedecor : torch.distributions.Distribution\n {\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public override Tensor mean {\n get {\n var df2 = this.df2.clone();\n df2[df2 <= 2] = torch.tensor(float.NaN);\n return df2 / (df2 - 2);\n }\n }\n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public override Tensor variance {\n get {\n using var _ = torch.NewDisposeScope();\n var df2 = this.df2.clone();\n df2[df2 <= 4] = torch.tensor(float.NaN);\n return (2 * df2.pow(2) * (this.df1 + df2 - 2) / (this.df1 * (df2 - 2).pow(2) * (df2 - 4))).MoveToOuterDisposeScope();\n }\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"df1\">Degrees of freedom parameter 1</param>\n /// <param name=\"df2\">Degrees of freedom parameter 2</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n public FisherSnedecor(Tensor df1, Tensor df2, torch.Generator generator = null) : base(generator)\n {\n var bcast = torch.broadcast_tensors(df1, df2);\n this.df1 = bcast[0].DetachFromDisposeScope();\n this.df2 = bcast[1].DetachFromDisposeScope();\n this.gamma1 = new Gamma(this.df1 * 0.5, this.df1, generator);\n this.gamma2 = new Gamma(this.df2 * 0.5, this.df2, generator);\n this.batch_shape = this.df1.size();\n }\n\n private Tensor df1;\n private Tensor df2;\n private Gamma gamma1;\n private Gamma gamma2;\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n public override Tensor rsample(params long[] sample_shape)\n {\n using var _ = torch.NewDisposeScope();\n var shape = ExtendedShape(sample_shape);\n var X1 = gamma1.rsample(sample_shape).view(shape);\n var X2 = gamma2.rsample(sample_shape).view(shape);\n\n var tiny = torch.finfo(X2.dtype).tiny;\n X2.clamp_(min: tiny);\n var Y = X1 / X2;\n \n return Y.clamp_(min: tiny).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor log_prob(Tensor value)\n {\n using var _ = torch.NewDisposeScope();\n var ct1 = this.df1 * 0.5;\n var ct2 = this.df2 * 0.5;\n var ct3 = this.df1 / this.df2;\n var t1 = (ct1 + ct2).lgamma() - ct1.lgamma() - ct2.lgamma();\n var t2 = ct1 * ct3.log() + (ct1 - 1) * torch.log(value);\n var t3 = (ct1 + ct2) * torch.log1p(ct3 * value);\n return (t1 + t2 - t3).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is FisherSnedecor))\n throw new ArgumentException(\"expand(): 'instance' must be a FisherSnedecor distribution\");\n\n var df1 = this.df1.expand(batch_shape);\n var df2 = this.df2.expand(batch_shape);\n\n var newDistribution = ((instance == null) ? new FisherSnedecor(df1, df2, generator) : instance) as FisherSnedecor;\n\n newDistribution.batch_shape = batch_shape;\n if (newDistribution == instance) {\n newDistribution.df1 = df1;\n newDistribution.df2 = df2;\n newDistribution.gamma1 = this.gamma1.expand(batch_shape) as Gamma;\n newDistribution.gamma2 = this.gamma2.expand(batch_shape) as Gamma;\n\n }\n return newDistribution;\n }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n public override Tensor entropy()\n {\n throw new NotImplementedException();\n }\n }\n\n }\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a Fisher-Snedecor distribution parameterized by `df1` and `df2`.\n /// </summary>\n /// <param name=\"df1\">Degrees of freedom parameter 1</param>\n /// <param name=\"df2\">Degrees of freedom parameter 2</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static FisherSnedecor FisherSnedecor(Tensor df1, Tensor df2, torch.Generator generator = null)\n {\n return new FisherSnedecor(df1, df2, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.7052238583564758, "alphanum_fraction": 0.7077114582061768, "avg_line_length": 33.956520080566406, "blob_id": "d630445cd725c592e3614ff3d13fb136ef8c65c9", "content_id": "fc67a88de47acc9ef191cccdd65a17317b439531", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 804, "license_type": "permissive", "max_line_length": 130, "num_lines": 23, "path": "/src/TorchSharp/PInvoke/LibTorchSharp.THSTorchCuda.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp.PInvoke\n{\n internal static partial class NativeMethods\n {\n [DllImport(\"LibTorchSharp\")]\n [return: MarshalAs(UnmanagedType.U1)]\n internal static extern bool THSTorchCuda_is_available();\n\n [DllImport(\"LibTorchSharp\")]\n [return: MarshalAs(UnmanagedType.U1)]\n internal static extern bool THSTorchCuda_cudnn_is_available();\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern int THSTorchCuda_device_count();\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSTorchCuda_synchronize(long device_index);\n }\n}\n" }, { "alpha_fraction": 0.5449577569961548, "alphanum_fraction": 0.5449577569961548, "avg_line_length": 33.11864471435547, "blob_id": "992bb272137652ad68ba5a325280bf1016c33afe", "content_id": "be913efd27d11dfdf7de835f59fddb31a6b9e352", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2013, "license_type": "permissive", "max_line_length": 130, "num_lines": 59, "path": "/src/TorchVision/RandomChoice.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class RandomChoice : IDisposable, ITransform\n {\n public RandomChoice(Generator generator, ITransform[] transforms)\n {\n this.transforms = transforms;\n this.generator = generator;\n }\n\n public void Dispose()\n {\n foreach (var t in transforms) {\n if (t is IDisposable) {\n ((IDisposable)t).Dispose();\n }\n }\n }\n\n public Tensor call(Tensor input)\n {\n var chance = torch.randint_int(transforms.Length, generator);\n return transforms[chance].call(input);\n }\n\n private ITransform[] transforms;\n private Generator generator;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Apply a single transformation randomly picked from a list. \n /// </summary>\n /// <param name=\"transforms\">A list of transforms to apply.</param>\n static public ITransform RandomChoice(params ITransform[] transforms)\n {\n return new RandomChoice(null, transforms);\n }\n\n /// <summary>\n /// Apply a single transformation randomly picked from a list. \n /// </summary>\n /// <param name=\"generator\">A random number generator instance.</param>\n /// <param name=\"transforms\">A list of transforms to apply.</param>\n static public ITransform RandomChoice(Generator generator, params ITransform[] transforms)\n {\n return new RandomChoice(generator, transforms);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6129446029663086, "alphanum_fraction": 0.6145948171615601, "avg_line_length": 46.846492767333984, "blob_id": "f931d728688c30958b1de42e6ffc6bfbb82f0d6d", "content_id": "554eb4de11865cbfbe1f8ad30f627e026f627c09", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 10908, "license_type": "permissive", "max_line_length": 186, "num_lines": 228, "path": "/src/TorchSharp/Tensor/torch.RandomSampling.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Diagnostics.Contracts;\nusing TorchSharp.PInvoke;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n // https://pytorch.org/docs/stable/torch#random-sampling\n public static partial class torch\n {\n // https://pytorch.org/docs/stable/generated/torch.seed\n /// <summary>\n /// Sets the seed for generating random numbers to a non-deterministic random number. Returns a 64 bit number used to seed the RNG.\n /// </summary>\n public static long seed() => torch.random.seed();\n\n // https://pytorch.org/docs/stable/generated/torch.manual_seed\n /// <summary>\n /// Sets the seed for generating random numbers. Returns a torch.Generator object.\n /// </summary>\n /// <param name=\"seed\">The desired seed.</param>\n public static Generator manual_seed(long seed) => torch.random.manual_seed(seed);\n\n // https://pytorch.org/docs/stable/generated/torch.initial_seed\n /// <summary>\n /// Returns the initial seed for generating random numbers.\n /// </summary>\n public static long initial_seed() => torch.random.initial_seed();\n\n // https://pytorch.org/docs/stable/generated/torch.get_rng_state\n /// <summary>\n /// Returns the random number generator state as a torch.ByteTensor.\n /// </summary>\n public static Tensor get_rng_state() => torch.random.get_rng_state();\n\n // https://pytorch.org/docs/stable/generated/torch.set_rng_state\n /// <summary>\n /// Sets the random number generator state.\n /// </summary>\n /// <param name=\"new_state\">The desired state</param>\n public static void set_rng_state(Tensor new_state) => torch.random.set_rng_state(new_state);\n\n // https://pytorch.org/docs/stable/generated/torch.bernoulli\n /// <summary>\n /// Draws binary random numbers (0 or 1) from a Bernoulli distribution.\n /// </summary>\n /// <param name=\"input\">The input tensor of probability values for the Bernoulli distribution</param>\n /// <param name=\"generator\">Optional random number generator</param>\n /// <returns></returns>\n public static Tensor bernoulli(Tensor input, Generator? generator = null) => input.bernoulli(generator);\n\n // https://pytorch.org/docs/stable/generated/torch.multinomial\n /// <summary>\n /// Returns a tensor where each row contains num_samples indices sampled from the multinomial probability distribution located in the corresponding row of tensor input.\n /// </summary>\n /// <param name=\"input\">A probabilities tensor</param>\n /// <param name=\"num_samples\">Number of samples to draw</param>\n /// <param name=\"replacement\">Whether to draw with replacement or not</param>\n /// <param name=\"generator\">Optional random number generator</param>\n public static Tensor multinomial(Tensor input, long num_samples, bool replacement = false, Generator? generator = null) => input.multinomial(num_samples, replacement, generator);\n\n // https://pytorch.org/docs/stable/generated/torch.normal\n /// <summary>\n /// Returns a tensor of random numbers drawn from separate normal distributions whose mean and standard deviation are given.\n /// </summary>\n /// <param name=\"mean\">The tensor of per-element means</param>\n /// <param name=\"std\">The tensor of per-element standard deviations</param>\n /// <param name=\"generator\">An optional random number generator</param>\n /// <returns></returns>\n /// <exception cref=\"ArgumentException\"></exception>\n public static Tensor normal(Tensor mean, Tensor std, Generator? generator = null)\n {\n if (std.device_type != mean.device_type || (std.device_type == DeviceType.CUDA && std.device_index != mean.device_index))\n throw new ArgumentException(\"The 'means' and 'stddev' tensors must be located on the same device.\");\n return randn(mean.shape, null, std.device, false, generator, names: null) * std + mean;\n }\n\n // https://pytorch.org/docs/stable/generated/torch.poisson\n /// <summary>\n /// Returns a tensor of the same size as input with each element sampled from a Poisson distribution with rate parameter given by the corresponding element in input\n /// </summary>\n /// <param name=\"input\">Input tensor.</param>\n /// <param name=\"generator\">Optional random number generator</param>\n /// <returns></returns>\n public static Tensor poisson(Tensor input, Generator? generator = null) => input.poisson(generator);\n\n // https://pytorch.org/docs/stable/generated/torch.rand\n // TODO: implement layout parameter\n static Tensor rand(\n long[] size,\n ScalarType? dtype = null,\n layout layout = layout.strided,\n Device? device = null,\n bool requires_grad = false)\n => rand(size, dtype, device, requires_grad);\n\n // https://pytorch.org/docs/stable/generated/torch.rand_like\n // TODO: implement layout parameter\n // TODO: implement memory_format parameter\n static Tensor rand_like(\n Tensor input,\n ScalarType? dtype=null,\n layout layout = layout.strided,\n Device? device=null,\n bool requires_grad=false,\n memory_format memory_format = memory_format.preserve_format)\n => rand_like(input, dtype, device, requires_grad);\n\n // https://pytorch.org/docs/stable/generated/torch.randint\n // TODO: implement layout parameter\n static Tensor randint(long low, long high, Size size,\n Generator? generator = null,\n ScalarType? dtype = null,\n layout layout = layout.strided,\n Device? device = null,\n bool requires_grad = false)\n => randint(low, high, size, dtype, device, requires_grad, generator);\n\n // TODO: implement layout parameter\n static Tensor randint(long high, Size size,\n Generator? generator = null,\n ScalarType? dtype = null,\n layout layout = layout.strided,\n Device? device = null,\n bool requires_grad = false)\n => randint(high, size, dtype, device, requires_grad, generator);\n\n // https://pytorch.org/docs/stable/generated/torch.randint_like\n // TODO: implement layout parameter\n // TODO: implement memory_format parameter\n static Tensor randint_like(\n Tensor input,\n long low,\n long high,\n ScalarType? dtype = null,\n layout layout = layout.strided,\n Device? device = null,\n bool requires_grad = false,\n memory_format memory_format = memory_format.preserve_format)\n => randint_like(input, low, high, dtype, device, requires_grad);\n\n // https://pytorch.org/docs/stable/generated/torch.randn\n // TODO: implement layout parameter\n static Tensor randn(\n long[] size,\n Generator? generator = null,\n ScalarType? dtype = null,\n layout layout = layout.strided,\n Device? device = null,\n bool requires_grad = false)\n => randn(size, dtype, device, requires_grad, generator);\n\n // https://pytorch.org/docs/stable/generated/torch.randn_like\n /// <summary>\n /// Returns a tensor with the same size as input that is filled with random numbers from a uniform distribution on the interval [0,1) .\n /// </summary>\n // TODO: implement layout parameter\n // TODO: implement memory_format parameter\n static Tensor randn_like(\n Tensor input,\n ScalarType? dtype = null,\n layout layout = layout.strided,\n Device? device = null,\n bool requires_grad = false,\n memory_format memory_format = memory_format.preserve_format)\n => input.rand_like(dtype, device, requires_grad);\n\n // https://pytorch.org/docs/stable/generated/torch.randn_like\n /// <summary>\n /// Returns a tensor with the same size as input that is filled with random numbers from a uniform distribution on the interval [0,1) .\n /// </summary>\n public static Tensor rand_like(Tensor input, ScalarType? dtype = null, Device? device = null, bool requires_grad = false)\n => input.rand_like(dtype, device, requires_grad);\n\n // https://pytorch.org/docs/stable/generated/torch.randperm\n /// <summary>\n /// Creates 1-D tensor of size [n] with a random permutation of [0, n).\n /// </summary>\n public static Tensor randperm(long n, ScalarType? dtype = null, Device? device = null,\n bool requires_grad = false, Generator? generator = null)\n => randperm(n, generator, dtype, layout.strided, device, false);\n\n /// <summary>\n /// Mutates the existing tensor to be a 1-D tensor of size [n] with a random permutation of [0, n).\n /// </summary>\n public static Tensor randperm(long n,\n Tensor @out,\n Generator? generator = null)\n {\n var genHandle = generator?.Handle ?? IntPtr.Zero;\n var res = NativeMethods.THSTensor_randperm_out(genHandle, n, @out.Handle);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.randperm\n /// <summary>\n /// Creates 1-D tensor of size [n] with a random permutation of [0, n).\n /// </summary>\n // TODO: implement layout parameter\n // TODO: implement pin_memory parameter\n static Tensor randperm(\n long n,\n Generator? generator = null,\n ScalarType? dtype = ScalarType.Int64,\n layout layout = layout.strided,\n Device? device = null,\n bool requires_grad = false,\n bool pin_memory = false)\n {\n device = InitializeDevice(device);\n dtype ??= ScalarType.Int64;\n\n var genHandle = generator?.Handle ?? IntPtr.Zero;\n\n var handle = THSTensor_randperm(genHandle, n, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_randperm(genHandle, n, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(handle);\n }\n }\n}" }, { "alpha_fraction": 0.5832617878913879, "alphanum_fraction": 0.5836910009384155, "avg_line_length": 39.17241287231445, "blob_id": "cb554b4a5683a579127722ca7974247e3ccc7555", "content_id": "71c7b6a23d98d2948bc1a5ad8840af112aa859a8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2330, "license_type": "permissive", "max_line_length": 134, "num_lines": 58, "path": "/src/TorchSharp/NN/Unflatten.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent an unflattening operation.\n /// </summary>\n public sealed class Unflatten : torch.nn.Module<Tensor, Tensor>\n {\n internal Unflatten(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_Unflatten_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Unflattens a tensor dim expanding it to a desired shape. For use with Sequential.\n /// </summary>\n /// <param name=\"dim\">Dimension to be unflattened</param>\n /// <param name=\"unflattenedSize\">New shape of the unflattened dimension</param>\n /// <returns></returns>\n public static Unflatten Unflatten(long dim, long[] unflattenedSize)\n {\n unsafe {\n fixed (long* pUnflattenedSize = unflattenedSize) {\n var handle = THSNN_Unflatten_ctor(dim, (IntPtr)pUnflattenedSize, unflattenedSize.Length, out var boxedHandle);\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n return new Unflatten(handle, boxedHandle);\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.46875, "alphanum_fraction": 0.46875, "avg_line_length": 27.935483932495117, "blob_id": "815911655cd314a5515ee60aeb8c5d95e7e4b827", "content_id": "8e88cb4a4747cb1dfffc245e32ed06170c91f518", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 896, "license_type": "permissive", "max_line_length": 130, "num_lines": 31, "path": "/src/TorchAudio/Datasets/YesnoDatasetItem.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n public static partial class datasets\n {\n /// <summary>\n /// An item in YESNO dataset.\n /// </summary>\n public struct YesnoDatasetItem\n {\n /// <summary>\n /// Samples of the audio clip\n /// </summary>\n public torch.Tensor waveform;\n\n /// <summary>\n /// Sampling rate of the audio clip\n /// </summary>\n public int sample_rate;\n\n /// <summary>\n /// Labels of the audio clip\n /// </summary>\n public string[] labels;\n }\n }\n }\n}" }, { "alpha_fraction": 0.5160085558891296, "alphanum_fraction": 0.5280149579048157, "avg_line_length": 41.12359619140625, "blob_id": "7af9f3ec848919e6cd5c245772688ed4e9109a8e", "content_id": "bef662f42e449066b2049b887f451a3ec1348638", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3748, "license_type": "permissive", "max_line_length": 163, "num_lines": 89, "path": "/src/TorchVision/RandomPerspective.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class RandomPerspective : ITransform\n {\n public RandomPerspective(double distortion, double p)\n {\n this.distortion = distortion;\n this.p = p;\n this.rnd = new Random();\n }\n\n public Tensor call(Tensor img)\n {\n if (rnd.NextDouble() <= p) {\n var _end = img.shape.Length;\n var w = (int)img.shape[_end - 1];\n var h = (int)img.shape[_end - 2];\n\n var (startpoints, endpoints) = GetParams(w, h);\n return transforms.functional.perspective(img, startpoints, endpoints);\n }\n\n return img;\n }\n\n private int Adjust(double input, double min, double max)\n {\n return (int)(Math.Floor(input * (max - min) + min));\n }\n\n private (List<IList<int>>, List<IList<int>>) GetParams(int width, int height)\n {\n var half_width = width / 2;\n var half_height = height / 2;\n\n var randoms = torch.rand(8, ScalarType.Float64).data<double>().ToArray();\n\n var topleft = new int[] {\n Adjust(randoms[0], 0, distortion * half_width + 1),\n Adjust(randoms[1], 0, distortion * half_height + 1)\n };\n var topright = new int[] {\n Adjust(randoms[2], width - (int)Math.Floor(distortion * half_width) - 1, width),\n Adjust(randoms[3], 0, (int)Math.Floor(distortion * half_height) + 1)\n };\n var botright = new int[] {\n Adjust(randoms[4], width - (int)Math.Floor(distortion * half_width) - 1, width),\n Adjust(randoms[5], height - (int)Math.Floor(distortion * half_height) - 1, height),\n };\n var botleft = new int[] {\n Adjust(randoms[6], 0, (int)Math.Floor(distortion * half_width) + 1),\n Adjust(randoms[7], height - (int)Math.Floor(distortion * half_height) - 1, height),\n };\n\n var startpoints = new int[][] { new int[] { 0, 0 }, new int[] { width - 1, 0 }, new int[] { width - 1, height - 1 }, new int[] { 0, height - 1 } };\n var endpoints = new int[][] { topleft, topright, botright, botleft }.ToList();\n\n return (startpoints.Select(x => x.ToList() as IList<int>).ToList(), endpoints.Select(x => x.ToList() as IList<int>).ToList());\n }\n\n private Random rnd;\n private double p;\n private double distortion;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Performs a random perspective transformation of the given image with a given probability.\n /// </summary>\n /// <param name=\"distortion\">Argument to control the degree of distortion and ranges from 0 to 1. Default is 0.5.</param>\n /// <param name=\"p\">Probability of the image being transformed. Default is 0.5.</param>\n /// <returns></returns>\n /// <remarks>The application and perspectives are all stochastic.</remarks>\n static public ITransform RandomPerspective(double distortion = 0.5, double p = 0.5)\n {\n return new RandomPerspective(distortion, p);\n }\n }\n }\n}" }, { "alpha_fraction": 0.6189464926719666, "alphanum_fraction": 0.6189464926719666, "avg_line_length": 47.06122589111328, "blob_id": "6d1e27c817186267dbe4236ade2187b3715276f9", "content_id": "e3cf8208c46e5f233794cbd5bdf4fa5f2714a30c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2354, "license_type": "permissive", "max_line_length": 288, "num_lines": 49, "path": "/src/TorchVision/Rotate.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System.Collections.Generic;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class Rotate : ITransform\n {\n internal Rotate(float angle, InterpolationMode interpolation = InterpolationMode.Nearest, bool expand = false, (int, int)? center = null, IList<float> fill = null)\n {\n this.angle = angle;\n this.fill = fill;\n this.expand = expand;\n this.center = center;\n this.interpolation = interpolation;\n }\n\n public torch.Tensor call(torch.Tensor img)\n {\n return transforms.functional.rotate(img, angle, interpolation, expand, center, fill);\n }\n\n private float angle;\n private bool expand;\n private (int, int)? center;\n private IList<float> fill;\n private InterpolationMode interpolation;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Rotate the image by angle, counter-clockwise.\n /// </summary>\n /// <param name=\"angle\">Angle by which to rotate.</param>\n /// <param name=\"interpolation\">Desired interpolation enum. Default is `InterpolationMode.NEAREST`.</param>\n /// <param name=\"expand\">If true, expands the output to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation.</param>\n /// <param name=\"center\">Center of rotation, (x, y). Origin is the upper left corner.</param>\n /// <param name=\"fill\">Pixel fill value for the area outside the rotated. If given a number, the value is used for all bands respectively.</param>\n static public ITransform Rotate(float angle, InterpolationMode interpolation = InterpolationMode.Nearest, bool expand = false, (int, int)? center = null, IList<float> fill = null)\n {\n return new Rotate(angle, interpolation, expand, center, fill);\n }\n }\n }\n}" }, { "alpha_fraction": 0.5113962292671204, "alphanum_fraction": 0.5249078869819641, "avg_line_length": 49.53792953491211, "blob_id": "7bdf7e92ae5e45e8d1a5d2721182013ede7cfaf0", "content_id": "882563c74641a8196b34be15a091a6ff03cfa585", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7327, "license_type": "permissive", "max_line_length": 182, "num_lines": 145, "path": "/src/TorchAudio/Datasets/SpeechCommandsDataset.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n public static partial class datasets\n {\n private class SpeechCommandsDataset : torch.utils.data.Dataset<SpeechCommandsDatasetItem>\n {\n internal const string URL = \"speech_commands_v0.02\";\n internal const string FOLDER_IN_ARCHIVE = \"SpeechCommands\";\n private const string HASH_DIVIDER = \"_nohash_\";\n private const string EXCEPT_FOLDER = \"_background_noise_\";\n internal static readonly IDictionary<string, string> _CHECKSUMS = new Dictionary<string, string> {\n [\"https://storage.googleapis.com/download.tensorflow.org/data/speech_commands_v0.01.tar.gz\"] = \"743935421bb51cccdb6bdd152e04c5c70274e935c82119ad7faeec31780d811d\",\n [\"https://storage.googleapis.com/download.tensorflow.org/data/speech_commands_v0.02.tar.gz\"] = \"af14739ee7dc311471de98f5f9d2c9191b18aedfe957f4a6ff791c709868ff58\",\n };\n\n private string _path;\n private string[] _walker;\n\n internal SpeechCommandsDataset(string path, string subset)\n {\n _path = path;\n if (subset == \"validation\") {\n _walker = LoadList(_path, \"validation_list.txt\");\n } else if (subset == \"testing\") {\n _walker = LoadList(_path, \"testing_list.txt\");\n } else if (subset == \"training\") {\n var excludes = new HashSet<string>(LoadList(_path, \"validation_list.txt\", \"testing_list.txt\"));\n _walker = Directory.EnumerateFiles(_path, \"*.wav\", SearchOption.AllDirectories)\n .Where(audioPath => audioPath.Contains(HASH_DIVIDER) && !audioPath.Contains(EXCEPT_FOLDER))\n .Where(audioPath => !excludes.Contains(audioPath))\n .OrderBy(audioPath => audioPath)\n .ToArray();\n } else {\n _walker = Directory.EnumerateFiles(_path, \"*.wav\", SearchOption.AllDirectories)\n .Where(audioPath => audioPath.Contains(HASH_DIVIDER) && !audioPath.Contains(EXCEPT_FOLDER))\n .OrderBy(audioPath => audioPath)\n .ToArray();\n }\n }\n\n public override long Count => _walker.LongLength;\n\n public override SpeechCommandsDatasetItem GetTensor(long index)\n {\n var audioPath = _walker[index];\n return LoadSpeechCommandsItem(audioPath);\n }\n\n private string[] LoadList(string root, params string[] filenames)\n {\n List<string> output = new();\n foreach (var filename in filenames) {\n var filepath = Path.Combine(root, filename);\n var pathList = File.ReadAllLines(filepath)\n .Select(line => Path.Combine(root, Path.Combine(line.Trim())));\n output.AddRange(pathList);\n }\n return output.ToArray();\n }\n\n private SpeechCommandsDatasetItem LoadSpeechCommandsItem(string filepath)\n {\n var filename = Path.GetFileName(filepath);\n var label = Path.GetFileName(Path.GetDirectoryName(filepath));\n\n // Some filenames have the form of \"xxx.wav.wav\"\n var speaker = Path.GetFileNameWithoutExtension(filename);\n speaker = Path.GetFileNameWithoutExtension(filename);\n\n var parts = speaker.Split(new string[] { HASH_DIVIDER }, StringSplitOptions.None);\n var speaker_id = parts[0];\n int utterance_number = int.Parse(parts[1]);\n\n // Load audio\n var (waveform, sample_rate) = torchaudio.load(filepath);\n return new SpeechCommandsDatasetItem {\n waveform = waveform,\n sample_rate = sample_rate,\n label = label,\n speaker_id = speaker_id,\n utterance_number = utterance_number\n };\n }\n }\n\n /// <summary>\n /// Create a Speech Commands dataset\n /// </summary>\n /// <param name=\"root\">The path to the dataset</param>\n /// <param name=\"url\">The URL to download the dataset from</param>\n /// <param name=\"folder_in_archive\">The top directory of the dataset</param>\n /// <param name=\"download\">True to download the dataset</param>\n /// <param name=\"subset\">Select a subset of the dataset, null, \"training\", \"validation\" or \"testing\"</param>\n /// <returns>The dataset</returns>\n /// <exception cref=\"InvalidDataException\"></exception>\n public static torch.utils.data.Dataset<SpeechCommandsDatasetItem> SPEECHCOMMANDS(\n string root,\n string url = SpeechCommandsDataset.URL,\n string folder_in_archive = SpeechCommandsDataset.FOLDER_IN_ARCHIVE,\n bool download = false,\n string subset = null)\n {\n if (url == \"speech_commands_v0.01\" || url == \"speech_commands_v0.02\") {\n string base_url = \"https://storage.googleapis.com/download.tensorflow.org/data/\";\n string ext_archive = \".tar.gz\";\n url = base_url + url + ext_archive;\n }\n\n string[] parts = url.Split('/');\n string basename = parts[parts.Length - 1];\n string archive = Path.Combine(root, basename);\n int index = basename.LastIndexOf('.');\n index = basename.LastIndexOf('.', index - 1);\n basename = basename.Substring(0, index);\n folder_in_archive = Path.Combine(folder_in_archive, basename);\n\n string path = Path.Combine(root, folder_in_archive);\n\n if (download) {\n if (!Directory.Exists(path)) {\n if (!File.Exists(archive)) {\n string checksum = SpeechCommandsDataset._CHECKSUMS.TryGetValue(url, out checksum) ? checksum : null;\n torch.hub.download_url_to_file(url, archive, hash_prefix: checksum);\n }\n utils.extract_archive(archive, path);\n }\n } else {\n if (!Directory.Exists(path)) {\n throw new InvalidDataException(\"Dataset not found. Please use `download=true` to download it.\");\n }\n }\n\n return new SpeechCommandsDataset(path, subset);\n }\n }\n }\n}" }, { "alpha_fraction": 0.5559908747673035, "alphanum_fraction": 0.5563173294067383, "avg_line_length": 39.30263137817383, "blob_id": "2195b86025076ed9a7f91d5da7a2406647f22870", "content_id": "cfd9ea1c7a343b03c761495d3017338438f2db1d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3063, "license_type": "permissive", "max_line_length": 130, "num_lines": 76, "path": "/src/TorchSharp/NN/Activation/Threshold.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a Threshold module.\n /// </summary>\n public sealed class Threshold : torch.nn.Module<Tensor, Tensor>\n {\n internal Threshold(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_Threshold_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public override string GetName()\n {\n return typeof(Threshold).Name;\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Threshold\n /// </summary>\n /// <param name=\"threshold\">The value to threshold at</param>\n /// <param name=\"value\">The value to replace with</param>\n /// <param name=\"inplace\">Do the operation in-place</param>\n /// <returns></returns>\n public static Threshold Threshold(double threshold, double value, bool inplace = false)\n {\n var handle = THSNN_Threshold_ctor(threshold, value, inplace, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Threshold(handle, boxedHandle);\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Thresholds each element of the input Tensor.\n /// </summary>\n /// <param name=\"x\">The input tensor</param>\n /// <param name=\"threshold\">The value to threshold at</param>\n /// <param name=\"value\">The value to replace with</param>\n /// <param name=\"inplace\">Do the operation in-place</param>\n /// <returns></returns>\n public static Tensor Threshold(Tensor x, double threshold, double value, bool inplace = false)\n {\n using (var m = nn.Threshold(threshold, value, inplace)) {\n return m.call(x);\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.4495481252670288, "alphanum_fraction": 0.49807870388031006, "avg_line_length": 46.07872772216797, "blob_id": "7eaf00b9ecefef34492f20cc69f50ee6358b3d12", "content_id": "91893eda7b1e0be285989fbecab0c21141e5a5c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 28106, "license_type": "permissive", "max_line_length": 180, "num_lines": 597, "path": "/src/TorchVision/models/InceptionV3.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class models\n {\n /// <summary>\n /// ResNet-18\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"dropout\"></param>\n /// <param name=\"transform_input\"></param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.inception_v3(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be 299x299. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.InceptionV3 inception_v3(\n int num_classes = 1000,\n float dropout = 0.5f,\n bool transform_input = false,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null)\n {\n return new Modules.InceptionV3(num_classes, dropout, transform_input, weights_file, skipfc, device);\n }\n }\n }\n\n namespace Modules\n {\n public class InceptionV3 : Module<Tensor, Tensor>\n {\n // The code here is is loosely based on\n // https://github.com/pytorch/vision/blob/main/torchvision/models/inception.py\n // Licence and copypright notice at: https://github.com/pytorch/vision/blob/main/LICENSE\n\n private readonly Module<Tensor, Tensor> Conv2d_1a_3x3;\n private readonly Module<Tensor, Tensor> Conv2d_2a_3x3;\n private readonly Module<Tensor, Tensor> Conv2d_2b_3x3;\n private readonly Module<Tensor, Tensor> maxpool1;\n private readonly Module<Tensor, Tensor> Conv2d_3b_1x1;\n private readonly Module<Tensor, Tensor> Conv2d_4a_3x3;\n private readonly Module<Tensor, Tensor> maxpool2;\n\n private readonly Module<Tensor, Tensor> Mixed_5b;\n private readonly Module<Tensor, Tensor> Mixed_5c;\n private readonly Module<Tensor, Tensor> Mixed_5d;\n private readonly Module<Tensor, Tensor> Mixed_6a;\n private readonly Module<Tensor, Tensor> Mixed_6b;\n private readonly Module<Tensor, Tensor> Mixed_6c;\n private readonly Module<Tensor, Tensor> Mixed_6d;\n private readonly Module<Tensor, Tensor> Mixed_6e;\n private readonly Module<Tensor, Tensor> AuxLogits;\n private readonly Module<Tensor, Tensor> Mixed_7a;\n private readonly Module<Tensor, Tensor> Mixed_7b;\n private readonly Module<Tensor, Tensor> Mixed_7c;\n private readonly AdaptiveAvgPool2d avgpool;\n private Dropout dropout;\n private readonly Linear fc;\n\n bool transform_input = false;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n Conv2d_1a_3x3.Dispose(); Conv2d_2a_3x3.Dispose(); Conv2d_2b_3x3.Dispose();\n Conv2d_3b_1x1.Dispose(); Conv2d_4a_3x3.Dispose();\n Mixed_5b.Dispose(); Mixed_5c.Dispose(); Mixed_5d.Dispose();\n Mixed_6a.Dispose(); Mixed_6b.Dispose(); Mixed_6c.Dispose();\n Mixed_6d.Dispose(); Mixed_6e.Dispose();\n AuxLogits.Dispose();\n Mixed_7a.Dispose(); Mixed_7b.Dispose(); Mixed_7c.Dispose();\n maxpool1.Dispose(); maxpool2.Dispose(); avgpool.Dispose();\n dropout.Dispose(); fc.Dispose();\n\n }\n base.Dispose(disposing);\n }\n\n public InceptionV3(int numClasses = 1000,\n float dropout = 0.5f,\n bool transform_input = false,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null) : base(nameof(InceptionV3))\n {\n this.transform_input = transform_input;\n\n Conv2d_1a_3x3 = conv_block(3, 32, kernel_size: 3, stride: 2);\n Conv2d_2a_3x3 = conv_block(32, 32, kernel_size: 3);\n Conv2d_2b_3x3 = conv_block(32, 64, kernel_size: 3, padding: 1);\n maxpool1 = MaxPool2d(kernelSize: 3, stride: 2);\n Conv2d_3b_1x1 = conv_block(64, 80, kernel_size: 1);\n Conv2d_4a_3x3 = conv_block(80, 192, kernel_size: 3);\n maxpool2 = MaxPool2d(kernelSize: 3, stride: 2);\n\n Mixed_5b = inception_a(192, pool_features: 32);\n Mixed_5c = inception_a(256, pool_features: 64);\n Mixed_5d = inception_a(288, pool_features: 64);\n Mixed_6a = inception_b(288);\n Mixed_6b = inception_c(768, channels_7x7: 128);\n Mixed_6c = inception_c(768, channels_7x7: 160);\n Mixed_6d = inception_c(768, channels_7x7: 160);\n Mixed_6e = inception_c(768, channels_7x7: 192);\n AuxLogits = inception_aux(768, numClasses);\n Mixed_7a = inception_d(768);\n Mixed_7b = inception_e(1280);\n Mixed_7c = inception_e(2048);\n avgpool = nn.AdaptiveAvgPool2d((1, 1));\n this.dropout = nn.Dropout(p: dropout);\n fc = nn.Linear(2048, numClasses);\n\n RegisterComponents();\n\n if (string.IsNullOrEmpty(weights_file)) {\n\n foreach (var (_, m) in named_modules()) {\n switch (m) {\n case TorchSharp.Modules.Conv2d conv:\n torch.nn.init.kaiming_normal_(conv.weight, mode: init.FanInOut.FanOut, nonlinearity: init.NonlinearityType.ReLU);\n break;\n case TorchSharp.Modules.Linear ln:\n torch.nn.init.normal_(ln.weight, 0, 0.01);\n torch.nn.init.constant_(ln.bias, 0);\n break;\n case TorchSharp.Modules.BatchNorm2d bn:\n torch.nn.init.constant_(bn.weight, 1);\n torch.nn.init.constant_(bn.bias, 0);\n break;\n }\n }\n }\n else {\n\n foreach (var (_, m) in named_modules()) {\n switch (m) {\n case TorchSharp.Modules.Linear ln:\n torch.nn.init.normal_(ln.weight, 0, 0.01);\n torch.nn.init.constant_(ln.bias, 0);\n break;\n }\n }\n this.load(weights_file, skip: skipfc ? new[] { \"fc.weight\", \"fc.bias\", \"AuxLogits.fc.weight\", \"AuxLogits.fc.bias\" } : null);\n }\n\n if (device != null && device.type == DeviceType.CUDA)\n this.to(device);\n }\n\n\n private static Module<Tensor, Tensor> conv_block(int in_channels, int out_channels, int kernel_size, int stride = 1, int padding = 0)\n {\n return Sequential(\n (\"conv\", Conv2d(in_channels, out_channels, bias: false, kernelSize: kernel_size, stride: stride, padding: padding)),\n (\"bn\", BatchNorm2d(out_channels, eps: 0.001)),\n (\"relu\", ReLU(true))\n );\n }\n\n private static Module<Tensor, Tensor> conv_block(int in_channels, int out_channels, (long, long) kernel_size, (long, long)? stride = null, (long, long)? padding = null)\n {\n return Sequential(\n (\"conv\", Conv2d(in_channels, out_channels, bias: false, kernelSize: kernel_size, stride: stride, padding: padding)),\n (\"bn\", BatchNorm2d(out_channels, eps: 0.001)),\n (\"relu\", ReLU(true))\n );\n }\n\n private Module<Tensor, Tensor> inception_a(int in_channels, int pool_features) => new InceptionA(in_channels, pool_features);\n private Module<Tensor, Tensor> inception_b(int in_channels) => new InceptionB(in_channels);\n private Module<Tensor, Tensor> inception_c(int in_channels, int channels_7x7) => new InceptionC(in_channels, channels_7x7);\n private Module<Tensor, Tensor> inception_d(int in_channels) => new InceptionD(in_channels);\n private Module<Tensor, Tensor> inception_e(int in_channels) => new InceptionE(in_channels);\n private Module<Tensor, Tensor> inception_aux(int in_channels, int num_classes) => new InceptionAux(in_channels, num_classes);\n\n public override Tensor forward(Tensor x)\n {\n // Transform\n using (var scope = NewDisposeScope()) {\n if (transform_input) {\n\n var x_ch0 = torch.unsqueeze(x[(null, null), 0], 1) * (0.229f / 0.5f) + (0.485f - 0.5f) / 0.5f;\n var x_ch1 = torch.unsqueeze(x[(null, null), 1], 1) * (0.224f / 0.5f) + (0.456f - 0.5f) / 0.5f;\n var x_ch2 = torch.unsqueeze(x[(null, null), 2], 1) * (0.225f / 0.5f) + (0.406f - 0.5f) / 0.5f;\n x = torch.cat(new[] { x_ch0, x_ch1, x_ch2 }, 1);\n }\n\n // N x 3 x 299 x 299\n x = Conv2d_1a_3x3.call(x);\n // N x 32 x 149 x 149\n x = Conv2d_2a_3x3.call(x);\n // N x 32 x 147 x 147\n x = Conv2d_2b_3x3.call(x);\n // N x 64 x 147 x 147\n x = maxpool1.call(x);\n // N x 64 x 73 x 73\n x = Conv2d_3b_1x1.call(x);\n // N x 80 x 73 x 73\n x = Conv2d_4a_3x3.call(x);\n // N x 192 x 71 x 71\n x = maxpool2.call(x);\n // N x 192 x 35 x 35\n x = Mixed_5b.call(x);\n // N x 256 x 35 x 35\n x = Mixed_5c.call(x);\n // N x 288 x 35 x 35\n x = Mixed_5d.call(x);\n // N x 288 x 35 x 35\n x = Mixed_6a.call(x);\n // N x 768 x 17 x 17\n x = Mixed_6b.call(x);\n // N x 768 x 17 x 17\n x = Mixed_6c.call(x);\n // N x 768 x 17 x 17\n x = Mixed_6d.call(x);\n // N x 768 x 17 x 17\n x = Mixed_6e.call(x);\n // N x 768 x 17 x 17\n x = Mixed_7a.call(x);\n // N x 1280 x 8 x 8\n x = Mixed_7b.call(x);\n // N x 2048 x 8 x 8\n x = Mixed_7c.call(x);\n // N x 2048 x 8 x 8\n // Adaptive average pooling\n x = avgpool.call(x);\n // N x 2048 x 1 x 1\n x = dropout.call(x);\n // N x 2048 x 1 x 1\n x = torch.flatten(x, 1);\n // N x 2048\n x = fc.call(x);\n // N x num_classes\n\n return x.MoveToOuterDisposeScope();\n }\n }\n\n class InceptionA : Module<Tensor, Tensor>\n {\n public InceptionA(int in_channels, int pool_features) : base(\"InceptionA\")\n {\n branch1x1 = conv_block(in_channels, 64, kernel_size: 1);\n branch5x5_1 = conv_block(in_channels, 48, kernel_size: 1);\n branch5x5_2 = conv_block(48, 64, kernel_size:5, padding: 2);\n branch3x3dbl_1 = conv_block(in_channels, 64, kernel_size:1);\n branch3x3dbl_2 = conv_block(64, 96, kernel_size:3, padding: 1);\n branch3x3dbl_3 = conv_block(96, 96, kernel_size:3, padding: 1);\n branch_pool = conv_block(in_channels, pool_features, kernel_size:1);\n\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor x)\n {\n var branch1x1_ = branch1x1.call(x);\n\n var branch5x5 = branch5x5_1.call(x);\n branch5x5 = branch5x5_2.call(branch5x5);\n\n var branch3x3dbl = branch3x3dbl_1.call(x);\n branch3x3dbl = branch3x3dbl_2.call(branch3x3dbl);\n branch3x3dbl = branch3x3dbl_3.call(branch3x3dbl);\n\n var branch_pool_ = functional.avg_pool2d(x, kernelSize: 3, stride: 1, padding: 1);\n branch_pool_ = branch_pool.call(branch_pool_);\n\n var outputs = new [] { branch1x1_, branch5x5, branch3x3dbl, branch_pool_ };\n return torch.cat(outputs, 1);\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n branch1x1.Dispose();\n branch3x3dbl_1.Dispose(); branch3x3dbl_2.Dispose(); branch3x3dbl_3.Dispose();\n branch_pool.Dispose();\n branch5x5_1.Dispose(); branch5x5_2.Dispose();\n }\n base.Dispose(disposing);\n }\n\n private readonly Module<Tensor, Tensor> branch1x1;\n private readonly Module<Tensor, Tensor> branch5x5_1;\n private readonly Module<Tensor, Tensor> branch5x5_2;\n private readonly Module<Tensor, Tensor> branch3x3dbl_1;\n private readonly Module<Tensor, Tensor> branch3x3dbl_2;\n private readonly Module<Tensor, Tensor> branch3x3dbl_3;\n private readonly Module<Tensor, Tensor> branch_pool;\n }\n\n class InceptionB : Module<Tensor, Tensor>\n {\n public InceptionB(int in_channels) : base(\"InceptionB\")\n {\n\n branch3x3 = conv_block(in_channels, 384, kernel_size: 3, stride: 2);\n branch3x3dbl_1 = conv_block(in_channels, 64, kernel_size: 1);\n branch3x3dbl_2 = conv_block(64, 96, kernel_size: 3, padding: 1);\n branch3x3dbl_3 = conv_block(96, 96, kernel_size: 3, stride: 2);\n\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor x)\n {\n\n var branch3x3_ = branch3x3.call(x);\n\n var branch3x3dbl = branch3x3dbl_1.call(x);\n branch3x3dbl = branch3x3dbl_2.call(branch3x3dbl);\n branch3x3dbl = branch3x3dbl_3.call(branch3x3dbl);\n\n var branch_pool = functional.max_pool2d(x, kernelSize: 3, stride: 2);\n\n var outputs = new[] { branch3x3_, branch3x3dbl, branch_pool };\n\n return torch.cat(outputs, 1);\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n branch3x3.Dispose();\n branch3x3dbl_1.Dispose();\n branch3x3dbl_2.Dispose();\n branch3x3dbl_3.Dispose();\n }\n base.Dispose(disposing);\n }\n\n private readonly Module<Tensor, Tensor> branch3x3;\n private readonly Module<Tensor, Tensor> branch3x3dbl_1;\n private readonly Module<Tensor, Tensor> branch3x3dbl_2;\n private readonly Module<Tensor, Tensor> branch3x3dbl_3;\n }\n\n class InceptionC : Module<Tensor, Tensor>\n {\n private readonly Module<Tensor, Tensor> branch1x1;\n private readonly Module<Tensor, Tensor> branch7x7_1;\n private readonly Module<Tensor, Tensor> branch7x7_2;\n private readonly Module<Tensor, Tensor> branch7x7_3;\n private readonly Module<Tensor, Tensor> branch7x7dbl_1;\n private readonly Module<Tensor, Tensor> branch7x7dbl_2;\n private readonly Module<Tensor, Tensor> branch7x7dbl_3;\n private readonly Module<Tensor, Tensor> branch7x7dbl_4;\n private readonly Module<Tensor, Tensor> branch7x7dbl_5;\n private readonly Module<Tensor, Tensor> branch_pool;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n branch1x1.Dispose();\n branch_pool.Dispose();\n branch7x7_1.Dispose(); branch7x7_2.Dispose(); branch7x7_3?.Dispose();\n branch7x7dbl_1.Dispose(); branch7x7dbl_2.Dispose(); branch7x7dbl_3.Dispose();\n branch7x7dbl_4.Dispose(); branch7x7dbl_5.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public InceptionC(int in_channels, int channels_7x7) : base(\"InceptionC\")\n {\n branch1x1 = conv_block(in_channels, 192, kernel_size: 1);\n\n var c7 = channels_7x7;\n branch7x7_1 = conv_block(in_channels, c7, kernel_size: 1);\n branch7x7_2 = conv_block(c7, c7, kernel_size: (1, 7), padding: (0, 3));\n branch7x7_3 = conv_block(c7, 192, kernel_size: (7, 1), padding: (3, 0));\n\n branch7x7dbl_1 = conv_block(in_channels, c7, kernel_size: 1);\n branch7x7dbl_2 = conv_block(c7, c7, kernel_size: (7, 1), padding: (3, 0));\n branch7x7dbl_3 = conv_block(c7, c7, kernel_size: (1, 7), padding: (0, 3));\n branch7x7dbl_4 = conv_block(c7, c7, kernel_size: (7, 1), padding: (3, 0));\n branch7x7dbl_5 = conv_block(c7, 192, kernel_size: (1, 7), padding: (0, 3));\n\n branch_pool = conv_block(in_channels, 192, kernel_size: 1);\n\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor x)\n {\n\n var branch1x1_ = branch1x1.call(x);\n\n var branch7x7 = branch7x7_1.call(x);\n branch7x7 = branch7x7_2.call(branch7x7);\n branch7x7 = branch7x7_3.call(branch7x7);\n\n var branch7x7dbl = branch7x7dbl_1.call(x);\n branch7x7dbl = branch7x7dbl_2.call(branch7x7dbl);\n branch7x7dbl = branch7x7dbl_3.call(branch7x7dbl);\n branch7x7dbl = branch7x7dbl_4.call(branch7x7dbl);\n branch7x7dbl = branch7x7dbl_5.call(branch7x7dbl);\n\n var branch_pool_ = functional.avg_pool2d(x, kernelSize: 3, stride: 1, padding: 1);\n branch_pool_ = branch_pool.call(branch_pool_);\n\n var outputs = new[] { branch1x1_, branch7x7, branch7x7dbl, branch_pool_ };\n return torch.cat(outputs, 1);\n }\n }\n\n class InceptionD : Module<Tensor, Tensor>\n {\n private readonly Module<Tensor, Tensor> branch3x3_1;\n private readonly Module<Tensor, Tensor> branch3x3_2;\n private readonly Module<Tensor, Tensor> branch7x7x3_1;\n private readonly Module<Tensor, Tensor> branch7x7x3_2;\n private readonly Module<Tensor, Tensor> branch7x7x3_3;\n private readonly Module<Tensor, Tensor> branch7x7x3_4;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n branch3x3_1.Dispose(); branch3x3_2.Dispose();\n branch7x7x3_1.Dispose(); branch7x7x3_2.Dispose();\n branch7x7x3_3.Dispose(); branch7x7x3_4.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public InceptionD(int in_channels) : base(\"InceptionD\")\n {\n branch3x3_1 = conv_block(in_channels, 192, kernel_size: 1);\n branch3x3_2 = conv_block(192, 320, kernel_size: 3, stride: 2);\n\n branch7x7x3_1 = conv_block(in_channels, 192, kernel_size: 1);\n branch7x7x3_2 = conv_block(192, 192, kernel_size: (1, 7), padding: (0, 3));\n branch7x7x3_3 = conv_block(192, 192, kernel_size: (7, 1), padding: (3, 0));\n branch7x7x3_4 = conv_block(192, 192, kernel_size: 3, stride: 2);\n\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor x)\n {\n var branch3x3 = branch3x3_1.call(x);\n branch3x3 = branch3x3_2.call(branch3x3);\n\n var branch7x7x3 = branch7x7x3_1.call(x);\n branch7x7x3 = branch7x7x3_2.call(branch7x7x3);\n branch7x7x3 = branch7x7x3_3.call(branch7x7x3);\n branch7x7x3 = branch7x7x3_4.call(branch7x7x3);\n\n var branch_pool = functional.max_pool2d(x, kernelSize: 3, stride: 2);\n var outputs = new[] { branch3x3, branch7x7x3, branch_pool };\n\n\n return torch.cat(outputs, 1);\n }\n }\n\n class InceptionE : Module<Tensor, Tensor>\n {\n private readonly Module<Tensor, Tensor> branch1x1;\n private readonly Module<Tensor, Tensor> branch3x3_1;\n private readonly Module<Tensor, Tensor> branch3x3_2a;\n private readonly Module<Tensor, Tensor> branch3x3_2b;\n private readonly Module<Tensor, Tensor> branch3x3dbl_1;\n private readonly Module<Tensor, Tensor> branch3x3dbl_2;\n private readonly Module<Tensor, Tensor> branch3x3dbl_3a;\n private readonly Module<Tensor, Tensor> branch3x3dbl_3b;\n private readonly Module<Tensor, Tensor> branch_pool;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n branch1x1.Dispose(); branch_pool.Dispose();\n branch3x3_1.Dispose(); branch3x3_2a.Dispose(); branch3x3_2b.Dispose();\n branch3x3dbl_1.Dispose(); branch3x3dbl_2.Dispose();\n branch3x3dbl_3a.Dispose(); branch3x3dbl_3b.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public InceptionE(int in_channels) : base(\"InceptionE\")\n {\n\n branch1x1 = conv_block(in_channels, 320, kernel_size: 1);\n\n branch3x3_1 = conv_block(in_channels, 384, kernel_size: 1);\n branch3x3_2a = conv_block(384, 384, kernel_size: (1, 3), padding: (0, 1));\n branch3x3_2b = conv_block(384, 384, kernel_size: (3, 1), padding: (1, 0));\n\n branch3x3dbl_1 = conv_block(in_channels, 448, kernel_size: 1);\n branch3x3dbl_2 = conv_block(448, 384, kernel_size: 3, padding: 1);\n branch3x3dbl_3a = conv_block(384, 384, kernel_size: (1, 3), padding: (0, 1));\n branch3x3dbl_3b = conv_block(384, 384, kernel_size: (3, 1), padding: (1, 0));\n\n branch_pool = conv_block(in_channels, 192, kernel_size: 1);\n\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor x)\n {\n\n var branch1x1_ = branch1x1.call(x);\n\n var branch3x3 = branch3x3_1.call(x);\n branch3x3 = torch.cat(new[] { branch3x3_2a.call(branch3x3), branch3x3_2b.call(branch3x3)}, 1);\n\n var branch3x3dbl = branch3x3dbl_1.call(x);\n branch3x3dbl = branch3x3dbl_2.call(branch3x3dbl);\n branch3x3dbl = torch.cat(new[] { branch3x3dbl_3a.call(branch3x3dbl), branch3x3dbl_3b.call(branch3x3dbl) }, 1);\n\n var branch_pool_ = functional.avg_pool2d(x, kernelSize: 3, stride: 1, padding: 1);\n branch_pool_ = branch_pool.call(branch_pool_);\n\n var outputs = new[] { branch1x1_, branch3x3, branch3x3dbl, branch_pool_ };\n\n return torch.cat(outputs, 1);\n }\n }\n\n class InceptionAux : Module<Tensor, Tensor>\n {\n private readonly Module<Tensor, Tensor> conv0;\n private readonly Module<Tensor, Tensor> conv1;\n private readonly Module<Tensor, Tensor> fc;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n conv0.Dispose();\n conv1.Dispose();\n fc.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public InceptionAux(int in_channels, int num_classes) : base(\"InceptionAux\")\n {\n\n conv0 = conv_block(in_channels, 128, kernel_size: 1);\n conv1 = conv_block(128, 768, kernel_size: 5);\n fc = nn.Linear(768, num_classes);\n\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor x)\n {\n // N x 768 x 17 x 17\n x = functional.avg_pool2d(x, kernelSize: 5, stride: 3);\n // N x 768 x 5 x 5\n x = conv0.call(x);\n // N x 128 x 5 x 5\n x = conv1.call(x);\n // N x 768 x 1 x 1\n // Adaptive average pooling\n x = functional.adaptive_avg_pool2d(x, (1, 1));\n // N x 768 x 1 x 1\n x = x.flatten(1);\n // N x 768\n x = fc.call(x);\n // N x 1000\n\n return x;\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6480686664581299, "alphanum_fraction": 0.6566523313522339, "avg_line_length": 25, "blob_id": "847f983e4f0dc6a3c4139ebef0f05929fd0052ea", "content_id": "e3e480120aea26849b9bbc5954ead108ca083602", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 235, "license_type": "permissive", "max_line_length": 131, "num_lines": 9, "path": "/src/TorchSharp/Tensor/Enums/DebugMode.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nnamespace TorchSharp\n{\n public enum DebugMode\n {\n @default = 0,\n warn = 1\n }\n}" }, { "alpha_fraction": 0.4951785206794739, "alphanum_fraction": 0.5121188163757324, "avg_line_length": 35.894229888916016, "blob_id": "74d4dace427f8ab9ef2a35a9456a34b71c531dd2", "content_id": "41f84dddf05f1d5d3cbc8f48550bce5c4e46117c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3837, "license_type": "permissive", "max_line_length": 83, "num_lines": 104, "path": "/test/TorchSharpTest/TestSaveSD.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System.Collections.Generic;\nusing TorchSharp.Modules;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\nusing Xunit;\n\n\nnamespace TorchSharp\n{\n [Collection(\"Sequential\")]\n public class TestSaveSD\n {\n private class LSTMModel : nn.Module<Tensor, Tensor>\n {\n public static int NUM_WORDS = 100;\n public static int EMBEDDING_VEC_LEN = 100;\n public static int HIDDEN_SIZE = 128;\n\n private Module<Tensor, Tensor> embedding;\n private LSTM lstm;\n private Module<Tensor, Tensor> dropout;\n private Module<Tensor, Tensor> dense;\n private Module<Tensor, Tensor> sigmoid;\n private Device _device;\n\n public LSTMModel(string name, Device device = null) : base(name)\n {\n _device = device;\n embedding = Embedding(NUM_WORDS, EMBEDDING_VEC_LEN);\n lstm = LSTM(EMBEDDING_VEC_LEN, HIDDEN_SIZE, batchFirst: true);\n dropout = Dropout(0.5);\n dense = Linear(HIDDEN_SIZE, 1);\n sigmoid = Sigmoid();\n\n RegisterComponents();\n if (device != null && device.type == DeviceType.CUDA)\n this.to(device);\n }\n\n public override Tensor forward(Tensor input)\n {\n var x_embed = embedding.call(input);\n var h0 = zeros(1, input.shape[0], HIDDEN_SIZE, device: _device);\n var c0 = zeros(1, input.shape[0], HIDDEN_SIZE, device: _device);\n var (x_rnn, _, _) = lstm.call(x_embed, (h0, c0));\n var x_rnn_last_seq = x_rnn[(null,null), -1, (null,null)];\n x_rnn_last_seq = dropout.call(x_rnn_last_seq);\n var logits = dense.call(x_rnn_last_seq);\n return sigmoid.call(logits);\n }\n }\n \n [Fact]\n public void TestSaveSDData_LSTM()\n {\n var lstm = new LSTMModel(\"lstm\", torch.CPU);\n lstm.save(\"./lstm.dat\");\n }\n \n class LeNet1Model : Module<Tensor, Tensor>\n {\n // The names of properties should be the same in C# and Python\n // in this case, we both name the Sequential as layers\n private readonly Module<Tensor, Tensor> layers;\n private Device _device;\n\n public LeNet1Model(string name, Device device = null) : base(name)\n {\n _device = device;\n\n // the names of each layer should also be the same in C# and Python\n var modules = new List<(string, Module<Tensor, Tensor>)>();\n modules.Add((\"conv-1\", Conv2d(1, 4, 5, padding: 2)));\n modules.Add((\"bnrm2d-1\", BatchNorm2d(4)));\n modules.Add((\"relu-1\", ReLU()));\n modules.Add((\"maxpool-1\", MaxPool2d(2, stride: 2)));\n modules.Add((\"conv-2\", Conv2d(4, 12, 5)));\n modules.Add((\"bnrm2d-2\", BatchNorm2d(12)));\n modules.Add((\"relu-2\", ReLU()));\n modules.Add((\"maxpool-2\", MaxPool2d(2, stride: 2)));\n modules.Add((\"flatten\", Flatten()));\n modules.Add((\"linear\", Linear(300, 10)));\n layers = Sequential(modules);\n\n RegisterComponents();\n if (device != null && device.type == TorchSharp.DeviceType.CUDA)\n this.to(device);\n }\n\n public override Tensor forward(Tensor input)\n {\n return layers.call(input);\n }\n }\n \n \n [Fact]\n public void TestSaveSDData_LeNet1()\n {\n var lenet1 = new LeNet1Model(\"lenet1\", torch.CPU);\n lenet1.save(\"./lenet1.dat\");\n }\n }\n}\n" }, { "alpha_fraction": 0.6036188006401062, "alphanum_fraction": 0.6161640286445618, "avg_line_length": 33.264461517333984, "blob_id": "9735217276e93d296990a720b55a586353b5765c", "content_id": "d04636db14a7bd3adfc21102b2fd0e4772c81b1d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4145, "license_type": "permissive", "max_line_length": 225, "num_lines": 121, "path": "/src/Native/build.sh", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\nset -e\n\nusage()\n{\n echo \"Usage: $0 --arch <Architecture> \"\n echo \"\"\n echo \"Options:\"\n echo \" --arch <Architecture> Target Architecture (x64, x86)\"\n echo \" --configuration <Configuration> Build Configuration (Debug, Release)\"\n echo \" --stripsymbols Enable symbol stripping (to external file)\"\n echo \" --libtorchpath <PathToLibtorch> Path to libtorch TorchConfig.cmake\"\n exit 1\n}\n\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n SOURCE=\"$(readlink \"$SOURCE\")\"\n [[ \"$SOURCE\" != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\nRootRepo=\"$DIR/../..\"\n\n__build_arch=\n__strip_argument=\n__libtorchpath=\n__configuration=Debug\n__rootBinPath=\"$RootRepo/bin\"\n__baseIntermediateOutputPath=\"$__rootBinPath/obj\"\n__versionSourceFile=\"$__baseIntermediateOutputPath/version.c\"\n\nwhile [ \"$1\" != \"\" ]; do\n lowerI=\"$(echo $1 | awk '{print tolower($0)}')\"\n case $lowerI in\n -h|--help)\n usage\n exit 1\n ;;\n --arch)\n shift\n __build_arch=$1\n ;;\n --configuration)\n shift\n __configuration=$1\n ;; \n --stripsymbols)\n __strip_argument=\"-DSTRIP_SYMBOLS=true\"\n ;;\n --libtorchpath)\n shift\n __libtorchpath=$1\n ;;\n *)\n echo \"Unknown argument to build.sh $1\"; usage; exit 1\n esac\n shift\ndone\n\n# Force the build to be release since libtorch is in release.\n__cmake_defines=\"-DCMAKE_BUILD_TYPE=${__configuration} ${__strip_argument} -DLIBTORCH_PATH=${__libtorchpath}\"\n\n__IntermediatesDir=\"$__baseIntermediateOutputPath/$__build_arch.$__configuration/Native\"\n__BinDir=\"$__rootBinPath/$__build_arch.$__configuration/Native\"\n\nmkdir -p \"$__BinDir\"\nmkdir -p \"$__IntermediatesDir\"\n\n# Set up the environment to be used for building with clang.\nif command -v \"clang-6.0\" > /dev/null 2>&1; then\n export CC=\"$(command -v clang-6.0)\"\n export CXX=\"$(command -v clang++-6.0)\"\nelif command -v \"clang-5.0\" > /dev/null 2>&1; then\n export CC=\"$(command -v clang-5.0)\"\n export CXX=\"$(command -v clang++-5.0)\"\nelif command -v \"clang-4.0\" > /dev/null 2>&1; then\n export CC=\"$(command -v clang-4.0)\"\n export CXX=\"$(command -v clang++-4.0)\"\nelif command -v clang > /dev/null 2>&1; then\n export CC=\"$(command -v clang)\"\n export CXX=\"$(command -v clang++)\"\nelse\n echo \"Unable to find Clang Compiler\"\n echo \"Install clang-6.0, clang-5.0, or clang-4.0\"\n exit 1\nfi\n\n# Specify path to be set for CMAKE_INSTALL_PREFIX.\n# This is where all built native libraries will copied to.\nexport __CMakeBinDir=\"$__BinDir\"\n\nif [ ! -f $__versionSourceFile ]; then\n __versionSourceLine=\"static char sccsid[] __attribute__((used)) = \\\"@(#)No version information produced\\\";\"\n echo $__versionSourceLine > $__versionSourceFile\nfi\n\nOSName=$(uname -s)\ncase $OSName in\n Darwin)\n \n # PyTorch is specifyin options that require OpenMP support but AppleClang's OpenMP support is lacking e.g. -fopenmp not supported\n # See https://github.com/oneapi-src/oneDNN/issues/591 for this potential workaround, though it may be better\n # to switch to brew clang.\n #LIBOMP=/usr/local/opt/libomp\n #__cmake_defines=${__cmake_defines} -DCMAKE_CXX_FLAGS=\"-I$LIBOMP/include\" -DCMAKE_C_FLAGS=\"-I$LIBOMP/include\" -DCMAKE_SHARED_LINKER_FLAGS=\"$LIBOMP/lib/libomp.dylib\" -DCMAKE_EXE_LINKER_FLAGS=\"$LIBOMP/lib/libomp.dylib\"\n ;;\n *)\n echo \"Unsupported OS '$OSName' detected. Downloading linux-$__PKG_ARCH tools.\"\n OS=Linux\n __PKG_RID=linux\n ;;\nesac\n\ncd \"$__IntermediatesDir\"\n\necho \"Building Machine Learning native components from $DIR to $(pwd)\"\nset -x # turn on trace\ncmake \"$DIR\" -G \"Unix Makefiles\" $__cmake_defines\nset +x # turn off trace\nmake install" }, { "alpha_fraction": 0.6977401375770569, "alphanum_fraction": 0.6977401375770569, "avg_line_length": 31.272727966308594, "blob_id": "c82e3d4873d722dd32bcd5035bdafd27ff553383", "content_id": "2fe9222715dec60edd412a86f3e12a0bb3053729", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 356, "license_type": "permissive", "max_line_length": 131, "num_lines": 11, "path": "/src/TorchSharp/Tensor/Enums/memory_format.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nnamespace TorchSharp\n{\n // https://pytorch.org/docs/stable/tensor_attributes.html#torch.memory_format\n public enum memory_format\n {\n preserve_format,\n contiguous_format,\n channels_last\n }\n}" }, { "alpha_fraction": 0.5151839256286621, "alphanum_fraction": 0.5194610953330994, "avg_line_length": 46.47208023071289, "blob_id": "db0703a130bd069424f3340637efe50df83fbc60", "content_id": "aacdc6f02ebea4086b29fcb8642fab273950d3fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9352, "license_type": "permissive", "max_line_length": 153, "num_lines": 197, "path": "/src/TorchSharp/Distributions/Distribution.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class distributions\n {\n public abstract class Distribution\n {\n public Distribution(torch.Generator generator, long[] batch_shape = null, long[] event_shape = null)\n {\n this.generator = generator;\n _init(batch_shape != null ? batch_shape : Size.Empty,\n event_shape != null ? event_shape : Size.Empty);\n }\n\n public Distribution(torch.Generator generator, Size batch_shape, Size? event_shape = null)\n {\n this.generator = generator;\n _init(batch_shape,\n event_shape != null ? event_shape : Size.Empty);\n }\n\n protected void _init(Size? batch_shape = null, Size? event_shape = null)\n {\n this.batch_shape = batch_shape != null ? batch_shape.Value : Size.Empty;\n this.event_shape = event_shape != null ? event_shape.Value : Size.Empty;\n }\n\n /// <summary>\n /// The shape over which parameters are batched.\n /// </summary>\n public Size batch_shape { get; protected set; }\n\n /// <summary>\n /// The shape of a single sample (without batching).\n /// </summary>\n public Size event_shape { get; protected set; }\n\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public abstract Tensor mean { get; }\n\n /// <summary>\n /// The mode of the distribution.\n /// </summary>\n public virtual Tensor mode { get { return new Tensor(IntPtr.Zero); } } \n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public abstract Tensor variance { get; }\n\n /// <summary>\n /// The standard deviation of the distribution\n /// </summary>\n public virtual Tensor stddev => variance.sqrt();\n\n /// <summary>\n /// Generates a sample_shape shaped sample or sample_shape shaped batch of samples if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">A list of dimension sizes</param>\n /// <returns>A tensor containing the sample.</returns>\n public virtual Tensor sample(params long[] sample_shape)\n {\n return rsample(sample_shape);\n }\n\n /// <summary>\n /// Generates a sample_shape shaped sample or sample_shape shaped batch of samples if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">A list of dimension sizes</param>\n /// <returns>A tensor containing the sample.</returns>\n public Tensor sample(Size sample_shape) => sample(sample_shape.Shape);\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n /// <returns>A tensor containing the sample.</returns>\n public abstract Tensor rsample(params long[] sample_shape);\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n /// <returns>A tensor containing the sample.</returns>\n public Tensor rsample(Size sample_shape) => rsample(sample_shape.Shape);\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n /// <returns></returns>\n public abstract Tensor log_prob(Tensor value);\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n /// <returns></returns>\n public abstract Tensor entropy();\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n /// <returns></returns>\n public abstract Distribution expand(Size batch_shape, Distribution instance = null);\n\n /// <summary>\n /// Returns the cumulative density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n /// <returns></returns>\n public virtual Tensor cdf(Tensor value)\n {\n throw new NotImplementedException(\"Distribution.cdf()\");\n }\n\n /// <summary>\n /// Returns the inverse cumulative density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n /// <returns></returns>\n public virtual Tensor icdf(Tensor value)\n {\n throw new NotImplementedException(\"Distribution.icdf()\");\n }\n\n /// <summary>\n /// Returns tensor containing all values supported by a discrete distribution. The result will enumerate over dimension 0, so the shape\n /// of the result will be `(cardinality,) + batch_shape + event_shape` (where `event_shape = ()` for univariate distributions).\n ///\n /// Note that this enumerates over all batched tensors in lock-step `[[0, 0], [1, 1], ...]`. With `expand=False`, enumeration happens\n /// along dim 0, but with the remaining batch dimensions being singleton dimensions, `[[0], [1], ..`\n /// </summary>\n /// <param name=\"expand\">Whether to expand the support over the batch dims to match the distribution's `batch_shape`.</param>\n /// <returns></returns>\n public virtual Tensor enumerate_support(bool expand = true)\n {\n throw new NotImplementedException();\n }\n\n /// <summary>\n /// Returns perplexity of distribution, batched over batch_shape.\n /// </summary>\n /// <returns></returns>\n public virtual Tensor perplexity() => torch.exp(entropy());\n\n protected long[] ExtendedShape(params long[] sample_shape)\n {\n if (batch_shape.Length == 0 && event_shape.Length == 0)\n return sample_shape;\n\n var result = new List<long>();\n if (sample_shape.Length > 0) result.AddRange(sample_shape);\n if (batch_shape.Length > 0) result.AddRange(batch_shape);\n if (event_shape.Length > 0) result.AddRange(event_shape);\n\n return result.ToArray();\n }\n\n protected Tensor LogitsToProbs(Tensor logits, bool isBinary = false)\n {\n return (isBinary) ? torch.sigmoid(logits) : torch.nn.functional.softmax(logits, dim: -1);\n }\n\n protected Tensor ProbsToLogits(Tensor probs, bool isBinary = false)\n {\n probs = ClampProbs(probs);\n return (isBinary) ? (torch.log(probs) - torch.log1p(-probs)) : torch.log(probs);\n }\n\n protected Tensor ClampProbs(Tensor probs)\n {\n var eps = torch.finfo(probs.dtype).eps;\n return probs.clamp(eps, 1 - eps);\n }\n\n protected Tensor ClampByZero(Tensor x) => (x.clamp_min(0) + x - x.clamp_max(0)) / 2;\n\n protected torch.Generator generator;\n\n protected const double euler_constant = 0.57721566490153286060; // Euler Mascheroni Constant\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6988155841827393, "alphanum_fraction": 0.7021996378898621, "avg_line_length": 23.58333396911621, "blob_id": "ab775b7454db8fd3e3c4ccd6ce55113048cee370", "content_id": "c966e0e97d088b78ba78a82173a8638a25ae45e7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 591, "license_type": "permissive", "max_line_length": 132, "num_lines": 24, "path": "/src/Native/LibTorchSharp/THSStorage.cpp", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "//// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#include \"THSStorage.h\"\n\nint64_t THSTensor_storage_offset(const Tensor tensor)\n{\n return tensor->storage_offset();\n}\n\nsize_t THSStorage_nbytes(const Tensor tensor)\n{\n return tensor->storage().nbytes();\n}\n\nvoid THSStorage_set_nbytes(const Tensor tensor, size_t nbytes)\n{\n tensor->storage().set_nbytes(nbytes);\n}\n\nvoid* THSStorage_data_ptr(const Tensor tensor)\n{\n auto &st = tensor->storage();\n auto &dp = st.data_ptr();\n return dp.get();\n}\n\n" }, { "alpha_fraction": 0.4516339898109436, "alphanum_fraction": 0.4516339898109436, "avg_line_length": 31.5744686126709, "blob_id": "c20e7b19f88ea78896e72fec44bc46b4a376b5fc", "content_id": "84c4997a12274577d9d7433662599e60011d3e20", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1530, "license_type": "permissive", "max_line_length": 130, "num_lines": 47, "path": "/src/TorchSharp/Dataset.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class utils\n {\n public static partial class data\n {\n public abstract class Dataset : Dataset<Dictionary<string, torch.Tensor>>\n {\n }\n\n /// <summary>\n /// Interface for Dataloader\n /// </summary>\n public abstract class Dataset<T> : IDisposable\n {\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n /// <summary>\n /// Size of dataset\n /// </summary>\n public abstract long Count { get; }\n\n /// <summary>\n /// Get tensor according to index\n /// </summary>\n /// <param name=\"index\">Index for tensor</param>\n /// <returns>Tensors of index. DataLoader will catenate these tensors.</returns>\n public abstract T GetTensor(long index);\n\n protected virtual void Dispose(bool disposing)\n {\n }\n }\n }\n }\n }\n}" }, { "alpha_fraction": 0.44726622104644775, "alphanum_fraction": 0.4784882068634033, "avg_line_length": 38.37647247314453, "blob_id": "0556093ea13715edeb080837a845a1e71eacef61", "content_id": "cbc74acf4c3e159cf74bbe5c1dcdac0c97f441b4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6694, "license_type": "permissive", "max_line_length": 134, "num_lines": 170, "path": "/src/TorchVision/Ops/Utils.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchvision,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/vision/blob/a4f53308b2d0f1aa9191686e326f45c26053f686/torchvision/ops/utils.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/vision/blob/main/LICENSE\n\n\nusing System;\nusing System.Collections.Generic;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class ops\n {\n internal static Tensor _upcast(Tensor t)\n {\n switch (t.dtype) {\n case ScalarType.BFloat16:\n case ScalarType.Float16:\n return t.@float();\n case ScalarType.Bool:\n case ScalarType.Byte:\n case ScalarType.Int8:\n case ScalarType.Int16:\n return t.@int();\n }\n return t.alias();\n }\n\n internal static Tensor _upcast_non_float(Tensor t) => (!t.is_floating_point() ? t.@float() : t.alias());\n\n internal static (Tensor, Tensor, Tensor, Tensor) unwrap4(Tensor[] t)\n {\n if (t.Length != 4) throw new ArgumentException(\"Not the right length\");\n return (t[0], t[1], t[2], t[3]);\n }\n\n internal static (Tensor, Tensor) _loss_inter_union(Tensor boxes1, Tensor boxes2)\n {\n var (x1, y1, x2, y2) = unwrap4(boxes1.unbind(dimension: -1));\n var (x1g, y1g, x2g, y2g) = unwrap4(boxes2.unbind(dimension: -1));\n\n // Intersection keypoints\n var xkis1 = max(x1, x1g);\n var ykis1 = max(y1, y1g);\n var xkis2 = min(x2, x2g);\n var ykis2 = min(y2, y2g);\n\n var intsctk = zeros_like(x1);\n var mask = (ykis2 > ykis1) & (xkis2 > xkis1);\n intsctk[mask] = (xkis2[mask] - xkis1[mask]) * (ykis2[mask] - ykis1[mask]);\n var unionk = (x2 - x1) * (y2 - y1) + (x2g - x1g) * (y2g - y1g) - intsctk;\n\n return (intsctk, unionk);\n }\n\n\n internal static (Tensor, Tensor) _diou_iou_loss(Tensor boxes1, Tensor boxes2, double eps = 1e-7)\n {\n var (intsct, union) = _loss_inter_union(boxes1, boxes2);\n var iou = intsct / (union + eps);\n // smallest enclosing box\n var (x1, y1, x2, y2) = unwrap4(boxes1.unbind(dimension: -1));\n var (x1g, y1g, x2g, y2g) = unwrap4(boxes2.unbind(dimension: -1));\n\n var xc1 = min(x1, x1g);\n var yc1 = min(y1, y1g);\n var xc2 = max(x2, x2g);\n var yc2 = max(y2, y2g);\n\n var diagonal_distance_squared = (xc2 - xc1).pow(2) + (yc2 - yc1).pow(2) + eps;\n // centers of boxes\n var x_p = (x2 + x1) / 2;\n var y_p = (y2 + y1) / 2;\n var x_g = (x1g + x2g) / 2;\n var y_g = (y1g + y2g) / 2;\n\n // The distance between boxes' centers squared.\n var centers_distance_squared = (x_p - x_g).pow(2) + (y_p - y_g).pow(2);\n // The distance IoU is the IoU penalized by a normalized\n // distance between boxes' centers squared.\n var loss = 1 - iou + (centers_distance_squared / diagonal_distance_squared);\n return (loss, iou);\n }\n\n internal static Tensor _cat(IList<Tensor> tensors, int dim = 0)\n {\n if (tensors.Count == 1)\n return tensors[0];\n return cat(tensors, dim);\n }\n\n internal static Tensor convert_boxes_to_roi_format(IList<Tensor> boxes)\n {\n var concat_boxes = _cat(boxes);\n var temp = new List<Tensor>();\n var idx_1 = TensorIndex.Ellipsis;\n var idx_2 = TensorIndex.Slice(stop: 1);\n for (var i = 0; i < boxes.Count; i++) {\n var b = boxes[i];\n temp.Add(full_like(b[idx_1, idx_2], i));\n }\n var ids = _cat(temp, dim: 0);\n var rois = cat(new Tensor[] { ids, concat_boxes }, dim: 1);\n return rois;\n }\n\n internal static void check_roi_boxes_shape(Tensor boxes)\n {\n if (boxes.size(1) != 5)\n throw new ArgumentException(\"The boxes tensor shape is not correct as Tensor[K, 5]\");\n }\n\n internal static void check_roi_boxes_shape(IList<Tensor> boxes)\n {\n foreach (var _tensor in boxes) {\n if (_tensor.size(1) != 4)\n throw new ArgumentException(\"The shape of the tensor in the boxes list is not correct as List[Tensor[L, 4]]\");\n }\n }\n\n internal static Tensor _box_cxcywh_to_xyxy(Tensor boxes)\n {\n var (cx, cy, w, h) = unwrap4(boxes.unbind(dimension: -1));\n var x1 = cx - 0.5 * w;\n var y1 = cy - 0.5 * h;\n var x2 = cx + 0.5 * w;\n var y2 = cy + 0.5 * h;\n boxes = torch.stack(new[] { x1, y1, x2, y2 }, dim: -1);\n return boxes;\n }\n\n internal static Tensor _box_xyxy_to_cxcywh(Tensor boxes)\n {\n var (x1, y1, x2, y2) = unwrap4(boxes.unbind(dimension: -1));\n var cx = (x1 + x2) / 2;\n var cy = (y1 + y2) / 2;\n var w = x2 - x1;\n var h = y2 - y1;\n\n boxes = torch.stack(new[] { cx, cy, w, h }, dim: -1);\n return boxes;\n }\n\n internal static Tensor _box_xywh_to_xyxy(Tensor boxes)\n {\n var (x, y, w, h) = unwrap4(boxes.unbind(dimension: -1));\n boxes = torch.stack(new[] { x, y, x + w, y + h }, dim: -1);\n return boxes;\n }\n\n internal static Tensor _box_xyxy_to_xywh(Tensor boxes)\n {\n var (x1, y1, x2, y2) = unwrap4(boxes.unbind(dimension: -1));\n var w = x2 - x1;\n var h = y2 - y1;\n boxes = torch.stack(new[] { x1, y1, w, h }, dim: -1);\n return boxes;\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.48641976714134216, "alphanum_fraction": 0.48641976714134216, "avg_line_length": 26, "blob_id": "5e618dc8a7e6d5fa3cbcd78fa3200d73eaf386e8", "content_id": "489f6e04a3b7364f535905dee51f8d4aace22b6a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 810, "license_type": "permissive", "max_line_length": 130, "num_lines": 30, "path": "/src/TorchAudio/BackendUtils.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n public static partial class backend\n {\n public static partial class utils\n {\n internal static AudioBackend _backend;\n\n static utils()\n {\n _backend = new NoBackend();\n }\n\n public static void set_audio_backend(AudioBackend backend)\n {\n _backend = backend;\n }\n\n public static AudioBackend get_audio_backend()\n {\n return _backend;\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5483773350715637, "alphanum_fraction": 0.5784046053886414, "avg_line_length": 39.703704833984375, "blob_id": "204c5fce8a4065bfc2f4bcf15fb49d1829ddd56a", "content_id": "5d551415d306b6d9561b0a7ed5945a6003a2f169", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3297, "license_type": "permissive", "max_line_length": 151, "num_lines": 81, "path": "/src/Examples/MobileNet.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\n\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\n\nnamespace TorchSharp.Examples\n{\n /// <summary>\n /// Modified version of MobileNet to classify CIFAR10 32x32 images.\n /// </summary>\n /// <remarks>\n /// With an unaugmented CIFAR-10 data set, the author of this saw training converge\n /// at roughly 75% accuracy on the test set, over the course of 1500 epochs.\n /// </remarks>\n class MobileNet : Module<Tensor, Tensor>\n {\n // The code here is is loosely based on https://github.com/kuangliu/pytorch-cifar/blob/master/models/mobilenet.py\n // Licence and copypright notice at: https://github.com/kuangliu/pytorch-cifar/blob/master/LICENSE\n\n private readonly long[] planes = new long[] { 64, 128, 128, 256, 256, 512, 512, 512, 512, 512, 512, 1024, 1024 };\n private readonly long[] strides = new long[] { 1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1 };\n\n private readonly Module<Tensor, Tensor> layers;\n\n public MobileNet(string name, int numClasses, Device device = null) : base(name)\n {\n if (planes.Length != strides.Length) throw new ArgumentException(\"'planes' and 'strides' must have the same length.\");\n\n var modules = new List<(string, Module<Tensor, Tensor>)>();\n\n modules.Add(($\"conv2d-first\", Conv2d(3, 32, kernelSize: 3, stride: 1, padding: 1, bias: false)));\n modules.Add(($\"bnrm2d-first\", BatchNorm2d(32)));\n modules.Add(($\"relu-first\", ReLU()));\n MakeLayers(modules, 32);\n modules.Add((\"avgpool\", AvgPool2d(new long[] { 2, 2 })));\n modules.Add((\"flatten\", Flatten()));\n modules.Add(($\"linear\", Linear(planes[planes.Length - 1], numClasses)));\n\n layers = Sequential(modules);\n\n RegisterComponents();\n\n if (device != null && device.type == DeviceType.CUDA)\n this.to(device);\n }\n\n private void MakeLayers(List<(string, Module<Tensor, Tensor>)> modules, long in_planes)\n {\n\n for (var i = 0; i < strides.Length; i++) {\n var out_planes = planes[i];\n var stride = strides[i];\n\n modules.Add(($\"conv2d-{i}a\", Conv2d(in_planes, in_planes, kernelSize: 3, stride: stride, padding: 1, groups: in_planes, bias: false)));\n modules.Add(($\"bnrm2d-{i}a\", BatchNorm2d(in_planes)));\n modules.Add(($\"relu-{i}a\", ReLU()));\n modules.Add(($\"conv2d-{i}b\", Conv2d(in_planes, out_planes, kernelSize: 1L, stride: 1L, padding: 0L, bias: false)));\n modules.Add(($\"bnrm2d-{i}b\", BatchNorm2d(out_planes)));\n modules.Add(($\"relu-{i}b\", ReLU()));\n\n in_planes = out_planes;\n }\n }\n\n public override Tensor forward(Tensor input)\n {\n return layers.forward(input);\n }\n\n protected override void Dispose(bool disposing)\n {\n if(disposing) {\n layers.Dispose();\n ClearModules();\n }\n base.Dispose(disposing);\n }\n }\n}\n" }, { "alpha_fraction": 0.5681625604629517, "alphanum_fraction": 0.5726785063743591, "avg_line_length": 56.60975646972656, "blob_id": "9cf4375fcc30905261f66fdfcd00028e21639803", "content_id": "d69ff96de62f04a4818a2d6131b01dcfcd6211f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7090, "license_type": "permissive", "max_line_length": 240, "num_lines": 123, "path": "/src/TorchSharp/NN/Transformer.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using System.Runtime.InteropServices;\n using Modules;\n\n namespace Modules\n {\n public sealed class Transformer : torch.nn.Module<Tensor, Tensor, Tensor>\n {\n internal Transformer(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n /// <summary>\n /// Take in and process masked source/target sequences.\n /// </summary>\n /// <param name=\"src\">The sequence to the encoder (required).</param>\n /// <param name=\"tgt\">The sequence to the decoder (required).</param>\n /// <param name=\"src_mask\">The additive mask for the src sequence (optional).</param>\n /// <param name=\"tgt_mask\">The additive mask for the tgt sequence (optional).</param>\n /// <param name=\"memory_mask\">The additive mask for the encoder output (optional).</param>\n /// <param name=\"src_key_padding_mask\">The ByteTensor mask for src keys per batch (optional).</param>\n /// <param name=\"tgt_key_padding_mask\">The ByteTensor mask for tgt keys per batch (optional).</param>\n /// <param name=\"memory_key_padding_mask\">The ByteTensor mask for memory keys per batch (optional).</param>\n /// <returns></returns>\n public Tensor call(Tensor src, Tensor tgt, Tensor src_mask, Tensor? tgt_mask = null, Tensor? memory_mask = null, Tensor? src_key_padding_mask = null, Tensor? tgt_key_padding_mask = null, Tensor? memory_key_padding_mask = null)\n {\n var res = THSNN_Transformer_forward(handle,\n src.Handle,\n tgt.Handle,\n src_mask?.Handle ?? IntPtr.Zero,\n tgt_mask?.Handle ?? IntPtr.Zero,\n memory_mask?.Handle ?? IntPtr.Zero,\n src_key_padding_mask?.Handle ?? IntPtr.Zero,\n tgt_key_padding_mask?.Handle ?? IntPtr.Zero,\n memory_key_padding_mask?.Handle ?? IntPtr.Zero);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Take in and process masked source/target sequences.\n /// </summary>\n /// <param name=\"src\">The sequence to the encoder (required).</param>\n /// <param name=\"tgt\">The sequence to the decoder (required).</param>\n public override Tensor forward(Tensor src, Tensor tgt)\n {\n var res = THSNN_Transformer_forward(handle,\n src.Handle,\n tgt.Handle,\n IntPtr.Zero,\n IntPtr.Zero,\n IntPtr.Zero,\n IntPtr.Zero,\n IntPtr.Zero,\n IntPtr.Zero);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n public enum Activations\n {\n ReLU = 0,\n GELU = 1\n }\n\n /// <summary>\n /// A transformer model. User is able to modify the attributes as needed. The architecture is based on the paper “Attention Is All You Need”.\n /// </summary>\n /// <param name=\"d_model\">The number of expected features in the encoder/decoder inputs (default=512).</param>\n /// <param name=\"nhead\">The number of heads in the multiheadattention models (default=8).</param>\n /// <param name=\"num_encoder_layers\">The number of sub-encoder-layers in the encoder (default=6).</param>\n /// <param name=\"num_decoder_layers\">The number of sub-decoder-layers in the decoder (default=6).</param>\n /// <param name=\"dim_feedforward\">The dimension of the feedforward network model (default=2048).</param>\n /// <param name=\"dropout\">The dropout value (default=0.1).</param>\n /// <param name=\"activation\">The activation function of encoder/decoder intermediate layer, relu or gelu (default=relu).</param>\n /// <returns></returns>\n public static Transformer Transformer(long d_model = 512, long nhead = 8, long num_encoder_layers = 6, long num_decoder_layers = 6, long dim_feedforward = 2048, double dropout = 0.1, Activations activation = nn.Activations.ReLU)\n {\n var res = THSNN_Transformer_ctor(d_model, nhead, num_encoder_layers, num_decoder_layers, dim_feedforward, dropout, (long)activation, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Transformer(res, boxedHandle);\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Computes scaled dot product attention on query, key and value tensors, using an optional attention mask if passed, and applying dropout if a probability greater than 0.0 is specified.\n /// </summary>\n /// <param name=\"query\">Query tensor, shaped (N, ..., L, E)</param>\n /// <param name=\"key\">Key tensor, shaped (N, ..., S, E)</param>\n /// <param name=\"value\">Value tensor, shaped (N, ..., S, Ev)</param>\n /// <param name=\"attn_mask\">\n /// Attention mask, shaped (N, ..., L, S).\n /// Two types of masks are supported:\n /// A boolean mask where a value of True indicates that the element should take part in attention.\n /// A float mask of the same type as query, key, value that is added to the attention score.\n /// </param>\n /// <param name=\"p\">Dropout probability</param>\n /// <param name=\"is_casual\">If true, assumes causal attention masking and errors if both attn_mask and is_causal are set.</param>\n /// <returns></returns>\n public static Tensor scaled_dot_product_attention(Tensor query, Tensor key, Tensor value, Tensor? attn_mask = null, double p = 0.0, [MarshalAs(UnmanagedType.U1)] bool is_casual = false)\n {\n if (p < 0) throw new ArgumentException(\"Dropout probability must be greater than or equal to zero.\");\n if (is_casual && attn_mask is not null) throw new ArgumentException(\"Casual attention masking cannot pass a mask.\");\n var res = THSNN_scaled_dot_product_attention(query.Handle, key.Handle, value.Handle, attn_mask is null ? IntPtr.Zero : attn_mask.Handle, p, is_casual);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5679244995117188, "alphanum_fraction": 0.5679244995117188, "avg_line_length": 27.675676345825195, "blob_id": "8b43c3b4da4d2ec476a327f8faf9a0e810793b4a", "content_id": "a106064df77514dc888aecfa057f11150b1f6508", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1060, "license_type": "permissive", "max_line_length": 130, "num_lines": 37, "path": "/src/TorchVision/Solarize.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class Solarize : ITransform\n {\n internal Solarize(double threshold)\n {\n this.threshold = threshold;\n }\n\n public Tensor call(Tensor input)\n {\n return transforms.functional.solarize(input, threshold);\n }\n\n private double threshold;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Solarize the image by inverting all pixel values above a threshold.\n /// </summary>\n /// <param name=\"threshold\">All pixels equal or above this value are inverted.</param>\n static public ITransform Solarize(double threshold)\n {\n return new Solarize(threshold);\n }\n }\n }\n}" }, { "alpha_fraction": 0.6311787366867065, "alphanum_fraction": 0.6425855755805969, "avg_line_length": 25.399999618530273, "blob_id": "f9759eeff22e157cef190ed3566126bfd3dffbd0", "content_id": "c6707d8f83b6dd3cd0631cdc02af30edd3da3e32", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 265, "license_type": "permissive", "max_line_length": 131, "num_lines": 10, "path": "/src/TorchSharp/Tensor/Enums/PrintOptionsProfile.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nnamespace TorchSharp\n{\n public enum PrintOptionsProfile\n {\n @default = 0,\n @short = 1,\n full = 2\n }\n}" }, { "alpha_fraction": 0.4884297549724579, "alphanum_fraction": 0.5034238696098328, "avg_line_length": 41.349998474121094, "blob_id": "db0f258d5c48f7757d3c0a06eff29cbc5f20e171", "content_id": "a01824120b72a56d733887ca19434e6b6d29031d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8470, "license_type": "permissive", "max_line_length": 134, "num_lines": 200, "path": "/src/TorchVision/Ops/Losses.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Drawing;\nusing System.Text;\nusing System.Threading.Tasks;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn.functional;\nusing static TorchSharp.torchvision;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class ops\n {\n // Ported from https://github.com/pytorch/vision/blob/main/torchvision/ops/focal_loss.py\n\n /// <summary>\n /// Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.\n /// </summary>\n /// <param name=\"inputs\">A float tensor of arbitrary shape. The predictions for each example. </param>\n /// <param name=\"targets\">A float tensor with the same shape as inputs.\n /// Stores the binary classification label for each element in inputs\n /// (0 for the negative class and 1 for the positive class).\n /// </param>\n /// <param name=\"alpha\">Weighting factor in range (0,1) to balance positive vs negative examples or -1 for ignore.</param>\n /// <param name=\"gamma\">Exponent of the modulating factor (1 - p_t) to balance easy vs hard examples.</param>\n /// <param name=\"reduction\">The kind of reduction to apply to the result.</param>\n /// <returns></returns>\n public static Tensor sigmoid_focal_loss(\n Tensor inputs,\n Tensor targets,\n double alpha = 0.25, double gamma = 2.0,\n nn.Reduction reduction = nn.Reduction.None)\n {\n var p = torch.sigmoid(inputs);\n var ce_loss = binary_cross_entropy_with_logits(inputs, targets, reduction: nn.Reduction.None);\n var p_t = p * targets + (1 - p) * (1 - targets);\n var loss = ce_loss * (1 - p_t).pow(gamma);\n\n if (alpha >= 0) {\n var alpha_t = alpha * targets + (1 - alpha) * (1 - targets);\n loss = alpha_t * loss;\n }\n\n switch (reduction) {\n case nn.Reduction.None:\n break;\n case nn.Reduction.Mean:\n loss = loss.mean();\n break;\n case nn.Reduction.Sum:\n loss = loss.sum();\n break;\n }\n\n return loss;\n }\n\n /// <summary>\n /// Gradient-friendly IoU loss with an additional penalty that is non-zero when the\n /// boxes do not overlap.This loss function considers important geometrical\n /// factors such as overlap area, normalized central point distance and aspect ratio.\n /// This loss is symmetric, so the boxes1 and boxes2 arguments are interchangeable.\n /// </summary>\n /// <param name=\"boxes1\">(Tensor[N, 4] or Tensor[4]) first set of boxes</param>\n /// <param name=\"boxes2\">(Tensor[N, 4] or Tensor[4]) second set of boxes</param>\n /// <param name=\"reduction\">The kind of reduction to apply to the result.</param>\n /// <param name=\"eps\">Small number to prevent division by zero.</param>\n public static Tensor complete_box_iou_loss(\n Tensor boxes1,\n Tensor boxes2,\n nn.Reduction reduction = nn.Reduction.None,\n double eps = 1e-7)\n {\n boxes1 = _upcast_non_float(boxes1);\n boxes2 = _upcast_non_float(boxes2);\n\n var (diou_loss, iou) = _diou_iou_loss(boxes1, boxes2);\n\n var xy = boxes1.unbind(dimension: -1);\n var xyg = boxes2.unbind(dimension: -1);\n\n // width and height of boxes\n var w_pred = xy[2] - xy[0];\n var h_pred = xy[3] - xy[1];\n var w_gt = xyg[2] - xyg[0];\n var h_gt = xyg[3] - xyg[1];\n\n var v = (4 / Math.Pow(Math.PI, 2)) * torch.pow((torch.atan(w_gt / h_gt) - torch.atan(w_pred / h_pred)), 2);\n\n Tensor alpha = null;\n\n using (var _ = torch.no_grad()) {\n alpha = v / (1 - iou + v + eps);\n }\n\n var loss = diou_loss + alpha * v;\n\n switch (reduction) {\n case nn.Reduction.None:\n break;\n case nn.Reduction.Mean:\n loss = loss.mean();\n break;\n case nn.Reduction.Sum:\n loss = loss.sum();\n break;\n }\n\n return loss;\n }\n\n /// <summary>\n /// Gradient-friendly IoU loss with an additional penalty that is non-zero when the\n /// distance between boxes' centers isn't zero.Indeed, for two exactly overlapping\n /// boxes, the distance IoU is the same as the IoU loss.\n /// This loss is symmetric, so the boxes1 and boxes2 arguments are interchangeable.\n /// </summary>\n /// <param name=\"boxes1\">(Tensor[N, 4] or Tensor[4]) first set of boxes</param>\n /// <param name=\"boxes2\">(Tensor[N, 4] or Tensor[4]) second set of boxes</param>\n /// <param name=\"reduction\">The kind of reduction to apply to the result.</param>\n /// <param name=\"eps\">Small number to prevent division by zero.</param>\n public static Tensor distance_box_iou_loss(\n Tensor boxes1,\n Tensor boxes2,\n nn.Reduction reduction = nn.Reduction.None,\n double eps = 1e-7)\n {\n boxes1 = _upcast_non_float(boxes1);\n boxes2 = _upcast_non_float(boxes2);\n\n var (loss, _) = _diou_iou_loss(boxes1, boxes2);\n\n switch (reduction) {\n case nn.Reduction.None:\n break;\n case nn.Reduction.Mean:\n loss = loss.mean();\n break;\n case nn.Reduction.Sum:\n loss = loss.sum();\n break;\n }\n\n return loss;\n }\n\n /// <summary>\n /// Gradient-friendly IoU loss with an additional penalty that is non-zero when the\n /// boxes do not overlap and scales with the size of their smallest enclosing box.\n /// This loss is symmetric, so the boxes1 and boxes2 arguments are interchangeable.\n /// </summary>\n /// <param name=\"boxes1\">(Tensor[N, 4] or Tensor[4]) first set of boxes</param>\n /// <param name=\"boxes2\">(Tensor[N, 4] or Tensor[4]) second set of boxes</param>\n /// <param name=\"reduction\">The kind of reduction to apply to the result.</param>\n /// <param name=\"eps\">Small number to prevent division by zero.</param>\n public static Tensor generalized_box_iou_loss(\n Tensor boxes1,\n Tensor boxes2,\n nn.Reduction reduction = nn.Reduction.None,\n double eps = 1e-7)\n {\n boxes1 = _upcast_non_float(boxes1);\n boxes2 = _upcast_non_float(boxes2);\n\n var (intsctk, unionk) = _loss_inter_union(boxes1, boxes2);\n var iouk = intsctk / (unionk + eps);\n\n var (x1, y1, x2, y2) = unwrap4(boxes1.unbind(dimension: -1));\n var (x1g, y1g, x2g, y2g) = unwrap4(boxes2.unbind(dimension: -1));\n\n // smallest enclosing box\n\n var xc1 = torch.min(x1, x1g);\n var yc1 = torch.min(y1, y1g);\n var xc2 = torch.max(x2, x2g);\n var yc2 = torch.max(y2, y2g);\n\n var area_c = (xc2 - xc1) * (yc2 - yc1);\n var miouk = iouk - ((area_c - unionk) / (area_c + eps));\n\n var loss = 1 - miouk;\n\n switch (reduction) {\n case nn.Reduction.None:\n break;\n case nn.Reduction.Mean:\n loss = loss.mean();\n break;\n case nn.Reduction.Sum:\n loss = loss.sum();\n break;\n }\n\n return loss;\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5421236753463745, "alphanum_fraction": 0.543523907661438, "avg_line_length": 43.404144287109375, "blob_id": "f5300b88f4ee7c621bea8996b591f75d2d1d0420", "content_id": "e607e9069d624100dc6a46ec7c0d0db872aa6376", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8570, "license_type": "permissive", "max_line_length": 149, "num_lines": 193, "path": "/src/TorchSharp/Distributions/OneHotCategorical.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// A Bernoulli distribution parameterized by `probs` or `logits` (but not both).\n /// </summary>\n public class OneHotCategorical : torch.distributions.Distribution\n {\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public override Tensor mean => _categorical._probs;\n\n /// <summary>\n /// The mode of the distribution.\n /// </summary>\n public override Tensor mode {\n get {\n var probs = _categorical.probs;\n var mode = probs.argmax(-1);\n return torch.nn.functional.one_hot(mode, num_classes: probs.shape[probs.ndim - 1]).to(probs);\n }\n }\n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public override Tensor variance => probs * (1 - _categorical.probs);\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"p\"></param>\n /// <param name=\"l\"></param>\n /// <param name=\"generator\"></param>\n public OneHotCategorical(Tensor p = null, Tensor l = null, torch.Generator generator = null) : base(generator)\n {\n _categorical = new Categorical(p, l, generator);\n\n if ((p is null && logits is null) || (p is not null && l is not null))\n throw new ArgumentException(\"One and only one of 'probs' and logits should be provided.\");\n\n this.batch_shape = p is null ? l.size() : p.size();\n this._probs = p?.alias().DetachFromDisposeScope();\n this._logits = l?.alias().DetachFromDisposeScope();\n }\n\n /// <summary>\n /// The probability of sampling 1\n /// </summary>\n public Tensor probs {\n get {\n return _probs ?? LogitsToProbs(_logits, true);\n }\n }\n\n /// <summary>\n /// The log-odds of sampling 1\n /// </summary>\n public Tensor logits {\n get {\n return _logits ?? ProbsToLogits(_probs);\n }\n }\n\n private Categorical _categorical;\n private Tensor _probs;\n private Tensor _logits;\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n /// <returns></returns>\n public override Tensor rsample(params long[] sample_shape)\n {\n var probs = _categorical.probs;\n var num_events = _categorical.num_events;\n var indices = _categorical.sample(sample_shape);\n return torch.nn.functional.one_hot(indices, num_events).to(probs);\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n /// <returns></returns>\n\n public override Tensor log_prob(Tensor value)\n {\n using var _ = torch.NewDisposeScope();\n var indices = value.max(-1).indexes;\n return _categorical.log_prob(indices).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n public override Tensor entropy()\n {\n return _categorical.entropy();\n }\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n /// <returns></returns>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is Bernoulli))\n throw new ArgumentException(\"expand(): 'instance' must be a Bernoulli distribution\");\n\n var p = _probs?.expand(batch_shape);\n var l = _logits?.expand(batch_shape);\n\n var newDistribution = ((instance == null) ? new OneHotCategorical(p, l, generator) : instance) as OneHotCategorical;\n\n newDistribution.batch_shape = batch_shape;\n if (newDistribution == instance) {\n newDistribution._probs = p;\n newDistribution._logits = l;\n newDistribution._categorical = _categorical.expand(batch_shape) as Categorical;\n }\n return newDistribution;\n }\n }\n\n }\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a Bernoulli distribution parameterized by `probs` or `logits` (but not both).\n /// </summary>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static OneHotCategorical OneHotCategorical(Tensor probs = null, Tensor logits = null, torch.Generator generator = null)\n {\n return new OneHotCategorical(probs, logits, generator);\n }\n\n /// <summary>\n /// Creates a Bernoulli distribution parameterized by `probs` or `logits` (but not both).\n /// </summary>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static OneHotCategorical OneHotCategorical(float? probs, float? logits, torch.Generator generator = null)\n {\n if (probs.HasValue && !logits.HasValue)\n return new OneHotCategorical(torch.tensor(probs.Value), null, generator);\n else if (!probs.HasValue && logits.HasValue)\n return new OneHotCategorical(null, torch.tensor(logits.Value), generator);\n else\n throw new ArgumentException(\"One and only one of 'probs' and logits should be provided.\");\n }\n\n\n /// <summary>\n /// Creates a Bernoulli distribution parameterized by `probs` or `logits` (but not both).\n /// </summary>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static OneHotCategorical OneHotCategorical(double? probs, double? logits, torch.Generator generator = null)\n {\n if (probs.HasValue && !logits.HasValue)\n return new OneHotCategorical(torch.tensor(probs.Value), null, generator);\n else if (!probs.HasValue && logits.HasValue)\n return new OneHotCategorical(null, torch.tensor(logits.Value), generator);\n else\n throw new ArgumentException(\"One and only one of 'probs' and 'logits' should be non-null\");\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.7004733681678772, "alphanum_fraction": 0.7033941149711609, "avg_line_length": 47.19902801513672, "blob_id": "834d40b704c6e3a33bdc762e29ce1bcc4823262f", "content_id": "394898ec8c659b5d1cc5dc707c5c5f06eb4c7963", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9929, "license_type": "permissive", "max_line_length": 130, "num_lines": 206, "path": "/src/TorchSharp/PInvoke/LibTorchSharp.THSSpecial.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp.PInvoke\n{\n internal static partial class NativeMethods\n {\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_airy_ai(IntPtr tensor);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_airy_ai_out(IntPtr tensor, IntPtr _out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_bessel_j0(IntPtr tensor);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_bessel_j0_out(IntPtr tensor, IntPtr _out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_bessel_j1(IntPtr tensor);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_bessel_j1_out(IntPtr tensor, IntPtr _out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_bessel_y0(IntPtr tensor);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_bessel_y0_out(IntPtr tensor, IntPtr _out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_bessel_y1(IntPtr tensor);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_bessel_y1_out(IntPtr tensor, IntPtr _out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_modified_bessel_i0(IntPtr tensor);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_modified_bessel_i0_out(IntPtr tensor, IntPtr _out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_modified_bessel_i1(IntPtr tensor);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_modified_bessel_i1_out(IntPtr tensor, IntPtr _out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_modified_bessel_k0(IntPtr tensor);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_modified_bessel_k0_out(IntPtr tensor, IntPtr _out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_modified_bessel_k1(IntPtr tensor);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_modified_bessel_k1_out(IntPtr tensor, IntPtr _out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_scaled_modified_bessel_k0(IntPtr tensor);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_scaled_modified_bessel_k0_out(IntPtr tensor, IntPtr _out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_scaled_modified_bessel_k1(IntPtr tensor);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_scaled_modified_bessel_k1_out(IntPtr tensor, IntPtr _out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_spherical_bessel_j0(IntPtr tensor);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_spherical_bessel_j0_out(IntPtr tensor, IntPtr _out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_chebyshev_polynomial_t(IntPtr x, IntPtr n);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_chebyshev_polynomial_t_out(IntPtr x, IntPtr n, IntPtr @out);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_chebyshev_polynomial_u(IntPtr x, IntPtr n);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_chebyshev_polynomial_u_out(IntPtr x, IntPtr n, IntPtr @out);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_chebyshev_polynomial_v(IntPtr x, IntPtr n);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_chebyshev_polynomial_v_out(IntPtr x, IntPtr n, IntPtr @out);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_chebyshev_polynomial_w(IntPtr x, IntPtr n);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_chebyshev_polynomial_w_out(IntPtr x, IntPtr n, IntPtr @out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_shifted_chebyshev_polynomial_t(IntPtr x, IntPtr n);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_shifted_chebyshev_polynomial_t_out(IntPtr x, IntPtr n, IntPtr @out);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_shifted_chebyshev_polynomial_u(IntPtr x, IntPtr n);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_shifted_chebyshev_polynomial_u_out(IntPtr x, IntPtr n, IntPtr @out);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_shifted_chebyshev_polynomial_v(IntPtr x, IntPtr n);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_shifted_chebyshev_polynomial_v_out(IntPtr x, IntPtr n, IntPtr @out);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_shifted_chebyshev_polynomial_w(IntPtr x, IntPtr n);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_shifted_chebyshev_polynomial_w_out(IntPtr x, IntPtr n, IntPtr @out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_hermite_polynomial_h(IntPtr x, IntPtr n);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_hermite_polynomial_h_out(IntPtr x, IntPtr n, IntPtr @out);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_hermite_polynomial_he(IntPtr x, IntPtr n);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_hermite_polynomial_he_out(IntPtr x, IntPtr n, IntPtr @out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_laguerre_polynomial_l(IntPtr x, IntPtr n);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_laguerre_polynomial_l_out(IntPtr x, IntPtr n, IntPtr @out);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_legendre_polynomial_p(IntPtr x, IntPtr n);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_legendre_polynomial_p_out(IntPtr x, IntPtr n, IntPtr @out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_entr(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_erf(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_erfc(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_erfcx(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_erfinv(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_expit(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_expm1(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_exp2(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_gammaln(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_gammainc(IntPtr tensor, IntPtr other);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_gammaincc(IntPtr tensor, IntPtr other);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_polygamma(long n, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_multigammaln(IntPtr tensor, long p);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_digamma(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_i0(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_i0e(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_i1(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_i1e(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_logit(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_log_softmax(IntPtr tensor, long dim, sbyte scalar_type);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_softmax(IntPtr tensor, long dim, sbyte scalar_type);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_ndtr(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_ndtri(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_sinc(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_xlog1py(IntPtr tensor, IntPtr other);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSSpecial_zeta(IntPtr tensor, IntPtr other);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern double THSSpecial_erf_scalar(double x);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern double THSSpecial_erfc_scalar(double x);\n }\n}\n" }, { "alpha_fraction": 0.5633528232574463, "alphanum_fraction": 0.5698505640029907, "avg_line_length": 34.79069900512695, "blob_id": "aae537606737be2746ed36854e0b1c789b26a76c", "content_id": "8679c97dd3df0a40eed01855ba1314e235f0b698", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1539, "license_type": "permissive", "max_line_length": 141, "num_lines": 43, "path": "/src/TorchVision/Grayscale.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class Grayscale : ITransform\n {\n internal Grayscale(int outputChannels = 1)\n {\n if (outputChannels != 1 && outputChannels != 3) throw new ArgumentException(\"The number of output channels must be 1 or 3.\");\n this.outputChannels = outputChannels;\n }\n\n public Tensor call(Tensor input)\n {\n int cDim = (int)input.Dimensions - 3;\n if (input.shape[cDim] == 1) return input.alias();\n if (input.shape[cDim] != 3)\n throw new ArgumentException(\"RGB input to 'Grayscale' transform must have 3 channels.\");\n return transforms.functional.rgb_to_grayscale(input, outputChannels);\n }\n\n protected int outputChannels;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Convert image to grayscale. \n /// </summary>\n /// <param name=\"outputChannels\">The number of channels in the output image tensor.</param>\n /// <returns></returns>\n static public ITransform Grayscale(int outputChannels = 1)\n {\n return new Grayscale(outputChannels);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5795321464538574, "alphanum_fraction": 0.5826510787010193, "avg_line_length": 47.40565872192383, "blob_id": "52144a5704fde98b5e62ad5f75147b9cafae5c3b", "content_id": "1cfe0a2f2e3957f48604aa66bea7cf5c0506c269", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5130, "license_type": "permissive", "max_line_length": 160, "num_lines": 106, "path": "/src/TorchVision/GaussianBlur.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\n\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class GaussianBlur : ITransform\n {\n internal GaussianBlur(IList<long> kernelSize, float min, float max)\n {\n if (kernelSize == null || kernelSize.Count != 2 || kernelSize.Any(x => x <= 0)) {\n throw new ArgumentException(\"Invalid kernel size argument.\");\n }\n if (min < 0 || max < 0 || min >= max) {\n throw new ArgumentException(\"Invalid GaussianBlur arguments.\");\n }\n this.sigma = (min == max) ?\n min :\n (float)(new Random().NextDouble() * (max - min) + min);\n this.kernelSize = kernelSize.ToArray();\n }\n\n public Tensor call(Tensor input)\n {\n return transforms.functional.gaussian_blur(input, kernelSize, new float[] { sigma });\n }\n\n protected long[] kernelSize;\n protected float sigma;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Apply a Gaussian blur effect to the image.\n /// </summary>\n /// <param name=\"kernelSize\">Gaussian kernel size</param>\n /// <param name=\"sigma\">Gaussian kernel standard deviation</param>\n /// <returns></returns>\n static public ITransform GaussianBlur(IList<long> kernelSize, float sigma)\n {\n return new GaussianBlur(kernelSize, sigma, sigma);\n }\n\n /// <summary>\n /// Apply a Gaussian blur effect to the image.\n /// </summary>\n /// <param name=\"kernelSize\">Gaussian kernel size</param>\n /// <param name=\"min\">Minimum value of the range for the uniform distribution from which the Gaussian kernel standard deviation will sampled</param>\n /// <param name=\"max\">Maximum value of the range for the uniform distribution from which the Gaussian kernel standard deviation will sampled</param>\n static public ITransform GaussianBlur(IList<long> kernelSize, float min = 0.1f, float max = 2.0f)\n {\n return new GaussianBlur(kernelSize, min, max);\n }\n\n /// <summary>\n /// Apply a Gaussian blur effect to the image.\n /// </summary>\n /// <param name=\"kernelSize\">Gaussian kernel size</param>\n /// <param name=\"sigma\">Gaussian kernel standard deviation</param>\n static public ITransform GaussianBlur(long kernelSize, float sigma)\n {\n return new GaussianBlur(new long[] { kernelSize, kernelSize }, sigma, sigma);\n }\n\n /// <summary>\n /// Apply a Gaussian blur effect to the image.\n /// </summary>\n /// <param name=\"kernelSize\">Gaussian kernel size</param>\n /// <param name=\"min\">Minimum value of the range for the uniform distribution from which the Gaussian kernel standard deviation will sampled</param>\n /// <param name=\"max\">Maximum value of the range for the uniform distribution from which the Gaussian kernel standard deviation will sampled</param>\n static public ITransform GaussianBlur(long kernelSize, float min = 0.1f, float max = 2.0f)\n {\n return new GaussianBlur(new long[] { kernelSize, kernelSize }, min, max);\n }\n\n /// <summary>\n /// Apply a Gaussian blur effect to the image.\n /// </summary>\n /// <param name=\"kernelHeight\">Gaussian kernel height</param>\n /// <param name=\"kernelWidth\">Gaussian kernel width</param>\n /// <param name=\"sigma\">Gaussian kernel standard deviation</param>\n static public ITransform GaussianBlur(long kernelHeight, long kernelWidth, float sigma)\n {\n return new GaussianBlur(new long[] { kernelHeight, kernelWidth }, sigma, sigma);\n }\n\n /// <summary>\n /// Apply a Gaussian blur effect to the image.\n /// </summary>\n /// <param name=\"kernelHeight\">Gaussian kernel height</param>\n /// <param name=\"kernelWidth\">Gaussian kernel width</param>\n /// <param name=\"min\">Minimum value of the range for the uniform distribution from which the Gaussian kernel standard deviation will sampled</param>\n /// <param name=\"max\">Minimum value of the range for the uniform distribution from which the Gaussian kernel standard deviation will sampled</param>\n static public ITransform GaussianBlur(long kernelHeight, long kernelWidth, float min = 0.1f, float max = 2.0f)\n {\n return new GaussianBlur(new long[] { kernelHeight, kernelWidth }, min, max);\n }\n }\n }\n}" }, { "alpha_fraction": 0.45181626081466675, "alphanum_fraction": 0.4575202763080597, "avg_line_length": 33.340206146240234, "blob_id": "e4947a432e287f760d67e84bf80de2c4a0e373d6", "content_id": "132721ee72a404b6bf8a59cbe62c86c78b83388d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9993, "license_type": "permissive", "max_line_length": 130, "num_lines": 291, "path": "/src/TorchSharp/Tensor/Size.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System.Linq;\nusing System.Collections.Generic;\nusing System.Collections;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torch\n {\n /// <summary>\n /// Represents the dimensions of a tensor, that is, its shape.\n /// </summary>\n /// <remarks>\n /// The primary purpose of this type, at the moment, is to avoid having to declare\n /// too many overloads on tensor factories that take input sizes.\n /// The name was chosen to coincide with 'torch.Size' in PyTorch. It may later be\n /// used as the return value of 'Tensor.shape' and 'Tensor.size()'\n /// </remarks>\n public struct Size : IEnumerable<long>\n {\n /// <summary>\n /// Represents an empty size.\n /// </summary>\n public static Size Empty = new Size(System.Array.Empty<long>());\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"shape\">An array of longs, the size of an N-D tensor.</param>\n public Size(long[] shape)\n {\n _shape = (long[])shape.Clone();\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"shape\">An enumerable of longs, the size of an N-D tensor.</param>\n public Size(IEnumerable<long> shape)\n {\n _shape = shape.ToArray();\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"shape\">An array of longs, the size of an N-D tensor.</param>\n public Size(int[] shape)\n {\n _shape = shape.Select(i => (long)i).ToArray();\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"size\">The size of a 1D tensor.</param>\n public Size(long size)\n {\n _shape = new long[] { size };\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"size\">The size of a 2D tensor.</param>\n public Size((long, long) size)\n {\n _shape = new long[] { size.Item1, size.Item2 };\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"size\">The size of a 3D tensor.</param>\n public Size((long, long, long) size)\n {\n _shape = new long[] { size.Item1, size.Item2, size.Item3 };\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"size\">The size of a 4D tensor.</param>\n public Size((long, long, long, long) size)\n {\n _shape = new long[] { size.Item1, size.Item2, size.Item3, size.Item4 };\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"size\">The size of a 5D tensor.</param>\n public Size((long, long, long, long, long) size)\n {\n _shape = new long[] { size.Item1, size.Item2, size.Item3, size.Item4, size.Item5 };\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"size\">The size of a 6D tensor.</param>\n public Size((long, long, long, long, long, long) size)\n {\n _shape = new long[] { size.Item1, size.Item2, size.Item3, size.Item4, size.Item5, size.Item6 };\n }\n\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"size\">The size of a 1D tensor.</param>\n public Size(int size)\n {\n _shape = new long[] { size };\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"size\">The size of a 2D tensor.</param>\n public Size((int, int) size)\n {\n _shape = new long[] { size.Item1, size.Item2 };\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"size\">The size of a 3D tensor.</param>\n public Size((int, int, int) size)\n {\n _shape = new long[] { size.Item1, size.Item2, size.Item3 };\n }\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"size\">The size of a 4D tensor.</param>\n public Size((int, int, int, int) size)\n {\n _shape = new long[] { size.Item1, size.Item2, size.Item3, size.Item4 };\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"size\">The size of a 5D tensor.</param>\n public Size((int, int, int, int, int) size)\n {\n _shape = new long[] { size.Item1, size.Item2, size.Item3, size.Item4, size.Item5 };\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"size\">The size of a 6D tensor.</param>\n public Size((int, int, int, int, int, int) size)\n {\n _shape = new long[] { size.Item1, size.Item2, size.Item3, size.Item4, size.Item5, size.Item6 };\n }\n\n /// <summary>\n /// Implicit conversion operators. Useful to avoid overloads everywhere.\n /// </summary>\n public static implicit operator Size(long size) => new Size(size);\n public static implicit operator Size((long, long) size) => new Size(size);\n public static implicit operator Size((long, long, long) size) => new Size(size);\n public static implicit operator Size((long, long, long, long) size) => new Size(size);\n public static implicit operator Size((long, long, long, long, long) size) => new Size(size);\n public static implicit operator Size((long, long, long, long, long, long) size) => new Size(size);\n\n public static implicit operator Size(long[] size) => new Size(size);\n\n public static Size operator +(Size left, Size right)\n {\n return new Size(left._shape.AsEnumerable<long>().Concat<long>(right._shape).ToArray());\n }\n\n public static Size operator +(Size left, IEnumerable<long> right)\n {\n return new Size(left._shape.AsEnumerable<long>().Concat<long>(right).ToArray());\n }\n\n //public static implicit operator Size(long[] size) => new Size(size);\n //public static implicit operator long[](Size size) => size._shape;\n\n public static bool operator ==(Size left, Size right) => left._shape == right._shape;\n\n public static bool operator !=(Size left, Size right) => left._shape != right._shape;\n\n public override bool Equals(object? obj)\n {\n if (obj is null || !(obj is Size)) return false;\n\n return _shape.Equals(((Size)obj)._shape);\n }\n\n public Size Slice(int first, int next)\n {\n if (next < 0) {\n next = _shape.Length + next;\n }\n\n if (first < 0) {\n first = _shape.Length + first;\n }\n\n if (next <= first) {\n return Size.Empty;\n }\n\n if (first == 0) {\n if (next == _shape.Length) {\n return this;\n }\n else {\n return new Size(_shape.Take(next));\n }\n }\n else {\n if (next == _shape.Length) {\n return new Size(_shape.Skip(first));\n } else {\n return new Size(_shape.Skip(first).Take(next-first));\n }\n }\n }\n\n public override int GetHashCode()\n {\n return _shape.GetHashCode();\n }\n\n /// <summary>\n /// The number of elements in a tensor, the product of its shape elements.\n /// </summary>\n /// <returns></returns>\n public long numel()\n {\n long size = 1;\n foreach (var s in _shape) {\n size *= s;\n }\n return size;\n }\n\n public bool IsEmpty => _shape.Length == 0;\n\n public bool IsScalar => IsEmpty;\n\n public int Length => _shape.Length;\n\n public IEnumerable<long> Take(int i) => _shape.Take<long>(i);\n\n public IEnumerator<long> GetEnumerator()\n {\n return _shape.AsEnumerable<long>().GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return this.GetEnumerator();\n }\n\n /// <summary>\n /// Element accessor\n /// </summary>\n /// <param name=\"idx\">The element index</param>\n /// <returns></returns>\n public long this[int idx] {\n get { return _shape[idx]; }\n }\n\n /// <summary>\n /// Element accessor\n /// </summary>\n /// <param name=\"idx\">The element index</param>\n /// <returns></returns>\n public long this[long idx] {\n get { return _shape[(int)idx]; }\n }\n\n public long[] Shape { get { return _shape; } }\n\n private long[] _shape;\n }\n\n\n }\n}\n" }, { "alpha_fraction": 0.5404923558235168, "alphanum_fraction": 0.5419193506240845, "avg_line_length": 39.62318801879883, "blob_id": "f0b863ec67b2532966e2e0584f867ac097f894a7", "content_id": "fe1d94bd532d41d3987fc502104cc688cf884957", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2803, "license_type": "permissive", "max_line_length": 151, "num_lines": 69, "path": "/src/TorchSharp/NN/PixelShuffle.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a dropout module.\n /// </summary>\n public sealed class PixelShuffle : torch.nn.Module<Tensor, Tensor>\n {\n internal PixelShuffle(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n /// <summary>\n /// Forward pass.\n /// </summary>\n /// <param name=\"tensor\">Input tensor</param>\n /// <returns></returns>\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_PixelShuffle_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Rearranges elements in a tensor of shape (*, C * r^2, H, W) to a tensor of shape(*, C, H * r, W * r), where r is an upscale factor.\n /// This is useful for implementing efficient sub-pixel convolution with a stride of 1/r.\n /// </summary>\n /// <param name=\"upscaleFactor\">Factor to increase spatial resolution by</param>\n /// <returns></returns>\n public static PixelShuffle PixelShuffle(long upscaleFactor)\n {\n var handle = THSNN_PixelShuffle_ctor(upscaleFactor, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new PixelShuffle(handle, boxedHandle);\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Rearranges elements in a tensor of shape (*, C * r^2, H, W) to a tensor of shape(*, C, H * r, W * r), where r is an upscale factor.\n /// This is useful for implementing efficient sub-pixel convolution with a stride of 1/r.\n /// </summary>\n /// <param name=\"x\">Input tensor</param>\n /// <param name=\"upscaleFactor\">Factor to increase spatial resolution by</param>\n /// <returns></returns>\n /// <returns></returns>\n public static Tensor pixel_shuffle(Tensor x, long upscaleFactor)\n {\n using (var d = nn.PixelShuffle(upscaleFactor)) {\n return d.call(x);\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6810643672943115, "alphanum_fraction": 0.7021636962890625, "avg_line_length": 37.554405212402344, "blob_id": "c1b1f31364fa1153b8a3affa31ad03ba3e1400aa", "content_id": "e1500d939016fb20da8539ac042dec4511f255bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 37205, "license_type": "permissive", "max_line_length": 259, "num_lines": 965, "path": "/src/Native/LibTorchSharp/THSConvolution.cpp", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#include \"THSNN.h\"\n\n#include <torch/nn/init.h>\n\n\n\nNNModule THSNN_AvgPool1d_ctor(const int64_t* kernelSize, const int64_t* stride, const int64_t* padding,\n bool ceil_mode, bool count_include_pad, int64_t divisor_override,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::AvgPool1dOptions(at::ArrayRef<int64_t>(kernelSize, 1)).ceil_mode(ceil_mode).count_include_pad(count_include_pad);\n if (stride)\n opts = opts.stride(at::ArrayRef<int64_t>(stride, 1));\n if (padding)\n opts = opts.padding(at::ArrayRef<int64_t>(padding, 1));\n if (divisor_override > 0)\n opts = opts.divisor_override(divisor_override);\n res = create_module<torch::nn::AvgPool1dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_AvgPool1d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::AvgPool1d>()->forward(*tensor));\n}\n\nNNModule THSNN_AvgPool2d_ctor(const int64_t* kernelSize, const int kernelSizeLength, const int64_t* stride, const int strideLength, const int64_t* padding, const int paddingLength,\n bool ceil_mode, bool count_include_pad, int64_t divisor_override,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::AvgPool2dOptions(at::ArrayRef<int64_t>(kernelSize, kernelSizeLength)).ceil_mode(ceil_mode).count_include_pad(count_include_pad);\n if (stride)\n opts = opts.stride(at::ArrayRef<int64_t>(stride, strideLength));\n if (padding)\n opts = opts.padding(at::ArrayRef<int64_t>(padding, paddingLength));\n if (divisor_override > 0)\n opts = opts.divisor_override(divisor_override);\n res = create_module<torch::nn::AvgPool2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_AvgPool2d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::AvgPool2d>()->forward(*tensor));\n}\n\nNNModule THSNN_AvgPool3d_ctor(const int64_t* kernelSize, const int kernelSizeLength, const int64_t* stride, const int strideLength, const int64_t* padding, const int paddingLength,\n bool ceil_mode, bool count_include_pad, int64_t divisor_override,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::AvgPool3dOptions(at::ArrayRef<int64_t>(kernelSize, kernelSizeLength)).ceil_mode(ceil_mode).count_include_pad(count_include_pad);\n if (stride)\n opts = opts.stride(at::ArrayRef<int64_t>(stride, strideLength));\n if (padding)\n opts = opts.padding(at::ArrayRef<int64_t>(padding, paddingLength));\n if (divisor_override > 0)\n opts = opts.divisor_override(divisor_override);\n res = create_module<torch::nn::AvgPool3dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_AvgPool3d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::AvgPool3d>()->forward(*tensor));\n}\n\nNNModule THSNN_AdaptiveAvgPool1d_ctor(const int64_t* kernelSize, const int kernelSizeLength,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::AdaptiveAvgPool1dOptions(at::ArrayRef<int64_t>(kernelSize, kernelSizeLength));\n res = create_module<torch::nn::AdaptiveAvgPool1dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_AdaptiveAvgPool1d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::AdaptiveAvgPool1d>()->forward(*tensor));\n}\n\nNNModule THSNN_AdaptiveAvgPool2d_ctor(const int64_t* kernelSize, const int kernelSizeLength,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::AdaptiveAvgPool2dOptions(at::ArrayRef<int64_t>(kernelSize, kernelSizeLength));\n res = create_module<torch::nn::AdaptiveAvgPool2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_AdaptiveAvgPool2d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::AdaptiveAvgPool2d>()->forward(*tensor));\n}\n\nNNModule THSNN_AdaptiveAvgPool3d_ctor(const int64_t* kernelSize, const int kernelSizeLength,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::AdaptiveAvgPool3dOptions(at::ArrayRef<int64_t>(kernelSize, kernelSizeLength));\n res = create_module<torch::nn::AdaptiveAvgPool3dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_AdaptiveAvgPool3d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::AdaptiveAvgPool3d>()->forward(*tensor));\n}\n\nNNModule THSNN_AdaptiveMaxPool1d_ctor(const int64_t* kernelSize, const int kernelSizeLength,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::AdaptiveMaxPool1dOptions(at::ArrayRef<int64_t>(kernelSize, kernelSizeLength));\n res = create_module<torch::nn::AdaptiveMaxPool1dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_AdaptiveMaxPool1d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::AdaptiveMaxPool1d>()->forward(*tensor));\n}\n\nNNModule THSNN_AdaptiveMaxPool2d_ctor(const int64_t* kernelSize, const int kernelSizeLength,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::AdaptiveMaxPool2dOptions(at::ArrayRef<int64_t>(kernelSize, kernelSizeLength));\n res = create_module<torch::nn::AdaptiveMaxPool2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_AdaptiveMaxPool2d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::AdaptiveMaxPool2d>()->forward(*tensor));\n}\n\nNNModule THSNN_AdaptiveMaxPool3d_ctor(const int64_t* kernelSize, const int kernelSizeLength,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::AdaptiveMaxPool3dOptions(at::ArrayRef<int64_t>(kernelSize, kernelSizeLength));\n res = create_module<torch::nn::AdaptiveMaxPool3dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_AdaptiveMaxPool3d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::AdaptiveMaxPool3d>()->forward(*tensor));\n}\n\nNNModule THSNN_LPPool1d_ctor(double norm_type, const int64_t* kernelSize, const int64_t* stride, const bool ceil_mode,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::LPPool1dOptions(norm_type, at::ArrayRef<int64_t>(kernelSize, 1)).ceil_mode(ceil_mode);\n if (stride)\n opts = opts.stride(at::ArrayRef<int64_t>(stride, 1));\n res = create_module<torch::nn::LPPool1dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_LPPool1d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::LPPool1d>()->forward(*tensor));\n}\n\nNNModule THSNN_LPPool2d_ctor(double norm_type, const int64_t* kernelSize, const int kernelSizeLength, const int64_t* stride, const int strideLength, const bool ceil_mode,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::LPPool2dOptions(norm_type, at::ArrayRef<int64_t>(kernelSize, kernelSizeLength)).ceil_mode(ceil_mode);\n if (stride)\n opts = opts.stride(at::ArrayRef<int64_t>(stride, strideLength));\n res = create_module<torch::nn::LPPool2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_LPPool2d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::LPPool2d>()->forward(*tensor));\n}\n\nNNModule THSNN_MaxPool1d_ctor(const int64_t* kernelSize, const int64_t* stride, const int64_t* padding, const int64_t* dilation, bool ceil_mode,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::MaxPool1dOptions(at::ArrayRef<int64_t>(kernelSize, 1)).ceil_mode(ceil_mode);\n if (stride)\n opts = opts.stride(at::ArrayRef<int64_t>(stride, 1));\n if (padding)\n opts = opts.padding(at::ArrayRef<int64_t>(padding, 1));\n if (dilation)\n opts = opts.dilation(at::ArrayRef<int64_t>(dilation, 1));\n\n res = create_module<torch::nn::MaxPool1dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_MaxPool1d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::MaxPool1d>()->forward(*tensor));\n}\n\nTensor THSNN_MaxPool1d_forward_with_indices(const NNModule module, const Tensor tensor, Tensor* indices)\n{\n std::tuple<at::Tensor, at::Tensor> res;\n CATCH(res = (*module)->as<torch::nn::MaxPool1d>()->forward_with_indices(*tensor););\n *indices = ResultTensor(std::get<1>(res));\n return ResultTensor(std::get<0>(res));\n}\n\nNNModule THSNN_MaxPool2d_ctor(const int64_t* kernelSize, const int kernelSizeLength, const int64_t* stride, const int strideLength,\n const int64_t* padding, const int paddingLength, const int64_t* dilation, const int dilationLength, bool ceil_mode,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::MaxPool2dOptions(at::ArrayRef<int64_t>(kernelSize, kernelSizeLength)).ceil_mode(ceil_mode);\n if (stride)\n opts = opts.stride(at::ArrayRef<int64_t>(stride, strideLength));\n if (padding)\n opts = opts.padding(at::ArrayRef<int64_t>(padding, paddingLength));\n if (dilation)\n opts = opts.dilation(at::ArrayRef<int64_t>(dilation, dilationLength));\n\n res = create_module<torch::nn::MaxPool2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_MaxPool2d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::MaxPool2d>()->forward(*tensor));\n}\n\nTensor THSNN_MaxPool2d_forward_with_indices(const NNModule module, const Tensor tensor, Tensor* indices)\n{\n std::tuple<at::Tensor, at::Tensor> res;\n CATCH(res = (*module)->as<torch::nn::MaxPool2d>()->forward_with_indices(*tensor););\n *indices = ResultTensor(std::get<1>(res));\n return ResultTensor(std::get<0>(res));\n}\n\nNNModule THSNN_MaxPool3d_ctor(const int64_t* kernelSize, const int kernelSizeLength, const int64_t* stride, const int strideLength,\n const int64_t* padding, const int paddingLength, const int64_t* dilation, const int dilationLength, bool ceil_mode,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::MaxPool3dOptions(at::ArrayRef<int64_t>(kernelSize, kernelSizeLength)).ceil_mode(ceil_mode);\n if (stride)\n opts = opts.stride(at::ArrayRef<int64_t>(stride, strideLength));\n if (padding)\n opts = opts.padding(at::ArrayRef<int64_t>(padding, paddingLength));\n if (dilation)\n opts = opts.dilation(at::ArrayRef<int64_t>(dilation, dilationLength));\n\n res = create_module<torch::nn::MaxPool3dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_MaxPool3d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::MaxPool3d>()->forward(*tensor));\n}\n\nTensor THSNN_MaxPool3d_forward_with_indices(const NNModule module, const Tensor tensor, Tensor* indices)\n{\n std::tuple<at::Tensor, at::Tensor> res;\n CATCH(res = (*module)->as<torch::nn::MaxPool3d>()->forward_with_indices(*tensor););\n *indices = ResultTensor(std::get<1>(res));\n return ResultTensor(std::get<0>(res));\n}\n\nNNModule THSNN_MaxUnpool1d_ctor(const int64_t* kernelSize, const int64_t* stride, const int64_t* padding, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::MaxUnpool1dOptions(at::ArrayRef<int64_t>(kernelSize, 1));\n if (stride)\n opts = opts.stride(at::ArrayRef<int64_t>(stride, 1));\n if (padding)\n opts = opts.padding(at::ArrayRef<int64_t>(padding, 1));\n\n res = create_module<torch::nn::MaxUnpool1dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_MaxUnpool1d_forward(const NNModule module, const Tensor tensor, const Tensor indices, const int64_t* outputSize)\n{\n if (outputSize != nullptr) {\n std::vector<int64_t> outSize;\n outSize.push_back(*outputSize);\n\n CATCH_TENSOR((*module)->as<torch::nn::MaxUnpool1d>()->forward(*tensor, *indices, outSize));\n }\n else {\n CATCH_TENSOR((*module)->as<torch::nn::MaxUnpool1d>()->forward(*tensor, *indices));\n }\n}\n\nNNModule THSNN_MaxUnpool2d_ctor(const int64_t* kernelSize, const int kernelSizeLength, const int64_t* stride, const int strideLength, const int64_t* padding, const int paddingLength, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::MaxUnpool2dOptions(at::ArrayRef<int64_t>(kernelSize, kernelSizeLength));\n if (stride)\n opts = opts.stride(at::ArrayRef<int64_t>(stride, strideLength));\n if (padding)\n opts = opts.padding(at::ArrayRef<int64_t>(padding, paddingLength));\n\n res = create_module<torch::nn::MaxUnpool2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_MaxUnpool2d_forward(const NNModule module, const Tensor tensor, const Tensor indices, const int64_t* outputSize, const int outputSizeLength)\n{\n if (outputSize != nullptr) {\n std::vector<int64_t> outSize;\n for (auto i = 0L; i < outputSizeLength; i++) {\n outSize.push_back(outputSize[i]);\n }\n\n CATCH_TENSOR((*module)->as<torch::nn::MaxUnpool2d>()->forward(*tensor, *indices, outSize));\n }\n else {\n CATCH_TENSOR((*module)->as<torch::nn::MaxUnpool2d>()->forward(*tensor, *indices));\n }\n}\n\nNNModule THSNN_MaxUnpool3d_ctor(const int64_t* kernelSize, const int kernelSizeLength, const int64_t* stride, const int strideLength, const int64_t* padding, const int paddingLength, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::MaxUnpool3dOptions(at::ArrayRef<int64_t>(kernelSize, kernelSizeLength));\n if (stride)\n opts = opts.stride(at::ArrayRef<int64_t>(stride, strideLength));\n if (padding)\n opts = opts.padding(at::ArrayRef<int64_t>(padding, paddingLength));\n\n res = create_module<torch::nn::MaxUnpool3dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_MaxUnpool3d_forward(const NNModule module, const Tensor tensor, const Tensor indices, const int64_t* outputSize, const int outputSizeLength)\n{\n if (outputSize != nullptr) {\n std::vector<int64_t> outSize;\n for (auto i = 0L; i < outputSizeLength; i++) {\n outSize.push_back(outputSize[i]);\n }\n\n CATCH_TENSOR((*module)->as<torch::nn::MaxUnpool3d>()->forward(*tensor, *indices, outSize));\n }\n else {\n CATCH_TENSOR((*module)->as<torch::nn::MaxUnpool3d>()->forward(*tensor, *indices));\n }\n}\n\n\nNNModule THSNN_FractionalMaxPool2d_ctor(const int64_t* kernelSize, const int kernelSizeLength, const int64_t* outputSize, const int outputSizeLength, const double* outputRatio, const int outputRatioLength, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::FractionalMaxPool2dOptions(at::ArrayRef<int64_t>(kernelSize, kernelSizeLength));\n if (outputSize)\n opts = opts.output_size(at::ArrayRef<int64_t>(outputSize, outputSizeLength));\n if (outputRatio)\n opts = opts.output_ratio(at::ArrayRef<double>(outputRatio, outputRatioLength));\n\n res = create_module<torch::nn::FractionalMaxPool2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_FractionalMaxPool2d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::FractionalMaxPool2d>()->forward(*tensor));\n}\n\nTensor THSNN_FractionalMaxPool2d_forward_with_indices(const NNModule module, const Tensor tensor, Tensor* indices)\n{\n std::tuple<at::Tensor, at::Tensor> res;\n CATCH(res = (*module)->as<torch::nn::FractionalMaxPool2d>()->forward_with_indices(*tensor););\n *indices = ResultTensor(std::get<1>(res));\n return ResultTensor(std::get<0>(res));\n}\n\nNNModule THSNN_FractionalMaxPool3d_ctor(const int64_t* kernelSize, const int kernelSizeLength, const int64_t* outputSize, const int outputSizeLength, const double* outputRatio, const int outputRatioLength, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::FractionalMaxPool3dOptions(at::ArrayRef<int64_t>(kernelSize, kernelSizeLength));\n if (outputSize)\n opts = opts.output_size(at::ArrayRef<int64_t>(outputSize, outputSizeLength));\n if (outputRatio)\n opts = opts.output_ratio(at::ArrayRef<double>(outputRatio, outputRatioLength));\n\n res = create_module<torch::nn::FractionalMaxPool3dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_FractionalMaxPool3d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::FractionalMaxPool3d>()->forward(*tensor));\n}\n\nTensor THSNN_FractionalMaxPool3d_forward_with_indices(const NNModule module, const Tensor tensor, Tensor* indices)\n{\n std::tuple<at::Tensor, at::Tensor> res;\n CATCH(res = (*module)->as<torch::nn::FractionalMaxPool3d>()->forward_with_indices(*tensor););\n *indices = ResultTensor(std::get<1>(res));\n return ResultTensor(std::get<0>(res));\n}\n\nNNModule THSNN_ZeroPad2d_ctor(const int64_t padding, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ZeroPad2dOptions(padding);\n res = create_module<torch::nn::ZeroPad2dImpl>(opts, outAsAnyModule);\n );\n}\n\nNNModule THSNN_ZeroPad2d_ctor_tuple(const int64_t padding_left, const int64_t padding_right, const int64_t padding_top, const int64_t padding_bottom, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ZeroPad2dOptions({ padding_left, padding_right, padding_top, padding_bottom });\n res = create_module<torch::nn::ZeroPad2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_ZeroPad2d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::ZeroPad2d>()->forward(*tensor));\n}\n\nNNModule THSNN_ConstantPad1d_ctor(const double value, const int64_t padding, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ConstantPad1dOptions(padding, value);\n res = create_module<torch::nn::ConstantPad1dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_ConstantPad1d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::ConstantPad1d>()->forward(*tensor));\n}\n\nNNModule THSNN_ConstantPad2d_ctor(const double value, const int64_t padding, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ConstantPad2dOptions(padding, value);\n res = create_module<torch::nn::ConstantPad2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_ConstantPad2d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::ConstantPad2d>()->forward(*tensor));\n}\n\nNNModule THSNN_ConstantPad3d_ctor(const double value, const int64_t padding, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ConstantPad3dOptions(padding, value);\n res = create_module<torch::nn::ConstantPad3dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_ConstantPad3d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::ConstantPad3d>()->forward(*tensor));\n}\n\nNNModule THSNN_ConstantPad1d_ctor_tuple(const double value, const int64_t padding_left, const int64_t padding_right, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ConstantPad1dOptions({ padding_left, padding_right }, value);\n res = create_module<torch::nn::ConstantPad1dImpl>(opts, outAsAnyModule);\n );\n}\n\nNNModule THSNN_ConstantPad2d_ctor_tuple(const double value, const int64_t padding_left, const int64_t padding_right, const int64_t padding_top, const int64_t padding_bottom, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ConstantPad2dOptions({ padding_left, padding_right, padding_top, padding_bottom }, value);\n res = create_module<torch::nn::ConstantPad2dImpl>(opts, outAsAnyModule);\n );\n}\n\nNNModule THSNN_ConstantPad3d_ctor_tuple(const double value, const int64_t padding_left, const int64_t padding_right, const int64_t padding_top, const int64_t padding_bottom, const int64_t padding_front, const int64_t padding_back, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ConstantPad3dOptions({ padding_left, padding_right, padding_top, padding_bottom, padding_front, padding_back }, value);\n res = create_module<torch::nn::ConstantPad3dImpl>(opts, outAsAnyModule);\n );\n}\n\nNNModule THSNN_ReplicationPad1d_ctor(const int64_t padding, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ReplicationPad1dOptions(padding);\n res = create_module<torch::nn::ReplicationPad1dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_ReplicationPad1d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::ReplicationPad1d>()->forward(*tensor));\n}\n\nNNModule THSNN_ReplicationPad2d_ctor(const int64_t padding, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ReplicationPad2dOptions(padding);\n res = create_module<torch::nn::ReplicationPad2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_ReplicationPad2d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::ReplicationPad2d>()->forward(*tensor));\n}\n\nNNModule THSNN_ReplicationPad3d_ctor(const int64_t padding, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ReplicationPad3dOptions(padding);\n res = create_module<torch::nn::ReplicationPad3dImpl>(opts, outAsAnyModule);\n );\n}\n\n\nTensor THSNN_ReplicationPad3d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::ReplicationPad3d>()->forward(*tensor));\n}\n\nNNModule THSNN_ReplicationPad1d_ctor_tuple(const int64_t padding_left, const int64_t padding_right, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ReplicationPad1dOptions({ padding_left, padding_right });\n res = create_module<torch::nn::ReplicationPad1dImpl>(opts, outAsAnyModule);\n );\n}\n\nNNModule THSNN_ReplicationPad2d_ctor_tuple(const int64_t padding_left, const int64_t padding_right, const int64_t padding_top, const int64_t padding_bottom, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ReplicationPad2dOptions({ padding_left, padding_right, padding_top, padding_bottom });\n res = create_module<torch::nn::ReplicationPad2dImpl>(opts, outAsAnyModule);\n );\n}\n\nNNModule THSNN_ReplicationPad3d_ctor_tuple(const int64_t padding_left, const int64_t padding_right, const int64_t padding_top, const int64_t padding_bottom, const int64_t padding_front, const int64_t padding_back, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ReplicationPad3dOptions({ padding_left, padding_right, padding_top, padding_bottom, padding_front, padding_back });\n res = create_module<torch::nn::ReplicationPad3dImpl>(opts, outAsAnyModule);\n );\n}\n\nNNModule THSNN_ReflectionPad1d_ctor(const int64_t padding, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ReflectionPad1dOptions(padding);\n res = create_module<torch::nn::ReflectionPad1dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_ReflectionPad1d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::ReflectionPad1d>()->forward(*tensor));\n}\n\nNNModule THSNN_ReflectionPad2d_ctor(const int64_t padding, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ReflectionPad2dOptions(padding);\n res = create_module<torch::nn::ReflectionPad2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_ReflectionPad2d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::ReflectionPad2d>()->forward(*tensor));\n}\n\nNNModule THSNN_ReflectionPad3d_ctor(const int64_t padding, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ReflectionPad3dOptions(padding);\n res = create_module<torch::nn::ReflectionPad3dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_ReflectionPad3d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::ReflectionPad3d>()->forward(*tensor));\n}\n\nNNModule THSNN_ReflectionPad1d_ctor_tuple(const int64_t padding_left, const int64_t padding_right, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ReflectionPad1dOptions({ padding_left, padding_right });\n res = create_module<torch::nn::ReflectionPad1dImpl>(opts, outAsAnyModule);\n );\n}\n\nNNModule THSNN_ReflectionPad2d_ctor_tuple(const int64_t padding_left, const int64_t padding_right, const int64_t padding_top, const int64_t padding_bottom, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ReflectionPad2dOptions({ padding_left, padding_right, padding_top, padding_bottom });\n res = create_module<torch::nn::ReflectionPad2dImpl>(opts, outAsAnyModule);\n );\n}\n\nNNModule THSNN_ReflectionPad3d_ctor_tuple(const int64_t padding_left, const int64_t padding_right, const int64_t padding_top, const int64_t padding_bottom, const int64_t padding_front, const int64_t padding_back, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ReflectionPad3dOptions({ padding_left, padding_right, padding_top, padding_bottom, padding_front, padding_back });\n res = create_module<torch::nn::ReflectionPad3dImpl>(opts, outAsAnyModule);\n );\n}\n\n\ntemplate<typename T>\nvoid ApplyPaddingMode(T& opts, const int64_t padding)\n{\n if (padding == 0)\n opts = opts.padding_mode(torch::kZeros);\n if (padding == 1)\n opts = opts.padding_mode(torch::kReflect);\n if (padding == 2)\n opts = opts.padding_mode(torch::kReplicate);\n if (padding == 3)\n opts = opts.padding_mode(torch::kCircular);\n}\n\nNNModule THSNN_Conv1d_ctor(const int64_t inputChannel, const int64_t outputChannel,\n const int64_t kernelSize, const int64_t stride, const int64_t padding,\n const int64_t dilation, const int64_t paddingMode, const int64_t groups, const bool bias,\n NNAnyModule* outAsAnyModule)\n{\n torch::nn::Conv1dOptions::padding_t padd(padding);\n if (padding == -1)\n {\n padd = torch::kSame;\n }\n\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::Conv1dOptions(inputChannel, outputChannel, kernelSize)\n .stride(stride)\n .padding(padd)\n .dilation(dilation)\n .groups(groups)\n .bias(bias);\n\n ApplyPaddingMode(opts, paddingMode);\n\n res = create_module<torch::nn::Conv1dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Conv1d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Conv1d>()->forward(*tensor));\n}\n\nTensor THSNN_Conv1d_bias(const NNModule module)\n{\n return get_bias<torch::nn::Conv1d>(module);\n}\n\nvoid THSNN_Conv1d_set_bias(const NNModule module, const Tensor bias)\n{\n set_bias<torch::nn::Conv1d>(module, bias);\n}\n\nTensor THSNN_Conv1d_weight(const NNModule module)\n{\n return get_weight<torch::nn::Conv1d>(module);\n}\n\nvoid THSNN_Conv1d_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::Conv1d>(module, weight);\n}\n\nNNModule THSNN_Conv2d_ctor(const int64_t inputChannel, const int64_t outputChannel,\n const int64_t kernelSize, const int64_t stride, const int64_t padding,\n const int64_t dilation, const int64_t paddingMode, const int64_t groups, const bool bias,\n NNAnyModule* outAsAnyModule)\n{\n torch::nn::Conv2dOptions::padding_t padd =\n (padding == -1) ? torch::kSame :\n (padding == 0) ? torch::kValid :\n torch::nn::Conv2dOptions::padding_t(padding);\n\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::Conv2dOptions(inputChannel, outputChannel, kernelSize)\n .stride(stride)\n .padding(padd)\n .dilation(dilation)\n .groups(groups)\n .bias(bias);\n ApplyPaddingMode(opts, paddingMode);\n\n res = create_module<torch::nn::Conv2dImpl>(opts, outAsAnyModule);\n );\n}\n\nNNModule THSNN_Conv2d_ctor_1(const int64_t inputChannel, const int64_t outputChannel,\n const int64_t kernelX, const int64_t kernelY,\n const int64_t strideX, const int64_t strideY,\n const int64_t paddingX, const int64_t paddingY,\n const int64_t dilationX, const int64_t dilationY,\n const int64_t paddingMode, const int64_t groups, const bool bias,\n NNAnyModule* outAsAnyModule)\n{\n torch::nn::Conv2dOptions::padding_t padd =\n (paddingX == -1) && (paddingY == 0) ? torch::kSame :\n (paddingX == 0) && (paddingY == 0) ? torch::kValid :\n (torch::nn::Conv2dOptions::padding_t)torch::ExpandingArray<2>({ paddingX, paddingY });\n\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::Conv2dOptions(inputChannel, outputChannel, { kernelX, kernelY })\n .stride({ strideX, strideY })\n .padding(padd)\n .dilation({ dilationX, dilationY })\n .groups(groups)\n .bias(bias);\n ApplyPaddingMode(opts, paddingMode);\n\n res = create_module<torch::nn::Conv2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Conv2d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Conv2d>()->forward(*tensor));\n}\n\nTensor THSNN_Conv2d_bias(const NNModule module)\n{\n return get_bias<torch::nn::Conv2d>(module);\n}\n\nvoid THSNN_Conv2d_set_bias(const NNModule module, const Tensor bias)\n{\n set_bias<torch::nn::Conv2d>(module, bias);\n}\n\nTensor THSNN_Conv2d_weight(const NNModule module)\n{\n return get_weight<torch::nn::Conv2d>(module);\n}\n\nvoid THSNN_Conv2d_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::Conv2d>(module, weight);\n}\n\nNNModule THSNN_Conv3d_ctor(const int64_t inputChannel, const int64_t outputChannel,\n const int64_t kernelSize, const int64_t stride, const int64_t padding,\n const int64_t dilation, const int64_t paddingMode, const int64_t groups, const bool bias,\n NNAnyModule* outAsAnyModule)\n{\n torch::nn::Conv3dOptions::padding_t padd =\n (padding == -1) ? torch::kSame :\n (padding == 0) ? torch::kValid :\n torch::nn::Conv3dOptions::padding_t(padding);\n\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::Conv3dOptions(inputChannel, outputChannel, kernelSize)\n .stride(stride)\n .padding(padd)\n .dilation(dilation)\n .groups(groups)\n .bias(bias);\n ApplyPaddingMode(opts, paddingMode);\n\n res = create_module<torch::nn::Conv3dImpl>(opts, outAsAnyModule);\n );\n}\n\nNNModule THSNN_Conv3d_ctor_1(const int64_t inputChannel, const int64_t outputChannel,\n const int64_t kernelX, const int64_t kernelY, const int64_t kernelZ,\n const int64_t strideX, const int64_t strideY, const int64_t strideZ,\n const int64_t paddingX, const int64_t paddingY, const int64_t paddingZ,\n const int64_t dilationX, const int64_t dilationY, const int64_t dilationZ,\n const int64_t paddingMode, const int64_t groups, const bool bias,\n NNAnyModule* outAsAnyModule)\n{\n torch::nn::Conv3dOptions::padding_t padd =\n (paddingX == -1) && (paddingY == 0) && (paddingZ == 0) ? torch::kSame :\n (paddingX == 0) && (paddingY == 0) && (paddingZ == 0) ? torch::kValid :\n (torch::nn::Conv3dOptions::padding_t)torch::ExpandingArray<3>({ paddingX, paddingY, paddingZ });\n\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::Conv3dOptions(inputChannel, outputChannel, { kernelX, kernelY, kernelZ })\n .stride({ strideX, strideY, strideZ })\n .padding(padd)\n .dilation({ dilationX, dilationY, dilationZ })\n .groups(groups)\n .bias(bias);\n ApplyPaddingMode(opts, paddingMode);\n\n res = create_module<torch::nn::Conv3dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Conv3d_bias(const NNModule module)\n{\n return get_bias<torch::nn::Conv3d>(module);\n}\n\nvoid THSNN_Conv3d_set_bias(const NNModule module, const Tensor bias)\n{\n set_bias<torch::nn::Conv3d>(module, bias);\n}\n\nTensor THSNN_Conv3d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Conv3d>()->forward(*tensor));\n}\n\nTensor THSNN_Conv3d_weight(const NNModule module)\n{\n return get_weight<torch::nn::Conv3d>(module);\n}\n\nvoid THSNN_Conv3d_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::Conv3d>(module, weight);\n}\n\n\nNNModule THSNN_ConvTranspose1d_ctor(const int64_t inputChannel, const int64_t outputChannel,\n const int64_t kernelSize, const int64_t stride, const int64_t padding, const int64_t output_padding,\n const int64_t dilation, const int64_t paddingMode, const int64_t groups, const bool bias,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ConvTranspose1dOptions(inputChannel, outputChannel, kernelSize)\n .stride(stride)\n .padding(padding)\n .dilation(dilation)\n .groups(groups)\n .bias(bias)\n .output_padding(output_padding);\n ApplyPaddingMode(opts, paddingMode);\n\n res = create_module<torch::nn::ConvTranspose1dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_ConvTranspose1d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::ConvTranspose1d>()->forward(*tensor));\n}\n\nTensor THSNN_ConvTranspose1d_bias(const NNModule module)\n{\n return get_bias<torch::nn::ConvTranspose1d>(module);\n}\n\nvoid THSNN_ConvTranspose1d_set_bias(const NNModule module, const Tensor bias)\n{\n set_bias<torch::nn::ConvTranspose1d>(module, bias);\n}\n\nTensor THSNN_ConvTranspose1d_weight(const NNModule module)\n{\n return get_weight<torch::nn::ConvTranspose1d>(module);\n}\n\nvoid THSNN_ConvTranspose1d_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::ConvTranspose1d>(module, weight);\n}\n\nNNModule THSNN_ConvTranspose2d_ctor(const int64_t inputChannel, const int64_t outputChannel,\n const int64_t kernelSize, const int64_t stride, const int64_t padding, const int64_t output_padding,\n const int64_t dilation, const int64_t paddingMode, const int64_t groups, const bool bias,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ConvTranspose2dOptions(inputChannel, outputChannel, kernelSize)\n .stride(stride)\n .padding(padding)\n .dilation(dilation)\n .groups(groups)\n .bias(bias)\n .output_padding(output_padding);\n ApplyPaddingMode(opts, paddingMode);\n\n res = create_module<torch::nn::ConvTranspose2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_ConvTranspose2d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::ConvTranspose2d>()->forward(*tensor));\n}\n\nTensor THSNN_ConvTranspose2d_bias(const NNModule module)\n{\n return get_bias<torch::nn::ConvTranspose2d>(module);\n}\n\nvoid THSNN_ConvTranspose2d_set_bias(const NNModule module, const Tensor bias)\n{\n set_bias<torch::nn::ConvTranspose2d>(module, bias);\n}\n\nTensor THSNN_ConvTranspose2d_weight(const NNModule module)\n{\n return get_weight<torch::nn::ConvTranspose2d>(module);\n}\n\nvoid THSNN_ConvTranspose2d_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::ConvTranspose2d>(module, weight);\n}\n\nNNModule THSNN_ConvTranspose3d_ctor(const int64_t inputChannel, const int64_t outputChannel,\n const int64_t kernelSize, const int64_t stride, const int64_t padding, const int64_t output_padding,\n const int64_t dilation, const int64_t paddingMode, const int64_t groups, const bool bias,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::ConvTranspose3dOptions(inputChannel, outputChannel, kernelSize)\n .stride(stride)\n .padding(padding)\n .dilation(dilation)\n .groups(groups)\n .bias(bias)\n .output_padding(output_padding);\n ApplyPaddingMode(opts, paddingMode);\n\n res = create_module<torch::nn::ConvTranspose3dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_ConvTranspose3d_bias(const NNModule module)\n{\n return get_bias<torch::nn::ConvTranspose3d>(module);\n}\n\nvoid THSNN_ConvTranspose3d_set_bias(const NNModule module, const Tensor bias)\n{\n set_bias<torch::nn::ConvTranspose3d>(module, bias);\n}\n\nTensor THSNN_ConvTranspose3d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::ConvTranspose3d>()->forward(*tensor));\n}\n\nTensor THSNN_ConvTranspose3d_weight(const NNModule module)\n{\n return get_weight<torch::nn::ConvTranspose3d>(module);\n}\n\nvoid THSNN_ConvTranspose3d_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::ConvTranspose3d>(module, weight);\n}\n" }, { "alpha_fraction": 0.7513944506645203, "alphanum_fraction": 0.7641434073448181, "avg_line_length": 43.29411697387695, "blob_id": "ad82228860773a71eb344eccd4a8592acc6c7816", "content_id": "a2610eca553080496e1d69c83d4979668d55b100", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3765, "license_type": "permissive", "max_line_length": 241, "num_lines": 85, "path": "/src/Native/LibTorchSharp/THSJIT.h", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#pragma once\n\n#include \"../Stdafx.h\"\n\n#include \"torch/script.h\"\n\n#include \"Utils.h\"\n\n// Copied from libtorch to share the type as an int8_t.\nenum TypeKind : int8_t {\n#define DEFINE_TYPE(T) T,\n C10_FORALL_TYPES(DEFINE_TYPE)\n#undef DEFINE_TYPE\n};\n\n// API.\n\nstruct TensorOrScalar\n{\n int64_t TypeCode;\n int64_t ArrayIndex;\n ptrdiff_t Handle;\n};\n\n\nEXPORT_API(JITModule) THSJIT_load(const char* filename, int64_t device, int64_t index);\nEXPORT_API(void) THSJIT_save(JITModule module, const char* filename);\nEXPORT_API(JITCompilationUnit) THSJIT_compile(const char* script);\n\nEXPORT_API(void) THSJIT_Module_dispose(const JITModule module);\nEXPORT_API(void) THSJIT_CompilationUnit_dispose(const JITCompilationUnit module);\n\nEXPORT_API(int) THSJIT_Module_num_inputs(const JITModule method);\nEXPORT_API(int) THSJIT_Module_num_outputs(const JITModule method);\n\nEXPORT_API(void) THSJIT_Module_forward(const JITModule module, const TensorOrScalar* tensorPtrs, const int length, TensorOrScalar* (*allocator)(int32_t idx, size_t length), int8_t* typeCode, int32_t idx);\nEXPORT_API(void) THSJIT_Module_invoke(const JITModule module, const char* name, const TensorOrScalar* tensorPtrs, const int length, TensorOrScalar* (*allocator)(int32_t idx, size_t length), int8_t* typeCode, int32_t idx);\n\nEXPORT_API(void) THSJIT_CompilationUnit_Invoke(const JITCompilationUnit module, const char* method, const TensorOrScalar* tensorPtrs, const int length, TensorOrScalar* (*allocator)(int32_t idx, size_t length), int8_t* typeCode, int32_t idx);\n\nEXPORT_API(int) THSJIT_Module_is_training(JITModule module);\nEXPORT_API(void) THSJIT_Module_train(JITModule module, bool on);\nEXPORT_API(void) THSJIT_Module_eval(JITModule module);\n\nEXPORT_API(void) THSJIT_Module_to_device_dtype(JITModule module, int8_t dtype, int64_t device, int64_t index);\nEXPORT_API(void) THSJIT_Module_to_device(JITModule module, int64_t device, int64_t index);\nEXPORT_API(void) THSJIT_Module_to_dtype(JITModule module, int8_t dtype);\n\nEXPORT_API(JITType) THSJIT_Module_getInputType(JITModule module, int8_t dtype);\n\nEXPORT_API(int8_t) THSJIT_Type_kind(JITType handle);\nEXPORT_API(void*) THSJIT_Type_cast(const JITType type);\n\nEXPORT_API(int8_t) THSJIT_TensorType_dtype(const JITTensorType type);\nEXPORT_API(void) THSJIT_TensorType_sizes(const JITTensorType type, int64_t* (*allocator)(int64_t length));\n\nEXPORT_API(void) THSJIT_Type_dispose(const JITType type);\nEXPORT_API(void) THSJIT_TensorType_dispose(const JITTensorType type);\n\nEXPORT_API(void) THSJIT_Module_modules(const JITModule module, JITModule* (*allocator)(size_t length));\nEXPORT_API(void) THSJIT_Module_named_modules(const JITModule module,\n JITModule* (*allocator)(size_t length),\n const char** (*allocator2)(size_t length));\n\nEXPORT_API(void) THSJIT_Module_named_children(const JITModule module,\n JITModule* (*allocator)(size_t length),\n const char** (*allocator2)(size_t length));\n\nEXPORT_API(JITMethod) THSJIT_Module_get_method(const JITModule module, const char* name);\n\nEXPORT_API(void) THSJIT_Module_parameters(const JITModule module, Tensor* (*allocator)(size_t length));\nEXPORT_API(void) THSJIT_Module_named_parameters(const JITModule module,\n Tensor* (*allocator)(size_t length),\n const char** (*allocator2)(size_t length));\n\nEXPORT_API(void) THSJIT_Module_named_buffers(const JITModule module,\n Tensor* (*allocator)(size_t length),\n const char** (*allocator2)(size_t length));\n\nEXPORT_API(int) THSJIT_Method_num_inputs(const JITMethod method);\n\nEXPORT_API(void) THSJIT_Method_dispose(const JITMethod method);\n\nEXPORT_API(const char*) THSJIT_Method_name(const JITMethod method);\n" }, { "alpha_fraction": 0.6331987977027893, "alphanum_fraction": 0.6352169513702393, "avg_line_length": 40.3125, "blob_id": "07afdd45ed80d06eac1a840ebb05273477fcea3b", "content_id": "4a2b244a97522255f43d3f133d199bd10dbcce53", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1982, "license_type": "permissive", "max_line_length": 117, "num_lines": 48, "path": "/src/TorchSharp/ThreadDisposeScopeStatistics.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "#nullable enable\nnamespace TorchSharp\n{\n /// <summary>\n /// Keeps track of statistics for a dispose scope. Can be queried to figure out performance/memory issues.\n /// </summary>\n public class ThreadDisposeScopeStatistics\n {\n /// <summary>\n /// The number of disposables that were created on this thread, but weren't captured by a DisposeScope.\n /// </summary>\n public long CreatedOutsideScopeCount { get; internal set; }\n\n /// <summary>\n /// The number of disposables that were created on this thread and were captured by a DisposeScope.\n /// </summary>\n public long CreatedInScopeCount { get; internal set; }\n\n /// <summary>\n /// The number of disposables that were disposed on this thread and were disposed while in a DisposeScope.\n /// </summary>\n public long DisposedInScopeCount { get; internal set; }\n\n /// <summary>\n /// Number of disposables that were once included in the scope, but were subsequently detached.\n /// </summary>\n public long DetachedFromScopeCount { get; internal set; }\n\n /// <summary>\n /// The number of disposables that are currently live on the current thread. If a It's aproximate, see\n /// Tensor.TotalCount. Disposables that weren't created within a DisposeScope, or detached from the dispose\n /// scope, will not be counted as alive.\n /// </summary>\n public long ThreadTotalLiveCount => CreatedInScopeCount - DisposedInScopeCount - DetachedFromScopeCount;\n\n /// <summary>\n /// Resets the counts for the current thread. See ThreadTotalLiveCount etc. Mainly used in tests to make sure\n /// we get a clean slate on the thread.\n /// </summary>\n public void Reset()\n {\n CreatedOutsideScopeCount = 0;\n CreatedInScopeCount = 0;\n DisposedInScopeCount = 0;\n DetachedFromScopeCount = 0;\n }\n }\n}" }, { "alpha_fraction": 0.5151354074478149, "alphanum_fraction": 0.5264205932617188, "avg_line_length": 42.2931022644043, "blob_id": "be2b0ba50ddf365ffbcc0593ba07837aef4ce7b5", "content_id": "53cccf5fa827536eea4ebdcc9b6fcb196152bee0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7532, "license_type": "permissive", "max_line_length": 140, "num_lines": 174, "path": "/src/TorchAudio/Transforms/InverseMelScale.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchaudio,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/audio/blob/bb77cbebb620a46fdc0dc7e6dae2253eef3f37e2/torchaudio/transforms/_transforms.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/audio/blob/main/LICENSE\n//\n\nusing System;\nusing System.Collections.Generic;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\nusing static TorchSharp.torchaudio;\nusing F = TorchSharp.torchaudio.functional;\n\nnamespace TorchSharp\n{\n namespace Transforms\n {\n public sealed class InverseMelScale : Module<Tensor, Tensor>, ITransform\n {\n public readonly double f_max;\n public readonly double f_min;\n public readonly long max_iter;\n public readonly long n_mels;\n public readonly long sample_rate;\n public readonly double tolerance_change;\n public readonly double tolerance_loss;\n public readonly Tensor fb;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n fb.Dispose();\n }\n base.Dispose(disposing);\n }\n\n internal InverseMelScale(\n string name,\n long n_stft,\n long n_mels = 128,\n long sample_rate = 16000,\n double f_min = 0.0,\n double? f_max = null,\n long max_iter = 100000,\n double tolerance_loss = 1e-05,\n double tolerance_change = 1e-08,\n MelNorm norm = MelNorm.none,\n torchaudio.MelScale mel_scale = torchaudio.MelScale.htk) : base(name)\n {\n this.n_mels = n_mels;\n this.sample_rate = sample_rate;\n this.f_max = f_max ?? (sample_rate / 2);\n this.f_min = f_min;\n this.max_iter = max_iter;\n this.tolerance_loss = tolerance_loss;\n this.tolerance_change = tolerance_change;\n\n if (f_min > this.f_max) {\n throw new ArgumentException($\"Require f_min: {this.f_min} <= f_max: {this.f_max}\");\n }\n\n this.fb = F.melscale_fbanks(n_stft, this.f_min, this.f_max, this.n_mels, this.sample_rate, norm, mel_scale);\n this.register_buffer(\"fb\", this.fb);\n }\n\n /// <param name=\"melspec\">A Mel frequency spectrogram of dimension (..., ``n_mels``, time)</param>\n /// <returns>Linear scale spectrogram of size (..., freq, time)</returns>\n /// <exception cref=\"ArgumentException\"></exception>\n public override Tensor forward(Tensor melspec)\n {\n // pack batch\n var shape = melspec.size();\n melspec = melspec.view(-1, shape[shape.Length - 2], shape[shape.Length - 1]);\n\n var n_mels = shape[shape.Length - 2];\n var time = shape[shape.Length - 1];\n var freq = this.fb.size(0); // (freq, n_mels)\n melspec = melspec.transpose(-1, -2);\n if (this.n_mels != n_mels) {\n throw new ArgumentException($\"Expected an input with {this.n_mels} mel bins. Found: {n_mels}\");\n }\n\n var specgram = nn.Parameter(torch.rand(\n melspec.size(0), time, freq, requires_grad: true, dtype: melspec.dtype, device: melspec.device));\n\n var optim = torch.optim.SGD(\n new List<Modules.Parameter> { specgram },\n learningRate: 0.1, momentum: 0.9);\n\n var loss = float.PositiveInfinity;\n for (long i = 0; i < this.max_iter; i++) {\n optim.zero_grad();\n var diff = melspec - specgram.matmul(this.fb);\n var new_loss = diff.pow(2).sum(dim: -1).mean();\n // take sum over mel-frequency then average over other dimensions\n // so that loss threshold is applied par unit timeframe\n new_loss.backward();\n optim.step();\n using (torch.no_grad())\n specgram.set_(specgram.clamp(min: 0));\n\n var new_loss_value = new_loss.item<float>();\n if (new_loss_value < this.tolerance_loss || Math.Abs(loss - new_loss_value) < this.tolerance_change) {\n break;\n }\n loss = new_loss_value;\n }\n\n specgram.requires_grad_(false);\n var specgram_tensor = specgram.clamp(min: 0).transpose(-1, -2);\n\n // unpack batch\n shape[shape.Length - 2] = freq;\n shape[shape.Length - 1] = time;\n specgram_tensor = specgram_tensor.view(shape);\n return specgram_tensor;\n }\n }\n }\n\n public partial class torchaudio\n {\n public partial class transforms\n {\n /// <summary>\n /// Estimate a STFT in normal frequency domain from mel frequency domain.\n /// It minimizes the euclidian norm between the input mel-spectrogram and the product between\n /// the estimated spectrogram and the filter banks using SGD.\n /// </summary>\n /// <param name=\"n_stft\">Number of bins in STFT. See ``n_fft`` in :class:`Spectrogram`.</param>\n /// <param name=\"n_mels\">Number of mel filterbanks.</param>\n /// <param name=\"sample_rate\">Sample rate of audio signal.</param>\n /// <param name=\"f_min\">Minimum frequency.</param>\n /// <param name=\"f_max\">Maximum frequency.</param>\n /// <param name=\"max_iter\">Maximum number of optimization iterations.</param>\n /// <param name=\"tolerance_loss\">Value of loss to stop optimization at.</param>\n /// <param name=\"tolerance_change\">Difference in losses to stop optimization at.</param>\n /// <param name=\"norm\">If 'slaney', divide the triangular mel weights by the width of the mel band (area normalization).</param>\n /// <param name=\"mel_scale\">Scale to use: ``htk`` or ``slaney``.</param>\n /// <returns></returns>\n public static Transforms.InverseMelScale InverseMelScale(\n long n_stft,\n long n_mels = 128,\n long sample_rate = 16000,\n double f_min = 0.0,\n double? f_max = null,\n long max_iter = 100000,\n double tolerance_loss = 1e-05,\n double tolerance_change = 1e-08,\n MelNorm norm = MelNorm.none,\n torchaudio.MelScale mel_scale = torchaudio.MelScale.htk)\n {\n return new Transforms.InverseMelScale(\n \"InverseMelScale\",\n n_stft,\n n_mels,\n sample_rate,\n f_min,\n f_max,\n max_iter,\n tolerance_loss,\n tolerance_change,\n norm,\n mel_scale);\n }\n }\n }\n}" }, { "alpha_fraction": 0.523976743221283, "alphanum_fraction": 0.5435646176338196, "avg_line_length": 48.87557601928711, "blob_id": "8fe05f4dcd57c2692e5e27bc9d344ba7b5c5fef3", "content_id": "134e89a63eecc85729dff5c9d3d64a0b8eaa87f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 10823, "license_type": "permissive", "max_line_length": 169, "num_lines": 217, "path": "/src/TorchVision/Ops/Boxes.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchvision,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/vision/blob/a4f53308b2d0f1aa9191686e326f45c26053f686/torchvision/ops/boxes.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/vision/blob/main/LICENSE\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n\n public static partial class ops\n {\n /// <summary>\n /// Converts boxes from given in_fmt to out_fmt.\n /// Supported in_fmt and out_fmt are:\n ///\n /// 'xyxy': boxes are represented via corners, x1, y1 being top left and x2, y2 being bottom right. This is the format that torchvision utilities expect.\n /// 'xywh' : boxes are represented via corner, width and height, x1, y2 being top left, w, h being width and height.\n /// 'cxcywh' : boxes are represented via centre, width and height, cx, cy being center of box, w, h being width and height.\n /// </summary>\n /// <param name=\"boxes\">Boxes which will be converted</param>\n /// <param name=\"in_fmt\">Input format of given boxes.</param>\n /// <param name=\"out_fmt\">Output format of given boxes.</param>\n /// <returns></returns>\n public static Tensor box_convert(Tensor boxes, BoxFormats in_fmt, BoxFormats out_fmt)\n {\n if (in_fmt == out_fmt) return boxes.clone();\n\n if (in_fmt != BoxFormats.xyxy && out_fmt != BoxFormats.xyxy) {\n boxes = (in_fmt == BoxFormats.xywh) ? _box_xywh_to_xyxy(boxes) : _box_cxcywh_to_xyxy(boxes);\n in_fmt = BoxFormats.xyxy;\n }\n\n if (in_fmt == BoxFormats.xyxy) {\n boxes = (out_fmt == BoxFormats.xywh) ? _box_xyxy_to_xywh(boxes) : _box_xyxy_to_cxcywh(boxes);\n } else if (out_fmt == BoxFormats.xyxy) {\n boxes = (in_fmt == BoxFormats.xywh) ? _box_xywh_to_xyxy(boxes) : _box_cxcywh_to_xyxy(boxes);\n }\n\n return boxes;\n }\n\n /// <summary>\n /// Computes the area of a set of bounding boxes, which are specified by their (x1, y1, x2, y2) coordinates.\n /// </summary>\n /// <param name=\"boxes\">Boxes for which the area will be computed. They are expected to be in (x1, y1, x2, y2) format.</param>\n /// <returns></returns>\n public static Tensor box_area(Tensor boxes)\n {\n boxes = _upcast(boxes);\n return (boxes[colon, 2] - boxes[colon, 0]) * (boxes[colon, 3] - boxes[colon, 1]);\n }\n\n /// <summary>\n /// Return intersection-over-union (Jaccard index) between two sets of boxes.\n /// </summary>\n /// <param name=\"boxes1\">First set of boxes</param>\n /// <param name=\"boxes2\">Second set of boxes</param>\n /// <returns>The NxM matrix containing the pairwise IoU values for every element in boxes1 and boxes2</returns>\n public static Tensor box_iou(Tensor boxes1, Tensor boxes2)\n {\n var inter = _box_inter_union(boxes1, boxes2, out var union);\n return inter / union;\n }\n\n /// <summary>\n /// Return generalized intersection-over-union (Jaccard index) between two sets of boxes.\n /// </summary>\n /// <param name=\"boxes1\">First set of boxes</param>\n /// <param name=\"boxes2\">Second set of boxes</param>\n /// <returns>The NxM matrix containing the pairwise generalized IoU values for every element in boxes1 and boxes2</returns>\n public static Tensor generalized_box_iou(Tensor boxes1, Tensor boxes2)\n {\n using var _ = NewDisposeScope();\n var inter = _box_inter_union(boxes1, boxes2, out var union);\n var iou = inter / union;\n\n var lti = torch.min(boxes1[colon, None, (null, 2)], boxes2[colon, (null, 2)]);\n var rbi = torch.max(boxes1[colon, None, (2, null)], boxes2[colon, (2, null)]);\n\n var whi = _upcast(rbi - lti).clamp(min: 0); // [N,M,2]\n var areai = whi[colon, colon, 0] * whi[colon, colon, 1];\n\n return (iou - (areai - union) / areai).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Return complete intersection-over-union (Jaccard index) between two sets of boxes.\n /// </summary>\n /// <param name=\"boxes1\">First set of boxes</param>\n /// <param name=\"boxes2\">Second set of boxes</param>\n /// <param name=\"eps\">Small number to prevent division by zero</param>\n /// <returns>The NxM matrix containing the complete distance IoU values for every element in boxes1 and boxes2</returns>\n public static Tensor complete_box_iou(Tensor boxes1, Tensor boxes2, double eps = 1e-7)\n {\n using var _ = NewDisposeScope();\n boxes1 = _upcast(boxes1);\n boxes2 = _upcast(boxes2);\n\n var diou = _box_diou_iou(boxes1, boxes2, out Tensor iou, eps);\n\n var w_pred = boxes1[colon, None, 2] - boxes1[colon, None, 0];\n var h_pred = boxes1[colon, None, 3] - boxes1[colon, None, 1];\n\n var w_gt = boxes2[colon, 2] - boxes2[colon, 0];\n var h_gt = boxes2[colon, 3] - boxes2[colon, 1];\n\n var v = (4 / (Math.Pow(Math.PI, 2))) * torch.pow(torch.atan(w_pred / h_pred) - torch.atan(w_gt / h_gt), 2);\n\n Tensor alpha;\n\n using (var ng = torch.no_grad()) {\n alpha = v / (1 - iou + v + eps);\n }\n return (diou - alpha * v).MoveToOuterDisposeScope();\n }\n\n\n /// <summary>\n /// Return generalized intersection-over-union (Jaccard index) between two sets of boxes.\n /// </summary>\n /// <param name=\"boxes1\">First set of boxes</param>\n /// <param name=\"boxes2\">Second set of boxes</param>\n /// <param name=\"eps\">Small number to prevent division by zero</param>\n /// <returns>The NxM matrix containing the pairwise distance IoU values for every element in boxes1 and boxes2</returns>\n public static Tensor distance_box_iou(Tensor boxes1, Tensor boxes2, double eps = 1e-7)\n {\n using var _ = NewDisposeScope();\n boxes1 = _upcast(boxes1);\n boxes2 = _upcast(boxes2);\n var diou = _box_diou_iou(boxes1, boxes2, out var _, eps: eps);\n return diou.MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Compute the bounding boxes around the provided masks.\n /// </summary>\n /// <param name=\"masks\">masks to transform where N is the number of masks and (H, W) are the spatial dimensions.</param>\n /// <returns>A [N, 4] tensor containing bounding boxes. The boxes are in the (x1, y1, x2, y2) format</returns>\n /// <exception cref=\"ArgumentException\">Raised if the input is not a three-dimensional tensor.</exception>\n public static Tensor masks_to_boxes(Tensor masks)\n {\n if (masks.ndim != 3) throw new ArgumentException(\"'masks' should have three dimensions: NxHxW\");\n if (masks.numel() == 0) {\n return torch.zeros(0, 4, device: masks.device, dtype: torch.float32);\n }\n\n var n = masks.shape[0];\n var bounding_boxes = torch.zeros(n, 4, device: masks.device, dtype: torch.float32);\n\n for (int i = 0;i < n; i++) {\n var yx = torch.where(masks[i] != 0);\n bounding_boxes[i, 0] = torch.min(yx[1]);\n bounding_boxes[i, 1] = torch.min(yx[0]);\n bounding_boxes[i, 2] = torch.max(yx[1]);\n bounding_boxes[i, 3] = torch.max(yx[0]);\n }\n return bounding_boxes;\n }\n\n private static Tensor _box_inter_union(Tensor boxes1, Tensor boxes2, out Tensor union)\n {\n var area1 = box_area(boxes1);\n var area2 = box_area(boxes2);\n\n var lt = torch.max(boxes1[colon, None, (null, 2)], boxes2[colon, (null, 2)]); // [N,M,2];\n var rb = torch.min(boxes1[colon, None, (2, null)], boxes2[colon, (2, null)]); // [N,M,2];\n\n var wh = _upcast(rb - lt).clamp(min: 0); // [N,M,2];\n var inter = wh[colon, colon, 0] * wh[colon, colon, 1]; // [N,M];\n\n union = area1[colon, None] + area2 - inter;\n return inter;\n }\n\n private static Tensor _box_diou_iou(Tensor boxes1, Tensor boxes2, out Tensor iou, double eps = 1e-7)\n {\n iou = box_iou(boxes1, boxes2);\n var lti = torch.min(boxes1[colon, None, (null, 2)], boxes2[colon, (null, 2)]);\n var rbi = torch.max(boxes1[colon, None, (2, null)], boxes2[colon, (2, null)]);\n var whi = _upcast(rbi - lti).clamp(min: 0); // [N,M,2];\n var diagonal_distance_squared = whi[colon, colon, 0].pow(2) + whi[colon, colon, 1].pow(2) + eps;\n // centers of boxes\n var x_p = (boxes1[colon, 0] + boxes1[colon, 2]) / 2;\n var y_p = (boxes1[colon, 1] + boxes1[colon, 3]) / 2;\n var x_g = (boxes2[colon, 0] + boxes2[colon, 2]) / 2;\n var y_g = (boxes2[colon, 1] + boxes2[colon, 3]) / 2;\n // The distance between boxes' centers squared.\n var centers_distance_squared = _upcast((x_p[colon, None] - x_g[None, colon])).pow(2) + _upcast((y_p[colon, None] - y_g[None, colon])).pow(2);\n // The distance IoU is the IoU penalized by a normalized\n // distance between boxes' centers squared.\n return iou - (centers_distance_squared / diagonal_distance_squared);\n }\n\n public enum BoxFormats\n {\n xyxy, xywh, cxcywh\n }\n\n private static TensorIndex colon = TensorIndex.Colon;\n private static TensorIndex None = TensorIndex.None;\n }\n }\n}\n" }, { "alpha_fraction": 0.5940752625465393, "alphanum_fraction": 0.6172938346862793, "avg_line_length": 32.53020095825195, "blob_id": "2c92de7a2557dbdcc81b9be1ca2150af183fbbe4", "content_id": "1bf14cab930ead617b095000c7e8e12984aee989", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4996, "license_type": "permissive", "max_line_length": 99, "num_lines": 149, "path": "/test/TorchSharpTest/pyimporttest.py", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "from collections import OrderedDict\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nimport importsd\n\n\nNUM_WORDS = 100\nEMBEDDING_VEC_LEN = 100\nHIDDEN_SIZE = 128\n\n\nclass LSTMModel(nn.Module):\n # The names of properties should be the same in C# and Python\n # otherwise, you have to manually change the key name in the state_dict\n def __init__(self):\n super(LSTMModel, self).__init__()\n self.embedding = nn.Embedding(NUM_WORDS, EMBEDDING_VEC_LEN)\n self.lstm = nn.LSTM(EMBEDDING_VEC_LEN, HIDDEN_SIZE, batch_first=True)\n self.dropout = nn.Dropout(0.5)\n self.dense = nn.Linear(HIDDEN_SIZE, 1)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n x_embed = self.embedding(x)\n x_lstm, _ = self.lstm(x_embed)\n x_lstm_last_seq = x_lstm[:, -1, :]\n x_lstm_last_seq = self.dropout(x_lstm_last_seq)\n logits = self.dense(x_lstm_last_seq)\n out = self.sigmoid(logits)\n return out\n\n\nclass LeNet1Model(nn.Module):\n # The names of properties should be the same in C# and Python\n # in this case, we both name the Sequential as layers\n def __init__(self):\n super(LeNet1Model, self).__init__()\n # the names of each layer should also be the same in C# and Python\n modules = OrderedDict([\n (\"conv-1\", nn.Conv2d(1, 4, 5, padding=2)),\n (\"bnrm2d-1\", nn.BatchNorm2d(4)),\n (\"relu-1\", nn.ReLU()),\n (\"maxpool-1\", nn.MaxPool2d(2, stride=2)),\n (\"conv-2\", nn.Conv2d(4, 12, 5)),\n (\"bnrm2d-2\", nn.BatchNorm2d(12)),\n (\"relu-2\", nn.ReLU()),\n (\"maxpool-2\", nn.MaxPool2d(2, stride=2)),\n (\"flatten\", nn.Flatten()),\n (\"linear\", nn.Linear(300, 10)),\n ])\n self.layers = nn.Sequential(modules)\n\n def forward(self, x):\n return self.layers.forward(x)\n\n\ndef testLSTM():\n print(\"testing LSTM\")\n mylstm = LSTMModel()\n with open(\"lstm.dat\", \"rb\") as f:\n sd = importsd.load_state_dict(f)\n # you can change the loaded key names here, for example:\n # sd = {k + \"py\": v for k, v in sd}\n # you can check the key names of state_dict in python by:\n # print(mylstm.state_dict())\n mylstm.load_state_dict(sd)\n\n # init values & functions\n torch.manual_seed(0)\n np.random.seed(0)\n labels = torch.tensor(np.random.randint(0, 1, [100, 1]), dtype=torch.float)\n inputs = torch.tensor(np.random.randint(0, 100, [100, 100]))\n opt = optim.Adam(mylstm.parameters(), lr=8e-5)\n loss_func = nn.BCELoss()\n\n # evaluation before training\n mylstm.eval()\n preds = mylstm.forward(inputs)\n preds = torch.round(preds)\n correct_num = torch.sum(preds == labels).item()\n print(f\"before training: {correct_num} corrected\")\n\n # training for 50 steps\n mylstm.train()\n for i in range(50):\n opt.zero_grad() # Reset the gradient in every iteration\n outputs = mylstm(inputs)\n loss = loss_func(outputs, labels) # Loss forward pass\n loss.backward() # Loss backaed pass\n opt.step() # Update all the parameters by the given learnig rule\n\n # evaluation after training\n mylstm.eval()\n preds = mylstm.forward(inputs)\n preds = torch.round(preds)\n correct_num = torch.sum(preds == labels).item()\n print(f\"after training: {correct_num} corrected\")\n\n\ndef testLeNet1():\n print(\"testing LeNet1\")\n mylenet = LeNet1Model()\n with open(\"lenet1.dat\", \"rb\") as f:\n sd = importsd.load_state_dict(f)\n # you can change the loaded key names here, for example:\n # sd = {k + \"py\": v for k, v in sd}\n # you can check the key names of state_dict in python by:\n # print(mylenet.state_dict())\n mylenet.load_state_dict(sd)\n\n # init values & functions\n torch.manual_seed(0)\n np.random.seed(0)\n labels = torch.tensor(np.random.randint(0, 10, [100]))\n inputs = torch.tensor(np.random.randint(0, 255, [100, 1, 28, 28]) / 255.0, dtype=torch.float32)\n opt = optim.Adam(mylenet.parameters(), lr=8e-5)\n loss_func = nn.CrossEntropyLoss()\n\n # evaluation before training\n mylenet.eval()\n output = mylenet.forward(inputs)\n _, preds = torch.max(output.data, dim=1)\n correct_num = torch.sum(preds == labels).item()\n print(f\"before training: {correct_num} corrected\")\n\n # training for 200 steps\n mylenet.train()\n for i in range(200):\n opt.zero_grad() # Reset the gradient in every iteration\n outputs = mylenet(inputs)\n loss = loss_func(outputs, labels) # Loss forward pass\n loss.backward() # Loss backaed pass\n opt.step() # Update all the parameters by the given learnig rule\n\n # evaluation after training\n mylenet.eval()\n output = mylenet.forward(inputs)\n _, preds = torch.max(output.data, dim=1)\n correct_num = torch.sum(preds == labels).item()\n print(f\"after training: {correct_num} corrected\")\n\n\nif __name__ == '__main__':\n testLSTM()\n testLeNet1()\n" }, { "alpha_fraction": 0.5116005539894104, "alphanum_fraction": 0.5163080096244812, "avg_line_length": 37.6298713684082, "blob_id": "4e6bfd60bf576dcac142404bfac714616492790b", "content_id": "0e153f7e037a2eff04c00cb6e5aeed9c23bae806", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5948, "license_type": "permissive", "max_line_length": 130, "num_lines": 154, "path": "/src/TorchVision/Randomizer.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class Randomizer : ITransform\n {\n internal Randomizer(ITransform transform, double p = 0.1)\n {\n this.p = p;\n this.transform = transform;\n }\n\n public Tensor call(Tensor input)\n {\n using (var chance = torch.rand(1))\n\n if (chance.item<float>() < p) {\n return transform.call(input);\n } else {\n return input;\n }\n }\n\n private ITransform transform;\n private double p;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Randomly apply a transform given a probability.\n /// </summary>\n /// <param name=\"transform\">The transform that will be applied randomly.</param>\n /// <param name=\"p\">The probablity of applying the transform</param>\n /// <returns></returns>\n /// <remarks>This uses the default TorchSharp RNG.</remarks>\n static public ITransform Randomize(ITransform transform, double p = 0.1)\n {\n return new Randomizer(transform, p);\n }\n\n /// <summary>\n /// Posterize the image randomly with a given probability by reducing the number of bits for each color channel. \n /// </summary>\n /// <param name=\"bits\">Number of bits to keep for each channel (0-8)</param>\n /// <param name=\"p\">Probability of the transform being applied.</param>\n /// <returns></returns>\n /// <remarks>The tensor must be an integer tensor</remarks>\n static public ITransform RandomPosterize(int bits, double p = 0.5)\n {\n return new Randomizer(Posterize(bits), p);\n }\n\n /// <summary>\n /// Equalize the image randomly with a given probability. \n /// </summary>\n /// <param name=\"p\">Probability of the transform being applied.</param>\n /// <returns></returns>\n /// <remarks>The tensor must be an integer tensor</remarks>\n static public ITransform Equalize(double p = 0.5)\n {\n return new Randomizer(Equalize(), p);\n }\n\n /// <summary>\n /// Solarize the image randomly with a given probability by inverting all pixel values above a threshold.\n /// </summary>\n /// <param name=\"threshold\">All pixels equal or above this value are inverted.</param>\n /// <param name=\"p\">Probability of the transform being applied.</param>\n /// <returns></returns>\n static public ITransform RandomSolarize(double threshold, double p = 0.5)\n {\n return new Randomizer(Solarize(threshold), p);\n }\n\n /// <summary>\n /// \n /// </summary>\n /// <param name=\"p\">Probability of the transform being applied.</param>\n /// <returns></returns>\n static public ITransform RandomVerticalFlip(double p = 0.5)\n {\n return new Randomizer(VerticalFlip(), p);\n }\n\n /// <summary>\n /// \n /// </summary>\n /// <param name=\"p\">Probability of the transform being applied.</param>\n /// <returns></returns>\n static public ITransform RandomHorizontalFlip(double p = 0.5)\n {\n return new Randomizer(HorizontalFlip(), p);\n }\n\n /// <summary>\n /// \n /// </summary>\n /// <param name=\"p\">Probability of the transform being applied.</param>\n /// <returns></returns>\n static public ITransform RandomGrayscale(double p = 0.1)\n {\n return new Randomizer(Grayscale(3), p);\n }\n\n /// <summary>\n /// Adjust the sharpness of the image randomly with a given probability. \n /// </summary>\n /// <param name=\"sharpness\">The sharpness factor</param>\n /// <param name=\"p\">Probability of the transform being applied.</param>\n /// <returns></returns>\n static public ITransform RandomAdjustSharpness(double sharpness, double p = 0.5)\n {\n return new Randomizer(AdjustSharpness(sharpness), p);\n }\n\n /// <summary>\n /// \n /// </summary>\n /// <param name=\"p\">Probability of the transform being applied.</param>\n /// <returns></returns>\n static public ITransform RandomAutoContrast(double p = 0.5)\n {\n return new Randomizer(AutoContrast(), p);\n }\n\n /// <summary>\n /// \n /// </summary>\n /// <param name=\"p\">Probability of the transform being applied.</param>\n /// <returns></returns>\n static public ITransform RandomInvert(double p = 0.5)\n {\n return new Randomizer(Invert(), p);\n }\n\n /// <summary>\n /// Apply randomly a list of transformations with a given probability.\n /// </summary>\n /// <param name=\"transforms\">A list of transforms to compose serially.</param>\n /// <param name=\"p\">Probability of the transforms being applied.</param>\n /// <returns></returns>\n static public ITransform RandomApply(ITransform[] transforms, double p = 0.5)\n {\n return new Randomizer(Compose(transforms), p);\n }\n }\n }\n}" }, { "alpha_fraction": 0.5785340070724487, "alphanum_fraction": 0.5785340070724487, "avg_line_length": 24.53333282470703, "blob_id": "850f2d67e96d73c6e54789304ea3903d34539b8a", "content_id": "42d5ee63e86aa67f0b007befdbe432dae9c045ed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 382, "license_type": "permissive", "max_line_length": 130, "num_lines": 15, "path": "/src/TorchAudio/MelScale.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n /// <summary>\n /// Scale type of mel filterbanks\n /// </summary>\n public enum MelScale\n {\n slaney,\n htk\n }\n }\n}" }, { "alpha_fraction": 0.7017045617103577, "alphanum_fraction": 0.7017045617103577, "avg_line_length": 24.214284896850586, "blob_id": "7f197adec0be9a871b7c046cbf103f45f993681c", "content_id": "4505451f652ccebecc58ce450c5a3ba2a18ebbf9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 352, "license_type": "permissive", "max_line_length": 130, "num_lines": 14, "path": "/src/TorchAudio/Transforms/ITransform.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\n\nnamespace TorchSharp\n{\n public partial class torchaudio\n {\n public interface ITransform : IModule<Tensor, Tensor>\n {\n }\n }\n}" }, { "alpha_fraction": 0.6907563209533691, "alphanum_fraction": 0.6941176652908325, "avg_line_length": 26.045454025268555, "blob_id": "f9e25e86405b9b91a2f7adf77f3d9cfca4e24108", "content_id": "740fc71d2a1e639d4cf824d1eee1675c13950f4b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 595, "license_type": "permissive", "max_line_length": 130, "num_lines": 22, "path": "/src/Native/LibTorchSharp/Utils.cpp", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#include \"Utils.h\"\n\n#include <cstring>\n#include <fstream>\n#if _WINDOWS\n#include <combaseapi.h>\n#define TP_CoTaskMemAlloc(t) CoTaskMemAlloc(t)\n#else\n#define TP_CoTaskMemAlloc(t) malloc(t)\n#endif\n\nthread_local char * torch_last_err = nullptr;\n\nconst char * make_sharable_string(const std::string str)\n{\n size_t n = str.length();\n char* result = (char *)TP_CoTaskMemAlloc(n + 1); \n strncpy(result, str.c_str(), n);\n result[n] = '\\0';\n return result;\n}\n" }, { "alpha_fraction": 0.5925925970077515, "alphanum_fraction": 0.595678985118866, "avg_line_length": 31.399999618530273, "blob_id": "3b28b40671e0eaca3666fefca066870f738848b6", "content_id": "8d93f7de1dccb3b78515b0f6d06b3ca4b64b9d17", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 648, "license_type": "permissive", "max_line_length": 130, "num_lines": 20, "path": "/src/Examples/Program.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nnamespace TorchSharp.Examples\n{\n public static class Program\n {\n public static void Main(string[] args)\n {\n //MNIST.Main(args);\n //AdversarialExampleGeneration.Main(args);\n CIFAR10.Main(args);\n //SequenceToSequence.Main(args);\n //TextClassification.Main(args);\n //ImageTransforms.Main(args);\n //SpeechCommands.Main(args);\n IOReadWrite.Main(args);\n Tensorboard.Main(args).Wait();\n }\n }\n}\n" }, { "alpha_fraction": 0.6174419522285461, "alphanum_fraction": 0.621430516242981, "avg_line_length": 52.49214553833008, "blob_id": "9fdcf0e95ca2bb4c20b3e73902726533fce1d061", "content_id": "fb4568b5c73292578f63e34c7406b7e4ec92ddd0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 40897, "license_type": "permissive", "max_line_length": 254, "num_lines": 764, "path": "/src/TorchSharp/Tensor/torch.OtherOperations.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing TorchSharp.PInvoke;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n // https://pytorch.org/docs/stable/torch#other-operations\n public static partial class torch\n {\n // https://pytorch.org/docs/stable/generated/torch.atleast_1d\n /// <summary>\n /// Returns a 1-dimensional view of each input tensor with zero dimensions. Input tensors with one or more dimensions are returned as-is.\n /// </summary>\n public static IEnumerable<Tensor> atleast_1d(params Tensor[] input) => input.Select(t => t.atleast_1d());\n\n // https://pytorch.org/docs/stable/generated/torch.atleast_2d\n /// <summary>\n /// Returns a 2-dimensional view of each input tensor with zero or one dimensions. Input tensors with two or more dimensions are returned as-is.\n /// </summary>\n public static IEnumerable<Tensor> atleast_2d(params Tensor[] input) => input.Select(t => t.atleast_2d());\n\n // https://pytorch.org/docs/stable/generated/torch.atleast_3d\n /// <summary>\n /// Returns a 1-dimensional view of each input tensor with fewer than three dimensions. Input tensors with three or more dimensions are returned as-is.\n /// </summary>\n public static IEnumerable<Tensor> atleast_3d(params Tensor[] input) => input.Select(t => t.atleast_3d());\n\n // https://pytorch.org/docs/stable/generated/torch.bincount\n /// <summary>\n /// Count the frequency of each value in an array of non-negative ints.\n /// </summary>\n public static Tensor bincount(Tensor input, Tensor? weights = null, long minlength = 0) => input.bincount(weights, minlength);\n\n // https://pytorch.org/docs/stable/generated/torch.block_diag\n /// <summary>\n /// Create a block diagonal matrix from provided tensors.\n /// </summary>\n /// <param name=\"tensors\">One or more tensors with 0, 1, or 2 dimensions.</param>\n /// <returns></returns>\n public static Tensor block_diag(params Tensor[] tensors)\n {\n using var parray = new PinnedArray<IntPtr>();\n IntPtr tensorsRef = parray.CreateArray(tensors.Select(p => p.Handle).ToArray());\n\n var res = THSTensor_block_diag(tensorsRef, parray.Array.Length);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.broadcast_tensors\n /// <summary>\n /// Broadcasts the given tensors according to Torch broadcasting semantics.\n /// </summary>\n /// <param name=\"tensors\">Any number of tensors of the same type</param>\n public static IList<Tensor> broadcast_tensors(params Tensor[] tensors)\n {\n if (tensors.Length == 0) {\n throw new ArgumentException(nameof(tensors));\n }\n if (tensors.Length == 1) {\n return tensors;\n }\n\n IntPtr[] ptrArray;\n\n using (var pa = new PinnedArray<IntPtr>())\n using (var parray = new PinnedArray<IntPtr>()) {\n\n IntPtr tensorsRef = parray.CreateArray(tensors.Select(p => p.Handle).ToArray());\n\n THSTensor_broadcast_tensors(tensorsRef, tensors.Length, pa.CreateArray);\n CheckForErrors();\n ptrArray = pa.Array;\n }\n\n return ptrArray.Select(x => new Tensor(x)).ToList();\n }\n\n // https://pytorch.org/docs/stable/generated/torch.broadcast_to\n public static Tensor broadcast_to(Tensor input, params long[] shape) => input.broadcast_to(shape);\n\n // https://pytorch.org/docs/stable/generated/torch.broadcast_shapes\n /// <summary>\n /// This is equivalent to <code>torch.broadcast_tensors(*map(torch.empty, shapes))[0].shape</code>\n /// but avoids the need create to intermediate tensors.\n /// This is useful for broadcasting tensors of common batch shape but different rightmost shape,\n /// e.g. to broadcast mean vectors with covariance matrices.\n /// </summary>\n /// <param name=\"shapes\">Shapes of tensors</param>\n /// <returns>A shape compatible with all input shapes</returns>\n /// <exception cref=\"ArgumentException\">If shapes are incompatible.</exception>\n public static Size broadcast_shapes(params long[][] shapes)\n {\n var max_len = 0;\n foreach (var shape in shapes) {\n var s = shape.Length;\n if (s > max_len) max_len = s;\n }\n\n var result = Enumerable.Repeat<long>(1, max_len).ToArray();\n\n foreach (var shape in shapes) {\n for (var i = shape.Length - 1; i >= 0; i--) {\n if (shape.Length == 0 || shape[i] == 1 || shape[i] == result[i])\n continue;\n if (result[i] != 1)\n throw new ArgumentException(\"Shape mismatch: objects cannot be broadcast to a single shape\");\n result[i] = shape[i];\n }\n }\n return result;\n }\n\n // https://pytorch.org/docs/stable/generated/torch.bucketize\n public static Tensor bucketize(Tensor input, Tensor boundaries, bool outInt32 = false, bool right = false)\n => input.bucketize(boundaries, outInt32, right);\n\n // https://pytorch.org/docs/stable/generated/torch.cartesian_prod\n /// <summary>\n /// Do cartesian product of the given sequence of tensors.\n /// </summary>\n /// <param name=\"tensors\"></param>\n public static Tensor cartesian_prod(IList<Tensor> tensors)\n {\n using var parray = new PinnedArray<IntPtr>();\n IntPtr tensorsRef = parray.CreateArray(tensors.Select(p => p.Handle).ToArray());\n\n var res = THSTensor_cartesian_prod(tensorsRef, parray.Array.Length);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.cartesian_prod\n /// <summary>\n /// Do cartesian product of the given sequence of tensors.\n /// </summary>\n /// <param name=\"tensors\"></param>\n public static Tensor cartesian_prod(params Tensor[] tensors) => cartesian_prod((IList<Tensor>)tensors);\n\n // https://pytorch.org/docs/stable/generated/torch.cdist\n /// <summary>\n /// Computes batched the p-norm distance between each pair of the two collections of row vectors.\n /// </summary>\n /// <param name=\"x1\">Input tensor of shape BxPxM</param>\n /// <param name=\"x2\">Input tensor of shape BxRxM</param>\n /// <param name=\"p\">p value for the p-norm distance to calculate between each vector (p > 0)</param>\n /// <param name=\"compute_mode\">\n /// use_mm_for_euclid_dist_if_necessary - will use matrix multiplication approach to calculate euclidean distance (p = 2) if P > 25 or R > 25\n /// use_mm_for_euclid_dist - will always use matrix multiplication approach to calculate euclidean distance (p = 2)\n /// donot_use_mm_for_euclid_dist - will never use matrix multiplication approach to calculate euclidean distance (p = 2)\n /// </param>\n /// <exception cref=\"ArgumentException\"></exception>\n public static Tensor cdist(\n Tensor x1,\n Tensor x2,\n double p = 2.0,\n compute_mode compute_mode = compute_mode.use_mm_for_euclid_dist_if_necessary)\n {\n if (p < 0)\n throw new ArgumentException($\"p must be non-negative\");\n\n var res = THSTensor_cdist(x1.Handle, x2.Handle, p, (long)compute_mode);\n if (res == IntPtr.Zero)\n CheckForErrors();\n return new Tensor(res);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.clone\n public static Tensor clone(Tensor input) => input.clone();\n\n // https://pytorch.org/docs/stable/generated/torch.combinations\n /// <summary>\n /// Compute combinations of length r of the given tensor\n /// </summary>\n /// <param name=\"input\">1D vector.</param>\n /// <param name=\"r\">Number of elements to combine</param>\n /// <param name=\"with_replacement\">Whether to allow duplication in combination</param>\n /// <returns></returns>\n public static Tensor combinations(Tensor input, int r = 2, bool with_replacement = false)\n {\n if (input.ndim != 1)\n throw new ArgumentException($\"Expected a 1D vector, but got one with {input.ndim} dimensions.\");\n if (r < 0)\n throw new ArgumentException($\"r must be non-negative\");\n\n var res = THSTensor_combinations(input.Handle, r, with_replacement);\n if (res == IntPtr.Zero)\n CheckForErrors();\n return new Tensor(res);\n }\n\n\n\n // https://pytorch.org/docs/stable/generated/torch.corrcoef\n public static Tensor corrcoef(Tensor input) => input.corrcoef();\n\n // https://pytorch.org/docs/stable/generated/torch.cov\n /// <summary>\n /// Estimates the covariance matrix of the variables given by the input matrix, where rows are the variables and columns are the observations.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"correction\">\n /// Difference between the sample size and sample degrees of freedom.\n /// Defaults to Bessel’s correction, correction = 1 which returns the unbiased estimate,\n /// even if both fweights and aweights are specified.\n /// Correction = 0 will return the simple average.\n /// </param>\n /// <param name=\"fweights\">\n /// A Scalar or 1D tensor of observation vector frequencies representing the number of times each observation should be repeated.\n /// Its numel must equal the number of columns of input.\n /// Must have integral dtype.</param>\n /// <param name=\"aweights\">A Scalar or 1D array of observation vector weights.\n /// These relative weights are typically large for observations considered “important” and smaller for\n /// observations considered less “important”.\n /// Its numel must equal the number of columns of input.\n /// Must have floating point dtype.</param>\n public static Tensor cov(Tensor input, long correction = 1, Tensor? fweights = null, Tensor? aweights = null)\n => input.cov(correction, fweights, aweights);\n\n // https://pytorch.org/docs/stable/generated/torch.cross\n /// <summary>\n /// Returns the cross product of vectors in dimension dim of input and other.\n /// input and other must have the same size, and the size of their dim dimension should be 3.\n /// </summary>\n public static Tensor cross(Tensor input, Scalar other, long dim = 0L) => input.cross(other, dim);\n\n // https://pytorch.org/docs/stable/generated/torch.cummax\n public static (Tensor values, Tensor indices) cummax(Tensor input, long dim) => input.cummax(dim);\n\n // https://pytorch.org/docs/stable/generated/torch.cummin\n public static (Tensor values, Tensor indices) cummin(Tensor input, long dim) => input.cummin(dim);\n\n // https://pytorch.org/docs/stable/generated/torch.cumprod\n public static Tensor cumprod(Tensor input, long dim, ScalarType? dtype = null) => input.cumprod(dim, dtype);\n\n // https://pytorch.org/docs/stable/generated/torch.cumsum\n /// <summary>\n /// Returns the cumulative sum of elements of input in the dimension dim.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dim\">The dimension to do the operation over</param>\n /// <param name=\"type\">The desired data type of returned tensor. If specified, the input tensor is casted to dtype before the operation is performed.\n /// This is useful for preventing data type overflows.</param>\n public static Tensor cumsum(Tensor input, long dim, ScalarType? type = null) => input.cumsum(dim, type);\n\n // https://pytorch.org/docs/stable/generated/torch.diag\n /// <summary>\n /// If input is a vector (1-D tensor), then returns a 2-D square tensor with the elements of input as the diagonal.\n /// If input is a matrix (2-D tensor), then returns a 1-D tensor with the diagonal elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"diagonal\">\n /// The argument diagonal controls which diagonal to consider:\n /// If diagonal is 0, it is the main diagonal.\n /// If diagonal is greater than 0, it is above the main diagonal.\n /// If diagonal is less than 0, it is below the main diagonal.\n /// </param>\n public static Tensor diag(Tensor input, long diagonal = 0) => input.diag(diagonal);\n\n // https://pytorch.org/docs/stable/generated/torch.diag_embed\n /// <summary>\n /// Creates a tensor whose diagonals of certain 2D planes (specified by dim1 and dim2) are filled by input.\n /// To facilitate creating batched diagonal matrices, the 2D planes formed by the last two dimensions of the returned tensor are chosen by default.\n ///\n /// The argument offset controls which diagonal to consider:\n /// If offset is equal to 0, it is the main diagonal.\n /// If offset is greater than 0, it is above the main diagonal.\n /// If offset is less than 0, it is below the main diagonal.\n ///\n /// The size of the new matrix will be calculated to make the specified diagonal of the size of the last input dimension.Note that for offset other than 0,\n ///\n /// the order of dim1 and dim2 matters.Exchanging them is equivalent to changing the sign of offset.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"offset\">Which diagonal to consider.</param>\n /// <param name=\"dim1\">First dimension with respect to which to take diagonal. </param>\n /// <param name=\"dim2\">Second dimension with respect to which to take diagonal</param>\n public static Tensor diag_embed(Tensor input, long offset = 0L, long dim1 = -2L, long dim2 = -1L)\n => input.diag_embed(offset, dim1, dim2);\n\n // https://pytorch.org/docs/stable/generated/torch.diagflat\n /// <summary>\n /// If input is a vector (1-D tensor), then returns a 2-D square tensor with the elements of input as the diagonal.\n /// If input is a matrix (2-D tensor), then returns a 2-D tensor with diagonal elements equal to a flattened input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"offset\">\n /// The argument diagonal controls which diagonal to consider:\n /// If diagonal is 0, it is the main diagonal.\n /// If diagonal is greater than 0, it is above the main diagonal.\n /// If diagonal is less than 0, it is below the main diagonal.\n /// </param>\n public static Tensor diagflat(Tensor input, long offset = 0) => input.diagflat(offset);\n\n // https://pytorch.org/docs/stable/generated/torch.diagonal\n /// <summary>\n /// Returns a partial view of input with the its diagonal elements with respect to dim1 and dim2 appended as a dimension at the end of the shape.\n /// The argument offset controls which diagonal to consider:\n ///\n /// If offset == 0, it is the main diagonal.\n /// If offset &gt; 0, it is above the main diagonal.\n /// If offset &lt; 0, it is below the main diagonal.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"offset\">Which diagonal to consider. Default: 0 (main diagonal).</param>\n /// <param name=\"dim1\">First dimension with respect to which to take diagonal. Default: 0.</param>\n /// <param name=\"dim2\">Second dimension with respect to which to take diagonal. Default: 1.</param>\n /// <remarks>\n /// Applying torch.diag_embed() to the output of this function with the same arguments yields a diagonal matrix with the diagonal entries of the input.\n /// However, torch.diag_embed() has different default dimensions, so those need to be explicitly specified.\n /// </remarks>\n public static Tensor diagonal(Tensor input, long offset = 0, long dim1 = 0, long dim2 = 0) => input.diagonal(offset, dim1, dim2);\n\n // https://pytorch.org/docs/stable/generated/torch.diff\n /// <summary>\n /// Computes the n-th forward difference along the given dimension.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"n\">The number of times to recursively compute the difference</param>\n /// <param name=\"dim\">The dimension to compute the difference along. Default is the last dimension.</param>\n /// <param name=\"prepend\">\n /// Values to prepend or append to input along dim before computing the difference.\n /// Their dimensions must be equivalent to that of input, and their shapes must match input’s shape except on dim.\n /// </param>\n /// <param name=\"append\">\n /// Values to prepend or append to input along dim before computing the difference.\n /// Their dimensions must be equivalent to that of input, and their shapes must match input’s shape except on dim.\n /// </param>\n public static Tensor diff(Tensor input, long n = 1, long dim = -1, Tensor? prepend = null, Tensor? append = null) => input.diff(n, dim, prepend, append);\n\n // https://pytorch.org/docs/stable/generated/torch.einsum\n /// <summary>\n /// Sums the product of the elements of the input operands along dimensions specified using a notation based on the Einstein summation convention.\n /// </summary>\n /// <param name=\"equation\">The subscripts for the Einstein summation.</param>\n /// <param name=\"tensors\">The operands to compute the Einstein sum of.</param>\n /// <remarks>\n /// Einsum allows computing many common multi-dimensional linear algebraic array operations by representing them in a short-hand format based on the\n /// Einstein summation convention, given by equation.The details of this format are described below, but the general idea is to label every dimension\n /// of the input operands with some subscript and define which subscripts are part of the output. The output is then computed by summing the product\n /// of the elements of the operands along the dimensions whose subscripts are not part of the output.For example, matrix multiplication can be computed\n /// using einsum as torch.einsum(“ij,jk->ik”, A, B). Here, j is the summation subscript and i and k the output subscripts(see section below for more details on why).\n /// </remarks>\n /// <returns></returns>\n public static Tensor einsum(string equation, params Tensor[] tensors)\n {\n using var parray = new PinnedArray<IntPtr>();\n IntPtr tensorsRef = parray.CreateArray(tensors.Select(p => p.Handle).ToArray());\n\n var res = THSTensor_einsum(equation, tensorsRef, parray.Array.Length);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.flatten\n /// <summary>\n /// Flattens input by reshaping it into a one-dimensional tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"start_dim\">The first dim to flatten</param>\n /// <param name=\"end_dim\">The last dim to flatten.</param>\n /// <remarks>Flattening a zero-dimensional tensor will return a one-dimensional view.</remarks>\n public static Tensor flatten(Tensor input, long start_dim = 0, long end_dim = -1) => input.flatten(start_dim, end_dim);\n\n // https://pytorch.org/docs/stable/generated/torch.flip\n public static Tensor flip(Tensor input, params long[] dims) => input.flip(dims);\n\n // https://pytorch.org/docs/stable/generated/torch.fliplr\n public static Tensor fliplr(Tensor input) => input.fliplr();\n\n // https://pytorch.org/docs/stable/generated/torch.flipud\n public static Tensor flipud(Tensor input) => input.flipud();\n\n // https://pytorch.org/docs/stable/generated/torch.kron\n /// <summary>\n /// Computes the Kronecker product of input and other.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"other\">The second tensor</param>\n public static Tensor kron(Tensor input, Tensor other) => input.kron(other);\n\n // https://pytorch.org/docs/stable/generated/torch.rot90\n /// <summary>\n /// Rotate a n-D tensor by 90 degrees in the plane specified by dims axis.\n /// Rotation direction is from the first towards the second axis if k is greater than 0,\n /// and from the second towards the first for k less than 0.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"k\">The number of times to rotate.</param>\n /// <param name=\"dims\">Axes to rotate</param>\n public static Tensor rot90(Tensor input, long k = 1, (long, long)? dims = null) => input.rot90(k, dims);\n\n // https://pytorch.org/docs/stable/generated/torch.gcd\n /// <summary>\n /// Computes the element-wise greatest common divisor (GCD) of input and other.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor gcd(Tensor left, Tensor right) => left.gcd(right);\n\n // https://pytorch.org/docs/stable/generated/torch.gcd\n /// <summary>\n /// Computes the element-wise greatest common divisor (GCD) of input and other.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor gcd_(Tensor left, Tensor right) => left.gcd_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.histc\n /// <summary>\n /// Computes the histogram of a tensor.\n /// The elements are sorted into equal width bins between min and max.If min and max are both zero, the minimum and maximum values of the data are used.\n /// Elements lower than min and higher than max are ignored.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"bins\">Number of histogram bins</param>\n /// <param name=\"min\">Lower end of the range (inclusive)</param>\n /// <param name=\"max\">Upper end of the range (inclusive)</param>\n public static Tensor histc(Tensor input, long bins = 100, long min = 0, long max = 0) => input.histc(bins, min, max);\n\n // https://pytorch.org/docs/stable/generated/torch.histogram\n [Obsolete(\"not implemented\", true)]\n static Tensor histogram(\n Tensor input,\n long bins,\n (float min, float max)? range = null,\n Tensor? weight = null,\n bool density = false)\n => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.histogram\n [Obsolete(\"not implemented\", true)]\n static Tensor histogram(\n Tensor input,\n long[] bins,\n (float min, float max)? range = null,\n Tensor? weight = null,\n bool density = false)\n => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.histogram\n [Obsolete(\"not implemented\", true)]\n static Tensor histogram(\n Tensor input,\n Tensor[] bins,\n (float min, float max)? range = null,\n Tensor? weight = null,\n bool density = false)\n => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.histogramdd\n [Obsolete(\"not implemented\", true)]\n static (Tensor hist_values, Tensor[] edges) histogramdd(\n Tensor input,\n long bins,\n (float min, float max)? range = null,\n Tensor? weight = null,\n bool density = false)\n => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.histogramdd\n [Obsolete(\"not implemented\", true)]\n static (Tensor hist_values, Tensor[] edges) histogramdd(\n Tensor input,\n long[] bins,\n (float min, float max)? range = null,\n Tensor? weight = null,\n bool density = false)\n => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.histogramdd\n [Obsolete(\"not implemented\", true)]\n static (Tensor hist_values, Tensor[] edges) histogramdd(\n Tensor input,\n Tensor[] bins,\n (float min, float max)? range = null,\n Tensor? weight = null,\n bool density = false)\n => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.meshgrid\n /// <summary>\n /// Creates grids of coordinates specified by the 1D inputs in tensors.\n /// This is helpful when you want to visualize data over some range of inputs.\n /// </summary>\n /// <returns></returns>\n /// <remarks>All tensors need to be of the same size.</remarks>\n static IEnumerable<Tensor> meshgrid(IEnumerable<Tensor> tensors, indexing indexing = indexing.ij)\n {\n var idx = indexing switch {\n indexing.ij => \"ij\",\n indexing.xy => \"xy\",\n _ => throw new ArgumentOutOfRangeException()\n };\n return meshgrid(tensors, idx);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.meshgrid\n /// <summary>\n /// Creates grids of coordinates specified by the 1D inputs in tensors.\n /// This is helpful when you want to visualize data over some range of inputs.\n /// </summary>\n /// <returns></returns>\n /// <remarks>All tensors need to be of the same size.</remarks>\n public static Tensor[] meshgrid(IEnumerable<Tensor> tensors, string indexing = \"ij\")\n {\n IntPtr[] ptrArray;\n\n using (var parray = new PinnedArray<IntPtr>()) {\n IntPtr tensorsRef = parray.CreateArray(tensors.Select(p => p.Handle).ToArray());\n _ = THSTensor_meshgrid(tensorsRef, parray.Array.Length, indexing, parray.CreateArray);\n CheckForErrors();\n ptrArray = parray.Array;\n }\n return ptrArray.Select(x => new Tensor(x)).ToArray();\n }\n\n // https://pytorch.org/docs/stable/generated/torch.lcm\n /// <summary>\n /// Computes the element-wise least common multiple (LCM) of input and other.\n /// </summary>\n /// <param name=\"input\">The first input tensor.</param>\n /// <param name=\"other\">The second input tensor.</param>\n /// <remarks>Both input and other must have integer types.</remarks>\n public static Tensor lcm(Tensor input, Tensor other) => input.lcm(other);\n\n // https://pytorch.org/docs/stable/generated/torch.lcm\n /// <summary>\n /// Computes the element-wise least common multiple (LCM) of input and other in place.\n /// </summary>\n /// <param name=\"input\">The first input tensor.</param>\n /// <param name=\"other\">The second input tensor.</param>\n /// <remarks>Both input and other must have integer types.</remarks>\n public static Tensor lcm_(Tensor input, Tensor other) => input.lcm_(other);\n\n // https://pytorch.org/docs/stable/generated/torch.logcumsumexp\n /// <summary>\n /// Returns the logarithm of the cumulative summation of the exponentiation of elements of input in the dimension dim.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dim\">The dimension to do the operation over</param>\n public static Tensor logcumsumexp(Tensor input, long dim) => input.logcumsumexp(dim);\n\n // https://pytorch.org/docs/stable/generated/torch.ravel\n public static Tensor ravel(Tensor input) => input.ravel();\n\n // https://pytorch.org/docs/stable/generated/torch.renorm\n /// <summary>\n /// Returns a tensor where each sub-tensor of input along dimension dim is normalized such that the p-norm of the sub-tensor is lower than the value maxnorm\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"p\">The power for the norm computation</param>\n /// <param name=\"dim\">The dimension to slice over to get the sub-tensors</param>\n /// <param name=\"maxnorm\">The maximum norm to keep each sub-tensor under</param>\n public static Tensor renorm(Tensor input, float p, long dim, float maxnorm) => input.renorm(p, dim, maxnorm);\n\n // https://pytorch.org/docs/stable/generated/torch.repeat_interleave\n /// <summary>\n /// Repeat elements of a tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"repeats\">The number of repeats</param>\n /// <param name=\"dim\">The dimension to repeat</param>\n /// <param name=\"output_size\">The size of output</param>\n /// <returns></returns>\n public static Tensor repeat_interleave(Tensor input, long repeats, long? dim = null, long? output_size = null) => input.repeat_interleave(repeats, dim, output_size);\n\n // https://pytorch.org/docs/stable/generated/torch.repeat_interleave\n /// <summary>\n /// Repeat elements of a tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"repeats\">The number of repeats</param>\n /// <param name=\"dim\">The dimension to repeat</param>\n /// <param name=\"output_size\">The size of output</param>\n /// <returns></returns>\n public static Tensor repeat_interleave(Tensor input, Tensor repeats, long? dim = null, long? output_size = null) => input.repeat_interleave(repeats, dim, output_size);\n\n // https://pytorch.org/docs/stable/generated/torch.roll\n /// <summary>\n /// Roll the tensor along the given dimension(s).\n /// Elements that are shifted beyond the last position are re-introduced at the first position.\n /// If a dimension is not specified, the tensor will be flattened before rolling and then restored to the original shape.\n /// </summary>\n public static Tensor roll(Tensor input, long shifts, long? dims = null) => input.roll(shifts, dims);\n\n // https://pytorch.org/docs/stable/generated/torch.roll\n /// <summary>\n /// Roll the tensor along the given dimension(s).\n /// Elements that are shifted beyond the last position are re-introduced at the first position.\n /// If a dimension is not specified, the tensor will be flattened before rolling and then restored to the original shape.\n /// </summary>\n public static Tensor roll(Tensor input, (long, long) shifts, (long, long) dims) => input.roll(shifts, dims);\n\n // https://pytorch.org/docs/stable/generated/torch.roll\n /// <summary>\n /// Roll the tensor along the given dimension(s).\n /// Elements that are shifted beyond the last position are re-introduced at the first position.\n /// If a dimension is not specified, the tensor will be flattened before rolling and then restored to the original shape.\n /// </summary>\n public static Tensor roll(Tensor input, (long, long, long) shifts, (long, long, long) dims) => input.roll(shifts, dims);\n\n // https://pytorch.org/docs/stable/generated/torch.roll\n /// <summary>\n /// Roll the tensor along the given dimension(s).\n /// Elements that are shifted beyond the last position are re-introduced at the first position.\n /// If a dimension is not specified, the tensor will be flattened before rolling and then restored to the original shape.\n /// </summary>\n public static Tensor roll(Tensor input, long[] shifts, long[] dims) => input.roll(shifts, dims);\n\n // https://pytorch.org/docs/stable/generated/torch.roll\n /// <summary>\n /// Roll the tensor along the given dimension(s).\n /// Elements that are shifted beyond the last position are re-introduced at the first position.\n /// If a dimension is not specified, the tensor will be flattened before rolling and then restored to the original shape.\n /// </summary>\n public static Tensor roll(Tensor input, long[] shifts) => input.roll(shifts);\n\n // https://pytorch.org/docs/stable/generated/torch.roll\n /// <summary>\n /// Roll the tensor along the given dimension(s).\n /// Elements that are shifted beyond the last position are re-introduced at the first position.\n /// If a dimension is not specified, the tensor will be flattened before rolling and then restored to the original shape.\n /// </summary>\n public static Tensor roll(Tensor input, ReadOnlySpan<long> shifts, ReadOnlySpan<long> dims = default) => input.roll(shifts, dims);\n\n // https://pytorch.org/docs/stable/generated/torch.tensordot\n /// <summary>\n /// Returns a contraction of <paramref name=\"a\"/> and <paramref name=\"b\"/> over multiple dimensions.\n /// tensordot implements a generalized matrix product.\n /// </summary>\n /// <param name=\"a\">Left tensor to contract</param>\n /// <param name=\"b\">Right tensor to contract</param>\n /// <param name=\"dims\">number of dimensions to contract for <paramref name=\"a\"/> and <paramref name=\"b\"/></param>\n /// <returns>contraction</returns>\n public static Tensor tensordot(Tensor a, Tensor b, long dims = 2) => a.tensordot(b, dims);\n\n // https://pytorch.org/docs/stable/generated/torch.tensordot\n /// <summary>\n /// Returns a contraction of <paramref name=\"a\"/> and <paramref name=\"b\"/> over multiple dimensions.\n /// tensordot implements a generalized matrix product.\n /// </summary>\n /// <param name=\"a\">Left tensor to contract</param>\n /// <param name=\"b\">Right tensor to contract</param>\n /// <param name=\"dims1\">dimensions to contract for <paramref name=\"a\"/></param>\n /// <param name=\"dims2\">dimensions to contract for <paramref name=\"b\"/></param>\n /// <returns>contraction</returns>\n public static Tensor tensordot(Tensor a, Tensor b, long[] dims1, long[] dims2) => a.tensordot(b, dims1, dims2);\n\n // https://pytorch.org/docs/stable/generated/torch.tensordot\n /// <summary>\n /// Returns a contraction of <paramref name=\"a\"/> and <paramref name=\"b\"/> over multiple dimensions.\n /// tensordot implements a generalized matrix product.\n /// </summary>\n /// <param name=\"a\">Left tensor to contract</param>\n /// <param name=\"b\">Right tensor to contract</param>\n /// <param name=\"dims\">dimensions to contract for <paramref name=\"a\"/> and <paramref name=\"b\"/> respectively</param>\n /// <returns>contraction</returns>\n public static Tensor tensordot(Tensor a, Tensor b, (long, long)[] dims) => a.tensordot(b, dims);\n\n // https://pytorch.org/docs/stable/generated/torch.trace\n /// <summary>\n /// Returns the sum of the elements of the diagonal of the input 2-D matrix.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor trace(Tensor input) => input.trace();\n\n // https://pytorch.org/docs/stable/generated/torch.tril\n public static Tensor tril(Tensor input, long diagonal = 0) => input.tril(diagonal);\n\n public static Tensor tril_(Tensor input, long diagonal = 0) => input.tril_(diagonal);\n\n // https://pytorch.org/docs/stable/generated/torch.tril_indices\n public static Tensor tril_indices(\n long row,\n long col,\n long offset = 0L,\n ScalarType dtype = ScalarType.Int64,\n Device? device = null)\n {\n if (!torch.is_integral(dtype))\n throw new ArgumentException(\"dtype must be integral.\");\n\n if (device == null) {\n device = torch.CPU;\n }\n\n var res = NativeMethods.THSTensor_tril_indices(row, col, offset, (sbyte)dtype, (int)device.type, device.index);\n if (res == IntPtr.Zero)\n CheckForErrors();\n return new Tensor(res);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.triu\n public static Tensor triu(Tensor input, long diagonal = 0L) => input.triu(diagonal);\n\n public static Tensor triu_(Tensor input, long diagonal = 0L) => input.triu_(diagonal);\n\n // https://pytorch.org/docs/stable/generated/torch.triu_indices\n public static Tensor triu_indices(\n long row,\n long col,\n long offset = 0L,\n ScalarType dtype = ScalarType.Int64,\n Device? device = null)\n {\n if (!torch.is_integral(dtype))\n throw new ArgumentException(\"dtype must be integral.\");\n\n if (device == null) {\n device = torch.CPU;\n }\n\n var res = NativeMethods.THSTensor_triu_indices(row, col, offset, (sbyte)dtype, (int)device.type, device.index);\n if (res == IntPtr.Zero)\n CheckForErrors();\n return new Tensor(res);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.vander\n public static Tensor vander(Tensor x, long N = -1, bool increasing = false) => x.vander(N, increasing);\n\n // https://pytorch.org/docs/stable/generated/torch.view_as_real\n /// <summary>\n /// Returns a view of input as a real tensor.\n /// For an input complex tensor of size m1, m2, …, mi, this function returns a new real tensor of size m1, m2, …, mi, 2, where the last dimension of size 2 represents the real and imaginary components of complex numbers.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n public static Tensor view_as_real(Tensor input) => input.view_as_real();\n\n // https://pytorch.org/docs/stable/generated/torch.view_as_complex\n /// <summary>\n /// Returns a view of input as a complex tensor.\n /// For an input complex tensor of size m1, m2, …, mi, 2, this function returns a new complex tensor of size m1, m2, …, mi where the last dimension of the input tensor is expected to represent the real and imaginary components of complex numbers.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n public static Tensor view_as_complex(Tensor input) => input.view_as_complex();\n\n // https://pytorch.org/docs/stable/generated/torch.resolve_conj\n /// <summary>\n /// Returns a new tensor with materialized conjugation if input’s conjugate bit is set to True, else returns input.\n /// The output tensor will always have its conjugate bit set to False.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor resolve_conj(Tensor input) => input.resolve_conj();\n\n // https://pytorch.org/docs/stable/generated/torch.resolve_neg\n /// <summary>\n /// Returns a new tensor with materialized negation if input’s negative bit is set to True, else returns input.\n /// The output tensor will always have its negative bit set to False.\n /// </summary>\n public static Tensor resolve_neg(Tensor input) => input.resolve_neg();\n\n /// <summary>\n /// Returns true if the input's negative bit is set to True.\n /// </summary>\n public static Tensor is_neg(Tensor input) => input.is_neg();\n }\n}" }, { "alpha_fraction": 0.668683648109436, "alphanum_fraction": 0.6760084629058838, "avg_line_length": 37.448978424072266, "blob_id": "756fb9fdb47cc2aa7f658aed5896b784fbdc41e1", "content_id": "5bb6d76619f601b1f67ab57fb823fbe53563bd27", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9420, "license_type": "permissive", "max_line_length": 224, "num_lines": 245, "path": "/src/Native/LibTorchSharp/THSLoss.cpp", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#include \"THSNN.h\"\n\n#include <torch/nn/init.h>\n\n\ntemplate<typename T>\nvoid ApplyReduction(T& opts, const int64_t reduction)\n{\n if (reduction == 0)\n opts = opts.reduction(torch::kNone);\n if (reduction == 1)\n opts = opts.reduction(torch::kMean);\n if (reduction == 2)\n opts = opts.reduction(torch::kSum);\n}\n\nTensor THSNN_binary_cross_entropy(const Tensor input, const Tensor target, const Tensor weight, const int64_t reduction)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::BinaryCrossEntropyFuncOptions();\n ApplyReduction(opts, reduction);\n if (weight != nullptr)\n opts = opts.weight(*weight);\n res = ResultTensor(torch::nn::functional::binary_cross_entropy(*input, *target, opts));\n )\n}\n\nTensor THSNN_binary_cross_entropy_with_logits(const Tensor input, const Tensor target, const Tensor weight, const int64_t reduction, const Tensor pos_weights_wrapper)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::BCEWithLogitsLossOptions();\n ApplyReduction(opts, reduction);\n if (pos_weights_wrapper != nullptr)\n opts = opts.pos_weight(*pos_weights_wrapper);\n if (weight != nullptr)\n opts = opts.weight(*weight);\n res = ResultTensor(torch::nn::functional::binary_cross_entropy_with_logits(*input, *target, opts));\n )\n}\n\nTensor THSNN_cosine_embedding_loss(const Tensor input1, const Tensor input2, const Tensor target, const double margin, const int64_t reduction)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::CosineEmbeddingLossFuncOptions().margin(margin);\n ApplyReduction(opts, reduction);\n res = ResultTensor(torch::nn::functional::cosine_embedding_loss(*input1, *input2, *target, opts));\n )\n}\n\nTensor THSNN_cross_entropy(const Tensor input, const Tensor target, const Tensor weight, const int64_t ignore_index, const bool has_ii, const int64_t reduction, const double smoothing)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::CrossEntropyFuncOptions();\n ApplyReduction(opts, reduction);\n opts.label_smoothing(smoothing);\n if (has_ii)\n opts = opts.ignore_index(ignore_index);\n if (weight != nullptr)\n opts = opts.weight(*weight);\n res = ResultTensor(torch::nn::functional::cross_entropy(*input, *target, opts));\n )\n}\n\nTensor THSNN_hinge_embedding_loss(const Tensor input, const Tensor target, const double margin, const int64_t reduction)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::HingeEmbeddingLossFuncOptions().margin(margin);\n ApplyReduction(opts, reduction);\n res = ResultTensor(torch::nn::functional::hinge_embedding_loss(*input, *target, opts));\n )\n}\n\nTensor THSNN_huber_loss(const Tensor input, const Tensor target, const double delta, const int64_t reduction)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::HuberLossFuncOptions().delta(delta);\n ApplyReduction(opts, reduction);\n res = ResultTensor(torch::nn::functional::huber_loss(*input, *target, opts));\n )\n}\n\n\nTensor THSNN_kl_div_loss(const Tensor input, const Tensor target, const int64_t reduction, const bool log_target)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::KLDivFuncOptions().log_target(log_target);\n ApplyReduction(opts, reduction);\n\n res = ResultTensor(torch::nn::functional::kl_div(*input, *target, opts));\n )\n}\n\nTensor THSNN_l1_loss(const Tensor input, const Tensor target, const int64_t reduction)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::MSELossFuncOptions();\n ApplyReduction(opts, reduction);\n\n res = ResultTensor(torch::nn::functional::mse_loss(*input, *target, opts));\n )\n}\n\nTensor THSNN_margin_ranking_loss(const Tensor input1, const Tensor input2, const Tensor target, const double margin, const int64_t reduction)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::MarginRankingLossFuncOptions().margin(margin);\n ApplyReduction(opts, reduction);\n res = ResultTensor(torch::nn::functional::margin_ranking_loss(*input1, *input2, *target, opts));\n )\n}\n\nTensor THSNN_mse_loss(const Tensor input, const Tensor target, const int64_t reduction)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::MSELossFuncOptions();\n ApplyReduction(opts, reduction);\n\n res = ResultTensor(torch::nn::functional::mse_loss(*input, *target, opts));\n )\n}\n\nTensor THSNN_nll_loss(const Tensor input, const Tensor target, const Tensor weight, const int64_t reduction)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::NLLLossFuncOptions();\n ApplyReduction(opts, reduction);\n if (weight != nullptr)\n opts = opts.weight(*weight);\n\n res = ResultTensor(torch::nn::functional::nll_loss(*input, *target, opts));\n )\n}\n\nTensor THSNN_poisson_loss(const Tensor input, const Tensor target, const bool logInput, const bool full, const double eps, const int64_t reduction)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::PoissonNLLLossFuncOptions().log_input(logInput).full(full).eps(eps);\n ApplyReduction(opts, reduction);\n\n res = ResultTensor(torch::nn::functional::poisson_nll_loss(*input, *target, opts));\n )\n}\n\nTensor THSNN_smooth_l1_loss(const Tensor input, const Tensor target, const int64_t reduction, const double beta)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::SmoothL1LossFuncOptions();\n ApplyReduction(opts, reduction);\n\n res = ResultTensor(torch::nn::functional::smooth_l1_loss(*input, *target, opts, beta));\n )\n}\n\nTensor THSNN_soft_margin_loss(const Tensor input, const Tensor target, const int64_t reduction)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::SoftMarginLossFuncOptions();\n ApplyReduction(opts, reduction);\n\n res = ResultTensor(torch::nn::functional::soft_margin_loss(*input, *target, opts));\n )\n}\n\nTensor THSNN_ctc_loss(const Tensor log_probs, const Tensor targets, const Tensor input_lengths, const Tensor target_lengths, int64_t blank, bool zero_infinity, const int64_t reduction)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::CTCLossFuncOptions().blank(blank).zero_infinity(zero_infinity);\n ApplyReduction(opts, reduction);\n\n res = ResultTensor(torch::nn::functional::ctc_loss(*log_probs, *targets, *input_lengths, *target_lengths, opts));\n )\n}\n\nTensor THSNN_multilabel_margin_loss(const Tensor input, const Tensor target, const int64_t reduction)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::MultilabelMarginLossFuncOptions();\n ApplyReduction(opts, reduction);\n\n res = ResultTensor(torch::nn::functional::multilabel_margin_loss(*input, *target, opts));\n )\n}\n\nTensor THSNN_multilabel_soft_margin_loss(const Tensor input, const Tensor target, const Tensor weight, const int64_t reduction)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::MultilabelSoftMarginLossFuncOptions();\n ApplyReduction(opts, reduction);\n if (weight != nullptr)\n opts = opts.weight(*weight);\n\n res = ResultTensor(torch::nn::functional::multilabel_soft_margin_loss(*input, *target, opts));\n )\n}\n\nTensor THSNN_multi_margin_loss(const Tensor input, const Tensor target, const int64_t p, const double margin, const Tensor weight, const int64_t reduction)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::MultiMarginLossFuncOptions()\n .p(p)\n .margin(margin);\n ApplyReduction(opts, reduction);\n if (weight != nullptr)\n opts = opts.weight(*weight);\n\n res = ResultTensor(torch::nn::functional::multi_margin_loss(*input, *target, opts));\n )\n}\n\nTensor THSNN_triplet_margin_loss(const Tensor anchor, const Tensor positive, const Tensor negative, double margin, int64_t p, double eps, bool swap, const int64_t reduction)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::TripletMarginLossFuncOptions()\n .p(p)\n .eps(eps)\n .margin(margin)\n .swap(swap);\n ApplyReduction(opts, reduction);\n\n res = ResultTensor(torch::nn::functional::triplet_margin_loss(*anchor, *positive, *negative, opts));\n )\n}\n\nTensor THSNN_triplet_margin_with_distance_loss(const Tensor anchor, const Tensor positive, const Tensor negative, Tensor(*distance_function)(const Tensor x, const Tensor y), double margin, bool swap, const int64_t reduction)\n{\n CATCH_RETURN_Tensor(\n auto opts = torch::nn::functional::TripletMarginWithDistanceLossFuncOptions()\n .margin(margin)\n .swap(swap);\n\n ApplyReduction(opts, reduction);\n\n if (distance_function != nullptr) {\n opts = opts.distance_function(\n [=](const at::Tensor& x, const at::Tensor& y) -> const at::Tensor& {\n auto x1 = ResultTensor(x);\n auto y1 = ResultTensor(y);\n return *distance_function(x1, y1);\n });\n }\n\n res = ResultTensor(torch::nn::functional::triplet_margin_with_distance_loss(*anchor, *positive, *negative, opts));\n )\n}\n" }, { "alpha_fraction": 0.6013590097427368, "alphanum_fraction": 0.601925253868103, "avg_line_length": 35.79166793823242, "blob_id": "c930e90ec5bec98691f0c32da6c8193f72f3a84c", "content_id": "7296a52a14c582cf2428d250f63f3215fede9115", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1766, "license_type": "permissive", "max_line_length": 130, "num_lines": 48, "path": "/src/TorchSharp/NN/Identity.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n public sealed class Identity : torch.nn.Module<Tensor, Tensor>\n {\n internal Identity(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_Identity_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// A placeholder identity operator.\n /// </summary>\n /// <returns>The same tensor as is input.</returns>\n public static Identity Identity()\n {\n var res = THSNN_Identity_ctor(out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Identity(res, boxedHandle);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5044258832931519, "alphanum_fraction": 0.5215146541595459, "avg_line_length": 36.311927795410156, "blob_id": "9b952b0b986168d478b2a5b4a70fac663b9c9120", "content_id": "215e4f74d52b55e633c8ae1d8847ff95cedcd414", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8134, "license_type": "permissive", "max_line_length": 197, "num_lines": 218, "path": "/src/Examples/CIFAR10.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Diagnostics;\nusing static TorchSharp.torch.nn;\nusing static TorchSharp.torch.nn.functional;\nusing static TorchSharp.torch.utils.data;\n\nnamespace TorchSharp.Examples\n{\n /// <summary>\n /// Driver for various models trained and evaluated on the CIFAR10 small (32x32) color image data set.\n /// </summary>\n /// <remarks>\n /// The dataset for this example can be found at: https://www.cs.toronto.edu/~kriz/cifar.html\n /// Download the binary file, and place it in a dedicated folder, e.g. 'CIFAR10,' then edit\n /// the '_dataLocation' definition below to point at the right folder.\n ///\n /// Note: so far, CIFAR10 is supported, but not CIFAR100.\n /// </remarks>\n class CIFAR10\n {\n private static int _epochs = 8;\n private static int _trainBatchSize = 64;\n private static int _testBatchSize = 128;\n\n private readonly static int _logInterval = 25;\n private readonly static int _numClasses = 100;\n\n private readonly static int _timeout = 3600; // One hour by default.\n\n internal static void Main(string[] args)\n {\n var datasetPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n\n torch.random.manual_seed(1);\n\n var device =\n // This worked on a GeForce RTX 2080 SUPER with 8GB, for all the available network architectures.\n // It may not fit with less memory than that, but it's worth modifying the batch size to fit in memory.\n torch.cuda.is_available() ? torch.CUDA :\n torch.CPU;\n\n if (device.type == DeviceType.CUDA) {\n _trainBatchSize *= 8;\n _testBatchSize *= 8;\n _epochs *= 16;\n }\n\n var modelName = args.Length > 0 ? args[0] : \"AlexNet\";\n var epochs = args.Length > 1 ? int.Parse(args[1]) : _epochs;\n var timeout = args.Length > 2 ? int.Parse(args[2]) : _timeout;\n\n Console.WriteLine();\n Console.WriteLine($\"\\tRunning {modelName} with CIFAR100 on {device.type.ToString()} for {epochs} epochs, terminating after {TimeSpan.FromSeconds(timeout)}.\");\n Console.WriteLine();\n\n Console.WriteLine($\"\\tCreating the model...\");\n\n Module<torch.Tensor, torch.Tensor> model = null;\n\n switch (modelName.ToLower()) {\n case \"alexnet\":\n model = new AlexNet(modelName, _numClasses, device);\n break;\n case \"mobilenet\":\n model = new MobileNet(modelName, _numClasses, device);\n break;\n case \"vgg11\":\n case \"vgg13\":\n case \"vgg16\":\n case \"vgg19\":\n model = new VGG(modelName, _numClasses, device);\n break;\n case \"resnet18\":\n model = ResNet.ResNet18(_numClasses, device);\n break;\n case \"resnet34\":\n _testBatchSize /= 4;\n model = ResNet.ResNet34(_numClasses, device);\n break;\n case \"resnet50\":\n _trainBatchSize /= 6;\n _testBatchSize /= 8;\n model = ResNet.ResNet50(_numClasses, device);\n break;\n#if false\n // The following is disabled, because they require big CUDA processors in order to run.\n case \"resnet101\":\n _trainBatchSize /= 6;\n _testBatchSize /= 8;\n model = ResNet.ResNet101(_numClasses, device);\n break;\n case \"resnet152\":\n _testBatchSize /= 4;\n model = ResNet.ResNet152(_numClasses, device);\n break;\n#endif\n }\n\n Console.WriteLine($\"\\tPreparing training and test data...\");\n Console.WriteLine();\n\n using (Dataset train_data = torchvision.datasets.CIFAR100(datasetPath, true, download: true),\n test_data = torchvision.datasets.CIFAR100(datasetPath, false, download: true))\n {\n using var train = new DataLoader(train_data, _trainBatchSize, device: device, shuffle: true);\n using var test = new DataLoader(test_data, _testBatchSize, device: device, shuffle: false);\n\n using (var optimizer = torch.optim.Adam(model.parameters(), 0.001)) {\n\n Stopwatch totalSW = new Stopwatch();\n totalSW.Start();\n\n for (var epoch = 1; epoch <= epochs; epoch++) {\n\n Stopwatch epchSW = new Stopwatch();\n epchSW.Start();\n\n Train(model, optimizer, torch.nn.NLLLoss(), train, epoch, _trainBatchSize, train_data.Count);\n Test(model, torch.nn.NLLLoss(), test, test_data.Count);\n\n epchSW.Stop();\n Console.WriteLine($\"Elapsed time for this epoch: {epchSW.Elapsed.TotalSeconds} s.\");\n\n if (totalSW.Elapsed.TotalSeconds > timeout) break;\n }\n\n totalSW.Stop();\n Console.WriteLine($\"Elapsed training time: {totalSW.Elapsed} s.\");\n }\n }\n\n model.Dispose();\n }\n\n private static void Train(\n Module<torch.Tensor, torch.Tensor> model,\n torch.optim.Optimizer optimizer,\n Loss<torch.Tensor, torch.Tensor, torch.Tensor> loss,\n DataLoader dataLoader,\n int epoch,\n long batchSize,\n long size)\n {\n model.train();\n\n int batchId = 1;\n long total = 0;\n long correct = 0;\n\n Console.WriteLine($\"Epoch: {epoch}...\");\n\n using (var d = torch.NewDisposeScope()) {\n\n foreach (var data in dataLoader) {\n\n optimizer.zero_grad();\n\n var target = data[\"label\"];\n var prediction = model.call(data[\"data\"]);\n var lsm = log_softmax(prediction, 1);\n var output = loss.call(lsm, target);\n\n output.backward();\n\n optimizer.step();\n\n total += target.shape[0];\n\n var predicted = prediction.argmax(1);\n correct += predicted.eq(target).sum().ToInt64();\n\n if (batchId % _logInterval == 0 || total == size) {\n Console.WriteLine($\"\\rTrain: epoch {epoch} [{total} / {size}] Loss: {output.ToSingle().ToString(\"0.000000\")} | Accuracy: { ((float)correct / total).ToString(\"0.000000\") }\");\n }\n\n batchId++;\n\n d.DisposeEverything();\n }\n }\n }\n\n private static void Test(\n Module<torch.Tensor, torch.Tensor> model,\n Loss<torch.Tensor, torch.Tensor, torch.Tensor> loss,\n DataLoader dataLoader,\n long size)\n {\n model.eval();\n\n double testLoss = 0;\n long correct = 0;\n int batchCount = 0;\n\n using (var d = torch.NewDisposeScope()) {\n\n foreach (var data in dataLoader) {\n\n var target = data[\"label\"];\n var prediction = model.call(data[\"data\"]);\n var lsm = log_softmax(prediction, 1);\n var output = loss.call(lsm, target);\n\n testLoss += output.ToSingle();\n batchCount += 1;\n\n var predicted = prediction.argmax(1);\n correct += predicted.eq(target).sum().ToInt64();\n\n d.DisposeEverything();\n }\n }\n\n Console.WriteLine($\"\\rTest set: Average loss {(testLoss / batchCount).ToString(\"0.0000\")} | Accuracy {((float)correct / size).ToString(\"0.0000\")}\");\n }\n }\n}\n" }, { "alpha_fraction": 0.40059059858322144, "alphanum_fraction": 0.4575561583042145, "avg_line_length": 32.95050811767578, "blob_id": "865a8c99e3cd4d61d62338f84b027274b2942e00", "content_id": "a27582bbba6821bbbb2b559ed8bd9604fed713fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 26753, "license_type": "permissive", "max_line_length": 240, "num_lines": 788, "path": "/test/TorchSharpTest/LinearAlgebra.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing Xunit;\nusing static TorchSharp.torch;\n\n#nullable enable\n\nnamespace TorchSharp\n{\n [Collection(\"Sequential\")]\n public class LinearAlgebra\n {\n [Fact]\n [TestOf(nameof(tensordot))]\n public void TestTensorDot()\n {\n var a = arange(60).reshape(3, 4, 5);\n var b = arange(24).reshape(4, 3, 2);\n var res = tensordot(a, b, new []{ 1L, 0L }, new []{ 0L, 1L });\n\n var expected = from_array(new long[,]\n {\n {4400, 4730},\n {4532, 4874},\n {4664, 5018},\n {4796, 5162},\n {4928, 5306}\n });\n\n Assert.True(allclose(res, expected));\n }\n\n [Fact]\n [TestOf(nameof(lu))]\n public void TestLUSolve()\n {\n var A = randn(2, 3, 3);\n var b = randn(2, 3, 1);\n\n {\n var (A_LU, pivots, infos) = lu(A);\n\n Assert.NotNull(A_LU);\n Assert.NotNull(pivots);\n Assert.Null(infos);\n\n Assert.Equal(new long[] { 2, 3, 3 }, A_LU.shape);\n Assert.Equal(new long[] { 2, 3 }, pivots.shape);\n\n var x = lu_solve(b, A_LU, pivots);\n Assert.Equal(new long[] { 2, 3, 1 }, x.shape);\n\n var y = norm(bmm(A, x) - b);\n Assert.Empty(y.shape);\n }\n\n {\n var (A_LU, pivots, infos) = lu(A, get_infos: true);\n\n Assert.NotNull(A_LU);\n Assert.NotNull(pivots);\n Assert.NotNull(infos);\n\n Assert.Equal(new long[] { 2, 3, 3 }, A_LU.shape);\n Assert.Equal(new long[] { 2, 3 }, pivots.shape);\n Assert.Equal(new long[] { 2 }, infos.shape);\n\n var x = lu_solve(b, A_LU, pivots);\n Assert.Equal(new long[] { 2, 3, 1 }, x.shape);\n\n var y = norm(bmm(A, x) - b);\n Assert.Empty(y.shape);\n }\n }\n\n [Fact]\n [TestOf(nameof(lu_unpack))]\n public void TestLUUnpack()\n {\n var A = randn(2, 3, 3);\n\n {\n var (A_LU, pivots, infos) = lu(A);\n\n Assert.NotNull(A_LU);\n Assert.NotNull(pivots);\n Assert.Null(infos);\n\n var (P, A_L, A_U) = lu_unpack(A_LU, pivots);\n\n Assert.NotNull(P);\n Assert.NotNull(A_L);\n Assert.NotNull(A_U);\n\n Assert.Equal(new long[] { 2, 3, 3 }, P.shape);\n Assert.Equal(new long[] { 2, 3, 3 }, A_L!.shape);\n Assert.Equal(new long[] { 2, 3, 3 }, A_U!.shape);\n }\n }\n\n [Fact]\n [TestOf(nameof(Tensor.mul))]\n public void TestMul()\n {\n var x = ones(new long[] { 100, 100 });\n\n var y = x.mul(0.5f.ToScalar());\n\n var ydata = y.data<float>();\n var xdata = x.data<float>();\n\n for (int i = 0; i < 100; i++) {\n for (int j = 0; j < 100; j++) {\n Assert.Equal(ydata[i + j], xdata[i + j] * 0.5f);\n }\n }\n }\n\n void TestMmGen(Device device)\n {\n {\n var x1 = ones(new long[] { 1, 2 }, device: device);\n var x2 = ones(new long[] { 2, 1 }, device: device);\n\n var y = x1.mm(x2).to(DeviceType.CPU);\n\n var ydata = y.data<float>();\n\n Assert.Equal(2.0f, ydata[0]);\n }\n //System.Runtime.InteropServices.ExternalException : addmm for CUDA tensors only supports floating - point types.Try converting the tensors with.float() at C:\\w\\b\\windows\\pytorch\\aten\\src\\THC / generic / THCTensorMathBlas.cu:453\n if (device.type == DeviceType.CPU) {\n var x1 = ones(new long[] { 1, 2 }, int64, device: device);\n var x2 = ones(new long[] { 2, 1 }, int64, device: device);\n\n var y = x1.mm(x2).to(DeviceType.CPU);\n\n var ydata = y.data<long>();\n\n Assert.Equal(2L, ydata[0]);\n }\n }\n\n [Fact]\n [TestOf(nameof(CPU))]\n public void TestMmCpu()\n {\n TestMmGen(CPU);\n }\n\n [Fact]\n [TestOf(nameof(CUDA))]\n public void TestMmCuda()\n {\n if (cuda.is_available()) {\n TestMmGen(CUDA);\n }\n }\n\n void TestMVGen(Device device)\n {\n {\n var mat1 = ones(new long[] { 4, 3 }, device: device);\n var vec1 = ones(new long[] { 3 }, device: device);\n\n var y = mat1.mv(vec1).to(DeviceType.CPU);\n\n Assert.Equal(4, y.shape[0]);\n }\n }\n\n void TestAddMVGen(Device device)\n {\n {\n var x1 = ones(new long[] { 4 }, device: device);\n var mat1 = ones(new long[] { 4, 3 }, device: device);\n var vec1 = ones(new long[] { 3 }, device: device);\n\n var y = x1.addmv(mat1, vec1).to(DeviceType.CPU);\n\n Assert.Equal(4, y.shape[0]);\n }\n }\n\n [Fact]\n [TestOf(nameof(CPU))]\n public void TestMVCpu()\n {\n TestMVGen(CPU);\n }\n\n [Fact]\n [TestOf(nameof(CUDA))]\n public void TestMVCuda()\n {\n if (cuda.is_available()) {\n TestMVGen(CUDA);\n }\n }\n\n [Fact]\n public void TestAddMVCpu()\n {\n TestAddMVGen(CPU);\n }\n\n [Fact]\n [TestOf(nameof(CUDA))]\n public void TestAddMVCuda()\n {\n if (cuda.is_available()) {\n TestAddMVGen(CUDA);\n }\n }\n\n void TestAddRGen(Device device)\n {\n {\n var x1 = ones(new long[] { 4, 3 }, device: device);\n var vec1 = ones(new long[] { 4 }, device: device);\n var vec2 = ones(new long[] { 3 }, device: device);\n\n var y = x1.addr(vec1, vec2).to(DeviceType.CPU);\n\n Assert.Equal(new long[] { 4, 3 }, y.shape);\n }\n }\n\n [Fact]\n [TestOf(nameof(CPU))]\n public void TestAddRCpu()\n {\n TestAddRGen(CPU);\n }\n\n [Fact]\n [TestOf(nameof(CUDA))]\n public void TestAddRCuda()\n {\n if (cuda.is_available()) {\n TestAddRGen(CUDA);\n }\n }\n\n [Fact]\n [TestOf(nameof(Tensor.vdot))]\n public void VdotTest()\n {\n var a = new float[] { 1.0f, 2.0f, 3.0f };\n var b = new float[] { 1.0f, 2.0f, 3.0f };\n var expected = tensor(a.Zip(b).Select(x => x.First * x.Second).Sum());\n var res = tensor(a).vdot(tensor(b));\n Assert.True(res.allclose(expected));\n }\n\n [Fact]\n [TestOf(nameof(Tensor.vander))]\n public void VanderTest()\n {\n var x = tensor(new int[] { 1, 2, 3, 5 });\n {\n var res = x.vander();\n var expected = tensor(new long[] { 1, 1, 1, 1, 8, 4, 2, 1, 27, 9, 3, 1, 125, 25, 5, 1 }, 4, 4);\n Assert.Equal(expected, res);\n }\n {\n var res = x.vander(3);\n var expected = tensor(new long[] { 1, 1, 1, 4, 2, 1, 9, 3, 1, 25, 5, 1 }, 4, 3);\n Assert.Equal(expected, res);\n }\n {\n var res = x.vander(3, true);\n var expected = tensor(new long[] { 1, 1, 1, 1, 2, 4, 1, 3, 9, 1, 5, 25 }, 4, 3);\n Assert.Equal(expected, res);\n }\n }\n\n [Fact]\n [TestOf(nameof(linalg.vander))]\n public void LinalgVanderTest()\n {\n var x = tensor(new int[] { 1, 2, 3, 5 });\n {\n var res = linalg.vander(x);\n var expected = tensor(new long[] { 1, 1, 1, 1, 1, 2, 4, 8, 1, 3, 9, 27, 1, 5, 25, 125 }, 4, 4);\n Assert.Equal(expected, res);\n }\n {\n var res = linalg.vander(x, 3);\n var expected = tensor(new long[] { 1, 1, 1, 1, 2, 4, 1, 3, 9, 1, 5, 25 }, 4, 3);\n Assert.Equal(expected, res);\n }\n }\n\n [Fact]\n [TestOf(nameof(linalg.cholesky))]\n public void CholeskyTest()\n {\n var a = randn(new long[] { 3, 2, 2 }, float64);\n a = a.matmul(a.swapdims(-2, -1)); // Worked this in to get it tested. Alias for 'transpose'\n var l = linalg.cholesky(a);\n\n Assert.True(a.allclose(l.matmul(l.swapaxes(-2, -1)))); // Worked this in to get it tested. Alias for 'transpose'\n }\n\n [Fact]\n [TestOf(nameof(linalg.cholesky_ex))]\n public void CholeskyExTest()\n {\n var a = randn(new long[] { 3, 2, 2 }, float64);\n a = a.matmul(a.swapdims(-2, -1)); // Worked this in to get it tested. Alias for 'transpose'\n var (l, info) = linalg.cholesky_ex(a);\n\n Assert.True(a.allclose(l.matmul(l.swapaxes(-2, -1))));\n }\n\n [Fact]\n [TestOf(nameof(linalg.inv))]\n public void InvTest()\n {\n var a = randn(new long[] { 3, 2, 2 }, float64);\n var l = linalg.inv(a);\n\n Assert.Equal(a.shape, l.shape);\n }\n\n [Fact]\n [TestOf(nameof(linalg.inv_ex))]\n public void InvExTest()\n {\n var a = randn(new long[] { 3, 2, 2 }, float64);\n var (l, info) = linalg.inv_ex(a);\n\n Assert.Equal(a.shape, l.shape);\n }\n\n [Fact]\n [TestOf(nameof(linalg.cond))]\n public void CondTestF64()\n {\n {\n var a = randn(new long[] { 3, 3, 3 }, float64);\n // The following mostly checks that the runtime interop doesn't blow up.\n _ = linalg.cond(a);\n _ = linalg.cond(a, \"fro\");\n _ = linalg.cond(a, \"nuc\");\n _ = linalg.cond(a, 1);\n _ = linalg.cond(a, -1);\n _ = linalg.cond(a, 2);\n _ = linalg.cond(a, -2);\n _ = linalg.cond(a, Double.PositiveInfinity);\n _ = linalg.cond(a, Double.NegativeInfinity);\n }\n }\n\n [Fact]\n [TestOf(nameof(linalg.cond))]\n public void CondTestCF64()\n {\n {\n var a = randn(new long[] { 3, 3, 3 }, complex128);\n // The following mostly checks that the runtime interop doesn't blow up.\n _ = linalg.cond(a);\n _ = linalg.cond(a, \"fro\");\n _ = linalg.cond(a, \"nuc\");\n _ = linalg.cond(a, 1);\n _ = linalg.cond(a, -1);\n _ = linalg.cond(a, 2);\n _ = linalg.cond(a, -2);\n _ = linalg.cond(a, Double.PositiveInfinity);\n _ = linalg.cond(a, Double.NegativeInfinity);\n }\n }\n\n [Fact]\n [TestOf(nameof(linalg.qr))]\n public void QRTest()\n {\n var a = randn(new long[] { 4, 25, 25 });\n\n var l = linalg.qr(a);\n\n Assert.Equal(a.shape, l.Q.shape);\n Assert.Equal(a.shape, l.R.shape);\n }\n\n [Fact]\n [TestOf(nameof(linalg.solve))]\n public void SolveTest()\n {\n var A = randn(3, 3);\n var b = randn(3);\n var x = linalg.solve(A, b);\n Assert.True(A.matmul(x).allclose(b, rtol: 1e-03, atol: 1e-06));\n }\n\n [Fact]\n [TestOf(nameof(linalg.solve_triangular))]\n public void SolveTriangularTest()\n {\n {\n var A = randn(3, 3).triu_();\n var b = randn(3, 4);\n var x = linalg.solve_triangular(A, b, upper: true);\n Assert.True(A.matmul(x).allclose(b, rtol: 1e-03, atol: 1e-06));\n }\n {\n var A = randn(2, 3, 3).tril_();\n var b = randn(2, 3, 4);\n var x = linalg.solve_triangular(A, b, upper: false);\n Assert.True(A.matmul(x).allclose(b, rtol: 1e-03, atol: 1e-06));\n }\n {\n var A = randn(2, 4, 4).tril_();\n var b = randn(2, 3, 4);\n var x = linalg.solve_triangular(A, b, upper: false, left: false);\n Assert.True(x.matmul(A).allclose(b, rtol: 1e-03, atol: 1e-06));\n }\n }\n\n [Fact]\n [TestOf(nameof(linalg.svd))]\n public void SVDTest()\n {\n var a = randn(new long[] { 4, 25, 15 });\n\n var l = linalg.svd(a);\n\n Assert.Equal(new long[] { 4, 25, 25 }, l.U.shape);\n Assert.Equal(new long[] { 4, 15 }, l.S.shape);\n Assert.Equal(new long[] { 4, 15, 15 }, l.Vh.shape);\n\n l = linalg.svd(a, fullMatrices: false);\n\n Assert.Equal(a.shape, l.U.shape);\n Assert.Equal(new long[] { 4, 15 }, l.S.shape);\n Assert.Equal(new long[] { 4, 15, 15 }, l.Vh.shape);\n }\n\n\n [Fact]\n [TestOf(nameof(linalg.svdvals))]\n public void SVDValsTest()\n {\n var a = tensor(new double[] { -1.3490, -0.1723, 0.7730,\n -1.6118, -0.3385, -0.6490,\n 0.0908, 2.0704, 0.5647,\n -0.6451, 0.1911, 0.7353,\n 0.5247, 0.5160, 0.5110}, 5, 3);\n\n var l = linalg.svdvals(a);\n Assert.True(l.allclose(tensor(new double[] { 2.5138929972840613, 2.1086555338402455, 1.1064930672223237 }), rtol: 1e-04, atol: 1e-07));\n }\n\n [Fact]\n [TestOf(nameof(linalg.lstsq))]\n public void LSTSQTest()\n {\n var a = randn(new long[] { 4, 25, 15 });\n var b = randn(new long[] { 4, 25, 10 });\n\n var l = linalg.lstsq(a, b);\n\n Assert.Equal(new long[] { 4, 15, 10 }, l.Solution.shape);\n Assert.Equal(0, l.Residuals.shape[0]);\n Assert.Equal(new long[] { 4 }, l.Rank.shape);\n Assert.Equal(new long[] { 4, 15, 10 }, l.Solution.shape);\n Assert.Equal(0, l.SingularValues.shape[0]);\n }\n\n [Fact]\n [TestOf(nameof(linalg.lu))]\n public void LUTest()\n {\n var A = randn(2, 3, 3);\n var A_factor = linalg.lu(A);\n // For right now, pretty much just checking that it's not blowing up.\n Assert.Multiple(\n () => Assert.NotNull(A_factor.P),\n () => Assert.NotNull(A_factor.L),\n () => Assert.NotNull(A_factor.U)\n );\n }\n\n [Fact]\n [TestOf(nameof(linalg.lu_factor))]\n public void LUFactorTest()\n {\n var A = randn(2, 3, 3);\n var A_factor = linalg.lu_factor(A);\n // For right now, pretty much just checking that it's not blowing up.\n Assert.Multiple(\n () => Assert.NotNull(A_factor.LU),\n () => Assert.NotNull(A_factor.Pivots)\n );\n }\n\n [Fact]\n [TestOf(nameof(linalg.ldl_factor))]\n public void LDLFactorTest()\n {\n var A = randn(2, 3, 3);\n var A_factor = linalg.ldl_factor(A);\n // For right now, pretty much just checking that it's not blowing up.\n Assert.Multiple(\n () => Assert.NotNull(A_factor.LU),\n () => Assert.NotNull(A_factor.Pivots)\n );\n }\n\n [Fact]\n [TestOf(nameof(linalg.ldl_factor))]\n public void LDLFactorExTest()\n {\n var A = randn(2, 3, 3);\n var A_factor = linalg.ldl_factor_ex(A);\n // For right now, pretty much just checking that it's not blowing up.\n Assert.Multiple(\n () => Assert.NotNull(A_factor.LU),\n () => Assert.NotNull(A_factor.Pivots),\n () => Assert.NotNull(A_factor.Info)\n );\n }\n\n [Fact]\n [TestOf(nameof(Tensor.matrix_power))]\n public void MatrixPowerTest()\n {\n var a = randn(new long[] { 25, 25 });\n var b = a.matrix_power(3);\n Assert.Equal(new long[] { 25, 25 }, b.shape);\n }\n\n [Fact]\n [TestOf(nameof(Tensor.matrix_exp))]\n public void MatrixExpTest1()\n {\n var a = randn(new long[] { 25, 25 });\n var b = a.matrix_exp();\n Assert.Equal(new long[] { 25, 25 }, b.shape);\n\n var c = matrix_exp(a);\n Assert.Equal(new long[] { 25, 25 }, c.shape);\n }\n\n [Fact]\n [TestOf(nameof(matrix_exp))]\n public void MatrixExpTest2()\n {\n var a = randn(new long[] { 16, 25, 25 });\n var b = a.matrix_exp();\n Assert.Equal(new long[] { 16, 25, 25 }, b.shape);\n var c = matrix_exp(a);\n Assert.Equal(new long[] { 16, 25, 25 }, c.shape);\n }\n\n [Fact]\n [TestOf(nameof(linalg.matrix_rank))]\n public void MatrixRankTest()\n {\n var mr1 = linalg.matrix_rank(randn(4, 3, 2));\n Assert.Equal(new long[] { 4 }, mr1.shape);\n\n var mr2 = linalg.matrix_rank(randn(2, 4, 3, 2));\n Assert.Equal(new long[] { 2, 4 }, mr2.shape);\n\n // Really just testing that it doesn't blow up in interop for the following lines:\n\n mr2 = linalg.matrix_rank(randn(2, 4, 3, 2), atol: 1.0);\n Assert.Equal(new long[] { 2, 4 }, mr2.shape);\n\n mr2 = linalg.matrix_rank(randn(2, 4, 3, 2), atol: 1.0, rtol: 0.0);\n Assert.Equal(new long[] { 2, 4 }, mr2.shape);\n\n mr2 = linalg.matrix_rank(randn(2, 4, 3, 2), atol: tensor(1.0));\n Assert.Equal(new long[] { 2, 4 }, mr2.shape);\n\n mr2 = linalg.matrix_rank(randn(2, 4, 3, 2), atol: tensor(1.0), rtol: tensor(0.0));\n Assert.Equal(new long[] { 2, 4 }, mr2.shape);\n }\n\n [Fact]\n [TestOf(nameof(linalg.multi_dot))]\n public void MultiDotTest()\n {\n var a = randn(new long[] { 25, 25 });\n var b = randn(new long[] { 25, 25 });\n var c = randn(new long[] { 25, 25 });\n var d = linalg.multi_dot(new Tensor[] { a, b, c });\n Assert.Equal(new long[] { 25, 25 }, d.shape);\n }\n\n [Fact]\n [TestOf(nameof(linalg.det))]\n public void DeterminantTest()\n {\n {\n var a = tensor(\n new float[] { 0.9478f, 0.9158f, -1.1295f,\n 0.9701f, 0.7346f, -1.8044f,\n -0.2337f, 0.0557f, 0.6929f }, 3, 3);\n var l = linalg.det(a);\n Assert.True(l.allclose(tensor(0.09335048f)));\n }\n {\n var a = tensor(\n new float[] { 0.9254f, -0.6213f, -0.5787f, 1.6843f, 0.3242f, -0.9665f,\n 0.4539f, -0.0887f, 1.1336f, -0.4025f, -0.7089f, 0.9032f }, 3, 2, 2);\n var l = linalg.det(a);\n Assert.True(l.allclose(tensor(new float[] { 1.19910491f, 0.4099378f, 0.7385352f })));\n }\n }\n\n [Fact]\n [TestOf(nameof(linalg.matrix_norm))]\n public void MatrixNormTest()\n {\n {\n var a = arange(9, float32).view(3, 3);\n\n var b = linalg.matrix_norm(a);\n var c = linalg.matrix_norm(a, ord: -1);\n\n Assert.Equal(14.282857f, b.item<float>());\n Assert.Equal(9.0f, c.item<float>());\n }\n }\n\n [Fact]\n [TestOf(nameof(linalg.vector_norm))]\n public void VectorNormTest()\n {\n {\n var a = tensor(\n new float[] { -4.0f, -3.0f, -2.0f, -1.0f, 0, 1.0f, 2.0f, 3.0f, 4.0f });\n\n var b = linalg.vector_norm(a, ord: 3.5);\n var c = linalg.vector_norm(a.view(3, 3), ord: 3.5);\n\n Assert.Equal(5.4344883f, b.item<float>());\n Assert.Equal(5.4344883f, c.item<float>());\n }\n }\n\n [Fact]\n [TestOf(nameof(linalg.pinv))]\n public void PinvTest()\n {\n var mr1 = linalg.pinv(randn(4, 3, 5));\n Assert.Equal(new long[] { 4, 5, 3 }, mr1.shape);\n\n // Really just testing that it doesn't blow up in interop for the following lines:\n\n mr1 = linalg.pinv(randn(4, 3, 5), atol: 1.0);\n Assert.Equal(new long[] { 4, 5, 3 }, mr1.shape);\n\n mr1 = linalg.pinv(randn(4, 3, 5), atol: 1.0, rtol: 0.0);\n Assert.Equal(new long[] { 4, 5, 3 }, mr1.shape);\n\n mr1 = linalg.pinv(randn(4, 3, 5), atol: tensor(1.0));\n Assert.Equal(new long[] { 4, 5, 3 }, mr1.shape);\n\n mr1 = linalg.pinv(randn(4, 3, 5), atol: tensor(1.0), rtol: tensor(0.0));\n Assert.Equal(new long[] { 4, 5, 3 }, mr1.shape);\n }\n\n [Fact]\n [TestOf(nameof(linalg.eig))]\n public void EigTest32()\n {\n {\n var a = tensor(\n new float[] { 2.8050f, -0.3850f, -0.3850f, 3.2376f, -1.0307f, -2.7457f, -2.7457f, -1.7517f, 1.7166f }, 3, 3);\n\n var expected = tensor(\n new (float, float)[] { (3.44288778f, 0.0f), (2.17609453f, 0.0f), (-2.128083f, 0.0f) });\n\n {\n var (values, vectors) = linalg.eig(a);\n Assert.NotNull(vectors);\n Assert.True(values.allclose(expected));\n }\n }\n }\n\n [Fact]\n [TestOf(nameof(linalg.eigvals))]\n public void EighvalsTest32()\n {\n var a = tensor(\n new float[] { 2.8050f, -0.3850f, -0.3850f, 3.2376f, -1.0307f, -2.7457f, -2.7457f, -1.7517f, 1.7166f }, 3, 3);\n var expected = tensor(\n new (float, float)[] { (3.44288778f, 0.0f), (2.17609453f, 0.0f), (-2.128083f, 0.0f) });\n var l = linalg.eigvals(a);\n Assert.True(l.allclose(expected));\n }\n\n // TODO: (Skip = \"Intermittently failing on MacOS or Linux (note: may now be working, we need to recheck)\")\n [FactIgnoreOnPlatform(\"Intermittently fails\", \"OSX\", \"Linux\")]\n [TestOf(nameof(linalg.eigvals))]\n public void EighvalsTest64()\n {\n var a = tensor(\n new double[] { 2.8050f, -0.3850f, -0.3850f, 3.2376f, -1.0307f, -2.7457f, -2.7457f, -1.7517f, 1.7166f }, 3, 3);\n var expected = tensor(\n new System.Numerics.Complex[] { new System.Numerics.Complex(3.44288778f, 0.0f), new System.Numerics.Complex(2.17609453f, 0.0f), new System.Numerics.Complex(-2.128083f, 0.0f) });\n var l = linalg.eigvals(a);\n Assert.True(l.allclose(expected));\n }\n\n // TODO: (Skip = \"Intermittently failing on MacOS or Linux (note: may now be working, we need to recheck)\")\n [FactIgnoreOnPlatform(\"Intermittently fails\", \"OSX\", \"Linux\")]\n [TestOf(nameof(linalg.eigvalsh))]\n public void EighvalshTest32()\n {\n var a = tensor(\n new float[] { 2.8050f, -0.3850f, -0.3850f, 3.2376f, -1.0307f, -2.7457f,\n -2.7457f, -1.7517f, 1.7166f, 2.2207f, 2.2207f, -2.0898f }, 3, 2, 2);\n var expected = tensor(\n new float[] { 2.5797f, 3.46290016f, -4.16046524f, 1.37806475f, -3.11126733f, 2.73806715f }, 3, 2);\n var l = linalg.eigvalsh(a);\n Assert.True(l.allclose(expected));\n }\n\n // TODO: (Skip = \"Intermittently failing on MacOS or Linux (note: may now be working, we need to recheck)\")\n [FactIgnoreOnPlatform(\"Intermittently fails\", \"OSX\", \"Linux\")]\n [TestOf(nameof(linalg.eigvalsh))]\n public void EighvalshTest64()\n {\n var a = tensor(\n new double[] { 2.8050, -0.3850, -0.3850, 3.2376, -1.0307, -2.7457,\n -2.7457, -1.7517, 1.7166, 2.2207, 2.2207, -2.0898 }, 3, 2, 2);\n var expected = tensor(\n new double[] { 2.5797, 3.46290016, -4.16046524, 1.37806475, -3.11126733, 2.73806715 }, 3, 2);\n var l = linalg.eigvalsh(a);\n Assert.True(l.allclose(expected));\n }\n\n [Fact]\n [TestOf(nameof(linalg.norm))]\n public void LinalgNormTest()\n {\n {\n var a = tensor(\n new float[] { -4.0f, -3.0f, -2.0f, -1.0f, 0.0f, 1.0f, 2.0f, 3.0f, 4.0f });\n var b = a.reshape(3, 3);\n\n Assert.True(linalg.norm(a).allclose(tensor(7.7460f)));\n Assert.True(linalg.norm(b).allclose(tensor(7.7460f)));\n Assert.True(linalg.norm(b, \"fro\").allclose(tensor(7.7460f)));\n\n Assert.True(linalg.norm(a, float.PositiveInfinity).allclose(tensor(4.0f)));\n Assert.True(linalg.norm(b, float.PositiveInfinity).allclose(tensor(9.0f)));\n Assert.True(linalg.norm(a, float.NegativeInfinity).allclose(tensor(0.0f)));\n Assert.True(linalg.norm(b, float.NegativeInfinity).allclose(tensor(2.0f)));\n\n Assert.True(linalg.norm(a, 1).allclose(tensor(20.0f)));\n Assert.True(linalg.norm(b, 1).allclose(tensor(7.0f)));\n Assert.True(linalg.norm(a, -1).allclose(tensor(0.0f)));\n Assert.True(linalg.norm(b, -1).allclose(tensor(6.0f)));\n\n Assert.True(linalg.norm(a, 2).allclose(tensor(7.7460f)));\n Assert.True(linalg.norm(b, 2).allclose(tensor(7.3485f)));\n Assert.True(linalg.norm(a, 3).allclose(tensor(5.8480f)));\n Assert.True(linalg.norm(a, -2).allclose(tensor(0.0f)));\n Assert.True(linalg.norm(a, -3).allclose(tensor(0.0f)));\n }\n }\n\n [Fact]\n public void TestTrilIndex()\n {\n var a = tril_indices(3, 3);\n var expected = new long[] { 0, 1, 1, 2, 2, 2, 0, 0, 1, 0, 1, 2 };\n Assert.Equal(expected, a.data<long>().ToArray());\n }\n\n [Fact]\n public void TestTriuIndex()\n {\n var a = triu_indices(3, 3);\n var expected = new long[] { 0, 0, 0, 1, 1, 2, 0, 1, 2, 1, 2, 2 };\n Assert.Equal(expected, a.data<long>().ToArray());\n }\n }\n}\n" }, { "alpha_fraction": 0.6116677522659302, "alphanum_fraction": 0.6152304410934448, "avg_line_length": 58.092105865478516, "blob_id": "2193a8c2faa8681546edda60ec36f27244284a7a", "content_id": "0473ddb98051c9ff5a8cf567bcdaa941706cee72", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4499, "license_type": "permissive", "max_line_length": 360, "num_lines": 76, "path": "/src/TorchSharp/NN/MultiheadAttention.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See License.txt in the project root for license information.\nusing System;\nusing static TorchSharp.PInvoke.NativeMethods;\nusing static TorchSharp.torch;\n\n#nullable enable\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n public sealed class MultiheadAttention : torch.nn.Module<Tensor, Tensor, Tensor, Tensor?, bool, Tensor?, Tuple<Tensor,Tensor>>\n {\n internal MultiheadAttention(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n /// <summary>\n /// Applies the MultiheadAttention function element-wise.\n /// </summary>\n /// <param name=\"query\">map a query and a set of key-value pairs to an output. See “Attention Is All You Need” for more details</param>\n /// <param name=\"key\"></param>\n /// <param name=\"value\"></param>\n /// <param name=\"key_padding_mask\">if provided, specified padding elements in the key will be ignored by the attention. When given a binary mask and a value is True, the corresponding value on the attention layer will be ignored. When given a byte mask and a value is non-zero, the corresponding value on the attention layer will be ignored</param>\n /// <param name=\"need_weights\">output attn_output_weights</param>\n /// <param name=\"attn_mask\">2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all the batches while a 3D mask allows to specify a different mask for the entries of each batch</param>\n /// <returns>attn_output, attn_ouput_weights</returns>\n\n public override Tuple<Tensor,Tensor> forward(Tensor query, Tensor key, Tensor value, Tensor? key_padding_mask, bool need_weights, Tensor? attn_mask)\n {\n THSNN_MultiheadAttention_forward(handle,\n query.Handle,\n key.Handle,\n value.Handle,\n key_padding_mask?.Handle ?? IntPtr.Zero,\n need_weights,\n attn_mask?.Handle ?? IntPtr.Zero,\n out var res1,\n out var res2);\n if (res1 == IntPtr.Zero || (need_weights && res2 == IntPtr.Zero)) { torch.CheckForErrors(); }\n return Tuple.Create(new Tensor(res1), new Tensor(res2));\n }\n\n public new Tuple<Tensor, Tensor> call(Tensor query, Tensor key, Tensor value, Tensor? key_padding_mask = null, bool need_weights = true, Tensor? attn_mask = null)\n {\n return base.call(query, key, value, key_padding_mask, need_weights, attn_mask);\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Allows the model to jointly attend to information from different representation subspaces (based on the paper “Attention Is All You Need”).\n /// </summary>\n /// <param name=\"embedded_dim\">total dimension of the model</param>\n /// <param name=\"num_heads\">parallel attention heads</param>\n /// <param name=\"dropout\">a Dropout layer on attn_output_weights. Default: 0.0</param>\n /// <param name=\"bias\">add bias as module parameter. Default: true</param>\n /// <param name=\"add_bias_kv\">add bias to the key and value sequences at dim=0</param>\n /// <param name=\"add_zero_attn\">add a new batch of zeros to the key and value sequences at dim=1</param>\n /// <param name=\"kdim\">total number of features in key</param>\n /// <param name=\"vdim\">total number of features in value</param>\n /// <returns></returns>\n public static MultiheadAttention MultiheadAttention(long embedded_dim, long num_heads, double dropout = 0.0, bool bias = true, bool add_bias_kv = false, bool add_zero_attn = false, long? kdim=null, long? vdim=null)\n {\n var _kdim = kdim.HasValue ? kdim.Value : embedded_dim;\n var _vdim = vdim.HasValue ? vdim.Value : embedded_dim;\n var res = THSNN_MultiheadAttention_ctor(embedded_dim, num_heads, dropout, bias, add_bias_kv, add_zero_attn, _kdim, _vdim, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new MultiheadAttention(res, boxedHandle);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.45609214901924133, "alphanum_fraction": 0.472366064786911, "avg_line_length": 47.0355339050293, "blob_id": "3e495b8f05fa894f7f63b7bc470422c63adcedc7", "content_id": "f06f92fdc865ab213ff13ac5daa838dc5e738ebe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9463, "license_type": "permissive", "max_line_length": 125, "num_lines": 197, "path": "/src/TorchVision/AutoAugment.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\nusing F = TorchSharp.torchvision.transforms.functional;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal abstract class AutoAugmentBase\n {\n protected enum opType {\n ShearX,\n ShearY,\n TranslateX,\n TranslateY,\n Rotate,\n Brightness,\n Color,\n Contrast,\n Sharpness,\n Posterize,\n Solarize,\n AutoContrast,\n Equalize,\n Invert,\n Identity\n }\n\n protected static Tensor apply_op(\n Tensor img,\n opType op_name,\n double magnitude,\n InterpolationMode interpolation,\n IList<float>? fill)\n {\n switch(op_name) {\n case opType.ShearX:\n return F.affine(\n img,\n angle: 0.0f,\n translate: new[] { 0, 0 },\n scale: 1.0f,\n shear: new[] { (float)((180.0 / Math.PI) * Math.Atan(magnitude)), 0.0f },\n interpolation: interpolation,\n fill: fill?.FirstOrDefault());\n case opType.ShearY:\n return F.affine(\n img,\n angle: 0.0f,\n translate: new[] { 0, 0 },\n scale: 1.0f,\n shear: new[] { 0.0f, (float)((180.0 / Math.PI) * Math.Atan(magnitude)) },\n interpolation: interpolation,\n fill: fill?.FirstOrDefault());\n case opType.TranslateX:\n return F.affine(\n img,\n angle: 0.0f,\n translate: new[] { (int)(magnitude), 0 },\n scale: 1.0f,\n interpolation: interpolation,\n shear: new[] { 0.0f, 0.0f },\n fill: fill?.FirstOrDefault());\n case opType.TranslateY:\n return F.affine(\n img,\n angle: 0.0f,\n translate: new[] { 0, (int)(magnitude) },\n scale: 1.0f,\n interpolation: interpolation,\n shear: new[] { 0.0f, 0.0f },\n fill: fill?.FirstOrDefault());\n case opType.Rotate:\n return F.rotate(img, (float)magnitude, interpolation, fill: fill);\n case opType.Brightness:\n return F.adjust_brightness(img, 1.0 + magnitude);\n case opType.Color:\n return F.adjust_saturation(img, 1.0 + magnitude);\n case opType.Contrast:\n return F.adjust_contrast(img, 1.0 + magnitude);\n case opType.Sharpness:\n return F.adjust_sharpness(img, 1.0 + magnitude);\n case opType.Posterize:\n return F.posterize(img, (int)magnitude);\n case opType.Solarize:\n return F.solarize(img, magnitude);\n case opType.AutoContrast:\n return F.autocontrast(img);\n case opType.Equalize:\n return F.equalize(img);\n case opType.Invert:\n return F.invert(img);\n case opType.Identity:\n return img; // Pass\n default:\n throw new ArgumentException($\"The provided operator {op_name} is not recognized.\");\n }\n }\n }\n\n /* Original implementation from:\n * https://pytorch.org/vision/main/_modules/torchvision/transforms/autoaugment.html#RandAugment */\n internal class RandAugment : AutoAugmentBase, ITransform\n {\n public RandAugment(\n int num_ops = 2,\n int magnitude = 9,\n int num_magnitude_bins = 31,\n InterpolationMode interpolation = InterpolationMode.Nearest,\n IList<float>? fill = null)\n {\n this.num_ops = num_ops;\n this.magnitude = magnitude;\n this.num_magnitude_bins = num_magnitude_bins;\n this.interpolation = interpolation;\n this.fill = fill;\n }\n\n public Tensor call(Tensor img)\n {\n using var _ = torch.NewDisposeScope();\n var cDim = img.Dimensions - 3;\n var height = img.shape[cDim + 1];\n var width = img.shape[cDim + 2];\n var op_meta = augmentation_space(num_magnitude_bins, (height, width));\n for (int i = 0; i < num_ops; ++i) {\n var op_index = torch.randint(0, op_meta.Count, 1).ToInt32();\n var op_name = op_meta.Keys.ToList()[op_index];\n var (magnitudes, signed) = op_meta[op_name];\n var magnitude = magnitudes.Dimensions > 0 ? magnitudes[this.magnitude].ToDouble() : 0.0;\n\n if (signed && torch.randint(0, 2, 1).ToBoolean())\n magnitude *= -1.0;\n\n img = apply_op(img, op_name, magnitude, interpolation, this.fill);\n }\n return img.MoveToOuterDisposeScope();\n }\n\n private Dictionary<opType, (Tensor, bool)> augmentation_space(int num_bins, (long height, long width) image_size)\n {\n return new Dictionary<opType, (Tensor, bool)> {\n { opType.Identity, (torch.tensor(0.0), false) },\n { opType.ShearX, (torch.linspace(0.0, 0.3, num_bins), true) },\n { opType.ShearY, (torch.linspace(0.0, 0.3, num_bins), true) },\n { opType.TranslateX, (torch.linspace(0.0, 150.0 / 331.0 * image_size.height, num_bins), true) },\n { opType.TranslateY, (torch.linspace(0.0, 150.0 / 331.0 * image_size.width, num_bins), true) },\n { opType.Rotate, (torch.linspace(0.0, 30.0, num_bins), true) },\n { opType.Brightness, (torch.linspace(0.0, 0.9, num_bins), true) },\n { opType.Color, (torch.linspace(0.0, 0.9, num_bins), true) },\n { opType.Contrast, (torch.linspace(0.0, 0.9, num_bins), true) },\n { opType.Sharpness, (torch.linspace(0.0, 0.9, num_bins), true) },\n { opType.Posterize, (8 - (torch.arange(num_bins) / ((num_bins - 1) / 4)).round().@int(), false)},\n { opType.Solarize, (torch.linspace(255.0, 0.0, num_bins), false) },\n { opType.AutoContrast, (torch.tensor(0.0), false) },\n { opType.Equalize, (torch.tensor(0.0), false) }\n };\n }\n\n private readonly int num_ops;\n private readonly int magnitude;\n private readonly int num_magnitude_bins;\n private readonly InterpolationMode interpolation;\n private readonly IList<float>? fill;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// RandAugment data augmentation method based on\n /// \"RandAugment: Practical automated data augmentation with a reduced search space\"\n /// https://arxiv.org/abs/1909.13719\n /// The image is expected to be a torch Tensor, it should be of type torch.uint8, and it is expected\n /// to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.\n /// </summary>\n /// <param name=\"num_ops\">Number of augmentation transformations to apply sequentially. Default: 2</param>\n /// <param name=\"magnitude\">Magnitude for all the transformations. Default: 9</param>\n /// <param name=\"num_magnitude_bins\">The number of different magnitude values. Default: 31</param>\n /// <param name=\"interpolation\">Desired interpolation enum defined by\n /// torchvision.transforms.InterpolationMode. Default: InterpolationMode.NEAREST.</param>\n /// <param name=\"fill\">Pixel fill value for the area outside the transformed\n /// image. If given a number, the value is used for all bands respectively. Default: null</param>\n static public ITransform RandAugment(\n int num_ops = 2,\n int magnitude = 9,\n int num_magnitude_bins = 31,\n InterpolationMode interpolation = InterpolationMode.Nearest,\n IList<float>? fill = null)\n {\n return new RandAugment(num_ops, magnitude, num_magnitude_bins, interpolation, fill);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5736501812934875, "alphanum_fraction": 0.5752227902412415, "avg_line_length": 42.35606002807617, "blob_id": "0f4ed65c2fb91ee2821da415f1600f77afa9d99e", "content_id": "4fbb086a3cb0d8e783ebdbf8b4ffb6cc6f417e50", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5725, "license_type": "permissive", "max_line_length": 149, "num_lines": 132, "path": "/src/TorchSharp/Distributions/Exponential.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// An Exponential distribution parameterized by `rate`.\n /// </summary>\n public class Exponential : torch.distributions.ExponentialFamily\n {\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public override Tensor mean => rate.reciprocal();\n\n public override Tensor mode => torch.zeros_like(rate);\n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public override Tensor variance => rate.pow(2);\n\n /// <summary>\n /// The standard deviation of the distribution\n /// </summary>\n public override Tensor stddev => rate.reciprocal();\n\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"rate\">rate = 1 / scale of the distribution (often referred to as 'β')</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n public Exponential(Tensor rate, torch.Generator generator = null) : base(generator)\n {\n var locScale = torch.broadcast_tensors(rate);\n this.batch_shape = rate.size();\n this.rate = locScale[0].DetachFromDisposeScope();\n }\n\n private Tensor rate;\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n public override Tensor rsample(params long[] sample_shape)\n {\n var shape = ExtendedShape(sample_shape);\n return rate.new_empty(shape).exponential_(generator: generator) / rate;\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor log_prob(Tensor value) => WrappedTensorDisposeScope(() => rate.log() - rate * value);\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n /// <returns></returns>\n public override Tensor entropy() => WrappedTensorDisposeScope(() => 1 - rate.log());\n\n /// <summary>\n /// Returns the cumulative density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor cdf(Tensor value) => WrappedTensorDisposeScope(() => 1 - torch.exp(-rate * value));\n\n /// <summary>\n /// Returns the inverse cumulative density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor icdf(Tensor value) => WrappedTensorDisposeScope(() => -torch.log(1 - value) / rate);\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is Exponential))\n throw new ArgumentException(\"expand(): 'instance' must be a Exponential distribution\");\n\n var r = rate.expand(batch_shape);\n\n var newDistribution = ((instance == null) ? new Exponential(r, generator) : instance) as Exponential;\n\n newDistribution.batch_shape = batch_shape;\n if (newDistribution == instance) {\n newDistribution.rate = r;\n }\n return newDistribution;\n }\n\n protected override IList<Tensor> NaturalParams => new Tensor[] { -rate };\n\n protected override Tensor MeanCarrierMeasure => torch.tensor(0, dtype:rate.dtype, device: rate.device);\n\n protected override Tensor LogNormalizer(params Tensor[] parameters) => -torch.log(-parameters[0]);\n }\n\n }\n\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a Exponential distribution parameterized by `rate`.\n /// </summary>\n /// <param name=\"rate\">rate = 1 / scale of the distribution (often referred to as 'β')</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Exponential Exponential(Tensor rate, torch.Generator generator = null)\n {\n return new Exponential(rate, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.4319537281990051, "alphanum_fraction": 0.4340375065803528, "avg_line_length": 40.053096771240234, "blob_id": "7ca88a51d0afb4d1c39b18d05f17be1c96005708", "content_id": "48f58f31f3a8f1ae7db47195c872176e18157155", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 27834, "license_type": "permissive", "max_line_length": 200, "num_lines": 678, "path": "/src/TorchSharp/Distributions/Transforms.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace TorchSharp\n{\n\n public static partial class torch\n {\n public static partial class distributions\n {\n public static partial class transforms\n {\n\n /// <summary>\n /// Abstract class for invertable transformations with computable log det jacobians.\n ///\n /// They are primarily used in torch.distributions.TransformedDistribution.\n /// </summary>\n /// <remarks>\n /// Derived classes should implement one or both of 'forward()' or 'inverse()'.\n /// Derived classes that set `bijective=true` should also implement 'log_abs_det_jacobian()'\n /// </remarks>\n public abstract class Transform\n {\n protected bool _bijective = false;\n\n protected constraints.Constraint _domain;\n\n protected constraints.Constraint _codomain;\n\n protected Transform _inv = null;\n\n public virtual int event_dim {\n get {\n if (_domain.event_dim == codomain.event_dim)\n return _domain.event_dim;\n throw new InvalidOperationException(\"Please use either .domain.event_dim or .codomain.event_dim\");\n }\n }\n\n public virtual Transform inv {\n get {\n Transform result = null;\n if (this._inv != null)\n result = _inv;\n if (result == null) {\n result = new _InverseTransform(this);\n _inv = result;\n }\n return result;\n }\n }\n\n public virtual constraints.Constraint domain {\n get {\n return _domain;\n }\n }\n\n public virtual constraints.Constraint codomain {\n get {\n return _codomain;\n }\n }\n\n public virtual bool bijective {\n get {\n return _bijective;\n }\n }\n\n public Tensor sign {\n get {\n return _sign();\n }\n }\n\n protected internal virtual Tensor _sign()\n {\n throw new NotImplementedException();\n }\n\n protected internal abstract Tensor _call(Tensor x);\n\n protected internal abstract Tensor _inverse(Tensor y);\n\n protected internal virtual Tensor log_abs_det_jacobian(Tensor x, Tensor y)\n {\n throw new NotImplementedException();\n }\n\n public Tensor forward(Tensor x) => this._call(x);\n\n public virtual long[] forward_shape(long[] shape) => shape;\n\n public virtual long[] inverse_shape(long[] shape) => shape;\n\n protected internal static Tensor _sum_rightmost(Tensor value, int dim)\n {\n if (dim == 0) return value;\n var required_shape = new long[value.shape.Length - dim + 1];\n var i = 0;\n for (; i < value.shape.Length - dim; i++) required_shape[i] = value.shape[i];\n required_shape[i] = -1;\n return value.reshape(required_shape).sum(-1);\n }\n }\n\n\n internal class _InverseTransform : Transform\n {\n public _InverseTransform(torch.distributions.transforms.Transform transform)\n {\n this._inv = transform;\n }\n\n public override constraints.Constraint domain {\n get {\n return _inv.domain;\n }\n }\n\n public override constraints.Constraint codomain {\n get {\n return _inv.codomain;\n }\n }\n\n public override bool bijective {\n get {\n return _inv.bijective;\n }\n }\n\n public override int event_dim => base.event_dim;\n\n public override Transform inv => base.inv;\n\n protected internal override Tensor log_abs_det_jacobian(Tensor x, Tensor y)\n {\n return -_inv.log_abs_det_jacobian(y, x);\n }\n\n protected internal override Tensor _call(Tensor x)\n {\n return _inv._inverse(x);\n }\n\n protected internal override Tensor _inverse(Tensor y)\n {\n return _inv._call(y);\n }\n\n protected internal override Tensor _sign()\n {\n return _inv.sign;\n }\n\n public override long[] forward_shape(long[] shape)\n {\n return _inv.forward_shape(shape);\n }\n\n public override long[] inverse_shape(long[] shape)\n {\n return _inv.inverse_shape(shape);\n }\n }\n\n public class ComposeTransform : Transform\n {\n public ComposeTransform(IEnumerable<Transform> parts, int cache_size = 0)\n {\n if (parts == null) throw new ArgumentNullException(\"parts cannot be null\");\n\n _parts = parts.ToArray();\n _reverse_parts = parts.Reverse().ToArray();\n }\n\n private Transform[] _parts;\n private Transform[] _reverse_parts;\n\n public override int event_dim => base.event_dim;\n\n public override Transform inv {\n get {\n Transform i = _inv;\n\n if (i == null) {\n i = new ComposeTransform(_reverse_parts.Select(p => p.inv));\n _inv = i;\n }\n return _inv;\n }\n }\n\n public override constraints.Constraint domain {\n get {\n if (_parts == null) return constraints.real;\n\n var cnt = _parts.Length;\n var d = _parts[0].domain;\n\n var ed = _parts[cnt - 1].codomain.event_dim;\n foreach (var part in _reverse_parts) {\n ed += part.domain.event_dim - part.codomain.event_dim;\n ed = ed < part.domain.event_dim ? part.domain.event_dim : ed;\n }\n if (ed > d.event_dim) {\n d = constraints.independent(domain, ed - domain.event_dim);\n }\n return d;\n }\n }\n\n public override constraints.Constraint codomain {\n get {\n if (_parts == null) return constraints.real;\n\n var cnt = _parts.Length;\n var cod = _parts[cnt - 1].domain;\n\n var ed = _parts[0].domain.event_dim;\n foreach (var part in _parts) {\n ed += part.codomain.event_dim - part.domain.event_dim;\n ed = ed < part.codomain.event_dim ? part.codomain.event_dim : ed;\n }\n if (ed > cod.event_dim) {\n cod = constraints.independent(codomain, ed - codomain.event_dim);\n }\n return cod;\n }\n }\n\n public override bool bijective => _parts.All(p => p.bijective);\n\n protected internal override Tensor _sign()\n {\n Tensor s = 1;\n foreach (var p in _parts) s *= p.sign;\n return s;\n }\n\n protected internal override Tensor _call(Tensor x)\n {\n using var _ = torch.NewDisposeScope();\n foreach (var p in _parts) {\n x = p._call(x);\n }\n return x.MoveToOuterDisposeScope();\n }\n\n protected internal override Tensor _inverse(Tensor y)\n {\n throw new NotImplementedException();\n }\n\n protected internal override Tensor log_abs_det_jacobian(Tensor x, Tensor y)\n {\n if (_parts == null) {\n return torch.zeros_like(x);\n }\n\n using var _ = torch.NewDisposeScope();\n\n var xs = new List<Tensor>();\n xs.Add(x);\n for (int i = 0; i < _parts.Length-1; i++) {\n var part = _parts[i];\n xs.Add(part._call(xs[i]));\n }\n xs.Add(y);\n\n var terms = new List<Tensor>();\n var event_dim = domain.event_dim;\n\n for (int i = 0; i < _parts.Length - 1; i++) {\n var part = _parts[i];\n var x1 = xs[i];\n var y1 = xs[i + 1];\n\n terms.Add(_sum_rightmost(part.log_abs_det_jacobian(x1, y), event_dim - part.domain.event_dim));\n event_dim += part.codomain.event_dim - part.domain.event_dim;\n }\n\n Tensor result = terms[0];\n for (var i = 1; i < terms.Count; i++) {\n result = result + terms[i];\n }\n return result.MoveToOuterDisposeScope();\n }\n\n public override long[] forward_shape(long[] shape)\n {\n foreach (var p in _parts) {\n shape = p.forward_shape(shape);\n }\n return shape;\n }\n\n public override long[] inverse_shape(long[] shape)\n {\n foreach (var p in _reverse_parts) {\n shape = p.forward_shape(shape);\n }\n return shape;\n }\n }\n\n public class IndepdenentTransform : Transform\n {\n private Transform base_transform;\n private int reinterpreted_batch_dims;\n\n public IndepdenentTransform(Transform base_transform, int reinterpreted_batch_dims)\n {\n this.base_transform = base_transform;\n this.reinterpreted_batch_dims = reinterpreted_batch_dims;\n }\n\n public override int event_dim => base.event_dim;\n\n public override Transform inv => base.inv;\n\n public override constraints.Constraint domain => constraints.independent(base_transform.domain, reinterpreted_batch_dims);\n\n public override constraints.Constraint codomain => constraints.independent(base_transform.codomain, reinterpreted_batch_dims);\n\n public override bool bijective => base_transform.bijective;\n\n public override long[] forward_shape(long[] shape)\n {\n return base_transform.forward_shape(shape);\n }\n\n public override long[] inverse_shape(long[] shape)\n {\n return base_transform.inverse_shape(shape);\n }\n\n protected internal override Tensor _sign() => base_transform._sign();\n\n protected internal override Tensor log_abs_det_jacobian(Tensor x, Tensor y)\n {\n using var _ = torch.NewDisposeScope();\n var result = base_transform.log_abs_det_jacobian(x, y);\n result = _sum_rightmost(result, reinterpreted_batch_dims);\n return result.MoveToOuterDisposeScope();\n }\n\n protected internal override Tensor _call(Tensor x)\n {\n if (x.dim() < domain.event_dim)\n throw new ArgumentException(\"Too few dimensions on input\");\n return base_transform._call(x);\n }\n\n protected internal override Tensor _inverse(Tensor y)\n {\n if (y.dim() < codomain.event_dim)\n throw new ArgumentException(\"Too few dimensions on input\");\n return base_transform._inverse(y);\n }\n }\n\n public class ReshapeTransform : Transform\n {\n private Size in_shape;\n private Size out_shape;\n\n public ReshapeTransform(long[] in_shape, long[] out_shape)\n {\n this.in_shape = in_shape;\n this.out_shape = out_shape;\n if (this.in_shape.numel() != this.out_shape.numel())\n throw new ArgumentException(\"in_shape, out_shape have different numbers of elements\");\n\n }\n public override bool bijective => true;\n\n public override constraints.Constraint domain => constraints.independent(constraints.real, in_shape.Length);\n\n public override constraints.Constraint codomain => constraints.independent(constraints.real, out_shape.Length);\n\n public override long[] forward_shape(long[] shape)\n {\n return base.forward_shape(shape);\n }\n\n public override long[] inverse_shape(long[] shape)\n {\n return base.inverse_shape(shape);\n }\n\n protected internal override Tensor log_abs_det_jacobian(Tensor x, Tensor y)\n {\n long inLen = x.shape.Length - (x.dim() - in_shape.Length);\n var batch_shape = new long[inLen];\n for (var i = 0; i < inLen; i++) {\n batch_shape[i] = x.shape[i];\n }\n return x.new_zeros(batch_shape);\n }\n\n protected internal override Tensor _call(Tensor x)\n {\n long inLen = x.shape.Length - (x.dim() - in_shape.Length);\n long otLen = out_shape.Length;\n var batch_shape = new long[inLen+otLen];\n for (var i = 0; i < inLen; i++) {\n batch_shape[i] = x.shape[i];\n }\n for (var i = 0; i < otLen; i++) {\n batch_shape[i+inLen] = out_shape[i];\n }\n return x.reshape(batch_shape);\n }\n\n protected internal override Tensor _inverse(Tensor y)\n {\n long otLen = y.shape.Length - (y.dim() - out_shape.Length);\n long inLen = in_shape.Length;\n var batch_shape = new long[inLen + otLen];\n for (var i = 0; i < otLen; i++) {\n batch_shape[i] = y.shape[i];\n }\n for (var i = 0; i < inLen; i++) {\n batch_shape[i + otLen] = in_shape[i];\n }\n return y.reshape(batch_shape);\n }\n }\n\n public class ExpTransform : Transform\n {\n public override constraints.Constraint domain => constraints.real;\n\n public override constraints.Constraint codomain => constraints.positive;\n\n public override bool bijective => true;\n\n protected internal override Tensor _sign() => 1;\n\n protected internal override Tensor log_abs_det_jacobian(Tensor x, Tensor y) => x;\n protected internal override Tensor _call(Tensor x) => x.exp();\n\n protected internal override Tensor _inverse(Tensor y) => y.log();\n }\n\n public class LogTransform : Transform\n {\n public override constraints.Constraint domain => constraints.positive;\n\n public override constraints.Constraint codomain => constraints.real;\n\n public override bool bijective => true;\n\n protected internal override Tensor _sign() => 1;\n\n protected internal override Tensor log_abs_det_jacobian(Tensor x, Tensor y) => -x;\n\n protected internal override Tensor _call(Tensor x) => x.log();\n\n protected internal override Tensor _inverse(Tensor y) => y.exp();\n }\n\n public class PowerTransform : Transform\n {\n private Tensor exponent;\n\n public PowerTransform(Tensor exponent)\n {\n this.exponent = exponent;\n }\n\n public override constraints.Constraint domain => constraints.positive;\n\n public override constraints.Constraint codomain => constraints.positive;\n\n public override bool bijective => true;\n\n protected internal override Tensor _sign() => 1;\n\n public override long[] forward_shape(long[] shape)\n {\n return torch.broadcast_shapes(shape, exponent.shape).Shape;\n }\n\n public override long[] inverse_shape(long[] shape)\n {\n return torch.broadcast_shapes(shape, exponent.shape).Shape;\n }\n\n protected internal override Tensor log_abs_det_jacobian(Tensor x, Tensor y)\n {\n return torch.WrappedTensorDisposeScope(() => (exponent * y / x).abs().log());\n }\n\n protected internal override Tensor _call(Tensor x)\n {\n return x.pow(exponent);\n }\n\n protected internal override Tensor _inverse(Tensor y)\n {\n return y.pow(1 / exponent);\n }\n }\n\n public class SigmoidTransform : Transform\n {\n public override constraints.Constraint domain => constraints.real;\n\n public override constraints.Constraint codomain => constraints.unit_interval;\n\n public override bool bijective => true;\n\n protected internal override Tensor _sign() => 1;\n\n protected internal override Tensor log_abs_det_jacobian(Tensor x, Tensor y) => -nn.functional.softplus(-x) - nn.functional.softplus(x);\n\n protected internal override Tensor _call(Tensor x)\n {\n var finfo = torch.finfo(x.dtype);\n return torch.WrappedTensorDisposeScope(() => torch.clamp(torch.sigmoid(x), min: finfo.tiny, max: 1 - finfo.eps));\n }\n\n protected internal override Tensor _inverse(Tensor y)\n {\n using var _ = torch.NewDisposeScope();\n var finfo = torch.finfo(y.dtype);\n y = y.clamp(min: finfo.tiny, max: 1 - finfo.eps);\n return (y.log() - (-y).log1p()).MoveToOuterDisposeScope();\n }\n }\n\n public class SoftplusTransform : Transform\n {\n public override constraints.Constraint domain => constraints.real;\n\n public override constraints.Constraint codomain => constraints.positive;\n\n public override bool bijective => true;\n\n protected internal override Tensor _sign() => 1;\n\n protected internal override Tensor log_abs_det_jacobian(Tensor x, Tensor y) => -nn.functional.softplus(-x);\n\n protected internal override Tensor _call(Tensor x) => nn.functional.softplus(-x);\n\n protected internal override Tensor _inverse(Tensor y) => (-y).expm1().neg().log() + y;\n }\n\n public class SoftmaxTransform : Transform\n {\n public override constraints.Constraint domain => constraints.real_vector;\n\n public override constraints.Constraint codomain => constraints.simplex;\n\n public override bool bijective => true;\n\n protected internal override Tensor _call(Tensor x)\n {\n var logprobs = x;\n var probs = (logprobs - logprobs.max(-1, true).values).exp();\n return probs / probs.sum(-1, true);\n }\n\n protected internal override Tensor _inverse(Tensor y)\n {\n return y.log();\n }\n }\n\n\n public class TanhTransform : Transform\n {\n public override constraints.Constraint domain => constraints.real;\n\n public override constraints.Constraint codomain => constraints.interval(-1.0, 1.0);\n\n public override bool bijective => true;\n\n protected internal override Tensor _sign() => 1;\n\n protected internal override Tensor log_abs_det_jacobian(Tensor x, Tensor y) => torch.WrappedTensorDisposeScope(() => 2.0 * (Math.Log(2.0) - x - -nn.functional.softplus(-2.0 * x)));\n\n protected internal override Tensor _call(Tensor x) => x.tanh();\n\n protected internal override Tensor _inverse(Tensor y) => y.atanh();\n }\n\n public class AbsTransform : Transform\n {\n public override constraints.Constraint domain => constraints.real;\n\n public override constraints.Constraint codomain => constraints.positive;\n\n protected internal override Tensor _call(Tensor x) => x.abs();\n\n protected internal override Tensor _inverse(Tensor y) => y;\n }\n\n public class AffineTransform : Transform\n {\n private Tensor loc;\n private Tensor scale;\n private int _event_dim;\n\n public AffineTransform(double loc, double scale, int event_dim = 0)\n {\n this._event_dim = event_dim;\n this.loc = loc;\n this.scale = scale;\n }\n\n public AffineTransform (Tensor loc, Tensor scale, int event_dim = 0)\n {\n this._event_dim = event_dim;\n this.loc = loc;\n this.scale = scale;\n }\n\n public override int event_dim => _event_dim;\n\n public override bool bijective => true;\n\n public override constraints.Constraint domain =>\n _event_dim == 0 ? constraints.real : constraints.independent(constraints.real, event_dim);\n\n public override constraints.Constraint codomain =>\n _event_dim == 0 ? constraints.real : constraints.independent(constraints.real, event_dim);\n\n public override long[] forward_shape(long[] shape)\n {\n return torch.broadcast_shapes(shape, loc.shape, scale.shape).Shape;\n }\n\n public override long[] inverse_shape(long[] shape)\n {\n return torch.broadcast_shapes(shape, loc.shape, scale.shape).Shape;\n }\n\n protected internal override Tensor log_abs_det_jacobian(Tensor x, Tensor y)\n {\n using var _ = torch.NewDisposeScope();\n var shape = x.shape;\n var scale = this.scale;\n var result = torch.abs(scale).log();\n\n if (_event_dim > 0) {\n var result_size = new long[result.shape.Length - _event_dim + 1];\n int i = 0;\n for (; i < result.shape.Length - _event_dim; i++) result_size[i] = result.shape[i];\n result_size[i] = -1;\n result = result.view(result_size).sum(-1);\n var nshape = new long[shape.Length];\n for (; i < shape.Length - _event_dim; i++) nshape[i] = shape[i];\n shape = nshape;\n }\n return result.expand(shape).MoveToOuterDisposeScope();\n }\n\n protected internal override Tensor _call(Tensor x) => torch.WrappedTensorDisposeScope(() => loc + scale * x);\n\n protected internal override Tensor _inverse(Tensor y) => torch.WrappedTensorDisposeScope(() => (y - loc) / scale);\n\n protected internal override Tensor _sign()\n {\n return scale.sign();\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6935985088348389, "alphanum_fraction": 0.7016780376434326, "avg_line_length": 39.224998474121094, "blob_id": "f788fa7e0caaf70a7fa0398e2ae4b69a1eb8b438", "content_id": "bc54870cd554a8893b69066c4bcce17356955df5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1609, "license_type": "permissive", "max_line_length": 130, "num_lines": 40, "path": "/src/TorchSharp/PInvoke/LibTorchSharp.THSData.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp.PInvoke\n{\n internal static partial class NativeMethods\n {\n#pragma warning disable CA2101\n [DllImport(\"LibTorchSharp\", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]\n internal static extern IntPtr THSData_loaderMNIST(\n [MarshalAs(UnmanagedType.LPStr)] string filename,\n long batchSize,\n [MarshalAs(UnmanagedType.U1)] bool isTrain);\n\n [DllImport(\"LibTorchSharp\", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]\n internal static extern IntPtr THSData_loaderCIFAR10(\n [MarshalAs(UnmanagedType.LPStr)] string path,\n long batchSize,\n [MarshalAs(UnmanagedType.U1)] bool isTrain);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSData_current(IntPtr iterator, IntPtr data, IntPtr target);\n\n [DllImport(\"LibTorchSharp\")]\n [return: MarshalAs(UnmanagedType.U1)]\n internal static extern bool THSData_moveNext(IntPtr iterator);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern long THSData_size(IntPtr iterator);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSData_reset(IntPtr iterator);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSData_dispose(IntPtr iterator);\n }\n#pragma warning restore CA2101\n}\n" }, { "alpha_fraction": 0.5785619020462036, "alphanum_fraction": 0.5825566053390503, "avg_line_length": 34.78571319580078, "blob_id": "edbc10770974a49626d6a0d4677e3d08ee68af0b", "content_id": "a9ee0ebe6bf3317ca1e3e115f971a3e9b27841df", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1502, "license_type": "permissive", "max_line_length": 130, "num_lines": 42, "path": "/src/TorchVision/AdjustSaturation.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class AdjustSaturation : ITransform\n {\n internal AdjustSaturation(double saturation_factor)\n {\n if (saturation_factor < 0.0)\n throw new ArgumentException($\"The saturation factor ({saturation_factor}) must be non-negative.\");\n this.saturation_factor = saturation_factor;\n }\n\n public Tensor call(Tensor img)\n {\n return transforms.functional.adjust_saturation(img, saturation_factor);\n }\n\n private double saturation_factor;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Adjust the color saturation of an image.\n /// </summary>\n /// <param name=\"saturation_factor\">\n /// How much to adjust the saturation. 0 will give a black and white image, 1 will give the original image\n /// while 2 will enhance the saturation by a factor of 2.\n /// </param>\n /// <returns></returns>\n static public ITransform AdjustSaturation(double saturation_factor)\n {\n return new AdjustSaturation(saturation_factor);\n }\n }\n }\n}" }, { "alpha_fraction": 0.5086056590080261, "alphanum_fraction": 0.5247212052345276, "avg_line_length": 39.3984375, "blob_id": "38cc94d081a917e7ddbdb63ab623d68c1a7148fb", "content_id": "7d12f5cc60032d2d00e14ac07ff3af4e0fa61875", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 15513, "license_type": "permissive", "max_line_length": 149, "num_lines": 384, "path": "/src/TorchAudio/Modules/WaveRNN.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchaudio,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/audio/blob/c15eee23964098f88ab0afe25a8d5cd9d728af54/torchaudio/models/wavernn.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/audio/blob/main/LICENSE\n//\n\nusing System;\nusing System.Collections.Generic;\nusing static TorchSharp.torch;\nusing F = TorchSharp.torch.nn.functional;\n\n#nullable enable\nnamespace TorchSharp.Modules\n{\n /// <summary>\n /// This class is used to represent a WaveRNN module.\n /// </summary>\n public class WaveRNN : nn.Module<Tensor, Tensor, Tensor>\n {\n private readonly int _pad;\n public readonly nn.Module<Tensor, Tensor> fc;\n public readonly nn.Module<Tensor, Tensor> fc1;\n public readonly nn.Module<Tensor, Tensor> fc2;\n public readonly nn.Module<Tensor, Tensor> fc3;\n public readonly int hop_length;\n public readonly int kernel_size;\n public readonly int n_aux;\n public readonly int n_bits;\n public readonly int n_classes;\n public readonly int n_rnn;\n public readonly nn.Module<Tensor, Tensor> relu1;\n public readonly nn.Module<Tensor, Tensor> relu2;\n public readonly GRU rnn1;\n public readonly GRU rnn2;\n internal readonly UpsampleNetwork upsample;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n fc.Dispose();\n fc1.Dispose();\n fc2.Dispose();\n fc3.Dispose();\n relu1.Dispose();\n relu2.Dispose();\n rnn1.Dispose();\n rnn2.Dispose();\n upsample.Dispose();\n }\n base.Dispose(disposing);\n }\n\n internal WaveRNN(\n string name,\n long[] upsample_scales,\n int n_classes,\n int hop_length,\n int n_res_block = 10,\n int n_rnn = 512,\n int n_fc = 512,\n int kernel_size = 5,\n int n_freq = 128,\n int n_hidden = 128,\n int n_output = 128) : base(name)\n {\n this.kernel_size = kernel_size;\n this._pad = (kernel_size % 2 == 1 ? kernel_size - 1 : kernel_size) / 2;\n this.n_rnn = n_rnn;\n this.n_aux = n_output / 4;\n this.hop_length = hop_length;\n this.n_classes = n_classes;\n this.n_bits = (int)(Math.Log(this.n_classes) / Math.Log(2) + 0.5);\n\n long total_scale = 1;\n foreach (var upsample_scale in upsample_scales) {\n total_scale *= upsample_scale;\n }\n if (total_scale != this.hop_length) {\n throw new ArgumentException($\"Expected: total_scale == hop_length, but found {total_scale} != {hop_length}\");\n }\n\n this.upsample = new UpsampleNetwork(\"upsamplenetwork\", upsample_scales, n_res_block, n_freq, n_hidden, n_output, kernel_size);\n this.fc = nn.Linear(n_freq + this.n_aux + 1, n_rnn);\n\n this.rnn1 = nn.GRU(n_rnn, n_rnn, batchFirst: true);\n this.rnn2 = nn.GRU(n_rnn + this.n_aux, n_rnn, batchFirst: true);\n\n this.relu1 = nn.ReLU(inplace: true);\n this.relu2 = nn.ReLU(inplace: true);\n\n this.fc1 = nn.Linear(n_rnn + this.n_aux, n_fc);\n this.fc2 = nn.Linear(n_fc + this.n_aux, n_fc);\n this.fc3 = nn.Linear(n_fc, this.n_classes);\n\n this.RegisterComponents();\n }\n\n /// <summary>\n /// Pass the input through the WaveRNN model.\n /// </summary>\n /// <param name=\"waveform\">The input waveform to the WaveRNN layer</param>\n /// <param name=\"specgram\">The input spectrogram to the WaveRNN layer</param>\n /// <returns></returns>\n /// <exception cref=\"ArgumentException\"></exception>\n public override Tensor forward(Tensor waveform, Tensor specgram)\n {\n if (waveform.size(1) != 1) {\n throw new ArgumentException(\"Require the input channel of waveform is 1\");\n }\n if (specgram.size(1) != 1) {\n throw new ArgumentException(\"Require the input channel of specgram is 1\");\n }\n // remove channel dimension until the end\n waveform = waveform.squeeze(1);\n specgram = specgram.squeeze(1);\n\n var batch_size = waveform.size(0);\n var h1 = torch.zeros(1, batch_size, this.n_rnn, dtype: waveform.dtype, device: waveform.device);\n var h2 = torch.zeros(1, batch_size, this.n_rnn, dtype: waveform.dtype, device: waveform.device);\n // output of upsample:\n // specgram: (n_batch, n_freq, (n_time - kernel_size + 1) * total_scale)\n // aux: (n_batch, n_output, (n_time - kernel_size + 1) * total_scale)\n Tensor aux;\n (specgram, aux) = this.upsample.call(specgram);\n specgram = specgram.transpose(1, 2);\n aux = aux.transpose(1, 2);\n\n var aux_idx = new long[5];\n for (int i = 0; i < aux_idx.Length; i++) {\n aux_idx[i] = this.n_aux * i;\n }\n var a1 = aux[TensorIndex.Colon, TensorIndex.Colon, TensorIndex.Slice(aux_idx[0], aux_idx[1])];\n var a2 = aux[TensorIndex.Colon, TensorIndex.Colon, TensorIndex.Slice(aux_idx[1], aux_idx[2])];\n var a3 = aux[TensorIndex.Colon, TensorIndex.Colon, TensorIndex.Slice(aux_idx[2], aux_idx[3])];\n var a4 = aux[TensorIndex.Colon, TensorIndex.Colon, TensorIndex.Slice(aux_idx[3], aux_idx[4])];\n\n var x = torch.cat(new Tensor[] { waveform.unsqueeze(-1), specgram, a1 }, dim: -1);\n x = this.fc.call(x);\n var res = x;\n (x, _) = this.rnn1.call(x, h1);\n\n x = x + res;\n res = x;\n x = torch.cat(new Tensor[] { x, a2 }, dim: -1);\n (x, _) = this.rnn2.call(x, h2);\n\n x = x + res;\n x = torch.cat(new Tensor[] { x, a3 }, dim: -1);\n x = this.fc1.call(x);\n x = this.relu1.call(x);\n\n x = torch.cat(new Tensor[] { x, a4 }, dim: -1);\n x = this.fc2.call(x);\n x = this.relu2.call(x);\n x = this.fc3.call(x);\n\n // bring back channel dimension\n return x.unsqueeze(1);\n }\n\n /// <summary>\n /// Inference method of WaveRNN.\n /// </summary>\n /// <param name=\"specgram\">Batch of spectrograms.</param>\n /// <param name=\"lengths\">Indicates the valid length of each audio in the batch.</param>\n /// <returns>The inferred waveform and the valid length in time axis of the output Tensor.</returns>\n public virtual (Tensor, Tensor?) infer(Tensor specgram, Tensor? lengths = null)\n {\n var device = specgram.device;\n var dtype = specgram.dtype;\n\n specgram = torch.nn.functional.pad(specgram, (this._pad, this._pad));\n Tensor aux;\n (specgram, aux) = this.upsample.call(specgram);\n if (lengths is not null) {\n lengths = lengths * this.upsample.total_scale;\n }\n\n var output = new List<Tensor>();\n long b_size = specgram.size(0);\n long seq_len = specgram.size(2);\n\n var h1 = torch.zeros(new long[] { 1, b_size, this.n_rnn }, device: device, dtype: dtype);\n var h2 = torch.zeros(new long[] { 1, b_size, this.n_rnn }, device: device, dtype: dtype);\n var x = torch.zeros(new long[] { b_size, 1 }, device: device, dtype: dtype);\n\n var aux_split = new Tensor[4];\n for (int i = 0; i < 4; i++) {\n aux_split[i] = aux[TensorIndex.Colon, TensorIndex.Slice(this.n_aux * i, this.n_aux * (i + 1)), TensorIndex.Colon];\n }\n\n for (int i = 0; i < seq_len; i++) {\n\n var m_t = specgram[TensorIndex.Colon, TensorIndex.Colon, i];\n\n var a1_t = aux_split[0][TensorIndex.Colon, TensorIndex.Colon, i];\n var a2_t = aux_split[1][TensorIndex.Colon, TensorIndex.Colon, i];\n var a3_t = aux_split[2][TensorIndex.Colon, TensorIndex.Colon, i];\n var a4_t = aux_split[3][TensorIndex.Colon, TensorIndex.Colon, i];\n\n x = torch.cat(new Tensor[] { x, m_t, a1_t }, dim: 1);\n x = this.fc.call(x);\n (_, h1) = this.rnn1.call(x.unsqueeze(1), h1);\n\n x = x + h1[0];\n var inp = torch.cat(new Tensor[] { x, a2_t }, dim: 1);\n (_, h2) = this.rnn2.call(inp.unsqueeze(1), h2);\n\n x = x + h2[0];\n x = torch.cat(new Tensor[] { x, a3_t }, dim: 1);\n x = F.relu(this.fc1.call(x));\n\n x = torch.cat(new Tensor[] { x, a4_t }, dim: 1);\n x = F.relu(this.fc2.call(x));\n\n var logits = this.fc3.call(x);\n\n var posterior = F.softmax(logits, dim: 1);\n\n x = torch.multinomial(posterior, 1).@float();\n // Transform label [0, 2 ** n_bits - 1] to waveform [-1, 1]\n\n x = 2 * x / ((1 << this.n_bits) - 1.0) - 1.0;\n\n output.Add(x);\n }\n return (torch.stack(output).permute(1, 2, 0), lengths);\n }\n\n private class ResBlock : nn.Module<Tensor, Tensor>\n {\n public nn.Module<Tensor, Tensor> resblock_model;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n resblock_model.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public ResBlock(string name, int n_freq = 128) : base(name)\n {\n this.resblock_model = nn.Sequential(\n nn.Conv1d(inputChannel: n_freq, outputChannel: n_freq, kernelSize: 1, bias: false),\n nn.BatchNorm1d(n_freq),\n nn.ReLU(inplace: true),\n nn.Conv1d(inputChannel: n_freq, outputChannel: n_freq, kernelSize: 1, bias: false),\n nn.BatchNorm1d(n_freq));\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor specgram)\n {\n return this.resblock_model.call(specgram) + specgram;\n }\n }\n\n internal class MelResNet : nn.Module<Tensor, Tensor>\n {\n public readonly nn.Module<Tensor, Tensor> melresnet_model;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n melresnet_model.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public MelResNet(\n string name,\n int n_res_block = 10,\n int n_freq = 128,\n int n_hidden = 128,\n int n_output = 128,\n int kernel_size = 5) : base(name)\n {\n var modules = new List<nn.Module<Tensor, Tensor>>();\n modules.Add(nn.Conv1d(inputChannel: n_freq, outputChannel: n_hidden, kernelSize: kernel_size, bias: false));\n modules.Add(nn.BatchNorm1d(n_hidden));\n modules.Add(nn.ReLU(inplace: true));\n for (int i = 0; i < n_res_block; i++) {\n modules.Add(new ResBlock(\"resblock\", n_hidden));\n }\n modules.Add(nn.Conv1d(inputChannel: n_hidden, outputChannel: n_output, kernelSize: 1));\n this.melresnet_model = nn.Sequential(modules);\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor specgram)\n {\n return this.melresnet_model.call(specgram);\n }\n }\n\n public class Stretch2d : nn.Module<Tensor, Tensor>\n {\n public long freq_scale;\n public long time_scale;\n\n public Stretch2d(string name, long time_scale, long freq_scale) : base(name)\n {\n this.freq_scale = freq_scale;\n this.time_scale = time_scale;\n this.RegisterComponents();\n }\n\n public override Tensor forward(Tensor specgram)\n {\n return specgram.repeat_interleave(this.freq_scale, -2).repeat_interleave(this.time_scale, -1);\n }\n }\n\n internal class UpsampleNetwork : nn.Module<Tensor, (Tensor,Tensor)>\n {\n public readonly long indent;\n public readonly MelResNet resnet;\n public readonly Stretch2d resnet_stretch;\n public readonly long total_scale;\n public readonly nn.Module<Tensor, Tensor> upsample_layers;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n resnet.Dispose();\n resnet_stretch.Dispose();\n upsample_layers .Dispose();\n }\n base.Dispose(disposing);\n }\n\n public UpsampleNetwork(\n string name,\n long[] upsample_scales,\n int n_res_block = 10,\n int n_freq = 128,\n int n_hidden = 128,\n int n_output = 128,\n int kernel_size = 5) : base(name)\n {\n long total_scale = 1;\n foreach (var upsample_scale in upsample_scales) {\n total_scale *= upsample_scale;\n }\n this.total_scale = total_scale;\n\n this.indent = (kernel_size - 1) / 2 * total_scale;\n this.resnet = new MelResNet(\"melresnet\", n_res_block, n_freq, n_hidden, n_output, kernel_size);\n this.resnet_stretch = new Stretch2d(\"stretch2d\", total_scale, 1);\n\n var up_layers = new List<nn.Module<Tensor, Tensor>>();\n foreach (var scale in upsample_scales) {\n var stretch = new Stretch2d(\"stretch2d\", scale, 1);\n var conv = nn.Conv2d(inputChannel: 1, outputChannel: 1, kernelSize: (1, scale * 2 + 1), padding: (0, scale), bias: false);\n torch.nn.init.constant_(conv.weight, 1.0 / (scale * 2 + 1));\n up_layers.Add(stretch);\n up_layers.Add(conv);\n }\n this.upsample_layers = nn.Sequential(up_layers);\n this.RegisterComponents();\n }\n\n public override (Tensor, Tensor) forward(Tensor specgram)\n {\n var resnet_output = this.resnet.call(specgram).unsqueeze(1);\n resnet_output = this.resnet_stretch.call(resnet_output);\n resnet_output = resnet_output.squeeze(1);\n\n specgram = specgram.unsqueeze(1);\n var upsampling_output = this.upsample_layers.call(specgram);\n upsampling_output = upsampling_output.squeeze(1)[TensorIndex.Colon, TensorIndex.Colon, TensorIndex.Slice(this.indent, -this.indent)];\n\n return (upsampling_output, resnet_output);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5384615659713745, "alphanum_fraction": 0.5384615659713745, "avg_line_length": 26.736841201782227, "blob_id": "42003a6ad9d51768ecf613f46814f4353df34c7e", "content_id": "7cb598edad11660fbe13f0dbcfaf82eb971e374a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1053, "license_type": "permissive", "max_line_length": 130, "num_lines": 38, "path": "/src/TorchVision/Lambda.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class Lambda : ITransform\n {\n internal Lambda(Func<Tensor, Tensor> lambda)\n {\n this.lambda = lambda;\n }\n\n public Tensor call(Tensor img)\n {\n return lambda(img);\n }\n\n private Func<Tensor, Tensor> lambda;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Apply a user-defined function as a transform. \n /// </summary>\n /// <param name=\"lambda\">Lambda/function to be used for transform.</param>\n /// <returns></returns>\n static public ITransform Lambda(Func<Tensor, Tensor> lambda)\n {\n return new Lambda(lambda);\n }\n }\n }\n}" }, { "alpha_fraction": 0.57302325963974, "alphanum_fraction": 0.5801550149917603, "avg_line_length": 42.58108139038086, "blob_id": "afb5d19e7142226a9e7999f8353927175bd9ef44", "content_id": "363cb40d59f29b76c3c54271c99d91a6e40ac5a1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3225, "license_type": "permissive", "max_line_length": 169, "num_lines": 74, "path": "/src/TorchSharp/NN/Dropout2d.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a Dropout2d module.\n /// </summary>\n public sealed class Dropout2d : torch.nn.Module<Tensor, Tensor>\n {\n internal Dropout2d(double p = 0.5, bool inplace = false) : base(nameof(Dropout2d))\n {\n this.p = p;\n this.inplace = inplace;\n }\n\n public override Tensor forward(Tensor input)\n {\n var res = THSNN_dropout2d(input.Handle, p, this.training, inplace);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n\n private bool inplace;\n private double p;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Randomly zero out entire channels (a channel is a 2D feature map, e.g., the jj -th channel of the ii -th sample in the batched input is a 2D tensor).\n /// Each channel will be zeroed out independently on every forward call with probability p using samples from a Bernoulli distribution.\n /// </summary>\n /// <param name=\"p\">Probability of an element to be zeroed. Default: 0.5</param>\n /// <param name=\"inplace\">If set to true, will do this operation in-place. Default: false</param>\n /// <returns></returns>\n public static Dropout2d Dropout2d(double p = 0.5, bool inplace = false)\n {\n return new Dropout2d(p, inplace);\n }\n\n public static partial class functional\n {\n\n /// <summary>\n /// Randomly zero out entire channels (a channel is a 2D feature map, e.g., the jj -th channel of the ii -th sample in the batched input is a 2D tensor).\n /// Each channel will be zeroed out independently on every forward call with probability p using samples from a Bernoulli distribution.\n /// </summary>\n /// <returns></returns>\n public static Tensor dropout2d(Tensor input, double p = 0.5, bool training = true, bool inplace = false)\n {\n var res = THSNN_dropout2d(input.Handle, p, training, inplace);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5326876640319824, "alphanum_fraction": 0.5332929491996765, "avg_line_length": 43.64864730834961, "blob_id": "507babe20d3e2fa97bff484f79d739eaeb463752", "content_id": "d73678789bf3c90fe7b65d2d582c9d4e5bf56570", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4956, "license_type": "permissive", "max_line_length": 144, "num_lines": 111, "path": "/src/TorchSharp/NN/Recurrent/GRUCell.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n public sealed class GRUCell : torch.nn.Module<Tensor, Tensor, Tensor>\n {\n internal GRUCell(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n public new static GRUCell Load(string modelPath)\n {\n var res = Module<Tensor, Tensor>.Load(modelPath);\n return new GRUCell(res.handle.DangerousGetHandle(), IntPtr.Zero);\n }\n\n /// <summary>\n /// Apply the GRU cell to an input tensor.\n /// </summary>\n /// <param name=\"input\">Tensor of shape (batch, input_size) containing the features of the input sequence.</param>\n /// <param name=\"h0\">Tensor of shape (batch, hidden_size) containing the initial hidden state for each element in the batch.</param>\n /// <returns></returns>\n public override Tensor forward(Tensor input, Tensor? h0 = null)\n {\n var hN = THSNN_GRUCell_forward(handle, input.Handle, h0?.Handle ?? IntPtr.Zero);\n if (hN == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(hN);\n }\n\n public Parameter? bias_ih {\n get {\n var res = THSNN_GRUCell_bias_ih(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return ((res == IntPtr.Zero) ? null : new Parameter(res));\n }\n set {\n THSNN_GRUCell_set_bias_ih(handle, (value is null ? IntPtr.Zero : value.Handle));\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"bias_ih\", value);\n }\n }\n\n public Parameter? bias_hh {\n get {\n var res = THSNN_GRUCell_bias_hh(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return ((res == IntPtr.Zero) ? null : new Parameter(res));\n }\n set {\n THSNN_GRUCell_set_bias_hh(handle, (value is null ? IntPtr.Zero : value.Handle));\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"bias_hh\", value);\n }\n }\n\n public Parameter? weight_ih {\n get {\n var res = THSNN_GRUCell_weight_ih(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n set {\n THSNN_GRUCell_set_weight_ih(handle, value is null ? IntPtr.Zero : value.Handle);\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"weight_ih\", value);\n }\n }\n\n public Parameter? weight_hh {\n get {\n var res = THSNN_GRUCell_weight_hh(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n set {\n THSNN_GRUCell_set_weight_hh(handle, value is null ? IntPtr.Zero : value.Handle);\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"weight_hh\", value);\n }\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// A gated recurrent unit (GRU) cell\n /// </summary>\n /// <param name=\"inputSize\">The number of expected features in the input x</param>\n /// <param name=\"hiddenSize\">The number of features in the hidden state h</param>\n /// <param name=\"device\">The desired device of the parameters and buffers in this module</param>\n /// <param name=\"dtype\">The desired floating point or complex dtype of the parameters and buffers in this module</param>\n /// <param name=\"bias\">If False, then the layer does not use bias weights b_ih and b_hh. Default: True</param>\n public static GRUCell GRUCell(long inputSize, long hiddenSize, bool bias = true, Device? device = null, ScalarType? dtype = null)\n {\n var res = THSNN_GRUCell_ctor(inputSize, hiddenSize, bias, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new GRUCell(res, boxedHandle).MoveModule<GRUCell>(device, dtype);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.4594695568084717, "alphanum_fraction": 0.4998132288455963, "avg_line_length": 35.17567443847656, "blob_id": "3d59ed9521a3a99455658f06d901141a8195daeb", "content_id": "3a76b9e32b6a1b432385cf0e61faed7f2949aa28", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2677, "license_type": "permissive", "max_line_length": 130, "num_lines": 74, "path": "/src/Examples/AlexNet.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\n\nnamespace TorchSharp.Examples\n{\n /// <summary>\n /// Modified version of original AlexNet to fix CIFAR10 32x32 images.\n /// </summary>\n class AlexNet : Module<Tensor, Tensor>\n {\n private readonly Module<Tensor, Tensor> features;\n private readonly Module<Tensor, Tensor> avgPool;\n private readonly Module<Tensor, Tensor> classifier;\n\n public AlexNet(string name, int numClasses, torch.Device device = null) : base(name)\n {\n features = Sequential(\n (\"c1\", Conv2d(3, 64, kernelSize: 3, stride: 2, padding: 1)),\n (\"r1\", ReLU(inplace: true)),\n (\"mp1\", MaxPool2d(kernelSize: new long[] { 2, 2 })),\n (\"c2\", Conv2d(64, 192, kernelSize: 3, padding: 1)),\n (\"r2\", ReLU(inplace: true)),\n (\"mp2\", MaxPool2d(kernelSize: new long[] { 2, 2 })),\n (\"c3\", Conv2d(192, 384, kernelSize: 3, padding: 1)),\n (\"r3\", ReLU(inplace: true)),\n (\"c4\", Conv2d(384, 256, kernelSize: 3, padding: 1)),\n (\"r4\", ReLU(inplace: true)),\n (\"c5\", Conv2d(256, 256, kernelSize: 3, padding: 1)),\n (\"r5\", ReLU(inplace: true)),\n (\"mp3\", MaxPool2d(kernelSize: new long[] { 2, 2 })));\n\n avgPool = AdaptiveAvgPool2d(new long[] { 2, 2 });\n\n classifier = Sequential(\n (\"d1\", Dropout()),\n (\"l1\", Linear(256 * 2 * 2, 4096)),\n (\"r1\", ReLU(inplace: true)),\n (\"d2\", Dropout()),\n (\"l2\", Linear(4096, 4096)),\n (\"r3\", ReLU(inplace: true)),\n (\"d3\", Dropout()),\n (\"l3\", Linear(4096, numClasses))\n );\n\n RegisterComponents();\n\n if (device != null && device.type == DeviceType.CUDA)\n this.to(device);\n }\n\n public override Tensor forward(Tensor input)\n {\n var f = features.call(input);\n var avg = avgPool.call(f);\n\n using (var x = avg.reshape(new long[] { avg.shape[0], 256 * 2 * 2 }))\n return classifier.call(x);\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n features.Dispose();\n avgPool.Dispose();\n classifier.Dispose();\n ClearModules();\n }\n base.Dispose(disposing);\n }\n }\n\n}\n" }, { "alpha_fraction": 0.5558139681816101, "alphanum_fraction": 0.561012327671051, "avg_line_length": 44.6875, "blob_id": "df6a5e536593f6f6d695a6fe488fd38804d3c8f8", "content_id": "bda99fb0923cb2af153b66be1db02d7bdc8a53f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7310, "license_type": "permissive", "max_line_length": 205, "num_lines": 160, "path": "/src/TorchSharp/Tensor/Factories/empty.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torch\n {\n /// <summary>\n /// Create a new tensor filled with empty\n /// </summary>\n public static Tensor empty(long[] size, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _empty(size, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new tensor filled with empty\n /// </summary>\n public static Tensor empty(ReadOnlySpan<long> size, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _empty(size, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 1-D tensor filled with empty\n /// </summary>\n public static Tensor empty(long size, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _empty(stackalloc long[] { size }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 2-D tensor filled with empty\n /// </summary>\n public static Tensor empty(long rows, long columns, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _empty(stackalloc long[] { rows, columns }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 3-D tensor filled with empty\n /// </summary>\n public static Tensor empty(long dim0, long dim1, long dim2, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _empty(stackalloc long[] { dim0, dim1, dim2 }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 4-D tensor filled with empty\n /// </summary>\n public static Tensor empty(long dim0, long dim1, long dim2, long dim3, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _empty(stackalloc long[] { dim0, dim1, dim2, dim3 }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 1-D tensor filled with empty\n /// </summary>\n public static Tensor empty(int size, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _empty(stackalloc long[] { size }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 2-D tensor filled with empty\n /// </summary>\n public static Tensor empty(int rows, int columns, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _empty(stackalloc long[] { rows, columns }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 3-D tensor filled with empty\n /// </summary>\n public static Tensor empty(int dim0, int dim1, int dim2, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _empty(stackalloc long[] { dim0, dim1, dim2 }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 4-D tensor filled with empty\n /// </summary>\n public static Tensor empty(int dim0, int dim1, int dim2, int dim3, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _empty(stackalloc long[] { dim0, dim1, dim2, dim3 }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Returns a tensor filled with uninitialized data, with the same size as input.\n /// </summary>\n public static Tensor empty_like(Tensor input, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null) => input.empty_like(dtype, device, requires_grad);\n\n\n /// <summary>\n /// Returns a tensor filled with uninitialized data. The shape and strides of the tensor is defined by the variable argument size and stride respectively.\n /// </summary>\n public static Tensor empty_strided(long[] size, long[] strides, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n device = InitializeDevice(device);\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n dtype = get_default_dtype();\n }\n\n unsafe {\n fixed (long* psizes = size, pstrides = strides) {\n var handle = THSTensor_empty_strided((IntPtr)psizes, size.Length, (IntPtr)pstrides, strides.Length, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_empty_strided((IntPtr)psizes, size.Length, (IntPtr)pstrides, strides.Length, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n var result = new Tensor(handle);\n\n if (names != null && names.Length > 0) {\n\n result.rename_(names);\n }\n\n return result;\n }\n }\n }\n\n /// <summary>\n /// Create a new tensor filled with empty\n /// </summary>\n private static Tensor _empty(ReadOnlySpan<long> size, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n device = InitializeDevice(device);\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n dtype = get_default_dtype();\n }\n\n unsafe {\n fixed (long* psizes = size) {\n var handle = THSTensor_empty((IntPtr)psizes, size.Length, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_empty((IntPtr)psizes, size.Length, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n var result = new Tensor(handle);\n\n if (names != null && names.Length > 0) {\n\n result.rename_(names);\n }\n\n return result;\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5628982782363892, "alphanum_fraction": 0.5657304525375366, "avg_line_length": 46.340782165527344, "blob_id": "bfc2ca728e291fa5ca1d78fb83443c90d0c9daa0", "content_id": "ff4258652cde445a8cba21abb0041bde11ba568b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8474, "license_type": "permissive", "max_line_length": 149, "num_lines": 179, "path": "/src/TorchSharp/Distributions/Multinomial.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// A Multinomial distribution parameterized by `probs` or `logits` (but not both).\n /// `total_count` must be broadcastable with `probs`/`logits`.\n /// </summary>\n public class Multinomial : torch.distributions.Distribution\n {\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public override Tensor mean => total_count * probs;\n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public override Tensor variance => WrappedTensorDisposeScope(() => total_count * probs * (1 - probs));\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"total_count\">Number of Bernoulli trials</param>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n public Multinomial(int total_count, Tensor probs = null, Tensor logits = null, torch.Generator generator = null) : base(generator) \n {\n this.total_count = total_count;\n this.categorical = new Categorical(probs, logits);\n this.batch_shape = this.categorical.batch_shape;\n var ps = this.categorical.param_shape;\n this.event_shape = new long[] { ps[ps.Length-1] };\n }\n\n private Multinomial(int total_count, Categorical categorical, torch.Generator generator = null) : base(generator)\n {\n this.total_count = total_count;\n this.categorical = categorical;\n this.batch_shape = categorical.batch_shape;\n var ps = categorical.param_shape;\n this.event_shape = new long[] { ps[ps.Length - 1] };\n }\n\n /// <summary>\n /// Event probabilities\n /// </summary>\n public Tensor probs => categorical.probs;\n\n /// <summary>\n /// Event log-odds\n /// </summary>\n public Tensor logits => categorical.logits;\n\n\n public long[] param_shape => categorical.param_shape;\n\n private int total_count;\n private Categorical categorical;\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n public override Tensor rsample(params long[] sample_shape)\n {\n var cShape = new List<long>(); cShape.Add(total_count); cShape.AddRange(sample_shape);\n\n using var _ = NewDisposeScope();\n var samples = categorical.sample(cShape.ToArray());\n var shifted_idx = Enumerable.Range(0, (int)samples.dim()).ToList();\n var tc = shifted_idx[0];\n shifted_idx.RemoveAt(0);\n shifted_idx.Add(tc);\n samples = samples.permute(shifted_idx.Select(i => (long)i).ToArray());\n var counts = samples.new_zeros(ExtendedShape(sample_shape));\n counts.scatter_add_(-1, samples, torch.ones_like(samples));\n return counts.type_as(probs).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor log_prob(Tensor value)\n {\n using var _ = NewDisposeScope();\n var bcast = torch.broadcast_tensors(logits, value);\n var l = bcast[0].clone();\n value = bcast[1];\n var log_factorial_n = torch.lgamma(value.sum(-1) + 1);\n var log_factorial_xs = torch.lgamma(value + 1).sum(-1);\n l[(value == 0) & (l == float.NegativeInfinity)] = torch.tensor(0.0f);\n var log_powers = (logits * value).sum(-1);\n return (log_factorial_n - log_factorial_xs + log_powers).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is Multinomial))\n throw new ArgumentException(\"expand(): 'instance' must be a Multinomial distribution\");\n\n var newDistribution = ((instance == null) ?\n new Multinomial(total_count, categorical.expand(batch_shape) as Categorical, generator) :\n instance) as Multinomial;\n\n if (newDistribution == instance) {\n newDistribution.total_count = total_count;\n newDistribution.categorical = categorical.expand(batch_shape) as Categorical;\n newDistribution.batch_shape = newDistribution.categorical.batch_shape;\n var ps = newDistribution.categorical.param_shape;\n newDistribution.event_shape = new long[] { ps[ps.Length - 1] };\n }\n\n return newDistribution;\n }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n /// <returns></returns>\n public override Tensor entropy()\n {\n throw new NotImplementedException();\n }\n }\n\n }\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a Multinomial distribution parameterized by `probs` or `logits` (but not both).\n /// `total_count` must be broadcastable with `probs`/`logits`.\n /// </summary>\n /// <param name=\"total_count\">Number of Bernoulli trials</param>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Multinomial Multinomial(int total_count, Tensor probs = null, Tensor logits = null, torch.Generator generator = null)\n {\n return new Multinomial(total_count, probs, logits, generator);\n }\n\n /// <summary>\n /// Creates an equal-probability multinomial distribution parameterized by the number of categories.\n /// `total_count` must be broadcastable with `probs`/`logits`.\n /// </summary>\n /// <param name=\"total_count\">Number of Bernoulli trials</param>\n /// <param name=\"categories\">The number of categories.</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Multinomial Multinomial(int total_count, int categories, torch.Generator generator = null)\n {\n var probs = torch.tensor(1.0 / categories).expand(categories);\n return new Multinomial(total_count, probs, null, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5633964538574219, "alphanum_fraction": 0.565691351890564, "avg_line_length": 36.91304397583008, "blob_id": "31f9c867490f7ed2e7c3be3aea7f9d3c48c95ee2", "content_id": "d6cd833be9a51d1606f8b7a5ffc0dc74b9438c36", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1747, "license_type": "permissive", "max_line_length": 131, "num_lines": 46, "path": "/src/TorchVision/Pad.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class Pad : ITransform\n {\n internal Pad(long[] pad, PaddingModes mode = PaddingModes.Constant, double value = 0)\n {\n this.pad = pad;\n this.mode = mode;\n this.value = value;\n }\n\n public Tensor call(Tensor input)\n {\n return TorchSharp.torch.nn.functional.pad(input, pad, mode, value);\n }\n\n private long[] pad;\n private PaddingModes mode;\n private double value;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Pad the given image on all sides with the given “pad” value.\n /// </summary>\n /// <param name=\"padding\">\n /// Padding on each border. If a single int is provided this is used to pad all borders.\n /// If sequence of length 2 is provided this is the padding on left/right and top/bottom respectively.\n /// If a sequence of length 4 is provided this is the padding for the left, top, right and bottom borders respectively.\n /// </param>\n /// <param name=\"fill\">Pixel fill value for constant fill.</param>\n /// <param name=\"mode\">Type of padding.</param>\n static public ITransform Pad(long[] padding, PaddingModes mode = PaddingModes.Constant, double fill = 0)\n {\n return new Pad(padding, mode, fill);\n }\n }\n }\n}" }, { "alpha_fraction": 0.5328271985054016, "alphanum_fraction": 0.5441445112228394, "avg_line_length": 42.638038635253906, "blob_id": "71a9a10d8f19ee1c9c79dafe06a408654d4e63bf", "content_id": "2ddb738f816682f3182214cbad2396ce1f779815", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 14226, "license_type": "permissive", "max_line_length": 187, "num_lines": 326, "path": "/src/TorchVision/dsets/CIFAR.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.utils.data;\n\nnamespace TorchSharp \n{\n public static partial class torchvision\n {\n public static partial class datasets\n {\n /// <summary>\n /// CIFAR10 Dataset.\n /// </summary>\n /// <remarks>\n /// The dataset for this example can be found at: https://www.cs.toronto.edu/~kriz/cifar.html\n /// </remarks>\n /// <param name=\"root\">Root directory of dataset where directory CIFAR{10,100} exists or will be saved to if download is set to true.</param>\n /// <param name=\"train\">If true, creates dataset from training set, otherwise creates from test set</param>\n /// <param name=\"download\">If true, downloads the dataset from the internet and puts it in root directory. If dataset is already downloaded, it is not downloaded again</param>\n /// <param name=\"target_transform\">A transform that takes in the target tensor and transforms it.</param>\n /// <returns>A CIFAR dataset.</returns>\n public static Dataset CIFAR10(string root, bool train, bool download = false, torchvision.ITransform target_transform = null)\n {\n return new Modules.CIFAR10(root, train, \"https://www.cs.toronto.edu/~kriz/\", download, target_transform);\n }\n\n /// <summary>\n /// CIFAR10 Dataset.\n /// </summary>\n /// <remarks>\n /// The dataset for this example can be found at: https://www.cs.toronto.edu/~kriz/cifar.html\n /// </remarks>\n /// <param name=\"root\">Root directory of dataset where directory CIFAR{10,100} exists or will be saved to if download is set to true.</param>\n /// <param name=\"train\">If true, creates dataset from training set, otherwise creates from test set</param>\n /// <param name=\"download\">If true, downloads the dataset from the internet and puts it in root directory. If dataset is already downloaded, it is not downloaded again</param>\n /// <param name=\"target_transform\">A function that takes in the target tensor and transforms it.</param>\n /// <returns>A CIFAR dataset.</returns>\n public static Dataset CIFAR10(string root, bool train, bool download, Func<Tensor, Tensor> target_transform)\n {\n return new Modules.CIFAR10(root, train, \"https://www.cs.toronto.edu/~kriz/\", download, new torchvision.Lambda(target_transform));\n }\n\n /// <summary>\n /// CIFAR100 Dataset.\n /// </summary>\n /// <remarks>\n /// The dataset for this example can be found at: https://www.cs.toronto.edu/~kriz/cifar.html\n /// </remarks>\n /// <param name=\"root\">Root directory of dataset where directory CIFAR{10,100} exists or will be saved to if download is set to true.</param>\n /// <param name=\"train\">If true, creates dataset from training set, otherwise creates from test set</param>\n /// <param name=\"download\">If true, downloads the dataset from the internet and puts it in root directory. If dataset is already downloaded, it is not downloaded again</param>\n /// <param name=\"target_transform\">A transform that takes in the target and transforms it.</param>\n /// <returns>A CIFAR dataset.</returns>\n public static Dataset CIFAR100(string root, bool train, bool download = false, torchvision.ITransform target_transform = null)\n {\n return new Modules.CIFAR100(root, train, \"https://www.cs.toronto.edu/~kriz/\", download, target_transform);\n }\n\n /// <summary>\n /// CIFAR100 Dataset.\n /// </summary>\n /// <remarks>\n /// The dataset for this example can be found at: https://www.cs.toronto.edu/~kriz/cifar.html\n /// </remarks>\n /// <param name=\"root\">Root directory of dataset where directory CIFAR{10,100} exists or will be saved to if download is set to true.</param>\n /// <param name=\"train\">If true, creates dataset from training set, otherwise creates from test set</param>\n /// <param name=\"download\">If true, downloads the dataset from the internet and puts it in root directory. If dataset is already downloaded, it is not downloaded again</param>\n /// <param name=\"target_transform\">A function that takes in the target and transforms it.</param>\n /// <returns>A CIFAR dataset.</returns>\n public static Dataset CIFAR100(string root, bool train, bool download, Func<Tensor, Tensor> target_transform)\n {\n return new Modules.CIFAR100(root, train, \"https://www.cs.toronto.edu/~kriz/\", download, new torchvision.Lambda(target_transform));\n }\n }\n }\n\n namespace Modules\n {\n internal abstract class DatasetHelper : Dataset\n {\n protected void DownloadFile(string file, string target, string baseUrl)\n {\n var filePath = JoinPaths(target, file);\n\n var netPath = baseUrl.EndsWith('/') ? $\"{baseUrl}{file}\" : $\"{baseUrl}/{file}\";\n\n if (!File.Exists(filePath)) {\n lock (_httpClient) {\n using var s = _httpClient.GetStreamAsync(netPath).Result;\n using var fs = new FileStream(file, FileMode.CreateNew);\n s.CopyToAsync(fs).Wait();\n }\n }\n }\n\n protected static string JoinPaths(string directory, string file)\n {\n#if NETSTANDARD2_0_OR_GREATER\n return NSPath.Join(directory, file);\n#else\n return Path.Join(directory, file);\n#endif // NETSTANDARD2_0_OR_GREATER\n }\n\n // Sharing a client among all dataset downloads, based on this article's advice:\n // https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/\n //\n private static HttpClient _httpClient = new HttpClient();\n }\n\n internal abstract class CIFAR : DatasetHelper\n {\n protected void Download(string targetDir, string baseUrl, string dataset, string fileName)\n {\n if (!Directory.Exists(targetDir)) {\n Directory.CreateDirectory(targetDir);\n }\n\n DownloadFile(fileName, targetDir, baseUrl);\n\n if (!File.Exists(Path.Combine(targetDir, $\"{dataset}-binary.bin\"))) {\n DecompressFile(fileName, targetDir, targetDir);\n }\n }\n\n private static void DecompressFile(string file, string sourceDir, string targetDir)\n {\n Utils.Decompress.ExtractTGZ(Path.Combine(sourceDir, file), targetDir);\n }\n }\n\n internal class CIFAR10 : CIFAR, IDisposable\n {\n public CIFAR10(string root, bool train, string baseUrl, bool download, torchvision.ITransform transform)\n {\n var targetDir = JoinPaths(root, \"CIFAR10\");\n\n if (download) Download(targetDir, baseUrl, \"cifar-10\", \"cifar-10-binary.tar.gz\");\n\n this.transform = transform;\n\n var dataPath = Path.Combine(targetDir, \"cifar-10-batches-bin\");\n\n if (!train) {\n _count = ReadSingleFile(Path.Combine(dataPath, \"test_batch.bin\"));\n } else {\n _count += ReadSingleFile(Path.Combine(dataPath, \"data_batch_1.bin\"));\n _count += ReadSingleFile(Path.Combine(dataPath, \"data_batch_2.bin\"));\n _count += ReadSingleFile(Path.Combine(dataPath, \"data_batch_3.bin\"));\n _count += ReadSingleFile(Path.Combine(dataPath, \"data_batch_4.bin\"));\n _count += ReadSingleFile(Path.Combine(dataPath, \"data_batch_5.bin\"));\n }\n\n }\n\n private int ReadSingleFile(string path)\n {\n const int height = 32;\n const int width = 32;\n const int channels = 3;\n const int count = 10000;\n\n byte[] dataBytes = File.ReadAllBytes(path);\n\n var imgSize = channels * height * width + 1;\n\n if (dataBytes.Length != imgSize * count)\n throw new InvalidDataException($\"Not a proper CIFAR10 file: {path}\");\n\n // Go through the data and create tensors\n\n // A previous version of this relied on LINQ expressions, but it was about 20% slower.\n\n for (var i = 0; i < count; i++) {\n\n var imgStart = i * imgSize;\n\n labels.Add(tensor(dataBytes[imgStart], int64));\n\n var floats = new float[imgSize-1];\n for (int j = 0; j < imgSize-1; j++) {\n floats[j] = dataBytes[1 + j + imgStart] / 256.0f;\n }\n\n data.Add(tensor(floats, new long[] { channels, width, height }));\n }\n\n return count;\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n data.ForEach(d => d.Dispose());\n labels.ForEach(d => d.Dispose());\n }\n }\n\n /// <summary>\n /// Get tensor according to index\n /// </summary>\n /// <param name=\"index\">Index for tensor</param>\n /// <returns>Tensors of index. DataLoader will catenate these tensors into batches.</returns>\n public override Dictionary<string, Tensor> GetTensor(long index)\n {\n var rdic = new Dictionary<string, Tensor>();\n if (transform is not null) {\n rdic.Add(\"data\", transform.call(data[(int)index]));\n }\n else {\n rdic.Add(\"data\", data[(int)index]);\n }\n rdic.Add(\"label\", labels[(int)index]);\n return rdic;\n }\n\n private List<Tensor> data = new();\n private List<Tensor> labels = new();\n\n private torchvision.ITransform transform;\n public override long Count => _count;\n\n private int _count = 0;\n }\n\n internal class CIFAR100 : CIFAR, IDisposable\n {\n public CIFAR100(string root, bool train, string baseUrl, bool download, torchvision.ITransform transform)\n {\n var targetDir = JoinPaths(root, \"CIFAR100\");\n\n if (download) Download(targetDir, baseUrl, \"cifar-100\", \"cifar-100-binary.tar.gz\");\n\n this.transform = transform;\n\n var dataPath = Path.Combine(targetDir, \"cifar-100-binary\");\n\n if (train) {\n _count = ReadSingleFile(Path.Combine(dataPath, \"train.bin\"));\n } else {\n _count = ReadSingleFile(Path.Combine(dataPath, \"test.bin\"));\n }\n\n }\n\n private int ReadSingleFile(string path)\n {\n const int height = 32;\n const int width = 32;\n const int channels = 3;\n\n byte[] dataBytes = File.ReadAllBytes(path);\n\n var imgSize = channels * height * width;\n var recSize = imgSize + 2;\n\n if (dataBytes.Length % recSize != 0)\n throw new InvalidDataException($\"Not a proper CIFAR100 file: {path}\");\n\n int count = dataBytes.Length / recSize;\n\n // Go through the data and create tensors\n\n for (var i = 0; i < count; i++) {\n\n var recStart = i * recSize;\n var imgStart = recStart + 2;\n\n // CIFAR100 has two labels -- one, which is 20 categories, one which is 100 entities.\n coarse_labels.Add(tensor(dataBytes[recStart], int64));\n fine_labels.Add(tensor(dataBytes[recStart+1], int64));\n\n var floats = new float[imgSize];\n for (int j = 0; j < imgSize; j++) {\n floats[j] = dataBytes[j + imgStart] / 256.0f;\n }\n\n data.Add(tensor(floats, new long[] { channels, width, height }));\n }\n\n return count;\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n data.ForEach(d => d.Dispose());\n fine_labels.ForEach(d => d.Dispose());\n coarse_labels.ForEach(d => d.Dispose());\n }\n }\n\n /// <summary>\n /// Get tensor according to index\n /// </summary>\n /// <param name=\"index\">Index for tensor</param>\n /// <returns>Tensors of index. DataLoader will catenate these tensors into batches.</returns>\n public override Dictionary<string, Tensor> GetTensor(long index)\n {\n var rdic = new Dictionary<string, Tensor>();\n if (transform is not null) {\n rdic.Add(\"data\", transform.call(data[(int)index]));\n } else {\n rdic.Add(\"data\", data[(int)index]);\n }\n rdic.Add(\"label\", fine_labels[(int)index]);\n rdic.Add(\"categories\", coarse_labels[(int)index]);\n return rdic;\n }\n\n private List<Tensor> data = new();\n private List<Tensor> coarse_labels = new();\n private List<Tensor> fine_labels = new();\n\n private torchvision.ITransform transform;\n public override long Count => _count;\n\n private int _count = 0;\n }\n }\n}\n" }, { "alpha_fraction": 0.5431309938430786, "alphanum_fraction": 0.5445367693901062, "avg_line_length": 43.460227966308594, "blob_id": "c22a87526d411890b389f5ec241e9a22078d97f7", "content_id": "3a1eb8dc8c227963ec0fb1856b3916823c52f617", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7825, "license_type": "permissive", "max_line_length": 149, "num_lines": 176, "path": "/src/TorchSharp/Distributions/Bernoulli.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// A Bernoulli distribution parameterized by `probs` or `logits` (but not both).\n /// </summary>\n public class Bernoulli : torch.distributions.Distribution\n {\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public override Tensor mean => probs;\n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public override Tensor variance =>\n WrappedTensorDisposeScope(() => probs * (1 - probs));\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"p\"></param>\n /// <param name=\"l\"></param>\n /// <param name=\"generator\"></param>\n public Bernoulli(Tensor p = null, Tensor l = null, torch.Generator generator = null) : base(generator)\n {\n if ((p is null && l is null) || (p is not null && l is not null))\n throw new ArgumentException(\"One and only one of 'probs' and logits should be provided.\");\n\n this.batch_shape = p is null ? l.size() : p.size();\n this._probs = p?.alias().DetachFromDisposeScope();\n this._logits = l?.alias().DetachFromDisposeScope();\n }\n\n /// <summary>\n /// The probability of sampling 1\n /// </summary>\n public Tensor probs {\n get {\n return _probs ?? LogitsToProbs(_logits, true);\n }\n }\n\n /// <summary>\n /// The log-odds of sampling 1\n /// </summary>\n public Tensor logits {\n get {\n return _logits ?? ProbsToLogits(_probs, true);\n }\n }\n\n private Tensor _probs;\n private Tensor _logits;\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n /// <returns></returns>\n public override Tensor rsample(params long[] sample_shape)\n {\n var shape = ExtendedShape(sample_shape);\n return torch.bernoulli(probs.expand(shape), generator);\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n /// <returns></returns>\n\n public override Tensor log_prob(Tensor value)\n {\n var logitsValue = torch.broadcast_tensors(logits, value);\n return -torch.nn.functional.binary_cross_entropy_with_logits(logitsValue[0], logitsValue[1], reduction: nn.Reduction.None);\n }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n public override Tensor entropy()\n {\n return torch.nn.functional.binary_cross_entropy_with_logits(logits, probs, reduction: nn.Reduction.None);\n }\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n /// <returns></returns>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is Bernoulli))\n throw new ArgumentException(\"expand(): 'instance' must be a Bernoulli distribution\");\n\n var p = _probs?.expand(batch_shape);\n var l = _logits?.expand(batch_shape);\n\n var newDistribution = ((instance == null) ? new Bernoulli(p, l, generator) : instance) as Bernoulli;\n\n newDistribution.batch_shape = batch_shape;\n if (newDistribution == instance) {\n newDistribution._probs = p;\n newDistribution._logits = l;\n }\n return newDistribution;\n }\n }\n\n }\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a Bernoulli distribution parameterized by `probs` or `logits` (but not both).\n /// </summary>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Bernoulli Bernoulli(Tensor probs = null, Tensor logits = null, torch.Generator generator = null)\n {\n return new Bernoulli(probs, logits, generator);\n }\n\n /// <summary>\n /// Creates a Bernoulli distribution parameterized by `probs` or `logits` (but not both).\n /// </summary>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Bernoulli Bernoulli(float? probs, float? logits, torch.Generator generator = null)\n {\n if (probs.HasValue && !logits.HasValue)\n return new Bernoulli(torch.tensor(probs.Value), null, generator);\n else if (!probs.HasValue && logits.HasValue)\n return new Bernoulli(null, torch.tensor(logits.Value), generator);\n else\n throw new ArgumentException(\"One and only one of 'probs' and logits should be provided.\");\n }\n\n\n /// <summary>\n /// Creates a Bernoulli distribution parameterized by `probs` or `logits` (but not both).\n /// </summary>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Bernoulli Bernoulli(double? probs, double? logits, torch.Generator generator = null)\n {\n if (probs.HasValue && !logits.HasValue)\n return new Bernoulli(torch.tensor(probs.Value), null, generator);\n else if (!probs.HasValue && logits.HasValue)\n return new Bernoulli(null, torch.tensor(logits.Value), generator);\n else\n throw new ArgumentException(\"One and only one of 'probs' and 'logits' should be non-null\");\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5323854684829712, "alphanum_fraction": 0.5331753492355347, "avg_line_length": 36.264705657958984, "blob_id": "c6a3db3a9163cc9ddf2f4fec8ee53fbedc6e277a", "content_id": "57c7b454cd46963008dfdf510b3fbc68102c98a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1266, "license_type": "permissive", "max_line_length": 130, "num_lines": 34, "path": "/src/TorchAudio/Datasets/Utils.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System.IO;\nusing System.Text;\nusing ICSharpCode.SharpZipLib.GZip;\nusing ICSharpCode.SharpZipLib.Tar;\n\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n public static partial class datasets\n {\n public static partial class utils\n {\n /// <summary>\n /// Extract an archive.\n /// </summary>\n /// <param name=\"from_path\">The path of the archive</param>\n /// <param name=\"to_path\">The path to extract the archive</param>\n internal static void extract_archive(string from_path, string to_path)\n {\n using (var fileStream = File.OpenRead(from_path)) {\n using (var inputStream = new GZipInputStream(fileStream)) {\n using (TarArchive tarArchive = TarArchive.CreateInputTarArchive(inputStream, Encoding.UTF8)) {\n tarArchive.ExtractContents(to_path);\n }\n }\n }\n }\n }\n }\n }\n}" }, { "alpha_fraction": 0.5554831624031067, "alphanum_fraction": 0.5606974363327026, "avg_line_length": 47.70634841918945, "blob_id": "1383722dd689bae865daa41fb40c5fff6871d414", "content_id": "58d9229c4ecd53a0e84a7031efc92ec7b44819e9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6137, "license_type": "permissive", "max_line_length": 228, "num_lines": 126, "path": "/src/TorchSharp/NN/Normalization/InstanceNorm1d.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n\n /// <summary>\n /// This class is used to represent a InstanceNorm1D module.\n /// </summary>\n public sealed class InstanceNorm1d : torch.nn.Module<Tensor, Tensor>\n {\n internal InstanceNorm1d(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n if (tensor.Dimensions < 2 || tensor.Dimensions > 3) throw new ArgumentException($\"Invalid number of dimensions for InstanceNorm argument: {tensor.Dimensions}\");\n var res = THSNN_InstanceNorm1d_forward(handle.DangerousGetHandle(), tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public Parameter? bias {\n get {\n var res = THSNN_InstanceNorm1d_bias(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n set {\n THSNN_InstanceNorm1d_set_bias(handle, (value is null ? IntPtr.Zero : value.Handle));\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"bias\", value);\n }\n }\n\n public Parameter? weight {\n get {\n var res = THSNN_InstanceNorm1d_weight(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n set {\n THSNN_InstanceNorm1d_set_weight(handle, value is null ? IntPtr.Zero : value.Handle);\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"weight\", value);\n }\n }\n\n public Tensor? running_mean {\n get {\n var res = THSNN_InstanceNorm1d_get_mean(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); return null; }\n return new Tensor(res);\n }\n set {\n THSNN_InstanceNorm1d_set_mean(handle, (value is null ? IntPtr.Zero : value.Handle));\n torch.CheckForErrors();\n ConditionallyRegisterBuffer(\"running_mean\", value);\n }\n }\n\n public Tensor? running_var {\n get {\n var res = THSNN_InstanceNorm1d_get_var(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); return null; }\n return new Tensor(res);\n }\n set {\n THSNN_InstanceNorm1d_set_var(handle, (value is null ? IntPtr.Zero : value.Handle));\n torch.CheckForErrors();\n ConditionallyRegisterBuffer(\"running_var\", value);\n }\n }\n\n public Tensor? num_batches_tracked {\n get {\n var res = THSNN_InstanceNorm1d_get_batches(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); return null; }\n return new Tensor(res);\n }\n }\n\n public void reset_running_stats()\n {\n THSNN_InstanceNorm1d_reset_stats(handle);\n torch.CheckForErrors();\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies Instance Normalization over a 3D input (a mini-batch of 1D inputs with optional additional channel dimension) as described in the paper Instance Normalization: The Missing Ingredient for Fast Stylization.\n /// </summary>\n /// <param name=\"features\">C from an expected input of size (N,C,L) or LL from input of size (N, L)</param>\n /// <param name=\"eps\">A value added to the denominator for numerical stability. Default: 1e-5</param>\n /// <param name=\"momentum\">The value used for the running_mean and running_var computation. Can be set to None for cumulative moving average (i.e. simple average). Default: 0.1</param>\n /// <param name=\"affine\">A boolean value that when set to True, this module has learnable affine parameters. Default: true</param>\n /// <param name=\"track_running_stats\">A boolean value that when set to True, this module tracks the running mean and variance, and when set to False,\n /// this module does not track such statistics, and initializes statistics buffers running_mean and running_var as None.\n /// When these buffers are None, this module always uses batch statistics. in both training and eval modes. Default: true</param>\n /// <param name=\"device\">The desired device of the parameters and buffers in this module</param>\n /// <param name=\"dtype\">The desired floating point or complex dtype of the parameters and buffers in this module</param>\n /// <returns></returns>\n public static InstanceNorm1d InstanceNorm1d(long features, double eps = 1e-05, double momentum = 0.1, bool affine = false, bool track_running_stats = false, Device? device = null, ScalarType? dtype = null)\n {\n unsafe {\n var handle = THSNN_InstanceNorm1d_ctor(features, eps, momentum, affine, track_running_stats, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new InstanceNorm1d(handle, boxedHandle).MoveModule<InstanceNorm1d>(device, dtype);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.32987022399902344, "alphanum_fraction": 0.3371623456478119, "avg_line_length": 48.14643478393555, "blob_id": "031d1bb0cbcbdde798f5af040f3ee43d6e38b953", "content_id": "328427b1abab7ef4ae03ee2d3d43cc39418774eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 25507, "license_type": "permissive", "max_line_length": 192, "num_lines": 519, "path": "/src/TorchSharp/Utils/tensorboard/GifEncoder/Encoder.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System;\nusing System.IO;\nusing SkiaSharp;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class utils\n {\n public static partial class tensorboard\n {\n internal static partial class GifEncoder\n {\n /// <summary>\n /// Class AnimatedGifEncoder - Encodes a GIF file consisting of one or more frames.\n ///\n /// No copyright asserted on the source code of this class. May be used for any\n /// purpose, however, refer to the Unisys LZW patent for restrictions on use of\n /// the associated LZWEncoder class. Please forward any corrections to\n /// [email protected].\n ///\n /// @author Kevin Weiner, FM Software\n /// @version 1.03 November 2003\n ///\n /// https://cs.android.com/android/platform/superproject/+/master:external/glide/third_party/gif_encoder/src/main/java/com/bumptech/glide/gifencoder/AnimatedGifEncoder.java\n /// </summary>\n internal class Encoder : IDisposable\n {\n protected int width; // image size\n protected int height;\n protected SKColor transparent = SKColor.Empty; // transparent color if given\n protected int transIndex; // transparent index in color table\n protected int repeat = -1; // no repeat\n protected int delay = 0; // frame delay (hundredths)\n protected bool started = false; // ready to output frames\n //\tprotected BinaryWriter bw;\n protected MemoryStream ms;\n //\t\tprotected FileStream fs;\n\n protected SKBitmap image; // current frame\n protected byte[] pixels; // BGR byte array from frame\n protected byte[] indexedPixels; // converted frame indexed to palette\n protected int colorDepth; // number of bit planes\n protected byte[] colorTab; // RGB palette\n protected bool[] usedEntry = new bool[256]; // active palette entries\n protected int palSize = 7; // color table size (bits-1)\n protected int dispose = -1; // disposal code (-1 = use default)\n protected bool closeStream = false; // close stream when finished\n protected bool firstFrame = true;\n protected bool sizeSet = false; // if false, get size from first frame\n protected int sample = 10; // default sample interval for quantizer\n private bool disposedValue;\n\n /// <summary>\n /// Sets the delay time between each frame, or changes it\n /// for subsequent frames (applies to last frame added).\n /// </summary>\n /// <param name=\"ms\"> delay time in milliseconds </param>\n public void SetDelay(int ms)\n {\n delay = (int)Math.Round(ms / 10.0f);\n }\n\n /// <summary>\n /// Sets the GIF frame disposal code for the last added frame\n /// and any subsequent frames. Default is 0 if no transparent\n /// color has been set, otherwise 2.\n /// </summary>\n /// <param name=\"code\"> disposal code. </param>\n public void SetDispose(int code)\n {\n if (code >= 0) {\n dispose = code;\n }\n }\n\n /// <summary>\n /// Sets the number of times the set of GIF frames\n /// should be played. Default is 1; 0 means play\n /// indefinitely. Must be invoked before the first\n /// image is added.\n /// </summary>\n /// <param name=\"iter\"> number of iterations. </param>\n public void SetRepeat(int iter)\n {\n if (iter >= 0) {\n repeat = iter;\n }\n }\n\n /// <summary>\n /// Sets the transparent color for the last added frame\n /// and any subsequent frames.\n /// Since all colors are subject to modification\n /// in the quantization process, the color in the final\n /// palette for each frame closest to the given color\n /// becomes the transparent color for that frame.\n /// May be set to null to indicate no transparent color.\n /// </summary>\n /// <param name=\"c\"> Color to be treated as transparent on display. </param>\n public void SetTransparent(SKColor c)\n {\n transparent = c;\n }\n\n /// <summary>\n /// Adds next GIF frame. The frame is not written immediately, but is\n /// actually deferred until the next frame is received so that timing\n /// data can be inserted. Invoking <code>finish()</code> flushes all\n /// frames. If <code>setSize</code> was not invoked, the size of the\n /// first image is used for all subsequent frames.\n /// </summary>\n /// <param name=\"im\"> BufferedImage containing frame to write. </param>\n /// <returns> true if successful. </returns>\n public bool AddFrame(SKBitmap im)\n {\n if ((im == null) || !started) {\n return false;\n }\n bool ok = true;\n try {\n if (!sizeSet) {\n // use first frame's size\n SetSize(im.Width, im.Height);\n }\n image = im;\n GetImagePixels(); // convert to correct format if necessary\n AnalyzePixels(); // build color table & map pixels\n if (firstFrame) {\n WriteLSD(); // logical screen descriptior\n WritePalette(); // global color table\n if (repeat >= 0) {\n // use NS app extension to indicate reps\n WriteNetscapeExt();\n }\n }\n WriteGraphicCtrlExt(); // write graphic control extension\n WriteImageDesc(); // image descriptor\n if (!firstFrame) {\n WritePalette(); // local color table\n }\n WritePixels(); // encode and write pixel data\n firstFrame = false;\n } catch (IOException) {\n ok = false;\n }\n\n return ok;\n }\n\n /// <summary>\n /// Flushes any pending data and closes output file.\n /// If writing to an OutputStream, the stream is not\n /// closed.\n /// </summary>\n /// <returns></returns>\n public bool Finish()\n {\n if (!started) return false;\n bool ok = true;\n started = false;\n try {\n ms.WriteByte(0x3b); // gif trailer\n ms.Flush();\n } catch (IOException) {\n ok = false;\n }\n\n // reset for subsequent use\n transIndex = 0;\n //\t\t\tfs = null;\n image = null;\n pixels = null;\n indexedPixels = null;\n colorTab = null;\n closeStream = false;\n firstFrame = true;\n\n return ok;\n }\n\n /// <summary>\n /// Sets frame rate in frames per second. Equivalent to\n /// <code>setDelay(1000/fps)</code>.\n /// </summary>\n /// <param name=\"fps\"> fps float frame rate (frames per second) </param>\n public void SetFrameRate(float fps)\n {\n if (fps != 0f) {\n delay = (int)Math.Round(100f / fps);\n }\n }\n\n /// <summary>\n /// Sets the GIF frame size. The default size is the\n /// size of the first frame added if this method is\n /// not invoked.\n /// </summary>\n /// <param name=\"w\"> frame width </param>\n /// <param name=\"h\"> frame width </param>\n public void SetSize(int w, int h)\n {\n if (started && !firstFrame) return;\n width = w;\n height = h;\n if (width < 1) width = 320;\n if (height < 1) height = 240;\n sizeSet = true;\n }\n\n /// <summary>\n /// Initiates GIF file creation on the given stream. The stream\n /// is not closed automatically.\n /// </summary>\n /// <param name=\"os\"> OutputStream on which GIF images are written. </param>\n /// <returns> false if initial write failed. </returns>\n public bool Start(MemoryStream os)\n {\n if (os == null) return false;\n bool ok = true;\n closeStream = false;\n ms = os;\n try {\n WriteString(\"GIF89a\"); // header\n } catch (IOException) {\n ok = false;\n }\n return started = ok;\n }\n\n /// <summary>\n /// Initiates writing of a GIF file to a memory stream.\n /// </summary>\n /// <returns></returns>\n public bool Start()\n {\n bool ok;\n try {\n ok = Start(new MemoryStream(10 * 1024));\n closeStream = true;\n } catch (IOException) {\n ok = false;\n }\n return started = ok;\n }\n\n /// <summary>\n /// Initiates writing of a GIF file with the specified name.\n /// </summary>\n /// <param name=\"file\"></param>\n /// <returns></returns>\n public bool Output(string file)\n {\n try {\n var fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);\n fs.Write(ms.ToArray(), 0, (int)ms.Length);\n fs.Close();\n } catch (IOException) {\n return false;\n }\n return true;\n }\n\n public MemoryStream Output()\n {\n return ms;\n }\n\n /// <summary>\n /// Analyzes image colors and creates color map.\n /// </summary>\n protected void AnalyzePixels()\n {\n int len = pixels.Length;\n int nPix = len / 3;\n indexedPixels = new byte[nPix];\n var nq = new NeuQuant(pixels, len, sample);\n // initialize quantizer\n colorTab = nq.Process(); // create reduced palette\n // convert map from BGR to RGB\n //\t\t\tfor (int i = 0; i < colorTab.Length; i += 3) \n //\t\t\t{\n //\t\t\t\tbyte temp = colorTab[i];\n //\t\t\t\tcolorTab[i] = colorTab[i + 2];\n //\t\t\t\tcolorTab[i + 2] = temp;\n //\t\t\t\tusedEntry[i / 3] = false;\n //\t\t\t}\n // map image pixels to new palette\n int k = 0;\n for (int i = 0; i < nPix; i++) {\n int index =\n nq.Map(pixels[k++] & 0xff,\n pixels[k++] & 0xff,\n pixels[k++] & 0xff);\n usedEntry[index] = true;\n indexedPixels[i] = (byte)index;\n }\n pixels = null;\n colorDepth = 8;\n palSize = 7;\n // get closest match to transparent color if specified\n if (transparent != SKColor.Empty) {\n //transIndex = FindClosest(transparent);\n transIndex = nq.Map(transparent.Blue, transparent.Green, transparent.Red);\n }\n }\n\n /// <summary>\n /// Returns index of palette color closest to c\n /// </summary>\n /// <param name=\"c\"></param>\n /// <returns></returns>\n protected int FindClosest(SKColor c)\n {\n if (colorTab == null) return -1;\n int r = c.Red;\n int g = c.Green;\n int b = c.Blue;\n int minpos = 0;\n int dmin = 256 * 256 * 256;\n int len = colorTab.Length;\n for (int i = 0; i < len;) {\n int dr = r - (colorTab[i++] & 0xff);\n int dg = g - (colorTab[i++] & 0xff);\n int db = b - (colorTab[i] & 0xff);\n int d = dr * dr + dg * dg + db * db;\n int index = i / 3;\n if (usedEntry[index] && (d < dmin)) {\n dmin = d;\n minpos = index;\n }\n i++;\n }\n return minpos;\n }\n\n /// <summary>\n /// Extracts image pixels into byte array \"pixels\"\n /// </summary>\n protected void GetImagePixels()\n {\n pixels = new byte[3 * image.Width * image.Height];\n int count = 0;\n\n for (int th = 0; th < image.Height; th++) {\n for (int tw = 0; tw < image.Width; tw++) {\n SKColor color = image.GetPixel(tw, th);\n pixels[count] = color.Red;\n count++;\n pixels[count] = color.Green;\n count++;\n pixels[count] = color.Blue;\n count++;\n }\n }\n\n //\t\tpixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();\n }\n\n /// <summary>\n /// Writes Graphic Control Extension\n /// </summary>\n protected void WriteGraphicCtrlExt()\n {\n ms.WriteByte(0x21); // extension introducer\n ms.WriteByte(0xf9); // GCE label\n ms.WriteByte(4); // data block size\n int transp, disp;\n if (transparent == SKColor.Empty) {\n transp = 0;\n disp = 0; // dispose = no action\n } else {\n transp = 1;\n disp = 2; // force clear if using transparent color\n }\n if (dispose >= 0) {\n disp = dispose & 7; // user override\n }\n disp <<= 2;\n\n // packed fields\n ms.WriteByte(Convert.ToByte(0 | // 1:3 reserved\n disp | // 4:6 disposal\n 0 | // 7 user input - 0 = none\n transp)); // 8 transparency flag\n\n WriteShort(delay); // delay x 1/100 sec\n ms.WriteByte(Convert.ToByte(transIndex)); // transparent color index\n ms.WriteByte(0); // block terminator\n }\n\n /// <summary>\n /// Writes Image Descriptor\n /// </summary>\n protected void WriteImageDesc()\n {\n ms.WriteByte(0x2c); // image separator\n WriteShort(0); // image position x,y = 0,0\n WriteShort(0);\n WriteShort(width); // image size\n WriteShort(height);\n // packed fields\n if (firstFrame) {\n // no LCT - GCT is used for first (or only) frame\n ms.WriteByte(0);\n } else {\n // specify normal LCT\n ms.WriteByte(Convert.ToByte(0x80 | // 1 local color table 1=yes\n 0 | // 2 interlace - 0=no\n 0 | // 3 sorted - 0=no\n 0 | // 4-5 reserved\n palSize)); // 6-8 size of color table\n }\n }\n\n /// <summary>\n /// Writes Logical Screen Descriptor\n /// </summary>\n protected void WriteLSD()\n {\n // logical screen size\n WriteShort(width);\n WriteShort(height);\n // packed fields\n ms.WriteByte(Convert.ToByte(0x80 | // 1 : global color table flag = 1 (gct used)\n 0x70 | // 2-4 : color resolution = 7\n 0x00 | // 5 : gct sort flag = 0\n palSize)); // 6-8 : gct size\n\n ms.WriteByte(0); // background color index\n ms.WriteByte(0); // pixel aspect ratio - assume 1:1\n }\n\n /// <summary>\n /// Writes Netscape application extension to define repeat count.\n /// </summary>\n protected void WriteNetscapeExt()\n {\n ms.WriteByte(0x21); // extension introducer\n ms.WriteByte(0xff); // app extension label\n ms.WriteByte(11); // block size\n WriteString(\"NETSCAPE\" + \"2.0\"); // app id + auth code\n ms.WriteByte(3); // sub-block size\n ms.WriteByte(1); // loop sub-block id\n WriteShort(repeat); // loop count (extra iterations, 0=repeat forever)\n ms.WriteByte(0); // block terminator\n }\n\n /// <summary>\n /// Writes color table\n /// </summary>\n protected void WritePalette()\n {\n ms.Write(colorTab, 0, colorTab.Length);\n int n = (3 * 256) - colorTab.Length;\n for (int i = 0; i < n; i++) {\n ms.WriteByte(0);\n }\n }\n\n /// <summary>\n /// Encodes and writes pixel data\n /// </summary>\n protected void WritePixels()\n {\n var encoder = new LZWEncoder(indexedPixels, colorDepth);\n encoder.Encode(ms);\n }\n\n /// <summary>\n /// Write 16-bit value to output stream, LSB first\n /// </summary>\n /// <param name=\"value\"></param>\n protected void WriteShort(int value)\n {\n ms.WriteByte(Convert.ToByte(value & 0xff));\n ms.WriteByte(Convert.ToByte((value >> 8) & 0xff));\n }\n\n /// <summary>\n /// Writes string to output stream\n /// </summary>\n /// <param name=\"s\"></param>\n protected void WriteString(string s)\n {\n char[] chars = s.ToCharArray();\n for (int i = 0; i < chars.Length; i++) {\n ms.WriteByte((byte)chars[i]);\n }\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (!disposedValue) {\n if (disposing) {\n ms.Dispose();\n }\n\n disposedValue = true;\n }\n }\n\n ~Encoder()\n {\n Dispose(disposing: false);\n }\n\n public void Dispose()\n {\n Dispose(disposing: true);\n GC.SuppressFinalize(this);\n }\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.4467984735965729, "alphanum_fraction": 0.47587883472442627, "avg_line_length": 32.08258819580078, "blob_id": "01b30a22e3773b7acca800c8b16d684a32688431", "content_id": "cca0434fb0783d8358ad95514efcc85442a247c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 14821, "license_type": "permissive", "max_line_length": 207, "num_lines": 448, "path": "/test/TorchSharpTest/TestJIT.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.IO;\nusing System.Linq;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\nusing Xunit;\n\n#nullable enable\n\nnamespace TorchSharp\n{\n [Collection(\"Sequential\")]\n public class TestJIT\n {\n [Fact]\n public void TestLoadJIT_Func()\n {\n // One linear layer followed by ReLU.\n using var m = torch.jit.load<Tensor, Tensor, Tensor>(@\"func.script.dat\");\n\n var sms = m.named_modules().ToArray();\n Assert.Empty(sms);\n\n var kids = m.named_children().ToArray();\n Assert.Empty(kids);\n\n var t = m.call(torch.ones(10), torch.ones(10));\n\n Assert.Equal(new long[] { 10 }, t.shape);\n Assert.Equal(torch.float32, t.dtype);\n Assert.True(torch.tensor(new float[] { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }).allclose(t));\n }\n\n [Fact]\n public void TestLoadJIT_1()\n {\n var input = torch.ones(10);\n var expected = torch.tensor(new float[] { 0.313458264f, 0, 0.9996568f, 0, 0, 0 });\n\n // One linear layer followed by ReLU.\n var m = torch.jit.load<Tensor, Tensor>(@\"linrelu.script.dat\");\n if (torch.cuda.is_available()) {\n m = m.to(torch.CUDA);\n input = input.to(torch.CUDA);\n expected = expected.to(torch.CUDA);\n }\n\n var t = m.call(input);\n\n Assert.Equal(new long[] { 6 }, t.shape);\n Assert.Equal(torch.float32, t.dtype);\n Assert.True(expected.allclose(t));\n }\n\n [Fact]\n public void TestSaveJIT()\n {\n var location = \"TestSaveJIT.ts\";\n if (File.Exists(location)) File.Delete(location);\n\n try {\n\n // One linear layer followed by ReLU.\n using var m1 = torch.jit.load<Tensor, Tensor>(@\"linrelu.script.dat\");\n\n torch.jit.save(m1, location);\n using var m2 = torch.jit.load<Tensor, Tensor>(location);\n\n var t = m2.call(torch.ones(10));\n\n Assert.Equal(new long[] { 6 }, t.shape);\n Assert.Equal(torch.float32, t.dtype);\n Assert.True(torch.tensor(new float[] { 0.313458264f, 0, 0.9996568f, 0, 0, 0 }).allclose(t));\n\n } finally {\n if (File.Exists(location)) File.Delete(location);\n }\n }\n\n [Fact]\n public void TestLoadJIT_2()\n {\n // One linear layer followed by ReLU.\n using var m = torch.jit.load<Tensor, Tensor>(@\"scripted.script.dat\");\n var t = m.call(torch.ones(6));\n\n Assert.Equal(new long[] { 6 }, t.shape);\n Assert.Equal(torch.float32, t.dtype);\n Assert.True(torch.tensor(new float[] { 1.554085f, 1.01024628f, -1.35086036f, -1.84021854f, 0.0127189457f, 0.5994258f }).allclose(t));\n }\n\n [Fact]\n public void TestLoadJIT_3()\n {\n // Two linear layers, nested Sequential, ReLU in between.\n using var m = torch.jit.load<Tensor, Tensor>(@\"l1000_100_10.script.dat\");\n\n var sms = m.named_modules().ToArray();\n Assert.Equal(4, sms.Length);\n\n var kids = m.named_children().ToArray();\n Assert.Equal(2, kids.Length);\n\n var t = m.call(torch.ones(1000));\n\n Assert.Equal(new long[] { 10 }, t.shape);\n Assert.Equal(torch.float32, t.dtype);\n Assert.True(torch.tensor(new float[] { 0.564213157f, -0.04519982f, -0.005117342f, 0.395530462f, -0.3780813f, -0.004734449f, -0.3221216f, -0.289159119f, 0.268511474f, 0.180702567f }).allclose(t));\n\n Assert.Throws<System.Runtime.InteropServices.ExternalException>(() => m.call(torch.ones(100)));\n }\n\n [Fact]\n public void TestLoadJIT_4()\n {\n // Definitely not a TorchScript file. Let's see what the runtime does with it.\n Assert.Throws<System.Runtime.InteropServices.ExternalException>(() => torch.jit.load(@\"bug510.dat\"));\n }\n\n [Fact]\n public void TestSaveLoadJITCUDA()\n {\n if (torch.cuda.is_available()) {\n\n {\n using var m = torch.jit.load<Tensor, Tensor>(@\"linrelu.script.dat\");\n\n m.to(DeviceType.CUDA);\n var params0 = m.parameters().ToArray();\n foreach (var p in params0)\n Assert.Equal(DeviceType.CUDA, p.device_type);\n\n var t = m.call(torch.ones(10).cuda()).cpu();\n\n Assert.Equal(new long[] { 6 }, t.shape);\n Assert.Equal(torch.float32, t.dtype);\n Assert.True(torch.tensor(new float[] { 0.313458264f, 0, 0.9996568f, 0, 0, 0 }).allclose(t));\n }\n {\n using var m = torch.jit.load<Tensor, Tensor>(@\"linrelu.script.dat\", DeviceType.CUDA);\n\n var params0 = m.parameters().ToArray();\n foreach (var p in params0)\n Assert.Equal(DeviceType.CUDA, p.device_type);\n\n var t = m.call(torch.ones(10).cuda()).cpu();\n\n Assert.Equal(new long[] { 6 }, t.shape);\n Assert.Equal(torch.float32, t.dtype);\n Assert.True(torch.tensor(new float[] { 0.313458264f, 0, 0.9996568f, 0, 0, 0 }).allclose(t));\n }\n }\n }\n\n [Fact]\n public void TestJIT_TupleOut()\n {\n // def a(x, y):\n // return x + y, x - y\n //\n using var m = torch.jit.load<(Tensor, Tensor)>(@\"tuple_out.dat\");\n\n var x = torch.rand(3, 4);\n var y = torch.rand(3, 4);\n var output = m.call(x, y);\n\n Assert.Multiple(\n () => Assert.Equal(x.shape, output.Item1.shape),\n () => Assert.Equal(x.shape, output.Item2.shape),\n () => Assert.Equal(x + y, output.Item1),\n () => Assert.Equal(x - y, output.Item2)\n );\n }\n\n [Fact]\n public void TestJIT_TupleOutError()\n {\n // def a(x, y):\n // return x + y, x - y\n //\n using var m = torch.jit.load<(Tensor, Tensor)>(@\"func.script.dat\");\n\n var x = torch.rand(3, 4);\n var y = torch.rand(3, 4);\n Assert.Throws<InvalidCastException>(() => m.call(x, y));\n }\n\n [Fact]\n public void TestJIT_ListOut()\n {\n // def a(x, y):\n // return [x + y, x - y]\n //\n using var m = torch.jit.load<Tensor[]>(@\"list_out.dat\");\n\n var x = torch.rand(3, 4);\n var y = torch.rand(3, 4);\n var output = m.call(x, y);\n\n Assert.Multiple(\n () => Assert.Equal(x.shape, output[0].shape),\n () => Assert.Equal(x.shape, output[1].shape),\n () => Assert.Equal(x + y, output[0]),\n () => Assert.Equal(x - y, output[1])\n );\n }\n\n [Fact]\n public void TestJIT_ListOutError()\n {\n // def a(x, y):\n // return x + y, x - y\n //\n using var m = torch.jit.load<Tensor[]>(@\"func.script.dat\");\n\n var x = torch.rand(3, 4);\n var y = torch.rand(3, 4);\n Assert.Throws<InvalidCastException>(() => m.call(x, y));\n }\n\n\n\n [Fact]\n public void TestLoadJIT_Methods()\n {\n // class MyModule(nn.Module):\n // def __init__(self):\n // super().__init__()\n // self.p = nn.Parameter(torch.rand(10))\n // def forward(self, x: Tensor, y: Tensor) -> Tuple[Tensor, Tensor]:\n // return x + y, x - y\n //\n // @torch.jit.export\n // def predict(self, x: Tensor) -> Tensor:\n // return x + self.p\n // @torch.jit.export\n // def add_scalar(self, x: Tensor, i: int) -> Tensor:\n // return x + i\n\n using var m = new TestScriptModule(@\"exported.method.dat\");\n\n var x = torch.rand(3, 4);\n var y = torch.rand(3, 4);\n var output = m.call(x, y);\n\n Assert.Multiple(\n () => Assert.Equal(x.shape, output.Item1.shape),\n () => Assert.Equal(x.shape, output.Item2.shape),\n () => Assert.Equal(x + y, output.Item1),\n () => Assert.Equal(x - y, output.Item2)\n );\n\n var ones = m.add_scalar(torch.zeros(10), 1);\n\n Assert.Equal(torch.ones(10), ones);\n\n var a = torch.rand(10);\n var predict = m.predict(a);\n\n Assert.Multiple(\n () => Assert.NotEqual(a, predict)\n );\n }\n\n internal class TestScriptModule : Module<Tensor, Tensor, (Tensor, Tensor)>\n {\n internal TestScriptModule(string filename) : base(nameof(TestScriptModule))\n {\n m = torch.jit.load<(Tensor, Tensor)> (filename);\n }\n\n public override (Tensor, Tensor) forward(Tensor input1, Tensor input2)\n {\n return m.call(input1, input2);\n }\n\n public Tensor predict(Tensor input)\n {\n return m.invoke<Tensor>(\"predict\", input);\n }\n\n public Tensor add_scalar(Tensor input, int i)\n {\n return m.invoke<Tensor>(\"add_scalar\", input, i);\n }\n\n private torch.jit.ScriptModule<(Tensor, Tensor)> m;\n }\n\n [Fact]\n public void TestJITCompile_1()\n {\n string script = @\"\n def relu_script(a, b):\n return torch.relu(a + b)\n def relu6_script(a, b):\n return torch.relu6(a + b)\n def add_i(x: Tensor, i: int) -> Tensor:\n return x + i\n def add_d(x: Tensor, i: float) -> Tensor:\n return x + i\n def add_ii(x: int, i: int) -> Tuple[int,int]:\n return (x + i,x-i)\n\";\n\n using var cu = torch.jit.compile(script);\n\n Assert.NotNull(cu);\n\n var x = torch.randn(3, 4);\n var y = torch.randn(3, 4);\n\n var zeros = torch.zeros(3, 4);\n var ones = torch.ones(3, 4);\n\n var z = (Tensor)cu.invoke(\"relu_script\", x, y);\n Assert.Equal(torch.nn.functional.relu(x + y), z);\n z = cu.invoke<Tensor>(\"relu6_script\", x, y);\n Assert.Equal(torch.nn.functional.relu6(x + y), z);\n z = cu.invoke<Tensor>(\"add_i\", zeros, 1);\n Assert.Equal(ones, z);\n z = cu.invoke<Tensor>(\"add_d\", zeros, 1.0);\n Assert.Equal(ones, z);\n\n var ss = cu.invoke<(Scalar,Scalar)>(\"add_ii\", 3, 1);\n Assert.Multiple(\n () => Assert.Equal(4, ss.Item1.ToInt32()),\n () => Assert.Equal(2, ss.Item2.ToInt32())\n );\n }\n\n [Fact]\n public void TestJITCompile_2()\n {\n string script = @\"\n def none_script(a: Any, b: Any):\n return a\n def none_tuple(a: Any, b: Any):\n return (a, None)\n def tuple_tuple(a: Any, b: Any, c:Any):\n return (a, (b, None))\n def list_tuple(a: Any, b: Any, c:Any):\n return [a, (b, c)]\n def list_tuple_list(a: Any, b: Any, c:Any):\n return [a, (b, [c, None])]\n\";\n\n using var cu = torch.jit.compile(script);\n\n Assert.NotNull(cu);\n\n var x = torch.randn(3, 4);\n var y = torch.randn(3, 5);\n var w = torch.randn(3, 6);\n\n var z = cu.invoke(\"none_script\", null, null);\n Assert.Null(z);\n z = cu.invoke(\"none_script\", null, y);\n Assert.Null(z);\n z = cu.invoke(\"none_script\", x, null);\n Assert.NotNull(z);\n\n {\n var zArr = cu.invoke<(object, object)>(\"none_tuple\", null, null);\n Assert.Null(zArr.Item1);\n Assert.Null(zArr.Item2);\n }\n\n {\n var zArr = cu.invoke<(object, object)>(\"none_tuple\", x, null);\n Assert.NotNull(zArr.Item1);\n Assert.Null(zArr.Item2);\n }\n\n {\n var zArr = cu.invoke<(object, object)>(\"tuple_tuple\", x, y, w);\n Assert.NotNull(zArr.Item1);\n Assert.Equal(x, (Tensor)zArr.Item1);\n //Assert.NotNull(zArr.Item2);\n var (a,b) = ((object, object))zArr.Item2;\n Assert.NotNull(a);\n Assert.Null(b);\n }\n\n {\n var zArr = cu.invoke<object[]>(\"list_tuple\", x, y, w);\n Assert.NotNull(zArr);\n Assert.NotNull(zArr[0]);\n Assert.IsType<Tensor>(zArr[0]);\n Assert.Equal(x, zArr[0]);\n Assert.NotNull(zArr[1]);\n Assert.IsType<(Tensor,Tensor)>(zArr[1]);\n }\n\n {\n var zArr = cu.invoke<object[]>(\"list_tuple_list\", x, y, w);\n Assert.NotNull(z);\n Assert.NotNull(zArr[0]);\n Assert.Equal(x, zArr[0]);\n Assert.NotNull(zArr[1]);\n }\n }\n\n [Fact]//(Skip =\"Doesn't work yet.\")]\n public void TestJITCompile_3()\n {\n string script = @\"\n def list_first(a: List[Tensor]) -> Tensor:\n return a[0]\n def list_two(a: List[Tensor]) -> List[Tensor]:\n return [a[0],a[1]]\n def list_from_two(a: List[Tensor], b: List[Tensor]) -> List[Tensor]:\n return [a[0],a[1],b[0],b[1]]\n\";\n\n using var cu = torch.jit.compile(script);\n\n Assert.NotNull(cu);\n\n var x = torch.randn(3, 4);\n var y = torch.randn(3, 5);\n var w = torch.randn(3, 6);\n\n {\n var zArr = cu.invoke<Tensor>(\"list_first\", new[] { new[] { x, y } });\n Assert.NotNull(zArr);\n Assert.Equal(x, zArr);\n }\n {\n var zArr = cu.invoke<Tensor[]>(\"list_two\", new [] { new[] { x, w } });\n Assert.NotNull(zArr);\n Assert.Equal(2, zArr.Length);\n Assert.Equal(x, zArr[0]);\n Assert.Equal(w, zArr[1]);\n }\n {\n var zArr = cu.invoke<Tensor[]>(\"list_from_two\", new[] { x, y }, new[] { y, w });\n Assert.NotNull(zArr);\n Assert.Equal(4, zArr.Length);\n Assert.Equal(x, zArr[0]);\n Assert.Equal(y, zArr[1]);\n Assert.Equal(y, zArr[2]);\n Assert.Equal(w, zArr[3]);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6138077974319458, "alphanum_fraction": 0.6138077974319458, "avg_line_length": 40.36800003051758, "blob_id": "d7dcc65168281c62ac0b6ac35ec7755c686f46cd", "content_id": "162eda077cfa06d85cb15a1b17eb6feb4f9ba49a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5171, "license_type": "permissive", "max_line_length": 140, "num_lines": 125, "path": "/src/TorchSharp/Tensor/Factories/as_tensor.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System.Collections.Generic;\nusing System.Linq;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torch\n {\n // as_tensor()\n\n public static Tensor as_tensor(Tensor data, ScalarType? dtype = null, Device? device = null)\n {\n if (dtype != null && device != null && (data.dtype != dtype || data.device != device)) {\n return data.to(dtype.Value, device).requires_grad_(data.requires_grad);\n } else if (dtype != null && data.dtype != dtype) {\n return data.to(dtype.Value).requires_grad_(data.requires_grad);\n } else if (device != null && data.device != device) {\n return data.to(device).requires_grad_(data.requires_grad);\n } else {\n return data.alias();\n }\n }\n\n public static Tensor as_tensor(IList<bool> rawArray, ScalarType? dtype = null, Device? device = null)\n {\n return torch.from_array(rawArray.ToArray(), dtype, device);\n }\n\n public static Tensor as_tensor(bool[] rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray, dtype, device);\n }\n\n public static Tensor as_tensor(IList<byte> rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray.ToArray(), dtype, device);\n }\n\n public static Tensor as_tensor(byte[] rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray, dtype, device);\n }\n\n public static Tensor as_tensor(IList<sbyte> rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray.ToArray(), dtype, device);\n }\n\n public static Tensor as_tensor(sbyte[] rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray, dtype, device);\n }\n\n public static Tensor as_tensor(IList<short> rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray.ToArray(), dtype, device);\n }\n\n public static Tensor as_tensor(short[] rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray, dtype, device);\n }\n\n public static Tensor as_tensor(IList<int> rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray.ToArray(), dtype, device);\n }\n\n public static Tensor as_tensor(int[] rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray, dtype, device);\n }\n\n public static Tensor as_tensor(IList<long> rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray.ToArray(), dtype, device);\n }\n\n public static Tensor as_tensor(long[] rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray, dtype, device);\n }\n\n public static Tensor as_tensor(IList<float> rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray.ToArray(), dtype, device);\n }\n\n public static Tensor as_tensor(float[] rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray, dtype, device);\n }\n\n public static Tensor as_tensor(IList<double> rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray.ToArray(), dtype, device);\n }\n\n public static Tensor as_tensor(double[] rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray, dtype, device);\n }\n\n public static Tensor as_tensor(IList<(float, float)> rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray.ToArray(), dtype, device);\n }\n\n public static Tensor as_tensor((float, float)[] rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray, dtype, device);\n }\n\n public static Tensor as_tensor(IList<System.Numerics.Complex> rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray.ToArray(), dtype, device);\n }\n\n public static Tensor as_tensor(System.Numerics.Complex[] rawArray, torch.ScalarType? dtype = null, torch.Device? device = null)\n {\n return torch.from_array(rawArray, dtype, device);\n }\n }\n}\n" }, { "alpha_fraction": 0.561601996421814, "alphanum_fraction": 0.5667617917060852, "avg_line_length": 52.5293083190918, "blob_id": "cd4abbdaec593fd0eabe05e42dc63a6a009f105f", "content_id": "5e514bef5e2ed4c80d2c36d70b4cf99afee6e37e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 60300, "license_type": "permissive", "max_line_length": 244, "num_lines": 1126, "path": "/src/TorchSharp/NN/Losses.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\n\nnamespace TorchSharp\n{\n using Modules;\n\n public abstract class Loss<T1, T2, TResult> : nn.Module<T1, T2, TResult>\n {\n public Loss(torch.nn.Reduction reduction = nn.Reduction.Mean) : base(nameof(Loss<T1, T2, TResult>))\n {\n this.reduction = reduction;\n }\n\n public torch.nn.Reduction reduction { get; }\n }\n\n public abstract class Loss<T1, T2, T3, TResult> : nn.Module<T1, T2, T3, TResult>\n {\n public Loss(torch.nn.Reduction reduction = nn.Reduction.Mean) : base(nameof(Loss<T1, T2, T3, TResult>))\n {\n this.reduction = reduction;\n }\n\n public torch.nn.Reduction reduction { get; }\n }\n public abstract class Loss<T1, T2, T3, T4, TResult> : nn.Module<T1, T2, T3, T4, TResult>\n {\n public Loss(torch.nn.Reduction reduction = nn.Reduction.Mean) : base(nameof(Loss<T1, T2, T3, T4, TResult>))\n {\n this.reduction = reduction;\n }\n\n public torch.nn.Reduction reduction { get; }\n }\n\n public abstract class WeightedLoss<T1, T2, TResult> : Loss<T1, T2, TResult>\n {\n public WeightedLoss(Tensor? weight = null, torch.nn.Reduction reduction = nn.Reduction.Mean) : base(reduction)\n {\n this.weight = weight;\n }\n\n public Tensor? weight { get; }\n }\n\n public abstract class WeightedLoss<T1, T2, T3, TResult> : Loss<T1, T2, T3, TResult>\n {\n public WeightedLoss(Tensor? weight = null, torch.nn.Reduction reduction = nn.Reduction.Mean) : base(reduction)\n {\n this.weight = weight;\n }\n\n public Tensor? weight { get; }\n }\n\n public abstract class WeightedLoss<T1, T2, T3, T4, TResult> : Loss<T1, T2, T3, T4, TResult>\n {\n public WeightedLoss(Tensor? weight = null, torch.nn.Reduction reduction = nn.Reduction.Mean) : base(reduction)\n {\n this.weight = weight;\n }\n\n public Tensor? weight { get; }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// This criterion combines log_softmax and nll_loss in a single function.\n /// </summary>\n /// <param name=\"weight\">A manual rescaling weight if provided it’s repeated to match input tensor shape</param>\n /// <param name=\"ignore_index\">Specifies a target value that is ignored and does not contribute to the input gradient.</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Modules.CrossEntropyLoss CrossEntropyLoss(Tensor? weight = null, long? ignore_index = null, Reduction reduction = Reduction.Mean)\n {\n return new Modules.CrossEntropyLoss(weight, ignore_index, reduction);\n }\n\n /// <summary>\n /// Measures the Binary Cross Entropy between the target and the output.\n /// </summary>\n /// <param name=\"weight\">A manual rescaling weight if provided it’s repeated to match input tensor shape</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Modules.BCELoss BCELoss(Tensor? weight = null, Reduction reduction = Reduction.Mean)\n {\n return new Modules.BCELoss(weight, reduction);\n }\n\n /// <summary>\n /// Measures Binary Cross Entropy between target and output logits.\n /// </summary>\n /// <param name=\"weight\">A manual rescaling weight if provided it’s repeated to match input tensor shape</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <param name=\"pos_weights\">A weight of positive examples. Must be a vector with length equal to the number of classes.</param>\n /// <returns></returns>\n public static Modules.BCEWithLogitsLoss BCEWithLogitsLoss(Tensor? weight = null, Reduction reduction = Reduction.Mean, Tensor? pos_weights = null)\n {\n return new Modules.BCEWithLogitsLoss(weight, reduction, pos_weights);\n }\n\n /// <summary>\n /// Measures the loss given two input tensor and a lable tensor with values 1 or -1.\n ///\n /// See: https://pytorch.org/docs/stable/generated/torch.nn.CosineEmbeddingLoss.html#torch.nn.CosineEmbeddingLoss\n /// </summary>\n /// <param name=\"margin\"> Should be a number from -1 to 1, 0 to 0.5 is suggested</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Modules.CosineEmbeddingLoss CosineEmbeddingLoss(double margin = 0.0, Reduction reduction = Reduction.Mean)\n {\n return new Modules.CosineEmbeddingLoss(margin, reduction);\n }\n\n\n /// <summary>\n /// The Connectionist Temporal Classification loss.\n ///\n /// Calculates loss between a continuous (unsegmented) time series and a target sequence.\n /// CTCLoss sums over the probability of possible alignments of input to target, producing a\n /// loss value which is differentiable with respect to each input node. The alignment of input to\n /// target is assumed to be “many-to-one”, which limits the length of the target sequence such that\n /// it must be less than the input length.\n /// </summary>\n /// <returns></returns>\n public static Modules.CTCLoss CTCLoss(long blank = 0, bool zero_infinity = false, Reduction reduction = Reduction.Mean)\n {\n return new Modules.CTCLoss(blank, zero_infinity, reduction);\n }\n\n /// <summary>\n /// Measures the loss given an input tensor x and a labels tensor y (containing 1 or -1).\n ///\n /// See: https://pytorch.org/docs/stable/generated/torch.nn.HingeEmbeddingLoss.html#torch.nn.HingeEmbeddingLoss\n /// </summary>\n /// <param name=\"margin\"> Should be a number from -1 to 1, 0 to 0.5 is suggested</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Modules.HingeEmbeddingLoss HingeEmbeddingLoss(double margin = 1.0, Reduction reduction = Reduction.Mean)\n {\n return new Modules.HingeEmbeddingLoss(margin, reduction);\n }\n\n /// <summary>\n /// Creates a criterion that uses a squared term if the absolute element-wise error falls below delta and a delta-scaled L1 term otherwise.\n ///\n /// See: https://pytorch.org/docs/stable/generated/torch.nn.HuberLoss.html#torch.nn.HuberLoss\n /// </summary>\n /// <param name=\"delta\">Specifies the threshold at which to change between delta-scaled L1 and L2 loss. The value must be positive. Default: 1.0</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Modules.HuberLoss HuberLoss(double delta = 1.0, Reduction reduction = Reduction.Mean)\n {\n return new Modules.HuberLoss(delta, reduction);\n }\n\n /// <summary>\n /// Creates a criterion that measures the loss given inputs x1, x2, two 1D mini-batch or 0D Tensors, and a label 1D mini-batch or 0D Tensor y (containing 1 or -1).\n ///\n /// See: https://pytorch.org/docs/stable/generated/torch.nn.MarginRankingLoss.html#torch.nn.MarginRankingLoss\n /// </summary>\n /// <param name=\"margin\">Has a default value of 0.</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Modules.MarginRankingLoss MarginRankingLoss(double margin = 0, Reduction reduction = Reduction.Mean)\n {\n return new Modules.MarginRankingLoss(margin, reduction);\n }\n\n /// <summary>\n /// Creates a criterion that optimizes a multi-label one-versus-all loss based on max-entropy, between input x and target y of size NxC.\n ///\n /// See: https://pytorch.org/docs/stable/generated/torch.nn.MultiLabelSoftMarginLoss.html#torch.nn.MultiLabelSoftMarginLoss\n /// </summary>\n /// <param name=\"weight\">A manual rescaling weight given to each class. If given, it has to be a Tensor of size C. Otherwise, it is treated as if having all ones.</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static MultiLabelSoftMarginLoss MultiLabelSoftMarginLoss(Tensor? weight = null, Reduction reduction = Reduction.Mean)\n {\n return new MultiLabelSoftMarginLoss(weight, reduction);\n }\n\n /// <summary>\n /// Creates a criterion that optimizes a multi-class classification hinge loss.\n ///\n /// See: https://pytorch.org/docs/stable/generated/torch.nn.MultiMarginLoss.html#torch.nn.MultiMarginLoss\n /// </summary>\n /// <param name=\"p\">Has a default value of 1. 1 and 2 are the only supported values.</param>\n /// <param name=\"margin\">Has a default value of 1</param>\n /// <param name=\"weight\">A manual rescaling weight given to each class. If given, it has to be a Tensor of size C. Otherwise, it is treated as if having all ones.</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n public static MultiMarginLoss MultiMarginLoss(int p = 1, double margin = 1.0, Tensor? weight = null, Reduction reduction = Reduction.Mean)\n {\n return new MultiMarginLoss(p, margin, weight, reduction);\n }\n\n /// <summary>\n /// Measures the element-wise mean squared error.\n /// </summary>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static MSELoss MSELoss(Reduction reduction = Reduction.Mean)\n {\n return new MSELoss(reduction);\n }\n\n /// <summary>\n /// Function that takes the mean element-wise absolute value difference.\n /// </summary>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static L1Loss L1Loss(Reduction reduction = Reduction.Mean)\n {\n return new L1Loss(reduction);\n }\n\n /// <summary>\n /// The negative log likelihood loss.\n /// </summary>\n /// <param name=\"weight\">A manual rescaling weight if provided it’s repeated to match input tensor shape</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static NLLLoss NLLLoss(Tensor? weight = null, Reduction reduction = Reduction.Mean)\n {\n return new NLLLoss(weight, reduction);\n }\n\n /// <summary>\n /// Poisson negative log likelihood loss.\n /// </summary>\n /// <param name=\"log_input\"></param>\n /// <param name=\"full\">Whether to compute full loss, i. e. to add the Stirling approximation term.</param>\n /// <param name=\"eps\">Small value to avoid evaluation of log(0)</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static PoissonNLLLoss PoissonNLLLoss(bool log_input = true, bool full = false, float eps = 1e-8f, Reduction reduction = Reduction.Mean)\n {\n return new PoissonNLLLoss(log_input, full, eps, reduction);\n }\n\n /// <summary>\n /// The Kullback-Leibler divergence Loss\n /// </summary>\n /// <param name=\"log_target\">A flag indicating whether target is passed in the log space.</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static KLDivLoss KLDivLoss(bool log_target = true, Reduction reduction = Reduction.Mean)\n {\n return new KLDivLoss(log_target, reduction);\n }\n\n /// <summary>\n /// Optimizes a two-class classification logistic loss between input tensor xx and target tensor yy (containing 1 or -1).\n /// </summary>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static SoftMarginLoss SoftMarginLoss(Reduction reduction = Reduction.Mean)\n {\n return new SoftMarginLoss(reduction);\n }\n\n /// <summary>\n /// Creates a criterion that measures the triplet loss given an input tensors x1, x2, x3 and a margin with a value greater than 0.\n /// This is used for measuring a relative similarity between samples.\n ///\n /// See: https://pytorch.org/docs/stable/generated/torch.nn.TripletMarginLoss.html#torch.nn.TripletMarginLoss\n /// </summary>\n /// <param name=\"margin\">\n /// A nonnegative margin representing the minimum difference between the positive and negative distances required for the loss to be 0.\n /// Larger margins penalize cases where the negative examples are not distant enough from the anchors, relative to the positives.\n /// </param>\n /// <param name=\"p\">The norm degree for pairwise distance. </param>\n /// <param name=\"eps\"></param>\n /// <param name=\"swap\">\n /// If true, and if the positive example is closer to the negative example than the anchor is, swaps the positive example and the anchor in the loss computation.\n /// The distance swap is described in detail in the paper Learning shallow convolutional feature descriptors with triplet losses by V. Balntas, E. Riba et al.\n /// </param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static TripletMarginLoss TripletMarginLoss(double margin = 1.0, long p = 2, double eps = 1e-06, bool swap = false, Reduction reduction = Reduction.Mean)\n {\n return new TripletMarginLoss(margin, p, eps, swap, reduction);\n }\n\n /// <summary>\n /// Creates a criterion that measures the triplet loss given input tensors a, p, and n (representing anchor, positive, and negative examples, respectively),\n /// and a nonnegative, real-valued function (\"distance function\") used to compute the relationship between the anchor and positive example (\"positive distance\")\n /// and the anchor and negative example (\"negative distance\").\n /// </summary>\n /// <param name=\"distance\"> A nonnegative, real-valued function that quantifies the closeness of two tensors. If not specified, nn.PairwiseDistance will be used.</param>\n /// <param name=\"margin\">\n /// A nonnegative margin representing the minimum difference between the positive and negative distances required for the loss to be 0.\n /// Larger margins penalize cases where the negative examples are not distant enough from the anchors, relative to the positives.\n /// </param>\n /// <param name=\"swap\">\n /// If true, and if the positive example is closer to the negative example than the anchor is, swaps the positive example and the anchor in the loss computation.\n /// The distance swap is described in detail in the paper Learning shallow convolutional feature descriptors with triplet losses by V. Balntas, E. Riba et al.\n /// </param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static TripletMarginWithDistanceLoss TripletMarginWithDistanceLoss(Func<Tensor, Tensor, Tensor>? distance = null, double margin = 1.0, bool swap = false, Reduction reduction = Reduction.Mean)\n {\n return new TripletMarginWithDistanceLoss(distance, margin, swap, reduction);\n }\n\n /// <summary>\n /// Gaussian negative log likelihood loss.\n /// </summary>\n /// <param name=\"full\">Include the constant term in the loss calculation</param>\n /// <param name=\"eps\">Value used to clamp var (see note below), for stability.</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static GaussianNLLLoss GaussianNLLLoss(bool full = false, float eps = 1e-8f, Reduction reduction = Reduction.Mean)\n {\n return new GaussianNLLLoss(full, eps, reduction);\n }\n\n /// <summary>\n /// Creates a criterion that optimizes a multi-class multi-classification hinge loss (margin-based loss) between input x (a 2D mini-batch Tensor)\n /// and output y (which is a 2D Tensor of target class indices).\n /// </summary>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static MultiLabelMarginLoss MultiLabelMarginLoss(Reduction reduction = Reduction.Mean)\n {\n return new MultiLabelMarginLoss(reduction);\n }\n\n /// <summary>\n /// Function that uses a squared term if the absolute element-wise error falls below beta and an L1 term otherwise.\n /// </summary>\n /// <param name=\"beta\">Specifies the threshold at which to change between L1 and L2 loss. The value must be non-negative. Default: 1.0</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static SmoothL1Loss SmoothL1Loss(Reduction reduction = Reduction.Mean, double beta = 1.0)\n {\n return new SmoothL1Loss(reduction, beta);\n }\n\n\n /// <summary>\n /// Class maintaing the supported loss functions.\n /// </summary>\n public static partial class functional\n {\n /// <summary>\n /// Function that measures Binary Cross Entropy between target and input logits.\n /// </summary>\n /// <param name=\"input\">Tensor of arbitrary shape as unnormalized scores (often referred to as logits).</param>\n /// <param name=\"target\">Tensor of the same shape as input with values between 0 and 1</param>\n /// <param name=\"weight\">A manual rescaling weight if provided it’s repeated to match input tensor shape</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <param name=\"pos_weights\">A weight of positive examples. Must be a vector with length equal to the number of classes.</param>\n /// <returns></returns>\n public static Tensor binary_cross_entropy_with_logits(Tensor input, Tensor target, Tensor? weight = null, Reduction reduction = Reduction.Mean, Tensor? pos_weights = null)\n {\n var res = THSNN_binary_cross_entropy_with_logits(input.Handle, target.Handle, weight?.Handle ?? IntPtr.Zero, (long)reduction, pos_weights?.Handle ?? IntPtr.Zero);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Function that measures the Binary Cross Entropy between the target and input probabilities.\n /// </summary>\n /// <param name=\"input\">Tensor of arbitrary shape as probabilities.</param>\n /// <param name=\"target\">Tensor of the same shape as input with values between 0 and 1</param>\n /// <param name=\"weight\">A manual rescaling weight if provided it’s repeated to match input tensor shape</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor binary_cross_entropy(Tensor input, Tensor target, Tensor? weight = null, Reduction reduction = Reduction.Mean)\n {\n var res = THSNN_binary_cross_entropy(input.Handle, target.Handle, weight?.Handle ?? IntPtr.Zero, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the cross entropy loss between input and target.\n /// </summary>\n /// <param name=\"input\">Tensor of arbitrary shape as unnormalized scores (often referred to as logits).</param>\n /// <param name=\"target\">Ground truth class indices or class probabilities; see Shape section below for supported shapes.</param>\n /// <param name=\"weight\">A manual rescaling weight if provided it’s repeated to match input tensor shape</param>\n /// <param name=\"ignore_index\">\n /// Specifies a target value that is ignored and does not contribute to the input gradient.\n /// Note that ignore_index is only applicable when the target contains class indices.\n /// </param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <param name=\"label_smoothing\">A float in [0.0, 1.0].\n /// Specifies the amount of smoothing when computing the loss, where 0.0 means no smoothing.\n /// The targets become a mixture of the original ground truth and a uniform distribution.</param>\n /// <returns></returns>\n public static Tensor cross_entropy(Tensor input, Tensor target, Tensor? weight = null, long ignore_index = -100, Reduction reduction = Reduction.Mean, double label_smoothing = 0.0)\n {\n var res = THSNN_cross_entropy(input.Handle, target.Handle, weight?.Handle ?? IntPtr.Zero, ignore_index, true, (long)reduction, label_smoothing);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Poisson negative log likelihood loss.\n /// </summary>\n /// <param name=\"input\">Expectation of underlying Poisson distribution.</param>\n /// <param name=\"target\">Random sample target.</param>\n /// <param name=\"log_input\"></param>\n /// <param name=\"full\">Whether to compute full loss, i.e. to add the Stirling approximation term.</param>\n /// <param name=\"eps\">Small value to avoid evaluation of log(0)</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor poisson_nll_loss(Tensor input, Tensor target, bool log_input = true, bool full = false, float eps = 1e-8f, Reduction reduction = Reduction.Mean)\n {\n var res = THSNN_poisson_loss(input.Handle, target.Handle, log_input, full, eps, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n ///\n /// </summary>\n /// <param name=\"input1\">(N,D) or (D), where N is the batch size and D is the embedding dimension.</param>\n /// <param name=\"input2\">Same shape as input1</param>\n /// <param name=\"target\">N or ()</param>\n /// <param name=\"margin\">Should be a number from -1−1 to 11, 00 to 0.50.5 is suggested</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor cosine_embedding_loss(Tensor input1, Tensor input2, Tensor target, double margin = 0.0, Reduction reduction = Reduction.Mean)\n {\n var res = THSNN_cosine_embedding_loss(input1.Handle, input2.Handle, target.Handle, margin, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the Connectionist Temporal Classification loss.\n /// </summary>\n /// <param name=\"log_probs\">The logarithmized probabilities of the outputs.</param>\n /// <param name=\"targets\"></param>\n /// <param name=\"input_lengths\">Lengths of the inputs.</param>\n /// <param name=\"target_lengths\">Lengths of the targets.</param>\n /// <param name=\"blank\">Blank label.</param>\n /// <param name=\"zero_infinity\">Whether to zero infinite losses and the associated gradients.</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor ctc_loss(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, long blank = 0, bool zero_infinity = false, Reduction reduction = Reduction.Mean)\n {\n var res = THSNN_ctc_loss(log_probs.Handle, targets.Handle, input_lengths.Handle, target_lengths.Handle, blank, zero_infinity, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Measures the loss given an input tensor x and a labels tensor y (containing 1 or -1).\n /// </summary>\n /// <param name=\"input\"></param>\n /// <param name=\"target\"></param>\n /// <param name=\"margin\"> Should be a number from -1 to 1, 0 to 0.5 is suggested</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor hinge_embedding_loss(Tensor input, Tensor target, double margin = 0.0, Reduction reduction = Reduction.Mean)\n {\n var res = THSNN_hinge_embedding_loss(input.Handle, target.Handle, margin, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Function that uses a squared term if the absolute element-wise error falls below delta and a delta-scaled L1 term otherwise.\n /// </summary>\n /// <param name=\"input\"></param>\n /// <param name=\"target\"></param>\n /// <param name=\"delta\">Specifies the threshold at which to change between delta-scaled L1 and L2 loss. The value must be positive. Default: 1.0</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor huber_loss(Tensor input, Tensor target, double delta = 1.0, Reduction reduction = Reduction.Mean)\n {\n var res = THSNN_huber_loss(input.Handle, target.Handle, delta, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Creates a criterion that measures the loss given inputs x1, x2, two 1D mini-batch or 0D Tensors, and a label 1D mini-batch or 0D Tensor y (containing 1 or -1).\n /// </summary>\n /// <param name=\"input1\"></param>\n /// <param name=\"input2\"></param>\n /// <param name=\"target\"></param>\n /// <param name=\"margin\">Has a default value of 0.</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor margin_ranking_loss(Tensor input1, Tensor input2, Tensor target, double margin = 0.0, Reduction reduction = Reduction.Mean)\n {\n var res = THSNN_margin_ranking_loss(input1.Handle, input2.Handle, target.Handle, margin, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Creates a criterion that optimizes a multi-class multi-classification hinge loss (margin-based loss) between input x (a 2D mini-batch Tensor)\n /// and output y (which is a 2D Tensor of target class indices).\n /// </summary>\n /// <param name=\"input\"></param>\n /// <param name=\"target\"></param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor multi_label_margin_loss(Tensor input, Tensor target, Reduction reduction = Reduction.Mean)\n {\n var res = THSNN_multilabel_margin_loss(input.Handle, target.Handle, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Creates a criterion that optimizes a multi-label one-versus-all loss based on max-entropy, between input x and target y of size NxC.\n /// </summary>\n /// <param name=\"input\"></param>\n /// <param name=\"target\"></param>\n /// <param name=\"weight\">A manual rescaling weight if provided it’s repeated to match input tensor shape</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor multilabel_soft_margin_loss(Tensor input, Tensor target, Tensor? weight = null,Reduction reduction = Reduction.Mean)\n {\n var res = THSNN_multilabel_soft_margin_loss(input.Handle, target.Handle, weight?.Handle ?? IntPtr.Zero, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Creates a criterion that optimizes a multi-class classification hinge loss.\n /// </summary>\n /// <param name=\"input\"></param>\n /// <param name=\"target\"></param>\n /// <param name=\"p\">Has a default value of 1. 1 and 2 are the only supported values.</param>\n /// <param name=\"margin\">Has a default value of 1</param>\n /// <param name=\"weight\">A manual rescaling weight if provided it’s repeated to match input tensor shape</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor multi_margin_loss(Tensor input, Tensor target, int p = 1, double margin = 1.0, Tensor? weight = null, Reduction reduction = Reduction.Mean)\n {\n IntPtr h = (weight is null) ? IntPtr.Zero : weight.Handle;\n var res = THSNN_multi_margin_loss(input.Handle, target.Handle, p, margin, h, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n ///\tMeasures the element-wise mean squared error.\n /// </summary>\n /// <param name=\"input\">Tensor of any shape.</param>\n /// <param name=\"target\">Tensor of the same shape as 'input'</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor mse_loss(Tensor input, Tensor target, Reduction reduction = Reduction.Mean)\n {\n var res = THSNN_mse_loss(input.Handle, target.Handle, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Function that takes the mean element-wise absolute value difference.\n /// </summary>\n /// <param name=\"input\">Tensor of any shape.</param>\n /// <param name=\"target\">Tensor of the same shape as 'input'</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor l1_loss(Tensor input, Tensor target, Reduction reduction = Reduction.Mean)\n {\n var res = THSNN_l1_loss(input.Handle, target.Handle, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the negative log likelihood loss.\n /// </summary>\n /// <param name=\"input\"></param>\n /// <param name=\"target\"></param>\n /// <param name=\"weight\">A manual rescaling weight if provided it’s repeated to match input tensor shape</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor nll_loss(Tensor input, Tensor target, Tensor? weight = null, Reduction reduction = Reduction.Mean)\n {\n var res = THSNN_nll_loss(input.Handle, target.Handle, weight?.Handle ?? IntPtr.Zero, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Gaussian negative log likelihood loss.\n /// </summary>\n /// <param name=\"input\"></param>\n /// <param name=\"target\"></param>\n /// <param name=\"variance\">Tensor of positive variance(s), one for each of the expectations in the input (heteroscedastic), or a single one (homoscedastic).</param>\n /// <param name=\"full\">Include the constant term in the loss calculation. </param>\n /// <param name=\"eps\">Value added to var, for stability</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor gaussian_nll_loss(Tensor input, Tensor target, Tensor variance, bool full = false, float eps = 1e-6f, Reduction reduction = Reduction.Mean)\n {\n return new Modules.GaussianNLLLoss(full, eps, reduction).call(input, target, variance);\n }\n\n /// <summary>\n /// Computes the Kullback-Leibler divergence Loss\n /// </summary>\n /// <param name=\"input\"></param>\n /// <param name=\"target\"></param>\n /// <param name=\"log_target\">A flag indicating whether target is passed in the log space.</param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor kl_div(Tensor input, Tensor target, bool log_target = true, Reduction reduction = Reduction.Mean)\n {\n var res = THSNN_kl_div_loss(input.Handle, target.Handle, (long)reduction, log_target);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Function that uses a squared term if the absolute element-wise error falls below beta and an L1 term otherwise.\n /// </summary>\n /// <param name=\"input\"></param>\n /// <param name=\"target\"></param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <param name=\"beta\">Specifies the threshold at which to change between L1 and L2 loss. The value must be non-negative.</param>\n /// <returns></returns>\n public static Tensor smooth_l1_loss(Tensor input, Tensor target, Reduction reduction = Reduction.Mean, double beta = 1.0)\n {\n var res = THSNN_smooth_l1_loss(input.Handle, target.Handle, (long)reduction, beta);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Optimizes a two-class classification logistic loss between input tensor x and target tensor y (containing 1 or -1).\n /// </summary>\n /// <param name=\"input\"></param>\n /// <param name=\"target\"></param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor soft_margin_loss(Tensor input, Tensor target, Reduction reduction = Reduction.Mean)\n {\n var res = THSNN_soft_margin_loss(input.Handle, target.Handle, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Creates a criterion that measures the triplet loss given an input tensors x1, x2, x3 and a margin with a value greater than 0.\n /// This is used for measuring a relative similarity between samples.\n /// </summary>\n /// <param name=\"anchor\"></param>\n /// <param name=\"positive\"></param>\n /// <param name=\"negative\"></param>\n /// <param name=\"margin\">\n /// A nonnegative margin representing the minimum difference between the positive and negative distances required for the loss to be 0.\n /// Larger margins penalize cases where the negative examples are not distant enough from the anchors, relative to the positives.\n /// </param>\n /// <param name=\"p\">The norm degree for pairwise distance. </param>\n /// <param name=\"eps\"></param>\n /// <param name=\"swap\">\n /// If true, and if the positive example is closer to the negative example than the anchor is, swaps the positive example and the anchor in the loss computation.\n /// The distance swap is described in detail in the paper Learning shallow convolutional feature descriptors with triplet losses by V. Balntas, E. Riba et al.\n /// </param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor triplet_margin_loss(Tensor anchor, Tensor positive, Tensor negative, double margin = 1.0, long p = 2, double eps = 1e-06, bool swap = false, Reduction reduction = Reduction.Mean)\n {\n var res = THSNN_triplet_margin_loss(anchor.Handle, positive.Handle, negative.Handle, margin, p, eps, swap, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Creates a criterion that measures the triplet loss given input tensors a, p, and n (representing anchor, positive, and negative examples, respectively),\n /// and a nonnegative, real-valued function (\"distance function\") used to compute the relationship between the anchor and positive example (\"positive distance\")\n /// and the anchor and negative example (\"negative distance\").\n /// </summary>\n /// <param name=\"anchor\"></param>\n /// <param name=\"positive\"></param>\n /// <param name=\"negative\"></param>\n /// <param name=\"distance\"> A nonnegative, real-valued function that quantifies the closeness of two tensors. If not specified, nn.PairwiseDistance will be used.</param>\n /// <param name=\"margin\">\n /// A nonnegative margin representing the minimum difference between the positive and negative distances required for the loss to be 0.\n /// Larger margins penalize cases where the negative examples are not distant enough from the anchors, relative to the positives.\n /// </param>\n /// <param name=\"swap\">\n /// If true, and if the positive example is closer to the negative example than the anchor is, swaps the positive example and the anchor in the loss computation.\n /// The distance swap is described in detail in the paper Learning shallow convolutional feature descriptors with triplet losses by V. Balntas, E. Riba et al.\n /// </param>\n /// <param name=\"reduction\">Specifies the reduction to apply to the output</param>\n /// <returns></returns>\n public static Tensor triplet_margin_with_distance_loss(Tensor anchor, Tensor positive, Tensor negative, Func<Tensor, Tensor, Tensor>? distance = null, double margin = 1.0, bool swap = false, Reduction reduction = Reduction.Mean)\n {\n DistanceFunctionNative? func = null;\n\n if (distance != null) {\n func = (IntPtr x, IntPtr y) => {\n var x1 = new Tensor(x);\n var y1 = new Tensor(y);\n var res = distance(x1, y1);\n\n GC.SuppressFinalize(x1);\n GC.SuppressFinalize(y1);\n GC.SuppressFinalize(res);\n\n return res.Handle;\n };\n }\n var res = THSNN_triplet_margin_with_distance_loss(anchor.Handle, positive.Handle, negative.Handle, func, margin, swap, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n public enum Reduction : long\n {\n None = 0,\n Mean = 1,\n Sum = 2\n }\n }\n }\n\n namespace Modules\n {\n public sealed class CrossEntropyLoss : WeightedLoss<Tensor, Tensor, Tensor>\n {\n public CrossEntropyLoss(Tensor? weight = null, long? ignore_index = null, Reduction reduction = Reduction.Mean, double label_smoothing = 0.0) : base(weight, reduction)\n {\n this.ignore_index = ignore_index;\n this.label_smoothing = label_smoothing;\n }\n\n public override Tensor forward(Tensor input, Tensor target)\n {\n var ii = ignore_index.HasValue ? ignore_index.Value : -100;\n var res = THSNN_cross_entropy(input.Handle, target.Handle, weight?.Handle ?? IntPtr.Zero, ii, ignore_index.HasValue, (long)reduction, label_smoothing);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public long? ignore_index { get; }\n public double label_smoothing { get; }\n }\n\n public sealed class BCELoss : WeightedLoss<Tensor, Tensor, Tensor>\n {\n public BCELoss(Tensor? weight = null, Reduction reduction = Reduction.Mean) : base(weight, reduction)\n {\n }\n\n public override Tensor forward(Tensor input, Tensor target)\n {\n var res = THSNN_binary_cross_entropy(input.Handle, target.Handle, weight?.Handle ?? IntPtr.Zero, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n public sealed class BCEWithLogitsLoss : WeightedLoss<Tensor, Tensor, Tensor>\n {\n public BCEWithLogitsLoss(Tensor? weight = null, Reduction reduction = Reduction.Mean, Tensor? pos_weights = null) : base(weight, reduction)\n {\n this.pos_weights = pos_weights;\n }\n\n public override Tensor forward(Tensor input, Tensor target)\n {\n var res = THSNN_binary_cross_entropy_with_logits(input.Handle, target.Handle, weight?.Handle ?? IntPtr.Zero, (long)reduction, pos_weights?.Handle ?? IntPtr.Zero);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public Tensor? pos_weights { get; }\n }\n\n public sealed class CosineEmbeddingLoss : Loss<Tensor, Tensor, Tensor, Tensor>\n {\n public CosineEmbeddingLoss(double margin = 0.0, Reduction reduction = Reduction.Mean) : base(reduction)\n {\n this.margin = margin;\n }\n\n public override Tensor forward(Tensor input1, Tensor input2, Tensor target)\n {\n var res = THSNN_cosine_embedding_loss(input1.Handle, input2.Handle, target.Handle, margin, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public double margin { get; }\n }\n\n public sealed class CTCLoss : Loss<Tensor, Tensor, Tensor, Tensor, Tensor>\n {\n public CTCLoss(long blank = 0, bool zero_infinity = false, Reduction reduction = Reduction.Mean) : base(reduction)\n {\n this.blank = blank;\n this.zero_infinity = zero_infinity;\n }\n\n public override Tensor forward(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths)\n {\n var res = THSNN_ctc_loss(log_probs.Handle, targets.Handle, input_lengths.Handle, target_lengths.Handle, blank, zero_infinity, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public long blank { get; }\n public bool zero_infinity { get; }\n }\n\n public sealed class HingeEmbeddingLoss : Loss<Tensor, Tensor, Tensor>\n {\n public HingeEmbeddingLoss(double margin = 0.0, Reduction reduction = Reduction.Mean) : base(reduction)\n {\n this.margin = margin;\n }\n\n public override Tensor forward(Tensor input, Tensor target)\n {\n var res = THSNN_hinge_embedding_loss(input.Handle, target.Handle, margin, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public double margin { get; }\n }\n\n public sealed class HuberLoss : Loss<Tensor, Tensor, Tensor>\n {\n public HuberLoss(double delta = 1.0, Reduction reduction = Reduction.Mean) : base(reduction)\n {\n this.delta = delta;\n }\n\n public override Tensor forward(Tensor input, Tensor target)\n {\n var res = THSNN_huber_loss(input.Handle, target.Handle, delta, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public double delta { get; }\n }\n\n public sealed class MarginRankingLoss : Loss<Tensor, Tensor, Tensor, Tensor>\n {\n public MarginRankingLoss(double margin = 0.0, Reduction reduction = Reduction.Mean) : base(reduction)\n {\n this.margin = margin;\n }\n\n public override Tensor forward(Tensor input1, Tensor input2, Tensor target)\n {\n var res = THSNN_margin_ranking_loss(input1.Handle, input2.Handle, target.Handle, margin, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public double margin { get; }\n }\n\n public sealed class MultiLabelMarginLoss : Loss<Tensor, Tensor, Tensor>\n {\n public MultiLabelMarginLoss(Reduction reduction = Reduction.Mean) : base(reduction)\n {\n }\n\n public override Tensor forward(Tensor input, Tensor target)\n {\n var res = THSNN_multilabel_margin_loss(input.Handle, target.Handle, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n public sealed class MultiLabelSoftMarginLoss : WeightedLoss<Tensor, Tensor, Tensor>\n {\n public MultiLabelSoftMarginLoss(Tensor? weight = null, Reduction reduction = Reduction.Mean) : base(weight, reduction)\n {\n }\n\n public override Tensor forward(Tensor input, Tensor target)\n {\n var res = THSNN_multilabel_soft_margin_loss(input.Handle, target.Handle, weight?.Handle ?? IntPtr.Zero, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n public sealed class MultiMarginLoss : WeightedLoss<Tensor, Tensor, Tensor>\n {\n public MultiMarginLoss(int p = 1, double margin = 1.0, Tensor? weight = null, Reduction reduction = Reduction.Mean) : base(weight, reduction)\n {\n this.margin = margin;\n this.p = p;\n }\n\n public override Tensor forward(Tensor input, Tensor target)\n {\n IntPtr h = (weight is null) ? IntPtr.Zero : weight.Handle;\n\n var res = THSNN_multi_margin_loss(input.Handle, target.Handle, p, margin, h, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public double margin { get; }\n public int p { get; }\n }\n\n public sealed class MSELoss : Loss<Tensor, Tensor, Tensor>\n {\n public MSELoss(Reduction reduction = Reduction.Mean) : base(reduction)\n {\n }\n\n public override Tensor forward(Tensor input, Tensor target)\n {\n var res = THSNN_mse_loss(input.Handle, target.Handle, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n public sealed class L1Loss : Loss<Tensor, Tensor, Tensor>\n {\n public L1Loss(Reduction reduction = Reduction.Mean) : base(reduction)\n {\n }\n\n public override Tensor forward(Tensor input, Tensor target)\n {\n var res = THSNN_l1_loss(input.Handle, target.Handle, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n public sealed class NLLLoss : WeightedLoss<Tensor, Tensor, Tensor>\n {\n public NLLLoss(Tensor? weight = null, Reduction reduction = Reduction.Mean) : base(weight, reduction)\n {\n }\n\n public override Tensor forward(Tensor input, Tensor target)\n {\n var res = THSNN_nll_loss(input.Handle, target.Handle, weight?.Handle ?? IntPtr.Zero, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n public sealed class PoissonNLLLoss : Loss<Tensor, Tensor, Tensor>\n {\n public PoissonNLLLoss(bool log_input = true, bool full = false, float eps = 1e-8f, Reduction reduction = Reduction.Mean) : base(reduction)\n {\n this.full = full;\n this.log_input = log_input;\n this.eps = eps;\n }\n\n public override Tensor forward(Tensor input, Tensor target)\n {\n var res = THSNN_poisson_loss(input.Handle, target.Handle, log_input, full, eps, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public bool log_input { get; }\n public bool full { get; }\n public float eps { get; }\n\n }\n\n public sealed class GaussianNLLLoss : Loss<Tensor, Tensor, Tensor, Tensor>\n {\n public GaussianNLLLoss(bool full = false, float eps = 1e-8f, Reduction reduction = Reduction.Mean) : base(reduction)\n {\n this.full = full;\n this.eps = eps;\n }\n\n public override Tensor forward(Tensor input, Tensor target, Tensor variance)\n {\n input = input.view(input.shape[0], -1);\n target = target.view(target.shape[0], -1);\n if (target.shape == input.shape) throw new ArgumentException(\"input and target must have the same shape\");\n\n variance = variance.view(target.shape[0], -1);\n if (variance.shape[1] != input.shape[1] && variance.shape[1] != 1) throw new ArgumentException(\"variance has the wrong shape\");\n\n if ((variance < 0).any().cpu().item<bool>()) throw new ArgumentException(\"variance has negative entry/entries\");\n\n using (var _ = torch.no_grad())\n variance = variance.clamp_min(eps);\n\n var loss = 0.5 * (variance.log() + (input - target).square() / variance).view(input.shape[0], -1).sum(dim: stackalloc long[] { 1 });\n\n if (full) {\n loss = loss + 0.5 * input.shape[1] * MathF.Log(2 * MathF.PI);\n }\n\n return (reduction == Reduction.Mean) ? loss.mean() : (reduction == Reduction.Sum) ? loss.sum() : loss;\n }\n\n public bool full { get; }\n public float eps { get; }\n\n }\n\n public sealed class KLDivLoss : Loss<Tensor, Tensor, Tensor>\n {\n public KLDivLoss(bool log_target = true, Reduction reduction = Reduction.Mean) : base(reduction)\n {\n this.log_target = log_target;\n }\n\n public override Tensor forward(Tensor input, Tensor target)\n {\n var res = THSNN_kl_div_loss(input.Handle, target.Handle, (long)reduction, log_target);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public bool log_target { get; }\n }\n\n public sealed class SmoothL1Loss : Loss<Tensor, Tensor, Tensor>\n {\n public SmoothL1Loss(Reduction reduction = Reduction.Mean, double beta = 1.0) : base(reduction)\n {\n this.beta = beta;\n }\n\n public override Tensor forward(Tensor input, Tensor target)\n {\n var res = THSNN_smooth_l1_loss(input.Handle, target.Handle, (long)reduction, beta);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public double beta { get; }\n }\n\n public sealed class SoftMarginLoss : Loss<Tensor, Tensor, Tensor>\n {\n public SoftMarginLoss(Reduction reduction = Reduction.Mean) : base(reduction)\n {\n }\n\n public override Tensor forward(Tensor input, Tensor target)\n {\n var res = THSNN_soft_margin_loss(input.Handle, target.Handle, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n public sealed class TripletMarginLoss : Loss<Tensor, Tensor, Tensor, Tensor>\n {\n public TripletMarginLoss(double margin = 1.0, long p = 2, double eps = 1e-06, bool swap = false, Reduction reduction = Reduction.Mean) : base(reduction)\n {\n this.margin = margin;\n this.p = p;\n this.eps = eps;\n this.swap = swap;\n }\n\n public override Tensor forward(Tensor anchor, Tensor positive, Tensor negative)\n {\n var res = THSNN_triplet_margin_loss(anchor.Handle, positive.Handle, negative.Handle, margin, p, eps, swap, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public double margin { get; }\n public long p { get; }\n double eps { get; }\n bool swap { get; }\n }\n\n public sealed class TripletMarginWithDistanceLoss : Loss<Tensor, Tensor, Tensor, Tensor>\n {\n public TripletMarginWithDistanceLoss(Func<Tensor, Tensor, Tensor>? distance = null, double margin = 1.0, bool swap = false, Reduction reduction = Reduction.Mean) : base(reduction)\n {\n if (distance != null) {\n this.distance = (IntPtr x, IntPtr y) => {\n var x1 = new Tensor(x);\n var y1 = new Tensor(y);\n var res = distance(x1, y1);\n\n GC.SuppressFinalize(x1);\n GC.SuppressFinalize(y1);\n GC.SuppressFinalize(res);\n\n return res.Handle;\n };\n }\n\n this.margin = margin;\n this.swap = swap;\n }\n\n public override Tensor forward(Tensor anchor, Tensor positive, Tensor negative)\n {\n var res = THSNN_triplet_margin_with_distance_loss(anchor.Handle, positive.Handle, negative.Handle, distance, margin, swap, (long)reduction);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n DistanceFunctionNative? distance { get; }\n public double margin { get; }\n bool swap { get; }\n }\n }\n}\n" }, { "alpha_fraction": 0.5615906715393066, "alphanum_fraction": 0.571774959564209, "avg_line_length": 38.653846740722656, "blob_id": "ecc96a1ede36505931832c95a316d4111d424671", "content_id": "31eee07674fed9f8df8ff36a32f47beb74d70f29", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2062, "license_type": "permissive", "max_line_length": 135, "num_lines": 52, "path": "/src/TorchVision/AdjustHue.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class AdjustHue : ITransform\n {\n internal AdjustHue(double hue_factor)\n {\n hue_factor %= 1.0;\n\n this.hue_factor = hue_factor;\n }\n\n public Tensor call(Tensor img)\n {\n return transforms.functional.adjust_hue(img, hue_factor);\n }\n\n private double hue_factor;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Adjust hue of an image.\n /// The image hue is adjusted by converting the image to HSV and cyclically shifting the intensities in the hue channel(H).\n /// The image is then converted back to original image mode.\n /// </summary>\n /// <param name=\"hue_factor\">\n /// How much to shift the hue channel. 0 means no shift in hue.\n /// Hue is often defined in degrees, with 360 being a full turn on the color wheel.\n /// In this library, 1.0 is a full turn, which means that 0.5 and -0.5 give complete reversal of\n /// the hue channel in HSV space in positive and negative direction respectively.\n /// </param>\n /// <returns></returns>\n /// <remarks>\n /// Unlike Pytorch, TorchSharp will allow the hue_factor to lie outside the range [-0.5,0.5].\n /// A factor of 0.75 has the same effect as -.25\n /// Note that adjusting the hue is a very expensive operation, and may therefore not be suitable as a method\n /// for data augmentation when training speed is important.\n /// </remarks>\n static public ITransform AdjustHue(double hue_factor)\n {\n return new AdjustHue(hue_factor);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5561426877975464, "alphanum_fraction": 0.575957715511322, "avg_line_length": 58.76315689086914, "blob_id": "df780ee75e893b03a70d7e2bd036027c655185c8", "content_id": "020ace0222c83784e3e911a58cf2d52f7c5821d3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2271, "license_type": "permissive", "max_line_length": 160, "num_lines": 38, "path": "/test/TorchSharpTest/netstandardTests.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System.IO;\nusing Xunit;\n\nnamespace TorchSharp\n{\n public class NetStandardTests\n {\n [Theory]\n [InlineData(@\"c:\\users\\me\", @\"middle\", @\"c:\\users\\me\\middle\")]\n [InlineData(@\"c:\\users\\me\", null, @\"c:\\users\\me\")]\n [InlineData(null, @\"last\", @\"last\")]\n [InlineData(@\"c:\\users\\me\", \"\", @\"c:\\users\\me\")]\n [InlineData(\"\", @\"last\", @\"last\")]\n [InlineData(@\"c:\\users\\me\\\", @\"middle\\\", @\"c:\\users\\me\\middle\\\")]\n [InlineData(@\"c:\\users\\me\", @\"\\middle\\\", @\"c:\\users\\me\\middle\\\")]\n public static void TestNSPath2Parts(string s1, string s2, string expected) => Assert.Equal(expected, NSPath.Join(s1, s2));\n\n [Theory]\n [InlineData(@\"c:\\users\\me\", @\"middle\", @\"last\", @\"c:\\users\\me\\middle\\last\")]\n [InlineData(null, @\"middle\", @\"last\", @\"middle\\last\")]\n [InlineData(@\"c:\\users\\me\", null, @\"last\", @\"c:\\users\\me\\last\")]\n [InlineData(@\"c:\\users\\me\", @\"middle\", null, @\"c:\\users\\me\\middle\")]\n [InlineData(@\"c:\\users\\me\\\", @\"middle\", @\"last\", @\"c:\\users\\me\\middle\\last\")]\n [InlineData(@\"c:\\users\\me\", @\"\\middle\\\", @\"last\", @\"c:\\users\\me\\middle\\last\")]\n [InlineData(@\"c:\\users\\me\", @\"\\middle\", @\"\\last\", @\"c:\\users\\me\\middle\\last\")]\n public static void TestNSPath3Parts(string s1, string s2, string s3, string expected) => Assert.Equal(expected, NSPath.Join(s1, s2, s3));\n\n [Theory]\n [InlineData(@\"c:\\users\\me\", @\"middle1\", @\"middle2\", @\"last\", @\"c:\\users\\me\\middle1\\middle2\\last\")]\n [InlineData(null, @\"middle1\", @\"middle2\", @\"last\", @\"middle1\\middle2\\last\")]\n [InlineData(@\"c:\\users\\me\", null, @\"middle2\", @\"last\", @\"c:\\users\\me\\middle2\\last\")]\n [InlineData(@\"c:\\users\\me\", @\"middle1\", null, @\"last\", @\"c:\\users\\me\\middle1\\last\")]\n [InlineData(@\"c:\\users\\me\", @\"middle1\", @\"middle2\", null, @\"c:\\users\\me\\middle1\\middle2\")]\n [InlineData(@\"c:\\users\\me\\\", @\"middle1\\\", @\"middle2\\\", @\"last\", @\"c:\\users\\me\\middle1\\middle2\\last\")]\n [InlineData(@\"c:\\users\\me\", @\"\\middle1\", @\"\\middle2\", @\"\\last\", @\"c:\\users\\me\\middle1\\middle2\\last\")]\n public static void TestNSPath4Parts(string s1, string s2, string s3, string s4, string expected) => Assert.Equal(expected, NSPath.Join(s1, s2, s3, s4));\n }\n}\n" }, { "alpha_fraction": 0.5096489191055298, "alphanum_fraction": 0.5152289867401123, "avg_line_length": 32.34108352661133, "blob_id": "93365016f0dbdb79ada3eaf47eb318e8dbe5fa4f", "content_id": "10c75c4193ca580119512807d978b587dd5cedde", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4301, "license_type": "permissive", "max_line_length": 149, "num_lines": 129, "path": "/src/Examples.Utils/AG_NEWSReader.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing TorchSharp;\nusing static TorchSharp.torch;\n\nnamespace TorchText.Data\n{\n public class AG_NEWSReader : IDisposable\n {\n public static AG_NEWSReader AG_NEWS(string split, Device device, string root = \".data\")\n {\n var dataPath = Path.Combine(root, $\"{split}.csv\");\n return new AG_NEWSReader(dataPath, device);\n }\n\n private AG_NEWSReader(string path, Device device)\n {\n _path = path;\n _device = device;\n }\n\n private string _path;\n private Device _device;\n\n public IEnumerable<(int, string)> Enumerate()\n {\n return File.ReadLines(_path).Select(line => ParseLine(line));\n }\n\n public IEnumerable<(Tensor, Tensor, Tensor)> GetBatches(Func<string, IEnumerable<string>> tokenizer, Vocab.Vocab vocab, long batch_size)\n {\n // This data set fits in memory, so we will simply load it all and cache it between epochs.\n\n var inputs = new List<(int, string)>();\n\n if (_data == null) {\n\n _data = new List<(Tensor, Tensor, Tensor)>();\n\n var counter = 0;\n var lines = Enumerate().ToList();\n var left = lines.Count;\n\n foreach (var line in lines) {\n\n inputs.Add(line);\n left -= 1;\n\n if (++counter == batch_size || left == 0) {\n _data.Add(Batchifier(inputs, tokenizer, vocab));\n inputs.Clear();\n counter = 0;\n }\n }\n }\n\n return _data;\n }\n\n private List<(Tensor, Tensor, Tensor)> _data;\n private bool disposedValue;\n\n private (Tensor, Tensor, Tensor) Batchifier(IEnumerable<(int, string)> input, Func<string, IEnumerable<string>> tokenizer, Vocab.Vocab vocab)\n {\n var label_list = new List<long>();\n var text_list = new List<Tensor>();\n var offsets = new List<long>();\n offsets.Add(0);\n\n long last = 0;\n\n foreach (var (label, text) in input) {\n label_list.Add(label);\n var processed_text = torch.tensor(tokenizer(text).Select(t => (long)vocab[t]).ToArray(),dtype:torch.int64);\n text_list.Add(processed_text);\n last += processed_text.size(0);\n offsets.Add(last);\n }\n\n var labels = torch.tensor(label_list.ToArray(), dtype: torch.int64).to(_device);\n var texts = torch.cat(text_list.ToArray(), 0).to(_device);\n var offs = torch.tensor(offsets.Take(label_list.Count).ToArray(), dtype:torch.int64).to(_device);\n\n return (labels, texts, offs);\n }\n\n public (int, string) ParseLine(string line)\n {\n int label = 0;\n string text = \"\";\n\n int firstComma = line.IndexOf(\"\\\",\\\"\");\n label = int.Parse(line.Substring(1, firstComma - 1));\n text = line.Substring(firstComma + 2, line.Length - firstComma - 2);\n int secondComma = text.IndexOf(\"\\\",\\\"\");\n text = text.Substring(secondComma + 2, text.Length - secondComma - 2);\n int thirdComma = text.IndexOf(\"\\\",\\\"\");\n\n text = text.Substring(thirdComma + 2, text.Length - thirdComma - 3);\n\n return (label-1, text);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (!disposedValue) {\n if (disposing && _data != null) {\n foreach (var (l, t, o) in _data) {\n l.Dispose();\n t.Dispose();\n o.Dispose();\n }\n }\n\n disposedValue = true;\n }\n }\n\n public void Dispose()\n {\n // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method\n Dispose(disposing: true);\n GC.SuppressFinalize(this);\n }\n }\n}\n" }, { "alpha_fraction": 0.5693780183792114, "alphanum_fraction": 0.5707602500915527, "avg_line_length": 48.24083709716797, "blob_id": "418b89fe66b2b9b3777dcd551b37920de68895c7", "content_id": "750f8ebc1a36ab048ab363cec490dcf4d2c2b950", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9405, "license_type": "permissive", "max_line_length": 156, "num_lines": 191, "path": "/src/TorchSharp/Distributions/NegativeBinomial.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn.functional;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// A NegativeBinomial distribution parameterized by total_count and either probs or logits (but not both).\n ///\n /// This is a distribution of the number of successful independent and identical Bernoulli trials\n /// before `total_count` failures are achieved. The probability of success of each Bernoulli trial is `probs`.\n /// </summary>\n public class NegativeBinomial : torch.distributions.Distribution\n {\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public override Tensor mean => total_count * torch.exp(logits);\n\n /// <summary>\n /// Mode of the negative binomial distribution.\n /// </summary>\n public override Tensor mode =>\n WrappedTensorDisposeScope(() => ((total_count - 1) * logits.exp()).floor_().clamp(min: 0));\n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public override Tensor variance =>\n WrappedTensorDisposeScope(() => mean / torch.sigmoid(-logits));\n\n public NegativeBinomial(Tensor total_count, Tensor p = null, Tensor l = null, torch.Generator generator = null) : base(generator)\n {\n this.batch_shape = p is null ? l.size() : p.size();\n this._probs = p ?? LogitsToProbs(l, true).DetachFromDisposeScope();\n this._logits = l ?? ProbsToLogits(p, true).DetachFromDisposeScope();\n this.generator = generator;\n\n var broadcast = (p is null) ? torch.broadcast_tensors(total_count, l) : torch.broadcast_tensors(total_count, p);\n this.total_count = broadcast[0].type_as(p ?? l).DetachFromDisposeScope();\n }\n\n /// <summary>\n /// Event probabilities\n /// </summary>\n public Tensor probs {\n get {\n return _probs;\n }\n }\n\n /// <summary>\n /// Event log-odds\n /// </summary>\n public Tensor logits {\n get {\n return _logits;\n }\n }\n\n private Tensor _probs;\n private Tensor _logits;\n private Tensor total_count;\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n public override Tensor rsample(params long[] sample_shape)\n {\n using var scope = NewDisposeScope();\n using (var _ = torch.no_grad()) {\n var gamma = distributions.Gamma(concentration:total_count, rate: torch.exp(-_logits));\n var rate = gamma.sample(sample_shape);\n return torch.poisson(rate, generator).MoveToOuterDisposeScope();\n }\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor log_prob(Tensor value)\n {\n using var _ = NewDisposeScope();\n var log_unnormalized_prob = (total_count * (-_logits).log_sigmoid() + value * logits.log_sigmoid());\n var log_normalization = (-torch.lgamma(total_count + value) + torch.lgamma(1.0 + value) + torch.lgamma(total_count));\n log_normalization = log_normalization.masked_fill(total_count + value == 0, 0);\n\n return (log_unnormalized_prob - log_normalization).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n public override Tensor entropy()\n {\n throw new NotImplementedException(nameof(entropy));\n }\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is NegativeBinomial))\n throw new ArgumentException(\"expand(): 'instance' must be a NegativeBinomial distribution\");\n\n var newDistribution = ((instance == null) ?\n new NegativeBinomial(total_count.expand(batch_shape), p: _probs?.expand(batch_shape), l: logits?.expand(batch_shape), generator) :\n instance) as NegativeBinomial;\n\n newDistribution.batch_shape = batch_shape;\n if (newDistribution == instance) {\n newDistribution.total_count = total_count.expand(batch_shape);\n newDistribution._probs = _probs?.expand(batch_shape);\n newDistribution._logits = _logits?.expand(batch_shape);\n }\n return newDistribution;\n }\n }\n\n }\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a NegativeBinomial distribution parameterized by `probs` or `logits` (but not both).\n /// `total_count` must be broadcastable with `probs`/`logits`.\n /// </summary>\n /// <param name=\"total_count\">Number of Bernoulli trials</param>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static NegativeBinomial NegativeBinomial(Tensor total_count, Tensor probs = null, Tensor logits = null, torch.Generator generator = null)\n {\n return new NegativeBinomial(total_count, probs, logits);\n }\n\n /// <summary>\n /// Creates a NegativeBinomial distribution parameterized by `probs` or `logits` (but not both).\n /// </summary>\n /// <param name=\"total_count\">Number of Bernoulli trials</param>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static NegativeBinomial NegativeBinomial(int total_count, float? probs, float? logits, torch.Generator generator = null)\n {\n if (probs.HasValue && !logits.HasValue)\n return new NegativeBinomial(torch.tensor(total_count), torch.tensor(probs.Value), null);\n else if (!probs.HasValue && logits.HasValue)\n return new NegativeBinomial(torch.tensor(total_count), null, torch.tensor(logits.Value));\n else\n throw new ArgumentException(\"One and only one of 'probs' and logits should be provided.\");\n }\n\n\n /// <summary>\n /// Creates a NegativeBinomial distribution parameterized by `probs` or `logits` (but not both).\n /// </summary>\n /// <param name=\"total_count\">Number of Bernoulli trials</param>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static NegativeBinomial NegativeBinomial(int total_count, double? probs, double? logits, torch.Generator generator = null)\n {\n if (probs.HasValue && !logits.HasValue)\n return new NegativeBinomial(torch.tensor(total_count), torch.tensor(probs.Value), null, generator);\n else if (!probs.HasValue && logits.HasValue)\n return new NegativeBinomial(torch.tensor(total_count), null, torch.tensor(logits.Value), generator);\n else\n throw new ArgumentException(\"One and only one of 'probs' and logits should be provided.\");\n }\n\n }\n }\n}\n" }, { "alpha_fraction": 0.5229358077049255, "alphanum_fraction": 0.5275229215621948, "avg_line_length": 15.769230842590332, "blob_id": "a1c0eb9defdf9b7a8cdaa900f081fd45b5cec240", "content_id": "1917bda876596786b466ed006d6d1cc7b600558b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 218, "license_type": "permissive", "max_line_length": 44, "num_lines": 13, "path": "/src/TorchSharp/Utils/tensorboard/Enums/HistogramBinSelector.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "namespace TorchSharp.Utils.tensorboard.Enums\n{\n public enum HistogramBinSelector : byte\n {\n Doane = 0,\n Rice,\n Scott,\n Sqrt,\n Stone,\n Sturges,\n Tensorflow\n }\n}\n" }, { "alpha_fraction": 0.5300502777099609, "alphanum_fraction": 0.5330653190612793, "avg_line_length": 38.79999923706055, "blob_id": "e82238826a2b03c1c547988fc25fc4909895cdca", "content_id": "b4c2f030ee85ace47dd110d5d4f47ce4c538c8ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4975, "license_type": "permissive", "max_line_length": 144, "num_lines": 125, "path": "/src/TorchSharp/Device.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n /// <summary>\n /// A torch.Device is an object representing the device on which a torch.Tensor is or will be allocated.\n /// </summary>\n public class Device\n {\n public DeviceType type { get; private set; } = DeviceType.CPU;\n public int index { get; private set; } = -1;\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"description\">A device descriptor 'device[:index]'</param>\n public Device(string description)\n {\n var splits = description.Split(':');\n if (splits.Length == 1) {\n // Interpret as a device type\n type = (DeviceType)Enum.Parse(typeof(DeviceType), splits[0].ToUpper());\n } else if (splits.Length == 2) {\n // Interpret as a device type and index\n type = (DeviceType)Enum.Parse(typeof(DeviceType), splits[0].ToUpper());\n index = int.Parse(splits[1]);\n }\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"deviceType\">CPU or CUDA</param>\n /// <param name=\"index\">For CUDA, the device index</param>\n public Device(string deviceType, int index = -1)\n {\n type = (DeviceType)Enum.Parse(typeof(DeviceType), deviceType.ToUpper());\n this.index = index;\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"deviceType\">CPU or CUDA</param>\n /// <param name=\"index\">For CUDA, the device index</param>\n public Device(DeviceType deviceType, int index = -1)\n {\n type = deviceType;\n this.index = index;\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"index\">The CUDA device index</param>\n public Device(int index)\n {\n type = DeviceType.CUDA;\n this.index = index;\n }\n\n /// <summary>\n /// Return the device descriptor using the input format.\n /// </summary>\n /// <returns></returns>\n public override string ToString()\n {\n return type == DeviceType.CPU ? \"cpu\" : (index == -1) ? $\"{type.ToString().ToLower()}\" : $\"{type.ToString().ToLower()}:{index}\";\n }\n\n public static implicit operator Device(string description)\n {\n return new Device(description);\n }\n }\n\n /// <summary>\n /// Convenience declaration of a CPU device accessible everywhere.\n /// </summary>\n public static Device CPU = new Device(DeviceType.CPU, -1);\n\n /// <summary>\n /// Convenience declaration of a CUDA device accessible everywhere.\n /// </summary>\n public static Device CUDA = new Device(DeviceType.CUDA, -1);\n\n /// <summary>\n /// Convenience declaration of a META device accessible everywhere.\n /// </summary>\n public static Device META = new Device(DeviceType.META, -1);\n\n /// <summary>\n /// Factory for a device object, following the Pytorch API.\n /// </summary>\n /// <param name=\"description\">String description of the device, e.g. 'cpu' or 'cuda:0'</param>\n /// <returns></returns>\n public static Device device(string description) => new Device(description);\n\n /// <summary>\n /// Factory for a device object, following the Pytorch API.\n /// </summary>\n /// <param name=\"deviceType\">The device type, e.g. 'cpu' or 'cuda'</param>\n /// <param name=\"index\">The device index. Ignored for CPUs</param>\n /// <returns></returns>\n public static Device device(string deviceType, int index = -1) => new Device(deviceType, index);\n\n /// <summary>\n /// Factory for a device object, following the Pytorch API.\n /// </summary>\n /// <param name=\"deviceType\">The device type, e.g. DeviceType.CPU or DeviceType.CUDA.</param>\n /// <param name=\"index\">The device index. Ignored for CPUs</param>\n /// <returns></returns>\n public static Device device(DeviceType deviceType, int index = -1) => new Device(deviceType, index);\n\n /// <summary>\n /// Factory for a CUDA device object, following the Pytorch API.\n /// </summary>\n /// <param name=\"index\">The CUDA device ordinal.</param>\n /// <returns></returns>\n public static Device device(int index) => new Device(DeviceType.CUDA, index);\n }\n}\n" }, { "alpha_fraction": 0.5669390559196472, "alphanum_fraction": 0.5686675310134888, "avg_line_length": 45.79411697387695, "blob_id": "711085ff192d874631e58f284a7d7635b57e6909", "content_id": "63a03c1790e18930c639520ec1f8093df3f9c6ab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6364, "license_type": "permissive", "max_line_length": 156, "num_lines": 136, "path": "/src/TorchSharp/Distributions/Cauchy.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// A Cauchy (Lorentz) distribution. The distribution of the ratio of\n /// independent normally distributed random variables with means `0` follows a Cauchy distribution.\n /// </summary>\n public class Cauchy : torch.distributions.Distribution\n {\n /// <summary>\n /// The mode of the distribution.\n /// </summary>\n public override Tensor mode => loc;\n\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public override Tensor mean => _mean;\n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public override Tensor variance => _variance;\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"loc\">Mode or median of the distribution.</param>\n /// <param name=\"scale\">Half width at half maximum.</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n public Cauchy(Tensor loc, Tensor scale, torch.Generator generator = null) : base(generator)\n {\n var locScale = torch.broadcast_tensors(loc, scale);\n this.loc = locScale[0].DetachFromDisposeScope();\n this.scale = locScale[1].DetachFromDisposeScope();\n this._mean = torch.full(ExtendedShape(), double.NaN, dtype: loc.dtype, device: loc.device).DetachFromDisposeScope();\n this._variance = torch.full(ExtendedShape(), double.PositiveInfinity, dtype: loc.dtype, device: loc.device).DetachFromDisposeScope();\n this.batch_shape = this.loc.size();\n }\n\n private Tensor loc;\n private Tensor scale;\n private Tensor _mean, _variance;\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n /// <returns></returns>\n public override Tensor rsample(params long[] sample_shape)\n {\n var shape = ExtendedShape(sample_shape);\n var eps = loc.new_empty(shape).cauchy_(generator: generator);\n return loc + eps * scale;\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor log_prob(Tensor value) =>\n WrappedTensorDisposeScope(() => -Math.Log(Math.PI) - scale.log() - (((value - loc) / scale).pow(2)).log1p()); \n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n /// <returns></returns>\n public override Tensor entropy() =>\n WrappedTensorDisposeScope(() => Math.Log(Math.PI * 4) + scale.log());\n\n /// <summary>\n /// Returns the cumulative density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor cdf(Tensor value) =>\n WrappedTensorDisposeScope(() => torch.atan((value - loc) / scale) / Math.PI + 0.5);\n\n /// <summary>\n /// Returns the inverse cumulative density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor icdf(Tensor value) =>\n WrappedTensorDisposeScope(() => torch.tan(Math.PI * (value - 0.5)) * scale + loc);\n\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is Cauchy))\n throw new ArgumentException(\"expand(): 'instance' must be a Cauchy distribution\");\n\n var newDistribution = ((instance == null) ? new Cauchy(loc.expand(batch_shape), scale.expand(batch_shape), generator) : instance) as Cauchy;\n\n newDistribution.batch_shape = batch_shape;\n if (newDistribution == instance) {\n newDistribution.loc = loc.expand(batch_shape);\n newDistribution.scale = scale.expand(batch_shape);\n }\n return newDistribution;\n }\n }\n\n }\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Samples from a Cauchy (Lorentz) distribution. The distribution of the ratio of\n /// independent normally distributed random variables with means `0` follows a Cauchy distribution.\n /// </summary>\n /// <param name=\"loc\">Mode or median of the distribution.</param>\n /// <param name=\"scale\">Half width at half maximum.</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Cauchy Cauchy(Tensor loc, Tensor scale, torch.Generator generator = null)\n {\n return new Cauchy(loc, scale, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5930420756340027, "alphanum_fraction": 0.5930420756340027, "avg_line_length": 49.79452133178711, "blob_id": "3dcc95d41e74123530e4794bbb5b6165845dd10d", "content_id": "620b8ac555def849e73efe782e978ca56a5db584", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3708, "license_type": "permissive", "max_line_length": 188, "num_lines": 73, "path": "/src/TorchSharp/NN/TransformerDecoder.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n public sealed class TransformerDecoder : torch.nn.Module<Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor>\n {\n internal TransformerDecoder(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n /// <summary>\n /// Pass the inputs (and mask) through the decoder layers in turn.\n /// </summary>\n /// <param name=\"tgt\">The sequence to the decoder layer (required).</param>\n /// <param name=\"memory\">The sequence from the last layer of the encoder (required).</param>\n /// <param name=\"tgt_mask\">The mask for the tgt sequence (optional).</param>\n /// <param name=\"memory_mask\">The mask for the memory sequence (optional).</param>\n /// <param name=\"tgt_key_padding_mask\">The mask for the tgt keys per batch (optional).</param>\n /// <param name=\"memory_key_padding_mask\">The mask for the memory keys per batch (optional).</param>\n /// <returns></returns>\n public override Tensor forward(Tensor tgt, Tensor memory, Tensor tgt_mask, Tensor memory_mask = null, Tensor tgt_key_padding_mask = null, Tensor memory_key_padding_mask = null)\n {\n var res = THSNN_TransformerDecoder_forward(handle,\n tgt.Handle,\n memory.Handle,\n tgt_mask?.Handle ?? IntPtr.Zero,\n memory_mask?.Handle ?? IntPtr.Zero,\n tgt_key_padding_mask?.Handle ?? IntPtr.Zero,\n memory_key_padding_mask?.Handle ?? IntPtr.Zero);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n public new Tensor call(Tensor tgt, Tensor memory, Tensor tgt_mask, Tensor memory_mask = null, Tensor tgt_key_padding_mask = null, Tensor memory_key_padding_mask = null)\n {\n return base.call(tgt, memory, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask);\n }\n\n /// <summary>\n /// Pass the inputs (and mask) through the decoder layers in turn.\n /// </summary>\n /// <param name=\"tgt\">The sequence to the decoder layer (required).</param>\n /// <param name=\"memory\">The sequence from the last layer of the encoder (required).</param>\n public Tensor call(Tensor tgt, Tensor memory)\n {\n return base.call(tgt, memory, null, null, null, null);\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// TransformerDecoder is a stack of N decoder layers\n /// </summary>\n /// <param name=\"decoder_layer\">An instance of the TransformerDecoderLayer class (required).</param>\n /// <param name=\"num_layers\">The number of sub-decoder-layers in the decoder (required).</param>\n /// <returns></returns>\n public static TransformerDecoder TransformerDecoder(TransformerDecoderLayer decoder_layer, long num_layers)\n {\n var res = THSNN_TransformerDecoder_ctor(decoder_layer.handle, num_layers, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new TransformerDecoder(res, boxedHandle);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6298515200614929, "alphanum_fraction": 0.6306329965591431, "avg_line_length": 57.181819915771484, "blob_id": "09a53f021f44c8559b840de351fee80d12dc393a", "content_id": "c5b3ae593b7ef653a6554acb2d222fb153d09f60", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3839, "license_type": "permissive", "max_line_length": 288, "num_lines": 66, "path": "/src/TorchVision/RandomRotation.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class RandomRotation : ITransform\n {\n public RandomRotation((double, double) degrees, InterpolationMode interpolation = InterpolationMode.Nearest, bool expand = false, (int, int)? center = null, IList<float> fill = null)\n {\n this.degrees = degrees;\n this.interpolation = interpolation;\n this.center = center;\n this.expand = expand;\n this.fill = fill;\n }\n\n public Tensor call(Tensor input)\n {\n var random = new Random();\n var angle = random.NextDouble() * (degrees.Item2 - degrees.Item1) + degrees.Item1;\n\n var rotate = torchvision.transforms.Rotate((float)angle, interpolation, expand, center, fill);\n return rotate.call(input);\n }\n\n private (double, double) degrees;\n private bool expand;\n private (int, int)? center;\n private IList<float> fill;\n private InterpolationMode interpolation;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Rotate the image by a random angle. \n /// </summary>\n /// <param name=\"degrees\">Range of degrees to select from (-degrees, +degrees).</param>\n /// <param name=\"interpolation\">Desired interpolation enum. Default is `InterpolationMode.NEAREST`.</param>\n /// <param name=\"expand\">If true, expands the output to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation.</param>\n /// <param name=\"center\">Center of rotation, (x, y). Origin is the upper left corner.</param>\n /// <param name=\"fill\">Pixel fill value for the area outside the rotated. If given a number, the value is used for all bands respectively.</param>\n static public ITransform RandomRotation(double degrees, InterpolationMode interpolation = InterpolationMode.Nearest, bool expand = false, (int, int)? center = null, IList<float> fill = null)\n {\n return new RandomRotation((-degrees, degrees), interpolation, expand, center, fill);\n }\n\n /// <summary>\n ///Rotate the image by a random angle. \n /// </summary>\n /// <param name=\"degrees\">Range of degrees to select from</param>\n /// <param name=\"interpolation\">Desired interpolation enum. Default is `InterpolationMode.NEAREST`.</param>\n /// <param name=\"expand\">If true, expands the output to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation.</param>\n /// <param name=\"center\">Center of rotation, (x, y). Origin is the upper left corner.</param>\n /// <param name=\"fill\">Pixel fill value for the area outside the rotated. If given a number, the value is used for all bands respectively.</param>\n static public ITransform RandomRotation((double, double) degrees, InterpolationMode interpolation = InterpolationMode.Nearest, bool expand = false, (int, int)? center = null, IList<float> fill = null)\n {\n return new RandomRotation(degrees, interpolation, expand, center, fill);\n }\n }\n }\n}" }, { "alpha_fraction": 0.6136853694915771, "alphanum_fraction": 0.62109375, "avg_line_length": 50.55555725097656, "blob_id": "f802ca6420e5fcff10309b248ea52e530ad9e644", "content_id": "31ad430b51ad7a021554cd667c9f57227d0f7df0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7424, "license_type": "permissive", "max_line_length": 215, "num_lines": 144, "path": "/src/TorchSharp/Tensor/Factories/tensor_long.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torch\n {\n /// <summary>\n /// Create a scalar tensor from a single value\n /// </summary>\n public static Tensor tensor(long scalar, ScalarType? dtype = null, Device? device = null, bool requires_grad = false)\n {\n device = InitializeDevice(device);\n var handle = THSTensor_newInt64Scalar(scalar, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n var tensor = new Tensor(handle);\n if (device is { }) {\n tensor = dtype.HasValue ? tensor.to(dtype.Value, device) : tensor.to(device);\n } else if (dtype.HasValue) {\n tensor = tensor.to_type(dtype.Value);\n }\n return tensor;\n }\n\n /// <summary>\n /// Create a tensor from an array of values, shaping it based on the shape passed in.\n /// </summary>\n [Pure]\n public static Tensor tensor(IList<long> rawArray, ReadOnlySpan<long> dimensions, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _tensor_i64(rawArray.ToArray(), dimensions, dtype, device, requires_grad, false, names);\n }\n\n /// <summary>\n /// Create a tensor from an array of values, shaping it based on the shape passed in.\n /// </summary>\n [Pure]\n public static Tensor tensor(long[] dataArray, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _tensor_i64(dataArray, stackalloc long[] { dataArray.LongLength }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a tensor from an array of values, shaping it based on the shape passed in.\n /// </summary>\n [Pure]\n public static Tensor tensor(long[] dataArray, ReadOnlySpan<long> dimensions, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _tensor_i64(dataArray, dimensions, dtype, device, requires_grad, names: names);\n }\n\n [Pure]\n private static Tensor _tensor_i64(Array rawArray, ReadOnlySpan<long> dimensions, ScalarType? dtype, Device? device, bool requires_grad, bool clone = false, string[]? names = null) =>\n _tensor_generic(rawArray, dimensions, (sbyte)ScalarType.Int64, dtype, device, requires_grad, names: names);\n\n /// <summary>\n /// Create a 1-D tensor from an array of values, shaping it based on the input array.\n /// </summary>\n /// <remarks>The Torch runtime does not take ownership of the data, so there is no device argument.</remarks>\n [Pure]\n public static Tensor tensor(IList<long> rawArray, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return tensor(rawArray, stackalloc long[] { (long)rawArray.Count }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a tensor from an array of values, organizing it as a two-dimensional tensor.\n /// </summary>\n /// <remarks>\n /// The Torch runtime does not take ownership of the data, so there is no device argument.\n /// The input array must have rows * columns elements.\n /// </remarks>\n [Pure]\n public static Tensor tensor(IList<long> rawArray, long rows, long columns, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return tensor(rawArray, stackalloc long[] { rows, columns }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a tensor from an array of values, organizing it as a three-dimensional tensor.\n /// </summary>\n /// <remarks>\n /// The Torch runtime does not take ownership of the data, so there is no device argument.\n /// The input array must have dim0*dim1*dim2 elements.\n /// </remarks>\n [Pure]\n public static Tensor tensor(IList<long> rawArray, long dim0, long dim1, long dim2, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return tensor(rawArray, stackalloc long[] { dim0, dim1, dim2 }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a tensor from an array of values, organizing it as a four-dimensional tensor.\n /// </summary>\n /// <remarks>\n /// The Torch runtime does not take ownership of the data, so there is no device argument.\n /// The input array must have dim0*dim1*dim2*dim3 elements.\n /// </remarks>\n [Pure]\n public static Tensor tensor(IList<long> rawArray, long dim0, long dim1, long dim2, long dim3, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return tensor(rawArray, stackalloc long[] { dim0, dim1, dim2, dim3 }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a two-dimensional tensor from a two-dimensional array of values.\n /// </summary>\n [Pure]\n public static Tensor tensor(long[,] rawArray, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _tensor_i64(rawArray, stackalloc long[] { rawArray.GetLongLength(0), rawArray.GetLongLength(1) }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a three-dimensional tensor from a three-dimensional array of values.\n /// </summary>\n [Pure]\n public static Tensor tensor(long[,,] rawArray, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _tensor_i64(rawArray, stackalloc long[] { rawArray.GetLongLength(0), rawArray.GetLongLength(1), rawArray.GetLongLength(2) }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a four-dimensional tensor from a four-dimensional array of values.\n /// </summary>\n [Pure]\n public static Tensor tensor(long[,,,] rawArray, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _tensor_i64(rawArray, stackalloc long[] { rawArray.GetLongLength(0), rawArray.GetLongLength(1), rawArray.GetLongLength(2), rawArray.GetLongLength(3) }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Cast a tensor to a 64-bit integer tensor.\n /// </summary>\n /// <param name=\"t\">The input tensor</param>\n /// <returns>'this' if the tensor is already a 64-bit integer tensor; otherwise, a new tensor.</returns>\n public static Tensor LongTensor(Tensor t) => t.to(ScalarType.Int64);\n }\n}\n" }, { "alpha_fraction": 0.5257009267807007, "alphanum_fraction": 0.5257009267807007, "avg_line_length": 22.83333396911621, "blob_id": "5a5330876f07ec5050be2ce1027629e6d0fefd45", "content_id": "729959af11ba810ecedfb8f4c9fecfc6cdf9b2ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 428, "license_type": "permissive", "max_line_length": 130, "num_lines": 18, "path": "/src/TorchAudio/AudioEncoding.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n /// <summary>\n /// Audio encoding\n /// </summary>\n public enum AudioEncoding\n {\n PCM_S,\n PCM_U,\n PCM_F,\n ULAW,\n ALAW\n }\n }\n}" }, { "alpha_fraction": 0.6038913130760193, "alphanum_fraction": 0.6116005778312683, "avg_line_length": 44.400001525878906, "blob_id": "c70c03e698bd8ffb8d2b36a6c5a308756f1f2acc", "content_id": "d602ee499aaf0c25244b56b361ecf87b1047d2bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5448, "license_type": "permissive", "max_line_length": 130, "num_lines": 120, "path": "/src/TorchAudio/Modules/Wav2Vec2Model.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchaudio,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/audio/blob/76fca37ac8941b72a509a6e58d623632efe04543/torchaudio/models/wav2vec2/model.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/audio/blob/main/LICENSE\n//\n\nusing static TorchSharp.torch;\n\n#nullable enable\nnamespace TorchSharp.Modules\n{\n /// <summary>\n /// Encoder model used in *wav2vec 2.0* [:footcite:`baevski2020wav2vec`].\n /// Note:\n /// To build the model, please use one of the factory functions.\n /// </summary>\n public partial class Wav2Vec2Model : nn.Module<Tensor, Tensor?, (Tensor, Tensor?)>\n {\n internal readonly FeatureExtractor feature_extractor;\n internal readonly Encoder encoder;\n private readonly nn.Module<Tensor, Tensor>? aux;\n\n /// <param name=\"name\"></param>\n /// <param name=\"feature_extractor\">Feature extractor that extracts feature vectors from raw audio Tensor.</param>\n /// <param name=\"encoder\">Encoder that converts the audio features into the sequence of probability\n /// distribution (in negative log-likelihood) over labels.</param>\n /// <param name=\"aux\">Auxiliary module. If provided, the output from encoder is passed to this module.</param>\n internal Wav2Vec2Model(\n string name,\n FeatureExtractor feature_extractor,\n Encoder encoder,\n nn.Module<Tensor, Tensor>? aux = null) : base(name)\n {\n this.feature_extractor = feature_extractor;\n this.encoder = encoder;\n this.aux = aux;\n RegisterComponents();\n }\n\n /// <summary>\n /// Extract feature vectors from raw waveforms\n /// \n /// This returns the list of outputs from the intermediate layers of\n /// transformer block in encoder.\n /// </summary>\n /// <param name=\"waveforms\">Audio tensor of shape `(batch, frames)`.</param>\n /// <param name=\"lengths\">Indicates the valid length of each audio in the batch.\n /// Shape: `(batch, )`.\n /// When the ``waveforms`` contains audios with different durations,\n /// by providing ``lengths`` argument, the model will compute\n /// the corresponding valid output lengths and apply proper mask in\n /// transformer attention layer.\n /// If ``None``, it is assumed that the entire audio waveform\n /// length is valid.</param>\n /// <param name=\"num_layers\">\n /// If given, limit the number of intermediate layers to go through.\n /// Providing `1` will stop the computation after going through one\n /// intermediate layers. If not given, the outputs from all the\n /// intermediate layers are returned.\n /// </param>\n /// <returns>\n /// List of Tensors\n /// Features from requested layers.\n /// Each Tensor is of shape: `(batch, time frame, feature dimension)`\n /// If ``lengths`` argument was provided, a Tensor of shape `(batch, )`\n /// is returned.\n /// It indicates the valid length in time axis of each feature Tensor.\n /// </returns>\n public (Tensor[], Tensor?) extract_features(\n Tensor waveforms,\n Tensor? lengths = null,\n int? num_layers = null)\n {\n Tensor x;\n (x, lengths) = this.feature_extractor.call(waveforms, lengths);\n var xs = this.encoder.extract_features(x, lengths, num_layers);\n return (xs, lengths);\n }\n\n /// <summary>\n /// Compute the sequence of probability distribution over labels.\n /// </summary>\n /// <param name=\"waveforms\">Audio tensor of shape `(batch, frames)`.\n /// waveforms (Tensor): Audio tensor of shape `(batch, frames)`.</param>\n /// <param name=\"lengths\">Indicates the valid length of each audio in the batch.\n /// Shape: `(batch, )`.\n /// When the ``waveforms`` contains audios with different durations,\n /// by providing ``lengths`` argument, the model will compute\n /// the corresponding valid output lengths and apply proper mask in\n /// transformer attention layer.\n /// If ``None``, it is assumed that all the audio in ``waveforms``\n /// have valid length. Default: ``None``.</param>\n /// <returns>\n /// The sequences of probability distribution (in logit) over labels.\n /// If ``lengths`` argument was provided, a Tensor of shape `(batch, )`\n /// is returned.\n /// It indicates the valid length in time axis of the output Tensor.\n /// </returns>\n public override (Tensor, Tensor?) forward(\n Tensor waveforms,\n Tensor? lengths = null)\n {\n Tensor x;\n (x, lengths) = this.feature_extractor.call(waveforms, lengths);\n x = this.encoder.call(x, lengths);\n if (this.aux != null) {\n x = this.aux.call(x);\n }\n return (x, lengths);\n }\n\n public new (Tensor, Tensor?) call(Tensor waveforms, Tensor? lengths = null) => base.call(waveforms, lengths);\n }\n}\n" }, { "alpha_fraction": 0.7279344797134399, "alphanum_fraction": 0.7388535141944885, "avg_line_length": 32.33333206176758, "blob_id": "b261bb4756fe03993c0b2cc038edac62327de90a", "content_id": "ff42768386cb125603fdf87ad819937b16bf816a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1099, "license_type": "permissive", "max_line_length": 130, "num_lines": 33, "path": "/src/Native/LibTorchSharp/THSAutograd.h", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#pragma once\n\n#include \"../Stdafx.h\"\n\n#include \"Utils.h\"\n\n// Returns whether the grad is enabled or not.\nEXPORT_API(bool) THSAutograd_isGradEnabled();\n\n// Enables / disables grad.\nEXPORT_API(void) THSAutograd_setGrad(bool enabled);\n\n// Returns whether the grad is enabled or not.\nEXPORT_API(bool) THSAutograd_isAnomalyEnabled();\n\nEXPORT_API(bool) THSAutograd_shouldCheckNaN();\n\n// Enables / disables grad.\nEXPORT_API(void) THSAutograd_setAnomaly(bool enabled, bool check_nan);\n\nEXPORT_API(void) THSAutograd_grad(\n Tensor* outputs, const int64_t oLength,\n Tensor* inputs, const int64_t iLength,\n Tensor* grad_outs, const int64_t gLenght,\n bool retain_graph, bool create_graph, bool allow_unused,\n Tensor* (*allocator)(size_t length));\n\nEXPORT_API(void) THSAutograd_backward(\n Tensor* tensors, const int64_t tLength,\n Tensor* grad_tensors, const int64_t gtLength,\n bool retain_graph, bool create_graph,\n Tensor* inputs, const int64_t iLength);" }, { "alpha_fraction": 0.7593501210212708, "alphanum_fraction": 0.7624157071113586, "avg_line_length": 52.47541046142578, "blob_id": "a44f837a01472ea6a1f43fe990762e2cbc9bf4ba", "content_id": "f1d28cebbb045c44d6775e968a8c07dbc1b1db5a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3262, "license_type": "permissive", "max_line_length": 284, "num_lines": 61, "path": "/CONTRIBUTING.md", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "Contributing to TorchSharp\n==========================\n\nIf you are here, it means you are interested in helping us out. A hearty welcome and thank you! There are many ways you can contribute to the ML.NET project:\n\n* Offer PR's to fix bugs or implement new features.\n* Give us feedback and bug reports regarding the software or the documentation.\n* Improve our examples, tutorials, and documentation.\n\nThis document describes contribution guidelines that are specific to TorchSharp. Please read [.NET Core Guidelines](https://github.com/dotnet/coreclr/blob/main/Documentation/project-docs/contributing.md) for more general .NET Core contribution guidelines.\n\n## Developers\n\nSee the [Developer Guide](DEVGUIDE.md) for details about building and developing in this repo.\n\n\n## Pull Requests\n\nIf you send us a PR, whether for documentation, examples, or library code, we require that you sign a digital Contributor License Agreement (CLA), so that we know you have the right to contribute. Once you have signed it, future PRs should go through without further requests to sign.\n\n* **DO** use your own forked repository for all development, and submit cross-fork PRs.\n* **DO** resolve merge conflicts early, by merging recent changes to 'main' into your development fork before submitting a PR.\n* **DO** submit all code changes via pull requests (PRs). PRs will be reviewed and potentially merged by the repo maintainers after a peer review that includes at least one maintainer.\n* **DO** give PRs short-but-descriptive names (for example, \"Improve code coverage for System.Console by 10%\", not \"Fix #1234\")\n* **DO** refer to any relevant issues, and include [keywords](https://help.github.com/articles/closing-issues-via-commit-messages/) that automatically close issues when the PR is merged.\n* **DO** tag any users that should know about and/or review the change.\n* **DO** ensure each commit successfully builds. The entire PR must pass all tests in the Continuous Integration (CI) system before it'll be merged.\n* **DO** add a brief description to the RELEASENOTES.md file at the top under the heading of the upcoming release.\n* **DO** address PR feedback in an additional commit(s) rather than amending the existing commits, and only rebase/squash them when necessary. This makes it easier for reviewers to track changes.\n* **DO** assume that [\"Squash and Merge\"](https://github.com/blog/2141-squash-your-commits) will be used to merge your commit unless you request otherwise in the PR.\n* **DO NOT** fix merge conflicts using a merge commit. Prefer `git rebase`.\n* **DO NOT** mix independent, unrelated changes in one PR. Separate unrelated fixes into separate PRs.\n\n\n## A Useful Tip\n\nA useful tip from the Tensorflow.NET repo:\n\nAfter you fork, add dotnet/TorchSharp as 'upstream' to your local repo ...\n\n```git\ngit remote add upstream https://github.com/dotnet/TorchSharp.git\n```\n\nThis makes it easy to keep your fork up to date by regularly pulling and merging from upstream.\n\nAssuming that you do all your development off your main branch, keep your main updated\nwith these commands:\n\n```git\ngit checkout main\ngit pull upstream main\ngit push origin main\n```\n\nThen, you merge onto your dev branch:\n\n```git\ngit checkout <<your dev branch>>\ngit merge main\n```\n" }, { "alpha_fraction": 0.5750093460083008, "alphanum_fraction": 0.5757575631141663, "avg_line_length": 38.89552307128906, "blob_id": "b6eba5bf64249ca3e13f827da0a88f45ed369aff", "content_id": "dc4fea3fe317eb299ba9f622acbbe26e50ef050c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2673, "license_type": "permissive", "max_line_length": 139, "num_lines": 67, "path": "/src/TorchSharp/NN/Activation/Softmax.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a Softmax module.\n /// </summary>\n public sealed class Softmax : torch.nn.Module<Tensor, Tensor>\n {\n internal Softmax(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_Softmax_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public override string GetName()\n {\n return typeof(Softmax).Name;\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Softmax\n /// </summary>\n /// <param name=\"dim\">A dimension along which Softmax will be computed (so every slice along dim will sum to 1)</param>\n /// <returns></returns>\n public static Softmax Softmax(long dim)\n {\n var handle = THSNN_Softmax_ctor(dim, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Softmax(handle, boxedHandle);\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Computes the softmax function for the input tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">A dimension along which softmax will be computed.</param>\n /// <param name=\"dtype\">The desired data type of returned tensor.</param>\n public static Tensor softmax(Tensor input, long dim, ScalarType? dtype = null) => torch.special.softmax(input, dim, dtype);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5465657114982605, "alphanum_fraction": 0.5545369982719421, "avg_line_length": 34.6729850769043, "blob_id": "33fdeb6653b51580c7e58f804c8ada514b0af26a", "content_id": "8fb175718ec201652a76b0d93010f49c06815762", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7527, "license_type": "permissive", "max_line_length": 208, "num_lines": 211, "path": "/src/Examples/TextClassification.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Collections.Generic;\nusing System.Diagnostics;\n\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\n\nnamespace TorchSharp.Examples\n{\n\n /// <summary>\n /// This example is based on the PyTorch tutorial at:\n ///\n /// https://pytorch.org/tutorials/beginner/text_sentiment_ngrams_tutorial.html\n ///\n /// It relies on the AG_NEWS dataset, which can be downloaded in CSV form at:\n ///\n /// https://github.com/mhjabreel/CharCnn_Keras/tree/master/data/ag_news_csv\n ///\n /// Download the two files, and place them in a folder called \"AG_NEWS\" in\n /// accordance with the file path below (Windows only).\n ///\n /// </summary>\n public class TextClassification\n {\n private const long emsize = 200;\n\n private const long batch_size = 128;\n private const long eval_batch_size = 128;\n\n private const int epochs = 15;\n\n // This path assumes that you're running this on Windows.\n#if NET472_OR_GREATER\n private readonly static string _dataLocation = NSPath.Join(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), \"..\", \"Downloads\", \"AG_NEWS\");\n#else\n private readonly static string _dataLocation = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), \"..\", \"Downloads\", \"AG_NEWS\");\n#endif // NET472_OR_GREATER\n internal static void Main(string[] args)\n\n {\n torch.random.manual_seed(1);\n\n var cwd = Environment.CurrentDirectory;\n\n var device = torch.cuda.is_available() ? torch.CUDA : torch.CPU;\n Console.WriteLine($\"Running TextClassification on {device.type.ToString()}\");\n\n using (var reader = TorchText.Data.AG_NEWSReader.AG_NEWS(\"train\", (Device)device, _dataLocation)) {\n\n var dataloader = reader.Enumerate();\n\n var tokenizer = TorchText.Data.Utils.get_tokenizer(\"basic_english\");\n\n var counter = new TorchText.Vocab.Counter<string>();\n foreach (var (label, text) in dataloader) {\n counter.update(tokenizer(text));\n }\n\n var vocab = new TorchText.Vocab.Vocab(counter);\n\n var model = new TextClassificationModel(vocab.Count, emsize, 4).to((Device)device);\n\n var loss = CrossEntropyLoss();\n var lr = 5.0;\n var optimizer = torch.optim.SGD(model.parameters(), lr);\n var scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1, 0.2, last_epoch: 5);\n\n // This data set is small enough that we can get away with\n // collecting memory only once per epoch.\n\n using (var d = torch.NewDisposeScope()) {\n\n foreach (var epoch in Enumerable.Range(1, epochs)) {\n\n var sw = new Stopwatch();\n sw.Start();\n\n train(epoch, reader.GetBatches(tokenizer, vocab, batch_size), model, loss, optimizer);\n\n sw.Stop();\n\n var pgFirst = optimizer.ParamGroups.First();\n\n Console.WriteLine($\"\\nEnd of epoch: {epoch} | lr: {pgFirst.LearningRate:0.00} | time: {sw.Elapsed.TotalSeconds:0.0}s\\n\");\n scheduler.step();\n }\n }\n\n using (var d = torch.NewDisposeScope()) {\n\n using (var test_reader = TorchText.Data.AG_NEWSReader.AG_NEWS(\"test\", (Device)device, _dataLocation)) {\n\n var sw = new Stopwatch();\n sw.Start();\n\n var accuracy = evaluate(test_reader.GetBatches(tokenizer, vocab, eval_batch_size), model, loss);\n\n sw.Stop();\n\n Console.WriteLine($\"\\nEnd of training: test accuracy: {accuracy:0.00} | eval time: {sw.Elapsed.TotalSeconds:0.0}s\\n\");\n scheduler.step();\n }\n }\n }\n }\n\n static void train(int epoch, IEnumerable<(Tensor, Tensor, Tensor)> train_data, TextClassificationModel model, Loss<torch.Tensor, torch.Tensor, torch.Tensor> criterion, torch.optim.Optimizer optimizer)\n {\n model.train();\n\n double total_acc = 0.0;\n long total_count = 0;\n long log_interval = 250;\n\n var batch = 0;\n\n var batch_count = train_data.Count();\n\n foreach (var (labels, texts, offsets) in train_data) {\n\n optimizer.zero_grad();\n\n using (var predicted_labels = model.call(texts, offsets)) {\n\n var loss = criterion.call(predicted_labels, labels);\n loss.backward();\n torch.nn.utils.clip_grad_norm_(model.parameters().ToArray(), 0.5);\n optimizer.step();\n\n total_acc += (predicted_labels.argmax(1) == labels).sum().to(torch.CPU).item<long>();\n total_count += labels.size(0);\n }\n\n if (batch % log_interval == 0 && batch > 0) {\n var accuracy = total_acc / total_count;\n Console.WriteLine($\"epoch: {epoch} | batch: {batch} / {batch_count} | accuracy: {accuracy:0.00}\");\n }\n\n batch += 1;\n }\n }\n\n static double evaluate(IEnumerable<(Tensor, Tensor, Tensor)> test_data, TextClassificationModel model, Loss<Tensor, Tensor, Tensor> criterion)\n {\n model.eval();\n\n double total_acc = 0.0;\n long total_count = 0;\n\n foreach (var (labels, texts, offsets) in test_data) {\n\n using (var predicted_labels = model.call(texts, offsets)) {\n var loss = criterion.call(predicted_labels, labels);\n\n total_acc += (predicted_labels.argmax(1) == labels).sum().to(torch.CPU).item<long>();\n total_count += labels.size(0);\n }\n }\n\n return total_acc / total_count;\n }\n }\n\n class TextClassificationModel : Module<Tensor, Tensor>\n {\n private Modules.EmbeddingBag embedding;\n private Modules.Linear fc;\n\n public TextClassificationModel(long vocab_size, long embed_dim, long num_class) : base(\"TextClassification\")\n {\n embedding = EmbeddingBag(vocab_size, embed_dim, sparse: false);\n fc = Linear(embed_dim, num_class);\n InitWeights();\n\n RegisterComponents();\n }\n\n private void InitWeights()\n {\n var initrange = 0.5;\n\n init.uniform_(embedding.weight, -initrange, initrange);\n init.uniform_(fc.weight, -initrange, initrange);\n init.zeros_(fc.bias);\n }\n\n public override Tensor forward(Tensor t)\n {\n throw new NotImplementedException();\n }\n\n public Tensor call(Tensor input, Tensor offsets)\n {\n return fc.call(embedding.call(input, offsets));\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n embedding.Dispose();\n fc.Dispose();\n ClearModules();\n }\n base.Dispose(disposing);\n }\n }\n}\n" }, { "alpha_fraction": 0.5338345766067505, "alphanum_fraction": 0.5371407270431519, "avg_line_length": 46.72010040283203, "blob_id": "ed558b1e96236a328e8cdee987a9c62078f697e6", "content_id": "3dc444bec3e731c1427e33c81044d74f184015a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 18761, "license_type": "permissive", "max_line_length": 207, "num_lines": 393, "path": "/src/TorchSharp/Utils/tensorboard/SummaryWriter.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Threading;\nusing Google.Protobuf;\nusing Tensorboard;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class utils\n {\n public static partial class tensorboard\n {\n /// <summary>\n /// Writes entries directly to event files in the log_dir to be consumed by TensorBoard.\n /// \n /// The SummaryWriter class provides a high-level API to create an event file in a given directory and add summaries and events to it.The class updates the file contents asynchronously.\n ///\n /// This allows a training program to call methods to add data to the file directly from the training loop, without slowing down training.\n /// </summary>\n /// <param name=\"log_dir\">\n /// Save directory location. Default is runs/CURRENT_DATETIME_HOSTNAME, which changes after each run.\n /// Use hierarchical folder structure to compare between runs easily. e.g. pass in ‘runs/exp1’, ‘runs/exp2’, etc.\n /// for each new experiment to compare across them\n /// </param>\n /// <param name=\"filename_suffix\">Suffix added to all event filenames in the log_dir directory.</param>\n /// <param name=\"createRunName\">Create a time-based run name, even if log_dir is specified.</param>\n public static Modules.SummaryWriter SummaryWriter(string log_dir = null, string filename_suffix = null, bool createRunName = false)\n {\n if (createRunName && !string.IsNullOrEmpty(log_dir)) {\n log_dir = CreateRunName(log_dir);\n }\n\n return new Modules.SummaryWriter(log_dir, filename_suffix);\n }\n\n internal static string CreateRunName(string log_dir)\n {\n var now = DateTime.Now;\n var _months = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedMonthNames;\n var name = $\"{_months[now.Month - 1]}{now.Day}_{now.Hour}-{now.Minute}-{now.Second}_{System.Net.Dns.GetHostName()}\";\n log_dir = Path.Combine(log_dir, name);\n return log_dir;\n }\n }\n }\n }\n\n namespace Modules\n {\n /// <summary>\n /// Writes entries directly to event files in the log_dir to be consumed by TensorBoard.\n /// \n /// The SummaryWriter class provides a high-level API to create an event file in a given directory and add summaries and events to it.The class updates the file contents asynchronously.\n ///\n /// This allows a training program to call methods to add data to the file directly from the training loop, without slowing down training.\n /// </summary>\n public class SummaryWriter\n {\n internal SummaryWriter(string log_dir, string filename_suffix)\n {\n _suffix = filename_suffix;\n\n if (string.IsNullOrEmpty(log_dir)) {\n _log_dir = torch.utils.tensorboard.CreateRunName(\"runs\");\n } else {\n _log_dir = log_dir;\n }\n\n if (!Directory.Exists(_log_dir)) {\n Directory.CreateDirectory(_log_dir);\n }\n\n var fileName = Path.Combine(_log_dir, $\"events.out.tfevents.{DateTime.Now.Ticks}.{System.Net.Dns.GetHostName()}.{Process.GetCurrentProcess().Id}.{Interlocked.Increment(ref _global_uid)}\");\n if (!string.IsNullOrEmpty(_suffix)) {\n fileName = fileName + \".\" + _suffix;\n }\n\n if (File.Exists(fileName)) {\n File.Delete(fileName);\n }\n\n InitFile(fileName);\n\n _fileNames[\"__default__\"] = fileName;\n }\n\n /// <summary>\n /// The directory/folder where logging is made.\n /// </summary>\n public string LogDir { get { return _log_dir; } }\n\n /// <summary>\n /// Add scalar data to summary.\n /// </summary>\n /// <param name=\"tag\">Data identifier</param>\n /// <param name=\"scalar_value\">Value to save</param>\n /// <param name=\"global_step\">Global step value to record</param>\n /// <param name=\"walltime\">Optional override default walltime (DateTimeOffset.Now.ToUnixTimeSeconds())</param>\n public void add_scalar(string tag, float scalar_value, int global_step, long? walltime = null)\n {\n var fileName = InitDefaultFile();\n SetWalltime(ref walltime);\n\n var summary = new Summary();\n summary.Value.Add(new Summary.Types.Value() { SimpleValue = scalar_value, Tag = tag });\n var evnt = new Event() { Step = global_step, WallTime = walltime.Value, Summary = summary };\n\n WriteEvent(fileName, evnt);\n }\n\n /// <summary>\n /// Adds many scalar data points to summary.\n /// </summary>\n /// <param name=\"main_tag\">Data identifier</param>\n /// <param name=\"tag_scalar_dict\">Dictionary storing the tag and corresponding values</param>\n /// <param name=\"global_step\">Global step value to record</param>\n /// <param name=\"walltime\">Optional override default walltime (DateTimeOffset.Now.ToUnixTimeSeconds())</param>\n public void add_scalars(string main_tag, IDictionary<string, float> tag_scalar_dict, int global_step, long? walltime = null)\n {\n SetWalltime(ref walltime);\n\n foreach (var kv in tag_scalar_dict) {\n\n var key = kv.Key;\n var scalar_value = kv.Value;\n\n var summary = new Summary();\n summary.Value.Add(new Summary.Types.Value() { SimpleValue = scalar_value, Tag = main_tag });\n var evnt = new Event() { Step = global_step, WallTime = walltime.Value, Summary = summary };\n\n if (!_fileNames.TryGetValue(key, out var fileName)) {\n\n // We haven't logged this tag from this session, yet. Create a clean file.\n\n var fileDir = Path.Combine(_log_dir, $\"{main_tag}_{key}\");\n if (!Directory.Exists(fileDir)) {\n Directory.CreateDirectory(fileDir);\n }\n\n fileName = Path.Combine(fileDir, $\"events.out.tfevents.{DateTime.Now.Ticks}.{System.Net.Dns.GetHostName()}.{Process.GetCurrentProcess().Id}.{Interlocked.Increment(ref _global_uid)}\");\n\n if (File.Exists(fileName)) {\n File.Delete(fileName);\n }\n\n InitFile(fileName);\n\n _fileNames[key] = fileName;\n }\n\n WriteEvent(fileName, evnt);\n }\n }\n\n\n /// <summary>\n /// Adds many scalar data points to summary.\n /// </summary>\n /// <param name=\"main_tag\">Data identifier</param>\n /// <param name=\"tag_scalar_dict\">List of tuples storing the tag and corresponding values</param>\n /// <param name=\"global_step\">Global step value to record</param>\n /// <param name=\"walltime\">Optional override default walltime (DateTimeOffset.Now.ToUnixTimeSeconds())</param>\n public void add_scalars(string main_tag, IList<(string, float)> tag_scalar_dict, int global_step, long? walltime = null)\n {\n SetWalltime(ref walltime);\n\n foreach (var (key, scalar_value) in tag_scalar_dict) {\n\n var summary = new Summary();\n summary.Value.Add(new Summary.Types.Value() { SimpleValue = scalar_value, Tag = main_tag });\n var evnt = new Event() { Step = global_step, WallTime = walltime.Value, Summary = summary };\n\n if (!_fileNames.TryGetValue(key, out var fileName)) {\n\n var fileDir = Path.Combine(_log_dir, $\"{main_tag}_{key}\");\n if (!Directory.Exists(fileDir)) {\n Directory.CreateDirectory(fileDir);\n }\n\n fileName = Path.Combine(fileDir, $\"events.out.tfevents.{DateTime.Now.Ticks}.{System.Net.Dns.GetHostName()}.{Process.GetCurrentProcess().Id}.{Interlocked.Increment(ref _global_uid)}\");\n\n if (!File.Exists(fileName)) {\n InitFile(fileName);\n }\n\n _fileNames[key] = fileName;\n }\n\n WriteEvent(fileName, evnt);\n }\n }\n\n /// <summary>\n /// Add histogram to summary.\n ///\n /// https://pytorch.org/docs/stable/_modules/torch/utils/tensorboard/writer.html#SummaryWriter.add_histogram\n /// </summary>\n /// <param name=\"tag\"> Data identifier </param>\n /// <param name=\"values\"> Values to build histogram </param>\n /// <param name=\"global_step\"> Global step value to record </param>\n /// <param name=\"bins\"> This determines how the bins are made </param>\n /// <param name=\"walltime\"> Optional override default walltime (DateTimeOffset.Now.ToUnixTimeSeconds()) </param>\n /// <param name=\"max_bins\"></param>\n public void add_histogram(string tag,\n torch.Tensor values,\n int global_step,\n Utils.tensorboard.Enums.HistogramBinSelector bins = Utils.tensorboard.Enums.HistogramBinSelector.Tensorflow,\n long? walltime = null,\n long? max_bins = null)\n {\n static torch.Tensor default_bins()\n {\n double v = 1e-12;\n var buckets = new List<double>();\n var neg_buckets = new List<double>();\n while (v < 1e20) {\n buckets.Add(v);\n neg_buckets.Add(-v);\n v *= 1.1;\n }\n neg_buckets.Reverse();\n var result = new List<double>();\n result.AddRange(neg_buckets); result.Add(0); result.AddRange(buckets);\n return torch.tensor(result);\n }\n\n var fileName = InitDefaultFile();\n SetWalltime(ref walltime);\n Summary summary = bins == Utils.tensorboard.Enums.HistogramBinSelector.Tensorflow ?\n torch.utils.tensorboard.Summary.histogram(tag, values, default_bins(), max_bins) :\n torch.utils.tensorboard.Summary.histogram(tag, values, (HistogramBinSelector)(byte)bins, max_bins);\n var evnt = new Event() { Step = global_step, WallTime = walltime.Value, Summary = summary };\n WriteEvent(fileName, evnt);\n }\n\n /// <summary>\n /// Add batched image data to summary.\n ///\n /// https://pytorch.org/docs/stable/tensorboard.html#torch.utils.tensorboard.writer.SummaryWriter.add_image\n /// </summary>\n /// <param name=\"tag\"> Data identifier </param>\n /// <param name=\"img_tensor\"> Image data </param>\n /// <param name=\"global_step\"> Global step value to record </param>\n /// <param name=\"walltime\"> Optional override default walltime (DateTimeOffset.Now.ToUnixTimeSeconds()) </param>\n /// <param name=\"dataformats\"> Image data format specification of the form CHW, HWC, HW, WH, etc. </param>\n public void add_img(string tag, torch.Tensor img_tensor, int global_step, long? walltime = null, string dataformats = \"CHW\")\n {\n var fileName = InitDefaultFile();\n SetWalltime(ref walltime);\n Summary summary = torch.utils.tensorboard.Summary.image(tag, img_tensor, dataformats: dataformats);\n var evnt = new Event() { Step = global_step, WallTime = walltime.Value, Summary = summary };\n WriteEvent(fileName, evnt);\n }\n\n /// <summary>\n /// Add batched image data to summary.\n ///\n /// https://pytorch.org/docs/stable/tensorboard.html#torch.utils.tensorboard.writer.SummaryWriter.add_image\n /// </summary>\n /// <param name=\"tag\"> Data identifier </param>\n /// <param name=\"file_name\"> Image file </param>\n /// <param name=\"global_step\"> Global step value to record </param>\n /// <param name=\"walltime\"> Optional override default walltime (DateTimeOffset.Now.ToUnixTimeSeconds()) </param>\n public void add_img(string tag, string file_name, int global_step, long? walltime = null)\n {\n var fileName = InitDefaultFile();\n SetWalltime(ref walltime);\n Summary summary = torch.utils.tensorboard.Summary.image(tag, file_name);\n var evnt = new Event() { Step = global_step, WallTime = walltime.Value, Summary = summary };\n WriteEvent(fileName, evnt);\n }\n\n /// <summary>\n /// Add video data to summary.\n ///\n /// https://pytorch.org/docs/stable/tensorboard.html#torch.utils.tensorboard.writer.SummaryWriter.add_video\n /// </summary>\n /// <param name=\"tag\"> Data identifier </param>\n /// <param name=\"vid_tensor\">\n /// Video data\n ///\n /// Shape: (N,T,C,H,W). The values should lie in [0, 255] for type uint8 or [0, 1] for type float.\n /// </param>\n /// <param name=\"global_step\"> Global step value to record </param>\n /// <param name=\"fps\"> Frames per second </param>\n /// <param name=\"walltime\"> Optional override default walltime (DateTimeOffset.Now.ToUnixTimeSeconds()) </param>\n public void add_video(string tag, torch.Tensor vid_tensor, int global_step, int fps = 4, long? walltime = null)\n {\n var fileName = InitDefaultFile();\n SetWalltime(ref walltime);\n Summary summary = torch.utils.tensorboard.Summary.video(tag, vid_tensor, fps);\n var evnt = new Event() { Step = global_step, WallTime = walltime.Value, Summary = summary };\n WriteEvent(fileName, evnt);\n }\n\n /// <summary>\n /// Add text data to summary.\n /// \n /// https://pytorch.org/docs/stable/_modules/torch/utils/tensorboard/writer.html#SummaryWriter.add_text\n /// </summary>\n /// <param name=\"tag\"> Data identifier </param>\n /// <param name=\"text_string\"> String to save </param>\n /// <param name=\"global_step\"> Global step value to record </param>\n /// <param name=\"walltime\"> Optional override default walltime (DateTimeOffset.Now.ToUnixTimeSeconds()) </param>\n public void add_text(string tag, string text_string, int global_step, long? walltime = null)\n {\n var fileName = InitDefaultFile();\n SetWalltime(ref walltime);\n\n var evnt = new Event() { Step = global_step, WallTime = walltime.Value, Summary = torch.utils.tensorboard.Summary.text(tag, text_string) };\n WriteEvent(fileName, evnt);\n }\n\n private static void InitFile(string fileName)\n {\n var evnt = new Event() { FileVersion = \"brain.Event:2\", WallTime = DateTime.Now.Ticks };\n WriteEvent(fileName, evnt);\n }\n\n private string InitDefaultFile()\n {\n var fileName = _fileNames[\"__default__\"];\n\n if (!File.Exists(fileName)) {\n InitFile(fileName);\n }\n\n return fileName;\n }\n\n private static void SetWalltime(ref long? walltime)\n => walltime ??= DateTimeOffset.Now.ToUnixTimeSeconds();\n\n private static void WriteEvent(string fileName, Event evnt)\n {\n var bytes = evnt.ToByteArray();\n\n long header = bytes.LongLength;\n uint header_crc = GetMaskedCrc(header);\n uint footer_crc = GetMaskedCrc(bytes);\n\n using (var fStream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read)) {\n fStream.Seek(0, SeekOrigin.End);\n\n using (var writers = new BinaryWriter(fStream)) {\n writers.Write(header);\n writers.Write(header_crc);\n using (var stream = new Google.Protobuf.CodedOutputStream(fStream, true)) {\n evnt.WriteTo(stream);\n }\n fStream.Seek(0, SeekOrigin.End);\n writers.Write(footer_crc);\n fStream.Flush();\n }\n }\n }\n\n private string _log_dir = null;\n private Dictionary<string, string> _fileNames = new Dictionary<string, string>();\n\n private string _suffix = null;\n\n private int _global_uid;\n\n private static uint GetMaskedCrc(byte[] data)\n {\n var value = TorchSharp.Utils.CRC32C.process(data);\n // Rotate right by 15 bits and add a constant.\n return ((value >> 15) | (value << 17)) + 0xa282ead8U;\n }\n\n private static uint GetMaskedCrc(int data)\n {\n var value = TorchSharp.Utils.CRC32C.process(data);\n // Rotate right by 15 bits and add a constant.\n return ((value >> 15) | (value << 17)) + 0xa282ead8U;\n }\n\n private static uint GetMaskedCrc(long data)\n {\n var value = TorchSharp.Utils.CRC32C.process(data);\n // Rotate right by 15 bits and add a constant.\n return ((value >> 15) | (value << 17)) + 0xa282ead8U;\n }\n }\n }\n}" }, { "alpha_fraction": 0.4700726568698883, "alphanum_fraction": 0.5074143409729004, "avg_line_length": 34.14495086669922, "blob_id": "cc8c0fe28dfdbec371ce590d040e987f7c3d4f7b", "content_id": "84f7bea9a0e3047583cf31c957a5583c58454fc2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 40732, "license_type": "permissive", "max_line_length": 173, "num_lines": 1159, "path": "/test/TorchSharpTest/TestTorchTensorBugs.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.IO;\n\nusing System.Threading;\nusing System.Runtime.CompilerServices;\n\nusing static TorchSharp.torch.nn;\nusing Xunit;\n\nusing static TorchSharp.torch;\nusing static TorchSharp.torchvision.models;\n\n\nusing System.Numerics;\n\n#nullable enable\n\nnamespace TorchSharp\n{\n // The tests in this file are all derived from reported GitHub Issues, serving\n // as regression tests.\n\n [Collection(\"Sequential\")]\n public class TestTorchTensorBugs\n {\n\n [Fact]\n public void ValidateAddInplace()\n {\n using var _ = NewDisposeScope();\n\n var x = torch.zeros(10, 10);\n var y = torch.ones(10).expand(10, 10);\n\n x.add_(y, 1);\n\n Assert.Equal(x, y);\n }\n\n [Fact(Skip = \"No longer throws an exception, and it doesn't seem like ever should have.\")]\n public void ValidateIssue145()\n {\n // Tensor.DataItem gives a hard crash on GPU tensor\n\n if (torch.cuda.is_available()) {\n\n using var _ = NewDisposeScope();\n\n var scalar = torch.tensor(3.14f, torch.CUDA);\n Assert.Throws<InvalidOperationException>(() => scalar.item<float>());\n var tensor = torch.zeros(new long[] { 10, 10 }, device: torch.CUDA);\n Assert.Throws<InvalidOperationException>(() => tensor.data<float>());\n Assert.Throws<InvalidOperationException>(() => { var _ = tensor.bytes; });\n }\n }\n\n class DoubleIt : nn.Module<Tensor, Tensor>\n {\n public DoubleIt() : base(\"double\") { }\n\n public override Tensor forward(Tensor t) => t * 2;\n }\n\n [Fact]\n public void ValidateIssue315_1()\n {\n using var _ = NewDisposeScope();\n\n // https://github.com/dotnet/TorchSharp/issues/315\n // custom module crash in GC thread\n\n // make Torch call our custom module by adding a ReLU in front of it\n using var net = nn.Sequential(\n (\"relu\", nn.ReLU()),\n (\"double\", new DoubleIt())\n );\n\n using var @in = torch.tensor(3);\n using var @out = net.call(@in);\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n\n [Fact]\n public void ValidateIssue315_2()\n {\n using var _ = NewDisposeScope();\n\n Func<Tensor, Tensor, Tensor> distance =\n (x, y) => {\n return (x - y).abs();\n };\n\n using (Tensor anchor = torch.rand(new long[] { 15, 5 }, requires_grad: true).neg())\n using (Tensor positive = torch.randn(new long[] { 15, 5 }, requires_grad: true))\n using (Tensor negative = torch.randn(new long[] { 15, 5 })) {\n\n var output = nn.TripletMarginWithDistanceLoss(distance);\n using (var result = output.call(anchor, positive, negative)) { }\n }\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n\n\n\n [Fact]\n public void ValidateIssue315_3()\n {\n using var _ = NewDisposeScope();\n\n var lin1 = Linear(1000, 100);\n var lin2 = Linear(100, 10);\n var seq = Sequential((\"lin1\", lin1), (\"relu1\", ReLU()), (\"lin2\", lin2));\n\n using var x = torch.randn(new long[] { 64, 1000 });\n using var y = torch.randn(new long[] { 64, 10 });\n\n double learning_rate = 0.00004f;\n var optimizer = torch.optim.LBFGS(seq.parameters(), learning_rate);\n var loss = nn.MSELoss(Reduction.Sum);\n\n Func<Tensor> closure = () => {\n using var eval = seq.call(x);\n var output = loss.call(eval, y);\n\n var l = output.ToSingle();\n\n optimizer.zero_grad();\n\n output.backward();\n return output;\n };\n\n optimizer.step(closure);\n\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n\n\n private void ThreadFunc()\n {\n using var _ = NewDisposeScope();\n\n using var net = nn.Sequential(\n (\"relu\", nn.ReLU()),\n (\"double\", new DoubleIt())\n );\n\n using var @in = torch.tensor(3);\n\n for (var i = 0; i < 1000; i++) {\n using var @out = net.call(@in);\n }\n }\n\n [Fact]\n public void ValidateIssue315_4()\n {\n // Is CustomModule thread-safe?\n // See: https://github.com/pytorch/pytorch/issues/19029\n\n var threads = new List<Thread>();\n\n for (var i = 0; i < 10; i++) {\n var t = new Thread(ThreadFunc);\n threads.Add(t);\n }\n\n foreach (var t in threads) {\n t.Start();\n }\n foreach (var t in threads) {\n t.Join();\n }\n }\n\n class TestModule : Module<Tensor, Tensor>\n {\n public TestModule() : base(nameof(TestModule)) { }\n\n public override torch.Tensor forward(torch.Tensor t) => t.clone();\n\n public static void Reproduce()\n {\n Tensor t = torch.zeros(10);\n\n var seq = Make();\n GC.Collect();\n GC.WaitForPendingFinalizers();\n for (var i = 0; i < 100; i++) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n t = seq.call(t);\n }\n }\n\n [MethodImpl(MethodImplOptions.NoInlining)]\n static Module<Tensor, Tensor> Make() => Sequential((\"t\", new TestModule()), (\"d\", Linear(10, 10)));\n }\n\n [Fact]\n void ValidateIssue321()\n {\n TestModule.Reproduce();\n }\n\n [Fact]\n public void ValidateIssue353()\n {\n using var _ = NewDisposeScope();\n\n //\n // Just validating that the methods are there.\n //\n using var x = torch.zeros(3, 3);\n using var y = torch.ones(3, 3);\n\n var mx1 = x.max();\n Assert.Equal(0, mx1.item<float>());\n\n var mx2 = x.maximum(y);\n Assert.True(mx2.allclose(y));\n\n var mn1 = x.min();\n Assert.Equal(0, mn1.item<float>());\n\n var mn2 = x.minimum(y);\n Assert.True(mn2.allclose(x));\n }\n\n [Fact]\n public void ValidateIssue399_1()\n {\n using var _ = NewDisposeScope();\n\n // Create a contiguous 3x4 matrix and fill with auto-inc values starting at zero.\n // 0 1 2 3\n // 4 5 6 7\n // 8 9 10 11\n using var contig = torch.arange(12, int32).reshape(3, 4).contiguous();\n var data1 = contig.data<int>();\n\n // Create a 3x2 slice of this, which should contain:\n // 1 2\n // 5 6\n // 9 10\n using var sub = contig.slice(1, 1, 3, 1);\n var data2 = sub.data<int>();\n\n Assert.Equal(12, data1.Count);\n Assert.Equal(6, data2.Count);\n\n Assert.False(sub.is_contiguous());\n Assert.True(sub.contiguous().data<int>() == data2);\n Assert.False(sub.contiguous().data<int>() != data2);\n Assert.Equal(sub.contiguous().data<int>(), data2);\n Assert.Equal(sub.contiguous().data<int>().ToArray(), data2.ToArray());\n }\n\n [Fact]\n public void ValidateIssue399_2()\n {\n using var _ = NewDisposeScope();\n\n // Create a contiguous 3x4 matrix and fill with auto-inc values starting at zero.\n // 0 1 2 3\n // 4 5 6 7\n // 8 9 10 11\n using var contig = torch.arange(12, int32).reshape(3, 4).contiguous();\n var data1 = contig.data<int>();\n\n // Creating the transpose, which should look like:\n // 0 4 8\n // 1 5 9\n // 2 6 10\n // 3 7 11\n using var trans = contig.t();\n var data2 = trans.data<int>();\n\n Assert.False(trans.is_contiguous());\n\n Assert.Equal(12, data1.Count);\n Assert.Equal(12, data2.Count);\n\n Assert.Equal(6, data2[2, 1]);\n Assert.Equal(7, data2[3, 1]);\n\n Assert.True(trans.contiguous().data<int>() == data2);\n Assert.False(trans.contiguous().data<int>() != data2);\n Assert.Equal(trans.contiguous().data<int>(), data2);\n Assert.Equal(trans.contiguous().data<int>().ToArray(), data2.ToArray());\n }\n\n [Fact]\n public void ValidateIssue399_3()\n {\n using var _ = NewDisposeScope();\n\n using var contig = torch.arange(27, int32).reshape(3, 3, 3).contiguous();\n using var trans = contig.permute(2, 0, 1);\n\n Assert.False(trans.is_contiguous());\n Assert.Equal<int>(trans.contiguous().data<int>(), trans.data<int>());\n Assert.Equal<int>(trans.contiguous().data<int>().ToArray(), trans.data<int>().ToArray());\n }\n\n [Fact]\n public void ValidateIssue399_4()\n {\n using var _ = NewDisposeScope();\n\n using var contig = torch.arange(12, int32).reshape(3, 4).contiguous();\n using var flipped = contig.t().flip(1);\n var strides = flipped.stride();\n\n Assert.False(flipped.is_contiguous());\n Assert.Equal<int>(flipped.contiguous().data<int>(), flipped.data<int>());\n Assert.Equal<int>(flipped.contiguous().data<int>().ToArray(), flipped.data<int>().ToArray());\n }\n\n [Fact]\n public void ValidateIssue399_5()\n {\n using var _ = NewDisposeScope();\n\n using var contig = torch.arange(12, int32).reshape(3, 4).contiguous();\n using var strided = contig.as_strided(new long[] { 3, 2, 4 }, new long[] { 4, 0, 1 });\n\n Assert.False(strided.is_contiguous());\n Assert.Equal<int>(strided.contiguous().data<int>(), strided.data<int>());\n Assert.Equal(new long[] { 3, 2, 4 }, strided.shape);\n }\n\n [Fact]\n public void ValidateIssue399_6()\n {\n using var _ = NewDisposeScope();\n\n using var contig = torch.arange(3, int32).reshape(3, 1).contiguous();\n using var strided = contig.expand(3, 4);\n\n Assert.False(strided.is_contiguous());\n Assert.Equal<int>(strided.contiguous().data<int>(), strided.data<int>());\n Assert.Equal(new long[] { 3, 4 }, strided.shape);\n }\n\n [Fact]\n public void ValidateIssue399_7()\n {\n using var _ = NewDisposeScope();\n\n using var contig = torch.arange(27, int32).reshape(3, 3, 3).contiguous();\n using var trans = contig.permute(2, 0, 1);\n\n Assert.False(trans.is_contiguous());\n\n // Test the enumerators.\n var data1 = trans.contiguous().data<int>();\n var data2 = trans.data<int>();\n\n var expected = new int[] { 0, 3, 6, 9, 12, 15, 18, 21, 24, 1, 4, 7, 10, 13, 16, 19, 22, 25, 2, 5, 8, 11, 14, 17, 20, 23, 26 };\n\n long idx = 0;\n foreach (var value in data1) {\n Assert.Equal(expected[idx], value);\n idx += 1;\n }\n Assert.Equal(27, idx);\n\n idx = 0;\n foreach (var value in data2) {\n Assert.Equal(expected[idx], value);\n idx += 1;\n }\n Assert.Equal(27, idx);\n\n var arr1 = data1.AsEnumerable<int>().ToArray();\n var arr2 = data2.AsEnumerable<int>().ToArray();\n\n Assert.Equal(expected, arr1);\n Assert.Equal(arr1, arr2);\n }\n\n [Fact]\n public void ValidateIssue399_8()\n {\n using var _ = NewDisposeScope();\n\n // We need to test something that has rank 1, because the TensorAccessor uses\n // seprate enumeration logic for that.\n using var contig = torch.arange(48, int32).reshape(12, 4).contiguous();\n using var sub = contig.slice(1, 1, 2, 1).squeeze(1);\n\n var data1 = sub.contiguous().data<int>();\n var data2 = sub.data<int>();\n\n Assert.True(data1 == data2);\n Assert.False(data1 != data2);\n\n Assert.Equal(data1.ToArray(), data2.ToArray());\n\n var expected = new int[] { 1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45 };\n\n long idx = 0;\n foreach (var value in data1) {\n Assert.Equal(expected[idx], value);\n idx += 1;\n }\n Assert.Equal(12, idx);\n\n idx = 0;\n foreach (var value in data2) {\n Assert.Equal(expected[idx], value);\n idx += 1;\n }\n Assert.Equal(12, idx);\n\n var arr1 = data1.AsEnumerable<int>().ToArray();\n var arr2 = data2.AsEnumerable<int>().ToArray();\n\n Assert.Equal(expected, arr1);\n Assert.Equal(arr1, arr2);\n }\n\n [Fact]\n public void ValidateRandThrowsOnWrongType()\n {\n using var _ = NewDisposeScope();\n\n Assert.Throws<ArgumentException>(() => torch.rand(3, 4, dtype: torch.int8));\n Assert.Throws<ArgumentException>(() => torch.rand(3, 4, dtype: torch.uint8));\n Assert.Throws<ArgumentException>(() => torch.rand(3, 4, dtype: torch.int16));\n Assert.Throws<ArgumentException>(() => torch.rand(3, 4, dtype: torch.int32));\n Assert.Throws<ArgumentException>(() => torch.rand(3, 4, dtype: torch.int64));\n Assert.Throws<ArgumentException>(() => torch.rand(3, 4, dtype: torch.@bool));\n Assert.Throws<ArgumentException>(() => torch.randn(3, 4, dtype: torch.int8));\n Assert.Throws<ArgumentException>(() => torch.randn(3, 4, dtype: torch.uint8));\n Assert.Throws<ArgumentException>(() => torch.randn(3, 4, dtype: torch.int16));\n Assert.Throws<ArgumentException>(() => torch.randn(3, 4, dtype: torch.int32));\n Assert.Throws<ArgumentException>(() => torch.randn(3, 4, dtype: torch.int64));\n Assert.Throws<ArgumentException>(() => torch.randn(3, 4, dtype: torch.@bool));\n }\n\n [Fact]\n public void ValidateIssue496()\n {\n using var _ = NewDisposeScope();\n\n var c2 = torch.nn.Conv2d(3, 16, kernelSize: (1, 7), stride: (1, 1), padding: (0, 3));\n var Win = torch.rand(16, 3, 8, 8);\n var s = c2.call(Win).shape;\n Assert.Equal(new long[] { 16, 16, 8, 8 }, s);\n }\n\n [Fact]\n public void ValidateIssue500()\n {\n using var _ = NewDisposeScope();\n\n using (var pool = BatchNorm1d(28)) {\n pool.eval();\n pool.call(torch.ones(1, 28));\n }\n using (var pool = BatchNorm1d(28))\n using (var seq = Sequential(pool)) {\n seq.eval();\n seq.call(torch.ones(1, 28));\n }\n using (var seq = new Module500()) {\n seq.eval();\n seq.call(torch.ones(1, 28));\n }\n }\n\n class Module500 : Module<Tensor, Tensor>\n {\n private Module<Tensor, Tensor> bn1 = BatchNorm1d(28);\n\n public Module500() : base(nameof(TestModule)) { RegisterComponents(); }\n\n public override torch.Tensor forward(torch.Tensor t) => bn1.call(t);\n }\n\n [Fact]\n public void ValidateIssue510()\n {\n using var _ = NewDisposeScope();\n\n var model = new Module510(1, 32);\n model.call(torch.randn(16, 1, 32));\n\n var w0 = model.get_parameter(\"stack.0.weight\").clone();\n var w1 = model.get_parameter(\"stack.1.weight\").clone();\n var b1 = model.get_parameter(\"stack.1.bias\").clone();\n var rm = model.get_buffer(\"stack.1.running_mean\").clone();\n var rv = model.get_buffer(\"stack.1.running_var\").clone();\n var nm = model.get_buffer(\"stack.1.num_batches_tracked\").clone();\n\n model.load(\"bug510.dat\");\n\n var w0_ = model.get_parameter(\"stack.0.weight\");\n var w1_ = model.get_parameter(\"stack.1.weight\");\n var b1_ = model.get_parameter(\"stack.1.bias\");\n var rm_ = model.get_buffer(\"stack.1.running_mean\");\n var rv_ = model.get_buffer(\"stack.1.running_var\");\n var nm_ = model.get_buffer(\"stack.1.num_batches_tracked\");\n\n Assert.NotEqual(w0, w0_);\n Assert.NotEqual(w1, w1_);\n Assert.NotEqual(b1, b1_);\n Assert.NotEqual(rm, rm_);\n Assert.NotEqual(rv, rv_);\n Assert.Equal(1, nm.item<long>());\n Assert.Equal(0, nm_.item<long>());\n }\n\n internal class Module510 : Module<Tensor, Tensor>\n {\n private readonly Module<Tensor, Tensor> stack;\n\n public Module510(int in_channels, int out_channels, int kernel_size = 3, int stride = 1, int padding = 0) : base(String.Empty)\n {\n var temp = BatchNorm1d(out_channels);\n this.stack = Sequential(\n Conv1d(in_channels, out_channels, 3, stride: stride, padding: padding, bias: false),\n temp,\n ReLU(inplace: true)\n );\n\n temp.weight = Parameter(torch.randn(temp.weight!.shape));\n temp.bias = Parameter(torch.randn(temp.bias!.shape));\n if (temp.running_mean is not null) temp.running_mean = torch.randn(temp.running_mean.shape);\n if (temp.running_var is not null) temp.running_var = torch.randn(temp.running_var.shape);\n\n this.RegisterComponents();\n }\n\n public override torch.Tensor forward(torch.Tensor t)\n {\n return this.stack.call(t);\n }\n }\n\n [Fact]\n public void ValidateIssue516()\n {\n if (torch.cuda.is_available()) {\n using var _ = NewDisposeScope();\n\n var model = new TestGradWarningModel();\n model.cuda();\n\n var optimizer = torch.optim.Adam(model.parameters());\n optimizer.zero_grad();\n\n var x = torch.ones(5, 3).cuda();\n var y = torch.ones(5, 4).cuda();\n\n var z = model.call(x);\n var lossFunc = torch.nn.CrossEntropyLoss();\n var loss = lossFunc.call(y, z);\n loss.backward();\n optimizer.step();\n\n var grad1 = optimizer.parameters().ToArray()[0].grad();\n Assert.NotNull(grad1);\n\n var grad2 = model.Weight.grad();\n Assert.NotNull(grad2);\n }\n }\n\n internal abstract class BaseModule : torch.nn.Module<Tensor, Tensor>\n {\n public int? InstanceId = null;\n\n protected BaseModule(string name) : base(name)\n {\n }\n }\n\n public class TestGradWarningModel : torch.nn.Module<Tensor, Tensor>\n {\n public readonly Modules.Parameter Weight;\n\n public TestGradWarningModel() : base(nameof(TestGradWarningModel))\n {\n Weight = torch.zeros(new long[] { 3, 4 }).AsParameter();\n RegisterComponents();\n }\n\n public override torch.Tensor forward(torch.Tensor t)\n {\n return torch.matmul(t, Weight);\n }\n }\n\n [Fact]\n public void Validate532()\n {\n using var _ = NewDisposeScope();\n var module = new Module532(1000, 100);\n\n var p = module.parameters().ToArray();\n var pB = module.batch.parameters().ToArray();\n var pC = module.conv.parameters().ToArray();\n\n Assert.Equal(pB.Length + pC.Length, p.Length);\n }\n\n internal class Module532 : Module<Tensor, Tensor>\n {\n public Module<Tensor, Tensor> conv;\n public Module<Tensor, Tensor> batch;\n private Module<Tensor, Tensor> seq;\n\n public Module532(int in_channels, int out_channels) : base(String.Empty)\n {\n conv = Conv1d(in_channels, out_channels, 3);\n batch = BatchNorm1d(out_channels);\n seq = Sequential(\n conv,\n batch,\n ReLU(inplace: true)\n );\n\n this.RegisterComponents();\n }\n\n public override torch.Tensor forward(torch.Tensor t)\n {\n return this.seq.call(t);\n }\n }\n\n\n\n [Fact]\n public void Validate538()\n {\n var module = new Module538(1000, 100);\n\n var sd = module.state_dict();\n\n Assert.Equal(7, sd.Count);\n\n if (File.Exists(\"bug538.dat\")) File.Delete(\"bug538.dat\");\n\n module.save(\"bug538.dat\");\n module.load(\"bug538.dat\");\n\n File.Delete(\"bug538.dat\");\n }\n\n internal class Module538 : Module<Tensor, Tensor>\n {\n private Module<Tensor, Tensor> seq;\n\n public Module538(int in_channels, int out_channels) : base(String.Empty)\n {\n seq = Sequential(Conv2d(1, 32, 3),\n BatchNorm2d(32),\n ReLU(),\n Flatten(),\n LogSoftmax(1)\n );\n\n RegisterComponents();\n }\n\n public override torch.Tensor forward(torch.Tensor t)\n {\n return this.seq.call(t);\n }\n }\n\n [Fact]\n public void GruModuleWorksWithoutPassingH0()\n {\n var device = torch.cuda.is_available() ? torch.CUDA : torch.CPU;\n using var _ = NewDisposeScope();\n using (Tensor input = torch.randn(new long[] { 5, 3, 10 }, device: device),\n h0 = torch.randn(new long[] { 1, 3, 20 }, device: device))\n using (var gru = GRU(10, 20)) {\n gru.to(device);\n var (output, hN) = gru.call(input);\n Assert.Equal(h0.shape, hN.shape);\n Assert.Equal(new long[] { input.shape[0], input.shape[1], 20 }, output.shape);\n }\n }\n\n [Fact]\n public void LstmModuleWorksWithoutPassingH0C0()\n {\n var device = torch.cuda.is_available() ? torch.CUDA : torch.CPU;\n using var _ = NewDisposeScope();\n using (Tensor input = torch.randn(new long[] { 5, 3, 10 }, device: device),\n h0 = torch.randn(new long[] { 1, 3, 20 }, device: device))\n using (var lstm = LSTM(10, 20)) {\n lstm.to(device);\n var (output, hN, hX) = lstm.call(input);\n Assert.Equal(h0.shape, hN.shape);\n Assert.Equal(h0.shape, hX.shape);\n Assert.Equal(new long[] { input.shape[0], input.shape[1], 20 }, output.shape);\n }\n }\n\n [Fact]\n public void RnnModuleWorksWithoutPassingH0()\n {\n var device = torch.cuda.is_available() ? torch.CUDA : torch.CPU;\n using var _ = NewDisposeScope();\n using (Tensor input = torch.randn(new long[] { 5, 3, 10 }, device: device),\n h0 = torch.randn(new long[] { 1, 3, 20 }, device: device))\n using (var rnn = RNN(10, 20)) {\n rnn.to(device);\n var (output, hN) = rnn.call(input);\n Assert.Equal(h0.shape, hN.shape);\n Assert.Equal(new long[] { input.shape[0], input.shape[1], 20 }, output.shape);\n }\n }\n\n [Fact]\n public void ValidateBug618()\n {\n if (torch.cuda.is_available()) {\n using var _ = NewDisposeScope();\n var mean = torch.randn(new long[] { 32, 3, 3 }, device: torch.CUDA);\n var tmp = torch.randn(new long[] { 3, 3 }, device: torch.CUDA);\n var log_std = tmp.expand_as(mean);\n var std = exp(log_std);\n var dist = torch.distributions.Normal(mean, std);\n dist.sample();// error\n }\n }\n\n [Fact]\n public void ValidateBug653()\n {\n var x = torch.linspace(0, 1, 100, dtype: torch.float32);\n var y = torch.linspace(0, 1, 100, dtype: torch.float64);\n var z = x.to(y);\n Assert.Equal(torch.float64, z.dtype);\n }\n\n [Fact]\n public void ValidateBug679()\n {\n // Per bug report.\n // https://github.com/dotnet/TorchSharp/issues/679\n //\n var dtype = torch.complex64;\n var spec = torch.rand(1, 1024, 500, dtype: dtype);\n Assert.Throws<System.Runtime.InteropServices.ExternalException>(() => torch.istft(spec, 512, 160, 400, null));\n\n spec = torch.rand(1, 512, 500, dtype: dtype);\n var x = torch.istft(spec, 512, 160, 400, null);\n\n spec = torch.rand(1, 257, 500, dtype: dtype);\n x = torch.istft(spec, 512, 160, 400, null);\n\n dtype = torch.complex128;\n spec = torch.rand(1, 1024, 500, dtype: dtype);\n Assert.Throws<System.Runtime.InteropServices.ExternalException>(() => torch.istft(spec, 512, 160, 400, null));\n\n spec = torch.rand(1, 512, 500, dtype: dtype);\n x = torch.istft(spec, 512, 160, 400, null);\n\n spec = torch.rand(1, 257, 500, dtype: dtype);\n x = torch.istft(spec, 512, 160, 400, null);\n }\n\n [Fact]\n public void ValidateBug715()\n {\n var resnet = resnet18();\n var resnetlist = resnet.named_children();\n var list = resnetlist.Take(6).Select(x => (x.name, (nn.Module<Tensor, Tensor>)x.module));\n var bone = nn.Sequential(list);\n\n var x = torch.zeros(1, 3, 64, 160);\n\n // This should not blow up.\n var tmp = bone.call(x);\n }\n\n [Fact]\n [TestOf(nameof(Modules.Categorical.probs))]\n public void ValidateBug836()\n {\n int nSamples = Convert.ToInt32(5e3);\n random.manual_seed(1);\n Tensor actionLogits = ones(nSamples, 2);\n Modules.Categorical distribution = new(logits: actionLogits);\n Tensor actions = distribution.sample();\n Tensor entropy = distribution.entropy();\n Tensor log_prob = distribution.log_prob(actions);\n var eMean = entropy.mean().ToSingle();\n var lMean = log_prob.mean().ToSingle();\n\n Assert.Equal(0.693147, eMean, 0.0001);\n Assert.Equal(-0.693147, lMean, 0.0001);\n }\n\n [Fact]\n [TestOf(nameof(torch.distributions.Bernoulli))]\n public void ValidateBug838()\n {\n int nSamples = Convert.ToInt32(5e6);\n random.manual_seed(1);\n Tensor actionLogits = rand(nSamples, 2);\n // This should not blow up.\n var distribution = distributions.Bernoulli(logits: actionLogits);\n }\n\n [Fact]\n public void ValidateMultiStepLR()\n {\n var gen = new Generator(4711);\n TestTraining.CreateLinearLayers(gen, out var lin1, out var lin2);\n TestTraining.CreateDataAndLabels(gen, out var x, out var y);\n\n var seq = Sequential((\"lin1\", lin1), (\"relu1\", ReLU()), (\"lin2\", lin2));\n\n double learning_rate = 0.1;\n var optimizer = torch.optim.SGD(seq.parameters(), learning_rate);\n var scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, new int[] { 3, 5, 7 }, 0.9);\n\n optimizer.zero_grad();\n optimizer.step();\n scheduler.step(1);\n Assert.Equal(0.1, optimizer.ParamGroups.First().LearningRate);\n scheduler.step(2);\n Assert.Equal(0.1, optimizer.ParamGroups.First().LearningRate);\n scheduler.step(3);\n Assert.Equal(0.09, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(4);\n Assert.Equal(0.09, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(5);\n Assert.Equal(0.09 * 0.9, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(6);\n scheduler.step(7);\n Assert.Equal(0.09 * 0.9 * 0.9, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(8);\n Assert.Equal(0.09 * 0.9 * 0.9, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(9);\n Assert.Equal(0.09 * 0.9 * 0.9, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(10);\n Assert.Equal(0.09 * 0.9 * 0.9, optimizer.ParamGroups.First().LearningRate, 0.00001);\n }\n\n\n\n [Fact]\n public void ValidatePolynomialLR()\n {\n {\n // Linear decay\n var gen = new Generator(4711);\n TestTraining.CreateLinearLayers(gen, out var lin1, out var lin2);\n TestTraining.CreateDataAndLabels(gen, out var x, out var y);\n\n var seq = Sequential((\"lin1\", lin1), (\"relu1\", ReLU()), (\"lin2\", lin2));\n\n double learning_rate = 0.1;\n var optimizer = torch.optim.SGD(seq.parameters(), learning_rate);\n var scheduler = torch.optim.lr_scheduler.PolynomialLR(optimizer, 10, 1);\n\n optimizer.zero_grad();\n optimizer.step();\n scheduler.step(1);\n Assert.Equal(0.09, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(2);\n Assert.Equal(0.08, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(3);\n Assert.Equal(0.07, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(4);\n Assert.Equal(0.06, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(5);\n Assert.Equal(0.05, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(6);\n scheduler.step(7);\n Assert.Equal(0.03, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(8);\n Assert.Equal(0.02, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(9);\n Assert.Equal(0.01, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(10);\n Assert.Equal(0.0, optimizer.ParamGroups.First().LearningRate, 0.00001);\n }\n {\n // Squared decay\n var gen = new Generator(4711);\n TestTraining.CreateLinearLayers(gen, out var lin1, out var lin2);\n TestTraining.CreateDataAndLabels(gen, out var x, out var y);\n\n var seq = Sequential((\"lin1\", lin1), (\"relu1\", ReLU()), (\"lin2\", lin2));\n\n double learning_rate = 0.1;\n var optimizer = torch.optim.SGD(seq.parameters(), learning_rate);\n var scheduler = torch.optim.lr_scheduler.PolynomialLR(optimizer, 10, 2);\n\n optimizer.zero_grad();\n optimizer.step();\n scheduler.step(1);\n Assert.Equal(0.081, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(2);\n Assert.Equal(0.064, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(3);\n Assert.Equal(0.049, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(4);\n Assert.Equal(0.036, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(5);\n Assert.Equal(0.025, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(6);\n scheduler.step(7);\n Assert.Equal(0.009, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(8);\n Assert.Equal(0.004, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(9);\n Assert.Equal(0.001, optimizer.ParamGroups.First().LearningRate, 0.00001);\n scheduler.step(10);\n Assert.Equal(0.0, optimizer.ParamGroups.First().LearningRate, 0.00001);\n }\n }\n\n\n [Fact]\n public void Validate845()\n {\n var module1 = new Module845(10, 10);\n var module2 = new Module845(10, 10);\n var module3 = new Module845(10, 10);\n\n var dev = torch.cuda.is_available() ? CUDA : CPU;\n\n module1.to(dev);\n module1.validate(float32, dev.type);\n\n module2.to(dev, float64);\n module2.validate(float64, dev.type);\n\n module3.to(float64);\n module3.validate(float64, CPU.type);\n }\n\n internal class Module845 : Module<Tensor, Tensor>\n {\n private Module<Tensor, Tensor> seq;\n\n public Module845(int in_channels, int out_channels) : base(String.Empty)\n {\n seq = Sequential(Conv2d(1, 32, 3),\n ReLU(),\n Flatten(),\n LogSoftmax(1)\n );\n\n register_buffer(\"test\", torch.ones(10, 10));\n RegisterComponents();\n }\n\n public override torch.Tensor forward(torch.Tensor t)\n {\n return this.seq.call(t);\n }\n\n public void validate(ScalarType expected, DeviceType devType)\n {\n foreach (var (name, buffer) in named_buffers()) {\n Assert.Equal(expected, buffer.dtype);\n Assert.Equal(devType, buffer.device_type);\n }\n }\n }\n\n [Fact]\n public void Validate851()\n {\n var a = torch.tensor(new long[] { 100, 200, 300, 400 }, new long[] { 1, 4 });\n a.print();\n var str = a.ToString(TorchSharp.TensorStringStyle.Numpy);\n Assert.Equal(\"[[100, 200, 300, 400]]\", str);\n }\n\n [Fact]\n public void Validate852()\n {\n float[] a = new float[12];\n var x = torch.as_tensor(a);\n }\n\n [Fact]\n public void Validate877()\n {\n if (torch.cuda.is_available()) {\n var device = torch.CUDA;\n torch.TryInitializeDeviceType(device.type);\n var train = new GitBlockTest(\"test\", device);\n\n var p0 = train.named_parameters().Select(p => p.name).ToArray();\n\n train.to(device);\n\n int named_parameters_1 = train.named_parameters().Count();\n train.to(torch.CUDA);\n int named_parameters_2 = train.named_parameters().Count();\n\n Assert.Equal(named_parameters_1, named_parameters_2);\n }\n }\n\n\n class GitTestCnn : Module<Tensor, Tensor>\n {\n private readonly TorchSharp.Modules.Sequential layers0;\n\n public GitTestCnn(string name, Device? device = null) : base(name)\n {\n var modules = new List<(string, Module<Tensor, Tensor>)>();\n modules.Add(($\"{name}-conv2d-1\", Conv2d(1, 4, kernelSize: (1L, 1L), stride: (1L, 1L), padding: (0L, 0L), paddingMode: PaddingModes.Replicate, bias: false)));\n layers0 = Sequential(modules);\n\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor t)\n {\n var t1 = layers0.call(t).squeeze_(3);\n return t1;\n }\n }\n\n class GitTestGru : Module<Tensor, Tensor>\n {\n private TorchSharp.Modules.GRU layers1;\n private TorchSharp.Modules.GRU layers2;\n private Tensor init_h0;\n private Tensor init_h1;\n\n public GitTestGru(string name, Device? device = null) : base(name)\n {\n layers1 = nn.GRU(1, 4, batchFirst: true);\n layers2 = nn.GRU(4, 4, batchFirst: true);\n\n var state_size = new long[] { 1, 1, 4 };\n init_h0 = torch.nn.Parameter(torch.zeros(state_size, device: device));\n init_h1 = torch.nn.Parameter(torch.zeros(state_size, device: device));\n\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor input)\n {\n var (rnn_output, states_h0) = layers1.call(input, init_h0);\n init_h0 = states_h0.detach_();\n var (_, states_h1) = layers2.call(rnn_output, init_h1);\n init_h1 = states_h1.detach_();\n var x2 = states_h1[-1];\n return x2;\n }\n }\n\n class GitBlockTest : Module<Tensor, Tensor>\n {\n private readonly Module<Tensor, Tensor> sequence_layers;\n\n public GitBlockTest(string name, Device? device = null) : base(name)\n {\n var modules = nn.ModuleDict<Module<Tensor, Tensor>>();\n modules.Add((\"cnn-1\", new GitTestCnn(\"GitTest\", device)));\n modules.Add((\"rnn-2\", new GitTestGru(\"GitTestGru\", device)));\n sequence_layers = Sequential(modules.values());\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor input)\n {\n var t0 = sequence_layers.call(input);\n return t0;\n }\n }\n\n\n [Fact]\n public void Validate912()\n {\n var test = new Test_912(2);\n Dictionary<string, Tensor> sd = test.state_dict(); // No layer2.modules keyword\n Assert.Contains(sd.Keys, k => k.StartsWith(\"layer2.modules\"));\n }\n\n public class Test_912 : nn.Module\n {\n public nn.Module layer;\n public nn.Module layer2;\n\n public Test_912(int layernum) : base(\"Test_912\")\n {\n layer = nn.Linear(16, 2);\n layer2 = new Test2_912((from l in Enumerable.Range(0, layernum)\n select new Test3_912()).ToArray(),\n (from l in Enumerable.Range(0, layernum)\n select new Test3_912()).ToArray());\n this.RegisterComponents();\n }\n }\n public class Test2_912 : nn.Module\n {\n public new Modules.ModuleList<Test3_912> modules;\n public Modules.ModuleList<nn.Module> modules2;\n public nn.Module layer;\n public Test2_912(Test3_912[] ms, nn.Module[] ms2) : base(\"Test2_912\")\n {\n layer = nn.Linear(16, 2);\n modules = nn.ModuleList(ms);\n modules2 = nn.ModuleList(ms2);\n this.RegisterComponents();\n }\n }\n public class Test3_912 : nn.Module\n {\n public nn.Module layer;\n public Test3_912() : base(\"Test3_912\")\n {\n layer = nn.Linear(16, 2);\n this.RegisterComponents();\n }\n }\n\n [Fact]\n public void Validate971()\n {\n var t = torch.tensor(new double[] { 0, 1, 2 });\n var std_dev = t.std(false).item<double>();\n\n Assert.Equal(0.8165, std_dev, 0.0001);\n }\n\n [Fact(Skip = \"Takes too long to run to completion.\")]\n static void Validate1057()\n {\n if (torch.cuda_is_available()) {\n var device = torch.CUDA;\n\n for (int i = 0; i < 25; i++) {\n using (var _ = torch.NewDisposeScope()) {\n var data = torch.randn(200000, 3, 32, 32).to(device).requires_grad_(true);\n }\n }\n }\n }\n }\n}" }, { "alpha_fraction": 0.5044707655906677, "alphanum_fraction": 0.505094587802887, "avg_line_length": 40.10256576538086, "blob_id": "7c952ddcb84dd69e220e002731fd0d0550a52e77", "content_id": "992f951b9f2d0357343dac1797d74c6ab75010c0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4809, "license_type": "permissive", "max_line_length": 133, "num_lines": 117, "path": "/src/TorchSharp/JIT/CompilationUnit.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing TorchSharp.PInvoke;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class jit\n {\n /// <summary>\n /// Represents a TorchScript compilation unit, i.e. a Python script file.\n /// </summary>\n /// <example>\n /// var cu = torch.jit.compile(@\"\n /// def relu_script(a, b):\n /// return torch.relu(a + b)\n /// \");\n ///\n /// var y = cu.invoke(\"relu_script\", torch.randn(10));\n /// </example>\n /// <remarks>\n /// Currently, scripts are limited to defining functions. Classes will be ignored.\n /// </remarks>\n public class CompilationUnit : IDisposable\n {\n internal CompilationUnit(IntPtr handle)\n {\n this.handle = handle;\n }\n\n ~CompilationUnit() => Dispose(false);\n\n /// <summary>\n /// Releases the storage.\n /// </summary>\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n /// <summary>\n /// Implements the .NET Dispose pattern.\n /// </summary>\n protected virtual void Dispose(bool disposing)\n {\n if (disposing && handle != IntPtr.Zero) {\n handle = IntPtr.Zero;\n }\n }\n\n internal IntPtr handle;\n\n /// <summary>\n /// Invoke a function from the compilation unit.\n /// </summary>\n /// <param name=\"name\">The name of the function.</param>\n /// <param name=\"objs\">Function arguments.</param>\n public object invoke(string name, params object[] objs)\n {\n if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(\"method name\");\n\n TensorOrScalar[] ptrArray = null;\n sbyte typeCode = 0;\n\n using (var parray = new IndexedPinnedArrays<TensorOrScalar>()) {\n\n var tRefsHandle = ScriptModule.DetermineArgumentTypeRefs(objs, out var count, parray);\n\n var allocated = parray.Count;\n\n THSJIT_CompilationUnit_Invoke(handle, name, tRefsHandle, count, parray.CreateArray, out typeCode, allocated);\n torch.CheckForErrors();\n ptrArray = parray[allocated];\n\n return ScriptModule.ProcessReturnValue(name, parray, ptrArray, typeCode);\n }\n }\n\n /// <summary>\n /// Invoke a function from the compilation unit.\n /// </summary>\n /// <typeparam name=\"TResult\">The return type of the TorchScript function.</typeparam>\n /// <param name=\"name\">The name of the function.</param>\n /// <param name=\"inputs\">Function arguments.</param>\n public TResult invoke<TResult>(string name, params object[] inputs) => (TResult)invoke(name, inputs);\n\n /// <summary>\n /// Invoke a function from the compilation unit.\n /// </summary>\n /// <typeparam name=\"T\">The type of all function arguments.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the TorchScript function.</typeparam>\n /// <param name=\"name\">The name of the function.</param>\n /// <param name=\"inputs\">Function arguments.</param>\n public TResult invoke<T, TResult>(string name, params T[] inputs) => (TResult)invoke(name, inputs);\n }\n\n /// <summary>\n /// Create a TorchScript compilation unit containing TorchScript-compliant Python from a string.\n /// </summary>\n /// <param name=\"script\">A string with Python code expressing a set of TorchScript functions.</param>\n /// <returns></returns>\n public static CompilationUnit compile(string script)\n {\n if (string.IsNullOrEmpty(script))\n throw new ArgumentNullException(\"empty script\");\n\n var result = THSJIT_compile(script);\n if (result == IntPtr.Zero)\n CheckForErrors();\n return new CompilationUnit(result);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5798611044883728, "alphanum_fraction": 0.5819978713989258, "avg_line_length": 39.25806427001953, "blob_id": "92d5292413ef9a197ebc4f6e473e64722d84a8c2", "content_id": "68bff2b606ff3d1079d5939b2eb016ccdf3d80fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3744, "license_type": "permissive", "max_line_length": 149, "num_lines": 93, "path": "/src/TorchSharp/Distributions/HalfCauchy.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n using static torch.distributions;\n\n namespace Modules\n {\n /// <summary>\n /// Creates a half-Cauchy distribution parameterized by `scale`\n /// </summary>\n public class HalfCauchy : TransformedDistribution\n {\n internal HalfCauchy(Tensor scale, torch.Generator generator = null) :\n base(Cauchy(torch.tensor(0).to(scale.dtype), scale, generator), new torch.distributions.transforms.AbsTransform(), generator)\n {\n this.scale = scale?.alias().DetachFromDisposeScope();\n }\n\n public Tensor scale { get; private set; }\n\n public override Tensor mean => torch.full(ExtendedShape(), double.PositiveInfinity, dtype: scale.dtype, device: scale.device);\n\n public override Tensor mode => torch.zeros_like(scale);\n\n public override Tensor variance => base_distribution.variance;\n\n public override Tensor log_prob(Tensor value)\n {\n using var _ = torch.NewDisposeScope();\n value = torch.as_tensor(value, scale.dtype, scale.device);\n var lp = base_distribution.log_prob(value) + Math.Log(2);\n lp = torch.where(value >= 0, lp, double.NegativeInfinity);\n return lp.MoveToOuterDisposeScope();\n }\n\n public override Tensor cdf(Tensor value)\n {\n return 2 * base_distribution.cdf(value) - 1;\n }\n\n public override Tensor icdf(Tensor value)\n {\n return base_distribution.icdf((value + 1) / 2);\n }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n public override Tensor entropy()\n {\n return base_distribution.entropy() - Math.Log(2);\n }\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n public override Distribution expand(Size batch_shape, Distribution instance = null)\n {\n var newDistribution = ((instance == null)\n ? new HalfCauchy(scale.expand(batch_shape), generator)\n : instance) as HalfCauchy;\n return base.expand(batch_shape, newDistribution);\n }\n }\n }\n\n\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a half-Cauchy distribution parameterized by `scale`\n /// </summary>\n /// <param name=\"scale\">Scale parameter of the distribution.</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static HalfCauchy HalfCauchy(Tensor scale, torch.Generator generator = null)\n {\n\n return new HalfCauchy(scale, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5810214281082153, "alphanum_fraction": 0.5895333886146545, "avg_line_length": 43.05555725097656, "blob_id": "2e9c9148c01ddcfbb74ec7390dc91c8e9407c38f", "content_id": "e06eecafa156e8d3ec4894a11ff3aff1382bf5d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3172, "license_type": "permissive", "max_line_length": 169, "num_lines": 72, "path": "/src/TorchSharp/NN/Dropout1d.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a Dropout2d module.\n /// </summary>\n public sealed class Dropout1d : torch.nn.Module<Tensor, Tensor>\n {\n internal Dropout1d(double p = 0.5, bool inplace = false) : base(nameof(Dropout1d))\n {\n this.p = p;\n this.inplace = inplace;\n }\n\n public override Tensor forward(Tensor tensor)\n {\n if (tensor.ndim != 3)\n throw new ArgumentException(\"tensor passed to Dropout1d must be of the shape (N,C,L\");\n return torch.nn.functional.dropout1d(tensor, this.p, this.training, this.inplace);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n\n private bool inplace;\n private double p;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Randomly zero out entire channels (a channel is a 2D feature map, e.g., the jj -th channel of the ii -th sample in the batched input is a 2D tensor).\n /// Each channel will be zeroed out independently on every forward call with probability p using samples from a Bernoulli distribution.\n /// </summary>\n /// <param name=\"p\">Probability of an element to be zeroed. Default: 0.5</param>\n /// <param name=\"inplace\">If set to true, will do this operation in-place. Default: false</param>\n /// <returns></returns>\n public static Dropout1d Dropout1d(double p = 0.5, bool inplace = false)\n {\n return new Dropout1d(p, inplace);\n }\n\n public static partial class functional\n {\n\n /// <summary>\n /// Randomly zero out entire channels (a channel is a 2D feature map, e.g., the jj -th channel of the ii -th sample in the batched input is a 2D tensor).\n /// Each channel will be zeroed out independently on every forward call with probability p using samples from a Bernoulli distribution.\n /// </summary>\n /// <returns></returns>\n public static Tensor dropout1d(Tensor input, double p = 0.5, bool training = true, bool inplace = false)\n {\n return dropout2d(input.unsqueeze(-1), p, training, inplace).squeeze(-1);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.653333306312561, "alphanum_fraction": 0.653333306312561, "avg_line_length": 29.882352828979492, "blob_id": "34210d34ce6bcbcf692763b5f024f55128db13dc", "content_id": "22956e9b3b88cef5015cb37011ee0697624b5ebf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 525, "license_type": "permissive", "max_line_length": 130, "num_lines": 17, "path": "/src/TorchVision/ITransform.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n /// <summary>\n /// This is essentially an alias. We're keeping it because it was\n /// introduced and thus leaving it in will avoid a breaking change.\n /// </summary>\n public interface ITransform : nn.IModule<Tensor, Tensor>\n {\n }\n }\n}\n" }, { "alpha_fraction": 0.4776082932949066, "alphanum_fraction": 0.48599597811698914, "avg_line_length": 61.72922897338867, "blob_id": "3ef1848b6a52f29192832d6835a59db4e24c58b4", "content_id": "dd43d825d25a8ffed0cae3943d69322edb6a62f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 20387, "license_type": "permissive", "max_line_length": 198, "num_lines": 325, "path": "/src/TorchSharp/Utils/tensorboard/Summary.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.IO;\nusing Google.Protobuf;\nusing SkiaSharp;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class utils\n {\n public static partial class tensorboard\n {\n public static partial class Summary\n {\n private static int calc_scale_factor(Tensor tensor)\n => tensor.dtype == ScalarType.Byte || tensor.dtype == ScalarType.Int8 ? 1 : 255;\n\n /// <summary>\n /// Outputs a `Summary` protocol buffer with a histogram.\n /// The generated\n /// [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto)\n /// has one summary value containing a histogram for `values`.\n /// This op reports an `InvalidArgument` error if any value is not finite.\n ///\n /// https://github.com/pytorch/pytorch/blob/1.7/torch/utils/tensorboard/summary.py#L283\n /// </summary>\n /// <param name=\"name\"> A name for the generated node. Will also serve as a series name in TensorBoard. </param>\n /// <param name=\"values\"> A real numeric `Tensor`. Any shape. Values to use to build the histogram. </param>\n /// <param name=\"bins\"></param>\n /// <param name=\"max_bins\"></param>\n /// <returns> A scalar `Tensor` of type `string`. The serialized `Summary` protocol buffer. </returns>\n public static Tensorboard.Summary histogram(string name, Tensor values, Tensor bins, long? max_bins = null)\n {\n if (values.device.type != DeviceType.CPU)\n values = values.cpu();\n Tensorboard.HistogramProto hist = make_histogram(values, bins, max_bins);\n var summary = new Tensorboard.Summary();\n summary.Value.Add(new Tensorboard.Summary.Types.Value() { Tag = name, Histo = hist });\n return summary;\n }\n\n /// <summary>\n /// Outputs a `Summary` protocol buffer with a histogram.\n /// The generated\n /// [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto)\n /// has one summary value containing a histogram for `values`.\n /// This op reports an `InvalidArgument` error if any value is not finite.\n ///\n /// https://github.com/pytorch/pytorch/blob/1.7/torch/utils/tensorboard/summary.py#L283\n /// </summary>\n /// <param name=\"name\"> A name for the generated node. Will also serve as a series name in TensorBoard. </param>\n /// <param name=\"values\"> A real numeric `Tensor`. Any shape. Values to use to build the histogram. </param>\n /// <param name=\"bins\"></param>\n /// <param name=\"max_bins\"></param>\n /// <returns> A scalar `Tensor` of type `string`. The serialized `Summary` protocol buffer. </returns>\n public static Tensorboard.Summary histogram(string name, Tensor values, HistogramBinSelector bins, long? max_bins = null)\n {\n Tensorboard.HistogramProto hist = make_histogram(values, bins, max_bins);\n var summary = new Tensorboard.Summary();\n summary.Value.Add(new Tensorboard.Summary.Types.Value() { Tag = name, Histo = hist });\n return summary;\n }\n\n /// <summary>\n /// Convert values into a histogram proto using logic from histogram.cc.\n ///\n /// https://github.com/pytorch/pytorch/blob/1.7/torch/utils/tensorboard/summary.py#L304\n /// </summary>\n /// <param name=\"values\"></param>\n /// <param name=\"bins\"></param>\n /// <param name=\"max_bins\"></param>\n /// <returns></returns>\n /// <exception cref=\"ArgumentException\"></exception>\n public static Tensorboard.HistogramProto make_histogram(Tensor values, Tensor bins, long? max_bins = null)\n {\n if (values.numel() == 0)\n throw new ArgumentException(\"The input has no element.\");\n if (values.dtype != ScalarType.Float64)\n values = values.to_type(ScalarType.Float64);\n values = values.reshape(-1);\n (Tensor counts, Tensor limits) = torch.histogram(values, bins);\n return make_histogram(values, counts, limits, max_bins);\n }\n\n /// <summary>\n /// Convert values into a histogram proto using logic from histogram.cc.\n ///\n /// https://github.com/pytorch/pytorch/blob/1.7/torch/utils/tensorboard/summary.py#L304\n /// </summary>\n /// <param name=\"values\"></param>\n /// <param name=\"bins\"></param>\n /// <param name=\"max_bins\"></param>\n /// <returns></returns>\n /// <exception cref=\"ArgumentException\"></exception>\n public static Tensorboard.HistogramProto make_histogram(Tensor values, HistogramBinSelector bins, long? max_bins = null)\n {\n if (values.numel() == 0)\n throw new ArgumentException(\"The input has no element.\");\n if (values.dtype != ScalarType.Float64)\n values = values.to_type(ScalarType.Float64);\n values = values.reshape(-1);\n (Tensor counts, Tensor limits) = torch.histogram(values, bins);\n return make_histogram(values, counts, limits, max_bins);\n }\n\n private static Tensorboard.HistogramProto make_histogram(Tensor values, Tensor counts, Tensor limits, long? max_bins = null)\n {\n long num_bins = counts.shape[0];\n if (max_bins != null && num_bins > max_bins) {\n long subsampling = num_bins / max_bins.Value;\n long subsampling_remainder = num_bins % subsampling;\n if (subsampling_remainder != 0)\n counts = nn.functional.pad(counts, (0, subsampling - subsampling_remainder), PaddingModes.Constant, 0);\n counts = counts.reshape(-1, subsampling).sum(1);\n Tensor new_limits = empty(new long[] { counts.numel() + 1 }, limits.dtype);\n new_limits[TensorIndex.Slice(null, -1)] = limits[TensorIndex.Slice(null, -1, subsampling)];\n new_limits[-1] = limits[-1];\n limits = new_limits;\n }\n\n Tensor cum_counts = cumsum(greater(counts, 0), 0);\n Tensor search_value = empty(2, cum_counts.dtype);\n search_value[0] = 0;\n search_value[1] = cum_counts[-1] - 1;\n Tensor search_result = searchsorted(cum_counts, search_value, right: true);\n long start = search_result[0].item<long>();\n long end = search_result[1].item<long>() + 1;\n counts = start > 0 ? counts[TensorIndex.Slice(start - 1, end)] : concatenate(new Tensor[] { tensor(new[] { 0 }), counts[TensorIndex.Slice(stop: end)] });\n limits = limits[TensorIndex.Slice(start, end + 1)];\n\n if (counts.numel() == 0 || limits.numel() == 0)\n throw new ArgumentException(\"The histogram is empty, please file a bug report.\");\n\n Tensor sum_sq = values.dot(values);\n Tensorboard.HistogramProto histogramProto = new Tensorboard.HistogramProto() {\n Min = values.min().item<double>(),\n Max = values.max().item<double>(),\n Num = values.shape[0],\n Sum = values.sum().item<double>(),\n SumSquares = sum_sq.item<double>(),\n };\n histogramProto.BucketLimit.AddRange(limits.data<double>().ToArray());\n histogramProto.Bucket.AddRange(counts.data<double>().ToArray());\n return histogramProto;\n }\n\n /// <summary>\n /// Outputs a `Summary` protocol buffer with images.\n /// The summary has up to `max_images` summary values containing images. The\n /// images are built from `tensor` which must be 3-D with shape `[height, width,\n /// channels]` and where `channels` can be:\n /// * 1: `tensor` is interpreted as Grayscale.\n /// * 3: `tensor` is interpreted as RGB.\n /// * 4: `tensor` is interpreted as RGBA.\n /// The `name` in the outputted Summary.Value protobufs is generated based on the\n /// name, with a suffix depending on the max_outputs setting:\n /// * If `max_outputs` is 1, the summary value tag is '*name*/image'.\n /// * If `max_outputs` is greater than 1, the summary value tags are\n /// generated sequentially as '*name*/image/0', '*name*/image/1', etc.\n /// </summary>\n /// <param name=\"tag\"> A name for the generated node. Will also serve as a series name in TensorBoard. </param>\n /// <param name=\"tensor\">\n /// A 3-D `uint8` or `float32` `Tensor` of shape `[height, width,\n /// channels]` where `channels` is 1, 3, or 4.\n /// 'tensor' can either have values in [0, 1] (float32) or [0, 255] (uint8).\n /// The image() function will scale the image values to [0, 255] by applying\n /// a scale factor of either 1 (uint8) or 255 (float32). Out-of-range values\n /// will be clipped.\n /// </param>\n /// <param name=\"rescale\"> Rescale image size </param>\n /// <param name=\"dataformats\"> Image data format specification of the form CHW, HWC, HW, WH, etc. </param>\n /// <returns> A scalar `Tensor` of type `string`. The serialized `Summary` protocol buffer. </returns>\n public static Tensorboard.Summary image(string tag, Tensor tensor, double rescale = 1, string dataformats = \"NCHW\")\n {\n tensor = utils.convert_to_HWC(tensor, dataformats);\n int scale_factor = calc_scale_factor(tensor);\n tensor = tensor.to_type(ScalarType.Float32);\n tensor = (tensor * scale_factor).clip(0, 255).to_type(ScalarType.Byte);\n Tensorboard.Summary.Types.Image image = make_image(tensor, rescale);\n var summary = new Tensorboard.Summary();\n summary.Value.Add(new Tensorboard.Summary.Types.Value() { Tag = tag, Image = image });\n return summary;\n }\n\n /// <summary>\n /// Outputs a `Summary` protocol buffer with images.\n /// </summary>\n /// <param name=\"tag\"> A name for the generated node. Will also serve as a series name in TensorBoard. </param>\n /// <param name=\"file_name\"> local image filename </param>\n /// <param name=\"rescale\"> Rescale image size </param>\n /// <returns> A scalar `Tensor` of type `string`. The serialized `Summary` protocol buffer. </returns>\n public static Tensorboard.Summary image(string tag, string file_name, double rescale = 1)\n {\n using var img = SKBitmap.Decode(file_name);\n Tensorboard.Summary.Types.Image image = make_image(img, rescale);\n var summary = new Tensorboard.Summary();\n summary.Value.Add(new Tensorboard.Summary.Types.Value() { Tag = tag, Image = image });\n return summary;\n }\n\n /// <summary>\n /// Convert a tensor representation of an image to Image protobuf\n /// \n /// https://github.com/pytorch/pytorch/blob/master/torch/utils/tensorboard/summary.py#L481\n /// </summary>\n /// <param name=\"tensor\"> HWC(0~255) image tensor </param>\n /// <param name=\"rescale\"> Rescale image size </param>\n /// <returns></returns>\n public static Tensorboard.Summary.Types.Image make_image(Tensor tensor, double rescale = 1)\n {\n using SKBitmap skBmp = TensorToSKBitmap(tensor);\n return make_image(skBmp, rescale);\n }\n\n /// <summary>\n /// Convert an image to Image protobuf\n /// \n /// https://github.com/pytorch/pytorch/blob/master/torch/utils/tensorboard/summary.py#L495\n /// </summary>\n /// <param name=\"img\"> Image </param>\n /// <param name=\"rescale\"> Rescale image size </param>\n /// <returns></returns>\n internal static Tensorboard.Summary.Types.Image make_image(SKBitmap img, double rescale = 1)\n {\n using var image = img.Copy();\n byte[] bmpData = image.Resize(new SKSizeI((int)(image.Width * rescale), (int)(image.Height * rescale)), SKFilterQuality.High).Encode(SKEncodedImageFormat.Png, 100).ToArray();\n return new Tensorboard.Summary.Types.Image() { Height = image.Height, Width = image.Width, Colorspace = 4, EncodedImageString = ByteString.CopyFrom(bmpData) };\n }\n\n /// <summary>\n /// https://github.com/pytorch/pytorch/blob/master/torch/utils/tensorboard/summary.py#L509\n /// </summary>\n /// <param name=\"tag\"> A name for the generated node. Will also serve as a series name in TensorBoard. </param>\n /// <param name=\"tensor\"> Video data </param>\n /// <param name=\"fps\"> Frames per second </param>\n /// <returns></returns>\n public static Tensorboard.Summary video(string tag, Tensor tensor, int fps)\n {\n tensor = utils.prepare_video(tensor);\n int scale_factor = calc_scale_factor(tensor);\n tensor = tensor.to_type(ScalarType.Float32);\n tensor = (tensor * scale_factor).clip(0, 255).to_type(ScalarType.Byte);\n Tensorboard.Summary.Types.Image video = make_video(tensor, fps);\n var summary = new Tensorboard.Summary();\n summary.Value.Add(new Tensorboard.Summary.Types.Value() { Tag = tag, Image = video });\n return summary;\n }\n\n /// <summary>\n /// https://github.com/pytorch/pytorch/blob/master/torch/utils/tensorboard/summary.py#L520\n /// </summary>\n /// <param name=\"tensor\"> Video data </param>\n /// <param name=\"fps\"> Frames per second </param>\n /// <returns></returns>\n public static Tensorboard.Summary.Types.Image make_video(Tensor tensor, int fps)\n {\n int h = (int)tensor.shape[1];\n int w = (int)tensor.shape[2];\n using GifEncoder.Encoder encoder = new GifEncoder.Encoder();\n encoder.Start();\n encoder.SetRepeat(0);\n encoder.SetFrameRate(fps);\n foreach (var t in tensor.split(1)) {\n using SKBitmap bitmap = TensorToSKBitmap(t.squeeze());\n encoder.AddFrame(bitmap);\n }\n encoder.Finish();\n Stream stream = encoder.Output();\n stream.Position = 0;\n return new Tensorboard.Summary.Types.Image() { Height = h, Width = w, Colorspace = 4, EncodedImageString = ByteString.FromStream(stream) };\n }\n\n private static SKBitmap TensorToSKBitmap(Tensor tensor)\n {\n int h = (int)tensor.shape[0];\n int w = (int)tensor.shape[1];\n int c = (int)tensor.shape[2];\n\n byte[,,] data = tensor.cpu().data<byte>().ToNDArray() as byte[,,];\n var skBmp = new SKBitmap(w, h, SKColorType.Rgba8888, SKAlphaType.Opaque);\n int pixelSize = 4;\n unsafe {\n byte* pSkBmp = (byte*)skBmp.GetPixels().ToPointer();\n for (int i = 0; i < h; i++) {\n for (int j = 0; j < w; j++) {\n pSkBmp[j * pixelSize] = data[i, j, 0];\n pSkBmp[j * pixelSize + 1] = data[i, j, 1];\n pSkBmp[j * pixelSize + 2] = data[i, j, 2];\n pSkBmp[j * pixelSize + 3] = c == 4 ? data[i, j, 3] : (byte)255;\n }\n pSkBmp += skBmp.Info.RowBytes;\n }\n }\n\n return skBmp;\n }\n\n /// <summary>\n /// https://github.com/pytorch/pytorch/blob/master/torch/utils/tensorboard/summary.py#L630\n /// </summary>\n /// <param name=\"tag\"> Data identifier </param>\n /// <param name=\"text\"> String to save </param>\n /// <returns></returns>\n public static Tensorboard.Summary text(string tag, string text)\n {\n // TextPluginData(version=0).SerializeToString()\n // output: b''\n var pluginData = new Tensorboard.SummaryMetadata.Types.PluginData() { PluginName = \"text\", Content = ByteString.CopyFromUtf8(\"\") };\n var smd = new Tensorboard.SummaryMetadata() { PluginData = pluginData };\n var shapeProto = new Tensorboard.TensorShapeProto();\n shapeProto.Dim.Add(new Tensorboard.TensorShapeProto.Types.Dim() { Size = 1 });\n var tensor = new Tensorboard.TensorProto() { Dtype = Tensorboard.DataType.DtString, TensorShape = shapeProto };\n tensor.StringVal.Add(ByteString.CopyFromUtf8(text));\n\n var summary = new Tensorboard.Summary();\n summary.Value.Add(new Tensorboard.Summary.Types.Value() { Tag = tag + \"/text_summary\", Metadata = smd, Tensor = tensor });\n return summary;\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.48758187890052795, "alphanum_fraction": 0.488153338432312, "avg_line_length": 35.39680099487305, "blob_id": "a578ff80f7aa6e51bd378213265001222032b3e8", "content_id": "b066a165a737a33ddd61a1bbb171c37ada852dfc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 22749, "license_type": "permissive", "max_line_length": 186, "num_lines": 625, "path": "/src/TorchSharp/Optimizers/Optimizer.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using System.IO;\n using Modules;\n using TorchSharp.Utils;\n\n public static partial class torch\n {\n public static partial class optim\n {\n /// <summary>\n /// Base class for all optimizers.\n /// </summary>\n public abstract partial class Optimizer : IDisposable\n {\n /// <summary>\n /// Class wrapping PyTorch's optimzer object reference.\n /// </summary>\n internal sealed class HType : SafeHandle\n {\n public HType(IntPtr preexistingHandle, bool ownsHandle) : base(IntPtr.Zero, ownsHandle)\n {\n SetHandle(preexistingHandle);\n }\n\n public override bool IsInvalid => handle == IntPtr.Zero;\n\n // This is just for marshalling\n internal HType() : base(IntPtr.Zero, true)\n {\n }\n\n protected override bool ReleaseHandle()\n {\n THSNN_Optimizer_dispose(this);\n return true;\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n ReleaseHandle();\n }\n }\n }\n\n internal HType handle;\n\n /// <summary>\n /// Constructor used for optimizers implemented in native code.\n /// </summary>\n /// <param name=\"handle\"></param>\n protected Optimizer(IntPtr handle)\n {\n if (handle != IntPtr.Zero) {\n this.handle = new HType(handle, true);\n }\n }\n\n ~Optimizer()\n {\n Dispose(false);\n }\n\n /// <summary>\n /// Releases the storage.\n /// </summary>\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n /// <summary>\n /// Implements the .NET Dispose pattern.\n /// </summary>\n protected virtual void Dispose(bool disposing)\n {\n if (disposing && handle != null && !handle.IsInvalid) {\n handle.Dispose();\n handle.SetHandleAsInvalid();\n }\n }\n\n /// <summary>\n /// Sets the gradients of all parameters to zero.\n /// </summary>\n public virtual void zero_grad()\n {\n THSNN_Optimizer_zero_grad(handle);\n torch.CheckForErrors();\n }\n\n [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\n public delegate IntPtr LossClosure();\n\n /// <summary>\n /// Add a param group to the Optimizer s param_groups.\n /// </summary>\n /// <param name=\"param_group\"></param>\n /// <remarks>This can be useful when fine tuning a pre-trained network as frozen layers can be made trainable and added to the Optimizer as training progresses.</remarks>\n public virtual void add_param_group(ParamGroup param_group)\n {\n throw new NotImplementedException($\"add_param_group\");\n }\n\n\n /// <summary>\n /// Performs a single optimization step (parameter update).\n /// </summary>\n /// <param name=\"closure\">A closure that reevaluates the model and returns the loss. Optional for most optimizers.</param>\n /// <returns></returns>\n public virtual Tensor step(Func<Tensor> closure = null)\n {\n IntPtr res = (closure == null) ?\n THSNN_Optimizer_step(handle, null) :\n THSNN_Optimizer_step(handle, () => {\n return closure().DecoupleFromNativeHandle();\n });\n\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n\n return (res == IntPtr.Zero) ? null : new Tensor(res);\n }\n\n /// <summary>\n /// Get the parameters that the optimizer is handling.\n /// </summary>\n public virtual IEnumerable<Parameter> parameters()\n {\n IntPtr[] ptrArray;\n\n using (var pa = new PinnedArray<IntPtr>()) {\n THSNN_Optimizer_getParameters(handle, pa.CreateArray);\n torch.CheckForErrors();\n ptrArray = pa.Array;\n }\n return ptrArray.Select(x => new Parameter(x));\n }\n\n public class StateDictionary\n {\n internal StateDictionary() { Options = new List<OptimizerOptions>(); State = new List<OptimizerState>(); }\n\n public List<OptimizerOptions> Options { get; private set; }\n\n public List<OptimizerState> State { get; private set; }\n }\n\n public virtual IEnumerable<ILearningRateController> ParamGroups {\n get => _parameter_groups;\n }\n\n protected IList<ParamGroup> _parameter_groups;\n }\n\n /// <summary>\n /// This interfce is used by learning rate schedulers to access and control\n /// the rates used by optimizers.\n /// </summary>\n public interface ILearningRateController\n {\n /// <summary>\n /// The current LR\n /// </summary>\n double LearningRate { set; get; }\n\n /// <summary>\n /// The initial LR\n /// </summary>\n double InitialLearningRate { set; get; }\n }\n\n /// <summary>\n /// Indicates optimizers with support for momentum, which some LR schedulers require.\n /// </summary>\n public interface IMomentum\n {\n double Momentum { get; set; }\n }\n\n /// <summary>\n /// Indicates optimizers with support for betas instead of momentum.\n /// </summary>\n public interface IBetas\n {\n (double, double) Betas { get; set; }\n }\n }\n }\n\n namespace Modules\n {\n using static torch.optim;\n\n /// <summary>\n /// Base class to help with a couple of the things that managed-code implementations need.\n /// </summary>\n public abstract class OptimizerHelper : Optimizer\n {\n public OptimizerHelper() : base(IntPtr.Zero)\n {\n }\n\n\n protected enum TypeCode\n {\n Double = 0,\n Long = 1,\n Tensor = 2,\n Options = 3,\n State = 4,\n }\n\n /// <summary>\n /// Saves the optimizer state.\n /// </summary>\n /// <param name=\"location\">The name of a file where optimizer state data will be stored.</param>\n public void save_state_dict(string location)\n {\n using var stream = System.IO.File.Create(location);\n using (var writer = new System.IO.BinaryWriter(stream)) {\n\n save_state_dict(writer);\n writer.Flush();\n stream.Flush();\n }\n }\n\n /// <summary>\n /// Loads the optimizer state.\n /// </summary>\n /// <param name=\"location\">The name of a file where optimizer state data is stored.</param>\n /// <remarks>\n /// Optimizer state saved from PyTorch cannot be restored -- the file format is unique to TorchSharp.\n /// </remarks>\n public void load_state_dict(string location)\n {\n using var stream = System.IO.File.OpenRead(location);\n using (var reader = new System.IO.BinaryReader(stream)) {\n\n load_state_dict(reader);\n }\n }\n\n /// <summary>\n /// Saves the optimizer state.\n /// </summary>\n /// <param name=\"writer\">A binary writer connected to a stream where .</param>\n public void save_state_dict(System.IO.BinaryWriter writer)\n {\n // Save the name of the optimizer, so that we can avoid problems.\n writer.Write(this.GetType().Name);\n\n var sd = state_dict();\n\n writer.Encode(sd.Options.Count); // 4 bytes\n writer.Encode(sd.State.Count); // 4 bytes\n\n foreach (var opts in sd.Options) {\n\n opts.SaveStateDict(writer);\n }\n\n foreach (var state in sd.State) {\n state.SaveStateDict(writer);\n }\n }\n\n /// <summary>\n /// Loads the optimizer state.\n /// </summary>\n /// <param name=\"reader\">A binary reader connected to a stream containing saved optimizer state.</param>\n /// <remarks>\n /// Optimizer state saved from PyTorch cannot be restored -- the file format is unique to TorchSharp.\n /// </remarks>\n public void load_state_dict(System.IO.BinaryReader reader)\n {\n var optName = reader.ReadString();\n if (optName != this.GetType().Name) {\n throw new InvalidDataException($\"Mismatched optimizer type: expected '{this.GetType().Name}', but found '{optName}' in the loaded stream.\");\n }\n\n // First, figure out how many entries.\n var options = reader.Decode();\n var states = reader.Decode();\n\n var sd = state_dict();\n\n if (options != sd.Options.Count) throw new ArgumentException(\"Invalid optimizer state -- different number of parameter groups.\");\n if (states != sd.State.Count) throw new ArgumentException(\"Invalid optimizer state -- different number of states.\");\n\n for (var i = 0; i < options; i++) {\n var opts = sd.Options[i] as OptimizerOptions;\n opts.LoadStateDict(reader);\n }\n\n for (var i = 0; i < states; i++) {\n\n var state = sd.State[i] as OptimizerState;\n state.LoadStateDict(reader);\n }\n }\n\n /// <summary>\n /// Loads the optimizer state.\n /// </summary>\n /// <param name=\"state_dict\">Optimizer state. Should be an object returned from a call to state_dict().</param>\n /// <remarks>\n /// The format of the optimizer state dict is different from PyTorch's. Instead of a dictionary with two entries,\n /// the state is represented as record with two entries, both containing lists with state.\n /// </remarks>\n public virtual void load_state_dict(StateDictionary state_dict)\n {\n var sd = this.state_dict();\n\n if (state_dict.Options.Count != sd.Options.Count) throw new ArgumentException(\"Invalid optimizer state -- different number of parameter groups.\");\n if (state_dict.State.Count != sd.State.Count) throw new ArgumentException(\"Invalid optimizer state -- different number of states.\");\n\n for (var i = 0; i < state_dict.Options.Count; i++) {\n\n var st_opts = sd.Options[i] as OptimizerOptions;\n if (st_opts != state_dict.Options[i]) {\n st_opts.LoadStateDict(state_dict.Options[i]);\n }\n }\n\n for (var i = 0; i < state_dict.State.Count; i++) {\n\n var st_state = sd.State[i] as OptimizerState;\n if (st_state != state_dict.State[i]) {\n st_state.LoadStateDict(state_dict.State[i]);\n }\n }\n }\n\n /// <summary>\n /// Returns the state of the optimizer as a dict.\n /// </summary>\n /// <returns></returns>\n /// <remarks>\n /// The format of the optimizer state dict is different from PyTorch's. Instead of a dictionary with two entries,\n /// the state is represented as record with two entries, both containing lists with state.\n /// </remarks>\n public virtual StateDictionary state_dict()\n {\n var dict = new StateDictionary();\n\n int pgidx = -1;\n int pridx = 0;\n foreach (var pg in _parameter_groups) {\n\n dict.Options.Add(pg.Options);\n\n foreach (var p in pg.Parameters) {\n\n dict.State.Add(_state[p.Handle]);\n pridx++;\n }\n pgidx--;\n }\n return dict;\n }\n\n /// <summary>\n /// Move all the state to the indicated device.\n /// </summary>\n /// <param name=\"device\">The device to move all state to.</param>\n public void to(Device device)\n {\n foreach (var pg in _parameter_groups) {\n foreach (var p in pg.Parameters) {\n var state = _state[p.Handle];\n state.to(device);\n }\n }\n }\n\n /// <summary>\n /// Sets the gradients of all parameters to zero.\n /// </summary>\n public override void zero_grad()\n {\n foreach (var g in _parameter_groups) {\n\n foreach (var p in g.Parameters) {\n\n using var grad = p.grad();\n\n if (grad is null) continue;\n\n grad.zero_().Dispose();\n }\n }\n }\n\n /// <summary>\n /// Support routine for implementation of step() in all optimizers that support parameter groups.\n /// </summary>\n /// <typeparam name=\"T\">The ParamGroup type in use</typeparam>\n /// <param name=\"body\">The body of the step update.</param>\n /// <param name=\"loss_closure\">The closure, if any, for computing the loss.</param>\n /// <returns></returns>\n protected Tensor _step<T>(Action<T> body, Func<Tensor> loss_closure = null) where T : ParamGroup\n {\n Tensor loss = null;\n\n if (loss_closure != null) {\n using (var _ = torch.enable_grad())\n loss = loss_closure();\n }\n\n using (var _ = torch.no_grad()) {\n\n using (var d = torch.NewDisposeScope()) {\n\n foreach (var group in _parameter_groups) {\n\n body(group as T);\n\n }\n }\n }\n\n return loss;\n }\n\n /// <summary>\n /// Get the parameters that the optimizer is handling.\n /// </summary>\n public override IEnumerable<Parameter> parameters()\n {\n return _parameter_groups.SelectMany(pg => pg.Parameters);\n }\n\n /// <summary>\n /// Add a param group to the Optimizer s param_groups.\n /// </summary>\n /// <param name=\"param_group\"></param>\n /// <remarks>This can be useful when fine tuning a pre-trained network as frozen layers can be made trainable and added to the Optimizer as training progresses.</remarks>\n public override void add_param_group(ParamGroup param_group)\n {\n _parameter_groups.Add(param_group);\n }\n\n protected OptimizerOptions _defaults;\n\n protected Utils.OrderedDict<IntPtr, OptimizerState> _state = new Utils.OrderedDict<IntPtr, OptimizerState>();\n }\n\n /// <summary>\n /// Base class for optimizer options.\n /// </summary>\n public class OptimizerOptions\n {\n public double? LearningRate { get; set; }\n public double InitialLearningRate { get; set; }\n\n /// <summary>\n /// Save the optimizer options (param-group hyperparameters) to a stream.\n /// </summary>\n /// <param name=\"writer\">A binary writer connected to a stream open for writing.</param>\n public virtual void SaveStateDict(BinaryWriter writer)\n {\n writer.Write(InitialLearningRate);\n writer.Write(LearningRate.Value);\n }\n\n /// <summary>\n /// Load the optimizer options (param-group hyperparameters) from a stream.\n /// </summary>\n /// <param name=\"reader\">A binary reader connected to a stream open for reading.</param>\n public virtual void LoadStateDict(BinaryReader reader)\n {\n InitialLearningRate = reader.ReadDouble();\n LearningRate = reader.ReadDouble();\n }\n\n /// <summary>\n /// Load optimizer options (param-group hyperparameters) from another optimizer.\n /// </summary>\n /// <param name=\"source\">An optimizer options record.</param>\n public virtual void LoadStateDict(OptimizerOptions source)\n {\n InitialLearningRate = source.InitialLearningRate;\n LearningRate = source.LearningRate;\n }\n }\n\n /// <summary>\n /// Base class for optimizer options.\n /// </summary>\n public abstract class OptimizerState\n {\n /// <summary>\n /// Save the optimizer parameter state to a stream.\n /// </summary>\n /// <param name=\"writer\">A binary writer connected to a stream open for writing.</param>\n public abstract void SaveStateDict(BinaryWriter writer);\n\n /// <summary>\n /// Load the optimizer parameter state from a stream.\n /// </summary>\n /// <param name=\"reader\">A binary reader connected to a stream open for reading.</param>\n public abstract void LoadStateDict(BinaryReader reader);\n\n /// <summary>\n /// Load optimizer parameter state from another optimizer.\n /// </summary>\n /// <param name=\"source\">An optimizer state record.</param>\n public abstract void LoadStateDict(OptimizerState source);\n\n /// <summary>\n /// Useful for tests, allows comparison of one state with another.\n /// </summary>\n /// <param name=\"other\">The other optimizer state</param>\n /// <returns></returns>\n public virtual bool ApproximatelyEquals(OptimizerState other)\n {\n return false;\n }\n\n /// <summary>\n /// Move all the state to the indicated device.\n /// </summary>\n /// <param name=\"device\">The device to move all state to.</param>\n public virtual void to(Device device) { }\n\n protected static void LoadConditionalStateTensor(BinaryReader reader, ref Tensor result)\n {\n var hasTensor = reader.ReadBoolean();\n\n if (hasTensor) {\n TensorExtensionMethods.Load(ref result, reader);\n } else {\n if (result is not null)\n result.Dispose();\n result = null;\n }\n }\n\n protected static void SaveConditionalStateTensor(BinaryWriter writer, Tensor tensor)\n {\n if (tensor is not null) {\n writer.Write(true);\n tensor.Save(writer);\n } else {\n writer.Write(false);\n }\n }\n }\n\n /// <summary>\n /// Base class for parameter groups\n /// </summary>\n public class ParamGroup : ILearningRateController\n {\n public IEnumerable<Parameter> Parameters { get; set; }\n\n public OptimizerOptions Options { get; set; }\n\n public double LearningRate { get => Options.LearningRate.Value; set => Options.LearningRate = value; }\n public double InitialLearningRate { get => Options.InitialLearningRate; set => Options.InitialLearningRate = value; }\n }\n\n /// <summary>\n /// Generic-typed version of ParamGroup\n /// </summary>\n /// <typeparam name=\"TOptions\">The type of options used for the parameter group.</typeparam>\n public class ParamGroup<TOptions> : ParamGroup where TOptions : OptimizerOptions\n {\n /// <summary>\n /// Constructor\n /// </summary>\n public ParamGroup()\n {\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"parameters\">The parameters of the parameter group</param>\n /// <param name=\"options\">The options of the parameter group</param>\n public ParamGroup(IEnumerable<Parameter> parameters, TOptions options = null)\n {\n base.Parameters = parameters;\n base.Options = options;\n }\n\n /// <summary>\n /// Parameter group options / hyperparameters, used to control the optimizer algorithm.\n /// </summary>\n public new TOptions Options { get => (TOptions)base.Options; set => base.Options = value; }\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n }\n}\n\n" }, { "alpha_fraction": 0.5719128251075745, "alphanum_fraction": 0.5807909369468689, "avg_line_length": 43.25, "blob_id": "a8e08fbc253d7fb6ad589ca2e079b3f927a8ce09", "content_id": "76176217c1541cfdc23d0ae099f5fe31c6d8b0eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6197, "license_type": "permissive", "max_line_length": 149, "num_lines": 140, "path": "/src/TorchSharp/Distributions/Beta.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// A Beta distribution parameterized by concentration1 and concentration0.\n /// </summary>\n public class Beta : torch.distributions.ExponentialFamily\n {\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public override Tensor mean => concentration1 / (concentration1 + concentration0);\n\n public override Tensor mode => dirichlet.mode[TensorIndex.Ellipsis, 0];\n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public override Tensor variance {\n get {\n using var _ = NewDisposeScope();\n var total = concentration0 + concentration1;\n return (concentration1 * concentration0 / (total.pow(2) * (total + 1))).MoveToOuterDisposeScope();\n }\n }\n\n // Note that the order of the arguments is not a mistake -- the original source has them\n // ordered this way.\n\n public Beta(Tensor concentration1, Tensor concentration0, torch.Generator generator = null) : base(generator)\n {\n var bcast = torch.broadcast_tensors(concentration1, concentration0);\n this.concentration1 = bcast[0].DetachFromDisposeScope();\n this.concentration0 = bcast[1].DetachFromDisposeScope();\n this.dirichlet = new Dirichlet(torch.stack(bcast, -1), generator);\n this.batch_shape = this.dirichlet.batch_shape;\n }\n\n\n protected Dirichlet dirichlet;\n private Tensor concentration1;\n private Tensor concentration0;\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n public override Tensor rsample(params long[] sample_shape)\n {\n return dirichlet.rsample(sample_shape).select(-1, 0);\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor log_prob(Tensor value)\n {\n var heads_tails = torch.stack(new Tensor[] { value, 1.0 - value }, -1);\n return dirichlet.log_prob(heads_tails);\n }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n public override Tensor entropy()\n {\n return dirichlet.entropy();\n }\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is Beta))\n throw new ArgumentException(\"expand(): 'instance' must be a Beta distribution\");\n\n var c0 = concentration0.expand(batch_shape);\n var c1 = concentration1.expand(batch_shape);\n\n var newDistribution = ((instance == null) ? new Beta(c1, c0, generator) : instance) as Beta;\n\n newDistribution.batch_shape = batch_shape;\n if (newDistribution == instance) {\n newDistribution.dirichlet = new Dirichlet(torch.stack(new Tensor[] { c1, c0 }, -1));\n newDistribution.concentration1 = c1;\n newDistribution.concentration0 = c0;\n }\n return newDistribution;\n }\n\n protected override IList<Tensor> NaturalParams => new Tensor[] { concentration1, concentration0 };\n\n protected override Tensor MeanCarrierMeasure => new Tensor(IntPtr.Zero);\n\n protected override Tensor LogNormalizer(params Tensor[] parameters)\n {\n var x = parameters[0];\n var y = parameters[1];\n\n return torch.lgamma(x) + torch.lgamma(y) - torch.lgamma(x + y);\n }\n }\n\n }\n\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a Beta distribution parameterized by concentration1 and concentration0.\n /// </summary>\n /// <param name=\"concentration1\">1st concentration parameter of the distribution (often referred to as 'α')</param>\n /// <param name=\"concentration0\">2nd concentration parameter of the distribution (often referred to as 'β')</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n /// <remarks>The order of the arguments is not a mistake -- the original source has them ordered this way.\n /// </remarks>\n public static Beta Beta(Tensor concentration1, Tensor concentration0, torch.Generator generator = null)\n {\n return new Beta(concentration1, concentration0, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5364921689033508, "alphanum_fraction": 0.537065327167511, "avg_line_length": 43.735042572021484, "blob_id": "81e18130097109206aa20ebfad3e4a9cb77a3ff5", "content_id": "94bf275d8f44e544fe937d6d70b899a9e87e2369", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5234, "license_type": "permissive", "max_line_length": 195, "num_lines": 117, "path": "/src/TorchSharp/NN/Recurrent/RNNCell.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n public sealed class RNNCell : torch.nn.Module<Tensor, Tensor, Tensor>\n {\n internal RNNCell(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public new static RNNCell Load(string modelPath)\n {\n var res = Module<Tensor, Tensor>.Load(modelPath);\n return new RNNCell(res.handle.DangerousGetHandle(), IntPtr.Zero);\n }\n\n /// <summary>\n /// Apply the RNN cell to an input tensor.\n /// </summary>\n /// <param name=\"input\">Tensor of shape (batch, input_size) containing the features of the input sequence.</param>\n /// <param name=\"h0\">Tensor of shape (batch, hidden_size) containing the initial hidden state for each element in the batch.</param>\n /// <returns></returns>\n public override Tensor forward(Tensor input, Tensor? h0 = null)\n {\n var hN = THSNN_RNNCell_forward(handle, input.Handle, h0?.Handle ?? IntPtr.Zero);\n if (hN == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(hN);\n }\n\n public Parameter? bias_ih {\n get {\n var res = THSNN_RNNCell_bias_ih(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return ((res == IntPtr.Zero) ? null : new Parameter(res));\n }\n set {\n THSNN_RNNCell_set_bias_ih(handle, (value is null ? IntPtr.Zero : value.Handle));\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"bias_ih\", value);\n\n }\n }\n\n public Parameter? bias_hh {\n get {\n var res = THSNN_RNNCell_bias_hh(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return ((res == IntPtr.Zero) ? null : new Parameter(res));\n }\n set {\n THSNN_RNNCell_set_bias_hh(handle, (value is null ? IntPtr.Zero : value.Handle));\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"bias_hh\", value);\n\n }\n }\n\n public Parameter? weight_ih {\n get {\n var res = THSNN_RNNCell_weight_ih(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n set {\n THSNN_RNNCell_set_weight_ih(handle, value is null ? IntPtr.Zero : value.Handle);\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"weight_ih\", value);\n }\n }\n\n public Parameter? weight_hh {\n get {\n var res = THSNN_RNNCell_weight_hh(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n set {\n THSNN_RNNCell_set_weight_hh(handle, value is null ? IntPtr.Zero : value.Handle);\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"weight_hh\", value);\n }\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// An Elman RNN cell with tanh or ReLU non-linearity.\n /// </summary>\n /// <param name=\"inputSize\">The number of expected features in the input x</param>\n /// <param name=\"hiddenSize\">The number of features in the hidden state h</param>\n /// <param name=\"nonLinearity\">The non-linearity to use. Can be either 'tanh' or 'relu'. Default: 'tanh'</param>\n /// <param name=\"bias\">If False, then the layer does not use bias weights b_ih and b_hh. Default: True</param>\n /// <param name=\"device\">The desired device of the parameters and buffers in this module</param>\n /// <param name=\"dtype\">The desired floating point or complex dtype of the parameters and buffers in this module</param>\n /// <returns></returns>\n public static RNNCell RNNCell(long inputSize, long hiddenSize, NonLinearities nonLinearity = nn.NonLinearities.Tanh, bool bias = true, Device? device = null, ScalarType? dtype = null)\n {\n var res = THSNN_RNNCell_ctor(inputSize, hiddenSize, (long)nonLinearity, bias, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new RNNCell(res, boxedHandle).MoveModule<RNNCell>(device, dtype);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.4843258559703827, "alphanum_fraction": 0.48990610241889954, "avg_line_length": 47.12702941894531, "blob_id": "1a6bd61fd5bb62cc7bd8207a5f7fa8e1292f0f29", "content_id": "fdf7cb47cda8967cba8593dd67522429b2a15ad2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 82991, "license_type": "permissive", "max_line_length": 319, "num_lines": 1724, "path": "/src/TorchSharp/NN/Module.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing TorchSharp.Modules;\nusing static TorchSharp.torch;\nusing static TorchSharp.Utils.LEB128Codec;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Base class for all neural network modules.\n /// Your models should subclass this class.\n /// </summary>\n /// <remarks>\n /// Modules can also contain other Modules, allowing to nest them in a tree structure.\n /// You can assign the submodules as regular fields of the derived Module class. Submodules assigned\n /// to fields will be registered, and will have their parameters converted and moved when you call to(),\n /// and saved to disk when calling save().\n /// </remarks>\n public class Module : IDisposable\n {\n /// <summary>\n /// Class wrapping PyTorch's module object reference.\n /// </summary>\n protected internal sealed class HType : SafeHandle\n {\n public HType(IntPtr preexistingHandle, bool ownsHandle, Action<HType> dispose = null)\n : base(IntPtr.Zero, ownsHandle)\n {\n _dispose = dispose ?? THSNN_Module_dispose;\n SetHandle(preexistingHandle);\n }\n\n public override bool IsInvalid => handle == IntPtr.Zero;\n\n // This is just for marshalling\n internal HType() : base(IntPtr.Zero, true)\n {\n }\n\n protected override bool ReleaseHandle()\n {\n if (!IsInvalid) {\n _dispose(this);\n }\n SetHandle(IntPtr.Zero);\n return true;\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n ReleaseHandle();\n }\n }\n\n private Action<HType> _dispose;\n }\n\n internal HType handle;\n\n /// Stores the AnyModule corresponding to this module.\n internal BoxedModule boxedModule;\n\n internal BoxedModule BoxedModule {\n get {\n if (boxedModule == null)\n throw new InvalidOperationException(\"A Sequential or Loaded module may not be added to a Sequential\");\n return boxedModule;\n }\n }\n\n internal Module(HType handle, IntPtr? boxedHandle)\n {\n this.handle = handle;\n boxedModule = boxedHandle.HasValue ? new BoxedModule(boxedHandle.Value) : null;\n\n if (handle.IsInvalid) return;\n register_p_and_b();\n }\n\n internal Module(IntPtr handle, IntPtr? boxedHandle, bool ownsHandle = true)\n {\n this.handle = new HType(handle, ownsHandle);\n boxedModule = boxedHandle.HasValue ? new BoxedModule(boxedHandle.Value) : null;\n\n if (handle == IntPtr.Zero) return;\n register_p_and_b();\n }\n\n private void register_p_and_b()\n {\n foreach (var (parameterName, parameter) in _named_parameters()) {\n register_parameter(parameterName, parameter);\n }\n foreach (var (bufferName, buffer) in _named_buffers()) {\n register_buffer(bufferName, buffer);\n }\n }\n\n ~Module() => Dispose(false);\n\n /// <summary>\n /// Releases the storage.\n /// </summary>\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n /// <summary>\n /// Implements the .NET Dispose pattern.\n /// </summary>\n protected virtual void Dispose(bool disposing)\n {\n if (disposing && !handle.IsInvalid) {\n\n foreach (var (_, p) in named_buffers(false)) {\n p.Dispose();\n }\n foreach (var (_, b) in named_parameters(false)) {\n b.Dispose();\n }\n\n foreach (var (_, m) in named_modules()) {\n m.Dispose();\n }\n\n handle.Dispose();\n handle.SetHandleAsInvalid();\n boxedModule?.Dispose();\n }\n }\n\n /// <summary>\n /// Moves and converts the parameters and buffers.\n /// </summary>\n /// <param name=\"device\">The target device.</param>\n /// <param name=\"dtype\">The target element type.</param>\n protected internal virtual Module _to(Device device, ScalarType dtype)\n {\n if (device.type != DeviceType.CUDA) { device = new Device(device.type, -1); };\n\n if (device.type == DeviceType.CUDA && !torch.cuda.is_available()) throw new InvalidOperationException(\"CUDA is not available.\");\n\n InitializeDeviceType(device.type);\n THSNN_Module_to_device_dtype(handle, (sbyte)dtype, (int)device.type, device.index);\n CheckForErrors();\n\n _toEpilog(device, dtype);\n\n return this;\n }\n\n protected void _toEpilog(Device device, ScalarType dtype)\n {\n foreach (var (_, sm) in named_children()) sm._to(device, dtype);\n\n var alreadyHandled = new HashSet<IntPtr>();\n\n foreach (var field in GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)) {\n\n var fieldName = field.Name;\n var value = field.GetValue(this);\n\n switch (value) {\n // This order in which these cases are arranged is significant.\n case Parameter param when dtype == param.dtype && device.type == param.device_type && device.index == param.device_index:\n alreadyHandled.Add(param.handle);\n continue;\n\n case Parameter param: {\n var t = param.to(dtype, device);\n t.retain_grad();\n var p = new Parameter(t, param.requires_grad);\n field.SetValue(this, p);\n ConditionallyRegisterParameter(fieldName, p);\n alreadyHandled.Add(p.handle);\n break;\n }\n\n case Tensor tensor when (device.type != tensor.device_type || device.index != tensor.device_index): {\n var t = tensor.to(dtype, device);\n field.SetValue(this, t);\n ConditionallyRegisterBuffer(fieldName, t);\n alreadyHandled.Add(t.handle);\n break;\n }\n\n case Tensor tensor:\n alreadyHandled.Add(tensor.handle);\n break;\n }\n }\n\n foreach (var (name, param) in named_parameters(false).ToList()) {\n if (alreadyHandled.Contains(param.handle)) continue;\n var t = param.to(dtype, device);\n ConditionallyRegisterParameter(name, t);\n }\n\n foreach (var (name, buffer) in named_buffers(false).ToList()) {\n if (alreadyHandled.Contains(buffer.handle)) continue;\n var t = buffer.to(dtype, device);\n ConditionallyRegisterBuffer(name, t);\n }\n\n _deviceType = device.type;\n _deviceIndex = device.index;\n\n Debug.Assert(_deviceType == DeviceType.CUDA || _deviceIndex == -1);\n }\n\n\n /// <summary>\n /// Moves the parameters and buffers.\n /// </summary>\n /// <param name=\"deviceType\">The device type, e.g. 'CPU' or 'CUDA'.</param>\n /// <param name=\"deviceIndex\">The optional device index.</param>\n /// <returns></returns>\n protected internal virtual Module _to(DeviceType deviceType, int deviceIndex = -1)\n {\n if (deviceType != DeviceType.CUDA) deviceIndex = -1;\n\n if (deviceType == DeviceType.CUDA && !torch.cuda.is_available()) throw new InvalidOperationException(\"CUDA is not available.\");\n\n if (deviceType != _deviceType || deviceIndex != _deviceIndex) {\n\n InitializeDeviceType(deviceType);\n THSNN_Module_to_device(handle, (int)deviceType, deviceIndex);\n CheckForErrors();\n\n _toEpilog(deviceType, deviceIndex);\n }\n\n Debug.Assert(_deviceType == DeviceType.CUDA || _deviceIndex == -1);\n\n return this;\n }\n\n protected void _toEpilog(DeviceType deviceType, int deviceIndex)\n {\n foreach (var (_, sm) in named_children()) sm._to(deviceType, deviceIndex);\n\n var alreadyHandled = new HashSet<IntPtr>();\n\n foreach (var field in GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)) {\n\n var fieldName = field.Name;\n var value = field.GetValue(this);\n\n switch (value) {\n // This order in which these cases are arranged is significant.\n case Parameter param when deviceType == param.device_type && deviceIndex == param.device_index:\n alreadyHandled.Add(param.handle);\n continue;\n\n case Parameter param: {\n var t = param.to(deviceType, deviceIndex);\n t.retain_grad();\n var p = new Parameter(t, param.requires_grad);\n field.SetValue(this, p);\n ConditionallyRegisterParameter(fieldName, p);\n alreadyHandled.Add(p.handle);\n break;\n }\n\n case Tensor tensor when (deviceType != tensor.device_type || deviceIndex != tensor.device_index): {\n var t = tensor.to(deviceType, deviceIndex);\n field.SetValue(this, t);\n ConditionallyRegisterBuffer(fieldName, t);\n alreadyHandled.Add(t.handle);\n break;\n }\n\n case Tensor tensor:\n alreadyHandled.Add(tensor.handle);\n break;\n }\n }\n\n foreach (var (name, param) in named_parameters(false).ToList()) {\n if (alreadyHandled.Contains(param.handle)) continue;\n var t = param.to(deviceType, deviceIndex);\n ConditionallyRegisterParameter(name, t);\n }\n\n foreach (var (name, buffer) in named_buffers(false).ToList()) {\n if (alreadyHandled.Contains(buffer.handle)) continue;\n var t = buffer.to(deviceType, deviceIndex);\n ConditionallyRegisterBuffer(name, t);\n }\n\n _deviceType = deviceType;\n _deviceIndex = deviceIndex;\n }\n\n private DeviceType _deviceType = DeviceType.CPU;\n private int _deviceIndex = -1;\n\n /// <summary>\n /// Convert the parameters and buffers.\n /// </summary>\n /// <returns></returns>\n protected internal virtual Module _to(ScalarType dtype)\n {\n THSNN_Module_to_dtype(handle, (sbyte)dtype);\n CheckForErrors();\n\n _toEpilog(dtype);\n\n return this;\n }\n\n protected void _toEpilog(ScalarType dtype)\n {\n foreach (var (_, sm) in named_children()) sm._to(dtype);\n\n var alreadyHandled = new HashSet<IntPtr>();\n\n foreach (var field in GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)) {\n\n var fieldName = field.Name;\n var value = field.GetValue(this);\n\n switch (value) {\n // This order in which these cases are arranged is significant.\n case Parameter param when dtype == param.dtype:\n alreadyHandled.Add(param.handle);\n continue;\n\n case Parameter param: {\n var t = param.to(dtype);\n t.retain_grad();\n var p = new Parameter(t, param.requires_grad);\n field.SetValue(this, p);\n ConditionallyRegisterParameter(fieldName, p);\n alreadyHandled.Add(p.handle);\n break;\n }\n\n case Tensor tensor when dtype == tensor.dtype:\n alreadyHandled.Add(tensor.handle);\n continue;\n\n case Tensor tensor: {\n var t = tensor.to(dtype);\n field.SetValue(this, t);\n ConditionallyRegisterBuffer(fieldName, t);\n alreadyHandled.Add(t.handle);\n break;\n }\n }\n }\n\n foreach (var (name, param) in named_parameters(false).ToList()) {\n if (alreadyHandled.Contains(param.handle)) continue;\n var t = param.to(dtype);\n ConditionallyRegisterParameter(name, t);\n }\n\n foreach (var (name, buffer) in named_buffers(false).ToList()) {\n if (alreadyHandled.Contains(buffer.handle)) continue;\n var t = buffer.to(dtype);\n ConditionallyRegisterBuffer(name, t);\n }\n }\n\n /// <summary>\n /// Moves and converts the parameters and buffers.\n /// </summary>\n /// <param name=\"other\">The tensor serving as a template.</param>\n /// <returns></returns>\n public Module _to(Tensor other)\n {\n _to(other.dtype);\n return _to(other.device_type, other.device_index);\n }\n\n\n\n /// <summary>\n /// Applies a function recursively to every submodule as well as this.\n /// </summary>\n /// <param name=\"fn\">Function to be applied to each submodule</param>\n /// <returns></returns>\n public virtual Module apply(Action<Module> fn)\n {\n foreach (var (_, m) in _internal_submodules) m.apply(fn);\n fn(this);\n return this;\n }\n\n public static Module Load(string filename)\n {\n if (!System.IO.File.Exists(filename))\n throw new System.IO.FileNotFoundException(filename);\n\n var handle = THSNN_Module_load(filename);\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n return new Module(handle, IntPtr.Zero);\n }\n\n public virtual void Save(string modelPath)\n => THSNN_Module_save(handle, modelPath);\n\n /// <summary>\n /// Sets the module in training mode.\n /// </summary>\n /// <remarks>\n /// This has any effect only on certain modules.See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.Dropout, BatchNorm, etc.\n /// </remarks>\n public virtual void train(bool train = true)\n {\n THSNN_Module_train(handle, train);\n CheckForErrors();\n foreach (var (_, m) in named_children()) { m.train(train); }\n }\n\n /// <summary>\n /// Sets the module in evaluation mode.\n /// </summary>\n /// <remarks>\n /// This has any effect only on certain modules.See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.Dropout, BatchNorm, etc.\n /// </remarks>\n public virtual void eval()\n {\n train(false);\n }\n\n /// <summary>\n /// Check whether the module is set to training or evaluation mode.\n /// </summary>\n public virtual bool training {\n get {\n var res = THSNN_Module_is_training(handle);\n CheckForErrors();\n return res;\n }\n }\n\n public virtual void zero_grad()\n {\n THSNN_Module_zero_grad(handle);\n CheckForErrors();\n }\n\n /// <summary>\n /// Returns an enumerable of module buffers, yielding both the name of the buffer as well as the buffer itself.\n /// </summary>\n /// <param name=\"recurse\">If true, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.</param>\n /// <returns>(string, torch.Tensor) – Tuple containing the name and buffer</returns>\n public virtual IEnumerable<(string name, Tensor buffer)> named_buffers(bool recurse = true)\n {\n var seen = new HashSet<IntPtr>();\n seen.Add(IntPtr.Zero); // Ignore invalid buffers.\n\n foreach (var nsm in _internal_buffers) {\n if (seen.Contains(nsm.Item2.handle)) continue;\n seen.Add(nsm.Item2.handle);\n yield return nsm;\n }\n\n if (!recurse) yield break;\n\n foreach (var (submoduleName, subModule) in _internal_submodules) {\n foreach (var (bufferName, buffer) in subModule.named_buffers(true)) {\n if (seen.Contains(buffer.handle)) continue;\n seen.Add(buffer.handle);\n yield return ($\"{submoduleName}.{bufferName}\", buffer);\n }\n }\n\n }\n\n /// <summary>\n /// Returns an enumerable of buffers.\n /// </summary>\n public virtual IEnumerable<Tensor> buffers(bool recurse = true) => named_buffers(recurse).Select(np => np.buffer);\n\n /// <summary>\n /// Returns an enumerable of immediate children modules, yielding both the name of the module as well as the module itself.\n /// </summary>\n /// <returns>(string, Module) – Tuple containing a name and child module</returns>\n public virtual IEnumerable<(string name, Module module)> named_children() => _internal_submodules;\n\n /// <summary>\n /// Returns an enumerable of all modules in the network, yielding both the name of the module as well as the module itself.\n /// </summary>\n /// <returns>(string, Module) – Tuple of name and module</returns>\n public virtual IEnumerable<(string name, Module module)> named_modules()\n {\n foreach (var nsm in _internal_submodules) {\n yield return nsm;\n }\n\n foreach (var (submoduleName, sm) in _internal_submodules) {\n foreach (var (n, p) in sm.named_modules()) {\n yield return ($\"{submoduleName}.{n}\", p);\n }\n }\n }\n\n /// <summary>\n /// Returns an enumerable of modules.\n /// </summary>\n public virtual IEnumerable<Module> modules() => named_modules().Select(np => np.module);\n\n /// <summary>\n /// Returns an enumerable of immediate modules.\n /// </summary>\n public virtual IEnumerable<Module> children() => named_children().Select(np => np.module);\n\n /// <summary>\n /// Returns a dictionary containing a whole state of the module.\n ///\n /// Both parameters and persistent buffers(e.g.running averages) are included.Keys are corresponding parameter and buffer names.\n /// Parameters and buffers set to null are not included.\n /// </summary>\n /// <param name=\"destination\">An optional dictionary where the state should be accumulated.</param>\n /// <param name=\"prefix\">A prefix string to use when entering the name of entries into the dictionary.</param>\n /// <returns></returns>\n public virtual Dictionary<string, Tensor> state_dict(Dictionary<string, Tensor> destination = null, string prefix = null)\n {\n destination ??= new Dictionary<string, Tensor>();\n\n foreach (var p in named_parameters()) {\n var key = string.IsNullOrEmpty(prefix) ? $\"{p.name}\" : $\"{prefix}.{p.name}\";\n destination.TryAdd(key, p.Item2);\n }\n\n foreach (var p in named_buffers()) {\n var key = string.IsNullOrEmpty(prefix) ? $\"{p.name}\" : $\"{prefix}.{p.name}\";\n destination.TryAdd(key, p.Item2);\n }\n\n foreach (var (n, p) in _internal_submodules) {\n var key = string.IsNullOrEmpty(prefix) ? $\"{n}\" : $\"{prefix}.{n}\";\n p.state_dict(destination, key);\n }\n\n return destination;\n }\n\n /// <summary>\n /// Copies parameters and buffers from state_dict into this module and its descendants.\n ///\n /// If strict is True, then the keys of state_dict must exactly match the keys returned by this module’s state_dict() function.\n /// </summary>\n /// <param name=\"source\">A dict containing parameters and persistent buffers.</param>\n /// <param name=\"strict\">Whether to strictly enforce that the keys in state_dict match the keys returned by this module’s state_dict() function.</param>\n /// <param name=\"skip\">A list of keys not to consider when loading the dictionary.</param>\n /// <returns></returns>\n public virtual (IList<string> missing_keys, IList<string> unexpected_keyes) load_state_dict(Dictionary<string, Tensor> source, bool strict = true, IList<string> skip = null)\n {\n List<string> missing = new List<string>();\n List<string> unexpected = new List<string>();\n skip ??= Array.Empty<string>();\n\n var destination = state_dict();\n\n foreach (var key in source.Keys) {\n if (skip.Contains(key)) continue;\n if (!destination.ContainsKey(key)) {\n unexpected.Add(key);\n }\n }\n\n foreach (var key in destination.Keys) {\n if (skip.Contains(key)) continue;\n if (!source.ContainsKey(key)) {\n missing.Add(key);\n }\n }\n\n if (strict && (missing.Count > 0 || unexpected.Count > 0))\n throw new InvalidOperationException(\"The loaded state_dict is not identical to the target dictionary.\");\n\n foreach (var key in source.Keys) {\n if (skip.Contains(key)) continue;\n if (destination.ContainsKey(key)) {\n destination[key].bytes = source[key].bytes;\n }\n }\n\n return (missing, unexpected);\n }\n\n protected virtual (string name, Parameter parameter)[] _named_parameters()\n {\n using var pa = new PinnedArray<IntPtr>();\n using var sa = new PinnedArray<IntPtr>();\n THSNN_Module_get_named_parameters(handle, pa.CreateArray, sa.CreateArray);\n CheckForErrors();\n var ptrArray = pa.Array;\n var strArray = sa.Array;\n\n return ptrArray.Select((x, i) => (Marshal.PtrToStringAnsi(strArray[i]), new Parameter(x))).ToArray();\n }\n\n protected virtual (string name, Tensor buffer)[] _named_buffers()\n {\n using var pa = new PinnedArray<IntPtr>();\n using var sa = new PinnedArray<IntPtr>();\n THSNN_Module_get_named_buffers(handle, pa.CreateArray, sa.CreateArray);\n CheckForErrors();\n var ptrArray = pa.Array;\n var strArray = sa.Array;\n\n return ptrArray.Select((x, i) => (Marshal.PtrToStringAnsi(strArray[i]), new Tensor(x))).ToArray();\n }\n\n /// <summary>\n /// Returns an enumerable of module parameters, yielding both the name of the parameter as well as the parameter itself.\n /// </summary>\n /// <param name=\"recurse\">If true, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.</param>\n /// <returns>(string, Parameter) – Tuple containing the name and parameter</returns>\n public virtual IEnumerable<(string name, Parameter parameter)> named_parameters(bool recurse = true)\n {\n var seen = new HashSet<IntPtr>();\n seen.Add(IntPtr.Zero); // Ignore invalid parameters.\n\n foreach (var nsm in _internal_params) {\n if (seen.Contains(nsm.Item2.handle)) continue;\n seen.Add(nsm.Item2.handle);\n yield return nsm;\n }\n\n if (!recurse) yield break;\n foreach (var (submoduleName, subModule) in _internal_submodules) {\n foreach (var (parameterName, parameter) in subModule.named_parameters(true)) {\n if (seen.Contains(parameter.handle)) continue;\n seen.Add(parameter.handle);\n yield return ($\"{submoduleName}.{parameterName}\", parameter);\n }\n }\n }\n\n protected virtual Parameter[] _parameters(bool recurse = true)\n {\n IntPtr[] ptrArray;\n\n using (var pa = new PinnedArray<IntPtr>()) {\n AllocatePinnedArray allocator = pa.CreateArray;\n THSNN_Module_get_parameters(handle, allocator, recurse);\n CheckForErrors();\n ptrArray = pa.Array;\n }\n return ptrArray.Select(x => new Parameter(x)).ToArray();\n }\n\n /// <summary>\n /// Returns an enumerable of module parameters.\n /// </summary>\n /// <param name=\"recurse\">If true, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.</param>\n /// <returns></returns>\n public virtual IEnumerable<Parameter> parameters(bool recurse = true)\n => named_parameters(recurse).Select(np => np.parameter);\n\n public virtual bool has_buffer(string target)\n {\n if (_internal_buffers.TryGetValue(target, out var buffer)) {\n return true;\n }\n\n var splits = target.Split('.');\n if (splits.Length <= 1) return false;\n foreach (var child in named_children().Where(nc => nc.name == splits[0])) {\n if (child.module.has_buffer(target.Remove(0, splits[0].Length + 1)))\n return true;\n }\n return false;\n }\n\n public virtual bool has_parameter(string target)\n {\n if (_internal_params.TryGetValue(target, out var parameter)) {\n return true;\n }\n\n var splits = target.Split('.');\n if (splits.Length <= 1) return false;\n foreach (var child in named_children().Where(nc => nc.name == splits[0])) {\n if (child.module.has_parameter(target.Remove(0, splits[0].Length + 1)))\n return true;\n }\n return false;\n }\n\n /// <summary>\n /// Returns the buffer given by target if it exists, otherwise throws an error.\n /// </summary>\n /// <param name=\"target\">The fully-qualified string name of the buffer to look for.</param>\n /// <returns>The tensor referenced by target</returns>\n public virtual Tensor get_buffer(string target)\n {\n if (target is null) throw new ArgumentNullException(\"target\");\n if (_internal_buffers.TryGetValue(target, out var buffer)) {\n return buffer;\n }\n\n var splits = target.Split('.');\n if (splits.Length <= 1) return null;\n foreach (var child in named_children().Where(nc => nc.name == splits[0])) {\n var p = child.module.get_buffer(target.Remove(0, splits[0].Length + 1));\n if (p is not null)\n return p;\n }\n return null;\n }\n\n /// <summary>\n /// Returns the parameter given by target if it exists, otherwise throws an error.\n /// </summary>\n /// <param name=\"target\">The fully-qualified string name of the Parameter to look for.</param>\n /// <returns>The Parameter referenced by target</returns>\n public virtual Parameter get_parameter(string target)\n {\n if (_internal_params.TryGetValue(target, out var parameter)) {\n return parameter;\n }\n\n var splits = target.Split('.');\n if (splits.Length <= 1) return null;\n foreach (var child in named_children().Where(nc => nc.name == splits[0])) {\n var p = child.module.get_parameter(target.Remove(0, splits[0].Length + 1));\n if (p is not null)\n return p;\n }\n return null;\n }\n\n /// <summary>\n /// Adds a buffer to the module.\n ///\n /// This is typically used to register a buffer that should not to be considered a model parameter.For example, BatchNorm’s running_mean is not a parameter,\n /// but is part of the module’s state.Buffers, by default, are persistent and will be saved alongside parameters.\n /// </summary>\n /// <param name=\"name\">Name of the buffer. The buffer can be accessed from this module using the given name</param>\n /// <param name=\"tensor\">\n /// Buffer to be registered. If null, then operations that run on buffers, such as cuda(), are ignored.\n /// If null, the buffer is not included in the module’s state_dict.</param>\n /// <exception cref=\"ArgumentNullException\"></exception>\n /// <exception cref=\"InvalidOperationException\"></exception>\n public virtual void register_buffer(string name, Tensor tensor)\n {\n if (tensor is null || tensor.handle == IntPtr.Zero)\n throw new ArgumentNullException(nameof(tensor), \"A null tensor cannot be registered as a buffer.\");\n\n if (!_internal_buffers.TryAdd(name, tensor))\n throw new InvalidOperationException($\"Tensor {name} is already registered.\");\n }\n\n /// <summary>\n /// Adds a parameter to the module.\n /// </summary>\n /// <param name=\"name\">Name of the parameter. The parameter can be accessed from this module using the given name</param>\n /// <param name=\"param\">\n /// Buffer to be registered.\n /// If null, then operations that run on buffers, such as cuda(), are ignored.\n /// If null, the buffer is not included in the module’s state_dict.</param>\n /// <exception cref=\"ArgumentNullException\"></exception>\n /// <exception cref=\"InvalidOperationException\"></exception>\n public virtual void register_parameter(string name, Parameter param)\n {\n if (param is null || param.handle == IntPtr.Zero)\n throw new ArgumentNullException(nameof(param), \"A null tensor cannot be registered as a parameter.\");\n\n if (!_internal_params.TryAdd(name, param))\n throw new InvalidOperationException($\"Parameter {name} is already registered.\");\n }\n\n /// <summary>\n /// Alias for register_module()\n /// </summary>\n /// <param name=\"name\">\n /// name of the child module.\n /// The child module can be accessed from this module using the given name\n /// </param>\n /// <param name=\"module\">child module to be added to the module.</param>\n /// <exception cref=\"ArgumentException\"></exception>\n /// <exception cref=\"InvalidOperationException\"></exception>\n public void add_module(string name, Module module)\n => register_module(name, module);\n\n /// <summary>\n /// Register a submodule.\n /// </summary>\n /// <param name=\"name\">Name of the submodule.</param>\n /// <param name=\"submodule\">The module to register.</param>\n /// <exception cref=\"ArgumentException\"></exception>\n /// <exception cref=\"InvalidOperationException\"></exception>\n public virtual void register_module(string name, Module submodule)\n {\n if (submodule is null || submodule.handle.IsInvalid) {\n if (_internal_submodules.ContainsKey(name)) {\n _internal_submodules.Remove(name);\n }\n } else {\n if (name.Contains(\".\")) {\n throw new ArgumentException($\"module name can't contain \\\".\\\", got: {name}\");\n }\n if (string.IsNullOrEmpty(name)) {\n throw new ArgumentException(\"module name can't be empty string \\\"\\\"\");\n }\n if (_internal_submodules.ContainsKey(name)) {\n throw new InvalidOperationException($\"Sub-module {name} is already registered.\");\n }\n\n submodule.RegisterComponents();\n\n _internal_submodules.Add(name, submodule);\n }\n }\n\n protected void ConditionallyRegisterParameter(string name, Tensor value)\n {\n if (value is null) {\n if (_internal_params.ContainsKey(name)) {\n _internal_params.Remove(name);\n }\n } else {\n var p = value is Parameter parameter\n ? parameter\n : new Parameter(value, requires_grad: true);\n\n if (_internal_params.ContainsKey(name)) {\n _internal_params[name] = p;\n } else {\n _internal_params.Add(name, p);\n }\n }\n }\n\n protected void ConditionallyRegisterBuffer(string name, Tensor value)\n {\n if (value is null) {\n if (_internal_buffers.ContainsKey(name)) {\n _internal_buffers.Remove(name);\n }\n } else {\n if (_internal_buffers.ContainsKey(name)) {\n _internal_buffers[name] = value;\n } else {\n _internal_buffers.Add(name, value);\n }\n }\n }\n\n public virtual string GetName()\n {\n var res = THSNN_Module_name(handle);\n CheckForErrors();\n return res;\n }\n\n /// <summary>\n /// Save the parameters and buffers of the module to a disk location.\n /// </summary>\n /// <param name=\"location\">The file path.</param>\n /// <param name=\"skip\">A list of keys not to consider when saving the weights.</param>\n /// <returns></returns>\n public Module save(string location, IList<string> skip = null)\n {\n using var stream = System.IO.File.Create(location);\n using var writer = new System.IO.BinaryWriter(stream);\n save(writer, skip);\n\n return this;\n }\n\n /// <summary>\n /// Save the parameters and buffers of the module to a disk location.\n /// </summary>\n /// <param name=\"writer\">A binary writer instance.</param>\n /// <param name=\"skip\">A list of keys not to consider when saving the weights.</param>\n /// <returns></returns>\n public Module save(System.IO.BinaryWriter writer, IList<string> skip = null)\n {\n var sd = state_dict();\n\n // First, write how many entries.\n save_state_dict(writer, sd, skip);\n\n return this;\n }\n\n /// <summary>\n /// Save the parameters and buffers of the module to a disk location.\n /// </summary>\n /// <param name=\"stream\">A writable stream instance.</param>\n /// <param name=\"skip\">A list of keys not to consider when saving the weights.</param>\n /// <returns></returns>\n public Module save(System.IO.Stream stream, IList<string> skip = null)\n {\n using var writer = new System.IO.BinaryWriter(stream);\n return save(writer, skip);\n }\n\n /// <summary>\n ///\n /// </summary>\n /// <param name=\"writer\">A binary writer instance.</param>\n /// <param name=\"skip\">A list of keys not to consider when saving the weights.</param>\n /// <param name=\"sd\">A dictionary containing all the buffers and parameters of the module.</param>\n public static void save_state_dict(System.IO.BinaryWriter writer, Dictionary<string, Tensor> sd, IList<string> skip = null)\n {\n if (skip is not null && skip.Count > 0) {\n // We need to make a copy, so that the passed-in 'sd' isn't modified.\n var tmp = new Dictionary<string, Tensor>();\n foreach (var kv in sd.Where(kv => !skip.Contains(kv.Key))) {\n tmp.Add(kv.Key, kv.Value);\n }\n sd = tmp;\n }\n\n writer.Encode(sd.Count); // 4 bytes\n\n foreach (var kvp in sd) {\n writer.Write(kvp.Key);\n kvp.Value.Save(writer);\n }\n }\n\n /// <summary>\n /// Load the parameters and buffers\n /// </summary>\n /// <param name=\"location\">The file path.</param>\n /// <param name=\"strict\">\n /// If true, will only load a module if it exactly corresponds to the current module's state.\n /// If false, will load the parameters and buffers that it finds in the saved file,\n /// leaving everything else alone.\n /// </param>\n /// <param name=\"skip\">A list of keys not to consider when loading the dictionary.</param>\n /// <returns>The module, with parameters and buffers loaded.</returns>\n /// <remarks>\n /// Using a skip list only prevents tensors in the target module from being modified, it\n /// does not alter any logic related to checking for matching tensor element types or entries.\n /// It may be necessary to also pass 'strict=false' to avoid exceptions.\n /// </remarks>\n public virtual Module load(string location, bool strict = true, IList<string> skip = null)\n {\n if (!System.IO.File.Exists(location))\n throw new System.IO.FileNotFoundException(location);\n\n using var stream = System.IO.File.OpenRead(location);\n using var reader = new System.IO.BinaryReader(stream);\n load(reader, strict, skip);\n\n return this;\n }\n\n /// <summary>\n /// Load the parameters and buffers\n /// </summary>\n /// <param name=\"reader\">A binary reader instance.</param>\n /// <param name=\"strict\">\n /// If true, will only load a module if it exactly corresponds to the current module's state.\n /// If false, will load the parameters and buffers that it finds in the saved file,\n /// leaving everything else alone.\n /// </param>\n /// <param name=\"skip\">A list of keys not to consider when loading the dictionary.</param>\n /// <returns>The module, with parameters and buffers loaded.</returns>\n /// <remarks>\n /// Using a skip list only prevents tensors in the target module from being modified, it\n /// does not alter any logic related to checking for matching tensor element types or entries.\n /// It may be necessary to also pass 'strict=false' to avoid exceptions.\n /// </remarks>\n public virtual Module load(System.IO.BinaryReader reader, bool strict = true, IList<string> skip = null)\n {\n skip ??= Array.Empty<string>();\n\n var dt = _deviceType;\n var di = _deviceIndex;\n\n if (dt != DeviceType.CPU) this.cpu();\n\n try {\n var sd = state_dict();\n\n // First, figure out how many entries.\n var streamEntries = reader.Decode();\n\n if (streamEntries != sd.Count && strict)\n throw new ArgumentException($\"Mismatched state_dict sizes: expected {sd.Count}, but found {streamEntries} entries.\");\n\n for (int i = 0; i < streamEntries; ++i) {\n var key = reader.ReadString();\n var found = sd.ContainsKey(key);\n if (!found && strict)\n throw new ArgumentException($\"Mismatched module state names: the target modules does not have a submodule or buffer named '{key}'\");\n\n if (found) {\n sd[key].Load(reader, skip: skip.Contains(key));\n }\n }\n } finally {\n if (dt != DeviceType.CPU) _to(dt, di);\n }\n\n return this;\n }\n\n /// <summary>\n /// Load the parameters and buffers\n /// </summary>\n /// <param name=\"stream\">A readable stream instance.</param>\n /// <param name=\"strict\">\n /// If true, will only load a module if it exactly corresponds to the current module's state.\n /// If false, will load the parameters and buffers that it finds in the saved file,\n /// leaving everything else alone.\n /// </param>\n /// <param name=\"skip\">A list of keys not to consider when loading the dictionary.</param>\n /// <returns>The module, with parameters and buffers loaded.</returns>\n /// <remarks>\n /// Using a skip list only prevents tensors in the target module from being modified, it\n /// does not alter any logic related to checking for matching tensor element types or entries.\n /// It may be necessary to also pass 'strict=false' to avoid exceptions.\n /// </remarks>\n public Module load(System.IO.Stream stream, bool strict = true, IList<string> skip = null)\n {\n using var reader = new System.IO.BinaryReader(stream);\n return load(reader, strict, skip);\n }\n\n /// <summary>\n /// Create a module and load its weights from disk.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"path\"></param>\n /// <returns></returns>\n public static Module Create<T>(string path)\n where T : Module, new()\n {\n var model = new T();\n return model.load(path);\n }\n\n /// <summary>\n /// Constructor for custom modules, i.e. those defined outside of TorchSharp.\n /// </summary>\n /// <param name=\"name\">The name of the module. Useful for debugging purposes, mostly.</param>\n protected Module(string name) : this(IntPtr.Zero, IntPtr.Zero)\n {\n this.name = name;\n\n IntPtr ForwardNative(IntPtr t)\n {\n var input = new Tensor(t);\n var output = ((nn.Module<Tensor, Tensor>)this).call(input);\n\n // handles must live on - we don't own them, but\n // the managed objects should go away.\n input.DecoupleFromNativeHandle();\n\n return output.DecoupleFromNativeHandle();\n }\n\n var res = THSNN_custom_module(name, ForwardNative, out var boxedHandle);\n CheckForErrors();\n handle = new HType(res, true);\n this._forwardNative = ForwardNative;\n boxedModule = new BoxedModule(boxedHandle);\n\n _init_parameters();\n }\n\n private void _init_parameters()\n { \n // In this case, the parameter registration was not done yet.\n foreach (var (parameterName, parameter) in _named_parameters()) {\n register_parameter(parameterName, parameter);\n }\n }\n\n protected virtual void RegisterComponents()\n {\n if (_areComponentsRegistered) return;\n\n foreach (var field in GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {\n\n var fieldName = field.Name;\n if (_internal_submodules.ContainsKey(fieldName) || _internal_params.ContainsKey(fieldName) || _internal_buffers.ContainsKey(fieldName)) continue;\n\n var value = field.GetValue(this);\n\n switch (value) {\n case Module module:\n register_module(fieldName, module);\n break;\n case Parameter param: // This test must come before the Tensor test\n register_parameter(fieldName, param);\n break;\n case Tensor tensor:\n register_buffer(fieldName, tensor);\n break;\n }\n }\n\n _areComponentsRegistered = true;\n }\n\n protected static (Device device, ScalarType dtype) GetDefaultDeviceAndType(Device device = null, ScalarType? dtype = null)\n {\n if (!dtype.HasValue)\n dtype = get_default_dtype();\n\n if (device == null)\n device = torch.CPU;\n\n return (device, dtype.Value);\n }\n\n internal T MoveModule<T>(Device device, ScalarType? dtype) where T : Module\n {\n T module = (T)this;\n\n return device != null ?\n (dtype.HasValue ? (T)module._to(device, dtype.Value) : (T)module._to(device.type, device.index)) :\n (dtype.HasValue ? (T)module._to(dtype.Value) : module);\n }\n\n protected void ClearModules() { _internal_submodules.clear(); }\n\n private bool _areComponentsRegistered;\n\n protected Utils.OrderedDict<string, Module> _internal_submodules = new Utils.OrderedDict<string, Module>();\n protected Utils.OrderedDict<string, Tensor> _internal_buffers = new Utils.OrderedDict<string, Tensor>();\n protected Utils.OrderedDict<string, Parameter> _internal_params = new Utils.OrderedDict<string, Parameter>();\n\n /// Keeps the callback delegate alive\n private ForwardFunctionC _forwardNative;\n protected string name;\n }\n\n internal class BoxedModule : IDisposable\n {\n internal sealed class HType : SafeHandle\n {\n public HType(IntPtr preexistingHandle, bool ownsHandle) : base(IntPtr.Zero, ownsHandle)\n => SetHandle(preexistingHandle);\n\n public override bool IsInvalid => handle == IntPtr.Zero;\n\n // This is just for marshalling\n internal HType() : base(IntPtr.Zero, true)\n {\n }\n\n protected override bool ReleaseHandle()\n {\n if (!IsInvalid) THSNN_AnyModule_dispose(this);\n handle = IntPtr.Zero;\n return true;\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n ReleaseHandle();\n }\n }\n }\n\n internal HType handle;\n\n internal BoxedModule(IntPtr handle)\n {\n this.handle = new HType(handle, true);\n }\n\n ~BoxedModule() => Dispose(false);\n\n /// <summary>\n /// Releases the storage.\n /// </summary>\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n /// <summary>\n /// Implements the .NET Dispose pattern.\n /// </summary>\n protected void Dispose(bool disposing)\n {\n if (disposing) {\n handle.Dispose();\n handle.SetHandleAsInvalid();\n }\n }\n }\n\n /// <summary>\n /// Interface for concrete modules with a forward() that takes a single argument.\n /// </summary>\n /// <typeparam name=\"T\">The argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module's forward() function.</typeparam>\n public interface IModule<T, TResult>\n {\n public TResult call(T input1);\n }\n\n /// <summary>\n /// Interface for concrete modules with a forward() that takes two arguments.\n /// </summary>\n /// <typeparam name=\"T1\">The first argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T2\">The second argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module's forward() function.</typeparam>\n public interface IModule<T1, T2, TResult>\n {\n public abstract TResult call(T1 input1, T2 input2);\n }\n\n /// <summary>\n /// Interface for concrete modules with a forward() that takes three arguments.\n /// </summary>\n /// <typeparam name=\"T1\">The first argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T2\">The second argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T3\">The third argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module's forward() function.</typeparam>\n public interface IModule<T1, T2, T3, TResult>\n {\n public abstract TResult call(T1 input1, T2 input2, T3 input3);\n }\n\n /// <summary>\n /// Interface for concrete modules with a forward() that takes four arguments.\n /// </summary>\n /// <typeparam name=\"T1\">The first argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T2\">The second argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T3\">The third argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T4\">The fourth argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module's forward() function.</typeparam>\n public interface IModule<T1, T2, T3, T4, TResult>\n {\n public abstract TResult call(T1 input1, T2 input2, T3 input3, T4 input4);\n }\n\n /// <summary>\n /// Interface for concrete modules with a forward() that takes five arguments.\n /// </summary>\n /// <typeparam name=\"T1\">The first argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T2\">The second argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T3\">The third argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T4\">The fourth argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T5\">The fifth argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module's forward() function.</typeparam>\n public interface IModule<T1, T2, T3, T4, T5, TResult>\n {\n public abstract TResult call(T1 input1, T2 input2, T3 input3, T4 input4, T5 input5);\n }\n\n /// <summary>\n /// Interface for concrete modules with a forward() that takes six arguments.\n /// </summary>\n /// <typeparam name=\"T1\">The first argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T2\">The second argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T3\">The third argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T4\">The fourth argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T5\">The fifth argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T6\">The sixth argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module's forward() function.</typeparam>\n public interface IModule<T1, T2, T3, T4, T5, T6, TResult>\n {\n public abstract TResult call(T1 input1, T2 input2, T3 input3, T4 input4, T5 input5, T6 input6);\n }\n\n /// <summary>\n /// Represents a module that accepts 'hook' to the module logic.\n /// </summary>\n public class HookableModule<TPreHook,TPostHook> : Module\n {\n protected HookableModule(string name) : base(name) { }\n\n protected HookableModule(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n internal HookableModule(HType handle, IntPtr? boxedHandle) : base(handle, boxedHandle) { }\n\n public HookRemover register_forward_hook(TPostHook hook)\n {\n var key = Guid.NewGuid().ToString();\n post_hooks.Add(key, hook);\n return new HookRemover(this, key);\n }\n\n public HookRemover register_forward_pre_hook(TPreHook hook)\n {\n var key = Guid.NewGuid().ToString();\n pre_hooks.Add(key, hook);\n return new HookRemover(this, key);\n }\n\n private void remove(string key)\n {\n if (pre_hooks.ContainsKey(key)) pre_hooks.Remove(key);\n if (post_hooks.ContainsKey(key)) post_hooks.Remove(key);\n }\n\n protected Dictionary<string, TPreHook> pre_hooks = new Dictionary<string, TPreHook>();\n protected Dictionary<string, TPostHook> post_hooks = new Dictionary<string, TPostHook>();\n\n /// <summary>\n /// Used to remove a specific hook, following the PyTorch API design.\n /// </summary>\n /// <remarks>The name and namespace of this class is not the same as in PyTorch, but serves the same purpose.</remarks>\n public class HookRemover\n {\n public HookRemover(HookableModule<TPreHook, TPostHook> module, string key)\n {\n this.module = module;\n this.key = key;\n }\n\n public void remove()\n {\n module.remove(key);\n }\n\n private HookableModule<TPreHook, TPostHook> module;\n private string key;\n }\n }\n\n /// <summary>\n /// Base class for concrete modules with a forward() that takes a single argument.\n /// </summary>\n /// <typeparam name=\"T\">The argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module's forward() function.</typeparam>\n public abstract class Module<T, TResult> : HookableModule<Func<Module<T,TResult>, T, T>, Func<Module<T, TResult>, T, TResult, TResult>>, IModule<T, TResult>\n {\n protected Module(string name) : base(name) { }\n protected Module(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n internal Module(HType handle, IntPtr? boxedHandle) : base(handle, boxedHandle) { }\n\n /// <summary>\n /// Invoke the logic of the module.\n /// </summary>\n /// <remarks>`forward` will not invoke any registered hooks for the module.</remarks>\n public abstract TResult forward(T input);\n\n /// <summary>\n /// Invoke the logic of the module.\n /// </summary>\n /// <remarks>`call` will invoke any registered hooks for the module.</remarks>\n public TResult call(T input)\n {\n // Call pre-hooks, if available.\n\n foreach (var hook in pre_hooks.Values) {\n var modified = hook(this, input);\n if (modified is not null)\n input = modified;\n }\n\n var result = forward(input);\n\n // Call post-hooks, if available.\n\n foreach (var hook in post_hooks.Values) {\n var modified = hook(this, input, result);\n if (modified is not null)\n result = modified;\n }\n\n return result;\n }\n }\n\n /// <summary>\n /// Base class for concrete modules with a forward() that takes two arguments.\n /// </summary>\n /// <typeparam name=\"T1\">The first argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T2\">The second argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module's forward() function.</typeparam>\n public abstract class Module<T1, T2, TResult> : HookableModule<Func<Module<T1, T2, TResult>, T1, T2, (T1, T2)?>, Func<Module<T1, T2, TResult>, T1, T2, TResult, TResult>>, IModule<T1, T2, TResult>\n {\n protected Module(string name) : base(name) { }\n protected Module(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n internal Module(HType handle, IntPtr? boxedHandle) : base(handle, boxedHandle) { }\n\n /// <summary>\n /// Invoke the logic of the module.\n /// </summary>\n /// <remarks>`forward` will not invoke any registered hooks for the module.</remarks>\n public abstract TResult forward(T1 input1, T2 input2);\n\n /// <summary>\n /// Invoke the logic of the module.\n /// </summary>\n /// <remarks>`call` will invoke any registered hooks for the module.</remarks>\n public TResult call(T1 input1, T2 input2)\n {\n // Call pre-hooks, if available.\n\n foreach (var hook in pre_hooks.Values) {\n var modified = hook(this, input1, input2);\n if (modified.HasValue) {\n input1 = modified.Value.Item1;\n input2 = modified.Value.Item2;\n }\n }\n\n var result = forward(input1, input2);\n\n // Call post-hooks, if available.\n\n foreach (var hook in post_hooks.Values) {\n var modified = hook(this, input1, input2, result);\n if (modified is not null)\n result = modified;\n }\n\n return result;\n }\n }\n\n /// <summary>\n /// Base class for concrete modules with a forward() that takes three arguments.\n /// </summary>\n /// <typeparam name=\"T1\">The first argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T2\">The second argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T3\">The third argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module's forward() function.</typeparam>\n public abstract class Module<T1, T2, T3, TResult> : HookableModule<Func<Module<T1, T2, T3, TResult>, T1, T2, T3, (T1, T2, T3)?>, Func<Module<T1, T2, T3, TResult>, T1, T2, T3, TResult, TResult>>, IModule<T1, T2, T3, TResult>\n {\n protected Module(string name) : base(name) { }\n protected Module(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n internal Module(HType handle, IntPtr? boxedHandle) : base(handle, boxedHandle) { }\n\n /// <summary>\n /// Invoke the logic of the module.\n /// </summary>\n /// <remarks>`forward` will not invoke any registered hooks for the module.</remarks>\n public abstract TResult forward(T1 input1, T2 input2, T3 input3);\n\n /// <summary>\n /// Invoke the logic of the module.\n /// </summary>\n /// <remarks>`call` will invoke any registered hooks for the module.</remarks>\n public TResult call(T1 input1, T2 input2, T3 input3)\n {\n // Call pre-hooks, if available.\n\n foreach (var hook in pre_hooks.Values) {\n var modified = hook(this, input1, input2, input3);\n if (modified.HasValue) {\n input1 = modified.Value.Item1;\n input2 = modified.Value.Item2;\n input3 = modified.Value.Item3;\n }\n }\n\n var result = forward(input1, input2, input3);\n\n // Call post-hooks, if available.\n\n foreach (var hook in post_hooks.Values) {\n var modified = hook(this, input1, input2, input3, result);\n if (modified is not null)\n result = modified;\n }\n\n return result;\n }\n }\n\n /// <summary>\n /// Base class for concrete modules with a forward() that takes four arguments.\n /// </summary>\n /// <typeparam name=\"T1\">The first argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T2\">The second argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T3\">The third argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T4\">The fourth argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module's forward() function.</typeparam>\n public abstract class Module<T1, T2, T3, T4, TResult> : HookableModule<Func<Module<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, (T1, T2, T3, T4)?>, Func<Module<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult, TResult>>, IModule<T1, T2, T3, T4, TResult>\n {\n protected Module(string name) : base(name) { }\n protected Module(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n internal Module(HType handle, IntPtr? boxedHandle) : base(handle, boxedHandle) { }\n\n /// <summary>\n /// Invoke the logic of the module.\n /// </summary>\n /// <remarks>`forward` will not invoke any registered hooks for the module.</remarks>\n public abstract TResult forward(T1 input1, T2 input2, T3 input3, T4 input4);\n\n /// <summary>\n /// Invoke the logic of the module.\n /// </summary>\n /// <remarks>`call` will invoke any registered hooks for the module.</remarks>\n public TResult call(T1 input1, T2 input2, T3 input3, T4 input4)\n {\n // Call pre-hooks, if available.\n\n foreach (var hook in pre_hooks.Values) {\n var modified = hook(this, input1, input2, input3, input4);\n if (modified.HasValue) {\n input1 = modified.Value.Item1;\n input2 = modified.Value.Item2;\n input3 = modified.Value.Item3;\n input4 = modified.Value.Item4;\n }\n }\n\n var result = forward(input1, input2, input3, input4);\n\n // Call post-hooks, if available.\n\n foreach (var hook in post_hooks.Values) {\n var modified = hook(this, input1, input2, input3, input4, result);\n if (modified is not null)\n result = modified;\n }\n\n return result;\n }\n }\n\n /// <summary>\n /// Base class for concrete modules with a forward() that takes five arguments.\n /// </summary>\n /// <typeparam name=\"T1\">The first argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T2\">The second argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T3\">The third argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T4\">The fourth argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T5\">The fifth argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module's forward() function.</typeparam>\n public abstract class Module<T1, T2, T3, T4, T5,TResult> : HookableModule<Func<Module<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, (T1, T2, T3, T4, T5)?>, Func<Module<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult, TResult>>, IModule<T1, T2, T3, T4, T5, TResult>\n {\n protected Module(string name) : base(name) { }\n protected Module(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n internal Module(HType handle, IntPtr? boxedHandle) : base(handle, boxedHandle) { }\n\n /// <summary>\n /// Invoke the logic of the module.\n /// </summary>\n /// <remarks>`forward` will not invoke any registered hooks for the module.</remarks>\n public abstract TResult forward(T1 input1, T2 input2, T3 input3, T4 input4, T5 input5);\n\n /// <summary>\n /// Invoke the logic of the module.\n /// </summary>\n /// <remarks>`call` will invoke any registered hooks for the module.</remarks>\n public TResult call(T1 input1, T2 input2, T3 input3, T4 input4, T5 input5)\n {\n // Call pre-hooks, if available.\n\n foreach (var hook in pre_hooks.Values) {\n var modified = hook(this, input1, input2, input3, input4, input5);\n if (modified.HasValue) {\n input1 = modified.Value.Item1;\n input2 = modified.Value.Item2;\n input3 = modified.Value.Item3;\n input4 = modified.Value.Item4;\n input5 = modified.Value.Item5;\n }\n }\n\n var result = forward(input1, input2, input3, input4, input5);\n\n // Call post-hooks, if available.\n\n foreach (var hook in post_hooks.Values) {\n var modified = hook(this, input1, input2, input3, input4, input5, result);\n if (modified is not null)\n result = modified;\n }\n\n return result;\n }\n }\n\n /// <summary>\n /// Base class for concrete modules with a forward() that takes six arguments.\n /// </summary>\n /// <typeparam name=\"T1\">The first argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T2\">The second argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T3\">The third argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T4\">The fourth argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T5\">The fifth argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"T6\">The sixth argument type of the module's forward() function.</typeparam>\n /// <typeparam name=\"TResult\">The return type of the module's forward() function.</typeparam>\n public abstract class Module<T1, T2, T3, T4, T5, T6, TResult> : HookableModule<Func<Module<T1, T2, T3, T4, T5, T6, TResult>, T1, T2, T3, T4, T5, T6, (T1, T2, T3, T4, T5, T6)?>, Func<Module<T1, T2, T3, T4, T5, T6, TResult>, T1, T2, T3, T4, T5, T6, TResult, TResult>>, IModule<T1, T2, T3, T4, T5, T6, TResult>\n {\n protected Module(string name) : base(name) { }\n protected Module(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n internal Module(HType handle, IntPtr? boxedHandle) : base(handle, boxedHandle) { }\n\n /// <summary>\n /// Invoke the logic of the module.\n /// </summary>\n /// <remarks>`forward` will not invoke any registered hooks for the module.</remarks>\n public abstract TResult forward(T1 input1, T2 input2, T3 input3, T4 input4, T5 input5, T6 input6);\n\n /// <summary>\n /// Invoke the logic of the module.\n /// </summary>\n /// <remarks>`call` will invoke any registered hooks for the module.</remarks>\n public TResult call(T1 input1, T2 input2, T3 input3, T4 input4, T5 input5, T6 input6)\n {\n // Call pre-hooks, if available.\n\n foreach (var hook in pre_hooks.Values) {\n var modified = hook(this, input1, input2, input3, input4, input5, input6);\n if (modified.HasValue) {\n input1 = modified.Value.Item1;\n input2 = modified.Value.Item2;\n input3 = modified.Value.Item3;\n input4 = modified.Value.Item4;\n input5 = modified.Value.Item5;\n input6 = modified.Value.Item6;\n }\n }\n\n var result = forward(input1, input2, input3, input4, input5, input6);\n\n // Call post-hooks, if available.\n\n foreach (var hook in post_hooks.Values) {\n var modified = hook(this, input1, input2, input3, input4, input5, input6, result);\n if (modified is not null)\n result = modified;\n }\n\n return result;\n }\n }\n }\n }\n\n public static class ModuleExtensionMethods\n {\n /// <summary>\n /// Converts the parameters and buffers.\n /// </summary>\n /// <param name=\"module\">The module to move</param>\n /// <param name=\"type\">The target element type.</param>\n public static T to<T>(this T module, torch.ScalarType type) where T : torch.nn.Module\n {\n return (T)module._to(type);\n }\n\n /// <summary>\n /// Moves and converts the parameters and buffers.\n /// </summary>\n /// <param name=\"module\">The module to move</param>\n /// <param name=\"device\">The target device.</param>\n /// <param name=\"type\">The target element type.</param>\n public static T to<T>(this T module, torch.Device device, torch.ScalarType type) where T : torch.nn.Module\n {\n return (T)module._to(device, type);\n }\n\n /// <summary>\n /// Moves the parameters and buffers.\n /// </summary>\n /// <param name=\"module\">The module to move</param>\n /// <param name=\"deviceType\">The device type, e.g. 'CPU' or 'CUDA'.</param>\n /// <param name=\"deviceIndex\">The optional device index.</param>\n public static T to<T>(this T module, DeviceType deviceType, int deviceIndex = -1) where T : torch.nn.Module\n {\n return (T)module._to(deviceType, deviceIndex);\n }\n\n /// <summary>\n /// Moves the parameters and buffers.\n /// </summary>\n /// <param name=\"module\">The module to move</param>\"\n /// <param name=\"device\">The target device</param>\n /// <returns></returns>\n public static T to<T>(this T module, Device device) where T : torch.nn.Module => (T)module._to(device.type, device.index);\n\n /// <summary>\n /// Moves the parameters and buffers.\n /// </summary>\n /// <param name=\"module\">The module to move</param>\n /// <param name=\"device\">A string denoting the target device.</param>\n /// <returns></returns>\n /// <remarks>Relies on the Device constructor to parse the string.</remarks>\n public static T to<T>(this T module, string device) where T : torch.nn.Module\n {\n var dev = new Device(device);\n return (T)module._to(dev.type, dev.index);\n }\n\n /// <summary>\n /// Moves and converts the parameters and buffers.\n /// </summary>\n /// <param name=\"module\">The module to move</param>\n /// <param name=\"other\">The tensor serving as a template.</param>\n /// <returns></returns>\n public static T to<T>(this T module, Tensor other) where T : torch.nn.Module\n {\n return (T)module._to(other.device, other.dtype);\n }\n\n /// <summary>\n /// Moves all model parameters and buffers to the CPU.\n /// </summary>\n public static T cpu<T>(this T module) where T : torch.nn.Module => (T)module._to(DeviceType.CPU);\n\n /// <summary>\n /// Moves all model parameters and buffers to a GPU.\n ///\n /// This also makes associated parameters and buffers different objects.So it should be called before constructing optimizer if the module will live on GPU while being optimized.\n /// </summary>\n /// <param name=\"module\">The module to move</param>\n /// <param name=\"deviceIndex\">If specified, all parameters will be copied to that device</param>\n public static T cuda<T>(this T module, int deviceIndex = -1) where T : torch.nn.Module => (T)module._to(DeviceType.CUDA, deviceIndex);\n }\n\n internal delegate IntPtr ForwardFunctionC(IntPtr tensor);\n}\n" }, { "alpha_fraction": 0.6053891181945801, "alphanum_fraction": 0.6099536418914795, "avg_line_length": 43.980133056640625, "blob_id": "abdfbf99b0e55fea149856f90758f30f84d5495c", "content_id": "43a50d336c83fb5ff2e832e8e059620343c00e6f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 13583, "license_type": "permissive", "max_line_length": 130, "num_lines": 302, "path": "/src/TorchSharp/DisposeScope.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing TorchSharp.Utils;\n\n#nullable enable\nnamespace TorchSharp\n{\n /// <summary>\n /// Keeps track of all disposables that are in the current scope - the dispose scopes can be nested and the\n /// nesting functionality is mainly managed by DisposeScopeManager.\n /// </summary>\n public sealed class DisposeScope : IDisposable\n {\n private readonly DisposeScopeManager _disposeScopeManager;\n\n public DisposeScope(DisposeScopeManager disposeScopeManager)\n {\n _disposeScopeManager = disposeScopeManager ?? throw new ArgumentNullException(nameof(disposeScopeManager));\n if (disposeScopeManager.DisposeScopeStack.Count > 0) {\n OuterScope = disposeScopeManager.DisposeScopeStack.Peek();\n }\n }\n\n /// <summary>\n /// The outer scope with relation to this scope.\n /// </summary>\n internal DisposeScope? OuterScope { get; }\n\n /// <summary>\n /// The disposables that are scheduled for disposing.\n /// </summary>\n /// TODO: There is a ReferenceEqualityComparer coming in .NET 6, use that!\n internal HashSet<IDisposable> Disposables { get; private set; } =\n new HashSet<IDisposable>(ReferenceEqualityComparer<IDisposable>.Default);\n\n /// <summary>\n /// A view of the disposables in the scope - this list will not be kept in synch with the disposables\n /// in the scope.\n /// </summary>\n public IReadOnlyList<IDisposable> DisposablesView => Disposables.ToList();\n\n /// <summary>\n /// The number of disposables currently held in the scope\n /// </summary>\n public int DisposablesCount => Disposables.Count;\n\n /// <summary>\n /// Includes a disposable in the scope - for tensors this is done automatically once the scope has been\n /// created. Use this method to add additional disposables that should be disposed, but you typically\n /// don't need to call this method.\n /// </summary>\n /// <param name=\"disposable\">The disposable to keep in the scope</param>\n /// <returns></returns>\n public T Include<T>(T disposable) where T : IDisposable\n {\n Disposables.Add(disposable);\n return disposable;\n }\n\n /// <summary>\n /// Excludes a set of tensors/disposables from the current dispose scope, and moves it up to the outer\n /// dispose scope, if one exists. See overloaded methods. If you wish to exclude a tensor from all sccopes,\n /// use Detach.\n /// </summary>\n public T MoveToOuter<T>(T disposable) where T : IDisposable\n {\n MoveToOuter(new IDisposable[] { disposable });\n return disposable;\n }\n\n /// <summary>\n /// Excludes a set of tensors/disposables from the current dispose scope, and moves it up to the outer\n /// dispose scope, if one exists. See overloaded methods. If you wish to exclude a tensor from all sccopes,\n /// use Detach.\n /// </summary>\n public (T1 first, T2 second) MoveToOuter<T1, T2>(T1 first, T2 second)\n where T1 : IDisposable where T2 : IDisposable\n {\n MoveToOuter(new IDisposable[] { first, second });\n return (first, second);\n }\n\n /// <summary>\n /// Excludes a set of tensors/disposables from the current dispose scope, and moves it up to the outer\n /// dispose scope, if one exists. See overloaded methods. If you wish to exclude a tensor from all sccopes,\n /// use Detach.\n /// </summary>\n public (T1 first, T2 second, T3 third) MoveToOuter<T1, T2, T3>(T1 first, T2 second, T3 third)\n where T1 : IDisposable where T2 : IDisposable where T3 : IDisposable\n {\n MoveToOuter(new IDisposable[] { first, second, third });\n return (first, second, third);\n }\n\n /// <summary>\n /// Excludes a set of tensors/disposables from the current dispose scope, and moves it up to the outer\n /// dispose scope, if one exists. See overloaded methods. If you wish to exclude a tensor from all sccopes,\n /// use Detach.\n /// </summary>\n public void MoveToOuter(params IDisposable[] disposables) =>\n MoveToOuter((IEnumerable<IDisposable>)disposables);\n\n /// <summary>\n /// Excludes a set of tensors/disposables from the current dispose scope, and moves it up to the outer\n /// dispose scope, if one exists. See overloaded methods. If you wish to exclude a tensor from all sccopes,\n /// use Detach.\n /// </summary>\n public void MoveToOuter(IEnumerable<IDisposable> disposables)\n {\n foreach (var disposable in disposables) {\n if (Disposables.Remove(disposable)) {\n AddToParent(disposable);\n }\n }\n }\n\n /// <summary>\n /// Detaches/excludes a set of tensors/disposables from the all dispose scopes, see overloaded methods. See MoveToOuter\n /// if you wish to move it to the outer dispose scope.\n /// </summary>\n public T Detach<T>(T disposable) where T : IDisposable\n {\n Detach(new IDisposable[] { disposable });\n return disposable;\n }\n\n /// <summary>\n /// Detaches/excludes a set of tensors/disposables from the all dispose scopes, see overloaded methods. See MoveToOuter\n /// if you wish to move it to the outer dispose scope.\n /// </summary>\n public (T1 first, T2 second) Detach<T1, T2>(T1 first, T2 second)\n where T1 : IDisposable where T2 : IDisposable\n {\n Detach(new IDisposable[] { first, second });\n return (first, second);\n }\n\n /// <summary>\n /// Detaches/excludes a set of tensors/disposables from the all dispose scopes, see overloaded methods. See MoveToOuter\n /// if you wish to move it to the outer dispose scope.\n /// </summary>\n public (T1 first, T2 second, T3 third) Detach<T1, T2, T3>(T1 first, T2 second, T3 third)\n where T1 : IDisposable where T2 : IDisposable where T3 : IDisposable\n {\n Detach(new IDisposable[] { first, second, third });\n return (first, second, third);\n }\n\n /// <summary>\n /// Detaches/excludes a set of tensors/disposables from the all dispose scopes, see overloaded methods. See MoveToOuter\n /// if you wish to move it to the outer dispose scope.\n /// </summary>\n public void Detach(params IDisposable[] disposables) => Detach((IEnumerable<IDisposable>)disposables);\n\n /// <summary>\n /// Detaches/excludes a set of tensors/disposables from the all dispose scopes, see overloaded methods. See MoveToOuter\n /// if you wish to move it to the outer dispose scope.\n /// </summary>\n public void Detach(IEnumerable<IDisposable> disposables)\n {\n foreach (var disposable in disposables) {\n if (Disposables.Remove(disposable)) {\n _disposeScopeManager.StatisticsInstance.DetachedFromScopeCount++;\n if (disposable is torch.Tensor tensor) {\n tensor.OwningDisposeScope = null;\n }\n }\n }\n }\n\n /// <summary>\n /// Disposes everything currently in the dispose scope.\n /// </summary>\n public void DisposeEverything() => DisposeEverythingBut(Enumerable.Empty<IDisposable>());\n\n /// <summary>\n /// As an intermediate step, you can dispose all the tensors/disposables currently scheduled for dispose, to\n /// clear up some memory without creating a new scope. Note that this doesn't permanently exclude the\n /// tensors from disposing, use Exclude for that. Also, excluded tensors don't need to be included\n /// here.\n /// </summary>\n public void DisposeEverythingBut(IEnumerable<IDisposable> inKeep)\n {\n // Avoiding multiple enumerations\n var oldList = Disposables;\n Disposables = inKeep.ToHashSet(ReferenceEqualityComparer<IDisposable>.Default);\n foreach (var disposable in oldList) {\n if (Disposables.Contains(disposable)) {\n continue;\n }\n\n if (disposable is torch.Tensor tensor) {\n // No need to have the disposable call back to the scope\n tensor.OwningDisposeScope = null;\n if (!tensor.IsInvalid) {\n _disposeScopeManager.StatisticsInstance.DisposedInScopeCount++;\n }\n } else {\n _disposeScopeManager.StatisticsInstance.DisposedInScopeCount++;\n }\n\n disposable.Dispose();\n }\n }\n\n /// <summary>\n /// As an intermediate step, you can dispose all the tensors/disposables currently scheduled for dispose, to\n /// clear up some memory without creating a new scope. Note that this doesn't permanently exclude the\n /// tensors from disposing, use Exclude for that. Also, excluded tensors don't need to be included\n /// here.\n /// </summary>\n public void DisposeEverythingBut(params IDisposable[] keep) =>\n DisposeEverythingBut((IEnumerable<IDisposable>)keep);\n\n /// <summary>\n /// As an intermediate step, you can dispose all the tensors/disposables currently scheduled for dispose, to\n /// clear up some memory without creating a new scope. Note that this doesn't permanently exclude the\n /// tensors from disposing, use Exclude for that. Also, excluded tensors don't need to be included\n /// here.\n /// </summary>\n public T DisposeEverythingBut<T>(T keep) where T : IDisposable\n {\n DisposeEverythingBut(new IDisposable[] { keep });\n return keep;\n }\n\n /// <summary>\n /// As an intermediate step, you can dispose all the tensors/disposables currently scheduled for dispose, to\n /// clear up some memory without creating a new scope. Note that this doesn't permanently exclude the\n /// tensors from disposing, use Exclude for that. Also, excluded tensors don't need to be included\n /// here.\n /// </summary>\n public (T1 first, T2 second) DisposeEverythingBut<T1, T2>(T1 first, T2 second)\n where T1 : IDisposable where T2 : IDisposable\n {\n DisposeEverythingBut(new IDisposable[] { first, second });\n return (first, second);\n }\n\n /// <summary>\n /// As an intermediate step, you can dispose all the tensors/disposables currently scheduled for dispose, to\n /// clear up some memory without creating a new scope. Note that this doesn't permanently exclude the\n /// tensors from disposing, use Exclude for that. Also, excluded tensors don't need to be included\n /// here.\n /// </summary>\n public (T1 first, T2 second, T3 third) DisposeEverythingBut<T1, T2, T3>(T1 first, T2 second, T3 third)\n where T1 : IDisposable where T2 : IDisposable where T3 : IDisposable\n {\n DisposeEverythingBut(new IDisposable[] { first, second, third });\n return (first, second, third);\n }\n\n /// <summary>\n /// Disposes of the DisposeScope and all the disposables in its list. You would typically not call this method,\n /// instead you should use a usings clause around the scope.\n /// </summary>\n public void Dispose()\n {\n DisposeEverything();\n _disposeScopeManager.RemoveDisposeScope(this);\n }\n\n /// <summary>\n /// A method that notifies the DisposeScope that a disposable was disposed, so that it can be removed from the\n /// tracked list. This will be called if a tensor is manually disposed, but you can also add your own\n /// disposables to the dispose scope. If you do, and dispose them manually, you should make sure to call this\n /// method.\n /// </summary>\n /// <param name=\"disposable\">The disposable that was disposed</param>\n public void MarkAsDisposed(IDisposable disposable)\n {\n _disposeScopeManager.StatisticsInstance.DisposedInScopeCount++;\n Disposables.Remove(disposable);\n if (disposable is torch.Tensor tensor) {\n tensor.OwningDisposeScope = null;\n }\n }\n\n /// <summary>\n /// Checks if the DisposeScope contains the disposable\n /// </summary>\n /// <param name=\"disposable\">The disposable that's searched for</param>\n /// <returns></returns>\n public bool Contains(IDisposable disposable) => Disposables.Contains(disposable);\n\n private void AddToParent(IDisposable disposable)\n {\n if (OuterScope != null) {\n OuterScope.Disposables.Add(disposable);\n } else {\n _disposeScopeManager.StatisticsInstance.DetachedFromScopeCount++;\n }\n\n if (disposable is torch.Tensor tensor) {\n tensor.OwningDisposeScope = OuterScope;\n }\n }\n }\n}" }, { "alpha_fraction": 0.6992481350898743, "alphanum_fraction": 0.6992481350898743, "avg_line_length": 19.538461685180664, "blob_id": "9ee620badae5b6b7cd767e709773fd5390f2d0f0", "content_id": "42bd0ef72d3509ab1412d403281dade320d0ef64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 266, "license_type": "permissive", "max_line_length": 41, "num_lines": 13, "path": "/src/TorchSharp/PInvoke/TensorOrScalar.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System;\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp.PInvoke\n{\n [StructLayout(LayoutKind.Sequential)]\n internal struct TensorOrScalar\n {\n public long TypeCode;\n public long ArrayIndex;\n public IntPtr Handle;\n }\n}" }, { "alpha_fraction": 0.6620370149612427, "alphanum_fraction": 0.6620370149612427, "avg_line_length": 23.11111068725586, "blob_id": "ba6474ae9b8689ae28d619a2dc0c38332292a822", "content_id": "b70213e1548037a93fee73fab1f754b413015a65", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 218, "license_type": "permissive", "max_line_length": 131, "num_lines": 9, "path": "/src/TorchSharp/Tensor/Enums/indexing.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nnamespace TorchSharp\n{\n public enum indexing\n {\n xy,\n ij\n }\n}" }, { "alpha_fraction": 0.593024730682373, "alphanum_fraction": 0.6021500825881958, "avg_line_length": 41.328041076660156, "blob_id": "4c1a0836e6290ab2b2539895653a6449ae2740fb", "content_id": "2b9d44ceb74a59122ca83ac6d124e9295bb24f79", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 23999, "license_type": "permissive", "max_line_length": 200, "num_lines": 567, "path": "/src/TorchSharp/netstandard.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n//\n// This file contains the implementation of functionality exist in .NET and not supported in netstandard.\n// The implementation is supported on Windows only. The goal mainly is to support .NET Framework.\n//\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\nnamespace System\n{\n internal static partial class NSExtension\n {\n public static HashSet<TSource> ToHashSet<TSource>(this IEnumerable<TSource> source) => source.ToHashSet(comparer: null);\n\n public static HashSet<TSource> ToHashSet<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)\n {\n if (source == null)\n {\n throw new ArgumentNullException(nameof(source));\n }\n\n // Don't pre-allocate based on knowledge of size, as potentially many elements will be dropped.\n return new HashSet<TSource>(source, comparer);\n }\n\n public static bool TryAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)\n {\n if (!dictionary.TryGetValue(key, out _))\n {\n dictionary.Add(key, value);\n return true;\n }\n\n return false;\n }\n\n public static bool Contains(this string source, char c) => !string.IsNullOrEmpty(source) && source.IndexOf(c) >= 0;\n public static bool EndsWith(this string source, char c) => !string.IsNullOrEmpty(source) && source[source.Length - 1] == c;\n public static bool StartsWith(this string source, char c) => !string.IsNullOrEmpty(source) && source[0] == c;\n }\n\n // MathF emulation on platforms which don't support it natively.\n internal static class MathF\n {\n public const float PI = (float)Math.PI;\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Max(float x, float y) => Math.Max(x, y);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Round(float x) => (float)Math.Round(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sqrt(float x) => (float)Math.Sqrt(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Sign(float x) => Math.Sign(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Abs(float x) => Math.Abs(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Log10(float x) => log10f(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Log2(float x) => log2f(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Acos(float x) => acosf(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Cos(float x) => cosf(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Cosh(float x) => coshf(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Atan(float x) => atanf(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Tanh(float x) => tanhf(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Pow(float x, float y) => powf(x, y);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sin(float x) => sinf(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sinh(float x) => sinhf(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Asinh(float x) => asinhf(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Tan(float x) => tanf(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Acosh(float x) => acoshf(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Atanh(float x) => atanhf(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Asin(float x) => asinf(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Log(float x) => logf(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Exp(float x) => expf(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Floor(float x) => floorf(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Ceiling(float x) => ceilf(x);\n [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Truncate(float x) => truncf(x);\n\n public static float Log(float x, float y)\n {\n if (float.IsNaN(x))\n {\n return x; // IEEE 754-2008: NaN payload must be preserved\n }\n\n if (float.IsNaN(y))\n {\n return y; // IEEE 754-2008: NaN payload must be preserved\n }\n\n if (y == 1)\n {\n return float.NaN;\n }\n\n if ((x != 1) && ((y == 0) || float.IsPositiveInfinity(y)))\n {\n return float.NaN;\n }\n\n return Log(x) / Log(y);\n }\n\n public static float IEEERemainder(float x, float y)\n {\n if (float.IsNaN(x))\n {\n return x; // IEEE 754-2008: NaN payload must be preserved\n }\n\n if (float.IsNaN(y))\n {\n return y; // IEEE 754-2008: NaN payload must be preserved\n }\n\n float regularMod = x % y;\n\n if (float.IsNaN(regularMod))\n {\n return float.NaN;\n }\n\n if ((regularMod == 0) && IsNegative(x))\n {\n return NegativeZero;\n }\n\n float alternativeResult = (regularMod - (Abs(y) * Sign(x)));\n\n if (Abs(alternativeResult) == Abs(regularMod))\n {\n float divisionResult = x / y;\n float roundedResult = Round(divisionResult);\n\n if (Abs(roundedResult) > Abs(divisionResult))\n {\n return alternativeResult;\n }\n else\n {\n return regularMod;\n }\n }\n\n if (Abs(alternativeResult) < Abs(regularMod))\n {\n return alternativeResult;\n }\n else\n {\n return regularMod;\n }\n }\n\n internal const float NegativeZero = (float)-0.0;\n internal static bool IsNegative(float x) => (((ulong)BitConverter.DoubleToInt64Bits(x)) & 0x8000000000000000) == 0x8000000000000000;\n\n private const string CrtLibrary = \"ucrtbase.dll\";\n [DllImport(CrtLibrary)] private static extern float asinhf(float x);\n [DllImport(CrtLibrary)] private static extern float acosf(float x);\n [DllImport(CrtLibrary)] private static extern float cosf(float x);\n [DllImport(CrtLibrary)] private static extern float coshf(float x);\n [DllImport(CrtLibrary)] private static extern float atanf(float x);\n [DllImport(CrtLibrary)] private static extern float tanhf(float x);\n [DllImport(CrtLibrary)] private static extern float powf(float x, float y);\n [DllImport(CrtLibrary)] private static extern float sinf(float x);\n [DllImport(CrtLibrary)] private static extern float sinhf(float x);\n [DllImport(CrtLibrary)] private static extern float tanf(float x);\n [DllImport(CrtLibrary)] private static extern float logf(float x);\n [DllImport(CrtLibrary)] private static extern float acoshf(float x);\n [DllImport(CrtLibrary)] private static extern float atanhf(float x);\n [DllImport(CrtLibrary)] private static extern float asinf(float x);\n [DllImport(CrtLibrary)] private static extern float log10f(float x);\n [DllImport(CrtLibrary)] private static extern float log2f(float x);\n [DllImport(CrtLibrary)] private static extern float expf(float x);\n [DllImport(CrtLibrary)] private static extern float floorf(float x);\n [DllImport(CrtLibrary)] private static extern float ceilf(float x);\n [DllImport(CrtLibrary)] private static extern float truncf(float x);\n }\n\n internal static partial class NativeLibrary\n {\n [DllImport(\"kernel32.dll\", CharSet=CharSet.Unicode, SetLastError = true)]\n internal static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hReservedNull, int dwFlags);\n\n public static bool TryLoad(string libraryPath, out IntPtr handle)\n {\n if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n throw new NotSupportedException(\"This call is not supported on non-Windows platforms.\");\n }\n\n if (libraryPath == null)\n throw new ArgumentNullException(nameof(libraryPath));\n\n handle = LoadFromPath(libraryPath, throwOnError: false);\n return handle != IntPtr.Zero;\n }\n\n public static bool TryLoad(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, out IntPtr handle)\n {\n if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n throw new NotSupportedException(\"This call is not supported on non-Windows platforms.\");\n }\n\n if (libraryName == null)\n throw new ArgumentNullException(nameof(libraryName));\n if (assembly == null)\n throw new ArgumentNullException(nameof(assembly));\n\n handle = LoadLibraryByName(libraryName,\n assembly,\n searchPath,\n throwOnError: false);\n return handle != IntPtr.Zero;\n }\n\n internal static IntPtr LoadLibraryByName(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, bool throwOnError)\n {\n // First checks if a default dllImportSearchPathFlags was passed in, if so, use that value.\n // Otherwise checks if the assembly has the DefaultDllImportSearchPathsAttribute attribute.\n // If so, use that value.\n\n int searchPathFlags;\n bool searchAssemblyDirectory;\n if (searchPath.HasValue)\n {\n searchPathFlags = (int)(searchPath.Value & ~DllImportSearchPath.AssemblyDirectory);\n searchAssemblyDirectory = (searchPath.Value & DllImportSearchPath.AssemblyDirectory) != 0;\n }\n else\n {\n GetDllImportSearchPathFlags(assembly, out searchPathFlags, out searchAssemblyDirectory);\n }\n\n LoadLibErrorTracker errorTracker = default;\n IntPtr ret = LoadBySearch(assembly, searchAssemblyDirectory, searchPathFlags, ref errorTracker, libraryName);\n if (throwOnError && ret == IntPtr.Zero)\n {\n errorTracker.Throw(libraryName);\n }\n\n return ret;\n }\n\n internal static IntPtr LoadBySearch(Assembly callingAssembly, bool searchAssemblyDirectory, int dllImportSearchPathFlags, ref LoadLibErrorTracker errorTracker, string libraryName)\n {\n IntPtr ret;\n\n int loadWithAlteredPathFlags = 0;\n bool libNameIsRelativePath = !Path.IsPathRooted(libraryName);\n\n foreach (LibraryNameVariation libraryNameVariation in LibraryNameVariation.DetermineLibraryNameVariations(libraryName, libNameIsRelativePath))\n {\n string currLibNameVariation = libraryNameVariation.Prefix + libraryName + libraryNameVariation.Suffix;\n\n if (!libNameIsRelativePath)\n {\n int flags = loadWithAlteredPathFlags;\n if ((dllImportSearchPathFlags & (int)DllImportSearchPath.UseDllDirectoryForDependencies) != 0)\n {\n // LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR is the only flag affecting absolute path. Don't OR the flags\n // unconditionally as all absolute path P/Invokes could then lose LOAD_WITH_ALTERED_SEARCH_PATH.\n flags |= dllImportSearchPathFlags;\n }\n\n ret = LoadLibraryHelper(currLibNameVariation, flags, ref errorTracker);\n if (ret != IntPtr.Zero)\n {\n return ret;\n }\n }\n else if ((callingAssembly != null) && searchAssemblyDirectory)\n {\n // Try to load the module alongside the assembly where the PInvoke was declared.\n // This only makes sense in dynamic scenarios (JIT/interpreter), so leaving this out for now.\n }\n\n ret = LoadLibraryHelper(currLibNameVariation, dllImportSearchPathFlags, ref errorTracker);\n if (ret != IntPtr.Zero)\n {\n return ret;\n }\n }\n\n return IntPtr.Zero;\n }\n\n internal static void GetDllImportSearchPathFlags(Assembly callingAssembly, out int searchPathFlags, out bool searchAssemblyDirectory)\n {\n var searchPath = DllImportSearchPath.AssemblyDirectory;\n\n foreach (CustomAttributeData cad in callingAssembly.CustomAttributes)\n {\n if (cad.AttributeType == typeof(DefaultDllImportSearchPathsAttribute))\n {\n searchPath = (DllImportSearchPath)cad.ConstructorArguments[0].Value!;\n }\n }\n\n searchPathFlags = (int)(searchPath & ~DllImportSearchPath.AssemblyDirectory);\n searchAssemblyDirectory = (searchPath & DllImportSearchPath.AssemblyDirectory) != 0;\n }\n\n private static IntPtr LoadFromPath(string libraryName, bool throwOnError)\n {\n LoadLibErrorTracker errorTracker = default;\n IntPtr ret = LoadLibraryHelper(libraryName, 0, ref errorTracker);\n if (throwOnError && ret == IntPtr.Zero)\n {\n errorTracker.Throw(libraryName);\n }\n\n return ret;\n }\n\n private static IntPtr LoadLibraryHelper(string libraryName, int flags, ref LoadLibErrorTracker errorTracker)\n {\n IntPtr ret = LoadLibraryEx(libraryName, IntPtr.Zero, flags);\n if (ret != IntPtr.Zero)\n {\n return ret;\n }\n\n int lastError = Marshal.GetLastWin32Error();\n if (lastError != LoadLibErrorTracker.ERROR_INVALID_PARAMETER)\n {\n errorTracker.TrackErrorCode(lastError);\n }\n\n return ret;\n }\n\n internal struct LoadLibErrorTracker\n {\n internal const int ERROR_INVALID_PARAMETER = 0x57;\n internal const int ERROR_MOD_NOT_FOUND = 126;\n internal const int ERROR_BAD_EXE_FORMAT = 193;\n\n private int _errorCode;\n\n public void Throw(string libraryName)\n {\n if (_errorCode == ERROR_BAD_EXE_FORMAT)\n {\n throw new BadImageFormatException();\n }\n\n throw new DllNotFoundException($\"Unable to native library '{libraryName}' or one of its dependencies.\");\n }\n\n public void TrackErrorCode(int errorCode)\n {\n _errorCode = errorCode;\n }\n\n }\n\n internal partial struct LibraryNameVariation\n {\n private const string LibraryNameSuffix = \".dll\";\n\n public string Prefix;\n public string Suffix;\n\n public LibraryNameVariation(string prefix, string suffix)\n {\n Prefix = prefix;\n Suffix = suffix;\n }\n\n internal static IEnumerable<LibraryNameVariation> DetermineLibraryNameVariations(string libName, bool isRelativePath, bool forOSLoader = false)\n {\n // This is a copy of the logic in DetermineLibNameVariations in dllimport.cpp in CoreCLR\n\n yield return new LibraryNameVariation(string.Empty, string.Empty);\n\n // Follow LoadLibrary rules if forOSLoader is true\n if (isRelativePath &&\n (!forOSLoader || libName.Contains('.') && !libName.EndsWith('.')) &&\n !libName.EndsWith(\".dll\", StringComparison.OrdinalIgnoreCase) &&\n !libName.EndsWith(\".exe\", StringComparison.OrdinalIgnoreCase))\n {\n yield return new LibraryNameVariation(string.Empty, LibraryNameSuffix);\n }\n }\n }\n }\n}\n\nnamespace System.Diagnostics.CodeAnalysis\n{\n [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n internal sealed class MaybeNullWhenAttribute : Attribute\n {\n /// <summary>Initializes the attribute with the specified return value condition.</summary>\n /// <param name=\"returnValue\">\n /// The return value condition. If the method returns this value, the associated parameter may be null.\n /// </param>\n public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;\n\n /// <summary>Gets the return value condition.</summary>\n public bool ReturnValue { get; }\n }\n}\n\nnamespace System.Linq\n{\n internal static partial class NSEnumerable\n {\n public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)\n {\n if (first is null)\n {\n throw new ArgumentNullException(nameof(first));\n }\n\n if (second is null)\n {\n throw new ArgumentNullException(nameof(second));\n }\n\n if (resultSelector is null)\n {\n throw new ArgumentNullException(nameof(resultSelector));\n }\n\n return ZipIterator(first, second, resultSelector);\n }\n\n public static IEnumerable<(TFirst First, TSecond Second)> Zip<TFirst, TSecond>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second)\n {\n if (first is null)\n {\n throw new ArgumentNullException(nameof(first));\n }\n\n if (second is null)\n {\n throw new ArgumentNullException(nameof(second));\n }\n\n return ZipIterator(first, second);\n }\n\n public static IEnumerable<(TFirst First, TSecond Second, TThird Third)> Zip<TFirst, TSecond, TThird>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, IEnumerable<TThird> third)\n {\n if (first is null)\n {\n throw new ArgumentNullException(nameof(first));\n }\n\n if (second is null)\n {\n throw new ArgumentNullException(nameof(second));\n }\n\n if (third is null)\n {\n throw new ArgumentNullException(nameof(third));\n }\n\n return ZipIterator(first, second, third);\n }\n\n private static IEnumerable<(TFirst First, TSecond Second)> ZipIterator<TFirst, TSecond>(IEnumerable<TFirst> first, IEnumerable<TSecond> second)\n {\n using (IEnumerator<TFirst> e1 = first.GetEnumerator())\n using (IEnumerator<TSecond> e2 = second.GetEnumerator())\n {\n while (e1.MoveNext() && e2.MoveNext())\n {\n yield return (e1.Current, e2.Current);\n }\n }\n }\n\n private static IEnumerable<TResult> ZipIterator<TFirst, TSecond, TResult>(IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)\n {\n using (IEnumerator<TFirst> e1 = first.GetEnumerator())\n using (IEnumerator<TSecond> e2 = second.GetEnumerator())\n {\n while (e1.MoveNext() && e2.MoveNext())\n {\n yield return resultSelector(e1.Current, e2.Current);\n }\n }\n }\n\n private static IEnumerable<(TFirst First, TSecond Second, TThird Third)> ZipIterator<TFirst, TSecond, TThird>(IEnumerable<TFirst> first, IEnumerable<TSecond> second, IEnumerable<TThird> third)\n {\n using (IEnumerator<TFirst> e1 = first.GetEnumerator())\n using (IEnumerator<TSecond> e2 = second.GetEnumerator())\n using (IEnumerator<TThird> e3 = third.GetEnumerator())\n {\n while (e1.MoveNext() && e2.MoveNext() && e3.MoveNext())\n {\n yield return (e1.Current, e2.Current, e3.Current);\n }\n }\n }\n }\n}\n\nnamespace System.IO\n{\n internal class NSPath\n {\n internal const char DirectorySeparatorChar = '\\\\'; // Windows implementation\n internal const char AltDirectorySeparatorChar = '/';\n internal const string DirectorySeparatorCharAsString = \"\\\\\";\n\n public static string Join(string path1, string path2)\n {\n if (path1 is null || path1.Length == 0)\n return path2;\n if (path2 is null || path2.Length == 0)\n return path1;\n\n bool hasSeparator = IsDirectorySeparator(path1[path1.Length - 1]) || IsDirectorySeparator(path2[0]);\n return hasSeparator ? string.Concat(path1, path2) : string.Concat(path1, DirectorySeparatorCharAsString, path2);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n internal static bool IsDirectorySeparator(char c) => c == DirectorySeparatorChar || c == AltDirectorySeparatorChar;\n\n public static string Join(string path1, string path2, string path3)\n {\n if (path1 is null || path1.Length == 0)\n return Join(path2, path3);\n\n if (path2 is null || path2.Length == 0)\n return Join(path1, path3);\n\n if (path3 is null || path3.Length == 0)\n return Join(path1, path2);\n\n bool firstHasSeparator = IsDirectorySeparator(path1[path1.Length - 1]) || IsDirectorySeparator(path2[0]);\n bool secondHasSeparator = IsDirectorySeparator(path2[path2.Length - 1]) || IsDirectorySeparator(path3[0]);\n return path1 + (firstHasSeparator ? \"\" : DirectorySeparatorCharAsString) + path2 + (secondHasSeparator ? \"\" : DirectorySeparatorCharAsString) + path3;\n }\n\n public static string Join(string path1, string path2, string path3, string path4)\n {\n if (path1 is null || path1.Length == 0)\n return Join(path2, path3, path4);\n\n if (path2 is null || path2.Length == 0)\n return Join(path1, path3, path4);\n\n if (path3 is null || path3.Length == 0)\n return Join(path1, path2, path4);\n\n if (path4 is null || path4.Length == 0)\n return Join(path1, path2, path3);\n\n bool firstHasSeparator = IsDirectorySeparator(path1[path1.Length - 1]) || IsDirectorySeparator(path2[0]);\n bool secondHasSeparator = IsDirectorySeparator(path2[path2.Length - 1]) || IsDirectorySeparator(path3[0]);\n bool thirdHasSeparator = IsDirectorySeparator(path3[path3.Length - 1]) || IsDirectorySeparator(path4[0]);\n\n return path1 + (firstHasSeparator ? \"\" : DirectorySeparatorCharAsString) +\n path2 + (secondHasSeparator ? \"\" : DirectorySeparatorCharAsString) +\n path3 + (thirdHasSeparator ? \"\" : DirectorySeparatorCharAsString) +\n path4;\n }\n }\n}" }, { "alpha_fraction": 0.5804773569107056, "alphanum_fraction": 0.5829253196716309, "avg_line_length": 46.36231994628906, "blob_id": "11ef884f5387b362ebf9ed98ddb722bd0f865f42", "content_id": "70a1858f09b10a684bd1d33112f2b9cd30986327", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6540, "license_type": "permissive", "max_line_length": 149, "num_lines": 138, "path": "/src/TorchSharp/Distributions/Gamma.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// A Gamma distribution parameterized by shape `concentration` and `rate`.\n /// </summary>\n public class Gamma : torch.distributions.ExponentialFamily\n {\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public override Tensor mean => WrappedTensorDisposeScope(() => concentration / rate);\n\n public override Tensor mode => WrappedTensorDisposeScope(() => ((concentration - 1) / rate).clamp_(min: 0));\n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public override Tensor variance => WrappedTensorDisposeScope(() => concentration / rate.pow(2));\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"concentration\">Shape parameter of the distribution (often referred to as 'α')</param>\n /// <param name=\"rate\">rate = 1 / scale of the distribution (often referred to as 'β')</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n public Gamma(Tensor concentration, Tensor rate, torch.Generator generator = null) : base(generator)\n {\n var locScale = torch.broadcast_tensors(concentration, rate);\n this.concentration = locScale[0].DetachFromDisposeScope();\n this.rate = locScale[1].DetachFromDisposeScope();\n this.batch_shape = this.concentration.size();\n }\n\n protected Tensor concentration;\n private Tensor rate;\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n public override Tensor rsample(params long[] sample_shape)\n {\n using var _ = torch.NewDisposeScope();\n var shape = ExtendedShape(sample_shape);\n var value = torch._standard_gamma(concentration.expand(shape), generator: generator) / rate.expand(shape);\n return value.detach().clamp_(min: torch.finfo(value.dtype).tiny).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor log_prob(Tensor value)\n {\n using var _ = torch.NewDisposeScope();\n value = torch.as_tensor(value, dtype: rate.dtype, device: rate.device);\n var result = concentration * rate.log() + (concentration - 1) * value.log() - rate * value - torch.lgamma(concentration);\n return result.MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n public override Tensor entropy() =>\n WrappedTensorDisposeScope(() =>\n concentration - rate.log() + concentration.lgamma() + (1.0 - concentration) * concentration.digamma());\n\n public override Tensor cdf(Tensor value) =>\n WrappedTensorDisposeScope(() => torch.special.gammainc(concentration, rate * value));\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is Gamma))\n throw new ArgumentException(\"expand(): 'instance' must be a Gamma distribution\");\n\n var c = concentration.expand(batch_shape);\n var r = rate.expand(batch_shape);\n\n var newDistribution = ((instance == null) ? new Gamma(c, r, generator) : instance) as Gamma;\n\n newDistribution.batch_shape = batch_shape;\n if (newDistribution == instance) {\n newDistribution.concentration = c;\n newDistribution.rate = r;\n }\n return newDistribution;\n }\n\n protected override IList<Tensor> NaturalParams => new Tensor[] { concentration - 1, rate };\n\n protected override Tensor MeanCarrierMeasure => torch.tensor(0, dtype:rate.dtype, device: rate.device);\n\n protected override Tensor LogNormalizer(params Tensor[] parameters)\n {\n var x = parameters[0];\n var y = parameters[1];\n\n return torch.lgamma(x + 1) + (x + 1) * torch.log(-y.reciprocal());\n }\n }\n\n }\n\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a Gamma distribution parameterized by shape `concentration` and `rate`.\n /// </summary>\n /// <param name=\"concentration\">Shape parameter of the distribution (often referred to as 'α')</param>\n /// <param name=\"rate\">rate = 1 / scale of the distribution (often referred to as 'β')</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Gamma Gamma(Tensor concentration, Tensor rate, torch.Generator generator = null)\n {\n return new Gamma(concentration, rate, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5351672172546387, "alphanum_fraction": 0.5367302298545837, "avg_line_length": 38.0121955871582, "blob_id": "e14378277b260b3c9865dfdbf5012e4192c33148", "content_id": "9fb1d3d6e9980d8f133772689517c9375eb13e77", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3199, "license_type": "permissive", "max_line_length": 132, "num_lines": 82, "path": "/src/TorchSharp/NN/Activation/PReLU.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a PReLU module.\n /// </summary>\n public sealed class PReLU : torch.nn.Module<Tensor, Tensor>\n {\n internal PReLU(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_PReLU_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public override string GetName()\n {\n return typeof(PReLU).Name;\n }\n\n public Parameter? weight {\n get {\n var res = THSNN_PReLU_weight(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n set {\n THSNN_PReLU_set_weight(handle, value!.Handle);\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"weight\", value);\n }\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Parameterized Rectified Linear Unit\n /// </summary>\n /// <param name=\"num_parameters\">\n /// Number of 'a' to learn.\n /// Although it takes an int as input, there is only two values are legitimate: 1, or the number of channels at input.\n /// </param>\n /// <param name=\"init\">The initial value of 'a'.</param>\n /// <param name=\"device\">The desired device of the parameters and buffers in this module</param>\n /// <param name=\"dtype\">The desired floating point or complex dtype of the parameters and buffers in this module</param>\n public static PReLU PReLU(long num_parameters, double init = 0.25, Device? device = null, ScalarType? dtype = null)\n {\n var handle = THSNN_PReLU_ctor(num_parameters, init, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new PReLU(handle, boxedHandle).MoveModule<PReLU>(device, dtype);\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Parameterized Rectified Linear Unit\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"weight\">Weight is expected to be a scalar or 1-D tensor.</param>\n public static Tensor prelu(Tensor input, Tensor weight)\n {\n return input.prelu(weight);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5407118201255798, "alphanum_fraction": 0.5411993861198425, "avg_line_length": 31.55555534362793, "blob_id": "60e9be32a739f1f7d85ad6a9c8d8a2ad42d85422", "content_id": "8027843562e85e3f9a6f5fcab8fb4ee4cd531345", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2051, "license_type": "permissive", "max_line_length": 130, "num_lines": 63, "path": "/src/TorchSharp/NN/Activation/LogSigmoid.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a LogSigmoid module.\n /// </summary>\n public sealed class LogSigmoid : torch.nn.Module<Tensor, Tensor>\n {\n internal LogSigmoid() : base(nameof(LogSigmoid)) { }\n\n public override Tensor forward(Tensor tensor)\n {\n return tensor.log_sigmoid();\n }\n\n public override string GetName()\n {\n return typeof(LogSigmoid).Name;\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// LogSigmoid activation\n /// </summary>\n /// <returns></returns>\n public static LogSigmoid LogSigmoid()\n {\n return new LogSigmoid();\n }\n\n public static partial class functional\n {\n /// <summary>\n /// LogSigmoid activation\n /// </summary>\n /// <param name=\"x\">The input tensor</param>\n /// <returns></returns>\n public static Tensor logsigmoid(Tensor x)\n {\n return x.log_sigmoid();\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5108544230461121, "alphanum_fraction": 0.518925666809082, "avg_line_length": 41.779762268066406, "blob_id": "98d550e3f7aecff71f2ae88945c3e5c0d3a88bc3", "content_id": "a5eefcd5ecfff5b3f3d13fcd38f79aa7793a899b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7186, "license_type": "permissive", "max_line_length": 178, "num_lines": 168, "path": "/src/TorchAudio/Transforms/MelSpectrogram.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchaudio,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/audio/blob/bb77cbebb620a46fdc0dc7e6dae2253eef3f37e2/torchaudio/transforms/_transforms.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/audio/blob/main/LICENSE\n//\n\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\nusing static TorchSharp.torchaudio;\n\nnamespace TorchSharp\n{\n namespace Transforms\n {\n public class MelSpectrogram : Module<Tensor, Tensor>\n {\n public readonly long sample_rate;\n public readonly long n_fft;\n public readonly long win_length;\n public readonly long hop_length;\n public readonly long pad;\n public readonly double power;\n public readonly bool normalized;\n public readonly long n_mels;\n public readonly double? f_max;\n public readonly double f_min;\n public readonly Spectrogram spectrogram;\n public readonly MelScale mel_scale;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n spectrogram.Dispose();\n mel_scale.Dispose();\n }\n base.Dispose(disposing);\n }\n\n\n internal MelSpectrogram(\n string name,\n long sample_rate = 16000,\n long n_fft = 400,\n long? win_length = null,\n long? hop_length = null,\n double f_min = 0.0,\n double? f_max = null,\n long pad = 0,\n long n_mels = 128,\n WindowFunction window_fn = null,\n double power = 2.0,\n bool normalized = false,\n bool center = true,\n PaddingModes pad_mode = PaddingModes.Reflect,\n bool onesided = true,\n MelNorm norm = MelNorm.none,\n torchaudio.MelScale mel_scale = torchaudio.MelScale.htk) : base(name)\n {\n this.sample_rate = sample_rate;\n this.n_fft = n_fft;\n this.win_length = win_length ?? n_fft;\n this.hop_length = hop_length ?? (this.win_length / 2);\n this.pad = pad;\n this.power = power;\n this.normalized = normalized;\n this.n_mels = n_mels; // number of mel frequency bins\n this.f_max = f_max;\n this.f_min = f_min;\n this.spectrogram = torchaudio.transforms.Spectrogram(\n n_fft: this.n_fft,\n win_length: this.win_length,\n hop_length: this.hop_length,\n pad: this.pad,\n window_fn: window_fn,\n power: this.power,\n normalized: this.normalized,\n center: center,\n pad_mode: pad_mode,\n onesided: onesided);\n this.mel_scale = torchaudio.transforms.MelScale(\n this.n_mels, this.sample_rate, this.f_min, this.f_max, this.n_fft / 2 + 1, norm, mel_scale\n );\n this.RegisterComponents();\n }\n\n /// <param name=\"waveform\">Tensor of audio of dimension (..., time).</param>\n /// <returns>Mel frequency spectrogram of size (..., ``n_mels``, time).</returns>\n public override Tensor forward(Tensor waveform)\n {\n var specgram = this.spectrogram.call(waveform);\n var mel_specgram = this.mel_scale.call(specgram);\n return mel_specgram;\n }\n }\n }\n\n public partial class torchaudio\n {\n public partial class transforms\n {\n /// <summary>\n /// Create MelSpectrogram for a raw audio signal.\n /// </summary>\n /// <param name=\"sample_rate\">Sample rate of audio signal.</param>\n /// <param name=\"n_fft\">Size of FFT, creates ``n_fft / 2 + 1`` bins.</param>\n /// <param name=\"win_length\">Window size.</param>\n /// <param name=\"hop_length\">Length of hop between STFT windows.</param>\n /// <param name=\"f_min\">Minimum frequency.</param>\n /// <param name=\"f_max\">Maximum frequency.</param>\n /// <param name=\"pad\">Two sided padding of signal.</param>\n /// <param name=\"n_mels\">Number of mel filterbanks.</param>\n /// <param name=\"window_fn\">A function to create a window tensor that is applied/multiplied to each frame/window.</param>\n /// <param name=\"power\">Exponent for the magnitude spectrogram, (must be > 0) e.g., 1 for energy, 2 for power, etc.</param>\n /// <param name=\"normalized\">Whether to normalize by magnitude after stft.</param>\n /// <param name=\"center\">whether to pad :attr:`waveform` on both sides so that the :math:`t`-th frame is centered at time :math:`t \\times \\text{hop\\_length}`.</param>\n /// <param name=\"pad_mode\">controls the padding method used when :attr:`center` is ``true``.</param>\n /// <param name=\"onesided\">controls whether to return half of results to avoid redundancy.</param>\n /// <param name=\"norm\">If \"slaney\", divide the triangular mel weights by the width of the mel band (area normalization).</param>\n /// <param name=\"mel_scale\">Scale to use: ``htk`` or ``slaney``.</param>\n /// <returns></returns>\n\n public static Transforms.MelSpectrogram MelSpectrogram(\n long sample_rate = 16000,\n long n_fft = 400,\n long? win_length = null,\n long? hop_length = null,\n double f_min = 0.0,\n double? f_max = null,\n long pad = 0,\n long n_mels = 128,\n WindowFunction window_fn = null,\n double power = 2.0,\n bool normalized = false,\n bool center = true,\n PaddingModes pad_mode = PaddingModes.Reflect,\n bool onesided = true,\n MelNorm norm = MelNorm.none,\n torchaudio.MelScale mel_scale = torchaudio.MelScale.htk)\n {\n return new Transforms.MelSpectrogram(\n \"MelSpectrogram\",\n sample_rate,\n n_fft,\n win_length,\n hop_length,\n f_min,\n f_max,\n pad,\n n_mels,\n window_fn,\n power,\n normalized,\n center,\n pad_mode,\n onesided,\n norm,\n mel_scale);\n }\n }\n }\n}" }, { "alpha_fraction": 0.5135135054588318, "alphanum_fraction": 0.5147420167922974, "avg_line_length": 22.97058868408203, "blob_id": "891957cd125641035954ca760ce019810d3e1475", "content_id": "46d408579eddb92837b0832097acd0a054c8be7f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 814, "license_type": "permissive", "max_line_length": 130, "num_lines": 34, "path": "/src/TorchVision/VerticalFlip.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class VerticalFlip : ITransform\n {\n internal VerticalFlip()\n {\n }\n\n public Tensor call(Tensor input)\n {\n return input.flip(-2);\n }\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Flip the image vertically.\n /// </summary>\n /// <returns></returns>\n static public ITransform VerticalFlip()\n {\n return new VerticalFlip();\n }\n }\n }\n}" }, { "alpha_fraction": 0.5217657685279846, "alphanum_fraction": 0.5223789215087891, "avg_line_length": 31, "blob_id": "f09a9531aecef0e8c398851d5a03b15d5a9fb34a", "content_id": "6d5b77751166e59c07d9554757a7d150c5bfcc24", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1631, "license_type": "permissive", "max_line_length": 130, "num_lines": 51, "path": "/src/TorchVision/Resize.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class Resize : ITransform\n {\n internal Resize(int height, int width, int? maxSize)\n {\n this.height = height;\n this.width = width;\n this.maxSize = maxSize;\n }\n\n public Tensor call(Tensor input)\n {\n return transforms.functional.resize(input, height, width, maxSize);\n }\n\n private int height, width;\n private int? maxSize;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Resize the input image to the given size.\n /// </summary>\n /// <param name=\"height\">Desired output height</param>\n /// <param name=\"width\">Desired output width</param>\n /// <returns></returns>\n static public ITransform Resize(int height, int width)\n {\n return new Resize(height, width, null);\n }\n\n /// <summary>\n /// Resize the input image to the given size.\n /// </summary>\n /// <param name=\"size\">Desired output size</param>\n /// <param name=\"maxSize\">Max size</param>\n static public ITransform Resize(int size, int? maxSize = null)\n {\n return new Resize(size, -1, maxSize);\n }\n }\n }\n}" }, { "alpha_fraction": 0.6404391527175903, "alphanum_fraction": 0.6462336182594299, "avg_line_length": 47.955223083496094, "blob_id": "67102487ac147824f8960fc83ee8e8387ae7e2d4", "content_id": "55cb1bf196fd09b43ce0664645d063eb3a78a7c0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3281, "license_type": "permissive", "max_line_length": 152, "num_lines": 67, "path": "/src/TorchSharp/Tensor/torch.Tensors.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Diagnostics.Contracts;\n\nnamespace TorchSharp\n{\n // https://pytorch.org/docs/stable/torch#tensors\n public static partial class torch\n {\n // https://pytorch.org/docs/stable/generated/torch.is_tensor\n [Pure]public static bool is_tensor(object obj) => obj is Tensor;\n\n // https://pytorch.org/docs/stable/generated/torch.is_storage\n [Pure]public static bool is_storage(object obj) => obj is Storage;\n\n // https://pytorch.org/docs/stable/generated/torch.is_complex\n /// <summary>\n /// Returns True if the data type of input is a complex data type i.e., one of torch.complex64, and torch.complex128.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n public static bool is_complex(Tensor input) => is_complex(input.dtype);\n\n // https://pytorch.org/docs/stable/generated/torch.is_floating_point\n /// <summary>\n /// Returns True if the data type of input is a floating point data type.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n public static bool is_floating_point(Tensor input) => is_floating_point(input.dtype);\n\n // https://pytorch.org/docs/stable/generated/torch.is_nonzero\n /// <summary>\n /// Returns True if the input is a single element tensor which is not equal to zero after type conversions,\n /// i.e. not equal to torch.tensor([0.]) or torch.tensor([0]) or torch.tensor([False]).\n /// Throws an InvalidOperationException if torch.numel() != 1.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n public static bool is_nonzero(Tensor input) => input.is_nonzero();\n\n // https://pytorch.org/docs/stable/generated/torch.set_default_dtype\n /// <summary>\n /// Sets the default floating point dtype to d. This dtype is:\n /// 1. The inferred dtype for python floats in torch.tensor().\n /// 2. Used to infer dtype for python complex numbers.\n /// The default complex dtype is set to torch.complex128 if default floating point dtype is torch.float64, otherwise it’s set to torch.complex64\n /// The default floating point dtype is initially torch.float32.\n /// </summary>\n /// <param name=\"dtype\"></param>\n public static void set_default_dtype(ScalarType dtype) { default_dtype = dtype; }\n\n // https://pytorch.org/docs/stable/generated/torch.get_default_dtype\n /// <summary>\n /// Get the current default floating point torch.dtype.\n /// </summary>\n /// <returns></returns>\n [Pure]public static ScalarType get_default_dtype() => default_dtype;\n\n // https://pytorch.org/docs/stable/generated/torch.set_default_tensor_type\n public static void set_default_tensor_type(Tensor t) => set_default_dtype(t.dtype);\n\n // https://pytorch.org/docs/stable/generated/torch.numel\n /// <summary>\n /// Get the number of elements in the input tensor.\n /// </summary>\n [Pure]public static long numel(Tensor input) => input.numel();\n }\n}" }, { "alpha_fraction": 0.5494467616081238, "alphanum_fraction": 0.5608575344085693, "avg_line_length": 32.627906799316406, "blob_id": "50b79906d4b177a753d089e6f7e0aa0e7edf69d5", "content_id": "087aab7b722133307ceac79301aad328fd9c28bd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2892, "license_type": "permissive", "max_line_length": 130, "num_lines": 86, "path": "/src/TorchAudio/Transforms/GriffinLim.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.torchaudio;\n\n// A number of implementation details in this file have been translated from the Python version of torchaudio,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/audio/blob/bb77cbebb620a46fdc0dc7e6dae2253eef3f37e2/torchaudio/transforms/_transforms.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/audio/blob/main/LICENSE\n//\n\nnamespace TorchSharp.Transforms\n{\n public sealed class GriffinLim : nn.Module<Tensor, Tensor>, ITransform\n {\n public readonly long n_fft;\n public readonly int n_iter;\n public readonly long win_length;\n public readonly long hop_length;\n public readonly Tensor window;\n public readonly long? length;\n public readonly double power;\n public readonly double momentum;\n public readonly bool rand_init;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n window.Dispose();\n }\n base.Dispose(disposing);\n }\n\n internal GriffinLim(\n string name,\n long n_fft = 400,\n int n_iter = 32,\n long? win_length = null,\n long? hop_length = null,\n WindowFunction window_fn = null,\n double power = 2.0,\n double momentum = 0.99,\n long? length = null,\n bool rand_init = true) : base(name)\n {\n if (momentum < 0 || 1 <= momentum) {\n throw new ArgumentOutOfRangeException($\"momentum must be in the range [0, 1). Found: {momentum}\");\n }\n\n this.n_fft = n_fft;\n this.n_iter = n_iter;\n this.win_length = win_length ?? n_fft;\n this.hop_length = hop_length ?? this.win_length / 2;\n if (window_fn != null) {\n this.window = window_fn(this.win_length);\n } else {\n this.window = torch.hann_window(this.win_length);\n }\n this.register_buffer(\"window\", this.window);\n this.length = length;\n this.power = power;\n this.momentum = momentum;\n this.rand_init = rand_init;\n }\n\n public override Tensor forward(Tensor specgram)\n {\n return torchaudio.functional.griffinlim(\n specgram,\n this.window,\n this.n_fft,\n this.hop_length,\n this.win_length,\n this.power,\n this.n_iter,\n this.momentum,\n this.length,\n this.rand_init\n );\n }\n }\n}\n" }, { "alpha_fraction": 0.5665773749351501, "alphanum_fraction": 0.5825388431549072, "avg_line_length": 50.86111068725586, "blob_id": "cefc3a6e112ef56095866801bcb6099e14efe450", "content_id": "2aece98d00a06c7fc674dd709d4f24f128dd8641", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9335, "license_type": "permissive", "max_line_length": 182, "num_lines": 180, "path": "/src/TorchVision/Ops/DropBlock.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchvision,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/vision/blob/a4f53308b2d0f1aa9191686e326f45c26053f686/torchvision/ops/drop_block.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/vision/blob/main/LICENSE\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing TorchSharp.Modules;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n\n public static partial class ops\n {\n /// <summary>\n /// Implements DropBlock2d from `\"DropBlock: A regularization method for convolutional networks\"\n /// https://arxiv.org/abs/1810.12890\n /// </summary>\n /// <param name=\"input\">The input tensor of 4 dimensions with the first one beinng its batch.</param>\n /// <param name=\"p\">Probability of an element to be dropped.</param>\n /// <param name=\"block_size\">Size of the block to drop.</param>\n /// <param name=\"inplace\">If set to true, will do this operation in-place</param>\n /// <param name=\"eps\">A small value added to the denominator for numerical stability.</param>\n /// <param name=\"training\">Apply dropblock if is true</param>\n /// <returns>The randomly zeroed [N, C, H, W] tensor after dropblock</returns>\n /// <exception cref=\"ArgumentOutOfRangeException\">If p is not in the range [0,1]</exception>\n /// <exception cref=\"ArgumentException\">If the input tensor is not 4-dimensional</exception>\n public static Tensor drop_block2d(Tensor input, double p, long block_size, bool inplace = false, double eps = 1e-6, bool training = true)\n {\n if (p < 0 || p > 1) throw new ArgumentOutOfRangeException(nameof(p));\n if (input.ndim != 4) throw new ArgumentException($\"input should be 4 dimensional. Got {input.ndim} dimensions.\");\n if (!training || p == 0) return input.alias();\n\n var (N, C, H, W) = (input.shape[0], input.shape[1], input.shape[2], input.shape[3]);\n\n block_size = Math.Min(block_size, Math.Min(W, H));\n // compute the gamma of Bernoulli distribution\n var gamma = (p * H * W) / ((block_size * block_size) * ((H - block_size + 1) * (W - block_size + 1)));\n var noise = torch.empty(N, C, H - block_size + 1, W - block_size + 1, dtype: input.dtype, device: input.device);\n noise.bernoulli_(gamma);\n\n var pad = block_size / 2;\n noise = torch.nn.functional.pad(noise, (pad, pad, pad, pad), value: 0);\n noise = torch.nn.functional.max_pool2d(noise, stride: 1, kernelSize: block_size, padding: block_size / 2);\n noise = 1 - noise;\n\n var normalize_scale = noise.numel() / (eps + noise.sum());\n if (inplace)\n input.mul_(noise).mul_(normalize_scale);\n else\n input = input * noise * normalize_scale;\n return input;\n }\n\n /// <summary>\n /// Implements DropBlock3d from `\"DropBlock: A regularization method for convolutional networks\"\n /// https://arxiv.org/abs/1810.12890\n /// </summary>\n /// <param name=\"input\">The input tensor of 5 dimensions with the first one beinng its batch.</param>\n /// <param name=\"p\">Probability of an element to be dropped.</param>\n /// <param name=\"block_size\">Size of the block to drop.</param>\n /// <param name=\"inplace\">If set to true, will do this operation in-place</param>\n /// <param name=\"eps\">A small value added to the denominator for numerical stability.</param>\n /// <param name=\"training\">Apply dropblock if is true</param>\n /// <returns>The randomly zeroed [N, C, D, H, W] tensor after dropblock</returns>\n /// <exception cref=\"ArgumentOutOfRangeException\">If p is not in the range [0,1]</exception>\n /// <exception cref=\"ArgumentException\">If the input tensor is not 5-dimensional</exception>\n public static Tensor drop_block3d(Tensor input, double p, long block_size, bool inplace = false, double eps = 1e-6, bool training = true)\n {\n if (p < 0 || p > 1) throw new ArgumentOutOfRangeException(nameof(p));\n if (input.ndim != 5) throw new ArgumentException($\"input should be 5-dimensional. Got {input.ndim} dimensions.\");\n if (!training || p == 0) return input.alias();\n\n var (N, C, D, H, W) = (input.shape[0], input.shape[1], input.shape[2], input.shape[3], input.shape[4]);\n\n block_size = Math.Min(Math.Min(block_size, D), Math.Min(W, H));\n // compute the gamma of Bernoulli distribution\n var gamma = (p * D * H * W) / ((block_size * block_size * block_size) * ((D - block_size + 1) * (H - block_size + 1) * (W - block_size + 1)));\n var noise = torch.empty(new[] { N, C, D - block_size + 1, H - block_size + 1, W - block_size + 1 }, dtype: input.dtype, device: input.device);\n noise.bernoulli_(gamma);\n\n var pad = block_size / 2;\n var padding = new[] { pad, pad, pad, pad, pad, pad };\n noise = torch.nn.functional.pad(noise, padding, value: 0);\n noise = torch.nn.functional.max_pool3d(noise, strides: new long[] { 1, 1, 1 }, kernelSize: new[] { block_size, block_size, block_size }, padding: new long[] { pad });\n noise = 1 - noise;\n\n var normalize_scale = noise.numel() / (eps + noise.sum());\n if (inplace)\n input.mul_(noise).mul_(normalize_scale);\n else\n input = input * noise * normalize_scale;\n return input;\n }\n\n /// <summary>\n /// Implements DropBlock2d from `\"DropBlock: A regularization method for convolutional networks\"\n /// https://arxiv.org/abs/1810.12890\n /// </summary>\n public static DropBlock2d DropBlock2d(double p, long block_size, bool inplace = false, double eps = 1e-6) => new DropBlock2d(p, block_size, inplace, eps);\n\n /// <summary>\n /// Implements DropBlock3d from `\"DropBlock: A regularization method for convolutional networks\"\n /// https://arxiv.org/abs/1810.12890\n /// </summary>\n public static DropBlock3d DropBlock3d(double p, long block_size, bool inplace = false, double eps = 1e-6) => new DropBlock3d(p, block_size, inplace, eps);\n }\n }\n\n namespace Modules\n {\n public class DropBlock2d : torch.nn.Module<Tensor,Tensor>\n {\n public DropBlock2d(double p, long block_size, bool inplace = false, double eps = 1e-6) : base(nameof(DropBlock2d))\n {\n this.p = p;\n this.block_size = block_size;\n this.inplace = inplace;\n this.eps = eps;\n }\n\n\n public override Tensor forward(Tensor input)\n {\n return torchvision.ops.drop_block2d(input, p, block_size, inplace, eps, training);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected override nn.Module _to(Device device, ScalarType dtype) => this;\n protected override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected override nn.Module _to(ScalarType dtype) => this;\n\n private bool inplace;\n private double p;\n private long block_size;\n private double eps;\n }\n\n public class DropBlock3d : torch.nn.Module<Tensor, Tensor>\n {\n public DropBlock3d(double p, long block_size, bool inplace = false, double eps = 1e-6) : base(nameof(DropBlock3d))\n {\n this.p = p;\n this.block_size = block_size;\n this.inplace = inplace;\n this.eps = eps;\n }\n\n\n public override Tensor forward(Tensor input)\n {\n return torchvision.ops.drop_block3d(input, p, block_size, inplace, eps, training);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected override nn.Module _to(Device device, ScalarType dtype) => this;\n protected override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected override nn.Module _to(ScalarType dtype) => this;\n\n private bool inplace;\n private double p;\n private long block_size;\n private double eps;\n }\n }\n}\n" }, { "alpha_fraction": 0.7226585745811462, "alphanum_fraction": 0.7297270894050598, "avg_line_length": 26.165332794189453, "blob_id": "32f1bab56c75157b13ddf13c2ad0aade49a996e7", "content_id": "96ee551e10b40f157239fe22efde491b5f2ad8ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10186, "license_type": "permissive", "max_line_length": 130, "num_lines": 375, "path": "/src/Native/LibTorchSharp/THSSpecial.cpp", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#include \"THSTensor.h\"\n\n#include <iostream>\n#include <fstream>\n\nTensor THSSpecial_airy_ai(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::airy_ai(*tensor));\n}\n\nTensor THSSpecial_airy_ai_out(const Tensor tensor, Tensor out)\n{\n CATCH_TENSOR(torch::special::airy_ai_out(*out, *tensor));\n}\n\nTensor THSSpecial_bessel_j0(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::bessel_j0(*tensor));\n}\n\nTensor THSSpecial_bessel_j0_out(const Tensor tensor, Tensor out)\n{\n CATCH_TENSOR(torch::special::bessel_j0_out(*out, *tensor));\n}\n\nTensor THSSpecial_bessel_j1(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::bessel_j1(*tensor));\n}\n\nTensor THSSpecial_bessel_j1_out(const Tensor tensor, Tensor out)\n{\n CATCH_TENSOR(torch::special::bessel_j1_out(*out, *tensor));\n}\n\nTensor THSSpecial_bessel_y0(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::bessel_y0(*tensor));\n}\n\nTensor THSSpecial_bessel_y0_out(const Tensor tensor, Tensor out)\n{\n CATCH_TENSOR(torch::special::bessel_y0_out(*out, *tensor));\n}\n\nTensor THSSpecial_bessel_y1(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::bessel_y1(*tensor));\n}\n\nTensor THSSpecial_bessel_y1_out(const Tensor tensor, Tensor out)\n{\n CATCH_TENSOR(torch::special::bessel_y1_out(*out, *tensor));\n}\n\nTensor THSSpecial_modified_bessel_i0(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::modified_bessel_i0(*tensor));\n}\n\nTensor THSSpecial_modified_bessel_i0_out(const Tensor tensor, Tensor out)\n{\n CATCH_TENSOR(torch::special::modified_bessel_i0_out(*out, *tensor));\n}\n\nTensor THSSpecial_modified_bessel_i1(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::modified_bessel_i1(*tensor));\n}\n\nTensor THSSpecial_modified_bessel_i1_out(const Tensor tensor, Tensor out)\n{\n CATCH_TENSOR(torch::special::modified_bessel_i1_out(*out, *tensor));\n}\n\nTensor THSSpecial_modified_bessel_k0(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::modified_bessel_k0(*tensor));\n}\n\nTensor THSSpecial_modified_bessel_k0_out(const Tensor tensor, Tensor out)\n{\n CATCH_TENSOR(torch::special::modified_bessel_k0_out(*out, *tensor));\n}\n\nTensor THSSpecial_modified_bessel_k1(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::modified_bessel_k1(*tensor));\n}\n\nTensor THSSpecial_modified_bessel_k1_out(const Tensor tensor, Tensor out)\n{\n CATCH_TENSOR(torch::special::modified_bessel_k1_out(*out, *tensor));\n}\n\nTensor THSSpecial_scaled_modified_bessel_k0(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::scaled_modified_bessel_k0(*tensor));\n}\n\nTensor THSSpecial_scaled_modified_bessel_k0_out(const Tensor tensor, Tensor out)\n{\n CATCH_TENSOR(torch::special::scaled_modified_bessel_k0_out(*out, *tensor));\n}\n\nTensor THSSpecial_scaled_modified_bessel_k1(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::scaled_modified_bessel_k1(*tensor));\n}\n\nTensor THSSpecial_scaled_modified_bessel_k1_out(const Tensor tensor, Tensor out)\n{\n CATCH_TENSOR(torch::special::scaled_modified_bessel_k1_out(*out, *tensor));\n}\n\nTensor THSSpecial_spherical_bessel_j0(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::spherical_bessel_j0(*tensor));\n}\n\nTensor THSSpecial_spherical_bessel_j0_out(const Tensor tensor, Tensor out)\n{\n CATCH_TENSOR(torch::special::spherical_bessel_j0_out(*out, *tensor));\n}\n\nTensor THSSpecial_chebyshev_polynomial_t(const Tensor x, const Tensor n)\n{\n CATCH_TENSOR(torch::special::chebyshev_polynomial_t(*x, *n));\n}\n\nTensor THSSpecial_chebyshev_polynomial_t_out(const Tensor x, const Tensor n, Tensor out)\n{\n CATCH_TENSOR(torch::special::chebyshev_polynomial_t_out(*out, *x, *n));\n}\n\nTensor THSSpecial_chebyshev_polynomial_u(const Tensor x, const Tensor n)\n{\n CATCH_TENSOR(torch::special::chebyshev_polynomial_u(*x, *n));\n}\n\nTensor THSSpecial_chebyshev_polynomial_u_out(const Tensor x, const Tensor n, Tensor out)\n{\n CATCH_TENSOR(torch::special::chebyshev_polynomial_u_out(*out, *x, *n));\n}\n\nTensor THSSpecial_chebyshev_polynomial_v(const Tensor x, const Tensor n)\n{\n CATCH_TENSOR(torch::special::chebyshev_polynomial_v(*x, *n));\n}\n\nTensor THSSpecial_chebyshev_polynomial_v_out(const Tensor x, const Tensor n, Tensor out)\n{\n CATCH_TENSOR(torch::special::chebyshev_polynomial_v_out(*out, *x, *n));\n}\n\nTensor THSSpecial_chebyshev_polynomial_w(const Tensor x, const Tensor n)\n{\n CATCH_TENSOR(torch::special::chebyshev_polynomial_w(*x, *n));\n}\n\nTensor THSSpecial_chebyshev_polynomial_w_out(const Tensor x, const Tensor n, Tensor out)\n{\n CATCH_TENSOR(torch::special::chebyshev_polynomial_w_out(*out, *x, *n));\n}\n\nTensor THSSpecial_shifted_chebyshev_polynomial_t(const Tensor x, const Tensor n)\n{\n CATCH_TENSOR(torch::special::shifted_chebyshev_polynomial_t(*x, *n));\n}\n\nTensor THSSpecial_shifted_chebyshev_polynomial_t_out(const Tensor x, const Tensor n, Tensor out)\n{\n CATCH_TENSOR(torch::special::shifted_chebyshev_polynomial_t_out(*out, *x, *n));\n}\n\nTensor THSSpecial_shifted_chebyshev_polynomial_u(const Tensor x, const Tensor n)\n{\n CATCH_TENSOR(torch::special::shifted_chebyshev_polynomial_u(*x, *n));\n}\n\nTensor THSSpecial_shifted_chebyshev_polynomial_u_out(const Tensor x, const Tensor n, Tensor out)\n{\n CATCH_TENSOR(torch::special::shifted_chebyshev_polynomial_u_out(*out, *x, *n));\n}\n\nTensor THSSpecial_shifted_chebyshev_polynomial_v(const Tensor x, const Tensor n)\n{\n CATCH_TENSOR(torch::special::shifted_chebyshev_polynomial_v(*x, *n));\n}\n\nTensor THSSpecial_shifted_chebyshev_polynomial_v_out(const Tensor x, const Tensor n, Tensor out)\n{\n CATCH_TENSOR(torch::special::shifted_chebyshev_polynomial_v_out(*out, *x, *n));\n}\n\nTensor THSSpecial_shifted_chebyshev_polynomial_w(const Tensor x, const Tensor n)\n{\n CATCH_TENSOR(torch::special::shifted_chebyshev_polynomial_w(*x, *n));\n}\n\nTensor THSSpecial_shifted_chebyshev_polynomial_w_out(const Tensor x, const Tensor n, Tensor out)\n{\n CATCH_TENSOR(torch::special::shifted_chebyshev_polynomial_w_out(*out, *x, *n));\n}\n\nTensor THSSpecial_hermite_polynomial_h(const Tensor x, const Tensor n)\n{\n CATCH_TENSOR(torch::special::hermite_polynomial_h(*x, *n));\n}\n\nTensor THSSpecial_hermite_polynomial_h_out(const Tensor x, const Tensor n, Tensor out)\n{\n CATCH_TENSOR(torch::special::hermite_polynomial_h_out(*out, *x, *n));\n}\n\nTensor THSSpecial_hermite_polynomial_he(const Tensor x, const Tensor n)\n{\n CATCH_TENSOR(torch::special::hermite_polynomial_he(*x, *n));\n}\n\nTensor THSSpecial_hermite_polynomial_he_out(const Tensor x, const Tensor n, Tensor out)\n{\n CATCH_TENSOR(torch::special::hermite_polynomial_he_out(*out, *x, *n));\n}\n\nTensor THSSpecial_laguerre_polynomial_l(const Tensor x, const Tensor n)\n{\n CATCH_TENSOR(torch::special::laguerre_polynomial_l(*x, *n));\n}\n\nTensor THSSpecial_laguerre_polynomial_l_out(const Tensor x, const Tensor n, Tensor out)\n{\n CATCH_TENSOR(torch::special::laguerre_polynomial_l_out(*out, *x, *n));\n}\n\nTensor THSSpecial_legendre_polynomial_p(const Tensor x, const Tensor n)\n{\n CATCH_TENSOR(torch::special::legendre_polynomial_p(*x, *n));\n}\n\nTensor THSSpecial_legendre_polynomial_p_out(const Tensor x, const Tensor n, Tensor out)\n{\n CATCH_TENSOR(torch::special::legendre_polynomial_p_out(*out, *x, *n));\n}\n\nTensor THSSpecial_entr(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::entr(*tensor));\n}\n\nTensor THSSpecial_erf(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::erf(*tensor));\n}\n\nTensor THSSpecial_erfc(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::erfc(*tensor));\n}\n\nTensor THSSpecial_erfcx(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::erfc(*tensor));\n}\n\nTensor THSSpecial_erfinv(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::erfinv(*tensor));\n}\n\nTensor THSSpecial_expit(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::expit(*tensor));\n}\n\nTensor THSSpecial_expm1(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::expm1(*tensor));\n}\n\nTensor THSSpecial_exp2(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::exp2(*tensor));\n}\n\nTensor THSSpecial_gammaln(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::gammaln(*tensor));\n}\n\nTensor THSSpecial_gammainc(const Tensor input, const Tensor other)\n{\n CATCH_TENSOR(torch::special::gammainc(*input, *other));\n}\n\nTensor THSSpecial_gammaincc(const Tensor input, const Tensor other)\n{\n CATCH_TENSOR(torch::special::gammaincc(*input, *other));\n}\n\nTensor THSSpecial_polygamma(const int64_t n, const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::polygamma(n, *tensor));\n}\n\nTensor THSSpecial_digamma(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::digamma(*tensor));\n}\n\nTensor THSSpecial_multigammaln(const Tensor tensor, const int64_t p)\n{\n CATCH_TENSOR(torch::special::multigammaln(*tensor, p));\n}\n\nTensor THSSpecial_i0e(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::i0e(*tensor));\n}\n\nTensor THSSpecial_i0(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::i0(*tensor));\n}\n\nTensor THSSpecial_i1e(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::i1e(*tensor));\n}\n\nTensor THSSpecial_i1(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::i1(*tensor));\n}\n\nTensor THSSpecial_logit(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::logit(*tensor));\n}\n\nTensor THSSpecial_log_softmax(const Tensor tensor, int64_t dim, int8_t scalar_type)\n{\n CATCH_TENSOR(torch::special::log_softmax(*tensor, dim, c10::ScalarType(scalar_type)));\n}\n\nTensor THSSpecial_ndtr(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::ndtr(*tensor));\n}\n\nTensor THSSpecial_ndtri(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::ndtri(*tensor));\n}\n\nTensor THSSpecial_sinc(const Tensor tensor)\n{\n CATCH_TENSOR(torch::special::sinc(*tensor));\n}\n\nTensor THSSpecial_softmax(const Tensor tensor, int64_t dim, int8_t scalar_type)\n{\n CATCH_TENSOR(torch::special::softmax(*tensor, dim, c10::ScalarType(scalar_type)));\n}\n\nTensor THSSpecial_xlog1py(const Tensor input, const Tensor other)\n{\n CATCH_TENSOR(torch::special::xlog1py(*input, *other));\n}\n\nTensor THSSpecial_zeta(const Tensor input, const Tensor other)\n{\n CATCH_TENSOR(torch::special::zeta(*input, *other));\n}" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 36.264705657958984, "blob_id": "496f723968283b1f04dc1fb493e887e3f5153cdb", "content_id": "8e6d4f48c78ed238d3f71e1d89ff0fa2e025296b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1267, "license_type": "permissive", "max_line_length": 130, "num_lines": 34, "path": "/src/TorchSharp/PInvoke/LibTorchSharp.THSGenerator.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp.PInvoke\n{\n internal static partial class NativeMethods\n {\n [DllImport(\"LibTorchSharp\")]\n internal static extern long THSGenerator_initial_seed(IntPtr handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSGenerator_get_rng_state(IntPtr handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSGenerator_set_rng_state(IntPtr handle, IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSGenerator_gen_manual_seed(IntPtr handle, long seed);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSGenerator_new(ulong seed, long device_type, long device_index);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSGenerator_default_generator();\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSGenerator_dispose(IntPtr handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSGenerator_manual_seed(long seed);\n }\n}\n" }, { "alpha_fraction": 0.5340318083763123, "alphanum_fraction": 0.537695050239563, "avg_line_length": 47.06338119506836, "blob_id": "6454ac651613cae5c50718b7e2d57d09cff6a3c8", "content_id": "53e6facfbd41664c6a26b43d990493026a0833e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 13651, "license_type": "permissive", "max_line_length": 236, "num_lines": 284, "path": "/src/TorchSharp/Tensor/Tensor.LinearAlgebra.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Linq;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public partial class Tensor\n {\n // https://pytorch.org/docs/stable/generated/torch.tensordot\n /// <summary>\n /// Returns a contraction of a and b over multiple dimensions.\n /// tensordot implements a generalized matrix product.\n /// </summary>\n public Tensor tensordot(Tensor b, long[] dims1, long[] dims2)\n {\n IntPtr res;\n unsafe {\n fixed (long* pdims1 = dims1, pdims2 = dims2) {\n res = THSLinalg_tensordot(Handle, b.Handle,(IntPtr)pdims1, dims1.Length,(IntPtr)pdims2, dims2.Length);\n }\n }\n if (res == IntPtr.Zero) {\n CheckForErrors();\n }\n return new Tensor(res);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.tensordot\n /// <summary>\n /// Returns a contraction of this tensor and <paramref name=\"b\"/> over multiple dimensions.\n /// tensordot implements a generalized matrix product.\n /// </summary>\n /// <param name=\"b\">Right tensor to contract</param>\n /// <param name=\"dims\">dimensions to contract for this tensor and <paramref name=\"b\"/> respectively</param>\n /// <returns>contraction</returns>\n public Tensor tensordot(Tensor b, (long, long)[] dims)\n => tensordot(b, dims.Select(t => t.Item1).ToArray(), dims.Select(t => t.Item2).ToArray());\n\n // https://pytorch.org/docs/stable/generated/torch.tensordot\n /// <summary>\n /// Returns a contraction of this tensor and <paramref name=\"b\"/> over multiple dimensions.\n /// tensordot implements a generalized matrix product.\n /// </summary>\n /// <param name=\"b\">Right tensor to contract</param>\n /// <param name=\"dims\">number of dimensions to contract for this tensor and <paramref name=\"b\"/></param>\n /// <returns>contraction</returns>\n public Tensor tensordot(Tensor b, long dims = 2)\n {\n if (dims < 0) throw new ArgumentOutOfRangeException(nameof(dims), dims, \"must be >= 0\");\n\n var list = new long[dims];\n for (long i = 0; i <= dims; i++) {\n list[i] = i;\n }\n\n return tensordot(b, list, list);\n }\n\n /// <summary>\n /// Computes the Cholesky decomposition of a symmetric positive-definite matrix AA or for batches of symmetric positive-definite matrices.\n /// </summary>\n /// <param name=\"upper\">If upper is true, the returned matrix U is upper-triangular. If upper is false, the returned matrix L is lower-triangular</param>\n /// <returns></returns>\n public Tensor cholesky(bool upper = false)\n {\n var res = THSTensor_cholesky(Handle, upper);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the inverse of a symmetric positive-definite matrix AA using its Cholesky factor uu : returns matrix inv\n /// </summary>\n /// <param name=\"upper\"></param>\n /// <returns></returns>\n public Tensor cholesky_inverse(bool upper = false)\n {\n var res = THSTensor_cholesky_inverse(Handle, upper);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Solves a linear system of equations with a positive semidefinite matrix to be inverted given its Cholesky factor matrix u.\n /// </summary>\n /// <param name=\"input2\"></param>\n /// <param name=\"upper\"></param>\n /// <returns></returns>\n public Tensor cholesky_solve(Tensor input2, bool upper = false)\n {\n var res = THSTensor_cholesky_solve(Handle, input2.Handle, upper);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the cross product of two 3-dimensional vectors.\n /// </summary>\n /// <remarks>\n /// Supports input of float, double, cfloat and cdouble dtypes. Also supports batches of vectors,\n /// for which it computes the product along the dimension dim. In this case, the output has the\n /// same batch dimensions as the inputs broadcast to a common shape.\n /// </remarks>\n public Tensor cross(Scalar other, long dim)\n {\n var res = THSTensor_cross(Handle, other.Handle, dim);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the determinant of a square matrix.\n /// </summary>\n public Tensor det()\n {\n return linalg.det(this);\n }\n\n /// <summary>\n /// Calculates log determinant of a square matrix or batches of square matrices.\n /// </summary>\n /// <returns></returns>\n public Tensor logdet()\n {\n var shape = this.shape;\n var len = shape.Length;\n if (shape[len - 1] != shape[len - 2]) throw new ArgumentException(\"The input tensor is not square\");\n\n var res = THSTensor_logdet(Handle);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n\n /// <summary>\n /// This is a low-level function for calling LAPACK’s geqrf directly.\n /// This function returns a namedtuple (a, tau) as defined in LAPACK documentation for geqrf.\n /// </summary>\n /// <remarks>\n /// Computes a QR decomposition of input. Both Q and R matrices are stored in the same output tensor a.\n /// The elements of R are stored on and above the diagonal. Elementary reflectors (or Householder vectors)\n /// implicitly defining matrix Q are stored below the diagonal. The results of this function can be used\n /// together with torch.linalg.householder_product() to obtain the Q matrix or with torch.ormqr(), which\n /// uses an implicit representation of the Q matrix, for an efficient matrix-matrix multiplication.\n /// </remarks>\n public (Tensor a, Tensor tau) geqrf()\n {\n var res = THSTensor_geqrf(Handle, out var tau);\n if (res == IntPtr.Zero || tau == IntPtr.Zero)\n torch.CheckForErrors();\n return (new Tensor(res), new Tensor(tau));\n }\n\n /// <summary>\n /// Matrix product of two tensors.\n /// </summary>\n /// <param name=\"target\"></param>\n /// <returns></returns>\n /// <remarks>\n /// The behavior depends on the dimensionality of the tensors as follows:\n /// 1. If both tensors are 1-dimensional, the dot product (scalar) is returned\n /// 2. If both arguments are 2-dimensional, the matrix-matrix product is returned.\n /// 3. If the first argument is 1-dimensional and the second argument is 2-dimensional, a 1 is prepended to its dimension for the purpose of the matrix multiply. After the matrix multiply, the prepended dimension is removed.\n /// 4. If the first argument is 2-dimensional and the second argument is 1-dimensional, the matrix-vector product is returned.\n /// 5. If both arguments are at least 1-dimensional and at least one argument is N-dimensional (where N > 2), then a batched matrix multiply is returned.\n /// </remarks>\n public Tensor matmul(Tensor target)\n {\n var res = THSTensor_matmul(Handle, target.Handle);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Performs a matrix multiplication of the matrices input and mat2.\n /// </summary>\n /// <param name=\"target\"></param>\n /// <returns></returns>\n public Tensor mm(Tensor target)\n {\n var res = THSTensor_mm(Handle, target.Handle);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Performs a matrix-vector product of the matrix input and the vector vec.\n /// </summary>\n /// <param name=\"target\"></param>\n /// <returns></returns>\n public Tensor mv(Tensor target)\n {\n var res = THSTensor_mv(Handle, target.Handle);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the matrix exponential of a square matrix or of each square matrix in a batch.\n /// </summary>\n public Tensor matrix_exp()\n {\n var res = THSTensor_matrix_exp(Handle);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the n-th power of a square matrix for an integer n.\n /// </summary>\n /// <param name=\"n\">The exponent</param>\n /// <returns></returns>\n /// <remarks>Input tensor must be of shape (*, m, m) where * is zero or more batch dimensions.</remarks>\n public Tensor matrix_power(int n)\n {\n var res = THSLinalg_matrix_power(Handle, n);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the dot product of two 1D tensors.\n /// </summary>\n /// <returns></returns>\n /// <remarks>\n /// The vdot(a, b) function handles complex numbers differently than dot(a, b).\n /// If the first argument is complex, the complex conjugate of the first argument is used for the calculation of the dot product.\n /// </remarks>\n public Tensor vdot(Tensor target)\n {\n if (shape.Length != 1 || target.shape.Length != 1 || shape[0] != target.shape[0]) throw new InvalidOperationException(\"vdot arguments must have the same shape.\");\n var res = THSTensor_vdot(Handle, target.Handle);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the dot product of two 1D tensors.\n /// </summary>\n /// <returns></returns>\n public Tensor dot(Tensor target)\n {\n if (shape.Length != 1 || target.shape.Length != 1 || shape[0] != target.shape[0]) throw new InvalidOperationException(\"dot arguments must have the same shape.\");\n var res = THSTensor_dot(Handle, target.Handle);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the pseudoinverse (Moore-Penrose inverse) of a matrix.\n /// </summary>\n /// <param name=\"rcond\">The tolerance value to determine when is a singular value zero </param>\n /// <param name=\"hermitian\">Indicates whether A is Hermitian if complex or symmetric if real. </param>\n /// <remarks>Input should be tensor of shape (*, m, n) where * is zero or more batch dimensions.</remarks>\n /// <returns></returns>\n public Tensor pinverse(double rcond = 1e-15, bool hermitian = false)\n {\n var res = THSLinalg_pinverse(Handle, rcond, hermitian);\n if (res == IntPtr.Zero)\n CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the matrix-matrix multiplication of a product of Householder matrices with a general matrix.\n /// </summary>\n /// <param name=\"tau\">Tensor of shape (*, min(mn, k)) where * is zero or more batch dimensions.</param>\n /// <param name=\"other\">Tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"left\">Controls the order of multiplication.</param>\n /// <param name=\"transpose\">Controls whether the matrix Q is conjugate transposed or not.</param>\n /// <returns></returns>\n public Tensor ormqr(Tensor tau, Tensor other, bool left = true, bool transpose = false)\n {\n var res = THSTensor_ormqr(Handle, tau.handle, other.Handle, left, transpose);\n if (res == IntPtr.Zero)\n CheckForErrors();\n return new Tensor(res);\n }\n }\n }\n}" }, { "alpha_fraction": 0.7786961793899536, "alphanum_fraction": 0.7956100702285767, "avg_line_length": 91.2676773071289, "blob_id": "00c69f84566b348e4bd5aeff6dd0f6c071100d71", "content_id": "330ceb1d259f0b53bcf94344456f73c4615bb3eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 54807, "license_type": "permissive", "max_line_length": 478, "num_lines": 594, "path": "/src/Native/LibTorchSharp/THSNN.h", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#pragma once\n\n#include \"../Stdafx.h\"\n\n#include \"torch/torch.h\"\n\n#include \"Utils.h\"\n\n// API.\n\nEXPORT_API(int) THSNN_Module_has_parameter(const NNModule module, const char* name);\nEXPORT_API(Tensor) THSNN_Module_get_parameter(const NNModule module, const char* name);\nEXPORT_API(void) THSNN_Module_get_named_parameters(const NNModule module, Tensor* (*allocator1)(size_t length), const char** (*allocator2)(size_t length));\nEXPORT_API(void) THSNN_Module_get_named_buffers(const NNModule module, Tensor* (*allocator1)(size_t length), const char** (*allocator2)(size_t length));\nEXPORT_API(void) THSNN_Module_get_named_children(const NNModule module, NNModule* (*allocator1)(size_t length), const char** (*allocator2)(size_t length));\nEXPORT_API(void) THSNN_Module_get_named_modules(const NNModule module, NNModule* (*allocator1)(size_t length), const char** (*allocator2)(size_t length));\nEXPORT_API(void) THSNN_Module_get_parameters(const NNModule module, Tensor* (*allocator1)(size_t length), bool recurse);\nEXPORT_API(int) THSNN_Module_is_training(NNModule module);\nEXPORT_API(void) THSNN_Module_train(NNModule module, bool on);\nEXPORT_API(long) THSNN_Module_children_size(const NNModule module);\nEXPORT_API(NNModule) THSNN_Module_child(const NNModule module, const int index);\nEXPORT_API(const char*) THSNN_Module_name(const NNModule module);\nEXPORT_API(void) THSNN_Module_zero_grad(const NNModule module);\nEXPORT_API(void) THSNN_Module_save(const NNModule module, const char* location);\nEXPORT_API(NNModule) THSNN_Module_load(const char* location);\nEXPORT_API(void) THSNN_Module_register_buffer(const NNModule module, const char* name, const Tensor submodule);\nEXPORT_API(void) THSNN_Module_register_parameter(const NNModule module, const char* name, const Tensor tensor, bool requires_grad);\nEXPORT_API(void) THSNN_Module_register_module(const NNModule module, const char* name, const NNModule submodule);\nEXPORT_API(void) THSNN_Module_dispose(const NNModule module);\nEXPORT_API(void) THSNN_Module_to_device(NNModule module, int64_t device, int64_t index);\nEXPORT_API(void) THSNN_Module_to_dtype(NNModule module, int8_t dtype);\nEXPORT_API(void) THSNN_Module_to_device_dtype(NNModule module, int8_t dtype, int64_t device, int64_t index);\n\nEXPORT_API(void) THSNN_AnyModule_dispose(const NNAnyModule module);\n//EXPORT_API(NNModule) THSNN_AnyModule_get(const NNAnyModule module);\n\nEXPORT_API(NNModule) THSNN_custom_module(const char* name, Tensor(*forward)(Tensor), NNAnyModule* outAsAnyModule);\n\n// Pooling\n\nEXPORT_API(NNModule) THSNN_MaxPool1d_ctor(const int64_t* kernelSize, const int64_t* stride, const int64_t* padding, const int64_t* dilation, bool ceil_mode, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_MaxPool1d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(Tensor) THSNN_MaxPool1d_forward_with_indices(const NNModule module, const Tensor tensor, Tensor *indices);\n\nEXPORT_API(NNModule) THSNN_MaxPool2d_ctor(const int64_t* kernelSize, const int kernelSizeLength, const int64_t* stride, const int strideLength, const int64_t* padding, const int paddingLength, const int64_t* dilation, const int dilationLength, bool ceil_mode, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_MaxPool2d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(Tensor) THSNN_MaxPool2d_forward_with_indices(const NNModule module, const Tensor tensor, Tensor* indices);\n\nEXPORT_API(NNModule) THSNN_MaxPool3d_ctor(const int64_t* kernelSize, const int kernelSizeLength, const int64_t* stride, const int strideLength, const int64_t* padding, const int paddingLength, const int64_t* dilation, const int dilationLength, bool ceil_mode, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_MaxPool3d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(Tensor) THSNN_MaxPool3d_forward_with_indices(const NNModule module, const Tensor tensor, Tensor* indices);\n\nEXPORT_API(NNModule) THSNN_FractionalMaxPool2d_ctor(const int64_t* kernelSize, const int kernelSizeLength, const int64_t* outputSize, const int outputSizeLength, const double* outputRatio, const int outputRatioLength, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_FractionalMaxPool2d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(Tensor) THSNN_FractionalMaxPool2d_forward_with_indices(const NNModule module, const Tensor tensor, Tensor* indices);\n\nEXPORT_API(NNModule) THSNN_FractionalMaxPool3d_ctor(const int64_t* kernelSize, const int kernelSizeLength, const int64_t* outputSize, const int outputSizeLength, const double* outputRatio, const int outputRatioLength, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_FractionalMaxPool3d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(Tensor) THSNN_FractionalMaxPool3d_forward_with_indices(const NNModule module, const Tensor tensor, Tensor* indices);\n\nEXPORT_API(NNModule) THSNN_MaxUnpool1d_ctor(const int64_t* kernelSize, const int64_t* stride, const int64_t* padding, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_MaxUnpool1d_forward(const NNModule module, const Tensor tensor, const Tensor indices, const int64_t* outputSize);\n\nEXPORT_API(NNModule) THSNN_MaxUnpool2d_ctor(const int64_t* kernelSize, const int kernelSizeLength, const int64_t* stride, const int strideLength, const int64_t* padding, const int paddingLength, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_MaxUnpool2d_forward(const NNModule module, const Tensor tensor, const Tensor indices, const int64_t* outputSize, const int outputSizeLength);\n\nEXPORT_API(NNModule) THSNN_MaxUnpool3d_ctor(const int64_t* kernelSize, const int kernelSizeLength, const int64_t* stride, const int strideLength, const int64_t* padding, const int paddingLength, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_MaxUnpool3d_forward(const NNModule module, const Tensor tensor, const Tensor indices, const int64_t* outputSize, const int outputSizeLength);\n\nEXPORT_API(NNModule) THSNN_AdaptiveAvgPool1d_ctor(const int64_t* sizes, const int length, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_AdaptiveAvgPool1d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_AdaptiveAvgPool2d_ctor(const int64_t* sizes, const int length, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_AdaptiveAvgPool2d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_AdaptiveAvgPool3d_ctor(const int64_t* sizes, const int length, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_AdaptiveAvgPool3d_forward(const NNModule module, const Tensor tensor);\n\nEXPORT_API(NNModule) THSNN_AdaptiveMaxPool1d_ctor(const int64_t* sizes, const int length, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_AdaptiveMaxPool1d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_AdaptiveMaxPool2d_ctor(const int64_t* sizes, const int length, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_AdaptiveMaxPool2d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_AdaptiveMaxPool3d_ctor(const int64_t* sizes, const int length, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_AdaptiveMaxPool3d_forward(const NNModule module, const Tensor tensor);\n\nEXPORT_API(NNModule) THSNN_AvgPool1d_ctor(const int64_t* kernelSize, const int64_t* stride, const int64_t* padding, bool ceil_mode, bool count_include_pad, int64_t divisor_override, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_AvgPool1d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_AvgPool2d_ctor(const int64_t* kernelSize, const int kernelSizeLength, const int64_t* stride, const int strideLength, const int64_t* padding, const int paddingLength, bool ceil_mode, bool count_include_pad, int64_t divisor_override, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_AvgPool2d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_AvgPool3d_ctor(const int64_t* kernelSize, const int kernelSizeLength, const int64_t* stride, const int strideLength, const int64_t* padding, const int paddingLength, bool ceil_mode, bool count_include_pad, int64_t divisor_override, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_AvgPool3d_forward(const NNModule module, const Tensor tensor);\n\nEXPORT_API(NNModule) THSNN_LPPool1d_ctor(double norm_type, const int64_t* kernelSize, const int64_t* stride, bool ceil_mode, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_LPPool1d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_LPPool2d_ctor(double norm_type, const int64_t* kernelSize, const int kernelSizeLength, const int64_t* stride, const int strideLength, bool ceil_mode, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_LPPool2d_forward(const NNModule module, const Tensor tensor);\n\n// Padding\n\nEXPORT_API(NNModule) THSNN_ZeroPad2d_ctor(const int64_t padding, NNAnyModule* outAsAnyModule);\nEXPORT_API(NNModule) THSNN_ZeroPad2d_ctor_tuple(const int64_t padding_left, const int64_t padding_right, const int64_t padding_top, const int64_t padding_bottom, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_ZeroPad2d_forward(const NNModule module, const Tensor tensor);\n\nEXPORT_API(NNModule) THSNN_ConstantPad1d_ctor(const double value, const int64_t padding, NNAnyModule* outAsAnyModule);\nEXPORT_API(NNModule) THSNN_ConstantPad1d_ctor_tuple(const double value, const int64_t padding_left, const int64_t padding_right, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_ConstantPad1d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_ConstantPad2d_ctor(const double value, const int64_t padding, NNAnyModule* outAsAnyModule);\nEXPORT_API(NNModule) THSNN_ConstantPad2d_ctor_tuple(const double value, const int64_t padding_left, const int64_t padding_right, const int64_t padding_top, const int64_t padding_bottom, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_ConstantPad2d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_ConstantPad3d_ctor(const double value, const int64_t padding, NNAnyModule* outAsAnyModule);\nEXPORT_API(NNModule) THSNN_ConstantPad3d_ctor_tuple(const double value, const int64_t padding_left, const int64_t padding_right, const int64_t padding_top, const int64_t padding_bottom, const int64_t padding_front, const int64_t padding_back, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_ConstantPad3d_forward(const NNModule module, const Tensor tensor);\n\nEXPORT_API(NNModule) THSNN_ReplicationPad1d_ctor(const int64_t padding, NNAnyModule* outAsAnyModule);\nEXPORT_API(NNModule) THSNN_ReplicationPad1d_ctor_tuple(const int64_t padding_left, const int64_t padding_right, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_ReplicationPad1d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_ReplicationPad2d_ctor(const int64_t padding, NNAnyModule* outAsAnyModule);\nEXPORT_API(NNModule) THSNN_ReplicationPad2d_ctor_tuple(const int64_t padding_left, const int64_t padding_right, const int64_t padding_top, const int64_t padding_bottom, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_ReplicationPad2d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_ReplicationPad3d_ctor(const int64_t padding, NNAnyModule* outAsAnyModule);\nEXPORT_API(NNModule) THSNN_ReplicationPad3d_ctor_tuple(const int64_t padding_left, const int64_t padding_right, const int64_t padding_top, const int64_t padding_bottom, const int64_t padding_front, const int64_t padding_back, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_ReplicationPad3d_forward(const NNModule module, const Tensor tensor);\n\nEXPORT_API(NNModule) THSNN_ReflectionPad1d_ctor(const int64_t padding, NNAnyModule* outAsAnyModule);\nEXPORT_API(NNModule) THSNN_ReflectionPad1d_ctor_tuple(const int64_t padding_left, const int64_t padding_right, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_ReflectionPad1d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_ReflectionPad2d_ctor(const int64_t padding, NNAnyModule* outAsAnyModule);\nEXPORT_API(NNModule) THSNN_ReflectionPad2d_ctor_tuple(const int64_t padding_left, const int64_t padding_right, const int64_t padding_top, const int64_t padding_bottom, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_ReflectionPad2d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_ReflectionPad3d_ctor(const int64_t padding, NNAnyModule* outAsAnyModule);\nEXPORT_API(NNModule) THSNN_ReflectionPad3d_ctor_tuple(const int64_t padding_left, const int64_t padding_right, const int64_t padding_top, const int64_t padding_bottom, const int64_t padding_front, const int64_t padding_back, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_ReflectionPad3d_forward(const NNModule module, const Tensor tensor);\n\n// Convolution\n\nEXPORT_API(NNModule) THSNN_Conv1d_ctor(const int64_t inputChannel, const int64_t outputChannel, const int64_t kernelSize, const int64_t stride, const int64_t padding, const int64_t dilation, const int64_t paddingMode, const int64_t groups, const bool bias, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Conv1d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(Tensor) THSNN_Conv1d_bias(const NNModule module);\nEXPORT_API(void) THSNN_Conv1d_set_bias(const NNModule module, const Tensor bias);\nEXPORT_API(Tensor) THSNN_Conv1d_weight(const NNModule module);\nEXPORT_API(void) THSNN_Conv1d_set_weight(const NNModule module, const Tensor weight);\nEXPORT_API(NNModule) THSNN_Conv2d_ctor(const int64_t inputChannel, const int64_t outputChannel, const int64_t kernelSize, const int64_t stride, const int64_t padding, const int64_t dilation, const int64_t paddingMode, const int64_t groups, const bool bias, NNAnyModule* outAsAnyModule);\nEXPORT_API(NNModule) THSNN_Conv2d_ctor_1(const int64_t inputChannel, const int64_t outputChannel, const int64_t kernelX, const int64_t kernelY, const int64_t strideX, const int64_t strideY, const int64_t paddingX, const int64_t paddingY, const int64_t dilationX, const int64_t dilationY, const int64_t paddingMode, const int64_t groups, const bool bias, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Conv2d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(Tensor) THSNN_Conv2d_weight(const NNModule module);\nEXPORT_API(void) THSNN_Conv2d_set_weight(const NNModule module, const Tensor weight);\nEXPORT_API(Tensor) THSNN_Conv2d_bias(const NNModule module);\nEXPORT_API(void) THSNN_Conv2d_set_bias(const NNModule module, const Tensor bias);\nEXPORT_API(NNModule) THSNN_Conv3d_ctor(const int64_t inputChannel, const int64_t outputChannel, const int64_t kernelSize, const int64_t stride, const int64_t padding, const int64_t dilation, const int64_t paddingMode, const int64_t groups, const bool bias, NNAnyModule* outAsAnyModule);\nEXPORT_API(NNModule) THSNN_Conv3d_ctor_1(const int64_t inputChannel, const int64_t outputChannel, const int64_t kernelX, const int64_t kernelY, const int64_t kernelZ, const int64_t strideX, const int64_t strideY, const int64_t strideZ, const int64_t paddingX, const int64_t paddingY, const int64_t paddingZ, const int64_t dilationX, const int64_t dilationY, const int64_t dilationZ, const int64_t paddingMode, const int64_t groups, const bool bias, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Conv3d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(Tensor) THSNN_Conv3d_weight(const NNModule module);\nEXPORT_API(void) THSNN_Conv3d_set_weight(const NNModule module, const Tensor weight);\nEXPORT_API(Tensor) THSNN_Conv3d_bias(const NNModule module);\nEXPORT_API(void) THSNN_Conv3d_set_bias(const NNModule module, const Tensor bias);\n\nEXPORT_API(NNModule) THSNN_ConvTranspose1d_ctor(const int64_t inputChannel, const int64_t outputChannel, const int64_t kernelSize, const int64_t stride, const int64_t padding, const int64_t output_padding, const int64_t dilation, const int64_t paddingMode, const int64_t groups, const bool bias, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_ConvTranspose1d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(Tensor) THSNN_ConvTranspose1d_bias(const NNModule module);\nEXPORT_API(void) THSNN_ConvTranspose1d_set_bias(const NNModule module, const Tensor bias);\nEXPORT_API(Tensor) THSNN_ConvTranspose1d_weight(const NNModule module);\nEXPORT_API(void) THSNN_ConvTranspose1d_set_weight(const NNModule module, const Tensor weight);\nEXPORT_API(NNModule) THSNN_ConvTranspose2d_ctor(const int64_t inputChannel, const int64_t outputChannel, const int64_t kernelSize, const int64_t stride, const int64_t padding, const int64_t output_padding, const int64_t dilation, const int64_t paddingMode, const int64_t groups, const bool bias, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_ConvTranspose2d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(Tensor) THSNN_ConvTranspose2d_weight(const NNModule module);\nEXPORT_API(void) THSNN_ConvTranspose2d_set_weight(const NNModule module, const Tensor weight);\nEXPORT_API(Tensor) THSNN_ConvTranspose2d_bias(const NNModule module);\nEXPORT_API(void) THSNN_ConvTranspose2d_set_bias(const NNModule module, const Tensor bias);\nEXPORT_API(NNModule) THSNN_ConvTranspose3d_ctor(const int64_t inputChannel, const int64_t outputChannel, const int64_t kernelSize, const int64_t stride, const int64_t padding, const int64_t output_padding, const int64_t dilation, const int64_t paddingMode, const int64_t groups, const bool bias, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_ConvTranspose3d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(Tensor) THSNN_ConvTranspose3d_weight(const NNModule module);\nEXPORT_API(void) THSNN_ConvTranspose3d_set_weight(const NNModule module, const Tensor weight);\nEXPORT_API(Tensor) THSNN_ConvTranspose3d_bias(const NNModule module);\nEXPORT_API(void) THSNN_ConvTranspose3d_set_bias(const NNModule module, const Tensor bias);\n\n// Normalization\n\nEXPORT_API(NNModule) THSNN_BatchNorm1d_ctor(const int64_t features, const double eps, const double momentum, const bool affine, const bool track_running_stats, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_BatchNorm1d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_BatchNorm2d_ctor(const int64_t features, const double eps, const double momentum, const bool affine, const bool track_running_stats, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_BatchNorm2d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_BatchNorm3d_ctor(const int64_t features, const double eps, const double momentum, const bool affine, const bool track_running_stats, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_BatchNorm3d_forward(const NNModule module, const Tensor tensor);\n\nEXPORT_API(Tensor) THSNN_BatchNorm1d_bias(const NNModule module);\nEXPORT_API(void) THSNN_BatchNorm1d_set_bias(const NNModule module, const Tensor bias);\nEXPORT_API(Tensor) THSNN_BatchNorm1d_weight(const NNModule module);\nEXPORT_API(void) THSNN_BatchNorm1d_set_weight(const NNModule module, const Tensor weight);\n\nEXPORT_API(Tensor) THSNN_BatchNorm2d_bias(const NNModule module);\nEXPORT_API(void) THSNN_BatchNorm2d_set_bias(const NNModule module, const Tensor bias);\nEXPORT_API(Tensor) THSNN_BatchNorm2d_weight(const NNModule module);\nEXPORT_API(void) THSNN_BatchNorm2d_set_weight(const NNModule module, const Tensor weight);\n\nEXPORT_API(Tensor) THSNN_BatchNorm3d_bias(const NNModule module);\nEXPORT_API(void) THSNN_BatchNorm3d_set_bias(const NNModule module, const Tensor bias);\nEXPORT_API(Tensor) THSNN_BatchNorm3d_weight(const NNModule module);\nEXPORT_API(void) THSNN_BatchNorm3d_set_weight(const NNModule module, const Tensor weight);\n\nEXPORT_API(void) THSNN_BatchNorm1d_reset_stats(const NNModule module);\nEXPORT_API(void) THSNN_BatchNorm2d_reset_stats(const NNModule module);\nEXPORT_API(void) THSNN_BatchNorm3d_reset_stats(const NNModule module);\n\nEXPORT_API(Tensor) THSNN_BatchNorm1d_get_mean(const NNModule module);\nEXPORT_API(Tensor) THSNN_BatchNorm2d_get_mean(const NNModule module);\nEXPORT_API(Tensor) THSNN_BatchNorm3d_get_mean(const NNModule module);\n\nEXPORT_API(void) THSNN_BatchNorm1d_set_mean(const NNModule module, const Tensor weight);\nEXPORT_API(void) THSNN_BatchNorm2d_set_mean(const NNModule module, const Tensor weight);\nEXPORT_API(void) THSNN_BatchNorm3d_set_mean(const NNModule module, const Tensor weight);\n\nEXPORT_API(Tensor) THSNN_BatchNorm1d_get_var(const NNModule module);\nEXPORT_API(Tensor) THSNN_BatchNorm2d_get_var(const NNModule module);\nEXPORT_API(Tensor) THSNN_BatchNorm3d_get_var(const NNModule module);\n\nEXPORT_API(void) THSNN_BatchNorm1d_set_var(const NNModule module, const Tensor weight);\nEXPORT_API(void) THSNN_BatchNorm2d_set_var(const NNModule module, const Tensor weight);\nEXPORT_API(void) THSNN_BatchNorm3d_set_var(const NNModule module, const Tensor weight);\n\nEXPORT_API(Tensor) THSNN_BatchNorm1d_get_batches(const NNModule module);\nEXPORT_API(Tensor) THSNN_BatchNorm2d_get_batches(const NNModule module);\nEXPORT_API(Tensor) THSNN_BatchNorm3d_get_batches(const NNModule module);\n\nEXPORT_API(NNModule) THSNN_InstanceNorm1d_ctor(const int64_t features, const double eps, const double momentum, const bool affine, const bool track_running_stats, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_InstanceNorm1d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_InstanceNorm2d_ctor(const int64_t features, const double eps, const double momentum, const bool affine, const bool track_running_stats, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_InstanceNorm2d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_InstanceNorm3d_ctor(const int64_t features, const double eps, const double momentum, const bool affine, const bool track_running_stats, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_InstanceNorm3d_forward(const NNModule module, const Tensor tensor);\n\nEXPORT_API(Tensor) THSNN_InstanceNorm1d_bias(const NNModule module);\nEXPORT_API(void) THSNN_InstanceNorm1d_set_bias(const NNModule module, const Tensor bias);\nEXPORT_API(Tensor) THSNN_InstanceNorm1d_weight(const NNModule module);\nEXPORT_API(void) THSNN_InstanceNorm1d_set_weight(const NNModule module, const Tensor weight);\n\nEXPORT_API(Tensor) THSNN_InstanceNorm2d_bias(const NNModule module);\nEXPORT_API(void) THSNN_InstanceNorm2d_set_bias(const NNModule module, const Tensor bias);\nEXPORT_API(Tensor) THSNN_InstanceNorm2d_weight(const NNModule module);\nEXPORT_API(void) THSNN_InstanceNorm2d_set_weight(const NNModule module, const Tensor weight);\n\nEXPORT_API(Tensor) THSNN_InstanceNorm3d_bias(const NNModule module);\nEXPORT_API(void) THSNN_InstanceNorm3d_set_bias(const NNModule module, const Tensor bias);\nEXPORT_API(Tensor) THSNN_InstanceNorm3d_weight(const NNModule module);\nEXPORT_API(void) THSNN_InstanceNorm3d_set_weight(const NNModule module, const Tensor weight);\n\nEXPORT_API(void) THSNN_InstanceNorm1d_reset_stats(const NNModule module);\nEXPORT_API(void) THSNN_InstanceNorm2d_reset_stats(const NNModule module);\nEXPORT_API(void) THSNN_InstanceNorm3d_reset_stats(const NNModule module);\n\nEXPORT_API(Tensor) THSNN_InstanceNorm1d_get_mean(const NNModule module);\nEXPORT_API(Tensor) THSNN_InstanceNorm2d_get_mean(const NNModule module);\nEXPORT_API(Tensor) THSNN_InstanceNorm3d_get_mean(const NNModule module);\n\nEXPORT_API(void) THSNN_InstanceNorm1d_set_mean(const NNModule module, const Tensor weight);\nEXPORT_API(void) THSNN_InstanceNorm2d_set_mean(const NNModule module, const Tensor weight);\nEXPORT_API(void) THSNN_InstanceNorm3d_set_mean(const NNModule module, const Tensor weight);\n\nEXPORT_API(Tensor) THSNN_InstanceNorm1d_get_var(const NNModule module);\nEXPORT_API(Tensor) THSNN_InstanceNorm2d_get_var(const NNModule module);\nEXPORT_API(Tensor) THSNN_InstanceNorm3d_get_var(const NNModule module);\n\nEXPORT_API(void) THSNN_InstanceNorm1d_set_var(const NNModule module, const Tensor weight);\nEXPORT_API(void) THSNN_InstanceNorm2d_set_var(const NNModule module, const Tensor weight);\nEXPORT_API(void) THSNN_InstanceNorm3d_set_var(const NNModule module, const Tensor weight);\n\nEXPORT_API(Tensor) THSNN_InstanceNorm1d_get_batches(const NNModule module);\nEXPORT_API(Tensor) THSNN_InstanceNorm2d_get_batches(const NNModule module);\nEXPORT_API(Tensor) THSNN_InstanceNorm3d_get_batches(const NNModule module);\n\n\n\nEXPORT_API(NNModule) THSNN_LayerNorm_ctor(const int64_t* norm_shape, const int64_t norm_shape_len, const double eps, const bool elementwise_affine, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_LayerNorm_forward(const NNModule module, const Tensor tensor);\n\nEXPORT_API(Tensor) THSNN_LayerNorm_bias(const NNModule module);\nEXPORT_API(void) THSNN_LayerNorm_set_bias(const NNModule module, const Tensor bias);\nEXPORT_API(Tensor) THSNN_LayerNorm_weight(const NNModule module);\nEXPORT_API(void) THSNN_LayerNorm_set_weight(const NNModule module, const Tensor weight);\n\nEXPORT_API(NNModule) THSNN_GroupNorm_ctor(const int64_t num_groups, const int64_t num_channels, const double eps, const bool affine, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_GroupNorm_forward(const NNModule module, const Tensor tensor);\n\nEXPORT_API(Tensor) THSNN_GroupNorm_bias(const NNModule module);\nEXPORT_API(void) THSNN_GroupNorm_set_bias(const NNModule module, const Tensor bias);\nEXPORT_API(Tensor) THSNN_GroupNorm_weight(const NNModule module);\nEXPORT_API(void) THSNN_GroupNorm_set_weight(const NNModule module, const Tensor weight);\n\nEXPORT_API(NNModule) THSNN_LocalResponseNorm_ctor(const int64_t size, const double alpha, const double beta, const double k, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_LocalResponseNorm_forward(const NNModule module, const Tensor tensor);\n\nEXPORT_API(Tensor) THSNN_batch_norm(const Tensor input, const Tensor running_mean, const Tensor running_var, const Tensor weight, const Tensor bias, const bool training, const double momentum, const double eps);\nEXPORT_API(Tensor) THSNN_group_norm(const Tensor input, int64_t num_groups, const Tensor weight, const Tensor bias, const double eps);\nEXPORT_API(Tensor) THSNN_instance_norm(const Tensor input, const Tensor running_mean, const Tensor running_var, const Tensor weight, const Tensor bias, const bool use_input_stats, const double momentum, const double eps);\nEXPORT_API(Tensor) THSNN_layer_norm(const Tensor input, const int64_t* normalized_shape, const int64_t normalized_shape_len, const Tensor weight, const Tensor bias, const double eps);\nEXPORT_API(Tensor) THSNN_local_response_norm(const Tensor input, const int64_t size, const double alpha, const double beta, const double k);\n\n// Dropout\n\nEXPORT_API(NNModule) THSNN_Dropout_ctor(double probability, bool inplace, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Dropout_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Dropout1d_ctor(double probability, bool inplace, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Dropout1d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Dropout2d_ctor(double probability, bool inplace, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Dropout2d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Dropout3d_ctor(double probability, bool inplace, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Dropout3d_forward(const NNModule module, const Tensor tensor);\n\nEXPORT_API(NNModule) THSNN_AlphaDropout_ctor(double probability, bool inplace, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_AlphaDropout_forward(const NNModule module, const Tensor tensor);\n\nEXPORT_API(NNModule) THSNN_FeatureAlphaDropout_ctor(double probability, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_FeatureAlphaDropout_forward(const NNModule module, const Tensor tensor);\n\nEXPORT_API(Tensor) THSNN_dropout(const Tensor input, const double p, bool training, bool inplace);\nEXPORT_API(Tensor) THSNN_dropout2d(const Tensor input, const double p, bool training, bool inplace);\nEXPORT_API(Tensor) THSNN_dropout3d(const Tensor input, const double p, bool training, bool inplace);\n\nEXPORT_API(Tensor) THSNN_alpha_dropout(const Tensor input, const double p, bool training, bool inplace);\n\nEXPORT_API(Tensor) THSNN_feature_alpha_dropout(const Tensor input, const double p, bool training, bool inplace);\n\nEXPORT_API(Tensor) THSNN_fold(const Tensor input, const int64_t out1, const int64_t out2, const int64_t kernel1, const int64_t kernel2, const int64_t stride1, const int64_t stride2, const int64_t pad1, const int64_t pad2, const int64_t dil1, const int64_t dil2);\nEXPORT_API(Tensor) THSNN_unfold(const Tensor input, const int64_t kernel1, const int64_t kernel2, const int64_t stride1, const int64_t stride2, const int64_t pad1, const int64_t pad2, const int64_t dil1, const int64_t dil2);\n\n// Linear\n\nEXPORT_API(NNModule) THSNN_Identity_ctor(NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Identity_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Linear_ctor(const int64_t input_size, const int64_t output_size, const bool with_bias, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Linear_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(Tensor) THSNN_Linear_bias(const NNModule module);\nEXPORT_API(void) THSNN_Linear_set_bias(const NNModule module, const Tensor tensor);\nEXPORT_API(Tensor) THSNN_Linear_weight(const NNModule module);\nEXPORT_API(void) THSNN_Linear_set_weight(const NNModule module, const Tensor tensor);\n\nEXPORT_API(Tensor) THSNN_functional_linear(const Tensor input, const Tensor weights, const Tensor bias);\nEXPORT_API(Tensor) THSNN_functional_bilinear(const Tensor input1, const Tensor input2, const Tensor weights, const Tensor bias);\n\nEXPORT_API(NNModule) THSNN_Bilinear_ctor(const int64_t input_size_1, const int64_t input_size_2, const int64_t output_size, const bool with_bias, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Bilinear_forward(const NNModule module, const Tensor x1, const Tensor x2);\nEXPORT_API(Tensor) THSNN_Bilinear_bias(const NNModule module);\nEXPORT_API(void) THSNN_Bilinear_set_bias(const NNModule module, const Tensor tensor);\nEXPORT_API(Tensor) THSNN_Bilinear_weight(const NNModule module);\nEXPORT_API(void) THSNN_Bilinear_set_weight(const NNModule module, const Tensor tensor);\n\n// Vision -- Modules\n\nEXPORT_API(NNModule) THSNN_PixelShuffle_ctor(const int64_t upscale_factor, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_PixelShuffle_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_PixelUnshuffle_ctor(const int64_t downscale_factor, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_PixelUnshuffle_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Upsample_ctor(const int64_t* size, const int size_len, const double* scale_factor, const int scale_factor_len, const int8_t mode, const int8_t align_corners, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Upsample_forward(const NNModule module, const Tensor tensor);\n\n// Vision -- Functions\n\nEXPORT_API(Tensor) THSNN_pad(const Tensor input, const int64_t* pad, const int pad_length, const int8_t mode, const double value);\nEXPORT_API(Tensor) THSNN_interpolate(const Tensor input, const int64_t* size, const int size_len, const double* scale_factor, const int scale_factor_len, const int8_t mode, const int8_t align_corners, const bool recompute_scale_factor, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_grid_sample(const Tensor input, const Tensor grid, const int8_t mode, const int8_t padding_mode, const int8_t align_corners);\nEXPORT_API(Tensor) THSNN_affine_grid(const Tensor theta, const int64_t* size, const int size_len, const bool align_corners);\n\n// Activation functions\n\nEXPORT_API(NNModule) THSNN_CELU_ctor(const double alpha, const bool inplace, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_CELU_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_ELU_ctor(const double alpha, const bool inplace, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_ELU_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_GELU_ctor(NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_GELU_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_GLU_ctor(const int64_t dim, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_GLU_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Hardshrink_ctor(const double lambda, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Hardshrink_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Hardtanh_ctor(const double min_val, const double max_val, const bool inplace, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Hardtanh_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_LeakyReLU_ctor(const double negative_sloope, const bool inplace, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_LeakyReLU_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Mish_ctor(NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Mish_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_PReLU_ctor(const int64_t nparams, const double init, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_PReLU_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(Tensor) THSNN_PReLU_weight(const NNModule module);\nEXPORT_API(void) THSNN_PReLU_set_weight(const NNModule module, const Tensor weight);\nEXPORT_API(NNModule) THSNN_ReLU_ctor(bool inplace, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_ReLU_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_ReLU6_ctor(bool inplace, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_ReLU6_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_RReLU_ctor(const double lower, const double upper, const bool inplace, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_RReLU_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_LogSoftmax_ctor(int64_t dim, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_LogSoftmax_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_SELU_ctor(bool inplace, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_SELU_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Sigmoid_ctor(NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Sigmoid_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_SiLU_ctor(NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_SiLU_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Softmax_ctor(const int64_t dim, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Softmax_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Softmax2d_ctor(NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Softmax2d_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Softmin_ctor(const int64_t dim, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Softmin_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Softplus_ctor(const double beta, const double threshold, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Softplus_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Softshrink_ctor(const double lambda, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Softshrink_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Softsign_ctor(NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Softsign_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Tanh_ctor(NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Tanh_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Tanhshrink_ctor(NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Tanhshrink_forward(const NNModule module, const Tensor tensor);\nEXPORT_API(NNModule) THSNN_Threshold_ctor(const double threshold, const double value, const bool inplace, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Threshold_forward(const NNModule module, const Tensor tensor);\n\n// Sparse\n\nEXPORT_API(NNModule) THSNN_Embedding_ctor(const int64_t num_embeddings, const int64_t embedding_dims, const int64_t padding_idx, bool has_pi, const double max_norm, const bool has_mn, const double norm_type, const bool scale_grad_by_freq, const bool sparse, NNAnyModule* outAsAnyModule);\nEXPORT_API(NNModule) THSNN_Embedding_from_pretrained(const Tensor embeddings, const bool freeze, const int64_t padding_idx, bool has_pi, const double max_norm, const bool has_mn, const double norm_type, const bool scale_grad_by_freq, const bool sparse, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Embedding_forward(const NNModule module, const Tensor weights);\nEXPORT_API(Tensor) THSNN_Embedding_weight(const NNModule module);\nEXPORT_API(void) THSNN_Embedding_set_weight(const NNModule module, const Tensor weights);\n\nEXPORT_API(NNModule) THSNN_EmbeddingBag_ctor(const int64_t num_embeddings, const int64_t embedding_dims, const double max_norm, const bool has_mn, const double norm_type, const bool scale_grad_by_freq, const int64_t mode, const bool sparse, const bool include_last_offset, const int64_t padding_idx, NNAnyModule* outAsAnyModule);\nEXPORT_API(NNModule) THSNN_EmbeddingBag_from_pretrained(const Tensor embeddings, const bool freeze, const double max_norm, const bool has_mn, const double norm_type, const bool scale_grad_by_freq, const int64_t mode, const bool sparse, const bool include_last_offset, const int64_t padding_idx, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_EmbeddingBag_forward(const NNModule module, const Tensor input, const Tensor offsets, const Tensor per_sample_weights);\nEXPORT_API(Tensor) THSNN_EmbeddingBag_weight(const NNModule module);\nEXPORT_API(void) THSNN_EmbeddingBag_set_weight(const NNModule module, const Tensor weights);\n\n// Transformer\n\nEXPORT_API(NNModule) THSNN_Transformer_ctor(const int64_t d_model, const int64_t nhead, const int64_t num_encoder_layers, const int64_t num_decoder_layers, const int64_t dim_feedforward, const double dropout, const int64_t activation, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Transformer_forward(const NNModule module, const Tensor src, const Tensor tgt, const Tensor src_mask, const Tensor tgt_mask, const Tensor memory_mask, const Tensor src_key_padding_mask, const Tensor tgt_key_padding_mask, const Tensor memory_key_padding_mask);\nEXPORT_API(NNModule) THSNN_TransformerEncoderLayer_ctor(const int64_t d_model, const int64_t nhead, const int64_t dim_feedforward, const double dropout, const int64_t activation, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_TransformerEncoderLayer_forward(const NNModule module, const Tensor src, const Tensor src_mask, const Tensor src_key_padding_mask);\nEXPORT_API(NNModule) THSNN_TransformerDecoderLayer_ctor(const int64_t d_model, const int64_t nhead, const int64_t dim_feedforward, const double dropout, const int64_t activation, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_TransformerDecoderLayer_forward(const NNModule module, const Tensor tgt, const Tensor memory, const Tensor tgt_mask, const Tensor memory_mask, const Tensor tgt_key_padding_mask, const Tensor memory_key_padding_mask);\nEXPORT_API(NNModule) THSNN_TransformerEncoder_ctor(const NNModule encoder_layer, const int64_t num_layers, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_TransformerEncoder_forward(const NNModule module, const Tensor src, const Tensor src_mask, const Tensor src_key_padding_mask);\nEXPORT_API(NNModule) THSNN_TransformerDecoder_ctor(const NNModule decoder_layer, const int64_t num_layers, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_TransformerDecoder_forward(const NNModule module, const Tensor tgt, const Tensor memory, const Tensor tgt_mask, const Tensor memory_mask, const Tensor tgt_key_padding_mask, const Tensor memory_key_padding_mask);\nEXPORT_API(NNModule) THSNN_MultiheadAttention_ctor(const int64_t embeded_dim, const int64_t num_heads, const double dropout, const bool bias, const bool add_bias_kv, const bool add_zero_attn, const int64_t kdim, const int64_t vdim, NNAnyModule* outAsAnyModule);\nEXPORT_API(void) THSNN_MultiheadAttention_forward(const NNModule module, const Tensor query, const Tensor key, const Tensor value, const Tensor key_padding_mask, const bool need_weights, const Tensor attn_mask, Tensor& res1, Tensor& res2);\n\n\n// Recurrent\n\nEXPORT_API(NNModule) THSNN_RNN_ctor(const int64_t input_size, const int64_t hidden_size, const int64_t num_layers, const int64_t nonlinearity, const bool bias, const bool batchFirst, const double dropout, const bool bidirectional, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_RNN_forward(const NNModule module, const Tensor input1, const Tensor input2, Tensor* h_n);\nEXPORT_API(PackedSequence) THSNN_RNN_forward_with_packed_input(const NNModule module, const PackedSequence input1, const Tensor input2, Tensor* h_n);\nEXPORT_API(NNModule) THSNN_GRU_ctor(const int64_t input_size, const int64_t hidden_size, const int64_t num_layers, const bool bias, const bool batchFirst, const double dropout, const bool bidirectional, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_GRU_forward(const NNModule module, const Tensor input1, const Tensor input2, Tensor* h_n);\nEXPORT_API(PackedSequence) THSNN_GRU_forward_with_packed_input(const NNModule module, const PackedSequence input1, const Tensor input2, Tensor* h_n);\nEXPORT_API(NNModule) THSNN_LSTM_ctor(const int64_t input_size, const int64_t hidden_size, const int64_t num_layers, const bool bias, const bool batchFirst, const double dropout, const bool bidirectional, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_LSTM_forward(const NNModule module, const Tensor input1, const Tensor h0, const Tensor c0, Tensor* h_n, Tensor* c_n);\nEXPORT_API(PackedSequence) THSNN_LSTM_forward_with_packed_input(const NNModule module, const PackedSequence input1, const Tensor h0, const Tensor c0, Tensor* h_n, Tensor* c_n);\n\nEXPORT_API(NNModule) THSNN_RNNCell_ctor(const int64_t input_size, const int64_t hidden_size, const int64_t nonlinearity, const bool bias, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_RNNCell_forward(const NNModule module, const Tensor input1, const Tensor h0);\nEXPORT_API(NNModule) THSNN_GRUCell_ctor(const int64_t input_size, const int64_t hidden_size, const bool bias, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_GRUCell_forward(const NNModule module, const Tensor input1, const Tensor h0);\nEXPORT_API(NNModule) THSNN_LSTMCell_ctor(const int64_t input_size, const int64_t hidden_size, const bool bias, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_LSTMCell_forward(const NNModule module, const Tensor input1, const Tensor h0, const Tensor c0, Tensor* c_n);\n\nEXPORT_API(void) THSNN_RNN_flatten_parameters(const NNModule module);\nEXPORT_API(void) THSNN_GRU_flatten_parameters(const NNModule module);\nEXPORT_API(void) THSNN_LSTM_flatten_parameters(const NNModule module);\n\nEXPORT_API(Tensor) THSNN_RNN_bias_ih(const NNModule module, const int64_t idx);\nEXPORT_API(void) THSNN_RNN_set_bias_ih(const NNModule module, const Tensor bias, const int64_t idx);\nEXPORT_API(Tensor) THSNN_RNN_weight_ih(const NNModule module, const int64_t idx);\nEXPORT_API(void) THSNN_RNN_set_weight_ih(const NNModule module, const Tensor weight, const int64_t idx);\nEXPORT_API(Tensor) THSNN_RNN_bias_hh(const NNModule module, const int64_t idx);\nEXPORT_API(void) THSNN_RNN_set_bias_hh(const NNModule module, const Tensor bias, const int64_t idx);\nEXPORT_API(Tensor) THSNN_RNN_weight_hh(const NNModule module, const int64_t idx);\nEXPORT_API(void) THSNN_RNN_set_weight_hh(const NNModule module, const Tensor weight, const int64_t idx);\n\nEXPORT_API(Tensor) THSNN_RNNCell_bias_ih(const NNModule module);\nEXPORT_API(void) THSNN_RNNCell_set_bias_ih(const NNModule module, const Tensor bias);\nEXPORT_API(Tensor) THSNN_RNNCell_weight_ih(const NNModule module);\nEXPORT_API(void) THSNN_RNNCell_set_weight_ih(const NNModule module, const Tensor weight);\nEXPORT_API(Tensor) THSNN_RNNCell_bias_hh(const NNModule module);\nEXPORT_API(void) THSNN_RNNCell_set_bias_hh(const NNModule module, const Tensor bias);\nEXPORT_API(Tensor) THSNN_RNNCell_weight_hh(const NNModule module);\nEXPORT_API(void) THSNN_RNNCell_set_weight_hh(const NNModule module, const Tensor weight);\n\nEXPORT_API(Tensor) THSNN_LSTMCell_bias_ih(const NNModule module);\nEXPORT_API(void) THSNN_LSTMCell_set_bias_ih(const NNModule module, const Tensor bias);\nEXPORT_API(Tensor) THSNN_LSTMCell_weight_ih(const NNModule module);\nEXPORT_API(void) THSNN_LSTMCell_set_weight_ih(const NNModule module, const Tensor weight);\nEXPORT_API(Tensor) THSNN_LSTMCell_bias_hh(const NNModule module);\nEXPORT_API(void) THSNN_LSTMCell_set_bias_hh(const NNModule module, const Tensor bias);\nEXPORT_API(Tensor) THSNN_LSTMCell_weight_hh(const NNModule module);\nEXPORT_API(void) THSNN_LSTMCell_set_weight_hh(const NNModule module, const Tensor weight);\n\nEXPORT_API(Tensor) THSNN_GRUCell_bias_ih(const NNModule module);\nEXPORT_API(void) THSNN_GRUCell_set_bias_ih(const NNModule module, const Tensor bias);\nEXPORT_API(Tensor) THSNN_GRUCell_weight_ih(const NNModule module);\nEXPORT_API(void) THSNN_GRUCell_set_weight_ih(const NNModule module, const Tensor weight);\nEXPORT_API(Tensor) THSNN_GRUCell_bias_hh(const NNModule module);\nEXPORT_API(void) THSNN_GRUCell_set_bias_hh(const NNModule module, const Tensor bias);\nEXPORT_API(Tensor) THSNN_GRUCell_weight_hh(const NNModule module);\nEXPORT_API(void) THSNN_GRUCell_set_weight_hh(const NNModule module, const Tensor weight);\n\n// Containers\n\nEXPORT_API(NNModule) THSNN_Sequential_ctor();\nEXPORT_API(void) THSNN_Sequential_push_back(const NNModule module, const char* name, const NNAnyModule submodule);\nEXPORT_API(Tensor) THSNN_Sequential_forward(const NNModule module, const Tensor tensor);\n\n// Loss functions\n\nEXPORT_API(Tensor) THSNN_binary_cross_entropy(const Tensor input, const Tensor target, const Tensor weight, const int64_t reduction);\nEXPORT_API(Tensor) THSNN_binary_cross_entropy_with_logits(const Tensor input, const Tensor target, const Tensor weight, const int64_t reduction, const Tensor pos_weights_);\nEXPORT_API(Tensor) THSNN_cosine_embedding_loss(const Tensor input1, const Tensor input2, const Tensor target, const double margin, const int64_t reduction);\nEXPORT_API(Tensor) THSNN_cross_entropy(const Tensor input, const Tensor target, const Tensor weight, const int64_t ignore_index, const bool has_ii, const int64_t reduction, const double smoothing);\nEXPORT_API(Tensor) THSNN_ctc_loss(const Tensor log_probs, const Tensor targets, const Tensor input_lengths, const Tensor target_lengths, int64_t blank, bool zero_infinity, const int64_t reduction);\nEXPORT_API(Tensor) THSNN_hinge_embedding_loss(const Tensor input, const Tensor target, const double margin, const int64_t reduction);\nEXPORT_API(Tensor) THSNN_huber_loss(const Tensor input, const Tensor target, const double delta, const int64_t reduction);\nEXPORT_API(Tensor) THSNN_l1_loss(const Tensor input, const Tensor target, const int64_t reduction);\nEXPORT_API(Tensor) THSNN_margin_ranking_loss(const Tensor input1, const Tensor input2, const Tensor target, const double margin, const int64_t reduction);\nEXPORT_API(Tensor) THSNN_mse_loss(const Tensor input, const Tensor target, const int64_t reduction);\nEXPORT_API(Tensor) THSNN_multilabel_margin_loss(const Tensor input, const Tensor target, const int64_t reduction);\nEXPORT_API(Tensor) THSNN_multilabel_soft_margin_loss(const Tensor input, const Tensor target, const Tensor weight, const int64_t reduction);\nEXPORT_API(Tensor) THSNN_multi_margin_loss(const Tensor input, const Tensor target, const int64_t p, const double margin, const Tensor weight, const int64_t reduction);\nEXPORT_API(Tensor) THSNN_nll_loss(const Tensor input, const Tensor target, const Tensor weight, const int64_t reduction);\nEXPORT_API(Tensor) THSNN_poisson_loss(const Tensor input, const Tensor target, const bool logInput, const bool full, const double eps, const int64_t reduction);\nEXPORT_API(Tensor) THSNN_kl_div_loss(const Tensor input, const Tensor target, const int64_t reduction, const bool log_target);\nEXPORT_API(Tensor) THSNN_smooth_l1_loss(const Tensor input, const Tensor target, const int64_t reduction, const double beta);\nEXPORT_API(Tensor) THSNN_soft_margin_loss(const Tensor input, const Tensor target, const int64_t reduction);\nEXPORT_API(Tensor) THSNN_triplet_margin_loss(const Tensor anchor, const Tensor positive, const Tensor negative, double margin, int64_t p, double eps, bool swap, const int64_t reduction);\nEXPORT_API(Tensor) THSNN_triplet_margin_with_distance_loss(const Tensor anchor, const Tensor positive, const Tensor negative, Tensor (*distance_function)(const Tensor x, const Tensor y), double margin, bool swap, const int64_t reduction);\n\n// Optimizers\n\nEXPORT_API(Optimizer) THSNN_Adagrad_ctor(const Tensor* parameters, const int len, const double learning_rate, const double lr_decay, const double weight_decay, const double initial_accumulator_value, const double eps);\nEXPORT_API(Optimizer) THSNN_Adam_ctor(const Tensor* parameters, const int len, const double learning_rate, const double beta1, const double beta2, const double eps, const double weight_decay, const bool amsgrad);\nEXPORT_API(Optimizer) THSNN_AdamW_ctor(const Tensor* parameters, const int len, const double learning_rate, const double beta1, const double beta2, const double eps, const double weight_decay, const bool amsgrad);\nEXPORT_API(Optimizer) THSNN_LBFGS_ctor(const Tensor* parameters, const int len, const double lr, const int64_t max_iter, const int64_t max_eval, const double tolerange_grad, const double tolerance_change, const int64_t history_size);\nEXPORT_API(Optimizer) THSNN_RMSprop_ctor(const Tensor* parameters, const int length, const double learning_rate, const double alpha, const double eps, const double weight_decay, const double momentum, const bool centered);\nEXPORT_API(Optimizer) THSNN_SGD_ctor(const Tensor* parameters, const int length, const double learning_rate, const double momentum, const double dampening, const double weight_decay, const bool nesterov);\n\nEXPORT_API(void) THSNN_Adam_set_betas(const Optimizer optimizer, double beta1, double beta2);\nEXPORT_API(void) THSNN_AdamW_set_betas(const Optimizer optimizer, double beta1, double beta2);\nEXPORT_API(void) THSNN_RMSprop_set_momentum(const Optimizer optimizer, double momentum);\nEXPORT_API(void) THSNN_SGD_set_momentum(const Optimizer optimizer, double momentum);\n\nEXPORT_API(void) THSNN_Optimizer_zero_grad(const Optimizer optimizer);\nEXPORT_API(void) THSNN_Optimizer_getParameters(const Optimizer optimizer, Tensor* (*allocator)(size_t length));\nEXPORT_API(Tensor) THSNN_Optimizer_step(const Optimizer optimizer, Tensor(*loss_closure)());\n\nEXPORT_API(void) THSNN_Optimizer_dispose(const Optimizer optimizer);\n\nEXPORT_API(void) THSNN_Adagrad_set_lr(const Optimizer optimizer, const double lr);\nEXPORT_API(void) THSNN_Adam_set_lr(const Optimizer optimizer, const double lr);\nEXPORT_API(void) THSNN_AdamW_set_lr(const Optimizer optimizer, const double lr);\nEXPORT_API(void) THSNN_LBFGS_set_lr(const Optimizer optimizer, const double lr);\nEXPORT_API(void) THSNN_RMSprop_set_lr(const Optimizer optimizer, const double lr);\nEXPORT_API(void) THSNN_SGD_set_lr(const Optimizer optimizer, const double lr);\n\n// Misc.\n\nEXPORT_API(Tensor) THSNN_one_hot(const Tensor self, const int64_t num_classes);\n\nEXPORT_API(NNModule) THSNN_Flatten_ctor(const int64_t start_dim, const int64_t end_dim, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Flatten_forward(const NNModule module, const Tensor tensor);\n\nEXPORT_API(NNModule) THSNN_Unflatten_ctor(const int64_t dim, const int64_t* shape, const int64_t shape_len, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_Unflatten_forward(const NNModule module, const Tensor tensor);\n\nEXPORT_API(NNModule) THSNN_CosineSimilarity_ctor(const int64_t dim, double eps, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_CosineSimilarity_forward(const NNModule module, const Tensor input1, const Tensor input2);\n\nEXPORT_API(NNModule) THSNN_PairwiseDistance_ctor(double p, double eps, bool keep_dim, NNAnyModule* outAsAnyModule);\nEXPORT_API(Tensor) THSNN_PairwiseDistance_forward(const NNModule module, const Tensor input1, const Tensor input2);\n\nEXPORT_API(Tensor) THSNN_scaled_dot_product_attention(const Tensor query, const Tensor key, const Tensor value, const Tensor attention_mask, double p, bool casual);\n\n// Initializers\n\nEXPORT_API(void) THSNN_initUniform(Tensor twrapper, double low, double high);\nEXPORT_API(void) THSNN_initKaimingUniform(Tensor tensor, double a);\n\n// Utils RNN\n\nEXPORT_API(Tensor) THSNN_PackedSequence_data(PackedSequence sequence);\nEXPORT_API(Tensor) THSNN_PackedSequence_batch_sizes(PackedSequence sequence);\nEXPORT_API(Tensor) THSNN_PackedSequence_sorted_indices(PackedSequence sequence);\nEXPORT_API(Tensor) THSNN_PackedSequence_unsorted_indices(PackedSequence sequence);\nEXPORT_API(void) THSNN_PackedSequence_dispose(PackedSequence sequence);\nEXPORT_API(PackedSequence) THSNN_pack_padded_sequence(Tensor input, Tensor lengths, bool batch_first, bool enforce_sorted);\nEXPORT_API(void) THSNN_pad_packed_sequence(PackedSequence sequence, bool batch_first, double padding_value, int64_t total_length, Tensor* res1, Tensor* res2);\nEXPORT_API(Tensor) THSNN_pad_sequence(const Tensor* sequences, const int sequences_len, bool batch_first, double padding_value);\nEXPORT_API(PackedSequence) THSNN_pack_sequence(const Tensor* sequences, int sequences_len, bool enforce_sorted);\n" }, { "alpha_fraction": 0.5700336694717407, "alphanum_fraction": 0.577104389667511, "avg_line_length": 43.3283576965332, "blob_id": "e68621f6b0776cfa4e2e92b351544d06f20a8044", "content_id": "16360fdc6c2ccad37f338ad9bc8092fca312bc52", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2970, "license_type": "permissive", "max_line_length": 142, "num_lines": 67, "path": "/src/TorchSharp/NN/PairwiseDistance.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// Computes the pairwise distance between vectors using the p-norm.\n /// </summary>\n public sealed class PairwiseDistance : torch.nn.Module<Tensor, Tensor, Tensor>\n {\n internal PairwiseDistance(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor input1, Tensor input2)\n {\n var res = THSNN_PairwiseDistance_forward(handle, input1.Handle, input2.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n public static PairwiseDistance PairwiseDistance(double p = 2.0, double eps = 1e-6, bool keep_dim = false)\n {\n var handle = THSNN_PairwiseDistance_ctor(p, eps, keep_dim, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new PairwiseDistance(handle, boxedHandle);\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Computes the pairwise distance between vectors using the p-norm.\n /// </summary>\n /// <param name=\"input1\">(N,D) or (D) where N = batch dimension and D = vector dimension</param>\n /// <param name=\"input2\">(N, D) or (D), same shape as the Input1</param>\n /// <param name=\"p\">The norm degree. Default: 2</param>\n /// <param name=\"eps\">Small value to avoid division by zero.</param>\n /// <param name=\"keep_dim\">Determines whether or not to keep the vector dimension.</param>\n /// <returns></returns>\n public static Tensor pairwise_distance(Tensor input1, Tensor input2, double p = 2.0, double eps = 1e-6, bool keep_dim = false)\n {\n using (var f = nn.PairwiseDistance(p, eps, keep_dim)) {\n return f.call(input1, input2);\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6527947783470154, "alphanum_fraction": 0.66431725025177, "avg_line_length": 50.632911682128906, "blob_id": "a0e605a034a0040ae475d0c2351586a8ba26b61e", "content_id": "f5ee6fe6e72a1a84e480c70db25fddb229c6d4e4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 16316, "license_type": "permissive", "max_line_length": 542, "num_lines": 316, "path": "/docfx/articles/modules.md", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "# Creating Your Own TorchSharp Modules\n\nUnfortunatly, the word 'Module' is one of the most overloaded terms in software. That said, the module concept is central to TorchSharp, which means we have to define its contextual meaning. \n\nIn the context of TorchSharp, it means the same as in PyTorch: the fundamental building block of all models is the 'Module' class. All neural network layers are derived from Module and the way to create a model for training and inference in your code is to create a new Module. Without it, back-propagation will not work.\n\n## Sequential\n\nFor the most basic network architecture, which actually covers a surprising breadth, there is a simple way to create modules -- the 'Sequential' class. This class is created from a list of Modules (i.e. model components). When data is passed to the model in the form of a tensor, the Sequential instance will invoke each submodule in the order they were passed when the Sequential instance was created, passing the output from each layer to the next. The output of the final submodule will be the output of the Sequential instance.\n\n```C#\nvar seq = Sequential((\"lin1\", Linear(100, 10)), (\"lin2\", Linear(10, 5)));\n...\nseq.forward(some_data);\n```\n\nThere is no real performance reason to use Sequential instead of rolling your own custom module, but there is much less code to write. That said, if using a custom module (up next) is your preference, for whatever reason, that's what you should do. It can be useful to create a custom module first, debug it, and then convert to using Sequential.\n\nSequential can only string together modules that take a single tensor and return a single tensor -- anything else needs to be a custom module.\n\n## Custom Modules\n\nA custom module is created by deriving a subclass from torch.nn.Module<T...,TResult>. The first generic parameters denote the input types of the module's forward() method:\n\n```C#\n private class TestModule1 : Module<Tensor,Tensor>\n {\n public TestModule1()\n : base(\"TestModule1\")\n {\n lin1 = Linear(100, 10);\n lin2 = Linear(10, 5);\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor input)\n {\n using (var x = lin1.forward(input))\n return lin2.forward(x);\n }\n\n private Module lin1;\n private Module lin2;\n }\n```\n\nNote that the field names in the module class correspond to the names that were passed in to the Sequential constructor in the earlier section.\n\nCustom modules should always call `RegisterComponents()` once all submodules and buffers (see discussion later in this document) have been created. This will register the modules and its parameters with the native runtime, which is essential for it to function correctly. For this to work properly, each submodule should have its own private field (**not** property) in the class. The only exception are submodules that do not have trainable weights, such as activation functions like ReLU or tanh.\n\nThe `forward()` method contains the computation of the module. It can contain a mix of TorchSharp primitives, layers, as well as any .NET code. Note, however, that only TorchSharp APIs are capable of operating on data residing in CUDA memory. Therefore, if performance is of the essence, expressing all computation in terms of TorchSharp APIs is essential. Non-TorchSharp APIs should be limited to things that aren't related to the tensor data, things like logging, for example.\n\nIn PyTorch, the `forward()` method takes an arbitrary number of arguments, of any type, and supports using default arguments. \n\nIn TorchSharp, the signature of `forward()` is determined by the type parameter signature of the Module<> base class. In most cases, the input and output are both `torch.Tensor`. As noted above, the Sequential module collection class assumes that it is passing only a single tensor along between its layers. Therefore, any model that needs to pass multiple arguments between layers will have to be custom.\n\nGoing back to the code inside the `forward()` method -- please note that the local variable 'x' was declared in a using statement. This is important in order to deallocate the native memory associated with it as soon as it is no longer needed. For that reason, it is important to pull out temporaries like this into local variables, especially when the code is running on a GPU. (More on this at: [Dispose vs. GC in TorchSharp](memory.md)) \n\nIn other words, the following code is less memory efficient, because it delays reclaiming native memory until the next time GC is run:\n\n```C#\n public override Tensor forward(Tensor input)\n {\n return lin2.forward(lin1.forward(input));\n }\n```\n\n## Using Sequential Inside A Custome Module\n\nCustom modules are often combined with Sequential, which is especially useful when building long chains of repetitive blocks inside a custom module. In the C# TorchSharp examples, VGG, MobileNet, and ResNet demonstrate this well. \n\nTo illustrate, this is the code for MobileNet from the TorchSharp examples:\n\n```C#\n class MobileNet : Module\n {\n private readonly long[] planes = new long[] { 64, 128, 128, 256, 256, 512, 512, 512, 512, 512, 512, 1024, 1024 };\n private readonly long[] strides = new long[] { 1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1 };\n\n private readonly Module layers;\n\n public MobileNet(string name, int numClasses, Device device = null) : base(name)\n {\n var modules = new List<(string, Module)>();\n\n modules.Add((\"conv2d-first\", \n Conv2d(3, 32, kernelSize: 3, stride: 1, padding: 1, bias: false)));\n modules.Add((\"bnrm2d-first\", \n BatchNorm2d(32)));\n modules.Add((\"relu-first\", \n ReLU()));\n MakeLayers(modules, 32);\n modules.Add((\"avgpool\", \n AvgPool2d(new long[] { 2, 2 })));\n modules.Add((\"flatten\", \n Flatten()));\n modules.Add((\"linear\", \n Linear(planes[^1], numClasses)));\n\n layers = Sequential(modules);\n\n RegisterComponents();\n }\n\n private void MakeLayers(List<(string, Module)> modules, long in_planes)\n {\n\n for (var i = 0; i < strides.Length; i++) {\n var out_planes = planes[i];\n var stride = strides[i];\n\n modules.Add(($\"conv2d-{i}a\", \n Conv2d(in_planes, in_planes, kernelSize: 3, stride: stride, padding: 1, groups: in_planes, bias: false)));\n modules.Add(($\"bnrm2d-{i}a\", \n BatchNorm2d(in_planes)));\n modules.Add(($\"relu-{i}a\", \n ReLU()));\n modules.Add(($\"conv2d-{i}b\", \n Conv2d(in_planes, out_planes, kernelSize: 1L, stride: 1L, padding: 0L, bias: false)));\n modules.Add(($\"bnrm2d-{i}b\", \n BatchNorm2d(out_planes)));\n modules.Add(($\"relu-{i}b\", \n ReLU()));\n\n in_planes = out_planes;\n }\n }\n\n public override Tensor forward(Tensor input)\n {\n return layers.forward(input);\n }\n }\n```\n\n## ModuleList\n\nIn some circumstances, it's useful to define a dynamic number of modules in a custom module. It could be because you want to parameterize the network architecture, or dynamically choose which layers to run, or just that its tedious to define so many fields. This may be addressed by using a ModuleList to contain the submodules. Unlike Sequential, ModuleList itself does not suffice -- its `forward()` method will throw an exception if invoked, and you must iterate through the modules of the list directly in your `forward()` implementation.\n\nThe purpose is simply to provide a list implementation that automatically registers the submodules when components are registered. You have to iterate through the list in the `forward()` method:\n\n```C#\n private class TestModule1 : Module<Tensor,Tensor>\n {\n public TestModule1()\n : base(\"TestModule1\")\n {\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor input)\n {\n for (int i = 0; i < submodules.Count; i++) { // Using 'for' instead of 'foreach' can be useful for debugging.\n input = submodules[i].forward(input); \n }\n }\n\n private ModuleList submodules = new ModuleList(Linear(100, 10), Linear(10, 5));\n }\n```\n\n## ModuleDict\n\nIn some circumstances, it's useful to define a dynamic number of modules in a custom module and use a dictionary to hold them. Like with `ModuleList`, it could be because you want to parameterize the network architecture, or dynamically choose which layers to run, or just that its tedious to define so many fields. This may be addressed by using a ModuleDict to contain the submodules.\n\nThe purpose is simply to provide a list implementation that automatically registers the submodules when components are registered. You have to iterate through the list in the `forward()` method:\n\n```C#\n private class TestModule1 : Module<Tensor,Tensor>\n {\n public TestModule1()\n : base(\"TestModule1\")\n {\n dict.Add(\"lin1\", Linear(100, 10));\n dict.Add(\"lin2\", Linear(10, 5));\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor input)\n {\n using (var x = submodules[\"lin1\"].forward(input))\n return submodules[\"lin2\"].forward(x);\n }\n\n private ModuleDict submodules = new ModuleDict();\n }\n```\n\nModuleDict is an ordered dictionary, so you can also iterate through the dictionary as if it were a list. If so, you will get a sequence of tuples with the submodule name and module in each iteration.\n\n## Parameter\n\nMany modules are just compositions of existing modules, but sometimes it will implement a novel algorithm. In this case, the `forward()` method will not just pass tensors from one module to another, but actually use TorchSharp operators and functions to perform arithmetic directly. If this requires training of parameters, those parameters should be declared directly in the module. The Parameter class is a wrapper around tensor; its only purpose is to make sure that it is registered with the native runtime.\n\nFor example, a re-implementation of 'Linear' would look something like:\n\n```C#\n private class MyLinear : Module<Tensor,Tensor>\n {\n public MyLinear(long input_size, long output_size)\n : base(\"MyLinear\")\n {\n weights = Parameter(torch.randn(input_size, output_size));\n bias = Parameter(torch.zeros(output_size));\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor input)\n {\n var mm = torch.matmul(input,weights);\n return mm.add_(bias);\n }\n\n private Parameter weights;\n private Parameter bias;\n }\n```\n\nIn this case, we're not relying on 'using' in the `forward()` method, because the \"temporary\" is reused as the target by the `add_()` function.\n\nParameter's dirty little secret is that it will clean out the tensor that is given to its constructor. So, `Parameter()` is preferrably used with another tensor factory (such as in the example above), or a cloned tensor. Once you have passes a tensor to the Parameter constructor, the original tensor is invalidated.\n\n## ParameterList\n\nMuch like ModuleList, ParameterList is a list of Parameter instances, which is automatically registered with the runtime if found as a field of a module instance.\n\n## ParameterDict\n\nMuch like ModuleDict, ParameterDict is a dictionary of Parameter instances, which is automatically registered with the runtime if found as a field of a module instance.\n\n## Buffers\n\nSometimes, a module needs to allocate tensor that are not trainable, i.e. their values are not modified during back-propagation. An example is a random dropout mask. These are referred to as 'buffers' as opposed to 'parameters' and are treated differently by `RegisterComponents()` -- even though they are not trainable, the native runtime still wants to know about them for other purposes, such as storing them to disk, so it is important to declare them in the module.\n\nEach buffer should be declared as a field of type 'Tensor' (not 'Parameter'). This will ensure that the buffer is registered properly when `RegisterComponents()` is called.\n\n\n## Modules, 'children()' and 'named_children()'\n\nIt is sometimes necessary to create a new model from an existing one and discard some of the final layers. The submodules will appear in the 'named_children' list in the same order that they are declared within the module itself, and when constructing a model based on the children, the layers may be reordered unless the submodules are declared in the same order that they are meant to be invoked.\n\nSo, for example:\n\n```C#\n private class TestModule1 : Module<Tensor,Tensor>\n {\n public TestModule1()\n : base(\"TestModule1\")\n {\n lin1 = Linear(100, 10);\n lin2 = Linear(10, 5);\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor input)\n {\n using (var x = lin1.forward(input))\n return lin2.forward(x);\n }\n\n // Correct -- the layers are declared in the same order they are invoked.\n private Module lin1;\n private Module lin2;\n }\n\n private class TestModule2 : Module<Tensor,Tensor>\n {\n public TestModule2()\n : base(\"TestModule2\")\n {\n lin1 = Linear(100, 10);\n lin2 = Linear(10, 5);\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor input)\n {\n using (var x = lin1.forward(input))\n return lin2.forward(x);\n }\n\n // Incorrect -- the layers are not declared in the same order they are invoked.\n private Module lin2;\n private Module lin1;\n }\n\n ...\n TestModule1 mod1 = ...\n TestModule2 mod2 = ...\n var seq1 = nn.Sequential(mod1.named_children());\n seq1.forward(t); // Does the same as mod1.forward(t)\n var seq2 = nn.Sequential(mod2.named_children());\n seq2.forward(t); // This probably blows up.\n```\n\n\n## Moving and Converting Modules\n\nThere are a few ways to move and/or convert the parameters and buffers in a module, whether custom or not. The actual methods that are used are declared as extension methods on 'Module,' but the implementation is found in three virtual methods declared as part of Module itself:\n\n```C#\nprotected virtual Module _to(ScalarType dtype)\nprotected virtual Module _to(DeviceType deviceType, int deviceIndex = -1)\nprotected virtual Module _to(Device device, ScalarType dtype)\n```\n\nThe most likely reason for overriding any or all of these is to \"hook\" calls to moves and conversions rather than implementing it differently. The Module base class already goes through all children modules, declared parameters and buffers, so it should generally not be necessary to implement these methods separately. In th \"hook\" scenario, it is advisable to end the body with a call to 'base._to(...)' like the TransformerModel in the SequenceToSequence example does:\n\n```C#\nprotected override Module _to(DeviceType deviceType, int deviceIndex = -1)\n{\n this.device = new Device(deviceType, deviceIndex);\n return base._to(deviceType, deviceIndex);\n}\n```\nIn this case, the model needs to know what device the parameters and buffers are, because it repeatedly generates a mask during training, and this mask must live on the same device as the model parameters.\n" }, { "alpha_fraction": 0.5411071181297302, "alphanum_fraction": 0.548352837562561, "avg_line_length": 58.48850631713867, "blob_id": "9cd3c2fae9978e47d1de2af7afa1ae7302e17649", "content_id": "d920eb7bce4f4322441f9ea03d2345ecae27f9af", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 10351, "license_type": "permissive", "max_line_length": 322, "num_lines": 174, "path": "/src/TorchSharp/NN/Pooling/AvgPool3D.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a AvgPool3D module.\n /// </summary>\n public sealed class AvgPool3d : torch.nn.Module<Tensor, Tensor>\n {\n internal AvgPool3d(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_AvgPool3d_forward(handle.DangerousGetHandle(), tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies a 3D average pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"kernel_size\">The size of the window</param>\n /// <param name=\"strides\">The stride of the window. Default value is kernel_size</param>\n /// <param name=\"padding\">implicit zero padding to be added on both sides</param>\n /// <param name=\"ceil_mode\">Whether to use ceil instead of floor to compute the output shape</param>\n /// <param name=\"count_include_pad\">Whether to include the zero-padding in the averaging calculation</param>\n /// <param name=\"divisor_override\">If specified, it will be used as divisor, otherwise size of the pooling region will be used</param>\n public static AvgPool3d AvgPool3d(long[] kernel_size, long[] strides = null, long[] padding = null, bool ceil_mode = false, bool count_include_pad = true, long? divisor_override = null)\n {\n unsafe {\n fixed (long* pkernelSize = kernel_size, pstrides = strides, ppadding = padding) {\n var handle = THSNN_AvgPool3d_ctor((IntPtr)pkernelSize, kernel_size.Length, (IntPtr)pstrides, (strides == null ? 0 : strides.Length), (IntPtr)ppadding, (padding == null ? 0 : padding.Length), ceil_mode, count_include_pad, divisor_override.HasValue ? divisor_override.Value : 0, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new AvgPool3d(handle, boxedHandle);\n }\n }\n }\n\n /// <summary>\n /// Applies a 3D average pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"kernel_size\">The size of the window</param>\n /// <param name=\"stride\">The stride of the window. Default value is kernel_size</param>\n /// <param name=\"padding\">implicit zero padding to be added on both sides</param>\n /// <param name=\"ceil_mode\">Whether to use ceil instead of floor to compute the output shape</param>\n /// <param name=\"count_include_pad\">Whether to include the zero-padding in the averaging calculation</param>\n /// <param name=\"divisor_override\">If specified, it will be used as divisor, otherwise size of the pooling region will be used</param>\n public static unsafe AvgPool3d AvgPool3d((long, long, long) kernel_size, (long, long, long)? stride = null, (long, long, long)? padding = null, bool ceil_mode = false, bool count_include_pad = true, long? divisor_override = null)\n {\n long svalue1 = (stride == null) ? kernel_size.Item1 : stride.Value.Item1;\n long svalue2 = (stride == null) ? kernel_size.Item2 : stride.Value.Item2;\n long svalue3 = (stride == null) ? kernel_size.Item3 : stride.Value.Item3;\n\n long pvalue1 = (padding == null) ? 0 : stride.Value.Item1;\n long pvalue2 = (padding == null) ? 0 : stride.Value.Item2;\n long pvalue3 = (padding == null) ? 0 : stride.Value.Item3;\n\n long* pkernelSize = stackalloc long[3] { kernel_size.Item1, kernel_size.Item2, kernel_size.Item3 };\n long* pstrides = stackalloc long[3] { svalue1, svalue2, svalue3 };\n long* ppadding = stackalloc long[3] { pvalue1, pvalue2, pvalue3 };\n\n var handle = THSNN_AvgPool3d_ctor((IntPtr)pkernelSize, 3, (IntPtr)pstrides, 3, (IntPtr)ppadding, 3, ceil_mode, count_include_pad, divisor_override.HasValue ? divisor_override.Value : 0, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new AvgPool3d(handle, boxedHandle);\n }\n\n /// <summary>\n /// Applies a 3D average pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"kernel_size\">The size of the window</param>\n /// <param name=\"stride\">The stride of the window. Default value is kernel_size</param>\n /// <param name=\"padding\">implicit zero padding to be added on both sides</param>\n /// <param name=\"ceil_mode\">Whether to use ceil instead of floor to compute the output shape</param>\n /// <param name=\"count_include_pad\">Whether to include the zero-padding in the averaging calculation</param>\n /// <param name=\"divisor_override\">If specified, it will be used as divisor, otherwise size of the pooling region will be used</param>\n public static unsafe AvgPool3d AvgPool3d(long kernel_size, long? stride = null, long? padding = null, bool ceil_mode = false, bool count_include_pad = true, long? divisor_override = null)\n {\n long svalue = (stride == null) ? kernel_size : stride.Value;\n long pvalue = (stride == null) ? 0 : padding.Value;\n\n long* pkernelSize = stackalloc long[3] { kernel_size, kernel_size, kernel_size };\n long* pstrides = stackalloc long[3] { svalue, svalue, svalue };\n long* ppadding = stackalloc long[3] { pvalue, pvalue, pvalue };\n\n var handle = THSNN_AvgPool3d_ctor((IntPtr)pkernelSize, 3, (IntPtr)pstrides, 3, (IntPtr)ppadding, 3, ceil_mode, count_include_pad, divisor_override.HasValue ? divisor_override.Value : 0, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new AvgPool3d(handle, boxedHandle);\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Applies 3D average-pooling operation in kT x kH x kW regions by step size sT x sH x sW steps.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"kernelSizes\"></param>\n /// <param name=\"strides\"></param>\n /// <param name=\"paddings\"></param>\n /// <param name=\"ceil_mode\"></param>\n /// <param name=\"count_include_pad\"></param>\n /// <returns></returns>\n public static Tensor avg_pool3d(Tensor input, long[] kernelSizes,\n long[] strides = null,\n long[] paddings = null,\n bool ceil_mode = false,\n bool count_include_pad = true)\n {\n strides = (strides == null) ? new long[] { 1 } : strides;\n paddings = (paddings == null) ? new long[] { 0 } : paddings;\n unsafe {\n fixed (long* pkernelSize = kernelSizes, pstrides = strides, ppadding = paddings) {\n var res =\n THSTensor_avg_pool3d(input.Handle,\n (IntPtr)pkernelSize, kernelSizes.Length,\n (IntPtr)pstrides, strides.Length,\n (IntPtr)ppadding, paddings.Length,\n ceil_mode,\n count_include_pad);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n public static Tensor avg_pool3d_backward(Tensor input, Tensor originalInput,\n long[] kernelSizes,\n long[] strides = null,\n long[] paddings = null,\n bool ceil_mode = false,\n bool count_include_pad = true,\n long divisorOverride = 0)\n {\n strides = (strides == null) ? new long[] { 1 } : strides;\n paddings = (paddings == null) ? new long[] { 0 } : paddings;\n unsafe {\n fixed (long* pkernelSize = kernelSizes, pstrides = strides, ppadding = paddings) {\n var res =\n THSTensor_avg_pool3d_backward(input.Handle, originalInput.Handle,\n (IntPtr)pkernelSize, kernelSizes.Length,\n (IntPtr)pstrides, strides.Length,\n (IntPtr)ppadding, paddings.Length,\n ceil_mode,\n count_include_pad,\n divisorOverride);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5389890670776367, "alphanum_fraction": 0.5425450801849365, "avg_line_length": 42.74444580078125, "blob_id": "1233e97601be87a90f079a1ffe1f4ea18dadb18c", "content_id": "1ce8c12a69dc2aa49a1bf1b2d31e27d3088495c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7874, "license_type": "permissive", "max_line_length": 149, "num_lines": 180, "path": "/src/TorchSharp/Distributions/Categorical.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n public class Categorical : torch.distributions.Distribution\n {\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public override Tensor mean => torch.full(ExtendedShape(), double.NaN, dtype: probs.dtype, device: probs.device);\n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public override Tensor variance => torch.full(ExtendedShape(), double.NaN, dtype: probs.dtype, device: probs.device);\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"probs\">Event probabilities</param>\n /// <param name=\"logits\">Even log-odds</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n public Categorical(Tensor probs = null, Tensor logits = null, torch.Generator generator = null) : base(generator)\n {\n var param = probs is null ? logits : probs;\n\n this._probs = (probs is not null) ? (probs / probs.sum(-1, keepdim: true)).DetachFromDisposeScope() : null;\n this._logits = (logits is not null) ? (logits - logits.logsumexp(-1, keepdim:true)).DetachFromDisposeScope() : null;\n this.num_events = param.size(-1);\n this.batch_shape = param.ndim > 1 ? param.shape.Take(param.shape.Length-1).ToArray() : new long[0];\n }\n\n /// <summary>\n /// Event probabilities\n /// </summary>\n public Tensor probs {\n get {\n return _probs ?? LogitsToProbs(_logits);\n }\n }\n\n /// <summary>\n /// Event log-odds\n /// </summary>\n public Tensor logits {\n get {\n return _logits ?? ProbsToLogits(_probs);\n }\n }\n\n /// <summary>\n /// The shape of the input parameter.\n /// </summary>\n public long[] param_shape {\n get {\n return _probs is null ? _logits.shape : _probs.shape;\n }\n }\n\n internal Tensor _probs;\n internal Tensor _logits;\n internal long num_events;\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n public override Tensor rsample(params long[] sample_shape)\n {\n var probs_2d = probs.reshape(-1, num_events);\n var samples_2d = torch.multinomial(probs_2d, sample_shape.Aggregate<long, long>(1, (x, y) => x * y), true, generator).T;\n return samples_2d.reshape(ExtendedShape(sample_shape));\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor log_prob(Tensor value)\n {\n value = value.@long().unsqueeze(-1);\n var valLogPmf = torch.broadcast_tensors(value, logits);\n value = valLogPmf[0][TensorIndex.Ellipsis, TensorIndex.Slice(null, 1)];\n return valLogPmf[1].gather(-1, value).squeeze(-1);\n }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n public override Tensor entropy()\n {\n var min_real = torch.finfo(logits.dtype).min;\n var logs = torch.clamp(logits, min: min_real);\n var p_log_p = logs * probs;\n return -p_log_p.sum(-1);\n }\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n /// <returns></returns>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is Categorical))\n throw new ArgumentException(\"expand(): 'instance' must be a Categorical distribution\");\n\n var param_shape = new List<long>();\n param_shape.AddRange(batch_shape);\n param_shape.Add(num_events);\n\n var shape = param_shape.ToArray();\n\n var p = _probs?.expand(shape);\n var l = _logits?.expand(shape);\n\n var newDistribution = ((instance == null) ? new Categorical(p, l, generator) : instance) as Categorical;\n\n newDistribution.batch_shape = batch_shape;\n if (newDistribution == instance) {\n newDistribution.num_events = this.num_events;\n newDistribution._probs = p;\n newDistribution._logits = l;\n }\n return newDistribution;\n }\n }\n\n }\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a Categorical distribution parameterized by `probs` or `logits` (but not both).\n ///\n /// Samples are integers from [0, K-1]` where `K` is probs.size(-1).\n /// \n /// If `probs` is 1-dimensional with length- `K`, each element is the relative probability\n /// of sampling the class at that index.\n /// \n /// If `probs` is N-dimensional, the first N-1 dimensions are treated as a batch of\n /// relative probability vectors.\n /// </summary>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Categorical Categorical(Tensor probs = null, Tensor logits = null, torch.Generator generator = null)\n {\n return new Categorical(probs, logits);\n }\n\n /// <summary>\n /// Creates an equal-probability categorical distribution parameterized by the number of categories.\n ///\n /// </summary>\n /// <param name=\"categories\">The number of categories.</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Categorical Categorical(int categories, torch.Generator generator = null)\n {\n var probs = torch.tensor(1.0 / categories).expand(categories);\n return new Categorical(probs, null, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.7330131530761719, "alphanum_fraction": 0.7362148761749268, "avg_line_length": 52.03773498535156, "blob_id": "9b2476113534bcdcb768c38e889196bd1d5652e1", "content_id": "c0d66ba2501804f7ee99e1f6fcb3ff88f1fd5ef3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5622, "license_type": "permissive", "max_line_length": 195, "num_lines": 106, "path": "/src/TorchSharp/PInvoke/LibTorchSharp.THSJIT.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp.PInvoke\n{\n#pragma warning disable CA2101\n internal static partial class NativeMethods\n {\n [DllImport(\"LibTorchSharp\", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]\n internal static extern void THSJIT_CompilationUnit_Invoke(IntPtr module, string name, IntPtr tensors, int length, AllocateIndexedPinnedArray allocator, out sbyte typeCode, int idx);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSJIT_CompilationUnit_dispose(IntPtr handle);\n\n [DllImport(\"LibTorchSharp\", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]\n internal static extern IntPtr THSJIT_compile(string script);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSJIT_Module_dispose(torch.nn.Module.HType handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSJIT_Module_named_parameters(torch.nn.Module.HType module, AllocatePinnedArray allocator1, AllocatePinnedArray allocator2);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSJIT_Module_named_buffers(torch.nn.Module.HType module, AllocatePinnedArray allocator1, AllocatePinnedArray allocator2);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSJIT_Module_named_modules(torch.nn.Module.HType module, AllocatePinnedArray allocator1, AllocatePinnedArray allocator2);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSJIT_Module_named_children(torch.nn.Module.HType module, AllocatePinnedArray allocator1, AllocatePinnedArray allocator2);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern long THSJIT_getNumModules(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern int THSJIT_Module_num_inputs(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern int THSJIT_Module_num_outputs(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSJIT_Module_train(torch.nn.Module.HType module, [MarshalAs(UnmanagedType.U1)] bool on);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSJIT_Module_eval(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n [return: MarshalAs(UnmanagedType.U1)]\n internal static extern bool THSJIT_Module_is_training(torch.nn.Module.HType module);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSJIT_Module_to_device(torch.nn.Module.HType module, long deviceType, long deviceIndex);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSJIT_Module_to_device_dtype(torch.nn.Module.HType module, sbyte dtype, long deviceType, long deviceIndex);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSJIT_Module_to_dtype(torch.nn.Module.HType module, sbyte dtype);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSJIT_Module_getInputType(torch.nn.Module.HType module, int index);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSJIT_getOutputType(torch.jit.Type.HType module, int index);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSJIT_Module_forward(torch.nn.Module.HType module, IntPtr tensors, int length, AllocateIndexedPinnedArray allocator, out sbyte typeCode, int idx);\n\n [DllImport(\"LibTorchSharp\", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]\n internal static extern void THSJIT_Module_invoke(torch.nn.Module.HType module, string name, IntPtr tensors, int length, AllocateIndexedPinnedArray allocator, out sbyte typeCode, int idx);\n\n [DllImport(\"LibTorchSharp\", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]\n internal static extern IntPtr THSJIT_load(string filename, long deviceType, long deviceIndex);\n\n [DllImport(\"LibTorchSharp\", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]\n internal static extern void THSJIT_save(torch.nn.Module.HType handle, string filename);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern long THSJIT_TensorType_sizes(torch.jit.Type.HType handle, AllocatePinnedArray allocator);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern int THSJIT_getDimensionedTensorTypeDimensions(torch.jit.Type.HType handle);\n\n [DllImport(\"LibTorchSharp\", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]\n internal static extern string THSJIT_getDimensionedTensorDevice(torch.jit.Type.HType handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern sbyte THSJIT_TensorType_dtype(torch.jit.Type.HType handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSJIT_Type_dispose(torch.jit.Type.HType handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSJIT_TensorType_dispose(torch.jit.Type.HType handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern sbyte THSJIT_Type_kind(torch.jit.Type.HType handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSJIT_Type_cast(torch.jit.Type.HType module);\n }\n#pragma warning restore CA2101\n}\n" }, { "alpha_fraction": 0.5343691110610962, "alphanum_fraction": 0.5343691110610962, "avg_line_length": 41.47999954223633, "blob_id": "cbf13b3685a0c3f831aa32a70641da9bec241dfd", "content_id": "b5aa0c65356564de366b7f8807fd6b0434a013be", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4248, "license_type": "permissive", "max_line_length": 142, "num_lines": 100, "path": "/src/TorchSharp/NN/Linear.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n public sealed class Linear : torch.nn.Module<Tensor, Tensor>\n {\n internal Linear(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public new static Linear Load(string modelPath)\n {\n var res = Module<Tensor, Tensor>.Load(modelPath);\n return new Linear(res.handle.DangerousGetHandle(), IntPtr.Zero);\n }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_Linear_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public Parameter? bias {\n get {\n var res = THSNN_Linear_bias(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return ((res == IntPtr.Zero) ? null : new Parameter(res));\n }\n set {\n THSNN_Linear_set_bias(handle, value?.Handle ?? IntPtr.Zero);\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"bias\", value);\n }\n }\n\n public Parameter? weight {\n get {\n var res = THSNN_Linear_weight(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n set {\n THSNN_Linear_set_weight(handle, value!.Handle);\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"weight\", value);\n }\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies a linear transformation to the incoming data.\n /// </summary>\n /// <param name=\"inputSize\">Size of each input sample</param>\n /// <param name=\"outputSize\">Size of each output sample</param>\n /// <param name=\"hasBias\">If set to false, the layer will not learn an additive bias.</param>\n /// <param name=\"device\">The desired device of the parameters and buffers in this module</param>\n /// <param name=\"dtype\">The desired floating point or complex dtype of the parameters and buffers in this module</param>\n public static Linear Linear(long inputSize, long outputSize, bool hasBias = true, Device? device = null, ScalarType? dtype = null)\n {\n var res = THSNN_Linear_ctor(inputSize, outputSize, hasBias, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n\n return new Linear(res, boxedHandle).MoveModule<Linear>(device, dtype);\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Applies a linear transformation to the incoming data.\n /// </summary>\n /// <param name=\"input\">Input tensor of shape (*,Hin)</param>\n /// <param name=\"weights\">Weights of shape (Hout,Hin) or (Hin)</param>\n /// <param name=\"bias\">Bias of shape (Hout) or ()</param>\n /// <returns>A tensor of shape (*,Hout) where '*' is the same as the subshape of the input.</returns>\n public static Tensor linear(Tensor input, Tensor weights, Tensor? bias = null)\n {\n IntPtr bPtr = bias?.Handle ?? IntPtr.Zero;\n var res = THSNN_functional_linear(input.Handle, weights.Handle, bPtr);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5198135375976562, "alphanum_fraction": 0.5225329995155334, "avg_line_length": 37.43283462524414, "blob_id": "05cebbf97c1b1309357e33a13ff07075d87f68bc", "content_id": "73b6ab1d7f6aad8634e678ec5e6b8145feddff75", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2574, "license_type": "permissive", "max_line_length": 125, "num_lines": 67, "path": "/src/TorchVision/File.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System.IO;\nusing System.Threading.Tasks;\n\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n partial class io\n {\n /// <summary>\n /// Reads a file into a <cref>Tensor</cref>.\n /// </summary>\n /// <param name=\"filename\">Path to the file.</param>\n /// <returns>\n /// One dimensional <cref>Tensor</cref> containing the bytes of the file.\n /// </returns>\n public static Tensor read_file(string filename)\n {\n return File.ReadAllBytes(filename);\n }\n\n /// <summary>\n /// Asynchronously reads a file into a <cref>Tensor</cref>.\n /// </summary>\n /// <param name=\"filename\">Path to the file.</param>\n /// <returns>\n /// A task that represents the asynchronous read operation.\n /// The value of the TResult parameter is a one dimensional <cref>Tensor</cref> containing the bytes of the file.\n /// </returns>\n public static async Task<Tensor> read_file_async(string filename)\n {\n byte[] data;\n\n using (FileStream stream = File.Open(filename, FileMode.Open)) {\n data = new byte[stream.Length];\n await stream.ReadAsync(data, 0, data.Length);\n }\n\n return data;\n }\n\n /// <summary>\n /// Writes a one dimensional <c>uint8</c> <cref>Tensor</cref> into a file.\n /// </summary>\n /// <param name=\"filename\">Path to the file.</param>\n /// <param name=\"data\">One dimensional <c>uint8</c> <cref>Tensor</cref>.</param>\n public static void write_file(string filename, Tensor data)\n {\n File.WriteAllBytes(filename, data.bytes.ToArray());\n }\n\n /// <summary>\n /// Asynchronously writes a one dimensional <c>uint8</c> <cref>Tensor</cref> into a file.\n /// </summary>\n /// <param name=\"filename\">Path to the file.</param>\n /// <param name=\"data\">One dimensional <c>uint8</c> <cref>Tensor</cref>.</param>\n public static async void write_file_async(string filename, Tensor data)\n {\n using (FileStream stream = File.Open(filename, FileMode.OpenOrCreate)) {\n await stream.WriteAsync(data.bytes.ToArray(), 0, (int)data.shape[0]);\n }\n }\n }\n }\n}" }, { "alpha_fraction": 0.5470979809761047, "alphanum_fraction": 0.554709792137146, "avg_line_length": 22.886363983154297, "blob_id": "1291b317d20afdd300825c6a6bc21fcd208c0ef6", "content_id": "5167c75981ff5ea409b2f107ee7be550ada57ce9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1051, "license_type": "permissive", "max_line_length": 130, "num_lines": 44, "path": "/src/TorchSharp/Utils/BigEndianReader.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.IO;\n\nnamespace TorchSharp.Utils\n{\n public class BigEndianReader\n {\n public BigEndianReader(BinaryReader baseReader)\n {\n mBaseReader = baseReader;\n }\n\n public int ReadInt32()\n {\n return BitConverter.ToInt32(ReadBigEndianBytes(4), 0);\n }\n\n public byte[] ReadBigEndianBytes(int count)\n {\n byte[] bytes = new byte[count];\n for (int i = count - 1; i >= 0; i--)\n bytes[i] = mBaseReader.ReadByte();\n\n return bytes;\n }\n\n public byte[] ReadBytes(int count)\n {\n return mBaseReader.ReadBytes(count);\n }\n\n public void Close()\n {\n mBaseReader.Close();\n }\n\n public Stream BaseStream {\n get { return mBaseReader.BaseStream; }\n }\n\n private BinaryReader mBaseReader;\n }\n}\n" }, { "alpha_fraction": 0.5101739168167114, "alphanum_fraction": 0.5280209183692932, "avg_line_length": 35.20164489746094, "blob_id": "fc47a1f549a0abf077c09ab9db5be28cc227455d", "content_id": "6069186fba0a9c79dba88e5910b53498af703b82", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8797, "license_type": "permissive", "max_line_length": 133, "num_lines": 243, "path": "/src/Examples/MNIST.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Diagnostics;\nusing static TorchSharp.torch;\n\nusing static TorchSharp.torch.nn;\nusing static TorchSharp.torch.utils.data;\n\nnamespace TorchSharp.Examples\n{\n /// <summary>\n /// Simple MNIST Convolutional model.\n /// </summary>\n /// <remarks>\n /// There are at least two interesting data sets to use with this example:\n ///\n /// 1. The classic MNIST set of 60000 images of handwritten digits.\n ///\n /// It is available at: http://yann.lecun.com/exdb/mnist/\n ///\n /// 2. The 'fashion-mnist' data set, which has the exact same file names and format as MNIST, but is a harder\n /// data set to train on. It's just as large as MNIST, and has the same 60/10 split of training and test\n /// data.\n /// It is available at: https://github.com/zalandoresearch/fashion-mnist/tree/master/data/fashion\n /// </remarks>\n public class MNIST\n {\n private static int _epochs = 1;\n private static int _trainBatchSize = 64;\n private static int _testBatchSize = 128;\n\n private readonly static int _logInterval = 100;\n\n internal static void Main(string[] args)\n {\n var dataset = args.Length > 0 ? args[0] : \"mnist\";\n var datasetPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n\n torch.random.manual_seed(1);\n\n var cwd = Environment.CurrentDirectory;\n\n var device = torch.cuda.is_available() ? torch.CUDA : torch.CPU;\n Console.WriteLine($\"Running MNIST on {device.type.ToString()}\");\n Console.WriteLine($\"Dataset: {dataset}\");\n\n if (device.type == DeviceType.CUDA) {\n _trainBatchSize *= 4;\n _testBatchSize *= 4;\n }\n\n using var model = new Model(\"model\", device);\n\n var normImage = torchvision.transforms.Normalize(new double[] { 0.1307 }, new double[] { 0.3081 });\n\n using (Dataset train_data = torchvision.datasets.MNIST(datasetPath, true, download: true, target_transform: normImage),\n test_data = torchvision.datasets.MNIST(datasetPath, false, download: true, target_transform: normImage)) {\n\n TrainingLoop(\"mnist\", device, model, train_data, test_data);\n }\n }\n\n internal static void TrainingLoop(string dataset, Device device, Model model, Dataset train_data, Dataset test_data)\n {\n using var train = new DataLoader(train_data, _trainBatchSize, device: device, shuffle: true);\n using var test = new DataLoader(test_data, _testBatchSize, device: device, shuffle: false);\n\n if (device.type == DeviceType.CUDA) {\n _epochs *= 4;\n }\n\n var optimizer = torch.optim.Adam(model.parameters());\n\n var scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1, 0.75);\n\n Stopwatch sw = new Stopwatch();\n sw.Start();\n\n for (var epoch = 1; epoch <= _epochs; epoch++) {\n\n using (var d = torch.NewDisposeScope()) {\n\n Train(model, optimizer, torch.nn.NLLLoss(reduction: Reduction.Mean), train, epoch, train_data.Count);\n Test(model, torch.nn.NLLLoss(reduction: torch.nn.Reduction.Sum), test, test_data.Count);\n\n Console.WriteLine($\"End-of-epoch memory use: {GC.GetTotalMemory(false)}\");\n scheduler.step();\n }\n }\n\n sw.Stop();\n Console.WriteLine($\"Elapsed time: {sw.Elapsed.TotalSeconds:F1} s.\");\n\n Console.WriteLine(\"Saving model to '{0}'\", dataset + \".model.bin\");\n model.save(dataset + \".model.bin\");\n }\n\n internal class Model : Module<Tensor, Tensor>\n {\n private Module<Tensor, Tensor> conv1 = Conv2d(1, 32, 3);\n private Module<Tensor, Tensor> conv2 = Conv2d(32, 64, 3);\n private Module<Tensor, Tensor> fc1 = Linear(9216, 128);\n private Module<Tensor, Tensor> fc2 = Linear(128, 10);\n\n // These don't have any parameters, so the only reason to instantiate\n // them is performance, since they will be used over and over.\n private Module<Tensor, Tensor> pool1 = MaxPool2d(kernelSize: new long[] { 2, 2 });\n\n private Module<Tensor, Tensor> relu1 = ReLU();\n private Module<Tensor, Tensor> relu2 = ReLU();\n private Module<Tensor, Tensor> relu3 = ReLU();\n\n private Module<Tensor, Tensor> dropout1 = Dropout(0.25);\n private Module<Tensor, Tensor> dropout2 = Dropout(0.5);\n\n private Module<Tensor, Tensor> flatten = Flatten();\n private Module<Tensor, Tensor> logsm = LogSoftmax(1);\n\n public Model(string name, torch.Device device = null) : base(name)\n {\n RegisterComponents();\n\n if (device != null && device.type == DeviceType.CUDA)\n this.to(device);\n }\n\n public override Tensor forward(Tensor input)\n {\n // All these modules are private to the model and won't have hooks,\n // so we can use 'forward' instead of 'call'\n var l11 = conv1.forward(input);\n var l12 = relu1.forward(l11);\n\n var l21 = conv2.forward(l12);\n var l22 = relu2.forward(l21);\n var l23 = pool1.forward(l22);\n var l24 = dropout1.forward(l23);\n\n var x = flatten.forward(l24);\n\n var l31 = fc1.forward(x);\n var l32 = relu3.forward(l31);\n var l33 = dropout2.forward(l32);\n\n var l41 = fc2.forward(l33);\n\n return logsm.forward(l41);\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n conv1.Dispose();\n conv2.Dispose();\n fc1.Dispose();\n fc2.Dispose();\n pool1.Dispose();\n relu1.Dispose();\n relu2.Dispose();\n relu3.Dispose();\n dropout1.Dispose();\n dropout2.Dispose();\n flatten.Dispose();\n logsm.Dispose();\n ClearModules();\n }\n base.Dispose(disposing);\n }\n }\n\n\n private static void Train(\n Model model,\n torch.optim.Optimizer optimizer,\n Loss<torch.Tensor, torch.Tensor, torch.Tensor> loss,\n DataLoader dataLoader,\n int epoch,\n long size)\n {\n model.train();\n\n int batchId = 1;\n long total = 0;\n\n Console.WriteLine($\"Epoch: {epoch}...\");\n\n using (var d = torch.NewDisposeScope()) {\n\n foreach (var data in dataLoader) {\n optimizer.zero_grad();\n\n var target = data[\"label\"];\n var prediction = model.call(data[\"data\"]);\n var output = loss.call(prediction, target);\n\n output.backward();\n\n optimizer.step();\n\n total += target.shape[0];\n\n if (batchId % _logInterval == 0 || total == size) {\n Console.WriteLine($\"\\rTrain: epoch {epoch} [{total} / {size}] Loss: {output.ToSingle():F4}\");\n }\n\n batchId++;\n\n d.DisposeEverything();\n }\n }\n }\n\n private static void Test(\n Model model,\n Loss<torch.Tensor, torch.Tensor, torch.Tensor> loss,\n DataLoader dataLoader,\n long size)\n {\n model.eval();\n\n double testLoss = 0;\n int correct = 0;\n\n using (var d = torch.NewDisposeScope()) {\n\n foreach (var data in dataLoader) {\n var prediction = model.call(data[\"data\"]);\n var output = loss.call(prediction, data[\"label\"]);\n testLoss += output.ToSingle();\n\n var pred = prediction.argmax(1);\n correct += pred.eq(data[\"label\"]).sum().ToInt32();\n\n d.DisposeEverything();\n }\n }\n\n Console.WriteLine($\"Size: {size}, Total: {size}\");\n\n Console.WriteLine($\"\\rTest set: Average loss {(testLoss / size):F4} | Accuracy {((double)correct / size):P2}\");\n }\n }\n}\n" }, { "alpha_fraction": 0.5167227983474731, "alphanum_fraction": 0.5228196382522583, "avg_line_length": 45.672088623046875, "blob_id": "3ca9ff687754f9a72e57785caafefbe648ab7028", "content_id": "fa12f67122d842dcaabdd3d69cb85b1fab63bc5e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 17222, "license_type": "permissive", "max_line_length": 229, "num_lines": 369, "path": "/src/TorchSharp/Optimizers/Rprop.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n public static partial class torch\n {\n public static partial class optim\n {\n\n /// <summary>\n /// Implements the the resilient backpropagation algorithm.\n ///\n /// A Direct Adaptive Method for Faster Backpropagation Learning: The RPROP Algorithm\n /// http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.21.1417\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"lr \">Learning rate</param>\n /// <param name=\"etaminus\">Multiplicative increase factor.</param>\n /// <param name=\"etaplus\">Multiplicative decrease factor.</param>\n /// <param name=\"min_step\">Minimum allowed step size.</param>\n /// <param name=\"max_step\">Maximum allowed step size.</param>\n /// <param name=\"maximize\">Maximize the params based on the objective, instead of minimizing.</param>\n public static Rprop Rprop(IEnumerable<Parameter> parameters, double lr = 1e-2, double etaminus = 0.5, double etaplus = 1.2, double min_step = 1e-6, double max_step = 50, bool maximize = false)\n {\n return new Rprop(parameters, lr, etaminus, etaplus, min_step, max_step, maximize);\n }\n\n /// <summary>\n /// Implements the the resilient backpropagation algorithm.\n ///\n /// A Direct Adaptive Method for Faster Backpropagation Learning: The RPROP Algorithm\n /// http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.21.1417\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"lr \">Learning rate</param>\n /// <param name=\"etaminus\">Multiplicative increase factor.</param>\n /// <param name=\"etaplus\">Multiplicative decrease factor.</param>\n /// <param name=\"min_step\">Minimum allowed step size.</param>\n /// <param name=\"max_step\">Maximum allowed step size.</param>\n /// <param name=\"maximize\">Maximize the params based on the objective, instead of minimizing.</param>\n public static Rprop Rprop(IEnumerable<(string name, Parameter parameter)> parameters, double lr = 1e-2, double etaminus = 0.5, double etaplus = 1.2, double min_step = 1e-6, double max_step = 50, bool maximize = false)\n {\n return new Rprop(parameters.Select(np => np.parameter), lr, etaminus, etaplus, min_step, max_step, maximize);\n }\n\n /// <summary>\n /// Implements the the resilient backpropagation algorithm.\n ///\n /// A Direct Adaptive Method for Faster Backpropagation Learning: The RPROP Algorithm\n /// http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.21.1417\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"lr \">Learning rate</param>\n /// <param name=\"etaminus\">Multiplicative increase factor.</param>\n /// <param name=\"etaplus\">Multiplicative decrease factor.</param>\n /// <param name=\"min_step\">Minimum allowed step size.</param>\n /// <param name=\"max_step\">Maximum allowed step size.</param>\n /// <param name=\"maximize\">Maximize the params based on the objective, instead of minimizing.</param>\n public static Rprop Rprop(IEnumerable<Rprop.ParamGroup> parameters, double lr = 1e-2, double etaminus = 0.5, double etaplus = 1.2, double min_step = 1e-6, double max_step = 50, bool maximize = false)\n {\n return new Rprop(parameters, lr, etaminus, etaplus, min_step, max_step, maximize);\n }\n }\n }\n\n namespace Modules\n {\n public class Rprop : OptimizerHelper\n {\n /// <summary>\n /// Implements Rprop algorithm (a variant of Adam based on infinity norm).\n ///\n /// It has been proposed in Adam: A Method for Stochastic Optimization.\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize.</param>\n /// <param name=\"lr \">Learning rate</param>\n /// <param name=\"etaminus\">Multiplicative increase factor.</param>\n /// <param name=\"etaplus\">Multiplicative decrease factor.</param>\n /// <param name=\"min_step\">Minimum allowed step size.</param>\n /// <param name=\"max_step\">Maximum allowed step size.</param>\n /// <param name=\"maximize\">Maximize the params based on the objective, instead of minimizing.</param>\n public Rprop(IEnumerable<Parameter> parameters, double lr = 0.01, double etaminus = 0.5, double etaplus = 1.2, double min_step = 1e-6, double max_step = 50, bool maximize = false)\n : this(new ParamGroup[] { new() { Parameters = parameters } }, lr, etaminus, etaplus, min_step, max_step, maximize)\n {\n }\n\n /// <summary>\n /// Implements Rprop algorithm (a variant of Adam based on infinity norm).\n ///\n /// It has been proposed in Adam: A Method for Stochastic Optimization.\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize.</param>\n /// <param name=\"lr \">Learning rate</param>\n /// <param name=\"etaminus\">Multiplicative increase factor.</param>\n /// <param name=\"etaplus\">Multiplicative decrease factor.</param>\n /// <param name=\"min_step\">Minimum allowed step size.</param>\n /// <param name=\"max_step\">Maximum allowed step size.</param>\n /// <param name=\"maximize\">Maximize the params based on the objective, instead of minimizing.</param>\n public Rprop(IEnumerable<ParamGroup> parameters, double lr = 1e-2, double etaminus = 0.5, double etaplus = 1.2, double min_step = 1e-6, double max_step = 50, bool maximize = false)\n {\n if (lr < 0.0) throw new ArgumentException($\"Invalid learning rate: {lr}\");\n\n var options = new Options {\n LearningRate = lr,\n InitialLearningRate = lr,\n maximize = maximize,\n etaminus = etaminus,\n etaplus = etaplus,\n min_step = min_step,\n max_step = max_step\n };\n\n _defaults = options;\n _parameter_groups = new List<Modules.ParamGroup>();\n\n foreach (var g in parameters) {\n add_param_group(g);\n }\n }\n\n /// <summary>\n /// Performs a single optimization step (parameter update).\n /// </summary>\n /// <param name=\"closure\">A closure that reevaluates the model and returns the loss. Optional for most optimizers.</param>\n /// <returns></returns>\n public override Tensor step(Func<Tensor> closure = null)\n {\n return _step<ParamGroup>(group => {\n\n var options = group.Options as Options;\n var maximize = options.maximize.Value;\n var etaminus = options.etaminus.Value;\n var etaplus = options.etaplus.Value;\n var min_step = options.min_step.Value;\n var max_step = options.max_step.Value;\n var lr = options.LearningRate.Value;\n\n foreach (var param in group.Parameters) {\n\n var grad = param.grad();\n\n if (grad is null) continue;\n\n if (grad.is_sparse) throw new ArgumentException(\"Rprop does not support sparse gradients\");\n\n if (maximize) grad = -grad;\n\n var state = (State)_state[param.handle];\n\n state.step += 1;\n\n grad = (max_step != 0)\n ? grad.add(param, alpha: max_step)\n : grad.alias();\n\n var sign = grad.mul(state.prev).sign();\n sign[sign.gt(0)] = (Tensor)etaplus;\n sign[sign.lt(0)] = (Tensor)etaminus;\n sign[sign.eq(0)] = (Tensor)1;\n\n state.step_size.mul_(sign).clamp_(min_step, max_step);\n\n grad = grad.clone();\n\n grad.index_put_(0, sign.eq(etaminus));\n\n param.addcmul_(grad.sign(), state.step_size, -1);\n\n state.prev.copy_(grad);\n }\n\n }, closure);\n }\n\n protected override void Dispose(bool disposing)\n {\n base.Dispose(disposing);\n foreach (var kvp in _state) {\n ((State)kvp.Item2).Dispose();\n }\n }\n /// <summary>\n /// Add a param group to the Optimizer s param_groups.\n /// </summary>\n /// <param name=\"param_group\"></param>\n /// <remarks>This can be useful when fine tuning a pre-trained network as frozen layers can be made trainable and added to the Optimizer as training progresses.</remarks>\n public override void add_param_group(Modules.ParamGroup param_group)\n {\n var def = _defaults as Options;\n if (param_group.Options is null) {\n param_group.Options = new Options();\n }\n\n var opt = param_group.Options as Options;\n\n // Make sure all the options are set.\n if (!opt.maximize.HasValue) opt.maximize = def.maximize;\n if (!opt.LearningRate.HasValue) opt.LearningRate = def.LearningRate;\n if (!opt.etaminus.HasValue) opt.etaminus = def.etaminus;\n if (!opt.etaplus.HasValue) opt.etaplus = def.etaplus;\n if (!opt.min_step.HasValue) opt.min_step = def.min_step;\n if (!opt.max_step.HasValue) opt.max_step = def.max_step;\n\n opt.InitialLearningRate = opt.LearningRate.Value;\n\n _parameter_groups.Add(param_group);\n\n foreach (var p in param_group.Parameters) {\n var state = new State();\n _state[p.Handle] = state;\n state.step = 0;\n state.prev = torch.zeros_like(p).DetachFromDisposeScope();\n state.step_size = p.new_empty(p.shape).fill_(opt.LearningRate).DetachFromDisposeScope();\n }\n }\n\n public sealed class State : OptimizerState, IDisposable\n {\n public long step;\n public Tensor prev;\n public Tensor step_size;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n private void Dispose(bool disposing)\n {\n if (disposing) {\n prev.Dispose();\n step_size.Dispose();\n }\n }\n\n /// <summary>\n /// Move all the state to the indicated device.\n /// </summary>\n /// <param name=\"device\">The device to move all state to.</param>\n public override void to(Device device)\n {\n prev = prev.to(device);\n step_size = step_size.to(device);\n }\n\n /// <summary>\n /// Load the optimizer parameter state from a stream.\n /// </summary>\n /// <param name=\"reader\">A binary reader connected to a stream open for reading.</param>\n public override void LoadStateDict(BinaryReader reader)\n {\n step = reader.ReadInt64();\n prev.Load(reader);\n step_size.Load(reader);\n }\n\n /// <summary>\n /// Save the optimizer parameter state to a stream.\n /// </summary>\n /// <param name=\"writer\">A binary writer connected to a stream open for writing.</param>\n public override void SaveStateDict(BinaryWriter writer)\n {\n writer.Write(this.step);\n prev.Save(writer);\n step_size.Save(writer);\n }\n\n /// <summary>\n /// Load optimizer parameter state from another optimizer.\n /// </summary>\n /// <param name=\"source\">An optimizer state record.</param>\n public override void LoadStateDict(OptimizerState source)\n {\n var st_state = source as State;\n prev.Dispose();\n step_size.Dispose();\n step = st_state.step;\n prev = st_state.prev;\n step_size = st_state.step_size;\n }\n\n /// <summary>\n /// Useful for tests, allows comparison of one state with another.\n /// </summary>\n /// <param name=\"other\">The other optimizer state</param>\n /// <returns></returns>\n public override bool ApproximatelyEquals(OptimizerState other)\n {\n var rhs = other as State;\n return (rhs is not null) && step == rhs.step && prev.allclose(rhs.prev) && step_size.allclose(rhs.step_size);\n }\n }\n\n\n public class Options : OptimizerOptions\n {\n public bool? maximize;\n public double? etaminus;\n public double? etaplus;\n public double? min_step;\n public double? max_step;\n\n /// <summary>\n /// Save the optimizer options (param-group hyperparameters) to a stream.\n /// </summary>\n /// <param name=\"writer\">A binary writer connected to a stream open for writing.</param>\n public override void SaveStateDict(BinaryWriter writer)\n {\n base.SaveStateDict(writer);\n writer.Write(maximize.Value);\n writer.Write(etaminus.Value);\n writer.Write(etaplus.Value);\n writer.Write(min_step.Value);\n writer.Write(max_step.Value);\n }\n\n /// <summary>\n /// Load the optimizer options (param-group hyperparameters) from a stream.\n /// </summary>\n /// <param name=\"reader\">A binary reader connected to a stream open for reading.</param>\n public override void LoadStateDict(BinaryReader reader)\n {\n base.LoadStateDict(reader);\n maximize = reader.ReadBoolean();\n etaminus = reader.ReadDouble();\n etaplus = reader.ReadDouble();\n min_step = reader.ReadDouble();\n max_step = reader.ReadDouble();\n }\n\n /// <summary>\n /// Load optimizer options (param-group hyperparameters) from another optimizer.\n /// </summary>\n /// <param name=\"source\">An optimizer options record.</param>\n public override void LoadStateDict(OptimizerOptions source)\n {\n base.LoadStateDict(source);\n var opts = source as Options;\n maximize = opts.maximize;\n etaminus = opts.etaminus;\n etaplus = opts.etaplus;\n min_step = opts.min_step;\n max_step = opts.max_step;\n }\n }\n\n public class ParamGroup : ParamGroup<Options>\n {\n public ParamGroup() { }\n\n public ParamGroup(IEnumerable<Parameter> parameters, Options options) : base(parameters, options) { }\n\n public ParamGroup(IEnumerable<Parameter> parameters, double lr = 1e-2, double etaminus = 0.5, double etaplus = 1.2, double min_step = 1e-6, double max_step = 50, bool maximize = false)\n : base(parameters, new Rprop.Options { LearningRate = lr, etaminus = etaminus, etaplus = etaplus, min_step = min_step, max_step = max_step, maximize = maximize })\n {\n }\n }\n\n }\n }\n}\n" }, { "alpha_fraction": 0.6332852840423584, "alphanum_fraction": 0.6390489935874939, "avg_line_length": 42.375, "blob_id": "cc01938f7ee6956e519cd65f24eea856cc481513", "content_id": "b84e5428cfbfb1149564e57a989e885cbebc4912", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1388, "license_type": "permissive", "max_line_length": 130, "num_lines": 32, "path": "/src/TorchSharp/Data/Loader.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp.Data\n{\n public class Loader\n {\n /// <summary>\n /// Create an iterator scanning the MNIST dataset.\n /// </summary>\n /// <param name=\"filename\">The position of the MNIST dataset</param>\n /// <param name=\"batchSize\">The required batch size</param>\n /// <param name=\"isTrain\">Wheter the iterator is for training or testing</param>\n /// <returns></returns>\n public static DataIterator MNIST(string filename, long batchSize, bool isTrain = true)\n {\n return new DataIterator(THSData_loaderMNIST(filename, batchSize, isTrain));\n }\n\n /// <summary>\n /// Create an iterator scanning the CIFAR10 dataset.\n /// </summary>\n /// <param name=\"path\">The position of the CIFAR10 dataset</param>\n /// <param name=\"batchSize\">The required batch size</param>\n /// <param name=\"isTrain\">Wheter the iterator is for training or testing</param>\n /// <returns></returns>\n public static DataIterator CIFAR10(string path, long batchSize, bool isTrain = true)\n {\n return new DataIterator(THSData_loaderCIFAR10(path, batchSize, isTrain));\n }\n }\n}\n" }, { "alpha_fraction": 0.5405641794204712, "alphanum_fraction": 0.5449376702308655, "avg_line_length": 43.40776824951172, "blob_id": "ca4125d90d0369aa18f6375d835108dbd2049394", "content_id": "316f81ea0d8f3caf3cd191ca6e2d50bf9783ba39", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4573, "license_type": "permissive", "max_line_length": 166, "num_lines": 103, "path": "/src/TorchSharp/NN/Bilinear.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n public sealed class Bilinear : Module<Tensor, Tensor, Tensor>\n {\n internal Bilinear(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n public new static Bilinear Load(string modelPath)\n {\n var res = Module<Tensor, Tensor>.Load(modelPath);\n return new Bilinear(res.handle.DangerousGetHandle(), IntPtr.Zero);\n }\n\n public override Tensor forward(Tensor input1, Tensor input2)\n {\n var res = THSNN_Bilinear_forward(handle, input1.Handle, input2.Handle);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n public Parameter? bias {\n get {\n var res = THSNN_Bilinear_bias(handle);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return ((res == IntPtr.Zero) ? null : new Parameter(res));\n }\n set {\n THSNN_Bilinear_set_bias(handle, value?.Handle ?? IntPtr.Zero);\n CheckForErrors();\n ConditionallyRegisterParameter(\"bias\", value);\n }\n }\n\n public Parameter? weight {\n get {\n var res = THSNN_Bilinear_weight(handle);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n set {\n THSNN_Bilinear_set_weight(handle, value?.Handle ?? IntPtr.Zero);\n CheckForErrors();\n ConditionallyRegisterParameter(\"weight\", value);\n }\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n\n /// <summary>\n /// Applies a bilinear transformation to the incoming data\n /// </summary>\n /// <param name=\"in1Features\">size of each first input sample</param>\n /// <param name=\"in2Features\">size of each second input sample</param>\n /// <param name=\"outputSize\">size of each output sample</param>\n /// <param name=\"hasBias\">If set to false, the layer will not learn an additive bias</param>\n /// <param name=\"device\">The desired device of the parameters and buffers in this module</param>\n /// <param name=\"dtype\">The desired floating point or complex dtype of the parameters and buffers in this module</param>\n /// <returns></returns>\n public static Bilinear Bilinear(long in1Features, long in2Features, long outputSize, bool hasBias = true, Device? device = null, ScalarType? dtype = null)\n {\n var res = THSNN_Bilinear_ctor(in1Features, in2Features, outputSize, hasBias, out var boxedHandle);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n\n return new Bilinear(res, boxedHandle).MoveModule<Bilinear>(device, dtype);\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Applies a bilinear transformation to the incoming data\n /// </summary>\n /// <param name=\"input1\">Input tensor of shape (N,*,H1)</param>\n /// <param name=\"input2\">Input tensor of shape (N,*,H2)</param>\n /// <param name=\"weight\">Weights of shape (Hout,H1, H2)</param>\n /// <param name=\"bias\">Optional bias of shape (Hout)</param>\n /// <returns>Tensor of shape (N,*,Hout)</returns>\n /// <remarks>The '*' sub-shape must be the same among the two inputs.</remarks>\n public static Tensor bilinear(Tensor input1, Tensor input2, Tensor weight, Tensor? bias = null)\n {\n IntPtr bPtr = bias?.Handle ?? IntPtr.Zero;\n var res = THSNN_functional_bilinear(input1.Handle, input2.Handle, weight.Handle, bPtr);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n}" }, { "alpha_fraction": 0.5852211713790894, "alphanum_fraction": 0.5852211713790894, "avg_line_length": 35.35293960571289, "blob_id": "9c68a4dd5c41496646d7643fb14f5c587fa6db5d", "content_id": "81e9051d8a44d3aa96d8fdcb9e5464414611700a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1858, "license_type": "permissive", "max_line_length": 130, "num_lines": 51, "path": "/src/TorchSharp/NN/Parameter.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// A kind of Tensor that is to be considered a module parameter.\n ///\n /// Parameters are Tensor subclasses, that have a very special property when used with Modules -\n /// when they’re assigned as Module attributes they are automatically added to the list of its parameters,\n /// and will appear e.g. in parameters() iterator.Assigning a Tensor doesn’t have such effect.This is because\n /// one might want to cache some temporary state, like last hidden state of the RNN, in the model.\n /// If there was no such class as Parameter, these temporaries would get registered too.\n /// </summary>\n public class Parameter : Tensor\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"data\">A tensor, which will become empty.</param>\n /// <param name=\"requires_grad\"></param>\n public Parameter(Tensor data, bool requires_grad = true) :\n base(data.with_requires_grad(requires_grad).MoveHandle())\n {\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"handle\">A tensor handle.</param>\n internal Parameter(System.IntPtr handle) : base(handle)\n {\n }\n\n };\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n public static Parameter Parameter(Tensor data, bool requires_grad = true) =>\n new Parameter(data, requires_grad);\n\n }\n }\n}\n" }, { "alpha_fraction": 0.6014527678489685, "alphanum_fraction": 0.6024212837219238, "avg_line_length": 35.24561309814453, "blob_id": "99567f0fa980537144825738fc31265fd504c8b7", "content_id": "668fbdb002553e76864ecd6860f42a3f16cb0377", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2065, "license_type": "permissive", "max_line_length": 130, "num_lines": 57, "path": "/src/TorchSharp/Tensor/torch.Parallelism.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Diagnostics.Contracts;\n\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n // https://pytorch.org/docs/stable/torch#parallelism\n public static partial class torch\n {\n // https://pytorch.org/docs/stable/generated/torch.get_num_threads\n /// <summary>\n /// Returns the number of threads used for parallelizing CPU operations\n /// </summary>\n public static int get_num_threads()\n {\n var res = THSTorch_get_num_threads();\n if (res == -1) CheckForErrors();\n return res;\n }\n\n // https://pytorch.org/docs/stable/generated/torch.set_num_threads\n /// <summary>\n /// Sets the number of threads used for parallelizing CPU operations\n /// </summary>\n /// <param name=\"num\">The number of threads to use.</param>\n public static void set_num_threads(int num)\n {\n THSTorch_set_num_threads(num);\n CheckForErrors();\n }\n\n // https://pytorch.org/docs/stable/generated/torch.get_num_interop_threads\n /// <summary>\n /// Returns the number of threads used for inter-op parallelism on CPU (e.g. in JIT interpreter)\n /// </summary>\n public static int get_num_interop_threads()\n {\n var res = THSTorch_get_num_interop_threads();\n if (res == -1) CheckForErrors();\n return res;\n }\n\n // https://pytorch.org/docs/stable/generated/torch.set_num_interop_threads\n /// <summary>\n /// Sets the number of threads used for inter-op parallelism on CPU (e.g. in JIT interpreter)\n /// </summary>\n /// <param name=\"num\">The number of threads to use.</param>\n public static void set_num_interop_threads(int num)\n {\n THSTorch_set_num_interop_threads(num);\n CheckForErrors();\n }\n }\n}" }, { "alpha_fraction": 0.5210997462272644, "alphanum_fraction": 0.5223785042762756, "avg_line_length": 30.280000686645508, "blob_id": "a85bb779728d53a1490270762f68b3453e502036", "content_id": "743e4c55c4553897b0d42e694da61adf8e4cbc04", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3128, "license_type": "permissive", "max_line_length": 185, "num_lines": 100, "path": "/src/Examples.Utils/Vocab.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing TorchSharp;\n\nusing static TorchSharp.torch.nn;\n\nnamespace TorchText.Vocab\n{\n /// <summary>\n /// This needs a permanent place.\n /// The functionality is based on the Python 'Counter' class.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n public class Counter<T> : IEnumerable<KeyValuePair<T, int>>\n {\n private Dictionary<T, int> _dict = new Dictionary<T, int>();\n\n public void update(T key)\n {\n if (_dict.TryGetValue(key, out int count)) {\n _dict[key] = count + 1;\n } else {\n _dict[key] = 1;\n }\n }\n public void update(IEnumerable<T> keys)\n {\n foreach (T key in keys) {\n update(key);\n }\n }\n public int this[T key] { get => _dict[key]; }\n\n public IEnumerator<KeyValuePair<T, int>> GetEnumerator()\n {\n return _dict.GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n }\n\n /// <summary>\n /// This belongs in its own package, 'TorchText'.\n /// For now, it's useful to keep it with the examples that use it.\n /// </summary>\n public class Vocab\n {\n public Vocab(Counter<string> counter, int? maxSize = null, int minFreq = 1, string[] specials = null, Func<torch.Tensor, torch.Tensor> unkInit = null, bool specialsFirst = true)\n {\n if (specials == null) specials = new string[] { \"<unk>\", \"<pad>\" };\n if (unkInit == null) unkInit = (t => init.zeros_(t.clone()));\n if (specialsFirst) {\n foreach (var sp in specials) {\n _dict.Add(sp, _last++);\n }\n }\n foreach (var kv in counter.Where(kv => kv.Value >= minFreq)) {\n if (!specials.Contains(kv.Key)) {\n _dict.Add(kv.Key, _last++);\n }\n if (_last > (maxSize ?? int.MaxValue))\n break;\n }\n if (!specialsFirst) {\n foreach (var sp in specials) {\n _dict.Add(sp, _last++);\n }\n }\n }\n\n public int this[string key] { get => _dict.TryGetValue(key, out int value) ? value : _dict[\"<unk>\"]; }\n\n public int Count => _dict.Count;\n\n public void Add(string key, int value)\n {\n _dict.Add(key, value);\n }\n\n public void Add(KeyValuePair<string, int> item)\n {\n Add(item.Key, item.Value);\n }\n\n public bool TryGetValue(string key, [MaybeNullWhen(false)] out int value)\n {\n return _dict.TryGetValue(key, out value);\n }\n\n private Dictionary<string, int> _dict = new Dictionary<string, int>();\n private int _last = 0;\n }\n}\n" }, { "alpha_fraction": 0.602297306060791, "alphanum_fraction": 0.6036486625671387, "avg_line_length": 51.85714340209961, "blob_id": "c08600650a03d8b2be994bffdd170809050e170c", "content_id": "b8cda7aebb1c55fd1597fb8e94d59b3156025925", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7400, "license_type": "permissive", "max_line_length": 172, "num_lines": 140, "path": "/src/TorchSharp/Distributions/RelaxedOneHotCategorical.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n using static torch.distributions;\n\n namespace Modules\n {\n /// <summary>\n /// Creates a RelaxedOneHotCategorical distribution, parametrized by `temperature`, and either `probs` or `logits` (but not both).\n /// This is a relaxed version of the `OneHotCategorical` distribution, so its samples are on simplex, and are reparametrizable..\n /// </summary>\n public class RelaxedOneHotCategorical : TransformedDistribution\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"temperature\">Relaxation temperature</param>\n /// <param name=\"probs\">the probability of sampling `1`</param>\n /// <param name=\"logits\">the log-odds of sampling `1`</param>\n /// <param name=\"generator\"></param>\n public RelaxedOneHotCategorical(Tensor temperature, Tensor probs = null, Tensor logits = null, torch.Generator generator = null) :\n base(ExpRelaxedCategorical(temperature, probs, logits, generator), new distributions.transforms.ExpTransform(), generator)\n {\n this._probs = probs?.alias().DetachFromDisposeScope();\n this._logits = logits?.alias().DetachFromDisposeScope();\n }\n\n private Tensor _probs;\n private Tensor _logits;\n\n private ExpRelaxedCategorical base_dist => this.base_distribution as ExpRelaxedCategorical;\n\n /// <summary>\n /// The probability of sampling 1\n /// </summary>\n public Tensor probs {\n get {\n return base_dist.probs;\n }\n }\n\n /// <summary>\n /// The log-odds of sampling 1\n /// </summary>\n public Tensor logits {\n get {\n return base_dist.logits;\n }\n }\n\n public Tensor temperature {\n get {\n return base_dist.logits;\n }\n }\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n /// <returns></returns>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is RelaxedOneHotCategorical))\n throw new ArgumentException(\"expand(): 'instance' must be a RelaxedOneHotCategorical distribution\");\n\n var newDistribution = ((instance == null) ? new RelaxedOneHotCategorical(temperature, _probs, _logits, generator) : instance) as RelaxedOneHotCategorical;\n\n newDistribution.batch_shape = batch_shape;\n return base.expand(batch_shape, newDistribution);\n }\n }\n\n }\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a RelaxedOneHotCategorical distribution, parametrized by `temperature`, and either `probs` or `logits` (but not both).\n /// This is a relaxed version of the `OneHotCategorical` distribution, so its samples are on simplex, and are reparametrizable..\n /// </summary>\n /// <param name=\"temperature\">Relaxation temperature</param>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static RelaxedOneHotCategorical RelaxedOneHotCategorical(Tensor temperature, Tensor probs = null, Tensor logits = null, torch.Generator generator = null)\n {\n return new RelaxedOneHotCategorical(temperature, probs, logits, generator);\n }\n\n /// <summary>\n /// Creates a RelaxedOneHotCategorical distribution, parametrized by `temperature`, and either `probs` or `logits` (but not both).\n /// This is a relaxed version of the `OneHotCategorical` distribution, so its samples are on simplex, and are reparametrizable..\n /// </summary>\n /// <param name=\"temperature\">Relaxation temperature</param>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static RelaxedOneHotCategorical RelaxedOneHotCategorical(Tensor temperature, float? probs, float? logits, torch.Generator generator = null)\n {\n if (probs.HasValue && !logits.HasValue)\n return new RelaxedOneHotCategorical(temperature, torch.tensor(probs.Value), null, generator);\n else if (!probs.HasValue && logits.HasValue)\n return new RelaxedOneHotCategorical(temperature, null, torch.tensor(logits.Value), generator);\n else\n throw new ArgumentException(\"One and only one of 'probs' and logits should be provided.\");\n }\n\n\n /// <summary>\n /// Creates a RelaxedOneHotCategorical distribution, parametrized by `temperature`, and either `probs` or `logits` (but not both).\n /// This is a relaxed version of the `OneHotCategorical` distribution, so its samples are on simplex, and are reparametrizable..\n /// </summary>\n /// <param name=\"temperature\">Relaxation temperature</param>\n /// <param name=\"probs\">The probability of sampling '1'</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static RelaxedOneHotCategorical RelaxedOneHotCategorical(Tensor temperature, double? probs, double? logits, torch.Generator generator = null)\n {\n if (probs.HasValue && !logits.HasValue)\n return new RelaxedOneHotCategorical(temperature, torch.tensor(probs.Value), null, generator);\n else if (!probs.HasValue && logits.HasValue)\n return new RelaxedOneHotCategorical(temperature, null, torch.tensor(logits.Value), generator);\n else\n throw new ArgumentException(\"One and only one of 'probs' and 'logits' should be non-null\");\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.3323427438735962, "alphanum_fraction": 0.8015121817588806, "avg_line_length": 76.79247283935547, "blob_id": "e01bc550a7443bf4b763ac6faf9e99a8a516f859", "content_id": "6f34e23b3016ad3384221af1257c309d74cd1f57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 72347, "license_type": "permissive", "max_line_length": 87, "num_lines": 930, "path": "/src/Native/LibTorchSharp/crc32c.c", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "/* Part of CRC-32C library: https://crc32c.machinezoo.com/ */\n/*\n Copyright (c) 2013 - 2014, 2016 Mark Adler, Robert Vazan, Max Vysokikh\n\n This software is provided 'as-is', without any express or implied\n warranty. In no event will the author be held liable for any damages\n arising from the use of this software.\n\n Permission is granted to anyone to use this software for any purpose,\n including commercial applications, and to alter it and redistribute it\n freely, subject to the following restrictions:\n\n 1. The origin of this software must not be misrepresented; you must not\n claim that you wrote the original software. If you use this software\n in a product, an acknowledgment in the product documentation would be\n appreciated but is not required.\n 2. Altered source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n 3. This notice may not be removed or altered from any source distribution.\n*/\n\n#ifndef _CRT_SECURE_NO_WARNINGS\n#define _CRT_SECURE_NO_WARNINGS\n#endif\n\n#include \"crc32c.h\"\n\n// ALTERED SOURCE VERSION\n//\n// Per #2 in the copyright notice above:\n// \n// The definition of 'NONMINMAX' below was altered from the original.\n\n//#define NOMINMAX\n\n#ifdef CRC32C_GCC\n#include <cpuid.h>\n#include <x86intrin.h>\n#else\n#include <intrin.h>\n#endif\n\n#define POLY 0x82f63b78\n#define LONG_SHIFT 8192\n#define SHORT_SHIFT 256\n\ntypedef const uint8_t *buffer;\n\nstatic union {\n uint32_t dword_table[16][256];\n uint64_t qword_array[2048];\n} table = {\n .qword_array = {\n 0xf26b830300000000, 0x1350f3f4e13b70f7, 0x35f1141cc79a971f, 0xd4ca64eb26a1e7e8,\n 0x78b2dbcc8ad958cf, 0x9989ab3b6be22838, 0xbf284cd34d43cfd0, 0x5e133c24ac78bf27,\n 0xe235446c105ec76f, 0x30e349bf165b798, 0x25afd373d7c45070, 0xc494a38436ff2087,\n 0x68ec1ca39a879fa0, 0x89d76c547bbcef57, 0xaf768bbc5d1d08bf, 0x4e4dfb4bbc267848,\n 0xd2d60ddd20bd8ede, 0x33ed7d2ac186fe29, 0x154c9ac2e72719c1, 0xf477ea35061c6936,\n 0x580f5512aa64d611, 0xb93425e54b5fa6e6, 0x9f95c20d6dfe410e, 0x7eaeb2fa8cc531f9,\n 0xc288cab230e349b1, 0x23b3ba45d1d83946, 0x5125dadf779deae, 0xe4292d5a1642ae59,\n 0x4851927dba3a117e, 0xa96ae28a5b016189, 0x8fcb05627da08661, 0x6ef075959c9bf696,\n 0xb3109ebf417b1dbc, 0x522bee48a0406d4b, 0x748a09a086e18aa3, 0x95b1795767dafa54,\n 0x39c9c670cba24573, 0xd8f2b6872a993584, 0xfe53516f0c38d26c, 0x1f682198ed03a29b,\n 0xa34e59d05125dad3, 0x42752927b01eaa24, 0x64d4cecf96bf4dcc, 0x85efbe3877843d3b,\n 0x2997011fdbfc821c, 0xc8ac71e83ac7f2eb, 0xee0d96001c661503, 0xf36e6f7fd5d65f4,\n 0x93ad106161c69362, 0x7296609680fde395, 0x5437877ea65c047d, 0xb50cf7894767748a,\n 0x197448aeeb1fcbad, 0xf84f38590a24bb5a, 0xdeeedfb12c855cb2, 0x3fd5af46cdbe2c45,\n 0x83f3d70e7198540d, 0x62c8a7f990a324fa, 0x44694011b602c312, 0xa55230e65739b3e5,\n 0x92a8fc1fb410cc2, 0xe811ff361a7a7c35, 0xceb018de3cdb9bdd, 0x2f8b6829dde0eb2a,\n 0x709db87b82f63b78, 0x91a6c88c63cd4b8f, 0xb7072f64456cac67, 0x563c5f93a457dc90,\n 0xfa44e0b4082f63b7, 0x1b7f9043e9141340, 0x3dde77abcfb5f4a8, 0xdce5075c2e8e845f,\n 0x60c37f1492a8fc17, 0x81f80fe373938ce0, 0xa759e80b55326b08, 0x466298fcb4091bff,\n 0xea1a27db1871a4d8, 0xb21572cf94ad42f, 0x2d80b0c4dfeb33c7, 0xccbbc0333ed04330,\n 0x502036a5a24bb5a6, 0xb11b46524370c551, 0x97baa1ba65d122b9, 0x7681d14d84ea524e,\n 0xdaf96e6a2892ed69, 0x3bc21e9dc9a99d9e, 0x1d63f975ef087a76, 0xfc5889820e330a81,\n 0x407ef1cab21572c9, 0xa145813d532e023e, 0x87e466d5758fe5d6, 0x66df162294b49521,\n 0xcaa7a90538cc2a06, 0x2b9cd9f2d9f75af1, 0xd3d3e1aff56bd19, 0xec064eed1e6dcdee,\n 0x31e6a5c7c38d26c4, 0xd0ddd53022b65633, 0xf67c32d80417b1db, 0x1747422fe52cc12c,\n 0xbb3ffd0849547e0b, 0x5a048dffa86f0efc, 0x7ca56a178ecee914, 0x9d9e1ae06ff599e3,\n 0x21b862a8d3d3e1ab, 0xc083125f32e8915c, 0xe622f5b7144976b4, 0x7198540f5720643,\n 0xab613a67590ab964, 0x4a5a4a90b831c993, 0x6cfbad789e902e7b, 0x8dc0dd8f7fab5e8c,\n 0x115b2b19e330a81a, 0xf0605bee020bd8ed, 0xd6c1bc0624aa3f05, 0x37faccf1c5914ff2,\n 0x9b8273d669e9f0d5, 0x7ab9032188d28022, 0x5c18e4c9ae7367ca, 0xbd23943e4f48173d,\n 0x105ec76f36e6f75, 0xe03e9c8112551f82, 0xc69f7b6934f4f86a, 0x27a40b9ed5cf889d,\n 0x8bdcb4b979b737ba, 0x6ae7c44e988c474d, 0x4c4623a6be2da0a5, 0xad7d53515f16d052,\n 0x13a2987700000000, 0x34e7a899274530ee, 0x5d28f9ab4e8a61dc, 0x7a6dc94569cf5132,\n 0x8eb65bcf9d14c3b8, 0xa9f36b21ba51f356, 0xc03c3a13d39ea264, 0xe7790afdf4db928a,\n 0x2c6769f63fc5f181, 0xb2259181880c16f, 0x62ed082a714f905d, 0x45a838c4560aa0b3,\n 0xb173aa4ea2d13239, 0x96369aa0859402d7, 0xfff9cb92ec5b53e5, 0xd8bcfb7ccb1e630b,\n 0x6c297b757f8be302, 0x4b6c4b9b58ced3ec, 0x22a31aa9310182de, 0x5e62a471644b230,\n 0xf13db8cde29f20ba, 0xd6788823c5da1054, 0xbfb7d911ac154166, 0x98f2e9ff8b507188,\n 0x53ec8af4404e1283, 0x74a9ba1a670b226d, 0x1d66eb280ec4735f, 0x3a23dbc6298143b1,\n 0xcef8494cdd5ad13b, 0xe9bd79a2fa1fe1d5, 0x8072289093d0b0e7, 0xa737187eb4958009,\n 0xecb55e73ff17c604, 0xcbf06e9dd852f6ea, 0xa23f3fafb19da7d8, 0x857a0f4196d89736,\n 0x71a19dcb620305bc, 0x56e4ad2545463552, 0x3f2bfc172c896460, 0x186eccf90bcc548e,\n 0xd370aff2c0d23785, 0xf4359f1ce797076b, 0x9dface2e8e585659, 0xbabffec0a91d66b7,\n 0x4e646c4a5dc6f43d, 0x69215ca47a83c4d3, 0xee0d96134c95e1, 0x27ab3d783409a50f,\n 0x933ebd71809c2506, 0xb47b8d9fa7d915e8, 0xddb4dcadce1644da, 0xfaf1ec43e9537434,\n 0xe2a7ec91d88e6be, 0x296f4e273acdd650, 0x40a01f1553028762, 0x67e52ffb7447b78c,\n 0xacfb4cf0bf59d487, 0x8bbe7c1e981ce469, 0xe2712d2cf1d3b55b, 0xc5341dc2d69685b5,\n 0x31ef8f48224d173f, 0x16aabfa6050827d1, 0x7f65ee946cc776e3, 0x5820de7a4b82460d,\n 0xe861628efbc3faf9, 0xcf245260dc86ca17, 0xa6eb0352b5499b25, 0x81ae33bc920cabcb,\n 0x7575a13666d73941, 0x523091d8419209af, 0x3bffc0ea285d589d, 0x1cbaf0040f186873,\n 0xd7a4930fc4060b78, 0xf0e1a3e1e3433b96, 0x992ef2d38a8c6aa4, 0xbe6bc23dadc95a4a,\n 0x4ab050b75912c8c0, 0x6df560597e57f82e, 0x43a316b1798a91c, 0x237f018530dd99f2,\n 0x97ea818c844819fb, 0xb0afb162a30d2915, 0xd960e050cac27827, 0xfe25d0beed8748c9,\n 0xafe4234195cda43, 0x2dbb72da3e19eaad, 0x447423e857d6bb9f, 0x6331130670938b71,\n 0xa82f700dbb8de87a, 0x8f6a40e39cc8d894, 0xe6a511d1f50789a6, 0xc1e0213fd242b948,\n 0x353bb3b526992bc2, 0x127e835b01dc1b2c, 0x7bb1d26968134a1e, 0x5cf4e2874f567af0,\n 0x1776a48a04d43cfd, 0x3033946423910c13, 0x59fcc5564a5e5d21, 0x7eb9f5b86d1b6dcf,\n 0x8a62673299c0ff45, 0xad2757dcbe85cfab, 0xc4e806eed74a9e99, 0xe3ad3600f00fae77,\n 0x28b3550b3b11cd7c, 0xff665e51c54fd92, 0x663934d7759baca0, 0x417c043952de9c4e,\n 0xb5a796b3a6050ec4, 0x92e2a65d81403e2a, 0xfb2df76fe88f6f18, 0xdc68c781cfca5ff6,\n 0x68fd47887b5fdfff, 0x4fb877665c1aef11, 0x2677265435d5be23, 0x13216ba12908ecd,\n 0xf5e98430e64b1c47, 0xd2acb4dec10e2ca9, 0xbb63e5eca8c17d9b, 0x9c26d5028f844d75,\n 0x5738b609449a2e7e, 0x707d86e763df1e90, 0x19b2d7d50a104fa2, 0x3ef7e73b2d557f4c,\n 0xca2c75b1d98eedc6, 0xed69455ffecbdd28, 0x84a6146d97048c1a, 0xa3e32483b041bcf4,\n 0xa541927e00000000, 0xea2ec0734f6f520d, 0x3b9f36649edea41a, 0x74f06469d1b1f617,\n 0x9d10acbb38513ec5, 0xd27ffeb6773e6cc8, 0x3ce08a1a68f9adf, 0x4ca15aace9e0c8d2,\n 0xd5e3eff470a27d8a, 0x9a8cbdf93fcd2f87, 0x4b3d4beeee7cd990, 0x45219e3a1138b9d,\n 0xedb2d13148f3434f, 0xa2dd833c079c1142, 0x736c752bd62de755, 0x3c0327269942b558,\n 0x4405696ae144fb14, 0xb6a3b67ae2ba919, 0xdadbcd707f9a5f0e, 0x95b49f7d30f50d03,\n 0x7c5457afd915c5d1, 0x333b05a2967a97dc, 0xe28af3b547cb61cb, 0xade5a1b808a433c6,\n 0x34a714e091e6869e, 0x7bc846edde89d493, 0xaa79b0fa0f382284, 0xe516e2f740577089,\n 0xcf62a25a9b7b85b, 0x43997828e6d8ea56, 0x92288e3f37691c41, 0xdd47dc3278064e4c,\n 0x622412a7c76580d9, 0x2d4b40aa880ad2d4, 0xfcfab6bd59bb24c3, 0xb395e4b016d476ce,\n 0x5a752c62ff34be1c, 0x151a7e6fb05bec11, 0xc4ab887861ea1a06, 0x8bc4da752e85480b,\n 0x12866f2db7c7fd53, 0x5de93d20f8a8af5e, 0x8c58cb3729195949, 0xc337993a66760b44,\n 0x2ad751e88f96c396, 0x65b803e5c0f9919b, 0xb409f5f21148678c, 0xfb66a7ff5e273581,\n 0x8360e9b326217bcd, 0xcc0fbbbe694e29c0, 0x1dbe4da9b8ffdfd7, 0x52d11fa4f7908dda,\n 0xbb31d7761e704508, 0xf45e857b511f1705, 0x25ef736c80aee112, 0x6a802161cfc1b31f,\n 0xf3c2943956830647, 0xbcadc63419ec544a, 0x6d1c3023c85da25d, 0x2273622e8732f050,\n 0xcb93aafc6ed23882, 0x84fcf8f121bd6a8f, 0x554d0ee6f00c9c98, 0x1a225cebbf63ce95,\n 0x2e66e53d8b277743, 0x6109b730c448254e, 0xb0b8412715f9d359, 0xffd7132a5a968154,\n 0x1637dbf8b3764986, 0x595889f5fc191b8b, 0x88e97fe22da8ed9c, 0xc7862def62c7bf91,\n 0x5ec498b7fb850ac9, 0x11abcabab4ea58c4, 0xc01a3cad655baed3, 0x8f756ea02a34fcde,\n 0x6695a672c3d4340c, 0x29faf47f8cbb6601, 0xf84b02685d0a9016, 0xb72450651265c21b,\n 0xcf221e296a638c57, 0x804d4c24250cde5a, 0x51fcba33f4bd284d, 0x1e93e83ebbd27a40,\n 0xf77320ec5232b292, 0xb81c72e11d5de09f, 0x69ad84f6ccec1688, 0x26c2d6fb83834485,\n 0xbf8063a31ac1f1dd, 0xf0ef31ae55aea3d0, 0x215ec7b9841f55c7, 0x6e3195b4cb7007ca,\n 0x87d15d662290cf18, 0xc8be0f6b6dff9d15, 0x190ff97cbc4e6b02, 0x5660ab71f321390f,\n 0xe90365e44c42f79a, 0xa66c37e9032da597, 0x77ddc1fed29c5380, 0x38b293f39df3018d,\n 0xd1525b217413c95f, 0x9e3d092c3b7c9b52, 0x4f8cff3beacd6d45, 0xe3ad36a5a23f48,\n 0x99a1186e3ce08a10, 0xd6ce4a63738fd81d, 0x77fbc74a23e2e0a, 0x4810ee79ed517c07,\n 0xa1f026ab04b1b4d5, 0xee9f74a64bdee6d8, 0x3f2e82b19a6f10cf, 0x7041d0bcd50042c2,\n 0x8479ef0ad060c8e, 0x4728ccfde2695e83, 0x96993aea33d8a894, 0xd9f668e77cb7fa99,\n 0x3016a0359557324b, 0x7f79f238da386046, 0xaec8042f0b899651, 0xe1a7562244e6c45c,\n 0x78e5e37adda47104, 0x378ab17792cb2309, 0xe63b4760437ad51e, 0xa954156d0c158713,\n 0x40b4ddbfe5f54fc1, 0xfdb8fb2aa9a1dcc, 0xde6a79a57b2bebdb, 0x91052ba83444b9d6,\n 0xdd45aab800000000, 0x62228939bf672381, 0xa6679b4b7b2231f3, 0x1900b8cac4451272,\n 0x2b01c95ef64463e6, 0x9466eadf49234067, 0x5023f8ad8d665215, 0xef44db2c32017194,\n 0x34211b85e964b13d, 0x8b463804560392bc, 0x4f032a76924680ce, 0xf06409f72d21a34f,\n 0xc26578631f20d2db, 0x7d025be2a047f15a, 0xb94749906402e328, 0x6206a11db65c0a9,\n 0xa60be33d725148b, 0xb5079db26842370a, 0x71428fc0ac072578, 0xce25ac41136006f9,\n 0xfc24ddd52161776d, 0x4343fe549e0654ec, 0x8706ec265a43469e, 0x3861cfa7e524651f,\n 0xe3040f0e3e41a5b6, 0x5c632c8f81268637, 0x98263efd45639445, 0x27411d7cfa04b7c4,\n 0x15406ce8c805c650, 0xaa274f697762e5d1, 0x6e625d1bb327f7a3, 0xd1057e9a0c40d422,\n 0x76e3f55faba65fe7, 0xc984d6de14c17c66, 0xdc1c4acd0846e14, 0xb2a6e72d6fe34d95,\n 0x80a796b95de23c01, 0x3fc0b538e2851f80, 0xfb85a74a26c00df2, 0x44e284cb99a72e73,\n 0x9f87446242c2eeda, 0x20e067e3fda5cd5b, 0xe4a5759139e0df29, 0x5bc256108687fca8,\n 0x69c32784b4868d3c, 0xd6a404050be1aebd, 0x12e11677cfa4bccf, 0xad8635f670c39f4e,\n 0xa1c6e1d47c834b6c, 0x1ea1c255c3e468ed, 0xdae4d02707a17a9f, 0x6583f3a6b8c6591e,\n 0x578282328ac7288a, 0xe8e5a1b335a00b0b, 0x2ca0b3c1f1e51979, 0x93c790404e823af8,\n 0x48a250e995e7fa51, 0xf7c573682a80d9d0, 0x3380611aeec5cba2, 0x8ce7429b51a2e823,\n 0xbee6330f63a399b7, 0x181108edcc4ba36, 0xc5c402fc1881a844, 0x7aa3217da7e68bc5,\n 0x8fe5638752a0c93f, 0x30824006edc7eabe, 0xf4c752742982f8cc, 0x4ba071f596e5db4d,\n 0x79a10061a4e4aad9, 0xc6c623e01b838958, 0x2833192dfc69b2a, 0xbde4121360a1b8ab,\n 0x6681d2babbc47802, 0xd9e6f13b04a35b83, 0x1da3e349c0e649f1, 0xa2c4c0c87f816a70,\n 0x90c5b15c4d801be4, 0x2fa292ddf2e73865, 0xebe780af36a22a17, 0x5480a32e89c50996,\n 0x58c0770c8585ddb4, 0xe7a7548d3ae2fe35, 0x23e246fffea7ec47, 0x9c85657e41c0cfc6,\n 0xae8414ea73c1be52, 0x11e3376bcca69dd3, 0xd5a6251908e38fa1, 0x6ac10698b784ac20,\n 0xb1a4c6316ce16c89, 0xec3e5b0d3864f08, 0xca86f7c217c35d7a, 0x75e1d443a8a47efb,\n 0x47e0a5d79aa50f6f, 0xf887865625c22cee, 0x3cc29424e1873e9c, 0x83a5b7a55ee01d1d,\n 0x24433c60f90696d8, 0x9b241fe14661b559, 0x5f610d938224a72b, 0xe0062e123d4384aa,\n 0xd2075f860f42f53e, 0x6d607c07b025d6bf, 0xa9256e757460c4cd, 0x16424df4cb07e74c,\n 0xcd278d5d106227e5, 0x7240aedcaf050464, 0xb605bcae6b401616, 0x9629f2fd4273597,\n 0x3b63eebbe6264403, 0x8404cd3a59416782, 0x4041df489d0475f0, 0xff26fcc922635671,\n 0xf36628eb2e238253, 0x4c010b6a9144a1d2, 0x884419185501b3a0, 0x37233a99ea669021,\n 0x5224b0dd867e1b5, 0xba45688c6700c234, 0x7e007afea345d046, 0xc167597f1c22f3c7,\n 0x1a0299d6c747336e, 0xa565ba57782010ef, 0x6120a825bc65029d, 0xde478ba40302211c,\n 0xec46fa3031035088, 0x5321d9b18e647309, 0x9764cbc34a21617b, 0x2803e842f54642fa,\n 0x38116fac00000000, 0x4833b0f47022df58, 0xd854d11ce045beb0, 0xa8760e44906761e8,\n 0xfd76643dc5670b91, 0x8d54bb65b545d4c9, 0x1d33da8d2522b521, 0x6d1105d555006a79,\n 0xb7330e7f8f2261d3, 0xc711d127ff00be8b, 0x5776b0cf6f67df63, 0x27546f971f45003b,\n 0x725405ee4a456a42, 0x276dab63a67b51a, 0x9211bb5eaa00d4f2, 0xe2336406da220baa,\n 0x23b9dafb1ba8b557, 0x539b05a36b8a6a0f, 0xc3fc644bfbed0be7, 0xb3debb138bcfd4bf,\n 0xe6ded16adecfbec6, 0x96fc0e32aeed619e, 0x69b6fda3e8a0076, 0x76b9b0824ea8df2e,\n 0xac9bbb28948ad484, 0xdcb96470e4a80bdc, 0x4cde059874cf6a34, 0x3cfcdac004edb56c,\n 0x69fcb0b951eddf15, 0x19de6fe121cf004d, 0x89b90e09b1a861a5, 0xf99bd151c18abefd,\n 0xf40050237516aae, 0x7f62da5a4773b5f6, 0xef05bbb2d714d41e, 0x9f2764eaa7360b46,\n 0xca270e93f236613f, 0xba05d1cb8214be67, 0x2a62b0231273df8f, 0x5a406f7b625100d7,\n 0x806264d1b8730b7d, 0xf040bb89c851d425, 0x6027da615836b5cd, 0x1005053928146a95,\n 0x45056f407d1400ec, 0x3527b0180d36dfb4, 0xa540d1f09d51be5c, 0xd5620ea8ed736104,\n 0x14e8b0552cf9dff9, 0x64ca6f0d5cdb00a1, 0xf4ad0ee5ccbc6149, 0x848fd1bdbc9ebe11,\n 0xd18fbbc4e99ed468, 0xa1ad649c99bc0b30, 0x31ca057409db6ad8, 0x41e8da2c79f9b580,\n 0x9bcad186a3dbbe2a, 0xebe80eded3f96172, 0x7b8f6f36439e009a, 0xbadb06e33bcdfc2,\n 0x5eadda1766bcb5bb, 0x2e8f054f169e6ae3, 0xbee864a786f90b0b, 0xcecabbfff6dbd453,\n 0x56b3baf06ea2d55c, 0x269165a81e800a04, 0xb6f604408ee76bec, 0xc6d4db18fec5b4b4,\n 0x93d4b161abc5decd, 0xe3f66e39dbe70195, 0x73910fd14b80607d, 0x3b3d0893ba2bf25,\n 0xd991db23e180b48f, 0xa9b3047b91a26bd7, 0x39d4659301c50a3f, 0x49f6bacb71e7d567,\n 0x1cf6d0b224e7bf1e, 0x6cd40fea54c56046, 0xfcb36e02c4a201ae, 0x8c91b15ab480def6,\n 0x4d1b0fa7750a600b, 0x3d39d0ff0528bf53, 0xad5eb117954fdebb, 0xdd7c6e4fe56d01e3,\n 0x887c0436b06d6b9a, 0xf85edb6ec04fb4c2, 0x6839ba865028d52a, 0x181b65de200a0a72,\n 0xc2396e74fa2801d8, 0xb21bb12c8a0ade80, 0x227cd0c41a6dbf68, 0x525e0f9c6a4f6030,\n 0x75e65e53f4f0a49, 0x777cbabd4f6dd511, 0xe71bdb55df0ab4f9, 0x9739040daf286ba1,\n 0x61e2d05e59f3bff2, 0x11c00f0629d160aa, 0x81a76eeeb9b60142, 0xf185b1b6c994de1a,\n 0xa485dbcf9c94b463, 0xd4a70497ecb66b3b, 0x44c0657f7cd10ad3, 0x34e2ba270cf3d58b,\n 0xeec0b18dd6d1de21, 0x9ee26ed5a6f30179, 0xe850f3d36946091, 0x7ea7d06546b6bfc9,\n 0x2ba7ba1c13b6d5b0, 0x5b85654463940ae8, 0xcbe204acf3f36b00, 0xbbc0dbf483d1b458,\n 0x7a4a6509425b0aa5, 0xa68ba513279d5fd, 0x9a0fdbb9a21eb415, 0xea2d04e1d23c6b4d,\n 0xbf2d6e98873c0134, 0xcf0fb1c0f71ede6c, 0x5f68d0286779bf84, 0x2f4a0f70175b60dc,\n 0xf56804dacd796b76, 0x854adb82bd5bb42e, 0x152dba6a2d3cd5c6, 0x650f65325d1e0a9e,\n 0x300f0f4b081e60e7, 0x402dd013783cbfbf, 0xd04ab1fbe85bde57, 0xa0686ea39879010f,\n 0xef306b1900000000, 0x34bccbdadb8ca0c3, 0x5dc55c6eb2f53777, 0x8649fcad697997b4,\n 0x8f3673066006181f, 0x54bad3c5bb8ab8dc, 0x3dc34471d2f32f68, 0xe64fe4b2097f8fab,\n 0x2f3c5b27c00c303e, 0xf4b0fbe41b8090fd, 0x9dc96c5072f90749, 0x4645cc93a975a78a,\n 0x4f3a4338a00a2821, 0x94b6e3fb7b8688e2, 0xfdcf744f12ff1f56, 0x2643d48cc973bf95,\n 0x6ac47d9485f4168d, 0xb148dd575e78b64e, 0xd8314ae3370121fa, 0x3bdea20ec8d8139,\n 0xac2658be5f20e92, 0xd14ec5483e7eae51, 0xb83752fc570739e5, 0x63bbf23f8c8b9926,\n 0xaac84daa45f826b3, 0x7144ed699e748670, 0x183d7addf70d11c4, 0xc3b1da1e2c81b107,\n 0xcace55b525fe3eac, 0x1142f576fe729e6f, 0x783b62c2970b09db, 0xa3b7c2014c87a918,\n 0xe13430f20e045beb, 0x3ab89031d588fb28, 0x53c10785bcf16c9c, 0x884da746677dcc5f,\n 0x813228ed6e0243f4, 0x5abe882eb58ee337, 0x33c71f9adcf77483, 0xe84bbf59077bd440,\n 0x213800ccce086bd5, 0xfab4a00f1584cb16, 0x93cd37bb7cfd5ca2, 0x48419778a771fc61,\n 0x413e18d3ae0e73ca, 0x9ab2b8107582d309, 0xf3cb2fa41cfb44bd, 0x28478f67c777e47e,\n 0x64c0267f8bf04d66, 0xbf4c86bc507ceda5, 0xd635110839057a11, 0xdb9b1cbe289dad2,\n 0x4c63e60ebf65579, 0xdf4a9ea3307af5ba, 0xb63309175903620e, 0x6dbfa9d4828fc2cd,\n 0xa4cc16414bfc7d58, 0x7f40b6829070dd9b, 0x16392136f9094a2f, 0xcdb581f52285eaec,\n 0xc4ca0e5e2bfa6547, 0x1f46ae9df076c584, 0x763f3929990f5230, 0xadb399ea4283f2f3,\n 0xf338dccf1c08b7d6, 0x28b47c0cc7841715, 0x41cdebb8aefd80a1, 0x9a414b7b75712062,\n 0x933ec4d07c0eafc9, 0x48b26413a7820f0a, 0x21cbf3a7cefb98be, 0xfa4753641577387d,\n 0x3334ecf1dc0487e8, 0xe8b84c320788272b, 0x81c1db866ef1b09f, 0x5a4d7b45b57d105c,\n 0x5332f4eebc029ff7, 0x88be542d678e3f34, 0xe1c7c3990ef7a880, 0x3a4b635ad57b0843,\n 0x76ccca4299fca15b, 0xad406a8142700198, 0xc439fd352b09962c, 0x1fb55df6f08536ef,\n 0x16cad25df9fab944, 0xcd46729e22761987, 0xa43fe52a4b0f8e33, 0x7fb345e990832ef0,\n 0xb6c0fa7c59f09165, 0x6d4c5abf827c31a6, 0x435cd0beb05a612, 0xdfb96dc8308906d1,\n 0xd6c6e26339f6897a, 0xd4a42a0e27a29b9, 0x6433d5148b03be0d, 0xbfbf75d7508f1ece,\n 0xfd3c8724120cec3d, 0x26b027e7c9804cfe, 0x4fc9b053a0f9db4a, 0x944510907b757b89,\n 0x9d3a9f3b720af422, 0x46b63ff8a98654e1, 0x2fcfa84cc0ffc355, 0xf443088f1b736396,\n 0x3d30b71ad200dc03, 0xe6bc17d9098c7cc0, 0x8fc5806d60f5eb74, 0x544920aebb794bb7,\n 0x5d36af05b206c41c, 0x86ba0fc6698a64df, 0xefc3987200f3f36b, 0x344f38b1db7f53a8,\n 0x78c891a997f8fab0, 0xa344316a4c745a73, 0xca3da6de250dcdc7, 0x11b1061dfe816d04,\n 0x18ce89b6f7fee2af, 0xc34229752c72426c, 0xaa3bbec1450bd5d8, 0x71b71e029e87751b,\n 0xb8c4a19757f4ca8e, 0x634801548c786a4d, 0xa3196e0e501fdf9, 0xd1bd36233e8d5d3a,\n 0xd8c2b98837f2d291, 0x34e194bec7e7252, 0x6a378eff8507e5e6, 0xb1bb2e3c5e8b4525,\n 0x68032cc800000000, 0xb8057558d0065990, 0xcde3e919a5e0c5d1, 0x1de5b08975e69c41,\n 0x262ed19b4e2dfd53, 0xf628880b9e2ba4c3, 0x83ce144aebcd3882, 0x53c84dda3bcb6112,\n 0xf458d66e9c5bfaa6, 0x245e8ffe4c5da336, 0x51b813bf39bb3f77, 0x81be4a2fe9bd66e7,\n 0xba752b3dd27607f5, 0x6a7372ad02705e65, 0x1f95eeec7796c224, 0xcf93b77ca7909bb4,\n 0x5558af753d5b83bd, 0x855ef6e5ed5dda2d, 0xf0b86aa498bb466c, 0x20be333448bd1ffc,\n 0x1b75522673767eee, 0xcb730bb6a370277e, 0xbe9597f7d696bb3f, 0x6e93ce670690e2af,\n 0xc90355d3a100791b, 0x19050c437106208b, 0x6ce3900204e0bcca, 0xbce5c992d4e6e55a,\n 0x872ea880ef2d8448, 0x5728f1103f2bddd8, 0x22ce6d514acd4199, 0xf2c834c19acb1809,\n 0x12b42bb27ab7077a, 0xc2b27222aab15eea, 0xb754ee63df57c2ab, 0x6752b7f30f519b3b,\n 0x5c99d6e1349afa29, 0x8c9f8f71e49ca3b9, 0xf9791330917a3ff8, 0x297f4aa0417c6668,\n 0x8eefd114e6ecfddc, 0x5ee9888436eaa44c, 0x2b0f14c5430c380d, 0xfb094d55930a619d,\n 0xc0c22c47a8c1008f, 0x10c475d778c7591f, 0x6522e9960d21c55e, 0xb524b006dd279cce,\n 0x2fefa80f47ec84c7, 0xffe9f19f97eadd57, 0x8a0f6ddee20c4116, 0x5a09344e320a1886,\n 0x61c2555c09c17994, 0xb1c40cccd9c72004, 0xc422908dac21bc45, 0x1424c91d7c27e5d5,\n 0xb3b452a9dbb77e61, 0x63b20b390bb127f1, 0x165497787e57bbb0, 0xc652cee8ae51e220,\n 0xfd99affa959a8332, 0x2d9ff66a459cdaa2, 0x58796a2b307a46e3, 0x887f33bbe07c1f73,\n 0x9d6d223cf56e0ef4, 0x4d6b7bac25685764, 0x388de7ed508ecb25, 0xe88bbe7d808892b5,\n 0xd340df6fbb43f3a7, 0x34686ff6b45aa37, 0x76a01abe1ea33676, 0xa6a6432ecea56fe6,\n 0x136d89a6935f452, 0xd130810ab933adc2, 0xa4d61d4bccd53183, 0x74d044db1cd36813,\n 0x4f1b25c927180901, 0x9f1d7c59f71e5091, 0xeafbe01882f8ccd0, 0x3afdb98852fe9540,\n 0xa036a181c8358d49, 0x7030f8111833d4d9, 0x5d664506dd54898, 0xd5d03dc0bdd31108,\n 0xee1b5cd28618701a, 0x3e1d0542561e298a, 0x4bfb990323f8b5cb, 0x9bfdc093f3feec5b,\n 0x3c6d5b27546e77ef, 0xec6b02b784682e7f, 0x998d9ef6f18eb23e, 0x498bc7662188ebae,\n 0x7240a6741a438abc, 0xa246ffe4ca45d32c, 0xd7a063a5bfa34f6d, 0x7a63a356fa516fd,\n 0xe7da25468fd9098e, 0x37dc7cd65fdf501e, 0x423ae0972a39cc5f, 0x923cb907fa3f95cf,\n 0xa9f7d815c1f4f4dd, 0x79f1818511f2ad4d, 0xc171dc46414310c, 0xdc114454b412689c,\n 0x7b81dfe01382f328, 0xab878670c384aab8, 0xde611a31b66236f9, 0xe6743a166646f69,\n 0x35ac22b35daf0e7b, 0xe5aa7b238da957eb, 0x904ce762f84fcbaa, 0x404abef22849923a,\n 0xda81a6fbb2828a33, 0xa87ff6b6284d3a3, 0x7f61632a17624fe2, 0xaf673abac7641672,\n 0x94ac5ba8fcaf7760, 0x44aa02382ca92ef0, 0x314c9e79594fb2b1, 0xe14ac7e98949eb21,\n 0x46da5c5d2ed97095, 0x96dc05cdfedf2905, 0xe33a998c8b39b544, 0x333cc01c5b3fecd4,\n 0x8f7a10e60f48dc6, 0xd8f1f89eb0f2d456, 0xad1764dfc5144817, 0x7d113d4f15121187,\n 0x493c7d2700000000, 0xdb4487699278fa4e, 0x6821ff4a211d826d, 0xfa590504b3657823,\n 0xb0779fd423b04da, 0x997f83b3d043fe94, 0x2a1afb90632686b7, 0xb86201def15e7cf9,\n 0xcd4a7493847609b4, 0x5f328edd160ef3fa, 0xec57f6fea56b8bd9, 0x7e2f0cb037137197,\n 0x8f717049c64d0d6e, 0x1d098a075435f720, 0xae6cf224e7508f03, 0x3c14086a7528754d,\n 0x443c18be0d006599, 0xd644e2f09f789fd7, 0x65219ad32c1de7f4, 0xf759609dbe651dba,\n 0x6071c644f3b6143, 0x947fe62add439b0d, 0x271a9e096e26e32e, 0xb5626447fc5e1960,\n 0xc04a110a89766c2d, 0x5232eb441b0e9663, 0xe1579367a86bee40, 0x732f69293a13140e,\n 0x827115d0cb4d68f7, 0x1009ef9e593592b9, 0xa36c97bdea50ea9a, 0x31146df3782810d4,\n 0x533cb6151a00cb32, 0xc1444c5b8878317c, 0x722134783b1d495f, 0xe059ce36a965b311,\n 0x1107b2cf583bcfe8, 0x837f4881ca4335a6, 0x301a30a279264d85, 0xa262caeceb5eb7cb,\n 0xd74abfa19e76c286, 0x453245ef0c0e38c8, 0xf6573dccbf6b40eb, 0x642fc7822d13baa5,\n 0x9571bb7bdc4dc65c, 0x70941354e353c12, 0xb46c3916fd504431, 0x2614c3586f28be7f,\n 0x5e3cd38c1700aeab, 0xcc4429c2857854e5, 0x7f2151e1361d2cc6, 0xed59abafa465d688,\n 0x1c07d756553baa71, 0x8e7f2d18c743503f, 0x3d1a553b7426281c, 0xaf62af75e65ed252,\n 0xda4ada389376a71f, 0x48322076010e5d51, 0xfb575855b26b2572, 0x692fa21b2013df3c,\n 0x9871dee2d14da3c5, 0xa0924ac4335598b, 0xb96c5c8ff05021a8, 0x2b14a6c16228dbe6,\n 0x7d3deb4334019664, 0xef45110da6796c2a, 0x5c20692e151c1409, 0xce5893608764ee47,\n 0x3f06ef99763a92be, 0xad7e15d7e44268f0, 0x1e1b6df4572710d3, 0x8c6397bac55fea9d,\n 0xf94be2f7b0779fd0, 0x6b3318b9220f659e, 0xd856609a916a1dbd, 0x4a2e9ad40312e7f3,\n 0xbb70e62df24c9b0a, 0x29081c6360346144, 0x9a6d6440d3511967, 0x8159e0e4129e329,\n 0x703d8eda3901f3fd, 0xe2457494ab7909b3, 0x51200cb7181c7190, 0xc358f6f98a648bde,\n 0x32068a007b3af727, 0xa07e704ee9420d69, 0x131b086d5a27754a, 0x8163f223c85f8f04,\n 0xf44b876ebd77fa49, 0x66337d202f0f0007, 0xd55605039c6a7824, 0x472eff4d0e12826a,\n 0xb67083b4ff4cfe93, 0x240879fa6d3404dd, 0x976d01d9de517cfe, 0x515fb974c2986b0,\n 0x673d20712e015d56, 0xf545da3fbc79a718, 0x4620a21c0f1cdf3b, 0xd45858529d642575,\n 0x250624ab6c3a598c, 0xb77edee5fe42a3c2, 0x41ba6c64d27dbe1, 0x96635c88df5f21af,\n 0xe34b29c5aa7754e2, 0x7133d38b380faeac, 0xc256aba88b6ad68f, 0x502e51e619122cc1,\n 0xa1702d1fe84c5038, 0x3308d7517a34aa76, 0x806daf72c951d255, 0x1215553c5b29281b,\n 0x6a3d45e8230138cf, 0xf845bfa6b179c281, 0x4b20c785021cbaa2, 0xd9583dcb906440ec,\n 0x28064132613a3c15, 0xba7ebb7cf342c65b, 0x91bc35f4027be78, 0x9b633911d25f4436,\n 0xee4b4c5ca777317b, 0x7c33b612350fcb35, 0xcf56ce31866ab316, 0x5d2e347f14124958,\n 0xac704886e54c35a1, 0x3e08b2c87734cfef, 0x8d6dcaebc451b7cc, 0x1f1530a556294d82,\n 0xf43ed64800000000, 0x19af0c29ed91da61, 0x2af1147bdecfc233, 0xc760ce1a335e1852,\n 0x4c4d24dfb873f297, 0xa1dcfebe55e228f6, 0x9282e6ec66bc30a4, 0x7f133c8d8b2deac5,\n 0x81354597750b93df, 0x6ca49ff6989a49be, 0x5ffa87a4abc451ec, 0xb26b5dc546558b8d,\n 0x3946b700cd786148, 0xd4d76d6120e9bb29, 0xe789753313b7a37b, 0xa18af52fe26791a,\n 0x1e29f1f6ea1727be, 0xf3b82b970786fddf, 0xc0e633c534d8e58d, 0x2d77e9a4d9493fec,\n 0xa65a03615264d529, 0x4bcbd900bff50f48, 0x7895c1528cab171a, 0x95041b33613acd7b,\n 0x6b2262299f1cb461, 0x86b3b848728d6e00, 0xb5eda01a41d37652, 0x587c7a7bac42ac33,\n 0xd35190be276f46f6, 0x3ec04adfcafe9c97, 0xd9e528df9a084c5, 0xe00f88ec14315ea4,\n 0x25fcefc5d1c2398d, 0xc86d35a43c53e3ec, 0xfb332df60f0dfbbe, 0x16a2f797e29c21df,\n 0x9d8f1d5269b1cb1a, 0x701ec7338420117b, 0x4340df61b77e0929, 0xaed105005aefd348,\n 0x50f77c1aa4c9aa52, 0xbd66a67b49587033, 0x8e38be297a066861, 0x63a964489797b200,\n 0xe8848e8d1cba58c5, 0x51554ecf12b82a4, 0x364b4cbec2759af6, 0xdbda96df2fe44097,\n 0xcfebc87b3bd51e33, 0x227a121ad644c452, 0x11240a48e51adc00, 0xfcb5d029088b0661,\n 0x77983aec83a6eca4, 0x9a09e08d6e3736c5, 0xa957f8df5d692e97, 0x44c622beb0f8f4f6,\n 0xbae05ba44ede8dec, 0x577181c5a34f578d, 0x642f999790114fdf, 0x89be43f67d8095be,\n 0x293a933f6ad7f7b, 0xef0273521b3ca51a, 0xdc5c6b002862bd48, 0x31cdb161c5f36729,\n 0x5256d3a3a66805eb, 0xbfc709c24bf9df8a, 0x8c99119078a7c7d8, 0x6108cbf195361db9,\n 0xea2521341e1bf77c, 0x7b4fb55f38a2d1d, 0x34eae307c0d4354f, 0xd97b39662d45ef2e,\n 0x275d407cd3639634, 0xcacc9a1d3ef24c55, 0xf992824f0dac5407, 0x1403582ee03d8e66,\n 0x9f2eb2eb6b1064a3, 0x72bf688a8681bec2, 0x41e170d8b5dfa690, 0xac70aab9584e7cf1,\n 0xb841f41d4c7f2255, 0x55d02e7ca1eef834, 0x668e362e92b0e066, 0x8b1fec4f7f213a07,\n 0x32068af40cd0c2, 0xeda3dceb199d0aa3, 0xdefdc4b92ac312f1, 0x336c1ed8c752c890,\n 0xcd4a67c23974b18a, 0x20dbbda3d4e56beb, 0x1385a5f1e7bb73b9, 0xfe147f900a2aa9d8,\n 0x753995558107431d, 0x98a84f346c96997c, 0xabf657665fc8812e, 0x46678d07b2595b4f,\n 0x8394ea2e77aa3c66, 0x6e05304f9a3be607, 0x5d5b281da965fe55, 0xb0caf27c44f42434,\n 0x3be718b9cfd9cef1, 0xd676c2d822481490, 0xe528da8a11160cc2, 0x8b900ebfc87d6a3,\n 0xf69f79f102a1afb9, 0x1b0ea390ef3075d8, 0x2850bbc2dc6e6d8a, 0xc5c161a331ffb7eb,\n 0x4eec8b66bad25d2e, 0xa37d51075743874f, 0x90234955641d9f1d, 0x7db29334898c457c,\n 0x6983cd909dbd1bd8, 0x841217f1702cc1b9, 0xb74c0fa34372d9eb, 0x5addd5c2aee3038a,\n 0xd1f03f0725cee94f, 0x3c61e566c85f332e, 0xf3ffd34fb012b7c, 0xe2ae27551690f11d,\n 0x1c885e4fe8b68807, 0xf119842e05275266, 0xc2479c7c36794a34, 0x2fd6461ddbe89055,\n 0xa4fbacd850c57a90, 0x496a76b9bd54a0f1, 0x7a346eeb8e0ab8a3, 0x97a5b48a639b62c2,\n 0xcb567ba500000000, 0x5816fa1e934081bb, 0xe83b0e22236d7587, 0x7b7b8f99b02df43c,\n 0x8d8c90ab46daeb0e, 0x1ecc1110d59a6ab5, 0xaee1e52c65b79e89, 0x3da16497f6f71f32,\n 0x46e3adb98db5d61c, 0xd5a32c021ef557a7, 0x658ed83eaed8a39b, 0xf6ce59853d982220,\n 0x3946b7cb6f3d12, 0x9379c70c582fbca9, 0x23543330e8024895, 0xb014b28b7b42c92e,\n 0xd5d1a16c1e87dac9, 0x469120d78dc75b72, 0xf6bcd4eb3deaaf4e, 0x65fc5550aeaa2ef5,\n 0x930b4a62585d31c7, 0x4bcbd9cb1db07c, 0xb0663fe57b304440, 0x2326be5ee870c5fb,\n 0x5864777093320cd5, 0xcb24f6cb00728d6e, 0x7b0902f7b05f7952, 0xe849834c231ff8e9,\n 0x1ebe9c7ed5e8e7db, 0x8dfe1dc546a86660, 0x3dd3e9f9f685925c, 0xae93684265c513e7,\n 0xf659ce373d0fb592, 0x65194f8cae4f3429, 0xd534bbb01e62c015, 0x46743a0b8d2241ae,\n 0xb08325397bd55e9c, 0x23c3a482e895df27, 0x93ee50be58b82b1b, 0xaed105cbf8aaa0,\n 0x7bec182bb0ba638e, 0xe8ac999023fae235, 0x58816dac93d71609, 0xcbc1ec17009797b2,\n 0x3d36f325f6608880, 0xae76729e6520093b, 0x1e5b86a2d50dfd07, 0x8d1b0719464d7cbc,\n 0xe8de14fe23886f5b, 0x7b9e9545b0c8eee0, 0xcbb3617900e51adc, 0x58f3e0c293a59b67,\n 0xae04fff065528455, 0x3d447e4bf61205ee, 0x8d698a77463ff1d2, 0x1e290bccd57f7069,\n 0x656bc2e2ae3db947, 0xf62b43593d7d38fc, 0x4606b7658d50ccc0, 0xd54636de1e104d7b,\n 0x23b129ece8e75249, 0xb0f1a8577ba7d3f2, 0xdc5c6bcb8a27ce, 0x939cddd058caa675,\n 0xb14910817a1f6b24, 0x2209913ae95fea9f, 0x9224650659721ea3, 0x164e4bdca329f18,\n 0xf793fb8f3cc5802a, 0x64d37a34af850191, 0xd4fe8e081fa8f5ad, 0x47be0fb38ce87416,\n 0x3cfcc69df7aabd38, 0xafbc472664ea3c83, 0x1f91b31ad4c7c8bf, 0x8cd132a147874904,\n 0x7a262d93b1705636, 0xe966ac282230d78d, 0x594b5814921d23b1, 0xca0bd9af015da20a,\n 0xafceca486498b1ed, 0x3c8e4bf3f7d83056, 0x8ca3bfcf47f5c46a, 0x1fe33e74d4b545d1,\n 0xe914214622425ae3, 0x7a54a0fdb102db58, 0xca7954c1012f2f64, 0x5939d57a926faedf,\n 0x227b1c54e92d67f1, 0xb13b9def7a6de64a, 0x11669d3ca401276, 0x9256e868590093cd,\n 0x64a1f75aaff78cff, 0xf7e176e13cb70d44, 0x47cc82dd8c9af978, 0xd48c03661fda78c3,\n 0x8c46a5134710deb6, 0x1f0624a8d4505f0d, 0xaf2bd094647dab31, 0x3c6b512ff73d2a8a,\n 0xca9c4e1d01ca35b8, 0x59dccfa6928ab403, 0xe9f13b9a22a7403f, 0x7ab1ba21b1e7c184,\n 0x1f3730fcaa508aa, 0x92b3f2b459e58911, 0x229e0688e9c87d2d, 0xb1de87337a88fc96,\n 0x472998018c7fe3a4, 0xd46919ba1f3f621f, 0x6444ed86af129623, 0xf7046c3d3c521798,\n 0x92c17fda5997047f, 0x181fe61cad785c4, 0xb1ac0a5d7afa71f8, 0x22ec8be6e9baf043,\n 0xd41b94d41f4def71, 0x475b156f8c0d6eca, 0xf776e1533c209af6, 0x643660e8af601b4d,\n 0x1f74a9c6d422d263, 0x8c34287d476253d8, 0x3c19dc41f74fa7e4, 0xaf595dfa640f265f,\n 0x59ae42c892f8396d, 0xcaeec37301b8b8d6, 0x7ac3374fb1954cea, 0xe983b6f422d5cd51,\n 0x9771f7c100000000, 0xbc7e6eb22b0f9973, 0xc16ec527561f32e6, 0xea615c547d10ab95,\n 0x3b4f920dac3e65cc, 0x10400b7e8731fcbf, 0x6d50a0ebfa21572a, 0x465f3998d12ece59,\n 0xcae14aa85d90bd69, 0xe1eed3db769f241a, 0x9cfe784e0b8f8f8f, 0xb7f1e13d208016fc,\n 0x66df2f64f1aed8a5, 0x4dd0b617daa141d6, 0x30c01d82a7b1ea43, 0x1bcf84f18cbe7330,\n 0x2c508d13bb217ad2, 0x75f1460902ee3a1, 0x7a4fbff5ed3e4834, 0x51402686c631d147,\n 0x806ee8df171f1f1e, 0xab6171ac3c10866d, 0xd671da3941002df8, 0xfd7e434a6a0fb48b,\n 0x71c0307ae6b1c7bb, 0x5acfa909cdbe5ec8, 0x27df029cb0aef55d, 0xcd09bef9ba16c2e,\n 0xddfe55b64a8fa277, 0xf6f1ccc561803b04, 0x8be167501c909091, 0xa0eefe23379f09e2,\n 0xe4df749473ae8355, 0xcfd0ede758a11a26, 0xb2c0467225b1b1b3, 0x99cfdf010ebe28c0,\n 0x48e11158df90e699, 0x63ee882bf49f7fea, 0x1efe23be898fd47f, 0x35f1bacda2804d0c,\n 0xb94fc9fd2e3e3e3c, 0x9240508e0531a74f, 0xef50fb1b78210cda, 0xc45f6268532e95a9,\n 0x1571ac3182005bf0, 0x3e7e3542a90fc283, 0x436e9ed7d41f6916, 0x686107a4ff10f065,\n 0x5ffe0e46c88ff987, 0x74f19735e38060f4, 0x9e13ca09e90cb61, 0x22eea5d3b59f5212,\n 0xf3c06b8a64b19c4b, 0xd8cff2f94fbe0538, 0xa5df596c32aeaead, 0x8ed0c01f19a137de,\n 0x26eb32f951f44ee, 0x29612a5cbe10dd9d, 0x547181c9c3007608, 0x7f7e18bae80fef7b,\n 0xae50d6e339212122, 0x855f4f90122eb851, 0xf84fe4056f3e13c4, 0xd3407d7644318ab7,\n 0x702cf16be75d06aa, 0x5b236818cc529fd9, 0x2633c38db142344c, 0xd3c5afe9a4dad3f,\n 0xdc1294a74b636366, 0xf71d0dd4606cfa15, 0x8a0da6411d7c5180, 0xa1023f323673c8f3,\n 0x2dbc4c02bacdbbc3, 0x6b3d57191c222b0, 0x7ba37ee4ecd28925, 0x50ace797c7dd1056,\n 0x818229ce16f3de0f, 0xaa8db0bd3dfc477c, 0xd79d1b2840ecece9, 0xfc92825b6be3759a,\n 0xcb0d8bb95c7c7c78, 0xe00212ca7773e50b, 0x9d12b95f0a634e9e, 0xb61d202c216cd7ed,\n 0x6733ee75f04219b4, 0x4c3c7706db4d80c7, 0x312cdc93a65d2b52, 0x1a2345e08d52b221,\n 0x969d36d001ecc111, 0xbd92afa32ae35862, 0xc082043657f3f3f7, 0xeb8d9d457cfc6a84,\n 0x3aa3531cadd2a4dd, 0x11acca6f86dd3dae, 0x6cbc61fafbcd963b, 0x47b3f889d0c20f48,\n 0x382723e94f385ff, 0x288deb4dbffc1c8c, 0x559d40d8c2ecb719, 0x7e92d9abe9e32e6a,\n 0xafbc17f238cde033, 0x84b38e8113c27940, 0xf9a325146ed2d2d5, 0xd2acbc6745dd4ba6,\n 0x5e12cf57c9633896, 0x751d5624e26ca1e5, 0x80dfdb19f7c0a70, 0x230264c2b4739303,\n 0xf22caa9b655d5d5a, 0xd92333e84e52c429, 0xa433987d33426fbc, 0x8f3c010e184df6cf,\n 0xb8a308ec2fd2ff2d, 0x93ac919f04dd665e, 0xeebc3a0a79cdcdcb, 0xc5b3a37952c254b8,\n 0x149d6d2083ec9ae1, 0x3f92f453a8e30392, 0x42825fc6d5f3a807, 0x698dc6b5fefc3174,\n 0xe533b58572424244, 0xce3c2cf6594ddb37, 0xb32c8763245d70a2, 0x98231e100f52e9d1,\n 0x490dd049de7c2788, 0x6202493af573befb, 0x1f12e2af8863156e, 0x341d7bdca36c8c1d,\n 0x3171d43000000000, 0x53927c5062e3a860, 0xf4b684f0c5c750c0, 0x96552c90a724f8a0,\n 0xbf1303418e62d771, 0xddf0ab21ec817f11, 0x7ad453814ba587b1, 0x1837fbe129462fd1,\n 0x28580c231929d813, 0x4abba4437bca7073, 0xed9f5ce3dcee88d3, 0x8f7cf483be0d20b3,\n 0xa63adb52974b0f62, 0xc4d97332f5a8a702, 0x63fd8b92528c5fa2, 0x11e23f2306ff7c2,\n 0x32264163253b026, 0x61c1cc7650b01846, 0xc6e534d6f794e0e6, 0xa4069cb695774886,\n 0x8d40b367bc316757, 0xefa31b07ded2cf37, 0x4887e3a779f63797, 0x2a644bc71b159ff7,\n 0x1a0bbc052b7a6835, 0x78e814654999c055, 0xdfccecc5eebd38f5, 0xbd2f44a58c5e9095,\n 0x94696b74a518bf44, 0xf68ac314c7fb1724, 0x51ae3bb460dfef84, 0x334d93d4023c47e4,\n 0x55d6b47c64a7604c, 0x37351c1c0644c82c, 0x9011e4bca160308c, 0xf2f24cdcc38398ec,\n 0xdbb4630deac5b73d, 0xb957cb6d88261f5d, 0x1e7333cd2f02e7fd, 0x7c909bad4de14f9d,\n 0x4cff6c6f7d8eb85f, 0x2e1cc40f1f6d103f, 0x89383cafb849e89f, 0xebdb94cfdaaa40ff,\n 0xc29dbb1ef3ec6f2e, 0xa07e137e910fc74e, 0x75aebde362b3fee, 0x65b943be54c8978e,\n 0x6785045a56f4d06a, 0x566ac3a3417780a, 0xa242549a933380aa, 0xc0a1fcfaf1d028ca,\n 0xe9e7d32bd896071b, 0x8b047b4bba75af7b, 0x2c2083eb1d5157db, 0x4ec32b8b7fb2ffbb,\n 0x7eacdc494fdd0879, 0x1c4f74292d3ea019, 0xbb6b8c898a1a58b9, 0xd98824e9e8f9f0d9,\n 0xf0ce0b38c1bfdf08, 0x922da358a35c7768, 0x35095bf804788fc8, 0x57eaf398669b27a8,\n 0xf83f14a8c94ec098, 0x9adcbcc8abad68f8, 0x3df844680c899058, 0x5f1bec086e6a3838,\n 0x765dc3d9472c17e9, 0x14be6bb925cfbf89, 0xb39a931982eb4729, 0xd1793b79e008ef49,\n 0xe116ccbbd067188b, 0x83f564dbb284b0eb, 0x24d19c7b15a0484b, 0x4632341b7743e02b,\n 0x6f741bca5e05cffa, 0xd97b3aa3ce6679a, 0xaab34b0a9bc29f3a, 0xc850e36af921375a,\n 0xca6ca48efb1d70be, 0xa88f0cee99fed8de, 0xfabf44e3eda207e, 0x6d485c2e5c39881e,\n 0x440e73ff757fa7cf, 0x26eddb9f179c0faf, 0x81c9233fb0b8f70f, 0xe32a8b5fd25b5f6f,\n 0xd3457c9de234a8ad, 0xb1a6d4fd80d700cd, 0x16822c5d27f3f86d, 0x7461843d4510500d,\n 0x5d27abec6c567fdc, 0x3fc4038c0eb5d7bc, 0x98e0fb2ca9912f1c, 0xfa03534ccb72877c,\n 0x9c9874e4ade9a0d4, 0xfe7bdc84cf0a08b4, 0x595f2424682ef014, 0x3bbc8c440acd5874,\n 0x12faa395238b77a5, 0x70190bf54168dfc5, 0xd73df355e64c2765, 0xb5de5b3584af8f05,\n 0x85b1acf7b4c078c7, 0xe7520497d623d0a7, 0x4076fc3771072807, 0x2295545713e48067,\n 0xbd37b863aa2afb6, 0x6930d3e6584107d6, 0xce142b46ff65ff76, 0xacf783269d865716,\n 0xaecbc4c29fba10f2, 0xcc286ca2fd59b892, 0x6b0c94025a7d4032, 0x9ef3c62389ee852,\n 0x20a913b311d8c783, 0x424abbd3733b6fe3, 0xe56e4373d41f9743, 0x878deb13b6fc3f23,\n 0xb7e21cd18693c8e1, 0xd501b4b1e4706081, 0x72254c1143549821, 0x10c6e47121b73041,\n 0x3980cba008f11f90, 0x5b6363c06a12b7f0, 0xfc479b60cd364f50, 0x9ea43300afd5e730,\n 0x30d2386500000000, 0x517648af61a470ca, 0xf39ad9f1c348e194, 0x923ea93ba2ec915e,\n 0xb3af8dbc837db5d9, 0xd20bfd76e2d9c513, 0x70e76c284035544d, 0x11431ce221912487,\n 0x33c5252603171d43, 0x526155ec62b36d89, 0xf08dc4b2c05ffcd7, 0x9129b478a1fb8c1d,\n 0xb0b890ff806aa89a, 0xd11ce035e1ced850, 0x73f0716b4322490e, 0x125401a1228639c4,\n 0x36fc02e3062e3a86, 0x57587229678a4a4c, 0xf5b4e377c566db12, 0x941093bda4c2abd8,\n 0xb581b73a85538f5f, 0xd425c7f0e4f7ff95, 0x76c956ae461b6ecb, 0x176d266427bf1e01,\n 0x35eb1fa0053927c5, 0x544f6f6a649d570f, 0xf6a3fe34c671c651, 0x97078efea7d5b69b,\n 0xb696aa798644921c, 0xd732dab3e7e0e2d6, 0x75de4bed450c7388, 0x147a3b2724a80342,\n 0x3c8e4d690c5c750c, 0x5d2a3da36df805c6, 0xffc6acfdcf149498, 0x9e62dc37aeb0e452,\n 0xbff3f8b08f21c0d5, 0xde57887aee85b01f, 0x7cbb19244c692141, 0x1d1f69ee2dcd518b,\n 0x3f99502a0f4b684f, 0x5e3d20e06eef1885, 0xfcd1b1becc0389db, 0x9d75c174ada7f911,\n 0xbce4e5f38c36dd96, 0xdd409539ed92ad5c, 0x7fac04674f7e3c02, 0x1e0874ad2eda4cc8,\n 0x3aa077ef0a724f8a, 0x5b0407256bd63f40, 0xf9e8967bc93aae1e, 0x984ce6b1a89eded4,\n 0xb9ddc236890ffa53, 0xd879b2fce8ab8a99, 0x7a9523a24a471bc7, 0x1b3153682be36b0d,\n 0x39b76aac096552c9, 0x58131a6668c12203, 0xfaff8b38ca2db35d, 0x9b5bfbf2ab89c397,\n 0xbacadf758a18e710, 0xdb6eafbfebbc97da, 0x79823ee149500684, 0x18264e2b28f4764e,\n 0x286ad27d18b8ea18, 0x49cea2b7791c9ad2, 0xeb2233e9dbf00b8c, 0x8a864323ba547b46,\n 0xab1767a49bc55fc1, 0xcab3176efa612f0b, 0x685f8630588dbe55, 0x9fbf6fa3929ce9f,\n 0x2b7dcf3e1baff75b, 0x4ad9bff47a0b8791, 0xe8352eaad8e716cf, 0x89915e60b9436605,\n 0xa8007ae798d24282, 0xc9a40a2df9763248, 0x6b489b735b9aa316, 0xaecebb93a3ed3dc,\n 0x2e44e8fb1e96d09e, 0x4fe098317f32a054, 0xed0c096fddde310a, 0x8ca879a5bc7a41c0,\n 0xad395d229deb6547, 0xcc9d2de8fc4f158d, 0x6e71bcb65ea384d3, 0xfd5cc7c3f07f419,\n 0x2d53f5b81d81cddd, 0x4cf785727c25bd17, 0xee1b142cdec92c49, 0x8fbf64e6bf6d5c83,\n 0xae2e40619efc7804, 0xcf8a30abff5808ce, 0x6d66a1f55db49990, 0xcc2d13f3c10e95a,\n 0x2436a77114e49f14, 0x4592d7bb7540efde, 0xe77e46e5d7ac7e80, 0x86da362fb6080e4a,\n 0xa74b12a897992acd, 0xc6ef6262f63d5a07, 0x6403f33c54d1cb59, 0x5a783f63575bb93,\n 0x2721ba3217f38257, 0x4685caf87657f29d, 0xe4695ba6d4bb63c3, 0x85cd2b6cb51f1309,\n 0xa45c0feb948e378e, 0xc5f87f21f52a4744, 0x6714ee7f57c6d61a, 0x6b09eb53662a6d0,\n 0x22189df712caa592, 0x43bced3d736ed558, 0xe1507c63d1824406, 0x80f40ca9b02634cc,\n 0xa165282e91b7104b, 0xc0c158e4f0136081, 0x622dc9ba52fff1df, 0x389b970335b8115,\n 0x210f80b411ddb8d1, 0x40abf07e7079c81b, 0xe2476120d2955945, 0x83e311eab331298f,\n 0xa272356d92a00d08, 0xc3d645a7f3047dc2, 0x613ad4f951e8ec9c, 0x9ea433304c9c56,\n 0x5407554600000000, 0xfc09ffcaa80eaa8c, 0x1f676af55f123e9, 0xa9f8dc23fdff8965,\n 0xffe51294abe247d2, 0x57ebb81803eced5e, 0xaa14317dfe13643b, 0x21a9bf1561dceb7,\n 0x62fac135228f955, 0xae21069ffa2653d9, 0x53de8ffa07d9dabc, 0xfbd02576afd77030,\n 0xadcdebc1f9cabe87, 0x5c3414d51c4140b, 0xf83cc828ac3b9d6e, 0x503262a4043537e2,\n 0xf056a7eca451f2aa, 0x58580d600c5f5826, 0xa5a78405f1a0d143, 0xda92e8959ae7bcf,\n 0x5bb4e03e0fb3b578, 0xf3ba4ab2a7bd1ff4, 0xe45c3d75a429691, 0xa64b695bf24c3c1d,\n 0xa27e5eb9f6790bff, 0xa70f4355e77a173, 0xf78f7d50a3882816, 0x5f81d7dc0b86829a,\n 0x99c196b5d9b4c2d, 0xa192b3e7f595e6a1, 0x5c6d3a82086a6fc4, 0xf463900ea064c548,\n 0x1948c6e34d4f93a5, 0xb1466c6fe5413929, 0x4cb9e50a18beb04c, 0xe4b74f86b0b01ac0,\n 0xb2aa8131e6add477, 0x1aa42bbd4ea37efb, 0xe75ba2d8b35cf79e, 0x4f5508541b525d12,\n 0x4b603fb61f676af0, 0xe36e953ab769c07c, 0x1e911c5f4a964919, 0xb69fb6d3e298e395,\n 0xe0827864b4852d22, 0x488cd2e81c8b87ae, 0xb5735b8de1740ecb, 0x1d7df101497aa447,\n 0xbd193449e91e610f, 0x15179ec54110cb83, 0xe8e817a0bcef42e6, 0x40e6bd2c14e1e86a,\n 0x16fb739b42fc26dd, 0xbef5d917eaf28c51, 0x430a5072170d0534, 0xeb04fafebf03afb8,\n 0xef31cd1cbb36985a, 0x473f6790133832d6, 0xbac0eef5eec7bbb3, 0x12ce447946c9113f,\n 0x44d38ace10d4df88, 0xecdd2042b8da7504, 0x1122a9274525fc61, 0xb92c03abed2b56ed,\n 0xce98720c9a9f274a, 0x6696d88032918dc6, 0x9b6951e5cf6e04a3, 0x3367fb696760ae2f,\n 0x657a35de317d6098, 0xcd749f529973ca14, 0x308b1637648c4371, 0x9885bcbbcc82e9fd,\n 0x9cb08b59c8b7de1f, 0x34be21d560b97493, 0xc941a8b09d46fdf6, 0x614f023c3548577a,\n 0x3752cc8b635599cd, 0x9f5c6607cb5b3341, 0x62a3ef6236a4ba24, 0xcaad45ee9eaa10a8,\n 0x6ac980a63eced5e0, 0xc2c72a2a96c07f6c, 0x3f38a34f6b3ff609, 0x973609c3c3315c85,\n 0xc12bc774952c9232, 0x69256df83d2238be, 0x94dae49dc0ddb1db, 0x3cd44e1168d31b57,\n 0x38e179f36ce62cb5, 0x90efd37fc4e88639, 0x6d105a1a39170f5c, 0xc51ef0969119a5d0,\n 0x93033e21c7046b67, 0x3b0d94ad6f0ac1eb, 0xc6f21dc892f5488e, 0x6efcb7443afbe202,\n 0x83d7e1a9d7d0b4ef, 0x2bd94b257fde1e63, 0xd626c24082219706, 0x7e2868cc2a2f3d8a,\n 0x2835a67b7c32f33d, 0x803b0cf7d43c59b1, 0x7dc4859229c3d0d4, 0xd5ca2f1e81cd7a58,\n 0xd1ff18fc85f84dba, 0x79f1b2702df6e736, 0x840e3b15d0096e53, 0x2c0091997807c4df,\n 0x7a1d5f2e2e1a0a68, 0xd213f5a28614a0e4, 0x2fec7cc77beb2981, 0x87e2d64bd3e5830d,\n 0x2786130373814645, 0x8f88b98fdb8fecc9, 0x727730ea267065ac, 0xda799a668e7ecf20,\n 0x8c6454d1d8630197, 0x246afe5d706dab1b, 0xd99577388d92227e, 0x719bddb4259c88f2,\n 0x75aeea5621a9bf10, 0xdda040da89a7159c, 0x205fc9bf74589cf9, 0x88516333dc563675,\n 0xde4cad848a4bf8c2, 0x764207082245524e, 0x8bbd8e6ddfbadb2b, 0x23b324e177b471a7,\n 0x678efd0100000000, 0xa8930703cf1dfa02, 0xfc597ff49bd782f5, 0x334485f654ca78f7,\n 0x55cd8e1a3243731b, 0x9ad07418fd5e8919, 0xce1a0cefa994f1ee, 0x107f6ed66890bec,\n 0x3081b376486e636, 0xcc15e135ab9b1c34, 0x98df99c2ff5164c3, 0x57c263c0304c9ec1,\n 0x314b682c56c5952d, 0xfe56922e99d86f2f, 0xaa9cead9cd1217d8, 0x658110db020fedda,\n 0xae83316dc90dcc6c, 0x619ecb6f0610366e, 0x3554b39852da4e99, 0xfa49499a9dc7b49b,\n 0x9cc04276fb4ebf77, 0x53ddb87434534575, 0x717c08360993d82, 0xc80a3a81af84c780,\n 0xca05d75bad8b2a5a, 0x5182d596296d058, 0x51d255ae365ca8af, 0x9ecfafacf94152ad,\n 0xf846a4409fc85941, 0x375b5e4250d5a343, 0x639126b5041fdbb4, 0xac8cdcb7cb0221b6,\n 0xf079132897f7ee29, 0x3f64e92a58ea142b, 0x6bae91dd0c206cdc, 0xa4b36bdfc33d96de,\n 0xc23a6033a5b49d32, 0xd279a316aa96730, 0x59ede2c63e631fc7, 0x96f018c4f17ee5c5,\n 0x94fff51ef371081f, 0x5be20f1c3c6cf21d, 0xf2877eb68a68aea, 0xc0358de9a7bb70e8,\n 0xa6bc8605c1327b04, 0x69a17c070e2f8106, 0x3d6b04f05ae5f9f1, 0xf276fef295f803f3,\n 0x3974df445efa2245, 0xf669254691e7d847, 0xa2a35db1c52da0b0, 0x6dbea7b30a305ab2,\n 0xb37ac5f6cb9515e, 0xc42a565da3a4ab5c, 0x90e02eaaf76ed3ab, 0x5ffdd4a8387329a9,\n 0x5df239723a7cc473, 0x92efc370f5613e71, 0xc625bb87a1ab4686, 0x93841856eb6bc84,\n 0x6fb14a69083fb768, 0xa0acb06bc7224d6a, 0xf466c89c93e8359d, 0x3b7b329e5cf5cf9f,\n 0x4d8d57a22a03aaa3, 0x8290ada0e51e50a1, 0xd65ad557b1d42856, 0x19472f557ec9d254,\n 0x7fce24b91840d9b8, 0xb0d3debbd75d23ba, 0xe419a64c83975b4d, 0x2b045c4e4c8aa14f,\n 0x290bb1944e854c95, 0xe6164b968198b697, 0xb2dc3361d552ce60, 0x7dc1c9631a4f3462,\n 0x1b48c28f7cc63f8e, 0xd455388db3dbc58c, 0x809f407ae711bd7b, 0x4f82ba78280c4779,\n 0x84809bcee30e66cf, 0x4b9d61cc2c139ccd, 0x1f57193b78d9e43a, 0xd04ae339b7c41e38,\n 0xb6c3e8d5d14d15d4, 0x79de12d71e50efd6, 0x2d146a204a9a9721, 0xe209902285876d23,\n 0xe0067df8878880f9, 0x2f1b87fa48957afb, 0x7bd1ff0d1c5f020c, 0xb4cc050fd342f80e,\n 0xd2450ee3b5cbf3e2, 0x1d58f4e17ad609e0, 0x49928c162e1c7117, 0x868f7614e1018b15,\n 0xda7ab98bbdf4448a, 0x1567438972e9be88, 0x41ad3b7e2623c67f, 0x8eb0c17ce93e3c7d,\n 0xe839ca908fb73791, 0x2724309240aacd93, 0x73ee48651460b564, 0xbcf3b267db7d4f66,\n 0xbefc5fbdd972a2bc, 0x71e1a5bf166f58be, 0x252bdd4842a52049, 0xea36274a8db8da4b,\n 0x8cbf2ca6eb31d1a7, 0x43a2d6a4242c2ba5, 0x1768ae5370e65352, 0xd8755451bffba950,\n 0x137775e774f988e6, 0xdc6a8fe5bbe472e4, 0x88a0f712ef2e0a13, 0x47bd0d102033f011,\n 0x213406fc46bafbfd, 0xee29fcfe89a701ff, 0xbae38409dd6d7908, 0x75fe7e0b1270830a,\n 0x77f193d1107f6ed0, 0xb8ec69d3df6294d2, 0xec2611248ba8ec25, 0x233beb2644b51627,\n 0x45b2e0ca223c1dcb, 0x8aaf1ac8ed21e7c9, 0xde65623fb9eb9f3e, 0x1178983d76f6653c,\n 0xf20c0dfe00000000, 0x13f860f3e1f46d0d, 0x3408a115c604aceb, 0xd5fccc1827f0c1e6,\n 0x7be922d989e52f27, 0x9a1d4fd46811422a, 0xbded8e324fe183cc, 0x5c19e33fae15eec1,\n 0xe42a2541162628bf, 0x5de484cf7d245b2, 0x222e89aad0228454, 0xc3dae4a731d6e959,\n 0x6dcf0a669fc30798, 0x8c3b676b7e376a95, 0xabcba68d59c7ab73, 0x4a3fcb80b833c67e,\n 0xde405c802c4c517e, 0x3fb4318dcdb83c73, 0x1844f06bea48fd95, 0xf9b09d660bbc9098,\n 0x57a573a7a5a97e59, 0xb6511eaa445d1354, 0x91a1df4c63add2b2, 0x7055b2418259bfbf,\n 0xc866743f3a6a79c1, 0x29921932db9e14cc, 0xe62d8d4fc6ed52a, 0xef96b5d91d9ab827,\n 0x41835b18b38f56e6, 0xa0773615527b3beb, 0x8787f7f3758bfa0d, 0x66739afe947f9700,\n 0xaa94af025898a2fc, 0x4b60c20fb96ccff1, 0x6c9003e99e9c0e17, 0x8d646ee47f68631a,\n 0x23718025d17d8ddb, 0xc285ed283089e0d6, 0xe5752cce17792130, 0x48141c3f68d4c3d,\n 0xbcb287bd4ebe8a43, 0x5d46eab0af4ae74e, 0x7ab62b5688ba26a8, 0x9b42465b694e4ba5,\n 0x3557a89ac75ba564, 0xd4a3c59726afc869, 0xf3530471015f098f, 0x12a7697ce0ab6482,\n 0x86d8fe7c74d4f382, 0x672c937195209e8f, 0x40dc5297b2d05f69, 0xa1283f9a53243264,\n 0xf3dd15bfd31dca5, 0xeec9bc561cc5b1a8, 0xc9397db03b35704e, 0x28cd10bddac11d43,\n 0x90fed6c362f2db3d, 0x710abbce8306b630, 0x56fa7a28a4f677d6, 0xb70e172545021adb,\n 0x191bf9e4eb17f41a, 0xf8ef94e90ae39917, 0xdf1f550f2d1358f1, 0x3eeb3802cce735fc,\n 0x433d4806b13145f8, 0xa2c9250b50c528f5, 0x8539e4ed7735e913, 0x64cd89e096c1841e,\n 0xcad8672138d46adf, 0x2b2c0a2cd92007d2, 0xcdccbcafed0c634, 0xed28a6c71f24ab39,\n 0x551b60b9a7176d47, 0xb4ef0db446e3004a, 0x931fcc526113c1ac, 0x72eba15f80e7aca1,\n 0xdcfe4f9e2ef24260, 0x3d0a2293cf062f6d, 0x1afae375e8f6ee8b, 0xfb0e8e7809028386,\n 0x6f7119789d7d1486, 0x8e8574757c89798b, 0xa975b5935b79b86d, 0x4881d89eba8dd560,\n 0xe694365f14983ba1, 0x7605b52f56c56ac, 0x20909ab4d29c974a, 0xc164f7b93368fa47,\n 0x795731c78b5b3c39, 0x98a35cca6aaf5134, 0xbf539d2c4d5f90d2, 0x5ea7f021acabfddf,\n 0xf0b21ee002be131e, 0x114673ede34a7e13, 0x36b6b20bc4babff5, 0xd742df06254ed2f8,\n 0x1ba5eafae9a9e704, 0xfa5187f7085d8a09, 0xdda146112fad4bef, 0x3c552b1cce5926e2,\n 0x9240c5dd604cc823, 0x73b4a8d081b8a52e, 0x54446936a64864c8, 0xb5b0043b47bc09c5,\n 0xd83c245ff8fcfbb, 0xec77af481e7ba2b6, 0xcb876eae398b6350, 0x2a7303a3d87f0e5d,\n 0x8466ed62766ae09c, 0x6592806f979e8d91, 0x42624189b06e4c77, 0xa3962c84519a217a,\n 0x37e9bb84c5e5b67a, 0xd61dd6892411db77, 0xf1ed176f03e11a91, 0x10197a62e215779c,\n 0xbe0c94a34c00995d, 0x5ff8f9aeadf4f450, 0x780838488a0435b6, 0x99fc55456bf058bb,\n 0x21cf933bd3c39ec5, 0xc03bfe363237f3c8, 0xe7cb3fd015c7322e, 0x63f52ddf4335f23,\n 0xa82abc1c5a26b1e2, 0x49ded111bbd2dcef, 0x6e2e10f79c221d09, 0x8fda7dfa7dd67004,\n }\n};\n\nstatic union {\n uint32_t dword_table[4][256];\n uint64_t qword_array[512];\n} long_shifts = {\n .qword_array = {\n 0xe040e0ac00000000, 0x252d5705c56db7a9, 0x6f77f90f8f3719a3, 0xaa1a4ea64a5aae0a,\n 0xfbc2a51b1b8245b7, 0x3eaf12b2deeff21e, 0x74f5bcb894b55c14, 0xb1980b1151d8ebbd,\n 0xd7446bc237048b6e, 0x1229dc6bf2693cc7, 0x58737261b83392cd, 0x9d1ec5c87d5e2564,\n 0xccc62e752c86ced9, 0x9ab99dce9eb7970, 0x43f137d6a3b1d77a, 0x869c807f66dc60d3,\n 0x8e49f6706e0916dc, 0x4b2441d9ab64a175, 0x17eefd3e13e0f7f, 0xc413587a2453b8d6,\n 0x95cbb3c7758b536b, 0x50a6046eb0e6e4c2, 0x1afcaa64fabc4ac8, 0xdf911dcd3fd1fd61,\n 0xb94d7d1e590d9db2, 0x7c20cab79c602a1b, 0x367a64bdd63a8411, 0xf317d314135733b8,\n 0xa2cf38a9428fd805, 0x67a28f0087e26fac, 0x2df8210acdb8c1a6, 0xe89596a308d5760f,\n 0x3c52cd14dc122db8, 0xf93f7abd197f9a11, 0xb365d4b75325341b, 0x7608631e964883b2,\n 0x27d088a3c790680f, 0xe2bd3f0a02fddfa6, 0xa8e7910048a771ac, 0x6d8a26a98dcac605,\n 0xb56467aeb16a6d6, 0xce3bf1d32e7b117f, 0x84615fd96421bf75, 0x410ce870a14c08dc,\n 0x10d403cdf094e361, 0xd5b9b46435f954c8, 0x9fe31a6e7fa3fac2, 0x5a8eadc7bace4d6b,\n 0x525bdbc8b21b3b64, 0x97366c6177768ccd, 0xdd6cc26b3d2c22c7, 0x180175c2f841956e,\n 0x49d99e7fa9997ed3, 0x8cb429d66cf4c97a, 0xc6ee87dc26ae6770, 0x3833075e3c3d0d9,\n 0x655f50a6851fb00a, 0xa032e70f407207a3, 0xea6849050a28a9a9, 0x2f05feaccf451e00,\n 0x7edd15119e9df5bd, 0xbbb0a2b85bf04214, 0xf1ea0cb211aaec1e, 0x3487bb1bd4c75bb7,\n 0x5d88cd2dbdc82d81, 0x98e57a8478a59a28, 0xd2bfd48e32ff3422, 0x17d26327f792838b,\n 0x460a889aa64a6836, 0x83673f336327df9f, 0xc93d9139297d7195, 0xc502690ec10c63c,\n 0x6a8c46438acca6ef, 0xafe1f1ea4fa11146, 0xe5bb5fe005fbbf4c, 0x20d6e849c09608e5,\n 0x710e03f4914ee358, 0xb463b45d542354f1, 0xfe391a571e79fafb, 0x3b54adfedb144d52,\n 0x3381dbf1d3c13b5d, 0xf6ec6c5816ac8cf4, 0xbcb6c2525cf622fe, 0x79db75fb999b9557,\n 0x28039e46c8437eea, 0xed6e29ef0d2ec943, 0xa73487e547746749, 0x6259304c8219d0e0,\n 0x485509fe4c5b033, 0xc1e8e73621a8079a, 0x8bb2493c6bf2a990, 0x4edffe95ae9f1e39,\n 0x1f071528ff47f584, 0xda6aa2813a2a422d, 0x90300c8b7070ec27, 0x555dbb22b51d5b8e,\n 0x819ae09561da0039, 0x44f7573ca4b7b790, 0xeadf936eeed199a, 0xcbc04e9f2b80ae33,\n 0x9a18a5227a58458e, 0x5f75128bbf35f227, 0x152fbc81f56f5c2d, 0xd0420b283002eb84,\n 0xb69e6bfb56de8b57, 0x73f3dc5293b33cfe, 0x39a97258d9e992f4, 0xfcc4c5f11c84255d,\n 0xad1c2e4c4d5ccee0, 0x687199e588317949, 0x222b37efc26bd743, 0xe7468046070660ea,\n 0xef93f6490fd316e5, 0x2afe41e0cabea14c, 0x60a4efea80e40f46, 0xa5c958434589b8ef,\n 0xf411b3fe14515352, 0x317c0457d13ce4fb, 0x7b26aa5d9b664af1, 0xbe4b1df45e0bfd58,\n 0xd8977d2738d79d8b, 0x1dfaca8efdba2a22, 0x57a06484b7e08428, 0x92cdd32d728d3381,\n 0xc31538902355d83c, 0x6788f39e6386f95, 0x4c222133ac62c19f, 0x894f969a690f7636,\n 0x7e7c2df300000000, 0x82847615fcf85be6, 0x8260eccefc1cc13d, 0x7e98b72800e49adb,\n 0x83a9d978fdd5f48b, 0x7f51829e012daf6d, 0x7fb5184501c935b6, 0x834d43a3fd316e50,\n 0x803bb214fe479fe7, 0x7cc3e9f202bfc401, 0x7c277329025b5eda, 0x80df28cffea3053c,\n 0x7dee469f03926b6c, 0x81161d79ff6a308a, 0x81f287a2ff8eaa51, 0x7d0adc440376f1b7,\n 0x871f64ccf963493f, 0x7be73f2a059b12d9, 0x7b03a5f1057f8802, 0x87fbfe17f987d3e4,\n 0x7aca904704b6bdb4, 0x8632cba1f84ee652, 0x86d6517af8aa7c89, 0x7a2e0a9c0452276f,\n 0x7958fb2b0724d6d8, 0x85a0a0cdfbdc8d3e, 0x85443a16fb3817e5, 0x79bc61f007c04c03,\n 0x848d0fa0faf12253, 0x78755446060979b5, 0x7891ce9d06ede36e, 0x8469957bfa15b888,\n 0x8956c97cf72ae48f, 0x75ae929a0bd2bf69, 0x754a08410b3625b2, 0x89b253a7f7ce7e54,\n 0x74833df70aff1004, 0x887b6611f6074be2, 0x889ffccaf6e3d139, 0x7467a72c0a1b8adf,\n 0x7711569b096d7b68, 0x8be90d7df595208e, 0x8b0d97a6f571ba55, 0x77f5cc400989e1b3,\n 0x8ac4a210f4b88fe3, 0x763cf9f60840d405, 0x76d8632d08a44ede, 0x8a2038cbf45c1538,\n 0x703580430e49adb0, 0x8ccddba5f2b1f656, 0x8c29417ef2556c8d, 0x70d11a980ead376b,\n 0x8de074c8f39c593b, 0x71182f2e0f6402dd, 0x71fcb5f50f809806, 0x8d04ee13f378c3e0,\n 0x8e721fa4f00e3257, 0x728a44420cf669b1, 0x726ede990c12f36a, 0x8e96857ff0eaa88c,\n 0x73a7eb2f0ddbc6dc, 0x8f5fb0c9f1239d3a, 0x8fbb2a12f1c707e1, 0x734371f40d3f5c07,\n 0x95c5921cebb9bfef, 0x693dc9fa1741e409, 0x69d9532117a57ed2, 0x952108c7eb5d2534,\n 0x68106697166c4b64, 0x94e83d71ea941082, 0x940ca7aaea708a59, 0x68f4fc4c1688d1bf,\n 0x6b820dfb15fe2008, 0x977a561de9067bee, 0x979eccc6e9e2e135, 0x6b669720151abad3,\n 0x9657f970e82bd483, 0x6aafa29614d38f65, 0x6a4b384d143715be, 0x96b363abe8cf4e58,\n 0x6ca6db2312daf6d0, 0x905e80c5ee22ad36, 0x90ba1a1eeec637ed, 0x6c4241f8123e6c0b,\n 0x91732fa8ef0f025b, 0x6d8b744e13f759bd, 0x6d6fee951313c366, 0x9197b573efeb9880,\n 0x92e144c4ec9d6937, 0x6e191f22106532d1, 0x6efd85f91081a80a, 0x9205de1fec79f3ec,\n 0x6f34b04f11489dbc, 0x93cceba9edb0c65a, 0x93287172ed545c81, 0x6fd02a9411ac0767,\n 0x62ef76931c935b60, 0x9e172d75e06b0086, 0x9ef3b7aee08f9a5d, 0x620bec481c77c1bb,\n 0x9f3a8218e146afeb, 0x63c2d9fe1dbef40d, 0x632643251d5a6ed6, 0x9fde18c3e1a23530,\n 0x9ca8e974e2d4c487, 0x6050b2921e2c9f61, 0x60b428491ec805ba, 0x9c4c73afe2305e5c,\n 0x617d1dff1f01300c, 0x9d854619e3f96bea, 0x9d61dcc2e31df131, 0x619987241fe5aad7,\n 0x9b8c3face5f0125f, 0x6774644a190849b9, 0x6790fe9119ecd362, 0x9b68a577e5148884,\n 0x6659cb271825e6d4, 0x9aa190c1e4ddbd32, 0x9a450a1ae43927e9, 0x66bd51fc18c17c0f,\n 0x65cba04b1bb78db8, 0x9933fbade74fd65e, 0x99d76176e7ab4c85, 0x652f3a901b531763,\n 0x981e54c0e6627933, 0x64e60f261a9a22d5, 0x640295fd1a7eb80e, 0x98face1be686e3e8,\n 0xd29f092f00000000, 0x724d6d80a0d264af, 0x96d7b6804448bfaf, 0x3605d22fe49adb00,\n 0x5a0e767188917f5e, 0xfadc12de28431bf1, 0x1e46c9deccd9c0f1, 0xbe94ad716c0ba45e,\n 0xc651816214ce884d, 0x6683e5cdb41cece2, 0x82193ecd508637e2, 0x22cb5a62f054534d,\n 0x4ec0fe3c9c5ff713, 0xee129a933c8d93bc, 0xa884193d81748bc, 0xaa5a253c78c52c13,\n 0xfb0219b5299d109a, 0x5bd07d1a894f7435, 0xbf4aa61a6dd5af35, 0x1f98c2b5cd07cb9a,\n 0x739366eba10c6fc4, 0xd341024401de0b6b, 0x37dbd944e544d06b, 0x9709bdeb4596b4c4,\n 0xefcc91f83d5398d7, 0x4f1ef5579d81fc78, 0xab842e57791b2778, 0xb564af8d9c943d7,\n 0x675deea6b5c2e789, 0xc78f8a0915108326, 0x23155109f18a5826, 0x83c735a651583c89,\n 0x81a5281b533a2134, 0x21774cb4f3e8459b, 0xc5ed97b417729e9b, 0x653ff31bb7a0fa34,\n 0x9345745dbab5e6a, 0xa9e633ea7b793ac5, 0x4d7ce8ea9fe3e1c5, 0xedae8c453f31856a,\n 0x956ba05647f4a979, 0x35b9c4f9e726cdd6, 0xd1231ff903bc16d6, 0x71f17b56a36e7279,\n 0x1dfadf08cf65d627, 0xbd28bba76fb7b288, 0x59b260a78b2d6988, 0xf96004082bff0d27,\n 0xa83838817aa731ae, 0x8ea5c2eda755501, 0xec70872e3eef8e01, 0x4ca2e3819e3deaae,\n 0x20a947dff2364ef0, 0x807b237052e42a5f, 0x64e1f870b67ef15f, 0xc4339cdf16ac95f0,\n 0xbcf6b0cc6e69b9e3, 0x1c24d463cebbdd4c, 0xf8be0f632a21064c, 0x586c6bcc8af362e3,\n 0x3467cf92e6f8c6bd, 0x94b5ab3d462aa212, 0x702f703da2b07912, 0xd0fd149202621dbd,\n 0x74eb4b47a6744268, 0xd4392fe806a626c7, 0x30a3f4e8e23cfdc7, 0x9071904742ee9968,\n 0xfc7a34192ee53d36, 0x5ca850b68e375999, 0xb8328bb66aad8299, 0x18e0ef19ca7fe636,\n 0x6025c30ab2baca25, 0xc0f7a7a51268ae8a, 0x246d7ca5f6f2758a, 0x84bf180a56201125,\n 0xe8b4bc543a2bb57b, 0x4866d8fb9af9d1d4, 0xacfc03fb7e630ad4, 0xc2e6754deb16e7b,\n 0x5d765bdd8fe952f2, 0xfda43f722f3b365d, 0x193ee472cba1ed5d, 0xb9ec80dd6b7389f2,\n 0xd5e7248307782dac, 0x7535402ca7aa4903, 0x91af9b2c43309203, 0x317dff83e3e2f6ac,\n 0x49b8d3909b27dabf, 0xe96ab73f3bf5be10, 0xdf06c3fdf6f6510, 0xad2208907fbd01bf,\n 0xc129acce13b6a5e1, 0x61fbc861b364c14e, 0x8561136157fe1a4e, 0x25b377cef72c7ee1,\n 0x27d16a73f54e635c, 0x87030edc559c07f3, 0x6399d5dcb106dcf3, 0xc34bb17311d4b85c,\n 0xaf40152d7ddf1c02, 0xf927182dd0d78ad, 0xeb08aa823997a3ad, 0x4bdace2d9945c702,\n 0x331fe23ee180eb11, 0x93cd869141528fbe, 0x77575d91a5c854be, 0xd785393e051a3011,\n 0xbb8e9d606911944f, 0x1b5cf9cfc9c3f0e0, 0xffc622cf2d592be0, 0x5f1446608d8b4f4f,\n 0xe4c7ae9dcd373c6, 0xae9e1e467c011769, 0x4a04c546989bcc69, 0xead6a1e93849a8c6,\n 0x86dd05b754420c98, 0x260f6118f4906837, 0xc295ba18100ab337, 0x6247deb7b0d8d798,\n 0x1a82f2a4c81dfb8b, 0xba50960b68cf9f24, 0x5eca4d0b8c554424, 0xfe1829a42c87208b,\n 0x92138dfa408c84d5, 0x32c1e955e05ee07a, 0xd65b325504c43b7a, 0x768956faa4165fd5,\n 0x4904f22100000000, 0xdb0d16639209e442, 0x68fb4c5421ffbe75, 0xfaf2a816b3f65a37,\n 0xafb8ecb43ff7cea, 0x98f26a89d1f698a8, 0x2b0430be6200c29f, 0xb90dd4fcf00926dd,\n 0xcefa0bf587fef9d4, 0x5cf3efb715f71d96, 0xef05b580a60147a1, 0x7d0c51c23408a3e3,\n 0x8d05771fc401853e, 0x1f0c935d5608617c, 0xacfac96ae5fe3b4b, 0x3ef32d2877f7df09,\n 0x431577780a118559, 0xd11c933a9818611b, 0x62eac90d2bee3b2c, 0xf0e32d4fb9e7df6e,\n 0xea0b9249eef9b3, 0x92e3efd0dbe71df1, 0x2115b5e7681147c6, 0xb31c51a5fa18a384,\n 0xc4eb8eac8def7c8d, 0x56e26aee1fe698cf, 0xe51430d9ac10c2f8, 0x771dd49b3e1926ba,\n 0x8714f246ce100067, 0x151d16045c19e425, 0xa6eb4c33efefbe12, 0x34e2a8717de65a50,\n 0x5d27f89314230ab2, 0xcf2e1cd1862aeef0, 0x7cd846e635dcb4c7, 0xeed1a2a4a7d55085,\n 0x1ed8847957dc7658, 0x8cd1603bc5d5921a, 0x3f273a0c7623c82d, 0xad2ede4ee42a2c6f,\n 0xdad9014793ddf366, 0x48d0e50501d41724, 0xfb26bf32b2224d13, 0x692f5b70202ba951,\n 0x99267dadd0228f8c, 0xb2f99ef422b6bce, 0xb8d9c3d8f1dd31f9, 0x2ad0279a63d4d5bb,\n 0x57367dca1e328feb, 0xc53f99888c3b6ba9, 0x76c9c3bf3fcd319e, 0xe4c027fdadc4d5dc,\n 0x14c901205dcdf301, 0x86c0e562cfc41743, 0x3536bf557c324d74, 0xa73f5b17ee3ba936,\n 0xd0c8841e99cc763f, 0x42c1605c0bc5927d, 0xf1373a6bb833c84a, 0x633ede292a3a2c08,\n 0x9337f8f4da330ad5, 0x13e1cb6483aee97, 0xb2c84681fbccb4a0, 0x20c1a2c369c550e2,\n 0x6142e74528461564, 0xf34b0307ba4ff126, 0x40bd593009b9ab11, 0xd2b4bd729bb04f53,\n 0x22bd9baf6bb9698e, 0xb0b47fedf9b08dcc, 0x34225da4a46d7fb, 0x914bc198d84f33b9,\n 0xe6bc1e91afb8ecb0, 0x74b5fad33db108f2, 0xc743a0e48e4752c5, 0x554a44a61c4eb687,\n 0xa543627bec47905a, 0x374a86397e4e7418, 0x84bcdc0ecdb82e2f, 0x16b5384c5fb1ca6d,\n 0x6b53621c2257903d, 0xf95a865eb05e747f, 0x4aacdc6903a82e48, 0xd8a5382b91a1ca0a,\n 0x28ac1ef661a8ecd7, 0xbaa5fab4f3a10895, 0x953a083405752a2, 0x9b5a44c1d25eb6e0,\n 0xecad9bc8a5a969e9, 0x7ea47f8a37a08dab, 0xcd5225bd8456d79c, 0x5f5bc1ff165f33de,\n 0xaf52e722e6561503, 0x3d5b0360745ff141, 0x8ead5957c7a9ab76, 0x1ca4bd1555a04f34,\n 0x7561edf73c651fd6, 0xe76809b5ae6cfb94, 0x549e53821d9aa1a3, 0xc697b7c08f9345e1,\n 0x369e911d7f9a633c, 0xa497755fed93877e, 0x17612f685e65dd49, 0x8568cb2acc6c390b,\n 0xf29f1423bb9be602, 0x6096f06129920240, 0xd360aa569a645877, 0x41694e14086dbc35,\n 0xb16068c9f8649ae8, 0x23698c8b6a6d7eaa, 0x909fd6bcd99b249d, 0x29632fe4b92c0df,\n 0x7f7068ae36749a8f, 0xed798ceca47d7ecd, 0x5e8fd6db178b24fa, 0xcc8632998582c0b8,\n 0x3c8f1444758be665, 0xae86f006e7820227, 0x1d70aa3154745810, 0x8f794e73c67dbc52,\n 0xf88e917ab18a635b, 0x6a87753823838719, 0xd9712f0f9075dd2e, 0x4b78cb4d027c396c,\n 0xbb71ed90f2751fb1, 0x297809d2607cfbf3, 0x9a8e53e5d38aa1c4, 0x887b7a741834586,\n }\n};\n\nstatic union {\n uint32_t dword_table[4][256];\n uint64_t qword_array[512];\n} short_shifts = {\n .qword_array = {\n 0xdcb17aa400000000, 0x603ff91dbc8e83b9, 0xa0400b277cf17183, 0x1cce889ec07ff23a,\n 0x255399a2f9e2e306, 0x99dd1a1b456c60bf, 0x59a2e82185139285, 0xe52c6b98399d113c,\n 0x2a98ca59f629b0fd, 0x961649e04aa73344, 0x5669bbda8ad8c17e, 0xeae73863365642c7,\n 0xd37a295f0fcb53fb, 0x6ff4aae6b345d042, 0xaf8b58dc733a2278, 0x1305db65cfb4a1c1,\n 0x350e6dafe9bf170b, 0x8980ee16553194b2, 0x49ff1c2c954e6688, 0xf5719f9529c0e531,\n 0xccec8ea9105df40d, 0x70620d10acd377b4, 0xb01dff2a6cac858e, 0xc937c93d0220637,\n 0xc327dd521f96a7f6, 0x7fa95eeba318244f, 0xbfd6acd16367d675, 0x3582f68dfe955cc,\n 0x3ac53e54e67444f0, 0x864bbded5afac749, 0x46344fd79a853573, 0xfabacc6e260bb6ca,\n 0xa232243d69258e7, 0xb6ada1fa6a1cdb5e, 0x76d253c0aa632964, 0xca5cd07916edaadd,\n 0xf3c1c1452f70bbe1, 0x4f4f42fc93fe3858, 0x8f30b0c65381ca62, 0x33be337fef0f49db,\n 0xfc0a92be20bbe81a, 0x408411079c356ba3, 0x80fbe33d5c4a9999, 0x3c756084e0c41a20,\n 0x5e871b8d9590b1c, 0xb966f20165d788a5, 0x7919003ba5a87a9f, 0xc59783821926f926,\n 0xe39c35483f2d4fec, 0x5f12b6f183a3cc55, 0x9f6d44cb43dc3e6f, 0x23e3c772ff52bdd6,\n 0x1a7ed64ec6cfacea, 0xa6f055f77a412f53, 0x668fa7cdba3edd69, 0xda01247406b05ed0,\n 0x15b585b5c904ff11, 0xa93b060c758a7ca8, 0x6944f436b5f58e92, 0xd5ca778f097b0d2b,\n 0xec5766b330e61c17, 0x50d9e50a8c689fae, 0x90a617304c176d94, 0x2c289489f099ee2d,\n 0x7479bd9ba8c8c73f, 0xc8f73e2214464486, 0x888cc18d439b6bc, 0xb4064fa168b73505,\n 0x8d9b5e9d512a2439, 0x3115dd24eda4a780, 0xf16a2f1e2ddb55ba, 0x4de4aca79155d603,\n 0x82500d665ee177c2, 0x3ede8edfe26ff47b, 0xfea17ce522100641, 0x422fff5c9e9e85f8,\n 0x7bb2ee60a70394c4, 0xc73c6dd91b8d177d, 0x7439fe3dbf2e547, 0xbbcd1c5a677c66fe,\n 0x9dc6aa904177d034, 0x21482929fdf9538d, 0xe137db133d86a1b7, 0x5db958aa8108220e,\n 0x64244996b8953332, 0xd8aaca2f041bb08b, 0x18d53815c46442b1, 0xa45bbbac78eac108,\n 0x6bef1a6db75e60c9, 0xd76199d40bd0e370, 0x171e6beecbaf114a, 0xab90e857772192f3,\n 0x920df96b4ebc83cf, 0x2e837ad2f2320076, 0xeefc88e8324df24c, 0x52720b518ec371f5,\n 0xa2ebe57c7e5a9fd8, 0x1e6566c5c2d41c61, 0xde1a94ff02abee5b, 0x62941746be256de2,\n 0x5b09067a87b87cde, 0xe78785c33b36ff67, 0x27f877f9fb490d5d, 0x9b76f44047c78ee4,\n 0x54c2558188732f25, 0xe84cd63834fdac9c, 0x28332402f4825ea6, 0x94bda7bb480cdd1f,\n 0xad20b6877191cc23, 0x11ae353ecd1f4f9a, 0xd1d1c7040d60bda0, 0x6d5f44bdb1ee3e19,\n 0x4b54f27797e588d3, 0xf7da71ce2b6b0b6a, 0x37a583f4eb14f950, 0x8b2b004d579a7ae9,\n 0xb2b611716e076bd5, 0xe3892c8d289e86c, 0xce4760f212f61a56, 0x72c9e34bae7899ef,\n 0xbd7d428a61cc382e, 0x1f3c133dd42bb97, 0xc18c33091d3d49ad, 0x7d02b0b0a1b3ca14,\n 0x449fa18c982edb28, 0xf811223524a05891, 0x386ed00fe4dfaaab, 0x84e053b658512912,\n 0x547df88f00000000, 0xfc860991a8fbf11e, 0x666c42541b94cd, 0xa89d9d5cfce065d3,\n 0xfc4ad115a837299a, 0x54b1200b00ccd884, 0xa85145d8fc2cbd57, 0xaab4c654d74c49,\n 0x1ffdd4a558225c5, 0xa9042c54fd79d4db, 0x55e449870199b108, 0xfd1fb899a9624016,\n 0xa9c8f4d0fdb50c5f, 0x13305ce554efd41, 0xfdd3601da9ae9892, 0x552891030155698c,\n 0xff79b305ab044b8a, 0x5782421b03ffba94, 0xab6227c8ff1fdf47, 0x399d6d657e42e59,\n 0x574e9a9f03336210, 0xffb56b81abc8930e, 0x3550e525728f6dd, 0xabaeff4cffd307c3,\n 0xaafb96c0fe866e4f, 0x20067de567d9f51, 0xfee0020daa9dfa82, 0x561bf31302660b9c,\n 0x2ccbf5a56b147d5, 0xaa374e44fe4ab6cb, 0x56d72b9702aad318, 0xfe2cda89aa512206,\n 0x799196a53e4e1e5, 0xaf62e874fb1f10fb, 0x53828da707ff7528, 0xfb797cb9af048436,\n 0xafae30f0fbd3c87f, 0x755c1ee53283961, 0xfbb5a43dafc85cb2, 0x534e55230733adac,\n 0x521b3caf0666c420, 0xfae0cdb1ae9d353e, 0x600a862527d50ed, 0xaefb597cfa86a1f3,\n 0xfa2c1535ae51edba, 0x52d7e42b06aa1ca4, 0xae3781f8fa4a7977, 0x6cc70e652b18869,\n 0xac9d52e0f8e0aa6f, 0x466a3fe501b5b71, 0xf886c62dacfb3ea2, 0x507d37330400cfbc,\n 0x4aa7b7a50d783f5, 0xac518a64f82c72eb, 0x50b1efb704cc1738, 0xf84a1ea9ac37e626,\n 0xf91f7725ad628faa, 0x51e4863b05997eb4, 0xad04e3e8f9791b67, 0x5ff12f65182ea79,\n 0x51285ebf0555a630, 0xf9d3afa1adae572e, 0x533ca72514e32fd, 0xadc83b6cf9b5c3e3,\n 0xf3b43b45a7c9c3ca, 0x5b4fca5b0f3232d4, 0xa7afaf88f3d25707, 0xf545e965b29a619,\n 0x5b8312df0ffeea50, 0xf378e3c1a7051b4e, 0xf9886125be57e9d, 0xa763770cf31e8f83,\n 0xa6361e80f24be60f, 0xecdef9e5ab01711, 0xf22d8a4da65072c2, 0x5ad67b530eab83dc,\n 0xe01371a5a7ccf95, 0xa6fac604f2873e8b, 0x5a1aa3d70e675b58, 0xf2e152c9a69caa46,\n 0x58b070cf0ccd8840, 0xf04b81d1a436795e, 0xcabe40258d61c8d, 0xa450151cf02ded93,\n 0xf0875955a4faa1da, 0x587ca84b0c0150c4, 0xa49ccd98f0e13517, 0xc673c86581ac409,\n 0xd32550a594fad85, 0xa5c9a414f1b45c9b, 0x5929c1c70d543948, 0xf1d230d9a5afc856,\n 0xa5057c90f178841f, 0xdfe8d8e59837501, 0xf11ee85da56310d2, 0x59e519430d98e1cc,\n 0xa050daa0f42d222f, 0x8ab2bbe5cd6d331, 0xf44b4e6da036b6e2, 0x5cb0bf7308cd47fc,\n 0x867f33a5c1a0bb5, 0xa09c0224f4e1faab, 0x5c7c67f708019f78, 0xf48796e9a0fa6e66,\n 0xf5d2ff65a1af07ea, 0x5d290e7b0954f6f4, 0xa1c96ba8f5b49327, 0x9329ab65d4f6239,\n 0x5de5d6ff09982e70, 0xf51e27e1a163df6e, 0x9fe42325d83babd, 0xa105b32cf5784ba3,\n 0xb54912a5f2969a5, 0xa3af6034f7d298bb, 0x5f4f05e70b32fd68, 0xf7b4f4f9a3c90c76,\n 0xa363b8b0f71e403f, 0xb9849ae5fe5b121, 0xf7782c7da305d4f2, 0x5f83dd630bfe25ec,\n 0x5ed6b4ef0aab4c60, 0xf62d45f1a250bd7e, 0xacd20225eb0d8ad, 0xa236d13cf64b29b3,\n 0xf6e19d75a29c65fa, 0x5e1a6c6b0a6794e4, 0xa2fa09b8f687f137, 0xa01f8a65e7c0029,\n 0x4a7ff16500000000, 0xde8013af94ffe2ca, 0x666c42002c13b365, 0xf293a0cab8ec51af,\n 0x125897af582766ca, 0x86a77565ccd88400, 0x3e4b24ca7434d5af, 0xaab4c600e0cb3765,\n 0xfa313cf1b04ecd94, 0x6ecede3b24b12f5e, 0xd6228f949c5d7ef1, 0x42dd6d5e08a29c3b,\n 0xa2165a3be869ab5e, 0x36e9b8f17c964994, 0x8e05e95ec47a183b, 0x1afa0b945085faf1,\n 0x2f0e1cbc6571edd9, 0xbbf1fe76f18e0f13, 0x31dafd949625ebc, 0x97e24d13dd9dbc76,\n 0x77297a763d568b13, 0xe3d698bca9a969d9, 0x5b3ac91311453876, 0xcfc52bd985badabc,\n 0x9f40d128d53f204d, 0xbbf33e241c0c287, 0xb353624df92c9328, 0x27ac80876dd371e2,\n 0xc767b7e28d184687, 0x5398552819e7a44d, 0xeb740487a10bf5e2, 0x7f8be64d35f41728,\n 0x809c2ad7cae3dbb2, 0x1463c81d5e1c3978, 0xac8f99b2e6f068d7, 0x38707b78720f8a1d,\n 0xd8bb4c1d92c4bd78, 0x4c44aed7063b5fb2, 0xf4a8ff78bed70e1d, 0x60571db22a28ecd7,\n 0x30d2e7437aad1626, 0xa42d0589ee52f4ec, 0x1cc1542656bea543, 0x883eb6ecc2414789,\n 0x68f58189228a70ec, 0xfc0a6343b6759226, 0x44e632ec0e99c389, 0xd019d0269a662143,\n 0xe5edc70eaf92366b, 0x711225c43b6dd4a1, 0xc9fe746b8381850e, 0x5d0196a1177e67c4,\n 0xbdcaa1c4f7b550a1, 0x2935430e634ab26b, 0x91d912a1dba6e3c4, 0x526f06b4f59010e,\n 0x55a30a9a1fdcfbff, 0xc15ce8508b231935, 0x79b0b9ff33cf489a, 0xed4f5b35a730aa50,\n 0xd846c5047fb9d35, 0x997b8e9ad3047fff, 0x2197df356be82e50, 0xb5683dffff17cc9a,\n 0xda5430f0902bc195, 0x4eabd23a04d4235f, 0xf6478395bc3872f0, 0x62b8615f28c7903a,\n 0x8273563ac80ca75f, 0x168cb4f05cf34595, 0xae60e55fe41f143a, 0x3a9f079570e0f6f0,\n 0x6a1afd6420650c01, 0xfee51faeb49aeecb, 0x46094e010c76bf64, 0xd2f6accb98895dae,\n 0x323d9bae78426acb, 0xa6c27964ecbd8801, 0x1e2e28cb5451d9ae, 0x8ad1ca01c0ae3b64,\n 0xbf25dd29f55a2c4c, 0x2bda3fe361a5ce86, 0x93366e4cd9499f29, 0x7c98c864db67de3,\n 0xe702bbe3ad7d4a86, 0x73fd59293982a84c, 0xcb110886816ef9e3, 0x5feeea4c15911b29,\n 0xf6b10bd4514e1d8, 0x9b94f277d1eb0312, 0x2378a3d8690752bd, 0xb7874112fdf8b077,\n 0x574c76771d338712, 0xc3b394bd89cc65d8, 0x7b5fc51231203477, 0xefa027d8a5dfd6bd,\n 0x10b7eb425ac81a27, 0x84480988ce37f8ed, 0x3ca4582776dba942, 0xa85bbaede2244b88,\n 0x48908d8802ef7ced, 0xdc6f6f4296109e27, 0x64833eed2efccf88, 0xf07cdc27ba032d42,\n 0xa0f926d6ea86d7b3, 0x3406c41c7e793579, 0x8cea95b3c69564d6, 0x18157779526a861c,\n 0xf8de401cb2a1b179, 0x6c21a2d6265e53b3, 0xd4cdf3799eb2021c, 0x403211b30a4de0d6,\n 0x75c6069b3fb9f7fe, 0xe139e451ab461534, 0x59d5b5fe13aa449b, 0xcd2a57348755a651,\n 0x2de16051679e9134, 0xb91e829bf36173fe, 0x1f2d3344b8d2251, 0x950d31fedf72c09b,\n 0xc588cb0f8ff73a6a, 0x517729c51b08d8a0, 0xe99b786aa3e4890f, 0x7d649aa0371b6bc5,\n 0x9dafadc5d7d05ca0, 0x9504f0f432fbe6a, 0xb1bc1ea0fbc3efc5, 0x2543fc6a6f3c0d0f,\n 0x25bbf5db00000000, 0x6ecc1e6d4b77ebb6, 0xb35422b796efd76c, 0xf823c901dd983cda,\n 0xd882df22833d829, 0x46ffc6446344339f, 0x9b67fa9ebedc0f45, 0xd0101128f5abe4f3,\n 0x75dc45895067b052, 0x3eabae3f1b105be4, 0xe33392e5c688673e, 0xa84479538dff8c88,\n 0x5def9da07854687b, 0x16987616332383cd, 0xcb004acceebbbf17, 0x8077a17aa5cc54a1,\n 0x8574957fa0cf60a4, 0xce037ec9ebb88b12, 0x139b42133620b7c8, 0x58eca9a57d575c7e,\n 0xad474d5688fcb88d, 0xe630a6e0c38b533b, 0x3ba89a3a1e136fe1, 0x70df718c55648457,\n 0xd513252df0a8d0f6, 0x9e64ce9bbbdf3b40, 0x43fcf2416647079a, 0x88b19f72d30ec2c,\n 0xfd20fd04d89b08df, 0xb65716b293ece369, 0x6bcf2a684e74dfb3, 0x20b8c1de05033405,\n 0x61c942624472b7b9, 0x2abea9d40f055c0f, 0xf726950ed29d60d5, 0xbc517eb899ea8b63,\n 0x49fa9a4b6c416f90, 0x28d71fd27368426, 0xdf154d27faaeb8fc, 0x9462a691b1d9534a,\n 0x31aef230141507eb, 0x7ad919865f62ec5d, 0xa741255c82fad087, 0xec36ceeac98d3b31,\n 0x199d2a193c26dfc2, 0x52eac1af77513474, 0x8f72fd75aac908ae, 0xc40516c3e1bee318,\n 0xc10622c6e4bdd71d, 0x8a71c970afca3cab, 0x57e9f5aa72520071, 0x1c9e1e1c3925ebc7,\n 0xe935faefcc8e0f34, 0xa242115987f9e482, 0x7fda2d835a61d858, 0x34adc635111633ee,\n 0x91619294b4da674f, 0xda167922ffad8cf9, 0x78e45f82235b023, 0x4cf9ae4e69425b95,\n 0xb9524abd9ce9bf66, 0xf225a10bd79e54d0, 0x2fbd9dd10a06680a, 0x64ca7667417183bc,\n 0xad5e9aa988e56f72, 0xe629711fc39284c4, 0x3bb14dc51e0ab81e, 0x70c6a673557d53a8,\n 0x856d4280a0d6b75b, 0xce1aa936eba15ced, 0x138295ec36396037, 0x58f57e5a7d4e8b81,\n 0xfd392afbd882df20, 0xb64ec14d93f53496, 0x6bd6fd974e6d084c, 0x20a11621051ae3fa,\n 0xd50af2d2f0b10709, 0x9e7d1964bbc6ecbf, 0x43e525be665ed065, 0x892ce082d293bd3,\n 0xd91fa0d282a0fd6, 0x46e611bb635de460, 0x9b7e2d61bec5d8ba, 0xd009c6d7f5b2330c,\n 0x25a222240019d7ff, 0x6ed5c9924b6e3c49, 0xb34df54896f60093, 0xf83a1efedd81eb25,\n 0x5df64a5f784dbf84, 0x1681a1e9333a5432, 0xcb199d33eea268e8, 0x806e7685a5d5835e,\n 0x75c59276507e67ad, 0x3eb279c01b098c1b, 0xe32a451ac691b0c1, 0xa85daeac8de65b77,\n 0xe92c2d10cc97d8cb, 0xa25bc6a687e0337d, 0x7fc3fa7c5a780fa7, 0x34b411ca110fe411,\n 0xc11ff539e4a400e2, 0x8a681e8fafd3eb54, 0x57f02255724bd78e, 0x1c87c9e3393c3c38,\n 0xb94b9d429cf06899, 0xf23c76f4d787832f, 0x2fa44a2e0a1fbff5, 0x64d3a19841685443,\n 0x9178456bb4c3b0b0, 0xda0faeddffb45b06, 0x7979207222c67dc, 0x4ce079b1695b8c6a,\n 0x49e34db46c58b86f, 0x294a602272f53d9, 0xdf0c9ad8fab76f03, 0x947b716eb1c084b5,\n 0x61d0959d446b6046, 0x2aa77e2b0f1c8bf0, 0xf73f42f1d284b72a, 0xbc48a94799f35c9c,\n 0x1984fde63c3f083d, 0x52f316507748e38b, 0x8f6b2a8aaad0df51, 0xc41cc13ce1a734e7,\n 0x31b725cf140cd014, 0x7ac0ce795f7b3ba2, 0xa758f2a382e30778, 0xec2f1915c994ecce,\n }\n};\n\n/* Table-driven software version as a fall-back. This is about 15 times slower\n than using the hardware instructions. This assumes little-endian integers,\n as is the case on Intel processors that the assembler code here is for. */\nuint32_t crc32c_append_sw(uint32_t crci, buffer input, size_t length)\n{\n buffer next = input;\n#ifdef _M_X64\n uint64_t crc;\n#else\n uint32_t crc;\n#endif\n\n crc = crci ^ 0xffffffff;\n#ifdef _M_X64\n while (length && ((uintptr_t)next & 7) != 0)\n {\n crc = table.dword_table[0][(crc ^ *next++) & 0xff] ^ (crc >> 8);\n --length;\n }\n while (length >= 16)\n {\n crc ^= *(uint64_t *)next;\n uint64_t high = *(uint64_t *)(next + 8);\n crc = table.dword_table[15][crc & 0xff]\n ^ table.dword_table[14][(crc >> 8) & 0xff]\n ^ table.dword_table[13][(crc >> 16) & 0xff]\n ^ table.dword_table[12][(crc >> 24) & 0xff]\n ^ table.dword_table[11][(crc >> 32) & 0xff]\n ^ table.dword_table[10][(crc >> 40) & 0xff]\n ^ table.dword_table[9][(crc >> 48) & 0xff]\n ^ table.dword_table[8][crc >> 56]\n ^ table.dword_table[7][high & 0xff]\n ^ table.dword_table[6][(high >> 8) & 0xff]\n ^ table.dword_table[5][(high >> 16) & 0xff]\n ^ table.dword_table[4][(high >> 24) & 0xff]\n ^ table.dword_table[3][(high >> 32) & 0xff]\n ^ table.dword_table[2][(high >> 40) & 0xff]\n ^ table.dword_table[1][(high >> 48) & 0xff]\n ^ table.dword_table[0][high >> 56];\n next += 16;\n length -= 16;\n }\n#else\n while (length && ((uintptr_t)next & 3) != 0)\n {\n crc = table.dword_table[0][(crc ^ *next++) & 0xff] ^ (crc >> 8);\n --length;\n }\n while (length >= 12)\n {\n crc ^= *(uint32_t *)next;\n uint32_t high = *(uint32_t *)(next + 4);\n uint32_t high2 = *(uint32_t *)(next + 8);\n crc = table.dword_table[11][crc & 0xff]\n ^ table.dword_table[10][(crc >> 8) & 0xff]\n ^ table.dword_table[9][(crc >> 16) & 0xff]\n ^ table.dword_table[8][crc >> 24]\n ^ table.dword_table[7][high & 0xff]\n ^ table.dword_table[6][(high >> 8) & 0xff]\n ^ table.dword_table[5][(high >> 16) & 0xff]\n ^ table.dword_table[4][high >> 24]\n ^ table.dword_table[3][high2 & 0xff]\n ^ table.dword_table[2][(high2 >> 8) & 0xff]\n ^ table.dword_table[1][(high2 >> 16) & 0xff]\n ^ table.dword_table[0][high2 >> 24];\n next += 12;\n length -= 12;\n }\n#endif\n while (length)\n {\n crc = table.dword_table[0][(crc ^ *next++) & 0xff] ^ (crc >> 8);\n --length;\n }\n return (uint32_t)crc ^ 0xffffffff;\n}\n\n/* Apply the zeros operator table to crc. */\nstatic inline uint32_t shift_crc(uint32_t shift_table[][256], uint32_t crc)\n{\n return shift_table[0][crc & 0xff]\n ^ shift_table[1][(crc >> 8) & 0xff]\n ^ shift_table[2][(crc >> 16) & 0xff]\n ^ shift_table[3][crc >> 24];\n}\n\nuint32_t crc32c_append(uint32_t crc, buffer input, size_t length)\n{\n\treturn crc32c_append_sw(crc, input, length);\n}\n" }, { "alpha_fraction": 0.43617162108421326, "alphanum_fraction": 0.4375, "avg_line_length": 50.21088409423828, "blob_id": "9007234a047b510c5ae12d8f58dbf856ddaec197", "content_id": "1b6edba218b536f3c22e6d3126a1cf71b86ef6d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 15056, "license_type": "permissive", "max_line_length": 228, "num_lines": 294, "path": "/src/TorchSharp/DataLoader.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.SymbolStore;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing TorchSharp.Utils;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class utils\n {\n public static partial class data\n {\n /// <summary>\n /// This class makes easier to create batch. Data set must implement Dataset interface\n /// </summary>\n public class DataLoader : DataLoader<Dictionary<string, torch.Tensor>, Dictionary<string, torch.Tensor>>\n {\n /// <summary>\n /// Pytorch style dataloader\n /// </summary>\n /// <param name=\"dataset\">Dataset for create batch</param>\n /// <param name=\"batchSize\">Size of batch</param>\n /// <param name=\"device\">device for output tensor</param>\n /// <param name=\"shuffler\">Shuffler for dataloader</param>\n /// <param name=\"num_worker\">Count of worker</param>\n /// <param name=\"drop_last\">\n /// Set to true to drop the last incomplete batch, if the dataset size is not divisible by the batch size.\n /// If alse and the size of dataset is not divisible by the batch size, then the last batch will be smaller.\n /// </param>\n public DataLoader(Dataset dataset, int batchSize, IEnumerable<long> shuffler, Device device = null, int num_worker = 1, bool drop_last = false)\n : base(dataset, batchSize, Collate, shuffler, device, num_worker, drop_last)\n {\n }\n\n /// <summary>\n /// Pytorch style dataloader\n /// </summary>\n /// <param name=\"dataset\">Dataset for create batch</param>\n /// <param name=\"batchSize\">Size of batch</param>\n /// <param name=\"shuffle\">true if shuffle dataset, false for not</param>\n /// <param name=\"device\">device for output tensor</param>\n /// <param name=\"seed\">Seed for generating shuffle</param>\n /// <param name=\"num_worker\">Count of worker</param>\n /// <param name=\"drop_last\">\n /// Set to true to drop the last incomplete batch, if the dataset size is not divisible by the batch size.\n /// If alse and the size of dataset is not divisible by the batch size, then the last batch will be smaller.\n /// </param>\n public DataLoader(Dataset dataset, int batchSize, bool shuffle = false, Device device = null, int? seed = null, int num_worker = 1, bool drop_last = false)\n : base(dataset, batchSize, Collate, shuffle, device, seed, num_worker, drop_last)\n {\n }\n\n private static Dictionary<string, torch.Tensor> Collate(IEnumerable<Dictionary<string, torch.Tensor>> dic, torch.Device device)\n {\n Dictionary<string, torch.Tensor> batch = new();\n foreach (var x in dic.First().Keys) {\n var t = cat(dic.Select(k => k[x].unsqueeze(0)).ToArray(), 0);\n if (t.device_type != device.type || t.device_index != device.index)\n t = t.to(device);\n batch[x] = t;\n }\n return batch;\n }\n }\n\n /// <summary>\n /// This class makes easier to create batch. Data set must implement Dataset interface\n /// </summary>\n public class DataLoader<T, S> : IEnumerable<S>, IDisposable\n {\n private Dataset<T> dataset;\n private int batchSize;\n private bool shuffle;\n private bool drop_last;\n private Device device;\n private IEnumerable<long> shuffler;\n private int num_worker;\n private Func<IEnumerable<T>, torch.Device, S> collate_fn;\n\n /// <summary>\n /// Pytorch style dataloader\n /// </summary>\n /// <param name=\"dataset\">Dataset for create batch</param>\n /// <param name=\"batchSize\">Size of batch</param>\n /// <param name=\"collate_fn\">Callback to merge items make to a batch</param>\n /// <param name=\"device\">device for output tensor</param>\n /// <param name=\"shuffler\">Shuffler for dataloader</param>\n /// <param name=\"num_worker\">Count of worker</param>\n /// <param name=\"drop_last\">\n /// Set to true to drop the last incomplete batch, if the dataset size is not divisible by the batch size.\n /// If alse and the size of dataset is not divisible by the batch size, then the last batch will be smaller.\n /// </param>\n public DataLoader(Dataset<T> dataset, int batchSize, Func<IEnumerable<T>, torch.Device, S> collate_fn, IEnumerable<long> shuffler, Device device = null, int num_worker = 1, bool drop_last = false)\n {\n this.dataset = dataset;\n this.batchSize = batchSize;\n this.shuffle = true;\n this.drop_last = drop_last;\n this.device = device ?? CPU;\n this.shuffler = shuffler;\n this.num_worker = num_worker;\n this.collate_fn = collate_fn;\n }\n\n /// <summary>\n /// Pytorch style dataloader\n /// </summary>\n /// <param name=\"dataset\">Dataset for create batch</param>\n /// <param name=\"batchSize\">Size of batch</param>\n /// <param name=\"collate_fn\">Callback to merge items to make a batch</param>\n /// <param name=\"shuffle\">true if shuffle dataset, false for not</param>\n /// <param name=\"device\">device for output tensor</param>\n /// <param name=\"seed\">Seed for generating shuffle</param>\n /// <param name=\"num_worker\">Count of worker</param>\n /// <param name=\"drop_last\">\n /// Set to true to drop the last incomplete batch, if the dataset size is not divisible by the batch size.\n /// If alse and the size of dataset is not divisible by the batch size, then the last batch will be smaller.\n /// </param>\n public DataLoader(Dataset<T> dataset, int batchSize, Func<IEnumerable<T>, torch.Device, S> collate_fn, bool shuffle = false, Device device = null, int? seed = null, int num_worker = 1, bool drop_last = false)\n {\n this.dataset = dataset;\n this.batchSize = batchSize;\n this.shuffle = shuffle;\n this.drop_last = drop_last;\n this.device = device ?? CPU;\n this.shuffler = seed is null ? new FisherYatesShuffler(dataset.Count) : new FisherYatesShuffler(dataset.Count, seed);\n this.num_worker = num_worker;\n this.collate_fn = collate_fn;\n }\n\n /// <summary>\n /// Generate enumerator\n /// </summary>\n /// <returns>Enumerator for batch</returns>\n public IEnumerator<S> GetEnumerator() =>\n new DataLoaderEnumerator(dataset, batchSize, shuffle, device, shuffler, num_worker, collate_fn);\n\n IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n\n /// <summary>\n /// Size of batch\n /// </summary>\n public long Count => drop_last ? (dataset.Count / batchSize) : ((dataset.Count - 1) / batchSize + 1);\n\n private class DataLoaderEnumerator : IEnumerator<S>\n {\n private Dataset<T> dataset;\n private int batchSize;\n private Device device;\n private bool shuffle;\n private IEnumerable<long> shuffleEnumerable;\n private IEnumerator<long> shuffler;\n private long currentVal = 0;\n private int num_worker = 0;\n private IList<IDisposable> currentDisposables;\n private Func<IEnumerable<T>, torch.Device, S> collate_fn;\n public DataLoaderEnumerator(Dataset<T> dataset, int batchSize, bool shuffle, Device device, IEnumerable<long> shuffleEnumerable, int num_worker, Func<IEnumerable<T>, torch.Device, S> collate_fn)\n {\n this.dataset = dataset;\n this.batchSize = batchSize;\n this.device = device;\n this.shuffle = shuffle;\n this.shuffleEnumerable = shuffleEnumerable;\n if (num_worker < 1) num_worker = 1;\n this.num_worker = num_worker;\n this.collate_fn = collate_fn;\n Reset();\n }\n\n private bool MoveNextValue()\n {\n if (shuffle) {\n if (!shuffler.MoveNext()) return false;\n currentVal = shuffler.Current;\n return true;\n } else {\n currentVal++;\n return currentVal < dataset.Count;\n }\n }\n\n /// <summary>\n /// Get next batch\n /// </summary>\n /// <returns>true if batch created, false if batch has finished</returns>\n public bool MoveNext()\n {\n DisposeCurrent();\n using (var scope = DisposeScopeManager.NewDisposeScope()) {\n if (!MoveNextValue()) return false;\n\n var tensorIndexList = new List<long> {currentVal};\n for (int i = 1; i < batchSize; i++) {\n if (!MoveNextValue()) break;\n tensorIndexList.Add(currentVal);\n }\n\n var items = new List<T>(new T[tensorIndexList.Count]);\n var taskedBatchCount = 0;\n\n //Run Async\n var tasks = new List<Task>();\n foreach (var _ in Enumerable.Range(1, num_worker - 1))\n tasks.Add(new(ProcessPendingBatches));\n tasks.ForEach(x => x.Start());\n\n ProcessPendingBatches();\n\n foreach (var task in tasks)\n task.Wait();\n\n using (var collate_scope = DisposeScopeManager.NewDisposeScope()) {\n Current = collate_fn(items, device);\n currentDisposables = collate_scope.DisposablesView.ToList();\n collate_scope.Detach(currentDisposables);\n }\n\n return true;\n\n void ProcessPendingBatches()\n {\n while (true) {\n var idx = ScheduleBatch();\n if (idx is null) break;\n items[idx.Value.Item1] = dataset.GetTensor(idx.Value.Item2);\n }\n }\n\n (int, long)? ScheduleBatch()\n {\n var t = Interlocked.Increment(ref taskedBatchCount) - 1;\n if (t < tensorIndexList.Count)\n return (t, tensorIndexList[t]);\n return null;\n }\n }\n }\n\n /// <summary>\n /// Reset enumerator\n /// </summary>\n public void Reset()\n {\n DisposeCurrent();\n if(shuffle) shuffler = shuffleEnumerable.GetEnumerator();\n currentVal = -1;\n }\n\n /// <summary>\n /// Current tensor\n /// </summary>\n public S Current { get; private set; }\n\n object IEnumerator.Current => Current;\n\n public void Dispose()\n {\n DisposeCurrent();\n }\n\n private void DisposeCurrent()\n {\n if (currentDisposables is null) return;\n foreach(var x in currentDisposables)\n x.Dispose();\n currentDisposables = null;\n shuffler?.Dispose();\n }\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (disposing) {\n dataset.Dispose();\n }\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.4713080823421478, "alphanum_fraction": 0.47497737407684326, "avg_line_length": 59.755645751953125, "blob_id": "cb594eb7a688753743a9bbb630116d874981c65e", "content_id": "ea15e2ee6173d9d94d546999e79eb284fd27d307", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 104943, "license_type": "permissive", "max_line_length": 364, "num_lines": 1727, "path": "/src/TorchSharp/Optimizers/LRScheduler.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Net.Security;\nusing TorchSharp.Modules;\n\n// All LR schedulers in this file are directly based on the Pytorch implementation at:\n//\n// https://github.com/pytorch/pytorch/blob/master/torch/optim/lr_scheduler.py\n//\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class optim\n {\n public static partial class lr_scheduler\n {\n public abstract class LRScheduler\n {\n protected LRScheduler()\n {\n\n }\n\n protected LRScheduler(Optimizer optimizer, int last_epoch = -1, bool verbose = false)\n {\n _optimizer = optimizer;\n _last_epoch = last_epoch;\n _verbose = verbose;\n _base_lrs = optimizer.ParamGroups.Select(pg => pg.InitialLearningRate).ToList();\n _last_lrs = optimizer.ParamGroups.Select(pg => pg.LearningRate).ToList();\n\n if (last_epoch == -1) {\n foreach (var pg in optimizer.ParamGroups) {\n pg.InitialLearningRate = pg.LearningRate;\n }\n }\n }\n\n /// <summary>\n /// Advance the learning rate schedule. \n /// </summary>\n /// <remarks>Typically, this is done once per epoch or once every N batches.</remarks>\n public virtual void step()\n {\n step(null);\n }\n\n /// <summary>\n /// Advance the learning rate schedule. \n /// </summary>\n /// <remarks>Typically, this is done once per epoch or once every N batches.</remarks>\n public virtual void step(int? epoch)\n {\n _step_count += 1;\n _last_epoch = (epoch.HasValue) ? epoch.Value : _last_epoch + 1;\n\n // NOTE: It is super-important to use the 'get_lr()' method no more than once per step(), since\n // for many LR schedulers, it will modify the internal state of the scheduler,\n // as well as that of the controlled optimizer.\n var lr = get_lr().ToList();\n var pgs = _optimizer.ParamGroups.ToList();\n\n for (int i = 0; i < _base_lrs.Count; i++) {\n\n pgs[i].LearningRate = lr[i];\n if (_verbose && _last_lrs[i] != lr[i])\n Console.WriteLine($\"Adjusting learning rate to {lr[i]}\");\n _last_lrs[i] = lr[i];\n }\n }\n\n /// <summary>\n /// Advance the learning rate scheduler, passing in the current value of some metric.\n /// </summary>\n /// <remarks>\n /// The metric value is ignored by most LR schedulers.\n /// </remarks>\n public virtual void step(double current, int? epoch = null)\n {\n // Ignore the metric\n step(epoch);\n }\n\n /// <summary>\n /// Compute the current learning rate for the scheduler.\n /// </summary>\n protected virtual IEnumerable<double> get_lr() => _optimizer.ParamGroups.Select(pg => pg.LearningRate);\n\n /// <summary>\n /// Return last computed learning rate by current scheduler.\n /// </summary>\n public IEnumerable<double> get_last_lr() => _last_lrs;\n\n internal Optimizer _optimizer;\n internal int _last_epoch = -1;\n internal bool _verbose = false;\n protected int _step_count = 0;\n internal IList<double> _last_lrs;\n internal IList<double> _base_lrs;\n }\n\n public static partial class impl\n {\n /// <summary>\n /// Sets the learning rate of each parameter group to the initial lr times a given function.\n /// When last_epoch=-1, sets initial lr as lr.\n /// </summary>\n public class LambdaLR : LRScheduler\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"lr_lambda\">A function which computes a multiplicative factor given an integer parameter epoch.</param>\n /// <param name=\"last_epoch\">The index of last epoch. Default: -1.</param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public LambdaLR(Optimizer optimizer, Func<int, double> lr_lambda, int last_epoch = -1, bool verbose = false) : base(optimizer, last_epoch, verbose)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n _lr_lambdas = Enumerable.Repeat(lr_lambda, optimizer.ParamGroups.Count()).ToList();\n\n step();\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"lr_lambdas\">A list of functions, one for each paramater group, which computes a multiplicative factor given an integer parameter epoch.</param>\n /// <param name=\"last_epoch\">The index of last epoch. Default: -1.</param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public LambdaLR(Optimizer optimizer, IEnumerable<Func<int, double>> lr_lambdas, int last_epoch = -1, bool verbose = false) : base(optimizer, last_epoch, verbose)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n _lr_lambdas = lr_lambdas.ToList();\n\n step();\n }\n\n /// <summary>\n /// Compute the current learning rate for the scheduler.\n /// </summary>\n protected override IEnumerable<double> get_lr()\n {\n var pgs = _optimizer.ParamGroups.ToList();\n return Enumerable.Range(0, pgs.Count).Select(i => _base_lrs[i] * _lr_lambdas[i](_last_epoch));\n }\n\n private List<Func<int, double>> _lr_lambdas;\n }\n\n /// <summary>\n /// Multiply the learning rate of each parameter group by the factor given in the specified function.\n /// When last_epoch = -1, sets initial lr as lr.\n /// </summary>\n public class MultiplicativeLR : LRScheduler\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"lr_lambdas\">A list of functions, one for each paramater group, which computes a multiplicative factor given an integer parameter epoch.</param>\n /// <param name=\"last_epoch\">The index of last epoch. Default: -1.</param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public MultiplicativeLR(Optimizer optimizer, IEnumerable<Func<int, double>> lr_lambdas, int last_epoch = -1, bool verbose = false) : base(optimizer, last_epoch, verbose)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n _lr_lambdas = lr_lambdas.ToList();\n\n step();\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"lr_lambda\">A function which computes a multiplicative factor given an integer parameter epoch.</param>\n /// <param name=\"last_epoch\">The index of last epoch. Default: -1.</param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public MultiplicativeLR(Optimizer optimizer, Func<int, double> lr_lambda, int last_epoch = -1, bool verbose = false) : base(optimizer, last_epoch, verbose)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n _lr_lambdas = Enumerable.Repeat(lr_lambda, optimizer.ParamGroups.Count()).ToList();\n\n step();\n }\n\n /// <summary>\n /// Compute the current learning rate for the scheduler.\n /// </summary>\n protected override IEnumerable<double> get_lr()\n {\n var pgs = _optimizer.ParamGroups.ToList();\n return (_last_epoch > 0)\n ? Enumerable.Range(0, pgs.Count).Select(i => pgs[i].LearningRate * _lr_lambdas[i](_last_epoch))\n : Enumerable.Range(0, pgs.Count).Select(i => pgs[i].LearningRate);\n }\n\n private List<Func<int, double>> _lr_lambdas;\n }\n\n /// <summary>\n /// Decays the learning rate of each parameter group by gamma every step_size epochs.\n /// Notice that such decay can happen simultaneously with other changes to the learning rate from outside this scheduler.\n /// When last_epoch=-1, sets initial lr as lr.\n /// </summary>\n public class StepLR : LRScheduler\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"step_size\">Period of learning rate decay.</param>\n /// <param name=\"gamma\">Multiplicative factor of learning rate decay. Default: 0.1.</param>\n /// <param name=\"last_epoch\">The index of last epoch. Default: -1.</param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public StepLR(Optimizer optimizer, int step_size, double gamma = 0.1, int last_epoch = -1, bool verbose = false) : base(optimizer, last_epoch, verbose)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n _step_size = step_size;\n _gamma = gamma;\n\n step();\n }\n\n /// <summary>\n /// Compute the current learning rate for the scheduler.\n /// </summary>\n protected override IEnumerable<double> get_lr()\n {\n return (_last_epoch == 0) || (_last_epoch % _step_size != 0)\n ? _optimizer.ParamGroups.Select(pg => pg.LearningRate)\n : _optimizer.ParamGroups.Select(pg => pg.LearningRate * _gamma);\n }\n\n private int _step_size;\n private double _gamma;\n }\n\n /// <summary>\n /// Decays the learning rate of each parameter group by gamma once the number of epoch reaches one of the milestones.\n /// Notice that such decay can happen simultaneously with other changes to the learning rate from outside this scheduler.\n /// When last_epoch=-1, sets initial lr as lr.\n /// </summary>\n public class MultiStepLR : LRScheduler\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"milestones\">List of epoch indices. Must be increasing.</param>\n /// <param name=\"gamma\">Multiplicative factor of learning rate decay. Default: 0.1.</param>\n /// <param name=\"last_epoch\">The index of last epoch. Default: -1.</param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public MultiStepLR(Optimizer optimizer, IList<int> milestones, double gamma = 0.1, int last_epoch = -1, bool verbose = false) : base(optimizer, last_epoch, verbose)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n _milestones = milestones;\n _gamma = gamma;\n\n step();\n }\n\n /// <summary>\n /// Compute the current learning rate for the scheduler.\n /// </summary>\n protected override IEnumerable<double> get_lr()\n {\n var idx = _milestones.IndexOf(_last_epoch);\n return idx == -1\n ? _optimizer.ParamGroups.Select(pg => pg.LearningRate)\n : _optimizer.ParamGroups.Select(pg => pg.LearningRate * _gamma);\n }\n\n private IList<int> _milestones;\n private double _gamma;\n }\n\n /// <summary>\n /// Decays the learning rate of each parameter group using a polynomial function in the given total_iters.\n /// When last_epoch=-1, sets initial lr as lr.\n /// </summary>\n public class PolynomialLR : LRScheduler\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"total_iters\">The number of steps that the scheduler decays the learning rate.</param>\n /// <param name=\"power\">The power of the polynomial.</param>\n /// <param name=\"last_epoch\">The index of last epoch. Default: -1.</param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public PolynomialLR(Optimizer optimizer, int total_iters = 5, int power = 1, int last_epoch = -1, bool verbose = false) : base(optimizer, last_epoch, verbose)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n _power = power;\n _total_iters = total_iters;\n step();\n }\n\n /// <summary>\n /// Compute the current learning rate for the scheduler.\n /// </summary>\n protected override IEnumerable<double> get_lr()\n {\n if (_last_epoch == 0 || _last_epoch > _total_iters) {\n return _optimizer.ParamGroups.Select(pg => pg.LearningRate);\n }\n else {\n var decay_factor = ((1.0 - _last_epoch / _total_iters) / (1.0 - (_last_epoch - 1) / _total_iters));\n if (_power != 1) {\n decay_factor = Math.Pow(decay_factor, _power);\n }\n return _optimizer.ParamGroups.Select(pg => pg.LearningRate * decay_factor);\n }\n }\n\n private double _total_iters;\n private int _power;\n }\n\n /// <summary>\n /// Decays the learning rate of each parameter group by gamma every epoch.\n /// Notice that such decay can happen simultaneously with other changes to the learning rate from outside this scheduler.\n /// When last_epoch=-1, sets initial lr as lr.\n /// </summary>\n public class ExponentialLR : LRScheduler\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"gamma\">Multiplicative factor of learning rate decay. Default: 0.1.</param>\n /// <param name=\"last_epoch\">The index of last epoch. Default: -1.</param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public ExponentialLR(Optimizer optimizer, double gamma = 0.1, int last_epoch = -1, bool verbose = false) : base(optimizer, last_epoch, verbose)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n _gamma = gamma;\n\n step();\n }\n\n /// <summary>\n /// Compute the current learning rate for the scheduler.\n /// </summary>\n protected override IEnumerable<double> get_lr()\n {\n return (_last_epoch == 0)\n ? _optimizer.ParamGroups.Select(pg => pg.LearningRate)\n : _optimizer.ParamGroups.Select(pg => pg.LearningRate * _gamma);\n }\n\n private double _gamma;\n }\n\n /// <summary>\n /// Decays the learning rate of each parameter group by a small constant factor until the number of epoch reaches a pre-defined milestone: total_iters.\n /// Notice that such decay can happen simultaneously with other changes to the learning rate from outside this scheduler.\n /// When last_epoch=-1, sets initial lr as lr.\n /// </summary>\n public class ConstantLR : LRScheduler\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"factor\">The number we multiply learning rate until the milestone.</param>\n /// <param name=\"total_iters\">The number of steps that the scheduler decays the learning rate.</param>\n /// <param name=\"last_epoch\">The index of last epoch. Default: -1.</param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public ConstantLR(Optimizer optimizer, double factor = 1.0 / 3, int total_iters = 5, int last_epoch = -1, bool verbose = false) : base(optimizer, last_epoch, verbose)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n _factor = factor;\n _total_iters = total_iters;\n\n step();\n }\n\n /// <summary>\n /// Compute the current learning rate for the scheduler.\n /// </summary>\n protected override IEnumerable<double> get_lr()\n {\n if (_last_epoch == 0) {\n return _optimizer.ParamGroups.Select(pg => pg.LearningRate * _factor);\n } else if (_last_epoch == _total_iters) {\n return _optimizer.ParamGroups.Select(pg => pg.LearningRate * (1.0 / _factor));\n } else {\n return _optimizer.ParamGroups.Select(pg => pg.LearningRate);\n }\n }\n\n private double _factor;\n private int _total_iters;\n }\n\n /// <summary>\n /// Decays the learning rate of each parameter group by linearly changing small multiplicative factor until the\n /// number of epoch reaches a pre-defined milestone: total_iters.\n /// Notice that such decay can happen simultaneously with other changes to the learning rate from outside this scheduler.\n /// When last_epoch=-1, sets initial lr as lr.\n /// </summary>\n public class LinearLR : LRScheduler\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"start_factor\">The number we multiply learning rate in the first epoch. The multiplication factor changes towards end_factor in the following epochs.</param>\n /// <param name=\"end_factor\">The number we multiply learning rate at the end of linear changing process.</param>\n /// <param name=\"total_iters\">The number of steps that the scheduler decays the learning rate.</param>\n /// <param name=\"last_epoch\">The index of last epoch. Default: -1.</param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public LinearLR(Optimizer optimizer, double start_factor = 1.0 / 3, double end_factor = 5, int total_iters = 5, int last_epoch = -1, bool verbose = false) : base(optimizer, last_epoch, verbose)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n _start_factor = start_factor;\n _end_factor = end_factor;\n _total_iters = total_iters;\n\n step();\n }\n\n /// <summary>\n /// Compute the current learning rate for the scheduler.\n /// </summary>\n protected override IEnumerable<double> get_lr()\n {\n if (_last_epoch == 0) {\n return _optimizer.ParamGroups.Select(pg => pg.LearningRate * _start_factor);\n } else if (_last_epoch > _total_iters) {\n return _optimizer.ParamGroups.Select(pg => pg.LearningRate);\n } else {\n var factor = (1 + (_end_factor - _start_factor)) / (_total_iters * _start_factor + (_last_epoch - 1) * (_end_factor - _start_factor));\n return _optimizer.ParamGroups.Select(pg => pg.LearningRate * factor);\n }\n }\n\n private double _start_factor;\n private double _end_factor;\n private int _total_iters;\n }\n\n /// <summary>\n /// Receives the list of schedulers that is expected to be called sequentially during optimization process and milestone points that provides exact intervals to reflect which scheduler is supposed to be called at a given epoch.\n /// </summary>\n public class SequentialLR : LRScheduler\n {\n public SequentialLR(Optimizer optimizer, IEnumerable<LRScheduler> schedulers, IEnumerable<int> milestones, int last_epoch = -1) : base(optimizer, last_epoch + 1, false)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n\n foreach (var scheduler in schedulers) {\n if (scheduler._optimizer != optimizer)\n throw new ArgumentException($\"The SequentialLR scheduler expects all its sub-schedulers to be bound to the same optimizer.\");\n }\n\n if (milestones.Count() != schedulers.Count() - 1) {\n throw new ArgumentException($\"Received {schedulers.Count()} schedulers and {milestones.Count()} milestones. The SequentialLR scheduler expects the number of schedulers to be one more than the number of milestones. \");\n }\n\n _schedulers = schedulers.ToArray();\n _milestones = milestones.ToArray();\n\n foreach (var group in optimizer.ParamGroups) {\n group.LearningRate = group.InitialLearningRate;\n }\n foreach (var scheduler in _schedulers) {\n scheduler._last_epoch -= 1;\n }\n _schedulers[0].step();\n _last_lrs = _schedulers[0]._last_lrs;\n }\n\n /// <summary>\n /// Compute the current learning rate for the scheduler.\n /// </summary>\n protected override IEnumerable<double> get_lr()\n {\n\n var idx = _milestones.Length;\n for (; idx > 0 ;) {\n if (_milestones[idx-1] <= _last_epoch) break;\n idx -= 1;\n }\n\n var scheduler = _schedulers[idx];\n if (idx > 0 && _milestones[idx - 1] == _last_epoch)\n scheduler.step(0);\n else\n scheduler.step();\n\n return _optimizer.ParamGroups.Select(pg => pg.LearningRate);\n }\n\n private LRScheduler[] _schedulers;\n private int[] _milestones;\n }\n\n /// <summary>\n /// Set the learning rate of each parameter group using a cosine annealing schedule.\n /// When last_epoch=-1, sets initial lr as lr.\n /// </summary>\n public class CosineAnnealingLR : LRScheduler\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"T_max\">Maximum number of iterations.</param>\n /// <param name=\"eta_min\">Minimum learning rate.</param>\n /// <param name=\"last_epoch\">The index of last epoch. Default: -1.</param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public CosineAnnealingLR(Optimizer optimizer, double T_max, double eta_min = 0, int last_epoch = -1, bool verbose = false) : base(optimizer, last_epoch, verbose)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n _T_max = T_max;\n _eta_min = eta_min;\n\n step();\n }\n\n /// <summary>\n /// Compute the current learning rate for the scheduler.\n /// </summary>\n protected override IEnumerable<double> get_lr()\n {\n if (_last_epoch == 0) {\n return _optimizer.ParamGroups.Select(pg => pg.LearningRate);\n } else if ((_last_epoch - 1 - _T_max) % (2 * _T_max) == 0) {\n var pgs = _optimizer.ParamGroups.ToList();\n return Enumerable.Range(0, pgs.Count).Select(i => pgs[i].LearningRate + (_base_lrs[i] - _eta_min) * (1 - Math.Cos(Math.PI / _T_max)) / 2);\n } else {\n return _optimizer.ParamGroups.Select(pg => (1 + Math.Cos(Math.PI * _last_epoch / _T_max)) /\n (1 + Math.Cos(Math.PI * (_last_epoch - 1) / _T_max)) * (pg.LearningRate - _eta_min) + _eta_min);\n }\n }\n\n private double _T_max;\n private double _eta_min;\n }\n\n /// <summary>\n /// Set the learning rate of each parameter group using a cosine annealing schedule.\n /// When last_epoch=-1, sets initial lr as lr.\n /// </summary>\n public class ReduceLROnPlateau : LRScheduler\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <returns>A scheduler</returns>\n public ReduceLROnPlateau(Optimizer optimizer, string mode = \"min\", double factor = 0.1, int patience = 10, double threshold = 1e-4, string threshold_mode = \"rel\", int cooldown = 0, IList<double> min_lr = null, double eps = 1e-8, bool verbose = false)\n :base(optimizer, -1, verbose)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n if (factor >= 1.0) throw new ArgumentException(\"Factor should be < 1.0\");\n\n switch (mode) {\n case \"min\":\n case \"max\":\n break;\n default:\n throw new ArgumentException($\"mode {mode} is unknown!\");\n }\n switch (threshold_mode) {\n case \"rel\":\n case \"abs\":\n break;\n default:\n throw new ArgumentException($\"threshold mode {threshold_mode} is unknown!\");\n }\n\n this._optimizer = optimizer;\n this.factor = factor;\n\n var pgLength = optimizer.ParamGroups.Count();\n if (min_lr == null || min_lr.Count == 0) {\n this.min_lrs = Enumerable.Repeat(0.0, pgLength).ToList();\n }\n else if (min_lr.Count == 1) {\n this.min_lrs = Enumerable.Repeat(min_lr[0], pgLength).ToList();\n }\n else {\n this.min_lrs = min_lr.ToList();\n }\n\n this.patience = patience;\n this.cooldown = cooldown;\n this.cooldown_counter = 0;\n this.mode = mode;\n this.threshold = threshold;\n this.threshold_mode = threshold_mode;\n this.best = -1;\n this.num_bad_epochs = -1;\n this.eps = eps;\n\n this.mode_worst = (mode == \"min\") ? double.PositiveInfinity : double.NegativeInfinity;\n\n reset();\n }\n\n /// <summary>\n /// Advance the LR scheduler one epoch.\n /// Unlike other LR schedulers, you're supposed to pass in the most recent value of the metric\n /// that is used to decided whether to modify the learning rates. \n /// </summary>\n /// <param name=\"current\">The current value of the metric that we're interested in imvproving.</param>\n /// <param name=\"epoch\">The current epoch.</param>\n public override void step(double current, int? epoch = null)\n {\n if (epoch == null) {\n epoch = _last_epoch + 1;\n }\n _last_epoch = epoch.Value;\n\n if (is_better(current, best)) {\n best = current;\n num_bad_epochs = 0;\n }\n else {\n num_bad_epochs += 1;\n }\n\n if (cooldown_counter > 0) {\n cooldown_counter -= 1;\n num_bad_epochs = 0;\n }\n\n if (num_bad_epochs > patience) {\n reduce_lr(_last_epoch);\n cooldown_counter = cooldown;\n num_bad_epochs = 0;\n }\n }\n\n public override void step()\n {\n throw new InvalidOperationException(\"step() should not be used with the ReduceLROnPlateau scheduler. Use step(double, int?), instead.\");\n }\n\n public override void step(int? epoch)\n {\n throw new InvalidOperationException(\"step(int?) should not be used with the ReduceLROnPlateau scheduler. Use step(double, int?), instead.\");\n }\n\n private bool is_better(double a, double best)\n {\n if (mode == \"min\" && threshold_mode == \"rel\") {\n return a < best * (1 - threshold);\n }\n else if (mode == \"min\" && threshold_mode == \"abs\") {\n return a < best - threshold;\n }\n else if (mode == \"max\" && threshold_mode == \"rel\") {\n return a > best * (threshold + 1);\n }\n else {\n return a > best + threshold;\n }\n }\n\n private void reduce_lr(long epoch)\n {\n var pgs = _optimizer.ParamGroups.ToList();\n\n for (var i = 0; i < pgs.Count; i++) {\n var param_group = pgs[i];\n\n var old_lr = param_group.LearningRate;\n var new_lr = Math.Max(old_lr * factor, min_lrs[i]);\n if (old_lr - new_lr > eps) {\n param_group.LearningRate = new_lr;\n if (_verbose) {\n Console.WriteLine($\"Epoch {epoch}: reducing learning rate of group {i} to {new_lr:g4}.\");\n }\n }\n }\n }\n\n private void reset()\n {\n best = mode_worst;\n cooldown_counter = 0;\n num_bad_epochs = 0;\n }\n\n private int patience;\n private int cooldown;\n private int cooldown_counter;\n private string mode;\n private double threshold;\n private string threshold_mode;\n private double best;\n private double mode_worst;\n private int num_bad_epochs;\n private double eps;\n\n private double factor;\n private List<double> min_lrs;\n }\n\n /// <summary>\n /// Sets the learning rate of each parameter group according to cyclical learning rate policy(CLR).\n ///\n /// The policy cycles the learning rate between two boundaries with a constant frequency, as detailed in\n /// the paper `Cyclical Learning Rates for Training Neural Networks`_.\n /// \n /// The distance between the two boundaries can be scaled on a per-iteration or per-cycle basis.\n /// </summary>\n public class CyclicLR : LRScheduler\n {\n public enum Mode\n {\n Triangular,\n Triangular2,\n ExpRange\n }\n public enum ScaleMode\n {\n Cycle,\n Iterations\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n public CyclicLR(Optimizer optimizer,\n double base_lr,\n double max_lr,\n int step_size_up = 2000,\n int step_size_down = -1,\n Mode mode = Mode.Triangular,\n double gamma = 1.0,\n Func<double, double> scale_fn = null,\n ScaleMode scale_mode = ScaleMode.Cycle,\n bool cycle_momentum = true,\n double base_momentum = 0.8,\n double max_momentum = 0.9,\n int last_epoch = -1,\n bool verbose = false) : base(optimizer, last_epoch, verbose)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n\n var pgCount = optimizer.ParamGroups.Count();\n\n Initialize(\n optimizer,\n Enumerable.Repeat(base_lr, pgCount),\n Enumerable.Repeat(max_lr, pgCount),\n step_size_up,\n step_size_down,\n mode,\n gamma,\n scale_fn,\n scale_mode,\n cycle_momentum,\n Enumerable.Repeat(base_momentum, pgCount),\n Enumerable.Repeat(max_momentum, pgCount));\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n public CyclicLR(Optimizer optimizer,\n IEnumerable<double> base_lr,\n IEnumerable<double> max_lr,\n int step_size_up = 2000,\n int step_size_down = -1,\n Mode mode = Mode.Triangular,\n double gamma = 1.0,\n Func<double, double> scale_fn = null,\n ScaleMode scale_mode = ScaleMode.Cycle,\n bool cycle_momentum = true,\n IEnumerable<double> base_momentum = null,\n IEnumerable<double> max_momentum = null,\n int last_epoch = -1,\n bool verbose = false) : base(optimizer, last_epoch, verbose)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n\n Initialize(\n optimizer,\n base_lr,\n max_lr,\n step_size_up,\n step_size_down,\n mode,\n gamma,\n scale_fn,\n scale_mode,\n cycle_momentum,\n base_momentum,\n max_momentum);\n }\n\n private void Initialize(Optimizer optimizer, IEnumerable<double> base_lr, IEnumerable<double> max_lr, int step_size_up, int step_size_down, Mode mode, double gamma, Func<double, double> scale_fn, ScaleMode scale_mode, bool cycle_momentum, IEnumerable<double> base_momentum, IEnumerable<double> max_momentum)\n {\n double down = (step_size_down == -1) ? step_size_up : step_size_down;\n _total_size = step_size_up + down;\n _step_ratio = step_size_up / _total_size;\n\n var pgs = optimizer.ParamGroups.ToList();\n\n _max_lrs = max_lr.ToList();\n _base_lrs = base_lr.ToList();\n\n if (_last_epoch == -1) {\n for (int i = 0; i < pgs.Count; i++) {\n pgs[i].LearningRate = _base_lrs[i];\n }\n }\n\n _mode = mode;\n _gamma = gamma;\n _cycle_momentum = cycle_momentum;\n\n if (cycle_momentum) {\n var momentum = optimizer as IMomentum;\n if (momentum == null && cycle_momentum) throw new ArgumentException($\"optimizer must support momentum with `cycle_momentum` option enabled\");\n\n _base_momentum = (base_momentum is null) ? Enumerable.Repeat(0.8, pgs.Count).ToList() : base_momentum.ToList();\n _max_momentum = (max_momentum is null) ? Enumerable.Repeat(0.9, pgs.Count).ToList() : max_momentum.ToList();\n\n if (_last_epoch == -1) {\n for (int i = 0; i < pgs.Count; i++) {\n (pgs[i] as IMomentum).Momentum = _base_momentum[i];\n }\n }\n }\n\n\n if (scale_fn == null) {\n switch (mode) {\n case Mode.Triangular:\n _scale_func = x => 1.0;\n _scale_mode = ScaleMode.Cycle;\n break;\n case Mode.Triangular2:\n _scale_func = x => 1.0 / (Math.Pow(2, x - 1));\n _scale_mode = ScaleMode.Cycle;\n break;\n case Mode.ExpRange:\n _scale_func = x => Math.Pow(this._gamma, x);\n _scale_mode = ScaleMode.Cycle;\n break;\n }\n } else {\n _scale_func = scale_fn;\n _scale_mode = scale_mode;\n }\n\n step();\n }\n\n /// <summary>\n /// Compute the current learning rate for the scheduler.\n /// </summary>\n protected override IEnumerable<double> get_lr()\n {\n var pgs = _optimizer.ParamGroups.ToList();\n\n var cycle = Math.Floor(1.0 + _last_epoch / _total_size);\n var x = 1.0 + _last_epoch / _total_size - cycle;\n\n var scale_factor = (x <= _step_ratio) ? x / _step_ratio : (x - 1) / (_step_ratio - 1);\n\n return Enumerable.Range(0, pgs.Count).Select(i => {\n\n var base_height = (_max_lrs[i] - _base_lrs[i]) * scale_factor;\n\n var computed_lr = (_scale_mode == ScaleMode.Cycle)\n ? _base_lrs[i] + base_height * _scale_func(cycle)\n : _base_lrs[i] + base_height * _scale_func(_last_epoch);\n\n if (_cycle_momentum) {\n\n base_height = (_max_momentum[i] - _base_momentum[i]) * scale_factor;\n\n (pgs[i] as IMomentum).Momentum = (_scale_mode == ScaleMode.Cycle)\n ? _max_momentum[i] + base_height * _scale_func(cycle)\n : _max_momentum[i] + base_height * _scale_func(_last_epoch);\n\n }\n\n return computed_lr;\n });\n }\n\n private double _total_size;\n private double _step_ratio;\n\n private Func<double, double> _scale_func;\n private ScaleMode _scale_mode;\n\n private bool _cycle_momentum;\n\n private List<double> _max_lrs;\n\n private List<double> _base_momentum;\n private List<double> _max_momentum;\n\n private Mode _mode;\n private double _gamma;\n }\n\n /// <summary>\n /// Sets the learning rate of each parameter group according to the 1cycle learning rate policy.\n /// </summary>\n public class OneCycleLR : LRScheduler\n {\n public enum AnnealStrategy\n {\n Cos,\n Linear\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n public OneCycleLR(Optimizer optimizer,\n double max_lr,\n int total_steps = -1,\n int epochs = -1,\n int steps_per_epoch = -1,\n double pct_start = 0.3,\n AnnealStrategy anneal_strategy = AnnealStrategy.Cos,\n bool cycle_momentum = true,\n double base_momentum = 0.85,\n double max_momentum = 0.95,\n double div_factor = 25,\n double final_div_factor = 1e4,\n bool three_phase = false,\n int last_epoch = -1, bool verbose = false) : base(optimizer, last_epoch, verbose)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n\n var pgCount = _optimizer.ParamGroups.Count();\n\n Initialize(optimizer,\n Enumerable.Repeat(max_lr, pgCount),\n total_steps,\n epochs,\n steps_per_epoch,\n pct_start, anneal_strategy,\n cycle_momentum,\n Enumerable.Repeat(base_momentum, pgCount),\n Enumerable.Repeat(max_momentum, pgCount),\n div_factor,\n final_div_factor,\n three_phase,\n last_epoch);\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n public OneCycleLR(Optimizer optimizer,\n IEnumerable<double> max_lr,\n int total_steps = -1,\n int epochs = -1,\n int steps_per_epoch = -1,\n double pct_start = 0.3,\n AnnealStrategy anneal_strategy = AnnealStrategy.Cos,\n bool cycle_momentum = true,\n IEnumerable<double> base_momentum = null,\n IEnumerable<double> max_momentum = null,\n double div_factor = 25,\n double final_div_factor = 1e4,\n bool three_phase = false,\n int last_epoch = -1, bool verbose = false) : base(optimizer, last_epoch, verbose)\n {\n if (optimizer == null) throw new ArgumentNullException(\"optimizer\");\n\n Initialize(optimizer,\n max_lr,\n total_steps,\n epochs,\n steps_per_epoch,\n pct_start,\n anneal_strategy,\n cycle_momentum,\n base_momentum,\n max_momentum,\n div_factor,\n final_div_factor,\n three_phase,\n last_epoch);\n }\n\n private void Initialize(Optimizer optimizer, IEnumerable<double> max_lr, int total_steps, int epochs, int steps_per_epoch, double pct_start, AnnealStrategy anneal_strategy, bool cycle_momentum, IEnumerable<double> base_momentum, IEnumerable<double> max_momentum, double div_factor, double final_div_factor, bool three_phase, int last_epoch)\n {\n _cycle_momentum = cycle_momentum;\n\n var pgs = optimizer.ParamGroups.ToList();\n\n if (cycle_momentum) {\n var _momentum = optimizer as IMomentum;\n var _betas = optimizer as IBetas;\n if (_momentum == null && _betas == null) throw new ArgumentException($\"optimizer must support momentum with `cycle_momentum` option enabled\");\n }\n\n if (pct_start < 0 || pct_start > 1) throw new ArgumentException($\"Expected float between 0 and 1 for pct_start, but got {pct_start}\");\n\n if (total_steps == -1 && epochs == -1 && steps_per_epoch == -1) {\n throw new ArgumentException(\"You must define either total_steps OR (epochs AND steps_per_epoch)\");\n } else if (total_steps != -1) {\n if (total_steps <= 0) throw new ArgumentException($\"Expected positive integer total_steps, but got {total_steps}\");\n _total_steps = total_steps;\n } else {\n if (epochs <= 0) throw new ArgumentException($\"Expected positive integer epochs, but got {epochs}\");\n if (steps_per_epoch <= 0) throw new ArgumentException($\"Expected positive integer steps_per_epoch, but got {steps_per_epoch}\");\n _total_steps = epochs * steps_per_epoch;\n }\n\n var mlr = max_lr.ToList();\n\n _betas = pgs.Select(pg => pg as IBetas).ToList();\n _momentum = pgs.Select(pg => pg as IMomentum).ToList();\n\n var initial_lrs = max_lr.Select(mlr => mlr / div_factor).ToList();\n\n _phase_values[\"initial_lr\"] = initial_lrs;\n _phase_values[\"max_lr\"] = mlr;\n _phase_values[\"min_lr\"] = initial_lrs.Select(ilr => ilr / final_div_factor).ToList();\n\n _annealing_func = (anneal_strategy == AnnealStrategy.Cos)\n ? (start, end, pct) => end + (start - end) / 2.0 * (Math.Cos(Math.PI * pct) + 1)\n : (start, end, pct) => (end - start) * pct + start;\n\n _schedule_phases = three_phase\n ? new PhaseDescriptor[] {\n new PhaseDescriptor { end_step = pct_start * _total_steps - 1, start_lr = \"initial_lr\", end_lr = \"max_lr\", start_momentum = \"max_momentum\", end_momentum = \"base_momentum\" },\n new PhaseDescriptor { end_step = 2 * pct_start * _total_steps - 2, start_lr = \"max_lr\", end_lr = \"initial_lr\", start_momentum = \"base_momentum\", end_momentum = \"max_momentum\" },\n new PhaseDescriptor { end_step = _total_steps - 1, start_lr = \"initial_lr\", end_lr = \"min_lr\", start_momentum = \"max_momentum\", end_momentum = \"max_momentum\" }\n }\n : new PhaseDescriptor[] {\n new PhaseDescriptor { end_step = pct_start * _total_steps - 1, start_lr = \"initial_lr\", end_lr = \"max_lr\", start_momentum = \"max_momentum\", end_momentum = \"base_momentum\" },\n new PhaseDescriptor { end_step = _total_steps - 1, start_lr = \"max_lr\", end_lr = \"min_lr\", start_momentum = \"base_momentum\", end_momentum = \"max_momentum\" },\n };\n\n if (last_epoch == -1) {\n\n if (cycle_momentum) {\n\n var _base_momentum = (base_momentum is null) ? Enumerable.Repeat(0.85, pgs.Count).ToList() : base_momentum.ToList();\n var _max_momentum = (max_momentum is null) ? Enumerable.Repeat(0.95, pgs.Count).ToList() : max_momentum.ToList();\n\n for (int i = 0; i < pgs.Count; i++) {\n if (_betas[i] != null) {\n var (_, beta2) = _betas[i].Betas;\n _betas[i].Betas = (_max_momentum[i], beta2);\n } else {\n if (_momentum[i] != null)\n _momentum[i].Momentum = _max_momentum[i];\n }\n }\n _phase_values[\"max_momentum\"] = _max_momentum;\n _phase_values[\"base_momentum\"] = _base_momentum;\n }\n }\n step();\n }\n\n /// <summary>\n /// Compute the current learning rate for the scheduler.\n /// </summary>\n protected override IEnumerable<double> get_lr()\n {\n var step_num = _last_epoch;\n if (step_num > _total_steps) {\n throw new InvalidOperationException($\"Tried to step {step_num + 1} times. The specified number of total steps is {_total_steps}\");\n }\n\n var pgs = _optimizer.ParamGroups.ToList();\n\n return Enumerable.Range(0, pgs.Count).Select(i => {\n\n double start_step = 0;\n double computed_lr = 0;\n double computed_momentum = 0;\n\n for (var j = 0; j < _schedule_phases.Length; j++) {\n\n var phase = _schedule_phases[j];\n var end_step = phase.end_step;\n\n if (step_num <= end_step || i == _schedule_phases.Length - 1) {\n var pct = (step_num - start_step) / (end_step - start_step);\n computed_lr = _annealing_func(_phase_values[phase.start_lr][i], _phase_values[phase.end_lr][i], pct);\n if (_cycle_momentum) {\n computed_momentum = _annealing_func(_phase_values[phase.start_momentum][i], _phase_values[phase.end_momentum][i], pct);\n }\n break;\n }\n start_step = phase.end_step;\n }\n\n if (_cycle_momentum) {\n if (_betas[i] != null) {\n var (_, beta2) = _betas[i].Betas;\n _betas[i].Betas = (computed_momentum, beta2);\n } else {\n _momentum[i].Momentum = computed_momentum;\n }\n }\n return computed_lr;\n });\n }\n\n private Func<double, double, double, double> _annealing_func;\n\n private PhaseDescriptor[] _schedule_phases;\n private Dictionary<string, List<double>> _phase_values = new Dictionary<string, List<double>>();\n\n private bool _cycle_momentum;\n\n private List<IBetas> _betas;\n private List<IMomentum> _momentum;\n\n private int _total_steps;\n\n private class PhaseDescriptor\n {\n public double end_step;\n public string start_lr;\n public string end_lr;\n public string start_momentum;\n public string end_momentum;\n }\n }\n\n /// <summary>\n /// Chains list of learning rate schedulers. It takes a list of chainable learning rate schedulers and applies step() to all of them.\n /// </summary>\n public class ChainedLR : LRScheduler\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"schedulers\">List of chained schedulers.</param>\n /// <returns>A scheduler</returns>\n public ChainedLR(IEnumerable<LRScheduler> schedulers)\n {\n _schedulers = schedulers;\n }\n\n public override void step()\n {\n foreach (var sched in _schedulers) {\n sched.step();\n }\n }\n\n private IEnumerable<LRScheduler> _schedulers;\n }\n }\n\n /// <summary>\n /// Decays the learning rate of each parameter group by gamma every step_size epochs.\n /// Notice that such decay can happen simultaneously with other changes to the learning rate from outside this scheduler.\n /// When last_epoch=-1, sets initial lr as lr.\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"step_size\">Period of learning rate decay.</param>\n /// <param name=\"gamma\">Multiplicative factor of learning rate decay. Default: 0.1.</param>\n /// <param name=\"last_epoch\">\n /// The index of the last batch. This parameter is used when resuming a training job.Since `step()` should be invoked after each\n /// batch instead of after each epoch, this number represents the total number of *batches* computed, not the total number of epochs computed.\n /// When last_epoch = -1, the schedule is started from the beginning.\n /// </param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public static LRScheduler StepLR(Optimizer optimizer, int step_size, double gamma = 0.1, int last_epoch = -1, bool verbose = false)\n {\n return new impl.StepLR(optimizer, step_size, gamma, last_epoch, verbose);\n }\n\n /// <summary>\n /// Sets the learning rate of each parameter group to the initial lr times a given function.\n /// When last_epoch=-1, sets initial lr as lr.\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"lr_lambda\">A function which computes a multiplicative factor given an integer parameter epoch.</param>\n /// <param name=\"last_epoch\">\n /// The index of the last batch. This parameter is used when resuming a training job.Since `step()` should be invoked after each\n /// batch instead of after each epoch, this number represents the total number of *batches* computed, not the total number of epochs computed.\n /// When last_epoch = -1, the schedule is started from the beginning.\n /// </param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public static LRScheduler LambdaLR(Optimizer optimizer, Func<int, double> lr_lambda, int last_epoch = -1, bool verbose = false)\n {\n return new impl.LambdaLR(optimizer, lr_lambda, last_epoch, verbose);\n\n }\n\n /// <summary>\n /// Decays the learning rate of each parameter group by gamma once the number of epoch reaches one of the milestones.\n /// Notice that such decay can happen simultaneously with other changes to the learning rate from outside this scheduler.\n /// When last_epoch=-1, sets initial lr as lr.\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"milestones\">List of epoch indices. Must be increasing.</param>\n /// <param name=\"gamma\">Multiplicative factor of learning rate decay. Default: 0.1.</param>\n /// <param name=\"last_epoch\">\n /// The index of the last batch. This parameter is used when resuming a training job.Since `step()` should be invoked after each\n /// batch instead of after each epoch, this number represents the total number of *batches* computed, not the total number of epochs computed.\n /// When last_epoch = -1, the schedule is started from the beginning.\n /// </param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public static LRScheduler MultiStepLR(Optimizer optimizer, IList<int> milestones, double gamma = 0.1, int last_epoch = -1, bool verbose = false)\n {\n return new impl.MultiStepLR(optimizer, milestones, gamma, last_epoch, verbose);\n\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"total_iters\">The number of steps that the scheduler decays the learning rate.</param>\n /// <param name=\"power\">The power of the polynomial.</param>\n /// <param name=\"last_epoch\">The index of last epoch. Default: -1.</param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public static LRScheduler PolynomialLR(Optimizer optimizer, int total_iters = 5, int power = 1, int last_epoch = -1, bool verbose = false)\n {\n return new impl.PolynomialLR(optimizer, total_iters, power, last_epoch, verbose);\n }\n\n /// <summary>\n /// Multiply the learning rate of each parameter group by the factor given in the specified function.\n /// When last_epoch = -1, sets initial lr as lr.\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"lr_lambda\">A function which computes a multiplicative factor given an integer parameter epoch.</param>\n /// <param name=\"last_epoch\">\n /// The index of the last batch. This parameter is used when resuming a training job.Since `step()` should be invoked after each\n /// batch instead of after each epoch, this number represents the total number of *batches* computed, not the total number of epochs computed.\n /// When last_epoch = -1, the schedule is started from the beginning.\n /// </param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public static LRScheduler MultiplicativeLR(Optimizer optimizer, Func<int, double> lr_lambda, int last_epoch = -1, bool verbose = false)\n {\n return new impl.MultiplicativeLR(optimizer, lr_lambda, last_epoch, verbose);\n\n }\n\n /// <summary>\n /// Decays the learning rate of each parameter group by gamma every epoch.\n /// Notice that such decay can happen simultaneously with other changes to the learning rate from outside this scheduler.\n /// When last_epoch=-1, sets initial lr as lr.\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"gamma\">Multiplicative factor of learning rate decay. Default: 0.1.</param>\n /// <param name=\"last_epoch\">\n /// The index of the last batch. This parameter is used when resuming a training job.Since `step()` should be invoked after each\n /// batch instead of after each epoch, this number represents the total number of *batches* computed, not the total number of epochs computed.\n /// When last_epoch = -1, the schedule is started from the beginning.\n /// </param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public static LRScheduler ExponentialLR(Optimizer optimizer, double gamma = 0.1, int last_epoch = -1, bool verbose = false)\n {\n return new impl.ExponentialLR(optimizer, gamma, last_epoch, verbose);\n }\n\n /// <summary>\n /// Decays the learning rate of each parameter group by a small constant factor until the number of epoch reaches a pre-defined milestone: total_iters.\n /// Notice that such decay can happen simultaneously with other changes to the learning rate from outside this scheduler.\n /// When last_epoch=-1, sets initial lr as lr.\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"factor\">The number we multiply learning rate until the milestone.</param>\n /// <param name=\"total_iters\">The number of steps that the scheduler decays the learning rate.</param>\n /// <param name=\"last_epoch\">\n /// The index of the last batch. This parameter is used when resuming a training job.Since `step()` should be invoked after each\n /// batch instead of after each epoch, this number represents the total number of *batches* computed, not the total number of epochs computed.\n /// When last_epoch = -1, the schedule is started from the beginning.\n /// </param>\n /// <param name=\"verbose\">If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public static LRScheduler ConstantLR(Optimizer optimizer, double factor = 1.0 / 3, int total_iters = 5, int last_epoch = -1, bool verbose = false)\n {\n return new impl.ConstantLR(optimizer, factor, total_iters, last_epoch, verbose);\n }\n\n /// <summary>\n /// Uses a list of schedulers, chosen based on the epoch. A sequence of milestones determines when a switch occurs from one scheduler to the next.\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer. All sub-schedulers must be bound to the same optimizer.</param>\n /// <param name=\"schedulers\">List of chained schedulers. Should be one more than the number of milestones.</param>\n /// <param name=\"milestones\">List of integers reflecting the milestone points.</param>\n /// <param name=\"last_epoch\">The index of last epoch. Default: -1.</param>\n /// <returns></returns>\n /// <remarks>The 'verbose' flag should be passed to each individual sub-scheduler.</remarks>\n public static LRScheduler SequentialLR(Optimizer optimizer, IEnumerable<LRScheduler> schedulers, IEnumerable<int> milestones, int last_epoch = -1)\n {\n return new impl.SequentialLR(optimizer, schedulers, milestones, last_epoch);\n }\n\n /// <summary>\n /// Decays the learning rate of each parameter group by linearly changing small multiplicative factor until the\n /// number of epoch reaches a pre-defined milestone: total_iters.\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"start_factor\">The number we multiply learning rate in the first epoch. The multiplication factor changes towards end_factor in the following epochs.</param>\n /// <param name=\"end_factor\">The number we multiply learning rate at the end of linear changing process.</param>\n /// <param name=\"total_iters\">The number of steps that the scheduler decays the learning rate.</param>\n /// <param name=\"last_epoch\">\n /// The index of the last batch. This parameter is used when resuming a training job.Since `step()` should be invoked after each\n /// batch instead of after each epoch, this number represents the total number of *batches* computed, not the total number of epochs computed.\n /// When last_epoch = -1, the schedule is started from the beginning.\n /// </param>\n /// <param name=\"verbose\">If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public static LRScheduler LinearLR(Optimizer optimizer, double start_factor = 1.0 / 3, double end_factor = 5, int total_iters = 5, int last_epoch = -1, bool verbose = false)\n {\n return new impl.LinearLR(optimizer, start_factor, end_factor, total_iters, last_epoch, verbose);\n }\n\n /// <summary>\n /// Chains list of learning rate schedulers. It takes a list of chainable learning rate schedulers and applies step() to all of them.\n /// </summary>\n ///<param name=\"schedulers\">List of chained schedulers.</param>\n /// <returns>A scheduler</returns>\n public static LRScheduler ChainedLR(IEnumerable<LRScheduler> schedulers)\n {\n return new impl.ChainedLR(schedulers);\n }\n\n /// <summary>\n /// Sets the learning rate using a cosine annealing schedule.\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"T_max\">Maximum number of iterations.</param>\n /// <param name=\"eta_min\">Minimum learning rate.</param>\n /// <param name=\"last_epoch\">\n /// The index of the last batch. This parameter is used when resuming a training job.Since `step()` should be invoked after each\n /// batch instead of after each epoch, this number represents the total number of *batches* computed, not the total number of epochs computed.\n /// When last_epoch = -1, the schedule is started from the beginning.\n /// </param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public static LRScheduler CosineAnnealingLR(Optimizer optimizer, double T_max, double eta_min = 0, int last_epoch = -1, bool verbose = false)\n {\n return new impl.CosineAnnealingLR(optimizer, T_max, eta_min, last_epoch, verbose);\n }\n\n /// <summary>\n /// Sets the learning rate of each parameter group according to the\n /// 1cycle learning rate policy.The 1cycle policy anneals the learning\n /// rate from an initial learning rate to some maximum learning rate and then\n /// from that maximum learning rate to some minimum learning rate much lower\n /// than the initial learning rate.\n /// \n /// This policy was initially described in the paper `Super-Convergence:\n /// Very Fast Training of Neural Networks Using Large Learning Rates`_.\n ///\n /// The 1cycle learning rate policy changes the learning rate after every batch.\n /// `step` should be called after a batch has been used for training.\n ///\n /// This scheduler is not chainable. \n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"max_lr\">Upper learning rate boundaries in the cycle</param>\n /// <param name=\"total_steps\">\n /// The total number of steps in the cycle.\n /// Note that if a value is not provided here, then it must be inferred by providing a value for epochs and steps_per_epoch.\n /// </param>\n /// <param name=\"epochs\">\n /// The number of epochs to train for. This is used along\n /// with steps_per_epoch in order to infer the total number of steps in the cycle\n /// if a value for total_steps is not provided.\n /// </param>\n /// <param name=\"steps_per_epoch\">\n /// The number of steps per epoch to train for. This is\n /// used along with epochs in order to infer the total number of steps in the\n /// cycle if a value for total_steps is not provided.\n /// </param>\n /// <param name=\"pct_start\">The percentage of the cycle (in number of steps) spent increasing the learning rate.</param>\n /// <param name=\"anneal_strategy\">Specifies the annealing strategy: \"cos\" for cosine annealing, \"linear\" for linear annealing.</param>\n /// <param name=\"cycle_momentum\">If true, momentum is cycled inversely to learning rate between 'base_momentum' and 'max_momentum'.</param>\n /// <param name=\"base_momentum\">\n /// Lower momentum boundaries in the cycle\n /// for each parameter group.Note that momentum is cycled inversely\n /// to learning rate; at the peak of a cycle, momentum is\n /// 'base_momentum' and learning rate is 'max_lr'.\n /// </param>\n /// <param name=\"max_momentum\">\n /// Upper momentum boundaries in the cycle for each parameter group.\n /// Functionally, it defines the cycle amplitude(max_momentum - base_momentum).\n /// Note that momentum is cycled inversely to learning rate; at the start of a cycle, momentum is 'max_momentum'\n /// and learning rate is 'base_lr'\n /// </param>\n /// <param name=\"div_factor\">Determines the initial learning rate via initial_lr = max_lr/div_factor</param>\n /// <param name=\"final_div_factor\">Determines the minimum learning rate via min_lr = initial_lr/final_div_factor</param>\n /// <param name=\"three_phase\">\n /// If ``True``, use a third phase of the schedule to annihilate the\n /// learning rate according to 'final_div_factor' instead of modifying the second\n /// phase (the first two phases will be symmetrical about the step indicated by 'pct_start').\n /// </param>\n /// <param name=\"last_epoch\">\n /// The index of the last batch. This parameter is used when resuming a training job.Since `step()` should be invoked after each\n /// batch instead of after each epoch, this number represents the total number of *batches* computed, not the total number of epochs computed.\n /// When last_epoch = -1, the schedule is started from the beginning.\n /// </param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n /// <remarks>\n /// Note also that the total number of steps in the cycle can be determined in one\n /// of two ways (listed in order of precedence):\n ///\n /// #. A value for total_steps is explicitly provided.\n /// #. A number of epochs (epochs) and a number of steps per epoch\n /// (steps_per_epoch) are provided.\n /// In this case, the number of total steps is inferred by\n /// total_steps = epochs * steps_per_epoch\n ///\n /// You must either provide a value for total_steps or provide a value for both\n /// epochs and steps_per_epoch.\n ///\n /// The default behaviour of this scheduler follows the fastai implementation of 1cycle, which\n /// claims that \"unpublished work has shown even better results by using only two phases\". To\n /// mimic the behaviour of the original paper instead, set ``three_phase= True``.\n /// </remarks>\n public static LRScheduler OneCycleLR(Optimizer optimizer,\n double max_lr,\n int total_steps = -1,\n int epochs = -1,\n int steps_per_epoch = -1,\n double pct_start = 0.3,\n impl.OneCycleLR.AnnealStrategy anneal_strategy = impl.OneCycleLR.AnnealStrategy.Cos,\n bool cycle_momentum = true,\n double base_momentum = 0.85,\n double max_momentum = 0.95,\n double div_factor = 25,\n double final_div_factor = 1e4,\n bool three_phase = false,\n int last_epoch = -1, bool verbose = false)\n {\n return new impl.OneCycleLR(optimizer, max_lr, total_steps, epochs, steps_per_epoch, pct_start, anneal_strategy, cycle_momentum, base_momentum, max_momentum, div_factor, final_div_factor, three_phase, last_epoch, verbose);\n }\n\n /// <summary>\n /// Sets the learning rate of each parameter group according to the\n /// 1cycle learning rate policy.The 1cycle policy anneals the learning\n /// rate from an initial learning rate to some maximum learning rate and then\n /// from that maximum learning rate to some minimum learning rate much lower\n /// than the initial learning rate.\n /// \n /// This policy was initially described in the paper `Super-Convergence:\n /// Very Fast Training of Neural Networks Using Large Learning Rates`_.\n ///\n /// The 1cycle learning rate policy changes the learning rate after every batch.\n /// `step` should be called after a batch has been used for training.\n ///\n /// This scheduler is not chainable. \n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"max_lr\">Upper learning rate boundaries in the cycle</param>\n /// <param name=\"total_steps\">\n /// The total number of steps in the cycle.\n /// Note that if a value is not provided here, then it must be inferred by providing a value for epochs and steps_per_epoch.\n /// </param>\n /// <param name=\"epochs\">\n /// The number of epochs to train for. This is used along\n /// with steps_per_epoch in order to infer the total number of steps in the cycle\n /// if a value for total_steps is not provided.\n /// </param>\n /// <param name=\"steps_per_epoch\">\n /// The number of steps per epoch to train for. This is\n /// used along with epochs in order to infer the total number of steps in the\n /// cycle if a value for total_steps is not provided.\n /// </param>\n /// <param name=\"pct_start\">The percentage of the cycle (in number of steps) spent increasing the learning rate.</param>\n /// <param name=\"anneal_strategy\">Specifies the annealing strategy: \"cos\" for cosine annealing, \"linear\" for linear annealing.</param>\n /// <param name=\"cycle_momentum\">If true, momentum is cycled inversely to learning rate between 'base_momentum' and 'max_momentum'.</param>\n /// <param name=\"base_momentum\">\n /// Lower momentum boundaries in the cycle\n /// for each parameter group.Note that momentum is cycled inversely\n /// to learning rate; at the peak of a cycle, momentum is\n /// 'base_momentum' and learning rate is 'max_lr'.\n /// </param>\n /// <param name=\"max_momentum\">\n /// Upper momentum boundaries in the cycle for each parameter group.\n /// Functionally, it defines the cycle amplitude(max_momentum - base_momentum).\n /// Note that momentum is cycled inversely to learning rate; at the start of a cycle, momentum is 'max_momentum'\n /// and learning rate is 'base_lr'\n /// </param>\n /// <param name=\"div_factor\">Determines the initial learning rate via initial_lr = max_lr/div_factor</param>\n /// <param name=\"final_div_factor\">Determines the minimum learning rate via min_lr = initial_lr/final_div_factor</param>\n /// <param name=\"three_phase\">\n /// If ``True``, use a third phase of the schedule to annihilate the\n /// learning rate according to 'final_div_factor' instead of modifying the second\n /// phase (the first two phases will be symmetrical about the step indicated by 'pct_start').\n /// </param>\n /// <param name=\"last_epoch\">\n /// The index of the last batch. This parameter is used when resuming a training job.Since `step()` should be invoked after each\n /// batch instead of after each epoch, this number represents the total number of *batches* computed, not the total number of epochs computed.\n /// When last_epoch = -1, the schedule is started from the beginning.\n /// </param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n /// <remarks>\n /// Note also that the total number of steps in the cycle can be determined in one\n /// of two ways (listed in order of precedence):\n ///\n /// #. A value for total_steps is explicitly provided.\n /// #. A number of epochs (epochs) and a number of steps per epoch\n /// (steps_per_epoch) are provided.\n /// In this case, the number of total steps is inferred by\n /// total_steps = epochs * steps_per_epoch\n ///\n /// You must either provide a value for total_steps or provide a value for both\n /// epochs and steps_per_epoch.\n ///\n /// The default behaviour of this scheduler follows the fastai implementation of 1cycle, which\n /// claims that \"unpublished work has shown even better results by using only two phases\". To\n /// mimic the behaviour of the original paper instead, set ``three_phase= True``.\n /// </remarks>\n public static LRScheduler OneCycleLR(Optimizer optimizer,\n IEnumerable<double> max_lr,\n int total_steps = -1,\n int epochs = -1,\n int steps_per_epoch = -1,\n double pct_start = 0.3,\n impl.OneCycleLR.AnnealStrategy anneal_strategy = impl.OneCycleLR.AnnealStrategy.Cos,\n bool cycle_momentum = true,\n IEnumerable<double> base_momentum = null,\n IEnumerable<double> max_momentum = null,\n double div_factor = 25,\n double final_div_factor = 1e4,\n bool three_phase = false,\n int last_epoch = -1, bool verbose = false)\n {\n return new impl.OneCycleLR(optimizer, max_lr, total_steps, epochs, steps_per_epoch, pct_start, anneal_strategy, cycle_momentum, base_momentum, max_momentum, div_factor, final_div_factor, three_phase, last_epoch, verbose);\n }\n\n /// <summary>\n /// Sets the learning rate of each parameter group according to\n /// cyclical learning rate policy(CLR). The policy cycles the learning\n /// rate between two boundaries with a constant frequency, as detailed in\n /// the paper `Cyclical Learning Rates for Training Neural Networks`_.\n /// The distance between the two boundaries can be scaled on a per-iteration\n /// or per-cycle basis.\n ///\n /// Cyclical learning rate policy changes the learning rate after every batch.\n /// `step` should be called after a batch has been used for training.\n ///\n /// This class has three built-in policies, as put forth in the paper:\n /// * \"triangular\": A basic triangular cycle without amplitude scaling.\n /// * \"triangular2\": A basic triangular cycle that scales initial amplitude by half each cycle.\n /// * \"exp_range\": A cycle that scales initial amplitude by gamma^(cycle iterations).\n /// }`\n /// at each cycle iteration.\n /// /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"base_lr\">Initial learning rate which is the lower boundary in the cycle</param>\n /// <param name=\"max_lr\">\n /// Upper learning rate boundaries in the cycle for each parameter group.\n /// Functionally, it defines the cycle amplitude(max_lr - base_lr).\n /// The lr at any cycle is the sum of base_lr and some scaling of the amplitude; therefore \n /// max_lr may not actually be reached depending on the scaling function.\n /// </param>\n /// <param name=\"step_size_up\">Number of training iterations in the increasing half of a cycle.</param>\n /// <param name=\"step_size_down\">\n /// Number of training iterations in the decreasing half of a cycle.\n /// If step_size_down is -1, it is set to step_size_up.\n /// </param>\n /// <param name=\"mode\">Values correspond to policies detailed above. If scale_fn is non-null, this argument is ignored.</param>\n /// <param name=\"gamma\">Constant in 'exp_range' scaling function</param>\n /// <param name=\"scale_fn\">Custom scaling policy defined by a single argument lambda function. If specified, then 'mode' is ignored.</param>\n /// <param name=\"scale_mode\">Defines whether scale_fn is evaluated on cycle number or cycle iterations(training iterations since start of cycle)</param>\n /// <param name=\"cycle_momentum\">If true, momentum is cycled inversely to learning rate between 'base_momentum' and 'max_momentum'.</param>\n /// <param name=\"base_momentum\">Lower momentum boundaries in the cycle. Note that momentum is cycled inversely to learning rate</param>\n /// <param name=\"max_momentum\">\n /// Upper momentum boundaries in the cycle.\n /// Functionally, it defines the cycle amplitude(max_momentum - base_momentum).\n /// The momentum at any cycle is the difference of max_momentum and some scaling of the amplitude; therefore\n /// base_momentum may not actually be reached depending on the scaling function.\n /// </param>\n /// <param name=\"last_epoch\">\n /// The index of the last batch. This parameter is used when resuming a training job.Since `step()` should be invoked after each\n /// batch instead of after each epoch, this number represents the total number of *batches* computed, not the total number of epochs computed.\n /// When last_epoch = -1, the schedule is started from the beginning.\n /// </param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public static LRScheduler CyclicLR(Optimizer optimizer,\n double base_lr,\n double max_lr,\n int step_size_up = 2000,\n int step_size_down = -1,\n impl.CyclicLR.Mode mode = impl.CyclicLR.Mode.Triangular,\n double gamma = 1.0,\n Func<double, double> scale_fn = null,\n impl.CyclicLR.ScaleMode scale_mode = impl.CyclicLR.ScaleMode.Cycle,\n bool cycle_momentum = true,\n double base_momentum = 0.8,\n double max_momentum = 0.9,\n int last_epoch = -1,\n bool verbose = false)\n {\n return new impl.CyclicLR(optimizer, base_lr, max_lr, step_size_up, step_size_down, mode, gamma, scale_fn, scale_mode, cycle_momentum, base_momentum, max_momentum, last_epoch, verbose);\n }\n\n /// <summary>\n /// Sets the learning rate of each parameter group according to\n /// cyclical learning rate policy(CLR). The policy cycles the learning\n /// rate between two boundaries with a constant frequency, as detailed in\n /// the paper `Cyclical Learning Rates for Training Neural Networks`_.\n /// The distance between the two boundaries can be scaled on a per-iteration\n /// or per-cycle basis.\n ///\n /// Cyclical learning rate policy changes the learning rate after every batch.\n /// `step` should be called after a batch has been used for training.\n ///\n /// This class has three built-in policies, as put forth in the paper:\n /// * \"triangular\": A basic triangular cycle without amplitude scaling.\n /// * \"triangular2\": A basic triangular cycle that scales initial amplitude by half each cycle.\n /// * \"exp_range\": A cycle that scales initial amplitude by gamma^(cycle iterations).\n /// }`\n /// at each cycle iteration.\n /// /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"base_lr\">Initial learning rate which is the lower boundary in the cycle</param>\n /// <param name=\"max_lr\">\n /// Upper learning rate boundaries in the cycle for each parameter group.\n /// Functionally, it defines the cycle amplitude(max_lr - base_lr).\n /// The lr at any cycle is the sum of base_lr and some scaling of the amplitude; therefore \n /// max_lr may not actually be reached depending on the scaling function.\n /// </param>\n /// <param name=\"step_size_up\">Number of training iterations in the increasing half of a cycle.</param>\n /// <param name=\"step_size_down\">\n /// Number of training iterations in the decreasing half of a cycle.\n /// If step_size_down is -1, it is set to step_size_up.\n /// </param>\n /// <param name=\"mode\">Values correspond to policies detailed above. If scale_fn is non-null, this argument is ignored.</param>\n /// <param name=\"gamma\">Constant in 'exp_range' scaling function</param>\n /// <param name=\"scale_fn\">Custom scaling policy defined by a single argument lambda function. If specified, then 'mode' is ignored.</param>\n /// <param name=\"scale_mode\">Defines whether scale_fn is evaluated on cycle number or cycle iterations(training iterations since start of cycle)</param>\n /// <param name=\"cycle_momentum\">If true, momentum is cycled inversely to learning rate between 'base_momentum' and 'max_momentum'.</param>\n /// <param name=\"base_momentum\">Lower momentum boundaries in the cycle. Note that momentum is cycled inversely to learning rate</param>\n /// <param name=\"max_momentum\">\n /// Upper momentum boundaries in the cycle.\n /// Functionally, it defines the cycle amplitude(max_momentum - base_momentum).\n /// The momentum at any cycle is the difference of max_momentum and some scaling of the amplitude; therefore\n /// base_momentum may not actually be reached depending on the scaling function.\n /// </param>\n /// <param name=\"last_epoch\">\n /// The index of the last batch. This parameter is used when resuming a training job.Since `step()` should be invoked after each\n /// batch instead of after each epoch, this number represents the total number of *batches* computed, not the total number of epochs computed.\n /// When last_epoch = -1, the schedule is started from the beginning.\n /// </param>\n /// <param name=\"verbose\"> If true, prints a message to stdout for each update. Default: false.</param>\n /// <returns>A scheduler</returns>\n public static LRScheduler CyclicLR(Optimizer optimizer,\n IEnumerable<double> base_lr,\n IEnumerable<double> max_lr,\n int step_size_up = 2000,\n int step_size_down = -1,\n impl.CyclicLR.Mode mode = impl.CyclicLR.Mode.Triangular,\n double gamma = 1.0,\n Func<double, double> scale_fn = null,\n impl.CyclicLR.ScaleMode scale_mode = impl.CyclicLR.ScaleMode.Cycle,\n bool cycle_momentum = true,\n IEnumerable<double> base_momentum = null,\n IEnumerable<double> max_momentum = null,\n int last_epoch = -1,\n bool verbose = false)\n {\n return new impl.CyclicLR(optimizer, base_lr, max_lr, step_size_up, step_size_down, mode, gamma, scale_fn, scale_mode, cycle_momentum, base_momentum, max_momentum, last_epoch, verbose);\n }\n\n /// <summary>\n /// Reduce learning rate when a metric has stopped improving.\n /// Models often benefit from reducing the learning rate by a factor of 2-10 once learning stagnates.\n /// This scheduler reads a metrics quantity and if no improvement is seen for a ‘patience’ number of epochs, the learning rate is reduced.\n /// </summary>\n /// <param name=\"optimizer\">Wrapped optimizer.</param>\n /// <param name=\"mode\">\n /// One of min, max. In min mode, lr will be reduced when the quantity monitored has stopped decreasing;\n /// in max mode it will be reduced when the quantity monitored has stopped increasing. Default: ‘min’\n /// </param>\n /// <param name=\"factor\">Factor by which the learning rate will be reduced. new_lr = lr * factor.</param>\n /// <param name=\"patience\">\n /// Number of epochs with no improvement after which learning rate will be reduced. For example, if patience = 2,\n /// then we will ignore the first 2 epochs with no improvement, and will only decrease the LR after the 3rd epoch if\n /// the loss still hasn’t improved then. Default: 10.</param>\n /// <param name=\"threshold\">Threshold for measuring the new optimum, to only focus on significant changes. </param>\n /// <param name=\"threshold_mode\">\n /// One of rel, abs. In rel mode, dynamic_threshold = best * ( 1 + threshold ) in ‘max’ mode or best * ( 1 - threshold ) in min mode. In abs mode, dynamic_threshold = best + threshold in max mode or best - threshold in min mode. Default: ‘rel’.\n /// </param>\n /// <param name=\"cooldown\">Number of epochs to wait before resuming normal operation after lr has been reduced.</param>\n /// <param name=\"min_lr\">A scalar or a list of scalars. A lower bound on the learning rate of all param groups or each group respectively. Default: 0.</param>\n /// <param name=\"eps\">Minimal decay applied to lr. If the difference between new and old lr is smaller than eps, the update is ignored. Default: 1e-8.</param>\n /// <param name=\"verbose\">Indicates whether to print a message to stdout for each update</param>\n public static LRScheduler ReduceLROnPlateau(Optimizer optimizer, string mode = \"min\", double factor = 0.1, int patience = 10, double threshold = 1e-4, string threshold_mode = \"rel\", int cooldown = 0, IList<double> min_lr = null, double eps = 1e-8, bool verbose = false)\n {\n return new impl.ReduceLROnPlateau(optimizer, mode, factor, patience, threshold, threshold_mode, cooldown, min_lr, eps, verbose);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.7059859037399292, "alphanum_fraction": 0.7059859037399292, "avg_line_length": 39.64285659790039, "blob_id": "1755d0a70f8e09c480d5933b1fdac547058547db", "content_id": "5e2c09e91c5415828c8995690ac86947ab7b5fd7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 570, "license_type": "permissive", "max_line_length": 131, "num_lines": 14, "path": "/src/TorchSharp/Tensor/torch.Serialization.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nnamespace TorchSharp\n{\n // https://pytorch.org/docs/stable/torch#serialization\n public static partial class torch\n {\n // https://pytorch.org/docs/stable/generated/torch.save\n public static void save(Tensor t, string location) => t.save(location);\n\n // https://pytorch.org/docs/stable/generated/torch.load\n public static Tensor load(string location) => Tensor.load(location);\n }\n}" }, { "alpha_fraction": 0.6069402098655701, "alphanum_fraction": 0.6089553833007812, "avg_line_length": 47.78291320800781, "blob_id": "8e4cc20afc504632ff9d714d4b4e5cde5a35d44b", "content_id": "0fccbd8ce82bb250c0ad0424b5030b0fff70e45d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 83377, "license_type": "permissive", "max_line_length": 197, "num_lines": 1709, "path": "/src/TorchSharp/Tensor/torch.PointwiseOps.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing ICSharpCode.SharpZipLib.BZip2;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n // https://pytorch.org/docs/stable/generated/torch.abs\n /// <summary>\n /// Compute the absolute value of each element in the tensor\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor abs(Tensor input) => input.abs();\n\n // https://pytorch.org/docs/stable/generated/torch.abs\n /// <summary>\n /// Compute the absolute value of each element in the tensor, in-place\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor abs_(Tensor input) => input.abs_();\n\n // https://pytorch.org/docs/stable/generated/torch.absolute\n /// <summary>\n /// Compute the absolute value of each element in the tensor\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor absolute(Tensor input) => input.absolute();\n\n // https://pytorch.org/docs/stable/generated/torch.absolute\n /// <summary>\n /// Compute the absolute value of each element in the tensor, in-place\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor absolute_(Tensor input) => input.absolute_();\n\n // https://pytorch.org/docs/stable/generated/torch.acos\n /// <summary>\n /// Computes the arccosine of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor acos(Tensor input) => input.acos();\n\n // https://pytorch.org/docs/stable/generated/torch.acos\n /// <summary>\n /// Computes the arccosine of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor acos_(Tensor input) => input.acos_();\n\n // https://pytorch.org/docs/stable/generated/torch.arccos\n /// <summary>\n /// Computes the arccosine of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor arccos(Tensor input) => input.arccos();\n\n // https://pytorch.org/docs/stable/generated/torch.arccos\n /// <summary>\n /// Computes the arccosine of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor arccos_(Tensor input) => input.arccos_();\n\n // https://pytorch.org/docs/stable/generated/torch.acosh\n /// <summary>\n /// Computes the hyperbolic arccosine of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor acosh(Tensor input) => input.acosh();\n\n // https://pytorch.org/docs/stable/generated/torch.acosh\n /// <summary>\n /// Computes the hyperbolic arccosine of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor acosh_(Tensor input) => input.acosh_();\n\n // https://pytorch.org/docs/stable/generated/torch.arccosh\n /// <summary>\n /// Computes the hyperbolic arccosine of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor arccosh(Tensor input) => input.arccosh();\n\n // https://pytorch.org/docs/stable/generated/torch.arccosh\n /// <summary>\n /// Computes the hyperbolic arccosine of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor arccosh_(Tensor input) => input.arccosh_();\n\n // https://pytorch.org/docs/stable/generated/torch.add\n /// <summary>\n /// Add two tensors, element-wise\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n /// <returns></returns>\n [Pure]public static Tensor add(Tensor left, Tensor right) => left.add(right);\n\n // https://pytorch.org/docs/stable/generated/torch.add\n /// <summary>\n /// Add a scalar value to each element in the target tensor.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]public static Tensor add(Tensor left, Scalar right) => left.add(right);\n\n // https://pytorch.org/docs/stable/generated/torch.add\n /// <summary>\n /// Add two tensors, element-wise, scaling the second operator by 'alpha'\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n /// <param name=\"alpha\">RHS scale factor.</param>\n [Pure]public static Tensor add(Tensor left, Tensor right, Scalar alpha) => left.add(right, alpha);\n\n // https://pytorch.org/docs/stable/generated/torch.add\n /// <summary>\n /// Add a scalar value to each element in the target tensor, scaled by 'alpha'\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n /// <param name=\"alpha\">RHS scale factor.</param>\n [Pure]public static Tensor add(Tensor left, Scalar right, Scalar alpha) => left.add(right, alpha);\n\n // https://pytorch.org/docs/stable/generated/torch.add\n /// <summary>\n /// Add two tensors, element-wise, in place\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor add_(Tensor left, Tensor right) => left.add_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.add\n /// <summary>\n /// Add a scalar value to each element in the target tensor, in place.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor add_(Tensor left, Scalar right) => left.add_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.add\n /// <summary>\n /// Add two tensors, element-wise, scaling the second operator by 'alpha', in place\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n /// <param name=\"alpha\">RHS scale factor.</param>\n public static Tensor add_(Tensor left, Tensor right, Scalar alpha) => left.add_(right, alpha);\n\n // https://pytorch.org/docs/stable/generated/torch.add\n /// <summary>\n /// Add a scalar value to each element in the target tensor, scaled by 'alpha', in place\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n /// <param name=\"alpha\">RHS scale factor.</param>\n public static Tensor add_(Tensor left, Scalar right, Scalar alpha) => left.add_(right, alpha);\n\n // https://pytorch.org/docs/stable/generated/torch.addcdiv\n /// <summary>\n /// Performs the element-wise division of tensor1 by tensor2, multiply the result by the scalar value and add it to input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"tensor1\">First tensor</param>\n /// <param name=\"tensor2\">Second tensor</param>\n /// <param name=\"value\">Scale factor</param>\n [Pure]public static Tensor addcdiv(Tensor input, Tensor tensor1, Tensor tensor2, Scalar value)\n => input.addcdiv(tensor1, tensor2, value);\n\n // https://pytorch.org/docs/stable/generated/torch.addcdiv\n /// <summary>\n /// Performs the element-wise division of tensor1 by tensor2, multiply the result by the scalar value and add it to input.\n /// In-place version of <see cref=\"addcdiv\"/>.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"tensor1\">First tensor</param>\n /// <param name=\"tensor2\">Second tensor</param>\n /// <param name=\"value\">Scale factor</param>\n public static Tensor addcdiv_(Tensor input, Tensor tensor1, Tensor tensor2, Scalar value)\n => input.addcdiv_(tensor1, tensor2, value);\n\n // https://pytorch.org/docs/stable/generated/torch.addcmul\n /// <summary>\n /// Performs the element-wise multiplication of tensor1 by tensor2, multiply the result by the scalar value and add it to input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"tensor1\">First tensor</param>\n /// <param name=\"tensor2\">Second tensor</param>\n /// <param name=\"value\">Scale factor</param>\n [Pure]public static Tensor addcmul(Tensor input, Tensor tensor1, Tensor tensor2, Scalar value)\n => input.addcmul(tensor1, tensor2, value);\n\n // https://pytorch.org/docs/stable/generated/torch.addcmul\n /// <summary>\n /// Performs the element-wise divismultiplicationion of tensor1 by tensor2, multiply the result by the scalar value and add it to input.\n /// In-place version of <see cref=\"addcmul\"/>.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"tensor1\">First tensor</param>\n /// <param name=\"tensor2\">Second tensor</param>\n /// <param name=\"value\">Scale factor</param>\n public static Tensor addcmul_(Tensor input, Tensor tensor1, Tensor tensor2, Scalar value)\n => input.addcmul_(tensor1, tensor2, value);\n\n // https://pytorch.org/docs/stable/generated/torch.angle\n /// <summary>\n /// Computes the element-wise angle (in radians) of the given input tensor.\n /// </summary>\n /// <returns></returns>\n /// <remarks>\n /// Starting in Torch 1.8, angle returns pi for negative real numbers, zero for non-negative real numbers, and propagates NaNs.\n /// Previously the function would return zero for all real numbers and not propagate floating-point NaNs.\n /// </remarks>\n [Pure]public static Tensor angle(Tensor input) => input.angle();\n\n // https://pytorch.org/docs/stable/generated/torch.asin\n /// <summary>\n /// Computes the arcsine of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor asin(Tensor input) => input.asin();\n\n // https://pytorch.org/docs/stable/generated/torch.asin\n /// <summary>\n /// Computes the arcsine of the elements of input, in place.\n /// </summary>\n /// <returns></returns>\n public static Tensor asin_(Tensor input) => input.asin_();\n\n // https://pytorch.org/docs/stable/generated/torch.arcsin\n /// <summary>\n /// Computes the arcsine of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor arcsin(Tensor input) => input.arcsin();\n\n // https://pytorch.org/docs/stable/generated/torch.arcsin\n /// <summary>\n /// Computes the arcsine of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor arcsin_(Tensor input) => input.arcsin_();\n\n // https://pytorch.org/docs/stable/generated/torch.asinh\n /// <summary>\n /// Computes the hyperbolic arcsine of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor asinh(Tensor input) => input.asinh();\n\n // https://pytorch.org/docs/stable/generated/torch.asinh\n /// <summary>\n /// Computes the hyperbolic arcsine of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor asinh_(Tensor input) => input.asinh_();\n\n // https://pytorch.org/docs/stable/generated/torch.arcsinh\n /// <summary>\n /// Computes the hyperbolic arcsine of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor arcsinh(Tensor input) => input.arcsinh();\n\n // https://pytorch.org/docs/stable/generated/torch.arcsinh\n /// <summary>\n /// Computes the hyperbolic arcsine of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor arcsinh_(Tensor input) => input.arcsinh_();\n\n // https://pytorch.org/docs/stable/generated/torch.atan\n /// <summary>\n /// Computes the arctangent of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor atan(Tensor input) => input.atan();\n\n // https://pytorch.org/docs/stable/generated/torch.atan\n /// <summary>\n /// Computes the arctangent of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor atan_(Tensor input) => input.atan_();\n\n // https://pytorch.org/docs/stable/generated/torch.arctan\n /// <summary>\n /// Computes the arctangent of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor arctan(Tensor input) => input.arctan();\n\n // https://pytorch.org/docs/stable/generated/torch.arctan\n /// <summary>\n /// Computes the arctangent of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor arctan_(Tensor input) => input.arctan_();\n\n // https://pytorch.org/docs/stable/generated/torch.atanh\n /// <summary>\n /// Computes the hyperbolic arctangent of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor atanh(Tensor input) => input.atanh();\n\n // https://pytorch.org/docs/stable/generated/torch.atanh\n /// <summary>\n /// Computes the hyperbolic arctangent of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor atanh_(Tensor input) => input.atanh_();\n\n // https://pytorch.org/docs/stable/generated/torch.arctanh\n /// <summary>\n /// Computes the hyperbolic arctangent of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor arctanh(Tensor input) => input.arctanh();\n\n /// <summary>\n /// Computes the hyperbolic arctangent of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor arctanh_(Tensor input) => input.arctanh_();\n\n // https://pytorch.org/docs/stable/generated/torch.atan2\n /// <summary>\n /// Element-wise arctangent of input / other with consideration of the quadrant.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor atan2(Tensor input, Tensor other) => input.atan2(other);\n\n /// <summary>\n /// Element-wise arctangent of input / other with consideration of the quadrant.\n /// </summary>\n /// <returns></returns>\n public static Tensor atan2_(Tensor input, Tensor other) => input.atan2_(other);\n\n // https://pytorch.org/docs/stable/generated/torch.arctan2\n /// <summary>\n /// Element-wise arctangent of input / other with consideration of the quadrant.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor arctan2(Tensor input, Tensor other) => input.arctan2(other);\n\n // https://pytorch.org/docs/stable/generated/torch.arctan2\n /// <summary>\n /// Element-wise arctangent of input / other with consideration of the quadrant.\n /// </summary>\n /// <returns></returns>\n public static Tensor arctan2_(Tensor input, Tensor other) => input.arctan2_(other);\n\n // https://pytorch.org/docs/stable/generated/torch.arctan\n /// <summary>\n /// Element-wise arctangent of input / other with consideration of the quadrant.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor arctan(Tensor input, Tensor other) => input.arctan(other);\n\n // https://pytorch.org/docs/stable/generated/torch.arctan\n /// <summary>\n /// Element-wise arctangent of input / other with consideration of the quadrant.\n /// </summary>\n /// <returns></returns>\n public static Tensor arctan_(Tensor input, Tensor other) => input.arctan_(other);\n\n // https://pytorch.org/docs/stable/generated/torch.bitwise_not\n /// <summary>\n /// Element-wise bitwise NOT\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor bitwise_not(Tensor input) => input.bitwise_not();\n\n // https://pytorch.org/docs/stable/generated/torch.bitwise_not\n /// <summary>\n /// Element-wise bitwise NOT, in place.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor bitwise_not_(Tensor input) => input.bitwise_not_();\n\n // https://pytorch.org/docs/stable/generated/torch.bitwise_and\n /// <summary>\n /// Element-wise bitwise AND\n /// </summary>\n /// <param name=\"left\">Left-hand operand.</param>\n /// <param name=\"right\">Right-hand operand.</param>\n [Pure]public static Tensor bitwise_and(Tensor left, Tensor right) => left.bitwise_and(right);\n\n // https://pytorch.org/docs/stable/generated/torch.bitwise_and\n /// <summary>\n /// Element-wise bitwise AND, in place.\n /// </summary>\n /// <param name=\"left\">Left-hand operand.</param>\n /// <param name=\"right\">Right-hand operand.</param>\n public static Tensor bitwise_and_(Tensor left, Tensor right) => left.bitwise_and_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.bitwise_or\n /// <summary>\n /// Element-wise bitwise OR\n /// </summary>\n /// <param name=\"left\">Left-hand operand.</param>\n /// <param name=\"right\">Right-hand operand.</param>\n [Pure]public static Tensor bitwise_or(Tensor left, Tensor right) => left.bitwise_or(right);\n\n // https://pytorch.org/docs/stable/generated/torch.bitwise_or\n /// <summary>\n /// Element-wise bitwiseXOR, in place.\n /// </summary>\n /// <param name=\"left\">Left-hand operand.</param>\n /// <param name=\"right\">Right-hand operand.</param>\n public static Tensor bitwise_or_(Tensor left, Tensor right) => left.bitwise_or_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.bitwise_xor\n /// <summary>\n /// Element-wise bitwise XOR\n /// </summary>\n /// <param name=\"left\">Left-hand operand.</param>\n /// <param name=\"right\">Right-hand operand.</param>\n [Pure]public static Tensor bitwise_xor(Tensor left, Tensor right) => left.bitwise_xor(right);\n\n // https://pytorch.org/docs/stable/generated/torch.bitwise_xor\n /// <summary>\n /// Element-wise bitwise XOR, in place.\n /// </summary>\n /// <param name=\"left\">Left-hand operand.</param>\n /// <param name=\"right\">Right-hand operand.</param>\n public static Tensor bitwise_xor_(Tensor left, Tensor right) => left.bitwise_xor_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.bitwise_left_shift\n /// <summary>\n /// Element-wise bitwise left shift\n /// </summary>\n /// <param name=\"left\">Left-hand operand.</param>\n /// <param name=\"right\">Right-hand operand.</param>\n public static Tensor bitwise_left_shift(Tensor left, Tensor right) => left.bitwise_left_shift(right);\n\n // https://pytorch.org/docs/stable/generated/torch.bitwise_left_shift\n /// <summary>\n /// Element-wise bitwise left shift, in place.\n /// </summary>\n /// <param name=\"left\">Left-hand operand.</param>\n /// <param name=\"right\">Right-hand operand.</param>\n public static Tensor bitwise_left_shift_(Tensor left, Tensor right) => left.bitwise_left_shift_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.bitwise_right_shift\n /// <summary>\n /// Element-wise bitwise right shift\n /// </summary>\n /// <param name=\"left\">Left-hand operand.</param>\n /// <param name=\"right\">Right-hand operand.</param>\n [Pure]public static Tensor bitwise_right_shift(Tensor left, Tensor right) => left.bitwise_right_shift(right);\n\n // https://pytorch.org/docs/stable/generated/torch.bitwise_right_shift\n /// <summary>\n /// Element-wise bitwise right shift, in place.\n /// </summary>\n /// <param name=\"left\">Left-hand operand.</param>\n /// <param name=\"right\">Right-hand operand.</param>\n public static Tensor bitwise_right_shift_(Tensor left, Tensor right) => left.bitwise_right_shift_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.ceil\n /// <summary>\n /// Returns a new tensor with the ceil of the elements of input, the smallest integer greater than or equal to each element.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor ceil(Tensor input) => input.ceil();\n\n // https://pytorch.org/docs/stable/generated/torch.ceil\n /// <summary>\n /// Replaces each element of the input with the smallest integer greater than or equal to the element.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor ceil_(Tensor input) => input.ceil_();\n\n // https://pytorch.org/docs/stable/generated/torch.clamp\n /// <summary>\n /// Clamps all elements in input into the range [ min, max ].\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"min\">The minimum value</param>\n /// <param name=\"max\">The maximum value</param>\n public static Tensor clamp(Tensor input, Scalar? min = null, Scalar? max = null) => input.clamp(min, max);\n\n // https://pytorch.org/docs/stable/generated/torch.clamp\n /// <summary>\n /// Clamps all elements in input into the range [ min, max ] in place.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"min\">The minimum value</param>\n /// <param name=\"max\">The maximum value</param>\n public static Tensor clamp_(Tensor input, Scalar? min = null, Scalar? max = null) => input.clamp_(min, max);\n\n // https://pytorch.org/docs/stable/generated/torch.clamp\n /// <summary>\n /// Clamps all elements in input into the range [ min, max ].\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"min\">The minimum value</param>\n /// <param name=\"max\">The maximum value</param>\n public static Tensor clamp(Tensor input, Tensor? min = null, Tensor? max = null) => input.clamp(min, max);\n\n // https://pytorch.org/docs/stable/generated/torch.clamp\n /// <summary>\n /// Clamps all elements in input into the range [ min, max ] in place.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"min\">The minimum value</param>\n /// <param name=\"max\">The maximum value</param>\n public static Tensor clamp_(Tensor input, Tensor? min = null, Tensor? max = null) => input.clamp_(min, max);\n\n // https://pytorch.org/docs/stable/generated/torch.clip\n public static Tensor clip(Tensor input, Scalar? min = null, Scalar? max = null) => input.clip(min, max);\n\n // https://pytorch.org/docs/stable/generated/torch.conj_physical\n /// <summary>\n /// Computes the element-wise conjugate of the given input tensor. If input has a non-complex <see cref=\"DeviceType\">dtype</see>, this function just returns input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor conj_physical(Tensor input) => input.conj_physical();\n\n // https://pytorch.org/docs/stable/generated/torch.conj_physical\n /// <summary>\n /// In-place version of conj_physical\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor conj_physical_(Tensor input) => input.conj_physical_();\n\n // https://pytorch.org/docs/stable/generated/torch.copysign\n /// <summary>\n /// Create a new floating-point tensor with the magnitude of input and the sign of other, elementwise.\n /// Supports broadcasting to a common shape, and integer and float inputs.\n /// </summary>\n /// <param name=\"input\">magnitudes</param>\n /// <param name=\"other\">contains value(s) whose signbit(s) are applied to the magnitudes in <paramref name=\"input\"/>.</param>\n /// <returns>the output tensor</returns>\n [Pure]public static Tensor copysign(Tensor input, Tensor other) => input.copysign(other);\n\n // https://pytorch.org/docs/stable/generated/torch.cos\n /// <summary>\n /// Computes the cosine of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor cos(Tensor input) => input.cos();\n\n /// <summary>\n /// Computes the cosine of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor cos_(Tensor input) => input.cos_();\n\n // https://pytorch.org/docs/stable/generated/torch.cosh\n /// <summary>\n /// Computes the hyperbolic cosine of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor cosh(Tensor input) => input.cosh();\n\n // https://pytorch.org/docs/stable/generated/torch.cosh\n /// <summary>\n /// Computes the hyperbolic cosine of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor cosh_(Tensor input) => input.cosh_();\n\n // https://pytorch.org/docs/stable/generated/torch.deg2rad\n [Pure]public static Tensor deg2rad(Tensor input) => input.deg2rad();\n\n // https://pytorch.org/docs/stable/generated/torch.div\n /// <summary>\n /// Divides each element of the input by the corresponding element of other.\n /// </summary>\n /// <param name=\"left\">Numerator</param>\n /// <param name=\"right\">Denominator</param>\n /// <param name=\"rounding_mode\">Rounding mode.</param>\n public static Tensor div(Tensor left, Tensor right, RoundingMode rounding_mode = RoundingMode.None) => left.div(right);\n\n // https://pytorch.org/docs/stable/generated/torch.div\n /// <summary>\n /// Divides each element of the input by a scalar value.\n /// </summary>\n /// <param name=\"left\">Numerator</param>\n /// <param name=\"right\">Denominator</param>\n /// <param name=\"rounding_mode\">Rounding mode.</param>\n public static Tensor div(Tensor left, Scalar right, RoundingMode rounding_mode = RoundingMode.None) => left.div(right);\n\n // https://pytorch.org/docs/stable/generated/torch.div\n /// <summary>\n /// Divides each element of the input by the corresponding element of other.\n /// </summary>\n /// <param name=\"left\">Numerator</param>\n /// <param name=\"right\">Denominator</param>\n /// <param name=\"rounding_mode\">Rounding mode.</param>\n public static Tensor div_(Tensor left, Scalar right, RoundingMode rounding_mode = RoundingMode.None) => left.div_(right, rounding_mode);\n\n // https://pytorch.org/docs/stable/generated/torch.div\n /// <summary>\n /// Divides each element of the input by the corresponding element of other.\n /// </summary>\n /// <param name=\"left\">Numerator</param>\n /// <param name=\"right\">Denominator</param>\n /// <param name=\"rounding_mode\">Rounding mode.</param>\n public static Tensor div_(Tensor left, Tensor right, RoundingMode rounding_mode = RoundingMode.None) => left.div_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.divide\n /// <summary>\n /// Divides each element of the input by the corresponding element of other.\n /// </summary>\n /// <param name=\"left\">Numerator</param>\n /// <param name=\"right\">Denominator</param>\n /// <param name=\"rounding_mode\">Rounding mode.</param>\n public static Tensor divide(Tensor left, Tensor right, RoundingMode rounding_mode = RoundingMode.None) => left.div(right);\n\n // https://pytorch.org/docs/stable/generated/torch.divide\n /// <summary>\n /// Divides each element of the input by a scalar value.\n /// </summary>\n /// <param name=\"left\">Numerator</param>\n /// <param name=\"right\">Denominator</param>\n /// <param name=\"rounding_mode\">Rounding mode.</param>\n public static Tensor divide(Tensor left, Scalar right, RoundingMode rounding_mode = RoundingMode.None) => left.div(right);\n\n // https://pytorch.org/docs/stable/generated/torch.divide\n /// <summary>\n /// Divides each element of the input by the corresponding element of other.\n /// </summary>\n /// <param name=\"left\">Numerator</param>\n /// <param name=\"right\">Denominator</param>\n /// <param name=\"rounding_mode\">Rounding mode.</param>\n public static Tensor divide_(Tensor left, Tensor right, RoundingMode rounding_mode = RoundingMode.None) => left.div_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.divide\n /// <summary>\n /// Divides each element of the input by the corresponding element of other.\n /// </summary>\n /// <param name=\"left\">Numerator</param>\n /// <param name=\"right\">Denominator</param>\n public static Tensor divide_(Tensor left, Scalar right) => left.div_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.digamma\n /// <summary>\n /// Computes the logarithmic derivative of the gamma function on input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor digamma(Tensor input) => input.digamma();\n\n // https://pytorch.org/docs/stable/generated/torch.digamma\n /// <summary>\n /// Computes the logarithmic derivative of the gamma function on input, in place.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor digamma_(Tensor input) => input.digamma_();\n\n // https://pytorch.org/docs/stable/generated/torch.erf\n /// <summary>\n /// Computes the error function of the input.\n /// </summary>\n public static Tensor erf(Tensor input) => input.erf();\n\n // https://pytorch.org/docs/stable/generated/torch.erf\n /// <summary>\n /// Computes the error function of the input in place.\n /// </summary>\n public static Tensor erf_(Tensor input) => input.erf_();\n\n // https://pytorch.org/docs/stable/generated/torch.erfc\n /// <summary>\n /// Computes the error function of the input.\n /// </summary>\n public static Tensor erfc(Tensor input) => input.erfc();\n\n // https://pytorch.org/docs/stable/generated/torch.erfc\n /// <summary>\n /// Computes the error function of the input in place.\n /// </summary>\n public static Tensor erfc_(Tensor input) => input.erfc_();\n\n // https://pytorch.org/docs/stable/generated/torch.erfinv\n /// <summary>\n /// Computes the error function of the input.\n /// </summary>\n public static Tensor erfinv(Tensor input) => input.erf();\n\n // https://pytorch.org/docs/stable/generated/torch.erfinv\n /// <summary>\n /// Computes the error function of the input in place.\n /// </summary>\n public static Tensor erfinv_(Tensor input) => input.erfinv_();\n\n // https://pytorch.org/docs/stable/generated/torch.exp\n /// <summary>\n /// Returns a new tensor with the exponential of the elements of the input tensor input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor exp(Tensor input) => input.exp();\n\n // https://pytorch.org/docs/stable/generated/torch.exp\n /// <summary>\n /// Replaces each element of the input with the exponential of the elements of the input tensor input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor exp_(Tensor input) => input.exp_();\n\n // https://pytorch.org/docs/stable/generated/torch.exp2\n /// <summary>\n /// Computes the base 2 exponential function of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor exp2(Tensor input) => input.exp2();\n\n // https://pytorch.org/docs/stable/generated/torch.expm1\n /// <summary>\n /// Returns a new tensor with the exponential of the elements minus 1 of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor expm1(Tensor input) => input.expm1();\n\n // https://pytorch.org/docs/stable/generated/torch.expm1\n /// <summary>\n /// Replaces each element with the exponential of the element minus 1 of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor expm1_(Tensor input) => input.expm1_();\n\n // https://pytorch.org/docs/stable/generated/torch.fake_quantize_per_channel_affine\n /// <summary>\n /// Returns a new tensor with the data in <paramref name=\"input\"/> fake quantized per channel using\n /// <paramref name=\"scale\"/>, <paramref name=\"zero_point\"/>, <paramref name=\"quant_min\"/> and <paramref name=\"quant_max\"/>,\n /// across the channel specified by <paramref name=\"axis\"/>.\n /// </summary>\n /// <param name=\"input\">the input value(s) (float32)</param>\n /// <param name=\"scale\">quantization scale, per channel (float32)</param>\n /// <param name=\"zero_point\">quantization zero_point, per channel (torch.int32, torch.half, or torch.float32)</param>\n /// <param name=\"axis\">channel axis</param>\n /// <param name=\"quant_min\">lower bound of the quantized domain</param>\n /// <param name=\"quant_max\">upper bound of the quantized domain</param>\n /// <returns>A newly fake_quantized per channel torch.float32 tensor</returns>\n [Pure, Obsolete(\"not implemented\", true)]\n public static Tensor fake_quantize_per_channel_affine(Tensor input, Tensor scale, Tensor zero_point, int axis, long quant_min, long quant_max)\n => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.fake_quantize_per_tensor_affine\n /// <summary>\n /// Returns a new tensor with the data in <paramref name=\"input\"/> fake quantized per channel using\n /// <paramref name=\"scale\"/>, <paramref name=\"zero_point\"/>, <paramref name=\"quant_min\"/> and <paramref name=\"quant_max\"/>,\n /// across the channel specified by axis.\n /// </summary>\n /// <param name=\"input\">the input value(s) (float32)</param>\n /// <param name=\"scale\">quantization scale, per channel (float32)</param>\n /// <param name=\"zero_point\">quantization zero_point, per channel (torch.int32, torch.half, or torch.float32)</param>\n /// <param name=\"quant_min\">lower bound of the quantized domain</param>\n /// <param name=\"quant_max\">upper bound of the quantized domain</param>\n /// <returns>A newly fake_quantized per channel torch.float32 tensor</returns>\n [Pure, Obsolete(\"not implemented\", true)]\n public static Tensor fake_quantize_per_tensor_affine(Tensor input, Tensor scale, Tensor zero_point, long quant_min, long quant_max)\n => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.fix\n /// <summary>\n /// Returns a new tensor with the truncated integer values of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor fix(Tensor input) => input.fix();\n\n // https://pytorch.org/docs/stable/generated/torch.fix\n /// <summary>\n /// Replaces each element with the truncated integer values of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor fix_(Tensor input) => input.fix_();\n\n // https://pytorch.org/docs/stable/generated/torch.float_power\n /// <summary>\n /// Raises input to the power of exponent, elementwise, in double precision.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"target\">The exponent.</param>\n /// <remarks> If neither input is complex returns a torch.float64 tensor, and if one or more inputs is complex returns a torch.complex128 tensor.</remarks>\n [Pure]public static Tensor float_power(Tensor input, Tensor target) => input.float_power(target);\n\n // https://pytorch.org/docs/stable/generated/torch.floor\n /// <summary>\n /// Returns a new tensor with the floor of the elements of input, the largest integer less than or equal to each element.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor floor(Tensor input) => input.floor();\n\n // https://pytorch.org/docs/stable/generated/torch.floor\n /// <summary>\n /// Replaces each element with the floor of the input, the largest integer less than or equal to each element.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor floor_(Tensor input) => input.floor_();\n\n // https://pytorch.org/docs/stable/generated/torch.floor_divide\n /// <summary>\n /// Computes input divided by other, elementwise, and floors the result.\n /// Supports broadcasting to a common shape, type promotion, and integer and float inputs.\n /// </summary>\n /// <param name=\"input\">the dividend</param>\n /// <param name=\"other\">the divisor</param>\n /// <returns>the output tensor</returns>\n [Pure]\n public static Tensor floor_divide(Tensor input, Tensor other) => input.floor_divide(other);\n\n // https://pytorch.org/docs/stable/generated/torch.floor_divide\n /// <summary>\n /// Computes input divided by other, elementwise, and floors the result.\n /// Supports broadcasting to a common shape, type promotion, and integer and float inputs.\n /// </summary>\n /// <param name=\"input\">the dividend</param>\n /// <param name=\"other\">the divisor</param>\n /// <returns>the output tensor</returns>\n public static Tensor floor_divide_(Tensor input, Tensor other) => input.floor_divide_(other);\n\n // https://pytorch.org/docs/stable/generated/torch.fmod\n /// <summary>\n /// Computes the element-wise remainder of division.\n /// </summary>\n [Pure]public static Tensor fmod(Tensor left, Tensor right) => left.fmod(right);\n\n // https://pytorch.org/docs/stable/generated/torch.fmod\n /// <summary>\n /// Computes the element-wise remainder of division, in place.\n /// </summary>\n /// <param name=\"left\">Numerator</param>\n /// <param name=\"right\">Denominator</param>\n public static Tensor fmod_(Tensor left, Tensor right) => left.fmod_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.fmod\n /// <summary>\n /// Computes the element-wise remainder of division.\n /// </summary>\n /// <param name=\"left\">Numerator</param>\n /// <param name=\"right\">Denominator</param>\n [Pure]public static Tensor fmod(Tensor left, Scalar right) => left.fmod(right);\n\n // https://pytorch.org/docs/stable/generated/torch.fmod\n /// <summary>\n /// Computes the element-wise remainder of division, in place.\n /// </summary>\n /// <param name=\"left\">Numerator</param>\n /// <param name=\"right\">Denominator</param>\n public static Tensor fmod_(Tensor left, Scalar right) => left.fmod_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.frac\n /// <summary>\n /// Computes the fractional portion of each element in input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor frac(Tensor input) => input.frac();\n\n // https://pytorch.org/docs/stable/generated/torch.frac\n /// <summary>\n /// Computes the fractional portion of each element in input, in-place.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor frac_(Tensor input) => input.frac_();\n\n // https://pytorch.org/docs/stable/generated/torch.frexp\n /// <summary>\n /// Decomposes input into mantissa and exponent tensors\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static (Tensor Mantissa, Tensor Exponent) frexp(Tensor input) => input.frexp();\n\n // https://pytorch.org/docs/stable/generated/torch.gradient\n [Pure, Obsolete(\"not implemented\", true)]\n public static ICollection<Tensor> gradient(Tensor input, int spacing = 1, long? dim = null, int edge_order = 1)\n => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.gradient\n [Pure, Obsolete(\"not implemented\", true)]\n public static ICollection<Tensor> gradient(Tensor input, int spacing = 1, long[]? dims = null, int edge_order = 1)\n => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.imag\n [Pure]public static Tensor imag(Tensor input) => input.imag;\n\n // https://pytorch.org/docs/stable/generated/torch.ldexp\n /// <summary>\n /// Multiplies input by pow(2,other).\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"other\">A tensor of exponents, typically integers</param>\n /// <remarks>Typically this function is used to construct floating point numbers by multiplying mantissas in input with integral powers of two created from the exponents in other.</remarks>\n [Pure]public static Tensor ldexp(Tensor input, Tensor other) => input.ldexp(other);\n\n // https://pytorch.org/docs/stable/generated/torch.ldexp\n /// <summary>\n /// Multiplies input by pow(2,other) in place.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"other\">A tensor of exponents, typically integers</param>\n /// <remarks>Typically this function is used to construct floating point numbers by multiplying mantissas in input with integral powers of two created from the exponents in other.</remarks>\n public static Tensor ldexp_(Tensor input, Tensor other) => input.ldexp_(other);\n\n // https://pytorch.org/docs/stable/generated/torch.lerp\n /// <summary>\n /// Does a linear interpolation of two tensors start (given by input)\n /// and end based on a scalar or tensor weight and returns the resulting out tensor.\n /// </summary>\n /// <remarks>\n /// The shapes of start and end must be broadcastable.\n /// If weight is a tensor, then the shapes of weight, start, and end must be broadcastable.\n /// </remarks>\n /// <param name=\"input\">the tensor with the starting points</param>\n /// <param name=\"end\">the tensor with the ending points</param>\n /// <param name=\"weight\">the weight for the interpolation formula</param>\n /// <returns>the output tensor</returns>\n [Pure]public static Tensor lerp(Tensor input, Tensor end, Tensor weight) => input.lerp(end, weight);\n\n // https://pytorch.org/docs/stable/generated/torch.lgamma\n /// <summary>\n /// Computes the logarithm of the gamma function on input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor lgamma(Tensor input) => input.lgamma();\n\n // https://pytorch.org/docs/stable/generated/torch.lgamma\n /// <summary>\n /// Computes the logarithm of the gamma function on input, in place.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor lgamma_(Tensor input) => input.lgamma();\n\n // https://pytorch.org/docs/stable/generated/torch.log\n /// <summary>\n /// Returns a new tensor with the natural logarithm of the input elements.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor log(Tensor input) => input.log();\n\n // https://pytorch.org/docs/stable/generated/torch.log\n /// <summary>\n /// Replaces each elements with the natural logarithm of the input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor log_(Tensor input) => input.log_();\n\n // https://pytorch.org/docs/stable/generated/torch.log10\n /// <summary>\n /// Returns a new tensor with the logarithm to the base 10 of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor log10(Tensor input) => input.log10();\n\n // https://pytorch.org/docs/stable/generated/torch.log10\n /// <summary>\n /// Replaces each elements with the logarithm to the base 10 of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor log10_(Tensor input) => input.log10_();\n\n // https://pytorch.org/docs/stable/generated/torch.log1p\n /// <summary>\n /// Returns a new tensor with the natural logarithm of (1 + input).\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor log1p(Tensor input) => input.log1p();\n\n // https://pytorch.org/docs/stable/generated/torch.log1p\n /// <summary>\n /// Replaces each elements with the natural logarithm of (1 + input), in place.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor log1p_(Tensor input) => input.log1p_();\n\n // https://pytorch.org/docs/stable/generated/torch.log2\n /// <summary>\n /// Returns a new tensor with the logarithm to the base 10 of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor log2(Tensor input) => input.log2();\n\n // https://pytorch.org/docs/stable/generated/torch.log2\n /// <summary>\n /// Replaces each elements with the logarithm to the base 10 of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor log2_(Tensor input) => input.log2_();\n\n // https://pytorch.org/docs/stable/generated/torch.logaddexp\n /// <summary>\n /// Logarithm of the sum of exponentiations of the inputs.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]public static Tensor logaddexp(Tensor left, Tensor right) => left.logaddexp(right);\n\n // https://pytorch.org/docs/stable/generated/torch.logaddexp2\n /// <summary>\n /// Logarithm of the sum of exponentiations of the inputs in base-2.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]public static Tensor logaddexp2(Tensor left, Tensor right) => left.logaddexp2(right);\n\n // https://pytorch.org/docs/stable/generated/torch.logical_and\n /// <summary>\n /// Element-wise logical AND\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]public static Tensor logical_and(Tensor left, Tensor right) => left.logical_and(right);\n\n // https://pytorch.org/docs/stable/generated/torch.logical_and\n /// <summary>\n /// Element-wise logical AND, in place.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor logical_and_(Tensor left, Tensor right) => left.logical_and_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.logical_not\n /// <summary>\n /// Element-wise logical NOT\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor logical_not(Tensor input) => input.logical_not();\n\n // https://pytorch.org/docs/stable/generated/torch.logical_or\n /// <summary>\n /// Element-wise logical OR\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]public static Tensor logical_or(Tensor left, Tensor right) => left.logical_or(right);\n\n // https://pytorch.org/docs/stable/generated/torch.logical_or\n /// <summary>\n /// Element-wise logicalXOR, in place.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor logical_or_(Tensor left, Tensor right) => left.logical_or_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.logical_xor\n /// <summary>\n /// Element-wise logical XOR\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]public static Tensor logical_xor(Tensor left, Tensor right) => left.logical_xor(right);\n\n // https://pytorch.org/docs/stable/generated/torch.logical_xor\n /// <summary>\n /// Element-wise logical XOR\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor logical_xor_(Tensor left, Tensor right) => left.logical_xor_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.logit\n /// <summary>\n /// Returns a new tensor with the logit of the elements of input.\n /// input is clamped to [eps, 1 - eps] when eps is not null\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"eps\">The epsilon for input clamp bound.</param>\n [Pure]public static Tensor logit(Tensor input, double? eps = null) => input.logit(eps);\n\n // https://pytorch.org/docs/stable/generated/torch.hypot\n /// <summary>\n /// Element-wise: given the legs of a right triangle, return its hypotenuse.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]public static Tensor hypot(Tensor left, Tensor right) => left.hypot(right);\n\n // https://pytorch.org/docs/stable/generated/torch.i0\n /// <summary>\n /// Alias for <see cref=\"torch.special.i0\"/>.\n /// </summary>\n /// <param name=\"input\"></param>\n /// <returns></returns>\n [Pure]public static Tensor i0(Tensor input) => special.i0(input);\n\n // https://pytorch.org/docs/stable/generated/torch.igamma\n /// <summary>\n /// Alias for <see cref=\"torch.special.gammainc\"/>.\n /// </summary>\n /// <param name=\"input\"></param>\n /// <param name=\"other\"></param>\n /// <returns></returns>\n [Pure]public static Tensor igamma(Tensor input, Tensor other) => special.gammainc(input, other);\n\n // https://pytorch.org/docs/stable/generated/torch.igammac\n /// <summary>\n /// Alias for <see cref=\"torch.special.gammaincc\"/>\".\n /// </summary>\n /// <param name=\"input\"></param>\n /// <param name=\"other\"></param>\n /// <returns></returns>\n [Pure]public static Tensor igammac(Tensor input, Tensor other) => special.gammaincc(input, other);\n\n // https://pytorch.org/docs/stable/generated/torch.mul\n /// <summary>\n /// Multiplies each element of the input by the corresponding element of other.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor mul(Tensor left, Tensor right) => left.mul(right);\n\n // https://pytorch.org/docs/stable/generated/torch.mul\n /// <summary>\n /// Divides each element of the input by a scalar value.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor mul(Tensor left, Scalar right) => left.mul(right);\n\n // https://pytorch.org/docs/stable/generated/torch.mul\n /// <summary>\n /// Divides each element of the input by the corresponding element of other.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor mul_(Tensor left, Tensor right) => left.mul_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.mul\n /// <summary>\n /// Divides each element of the input by the corresponding element of other.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor mul_(Tensor left, Scalar right) => left.mul_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.multiply\n /// <summary>\n /// Multiplies each element of the input by the corresponding element of other.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor multiply(Tensor left, Tensor right) => left.mul(right);\n\n // https://pytorch.org/docs/stable/generated/torch.multiply\n /// <summary>\n /// Divides each element of the input by a scalar value.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor multiply(Tensor left, Scalar right) => left.mul(right);\n\n // https://pytorch.org/docs/stable/generated/torch.multiply\n /// <summary>\n /// Divides each element of the input by the corresponding element of other.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor multiply_(Tensor left, Tensor right) => left.mul_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.multiply\n /// <summary>\n /// Divides each element of the input by the corresponding element of other.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor multiply_(Tensor left, Scalar right) => left.mul_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.mvlgamma\n /// <summary>\n /// Computes the multivariate log-gamma function) with dimension pp element-wise\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"p\">The number of dimensions</param>\n /// <returns></returns>\n public static Tensor mvlgamma(Tensor input, long p) => input.mvlgamma(p);\n\n // https://pytorch.org/docs/stable/generated/torch.mvlgamma\n /// <summary>\n /// Computes the multivariate log-gamma function) with dimension pp element-wise, in place.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"p\">The number of dimensions</param>\n /// <returns></returns>\n public static Tensor mvlgamma_(Tensor input, long p) => input.mvlgamma_(p);\n\n // https://pytorch.org/docs/stable/generated/torch.nan_to_num\n /// <summary>\n /// Replaces NaN, positive infinity, and negative infinity values in input with the values specified by nan,\n /// posinf, and neginf, respectively. By default, NaNs are replaced with zero,\n /// positive infinity is replaced with the greatest finite value representable by input’s dtype,\n /// and negative infinity is replaced with the least finite value representable by input’s dtype.\n /// </summary>\n /// <param name=\"input\">the input tensor</param>\n /// <param name=\"nan\">the value to replace NaNs with. Default is zero.</param>\n /// <param name=\"posinf\">\n /// if a Number, the value to replace positive infinity values with.\n /// If None, positive infinity values are replaced with the greatest finite value representable by input’s dtype.\n /// Default is null.\n /// </param>\n /// <param name=\"neginf\">\n /// if a Number, the value to replace negative infinity values with.\n /// If None, negative infinity values are replaced with the lowest finite value representable by input’s dtype.\n /// Default is null.\n /// </param>\n /// <returns></returns>\n public static Tensor nan_to_num(Tensor input, double nan = 0d, double? posinf = null, double? neginf = null)\n => input.nan_to_num(nan, posinf, neginf);\n\n // https://pytorch.org/docs/stable/generated/torch.neg\n /// <summary>\n /// Negation\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor neg(Tensor input) => input.neg();\n\n // https://pytorch.org/docs/stable/generated/torch.neg\n /// <summary>\n /// In-place negation\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor neg_(Tensor input) => input.neg_();\n\n // https://pytorch.org/docs/stable/generated/torch.negative\n /// <summary>\n /// Negation\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor negative(Tensor input) => input.neg();\n\n // https://pytorch.org/docs/stable/generated/torch.negative\n /// <summary>\n /// In-place negation\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor negative_(Tensor input) => input.neg_();\n\n\n // https://pytorch.org/docs/stable/generated/torch.nextafter\n public static Tensor nextafter(Tensor input, Tensor other) => input.nextafter(other);\n\n // https://pytorch.org/docs/stable/generated/torch.polygamma\n /// <summary>\n /// Computes the Nth derivative of the digamma function on input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"p\">The number of dimensions</param>\n /// <returns></returns>\n public static Tensor polygamma(Tensor input, long p) => input.polygamma(p);\n\n // https://pytorch.org/docs/stable/generated/torch.polygamma\n /// <summary>\n /// Computes the Nth derivative of the digamma function on input, in-place.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"p\">The number of dimensions</param>\n public static Tensor polygamma_(Tensor input, long p) => input.polygamma_(p);\n\n // https://pytorch.org/docs/stable/generated/torch.positive\n public static Tensor positive(Tensor input) => input.positive();\n\n // https://pytorch.org/docs/stable/generated/torch.pow\n /// <summary>\n /// Takes the power of each element in input with exponent and returns a tensor with the result.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"exponent\">The right-hand operand.</param>\n [Pure]public static Tensor pow(Tensor left, Tensor exponent) => left.pow(exponent);\n\n // https://pytorch.org/docs/stable/generated/torch.pow\n /// <summary>\n /// Takes the power of each element in input with exponent and returns a tensor with the result.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"exponent\">The right-hand operand.</param>\n [Pure]public static Tensor pow(Tensor left, Scalar exponent) => left.pow(exponent);\n\n // https://pytorch.org/docs/stable/generated/torch.pow\n /// <summary>\n /// Replaces each element in input with the power of the element and the exponent.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"exponent\">The right-hand operand.</param>\n public static Tensor pow_(Tensor left, Tensor exponent) => left.pow_(exponent);\n\n // https://pytorch.org/docs/stable/generated/torch.pow\n /// <summary>\n /// Replaces each element in input with the power of the element and the exponent.\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"exponent\">The right-hand operand.</param>\n public static Tensor pow_(Tensor left, Scalar exponent) => left.pow_(exponent);\n\n // https://pytorch.org/docs/stable/generated/torch.quantized_batch_norm\n /// <summary>\n /// Applies batch normalization on a 4D (NCHW) quantized tensor.\n /// </summary>\n /// <param name=\"input\">quantized tensor</param>\n /// <param name=\"weight\">float tensor that corresponds to the gamma, size C</param>\n /// <param name=\"bias\">float tensor that corresponds to the beta, size C</param>\n /// <param name=\"mean\">float mean value in batch normalization, size C</param>\n /// <param name=\"var\">float tensor for variance, size C</param>\n /// <param name=\"eps\">a value added to the denominator for numerical stability.</param>\n /// <param name=\"output_scale\">output quantized tensor scale</param>\n /// <param name=\"output_zero_point\">output quantized tensor zero_point</param>\n /// <returns>A quantized tensor with batch normalization applied.</returns>\n [Pure, Obsolete(\"not implemented\", true)]\n public static Tensor quantized_batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor mean, Tensor @var, double eps, double output_scale, long output_zero_point)\n => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.quantized_max_pool1d\n /// <summary>\n /// Applies a 1D max pooling over an input quantized tensor composed of several input planes.\n /// </summary>\n /// <param name=\"input\">quantized tensor</param>\n /// <param name=\"kernel_size\">the size of the sliding window</param>\n /// <param name=\"stride\">the stride of the sliding window</param>\n /// <param name=\"padding\">padding to be added on both sides, must be &gt;= 0 and &lt;= kernel_size / 2</param>\n /// <param name=\"dilation\">the stride between elements within a sliding window, must be &gt; 0. Default 1</param>\n /// <param name=\"ceil_mode\">If <value>true</value>, will use ceil instead of floor to compute the output shape. Defaults to <value>false</value>.</param>\n /// <returns>A quantized tensor with max_pool1d applied.</returns>\n [Pure, Obsolete(\"not implemented\", true)]\n public static Tensor quantized_max_pool1d(Tensor input, long[] kernel_size, long[]? stride, long[]? padding, long dilation=1, bool ceil_mode=false)\n => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.quantized_max_pool2d\n /// <summary>\n /// Applies a 2D max pooling over an input quantized tensor composed of several input planes.\n /// </summary>\n /// <param name=\"input\">quantized tensor</param>\n /// <param name=\"kernel_size\">the size of the sliding window</param>\n /// <param name=\"stride\">the stride of the sliding window</param>\n /// <param name=\"padding\">padding to be added on both sides, must be &gt;= 0 and &lt;= kernel_size / 2</param>\n /// <param name=\"dilation\">The stride between elements within a sliding window, must be > 0. Default 1</param>\n /// <param name=\"ceil_mode\">If <value>true</value>, will use ceil instead of floor to compute the output shape. Defaults to <value>false</value>.</param>\n /// <returns>A quantized tensor with max_pool2d applied.</returns>\n [Pure, Obsolete(\"not implemented\", true)]\n public static Tensor quantized_max_pool2d(Tensor input, long[] kernel_size, long[]? stride, long[]? padding, long dilation=1, bool ceil_mode=false)\n => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.rad2deg\n /// <summary>\n /// Returns a new tensor with each of the elements of input converted from angles in radians to degrees.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <returns>tensor with angles in radians</returns>\n public static Tensor rad2deg(Tensor input) => input.rad2deg();\n\n // https://pytorch.org/docs/stable/generated/torch.real\n /// <summary>\n /// Returns a new tensor containing real values of the self tensor.\n /// The returned tensor and self share the same underlying storage.\n /// </summary>\n /// <param name=\"input\">the input tensor.</param>\n /// <returns>tensor containing real values</returns>\n [Pure]public static Tensor real(Tensor input) => input.real;\n\n // https://pytorch.org/docs/stable/generated/torch.reciprocal\n /// <summary>\n /// Returns a new tensor with the reciprocal of the elements of input\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor reciprocal(Tensor input) => input.reciprocal();\n\n // https://pytorch.org/docs/stable/generated/torch.reciprocal\n /// <summary>\n /// Replaces each element with the reciprocal of the input\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor reciprocal_(Tensor input) => input.reciprocal_();\n\n // https://pytorch.org/docs/stable/generated/torch.remainder\n /// <summary>\n /// Computes the element-wise remainder of division.\n /// </summary>\n /// <param name=\"left\">Numerator</param>\n /// <param name=\"right\">Denominator</param>\n [Pure]public static Tensor remainder(Tensor left, Tensor right) => left.remainder(right);\n\n // https://pytorch.org/docs/stable/generated/torch.remainder\n /// <summary>\n /// Computes the element-wise remainder of division.\n /// </summary>\n /// <param name=\"left\">Numerator</param>\n /// <param name=\"right\">Denominator</param>\n [Pure]public static Tensor remainder(Tensor left, Scalar right) => left.remainder(right);\n\n // https://pytorch.org/docs/stable/generated/torch.remainder\n /// <summary>\n /// Computes the element-wise remainder of division, in place\n /// </summary>\n /// <param name=\"left\">Numerator</param>\n /// <param name=\"right\">Denominator</param>\n public static Tensor remainder_(Tensor left, Tensor right) => left.remainder_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.remainder\n /// <summary>\n /// Computes the element-wise remainder of division, in place\n /// </summary>\n /// <param name=\"left\">Numerator</param>\n /// <param name=\"right\">Denominator</param>\n public static Tensor remainder_(Tensor left, Scalar right) => left.remainder_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.round\n /// <summary>\n /// Returns a new tensor with each of the elements of input rounded to the closest value with the given number of decimals.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"decimals\">Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point.</param>\n [Pure]public static Tensor round(Tensor input, long decimals = 0L) => input.round(decimals);\n\n // https://pytorch.org/docs/stable/generated/torch.round\n /// <summary>\n /// Replaces each of the elements of input with the element rounded to the closest value with the given number of decimals.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"decimals\">Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point.</param>\n public static Tensor round_(Tensor input, long decimals = 0L) => input.round_(decimals);\n\n // https://pytorch.org/docs/stable/generated/torch.rsqrt\n /// <summary>\n /// Returns a new tensor with the reciprocal of the square-root of each of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor rsqrt(Tensor input) => input.rsqrt();\n\n // https://pytorch.org/docs/stable/generated/torch.rsqrt\n /// <summary>\n /// Replaces each of the elements of input with the reciprocal of the square-root of each of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor rsqrt_(Tensor input) => input.rsqrt_();\n\n // https://pytorch.org/docs/stable/generated/torch.sigmoid\n /// <summary>\n /// Computes the logistic sigmoid function of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor sigmoid(Tensor input) => input.sigmoid();\n\n // https://pytorch.org/docs/stable/generated/torch.sigmoid\n /// <summary>\n /// Computes the logistic sigmoid function of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor sigmoid_(Tensor input) => input.sigmoid_();\n\n // https://pytorch.org/docs/stable/generated/torch.sign\n /// <summary>\n /// Returns a new tensor with the signs (-1, 0, 1) of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor sign(Tensor input) => input.sign();\n\n // https://pytorch.org/docs/stable/generated/torch.sign\n /// <summary>\n /// Returns a new tensor with the signs (-1, 0, 1) of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure] public static Tensor sign_(Tensor input) => input.sign_();\n\n // https://pytorch.org/docs/stable/generated/torch.sgn\n /// <summary>\n /// This function is an extension of torch.sign() to complex tensors.\n /// It computes a new tensor whose elements have the same angles as the corresponding\n /// elements of input and absolute values (i.e. magnitudes) of one for complex tensors\n /// and is equivalent to torch.sign() for non-complex tensors.\n /// </summary>\n /// <param name=\"input\">the input tensor.</param>\n /// <returns>the output tensor.</returns>\n [Pure]\n public static Tensor sgn(Tensor input) => input.sgn();\n\n // https://pytorch.org/docs/stable/generated/torch.sgn\n /// <summary>\n /// This function is an extension of torch.sign() to complex tensors.\n /// It computes a new tensor whose elements have the same angles as the corresponding\n /// elements of input and absolute values (i.e. magnitudes) of one for complex tensors\n /// and is equivalent to torch.sign() for non-complex tensors.\n /// </summary>\n /// <param name=\"input\">the input tensor.</param>\n /// <returns>the output tensor.</returns>\n [Pure]\n public static Tensor sgn_(Tensor input) => input.sgn_();\n\n // https://pytorch.org/docs/stable/generated/torch.signbit\n /// <summary>\n /// Tests whether each element of input has its sign bit set (is less than zero) or not.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <returns>A boolean tensor of the same shape as the input.</returns>\n [Pure]public static Tensor signbit(Tensor input) => input.signbit();\n\n // https://pytorch.org/docs/stable/generated/torch.sin\n /// <summary>\n /// Computes the sine of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor sin(Tensor input) => input.sin();\n\n // https://pytorch.org/docs/stable/generated/torch.sin\n /// <summary>\n /// Computes the sine of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor sin_(Tensor input) => input.sin_();\n\n // https://pytorch.org/docs/stable/generated/torch.sinc\n /// <summary>\n /// Computes the normalized sinc of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor sinc(Tensor input) => input.sinc();\n\n // https://pytorch.org/docs/stable/generated/torch.sinc\n /// <summary>\n /// Computes the normalized sinc of input, in place.\n /// </summary>\n /// <returns></returns>\n public static Tensor sinc_(Tensor input) => input.sinc_();\n\n // https://pytorch.org/docs/stable/generated/torch.sinh\n /// <summary>\n /// Computes the hyperbolic sine of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor sinh(Tensor input) => input.sinh();\n\n // https://pytorch.org/docs/stable/generated/torch.sinh\n /// <summary>\n /// Computes the hyperbolic sine of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor sinh_(Tensor input) => input.sinh_();\n\n // https://pytorch.org/docs/stable/generated/torch.sqrt\n /// <summary>\n /// Computes the element-wise square root\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor sqrt(Tensor input) => input.sqrt();\n\n // https://pytorch.org/docs/stable/generated/torch.sqrt\n /// <summary>\n /// Computes the element-wise square root, in place\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor sqrt_(Tensor input) => input.sqrt_();\n\n // https://pytorch.org/docs/stable/generated/torch.square\n /// <summary>\n /// Computes the element-wise square\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor square(Tensor input) => input.square();\n\n // https://pytorch.org/docs/stable/generated/torch.sub\n /// <summary>\n /// Element-wise subtraction\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]public static Tensor sub(Tensor left, Tensor right) => left.sub(right);\n\n // https://pytorch.org/docs/stable/generated/torch.sub\n /// <summary>\n /// Element-wise subtraction\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]public static Tensor sub(Tensor left, Scalar right) => left.sub(right);\n\n // https://pytorch.org/docs/stable/generated/torch.sub\n /// <summary>\n /// Element-wise subtraction\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor sub_(Tensor left, Tensor right) => left.sub_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.sub\n /// <summary>\n /// Element-wise subtraction\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor sub_(Tensor left, Scalar right) => left.sub_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.subtract\n /// <summary>\n /// Element-wise subtraction\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]public static Tensor subtract(Tensor left, Tensor right) => left.subtract(right);\n\n // https://pytorch.org/docs/stable/generated/torch.subtract\n /// <summary>\n /// Element-wise subtraction\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]public static Tensor subtract(Tensor left, Scalar right) => left.subtract(right);\n\n // https://pytorch.org/docs/stable/generated/torch.subtract\n /// <summary>\n /// Element-wise subtraction\n /// </summary>\n /// <returns></returns>\n public static Tensor subtract_(Tensor left, Tensor right) => left.subtract_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.subtract\n /// <summary>\n /// Element-wise subtraction\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n public static Tensor subtract_(Tensor left, Scalar right) => left.subtract_(right);\n\n // https://pytorch.org/docs/stable/generated/torch.tan\n /// <summary>\n /// Computes the tangent of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]public static Tensor tan(Tensor input) => input.tan();\n\n // https://pytorch.org/docs/stable/generated/torch.tan\n /// <summary>\n /// Computes the tangent of the elements of input. In-place version.\n /// </summary>\n /// <returns></returns>\n public static Tensor tan_(Tensor input) => input.tan_();\n\n // https://pytorch.org/docs/stable/generated/torch.tanh\n /// <summary>\n /// Computes the hyperbolic tangent of the elements of input.\n /// </summary>\n /// <returns></returns>\n [Pure]\n public static Tensor tanh(Tensor input) => input.tanh();\n\n // https://pytorch.org/docs/stable/generated/torch.tanh\n /// <summary>\n /// Computes the hyperbolic tangent of the elements of input.\n /// </summary>\n /// <returns></returns>\n public static Tensor tanh_(Tensor input) => input.tanh_();\n\n // https://pytorch.org/docs/stable/generated/torch.true_divide\n /// <summary>\n /// Alias for torch.div() with rounding_mode=None.\n /// </summary>\n [Pure]\n public static Tensor true_divide(Tensor dividend, Tensor divisor) => dividend.true_divide(divisor);\n\n // https://pytorch.org/docs/stable/generated/torch.true_divide\n /// <summary>\n /// Alias for torch.div_() with rounding_mode=None.\n /// </summary>\n public static Tensor true_divide_(Tensor dividend, Tensor divisor) => dividend.true_divide_(divisor);\n\n // https://pytorch.org/docs/stable/generated/torch.trunc\n /// <summary>\n /// Returns a new tensor with the truncated integer values of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]\n public static Tensor trunc(Tensor input) => input.trunc();\n\n // https://pytorch.org/docs/stable/generated/torch.trunc\n /// <summary>\n /// Replaces each element with the truncated integer values of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor trunc_(Tensor input) => input.trunc_();\n\n // https://pytorch.org/docs/stable/generated/torch.xlogy\n /// <summary>\n /// Computes x * log(y)\n /// </summary>\n /// <param name=\"x\">The 'x' operand.</param>\n /// <param name=\"y\">The 'y' operand.</param>\n [Pure]\n public static Tensor xlogy(Tensor x, Tensor y) => x.xlogy(y);\n\n // https://pytorch.org/docs/stable/generated/torch.xlogy\n /// <summary>\n /// Computes x * log(y) in place\n /// </summary>\n /// <param name=\"x\">The 'x' operand.</param>\n /// <param name=\"y\">The 'y' operand.</param>\n public static Tensor xlogy_(Tensor x, Tensor y) => x.xlogy_(y);\n\n // https://pytorch.org/docs/stable/generated/torch.xlogy\n /// <summary>\n /// Computes x * log(y)\n /// </summary>\n /// <param name=\"x\">The 'x' operand.</param>\n /// <param name=\"y\">The 'y' operand.</param>\n [Pure]\n public static Tensor xlogy(Tensor x, Scalar y) => x.xlogy(y);\n\n // https://pytorch.org/docs/stable/generated/torch.xlogy\n /// <summary>\n /// Computes x * log(y) in place\n /// </summary>\n /// <param name=\"x\">The 'x' operand.</param>\n /// <param name=\"y\">The 'y' operand.</param>\n public static Tensor xlogy_(Tensor x, Scalar y) => x.xlogy_(y);\n }\n}" }, { "alpha_fraction": 0.7084447741508484, "alphanum_fraction": 0.7176156044006348, "avg_line_length": 57.17777633666992, "blob_id": "31a107ecd71f9c25089128952e275abe1991c603", "content_id": "8884e02790c5ebc92391c4c96db1a2fae3d199ab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2617, "license_type": "permissive", "max_line_length": 206, "num_lines": 45, "path": "/src/TorchVision/LibTorchSharp.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp\n{\n internal static class NativeMethods\n {\n /* Tensor THSVision_AdjustHue(const Tensor i, const double hue_factor) */\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSVision_AdjustHue(IntPtr img, double hue_factor);\n\n // EXPORT_API(Tensor) THSVision_ApplyGridTransform(Tensor img, Tensor grid, const int8_t m, const float* fill, const int64_t fill_length);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSVision_ApplyGridTransform(IntPtr img, IntPtr grid, sbyte mode, IntPtr fill,\n long fill_length);\n\n /* Tensor THSVision_GenerateAffineGrid(Tensor theta, const int64_t w, const int64_t h, const int64_t ow, const int64_t oh); */\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSVision_GenerateAffineGrid(IntPtr theta, long w, long h, long ow, long oh);\n\n /* Tensor THSVision_ComputeOutputSize(const float* matrix, const int64_t matrix_length, const int64_t w, const int64_t h); */\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSVision_ComputeOutputSize(IntPtr matrix, long matrix_length, long w, long h,\n out int first, out int second);\n\n /* Tensor THSVision_PerspectiveGrid(const float* coeffs, const int64_t coeffs_length, const int64_t ow, const int64_t oh, const int8_t scalar_type, const int device_type, const int device_index); */\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSVision_PerspectiveGrid(IntPtr coeffs, long coeffs_length, long ow, long oh,\n sbyte dtype, int device_type, int device_index);\n\n /* Tensor THSVision_ScaleChannel(Tensor ic); */\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSVision_ScaleChannel(IntPtr img);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSVision_BRGA_RGB(IntPtr inputBytes, IntPtr redBytes, IntPtr greenBytes, IntPtr blueBytes, long inputChannelCount, long imageSize);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSVision_BRGA_RGBA(IntPtr inputBytes, IntPtr redBytes, IntPtr greenBytes, IntPtr blueBytes, IntPtr alphaBytes, long inputChannelCount, long imageSize);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSVision_RGB_BRGA(IntPtr inputBytes, IntPtr outBytes, long inputChannelCount, long imageSize);\n }\n}" }, { "alpha_fraction": 0.49823907017707825, "alphanum_fraction": 0.49948206543922424, "avg_line_length": 30.34415626525879, "blob_id": "eb584a341ac54b0943aa3f4b4c541f09749788e2", "content_id": "129753d35374ef60700acd8c42f4407bee937305", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4827, "license_type": "permissive", "max_line_length": 156, "num_lines": 154, "path": "/src/TorchSharp/NN/ParameterList.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System.Collections;\nusing System.Collections.Generic;\nusing static TorchSharp.torch.nn;\n\nnamespace TorchSharp\n{\n using System.Linq;\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// Holds parameters in a list.\n /// ParameterList can be indexed like a regular list, but parameters it contains are properly registered, and will be visible by all Module methods.\n /// </summary>\n public class ParameterList : Module, IList<Parameter>\n {\n public ParameterList(params Parameter[] parameters) : base(nameof(ParameterList))\n {\n if (parameters != null && parameters.Length > 0) {\n _list.AddRange(parameters);\n }\n }\n\n protected override void RegisterComponents()\n {\n if (_registered) return;\n\n for (int i = 0; i < _list.Count; i++) {\n register_parameter($\"{i}\", _list[i]);\n }\n _registered = true;\n }\n\n public override IEnumerable<(string name, Parameter parameter)> named_parameters(bool recurse = true)\n {\n return Enumerable.Range(0, _list.Count).Select(i => ($\"{i}\", _list[i]));\n }\n\n public override bool has_parameter(string target)\n {\n return int.TryParse(target, out int idx) && idx > -1 && idx < _list.Count && _list[idx] is not null;\n }\n\n public override Parameter get_parameter(string target)\n {\n if (int.TryParse(target, out int idx) && idx > -1 && idx < _list.Count) {\n return _list[idx];\n }\n return null;\n }\n\n private bool _registered = false;\n\n public Parameter this[int index] {\n get => _list[index];\n set => _list[index] = value;\n }\n\n public int Count => _list.Count;\n\n public bool IsReadOnly => false;\n\n public void Add(Parameter item)\n {\n _list.Add(item);\n }\n\n // The following two funtions are here because PyTorch defines them.\n\n /// <summary>\n /// Appends parameters from an enumeration to the end of the list.\n /// </summary>\n /// <param name=\"parameters\"></param>\n public void extend(IEnumerable<Parameter> parameters)\n {\n _list.AddRange(parameters);\n }\n\n /// <summary>\n /// Appends zero or more parameters to the end of the list.\n /// </summary>\n public void append(params Parameter[] parameters)\n {\n if (parameters != null && parameters.Length > 0) {\n _list.AddRange(parameters);\n }\n }\n\n public void Clear()\n {\n _list.Clear();\n }\n\n public bool Contains(Parameter item)\n {\n return _list.Contains(item);\n }\n\n public void CopyTo(Parameter[] array, int arrayIndex)\n {\n _list.CopyTo(array, arrayIndex);\n }\n\n public IEnumerator<Parameter> GetEnumerator()\n {\n return _list.GetEnumerator();\n }\n\n public int IndexOf(Parameter item)\n {\n return _list.IndexOf(item);\n }\n\n public void Insert(int index, Parameter item)\n {\n _list.Insert(index, item);\n }\n\n public bool Remove(Parameter item)\n {\n return _list.Remove(item);\n }\n\n public void RemoveAt(int index)\n {\n _list.RemoveAt(index);\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n private List<Parameter> _list = new List<Parameter>();\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Create a ParameterList instance from an array of parameter tensors.\n /// </summary>\n /// <param name=\"parameters\">A list of modules.</param>\n /// <remarks>\n /// ParameterList can be indexed like a regular list, but the parameters it contains are properly registered.\n /// </remarks>\n public static ParameterList ParameterList(params Parameter[] parameters) => new ParameterList(parameters);\n }\n }\n}\n" }, { "alpha_fraction": 0.546951413154602, "alphanum_fraction": 0.5482556223869324, "avg_line_length": 42.50354766845703, "blob_id": "496925f4af86e870ef9a3b5bfee49b255b170f58", "content_id": "047751d0afae96ee1eccf0b0ca4d297d24339362", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6134, "license_type": "permissive", "max_line_length": 149, "num_lines": 141, "path": "/src/TorchSharp/Distributions/Uniform.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// Generates uniformly distributed random samples from the half-open interval [low, high[.\n /// </summary>\n public class Uniform : torch.distributions.Distribution\n {\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public override Tensor mean =>\n WrappedTensorDisposeScope(() => (high + low) / 2);\n\n public override Tensor mode => double.NaN * high;\n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public override Tensor variance =>\n WrappedTensorDisposeScope(() => (high - low).pow(2) / 12);\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"low\">Lower bound (inclusive)</param>\n /// <param name=\"high\">Upper bound (exclusive)</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n public Uniform(Tensor low, Tensor high, torch.Generator generator = null) : base(generator, low.size())\n {\n var lowHigh = torch.broadcast_tensors(low, high);\n this.low = lowHigh[0].DetachFromDisposeScope();\n this.high = lowHigh[1].DetachFromDisposeScope();\n }\n\n private Tensor high;\n private Tensor low;\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n public override Tensor rsample(params long[] sample_shape)\n {\n using var _ = torch.NewDisposeScope();\n var shape = ExtendedShape(sample_shape);\n var rand = torch.rand(shape, dtype: low.dtype, device: low.device, generator: generator);\n return (low + rand * (high - low)).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor log_prob(Tensor value)\n {\n using var _ = torch.NewDisposeScope();\n var lb = low.le(value).type_as(low);\n var ub = high.gt(value).type_as(low);\n return (torch.log(lb.mul(ub)) - torch.log(high - low)).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns the cumulative density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor cdf(Tensor value)\n {\n return torch.WrappedTensorDisposeScope(() => ((value - low) / (high - low)).clamp_(0, 1));\n }\n\n /// <summary>\n /// Returns the inverse cumulative density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor icdf(Tensor value)\n {\n return torch.WrappedTensorDisposeScope(() => (value * (high - low)).add_(low));\n }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n public override Tensor entropy()\n {\n return torch.WrappedTensorDisposeScope(() => (high - low).log_());\n }\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is Uniform))\n throw new ArgumentException(\"expand(): 'instance' must be a Uniform distribution\");\n\n var newDistribution = ((instance == null) ?\n new Uniform(low.expand(batch_shape), high.expand(batch_shape), generator) :\n instance) as Uniform;\n\n newDistribution.batch_shape = batch_shape;\n if (newDistribution == instance)\n {\n newDistribution.low = low.expand(batch_shape);\n newDistribution.high = high.expand(batch_shape);\n }\n return newDistribution;\n }\n }\n\n }\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Generates uniformly distributed random samples from the half-open interval [low, high[.\n /// </summary>\n /// <param name=\"low\">Lower bound (inclusive)</param>\n /// <param name=\"high\">Upper bound (exclusive)</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Uniform Uniform(Tensor low, Tensor high, torch.Generator generator = null)\n {\n return new Uniform(low, high, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6966068148612976, "alphanum_fraction": 0.7001996040344238, "avg_line_length": 36.01970291137695, "blob_id": "d5e6f8e37ec41423493c2d075b54a69f00e71124", "content_id": "42fd493ee202f49d0720ccfed9dc2240296b579e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7515, "license_type": "permissive", "max_line_length": 234, "num_lines": 203, "path": "/src/Native/LibTorchSharp/THSOptimizers.cpp", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#include \"THSNN.h\"\n\n#include <torch/nn/init.h>\n\nvoid THSNN_Optimizer_getParameters(const Optimizer optimizer, Tensor* (*allocator)(size_t length))\n{\n auto parameters = (*optimizer)->parameters();\n Tensor* result = allocator(parameters.size());\n\n for (size_t i = 0; i < parameters.size(); i++)\n {\n result[i] = ResultTensor(parameters[i]);\n }\n}\n\nTensor THSNN_Optimizer_step(const Optimizer optimizer, Tensor(*loss_closure)())\n{\n CATCH_TENSOR((loss_closure == nullptr) ? (*optimizer)->step() : (*optimizer)->step([loss_closure]() -> at::Tensor { return *(loss_closure()); }));\n}\n\nvoid THSNN_Optimizer_zero_grad(const Optimizer optimizer)\n{\n (*optimizer)->zero_grad();\n auto defaults = (*optimizer)->defaults();\n}\n\nOptimizer THSNN_Adagrad_ctor(const Tensor* parameters, const int length, const double learning_rate, const double lr_decay, const double weight_decay, const double initial_accumulator_value, const double eps)\n{\n auto params = toTensors<at::Tensor>((torch::Tensor**)parameters, length);\n auto options = torch::optim::AdagradOptions(learning_rate)\n .lr_decay(lr_decay)\n .weight_decay(weight_decay)\n .initial_accumulator_value(initial_accumulator_value)\n .eps(eps);\n\n return new std::shared_ptr<torch::optim::Optimizer>(std::make_shared<torch::optim::Adagrad>(torch::optim::Adagrad(params, options)));\n}\n\nOptimizer THSNN_Adam_ctor(const Tensor* parameters, const int length, const double learning_rate, const double beta1, const double beta2, const double eps, const double weight_decay, const bool amsgrad)\n{\n auto params = toTensors<at::Tensor>((torch::Tensor**)parameters, length);\n auto options = torch::optim::AdamOptions(learning_rate)\n .betas(std::make_tuple(beta1, beta2))\n .eps(eps)\n .weight_decay(weight_decay)\n .amsgrad(amsgrad);\n\n return new std::shared_ptr<torch::optim::Optimizer>(std::make_shared<torch::optim::Adam>(torch::optim::Adam(params, options)));\n}\n\nOptimizer THSNN_AdamW_ctor(const Tensor* parameters, const int length, const double learning_rate, const double beta1, const double beta2, const double eps, const double weight_decay, const bool amsgrad)\n{\n auto params = toTensors<at::Tensor>((torch::Tensor**)parameters, length);\n auto options = torch::optim::AdamWOptions(learning_rate)\n .betas(std::make_tuple(beta1, beta2))\n .eps(eps)\n .weight_decay(weight_decay)\n .amsgrad(amsgrad);\n\n return new std::shared_ptr<torch::optim::Optimizer>(std::make_shared<torch::optim::AdamW>(torch::optim::AdamW(params, options)));\n}\n\nOptimizer THSNN_LBFGS_ctor(const Tensor* parameters, const int length, const double learning_rate, const int64_t max_iter, const int64_t max_eval, const double tolerange_grad, const double tolerance_change, const int64_t history_size)\n{\n auto params = toTensors<at::Tensor>((torch::Tensor**)parameters, length);\n auto options = torch::optim::LBFGSOptions(learning_rate)\n .max_iter(max_iter)\n .max_eval(max_eval)\n .tolerance_grad(tolerange_grad)\n .tolerance_change(tolerance_change)\n .history_size(history_size);\n\n return new std::shared_ptr<torch::optim::Optimizer>(std::make_shared<torch::optim::LBFGS>(torch::optim::LBFGS(params, options)));\n}\n\nOptimizer THSNN_RMSprop_ctor(const Tensor* parameters, const int length, const double learning_rate, const double alpha, const double eps, const double weight_decay, const double momentum, const bool centered)\n{\n auto params = toTensors<at::Tensor>((torch::Tensor**)parameters, length);\n\n auto options = torch::optim::RMSpropOptions(learning_rate)\n .alpha(alpha)\n .eps(eps)\n .weight_decay(weight_decay)\n .momentum(momentum)\n .centered(centered);\n\n return new std::shared_ptr<torch::optim::Optimizer>(std::make_shared<torch::optim::RMSprop>(torch::optim::RMSprop(params, options)));\n}\n\nOptimizer THSNN_SGD_ctor(const Tensor* parameters, const int length, const double learning_rate, const double momentum, const double dampening, const double weight_decay, const bool nesterov)\n{\n auto params = toTensors<at::Tensor>((torch::Tensor**)parameters, length);\n auto opts = torch::optim::SGDOptions(learning_rate)\n .momentum(momentum)\n .dampening(dampening)\n .weight_decay(weight_decay)\n .nesterov(nesterov);\n\n return new std::shared_ptr<torch::optim::Optimizer>(std::make_shared<torch::optim::SGD>(torch::optim::SGD(params, opts)));\n}\n\n\n// Scheduler integration\n\ntemplate<typename OptionsType>\nvoid SetLearningRate(const Optimizer optimizer, const double lr)\n{\n auto options = dynamic_cast<OptionsType*>(&(*optimizer)->defaults());\n options->lr(lr);\n\n auto& pgs = (*optimizer)->param_groups();\n for (auto pg = pgs.begin(); pg < pgs.end(); ++pg)\n {\n options = dynamic_cast<OptionsType*>(&(pg->options()));\n options->lr(lr);\n }\n}\n\ntemplate<typename OptionsType>\nvoid SetMomentum(const Optimizer optimizer, const double momentum)\n{\n auto options = dynamic_cast<OptionsType*>(&(*optimizer)->defaults());\n options->momentum(momentum);\n\n auto& pgs = (*optimizer)->param_groups();\n for (auto pg = pgs.begin(); pg < pgs.end(); ++pg)\n {\n options = dynamic_cast<OptionsType*>(&(pg->options()));\n options->momentum(momentum);\n }\n}\n\ntemplate<typename OptionsType>\nvoid SetBetas(const Optimizer optimizer, const double beta1, const double beta2)\n{\n auto betas = std::make_tuple(beta1, beta2);\n\n auto options = dynamic_cast<OptionsType*>(&(*optimizer)->defaults());\n options->betas(betas);\n\n auto& pgs = (*optimizer)->param_groups();\n for (auto pg = pgs.begin(); pg < pgs.end(); ++pg)\n {\n options = dynamic_cast<OptionsType*>(&(pg->options()));\n options->betas(betas);\n }\n}\n\nvoid THSNN_Adagrad_set_lr(const Optimizer optimizer, const double lr)\n{\n SetLearningRate<torch::optim::AdagradOptions>(optimizer, lr);\n}\n\nvoid THSNN_Adam_set_lr(const Optimizer optimizer, const double lr)\n{\n SetLearningRate<torch::optim::AdamOptions>(optimizer, lr);\n}\n\nvoid THSNN_AdamW_set_lr(const Optimizer optimizer, const double lr)\n{\n SetLearningRate<torch::optim::AdamWOptions>(optimizer, lr);\n}\n\nvoid THSNN_RMSprop_set_lr(const Optimizer optimizer, const double lr)\n{\n SetLearningRate<torch::optim::RMSpropOptions>(optimizer, lr);\n}\n\nvoid THSNN_LBFGS_set_lr(const Optimizer optimizer, const double lr)\n{\n SetLearningRate<torch::optim::LBFGSOptions>(optimizer, lr);\n}\n\nvoid THSNN_SGD_set_lr(const Optimizer optimizer, const double lr)\n{\n SetLearningRate<torch::optim::SGDOptions>(optimizer, lr);\n}\n\nvoid THSNN_Optimizer_dispose(const Optimizer optimizer)\n{\n delete optimizer; // NOTE: this reduces the ref count on the shared_ptr\n}\n\nvoid THSNN_Adam_set_betas(const Optimizer optimizer, double beta1, double beta2)\n{\n SetBetas<torch::optim::AdamOptions>(optimizer, beta1, beta2);\n}\n\nvoid THSNN_AdamW_set_betas(const Optimizer optimizer, double beta1, double beta2)\n{\n SetBetas<torch::optim::AdamWOptions>(optimizer, beta1, beta2);\n}\n\nvoid THSNN_RMSprop_set_momentum(const Optimizer optimizer, double momentum)\n{\n SetMomentum<torch::optim::RMSpropOptions>(optimizer, momentum);\n}\n\nvoid THSNN_SGD_set_momentum(const Optimizer optimizer, double momentum)\n{\n SetMomentum<torch::optim::SGDOptions>(optimizer, momentum);\n}\n" }, { "alpha_fraction": 0.6264303922653198, "alphanum_fraction": 0.6299987435340881, "avg_line_length": 52.64521408081055, "blob_id": "caad04d8ac7c7c6fb283494d9275cc86e2166e83", "content_id": "8e062c7863cbfdf170583d1ac3ab11463e5df032", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 32509, "license_type": "permissive", "max_line_length": 183, "num_lines": 606, "path": "/src/TorchSharp/Tensor/torch.IndexingSlicingJoiningMutatingOps.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n // https://pytorch.org/docs/stable/torch#indexing-slicing-joining-mutating-ops\n public static partial class torch\n {\n // https://pytorch.org/docs/stable/generated/torch.adjoint\n /// <summary>\n /// Returns a view of the tensor conjugated and with the last two dimensions transposed.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n public static Tensor adjoint(Tensor input) => input.adjoint();\n\n // https://pytorch.org/docs/stable/generated/torch.argwhere\n /// <summary>\n /// Returns a tensor containing the indices of all non-zero elements of input.\n /// Each row in the result contains the indices of a non-zero element in input.\n /// The result is sorted lexicographically, with the last index changing the fastest (C-style).\n /// If input has n dimensions, then the resulting indices tensor out is of size (z×n), where\n /// z is the total number of non-zero elements in the input tensor.\n /// </summary>\n public static Tensor argwhere(Tensor input) => input.argwhere();\n\n // https://pytorch.org/docs/stable/generated/torch.cat\n /// <summary>\n /// Concatenates the given sequence of tensors in the given dimension.\n /// </summary>\n /// <param name=\"tensors\">A sequence of tensors of the same type. Non-empty tensors provided must have the same shape, except in the cat dimension.</param>\n /// <param name=\"dim\">The dimension over which the tensors are concatenated</param>\n /// <remarks> All tensors must either have the same shape (except in the concatenating dimension) or be empty.</remarks>\n public static Tensor cat(IList<Tensor> tensors, long dim = 0)\n {\n switch (tensors.Count)\n {\n case <=0: throw new ArgumentException(nameof(tensors));\n case 1: return tensors[0];\n }\n\n using var parray = new PinnedArray<IntPtr>();\n IntPtr tensorsRef = parray.CreateArray(tensors.Select(p => p.Handle).ToArray());\n\n var res = THSTensor_cat(tensorsRef, parray.Array.Length, dim);\n if (res == IntPtr.Zero) CheckForErrors();\n return new Tensor(res);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.concat\n /// <summary>\n /// Alias of torch.cat()\n /// </summary>\n /// <param name=\"tensors\">A sequence of tensors of the same type. Non-empty tensors provided must have the same shape, except in the cat dimension.</param>\n /// <param name=\"dim\">The dimension over which the tensors are concatenated</param>\n /// <remarks> All tensors must either have the same shape (except in the concatenating dimension) or be empty.</remarks>\n public static Tensor concat(IList<Tensor> tensors, long dim = 0) => torch.cat(tensors, dim);\n\n // https://pytorch.org/docs/stable/generated/torch.conj\n /// <summary>\n /// Returns a view of input with a flipped conjugate bit. If input has a non-complex dtype, this function just returns input.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor conj(Tensor input) => input.conj();\n\n // https://pytorch.org/docs/stable/generated/torch.chunk\n public static Tensor[] chunk(Tensor input, long chunks, long dim = 0)\n => input.chunk(chunks, dim);\n\n // https://pytorch.org/docs/stable/generated/torch.dsplit\n public static Tensor[] dsplit(Tensor input, Tensor indices_or_sections)\n => input.dsplit(indices_or_sections);\n\n // https://pytorch.org/docs/stable/generated/torch.dsplit\n public static Tensor[] dsplit(Tensor input, long size)\n => input.dsplit(size);\n\n // https://pytorch.org/docs/stable/generated/torch.dsplit\n public static Tensor[] dsplit(Tensor input, long[] indices_or_sections)\n => input.dsplit(indices_or_sections);\n\n // https://pytorch.org/docs/stable/generated/torch.dsplit\n public static Tensor[] dsplit(Tensor input, (long, long) indices_or_sections)\n => input.dsplit(indices_or_sections);\n\n // https://pytorch.org/docs/stable/generated/torch.dsplit\n public static Tensor[] dsplit(Tensor input, (long, long, long) indices_or_sections)\n => input.dsplit(indices_or_sections);\n\n // https://pytorch.org/docs/stable/generated/torch.dsplit\n public static Tensor[] dsplit(Tensor input, (long, long, long, long) indices_or_sections)\n => input.dsplit(indices_or_sections);\n\n // https://pytorch.org/docs/stable/generated/torch.dstack\n /// <summary>\n /// Stack tensors in sequence depthwise (along third axis).\n /// </summary>\n /// <param name=\"tensors\"></param>\n /// <returns></returns>\n /// <remarks>This is equivalent to concatenation along the third axis after 1-D and 2-D tensors have been reshaped by torch.atleast_3d().</remarks>\n public static Tensor dstack(params Tensor[] tensors)\n => dstack((IEnumerable<Tensor>)tensors);\n\n // https://pytorch.org/docs/stable/generated/torch.dstack\n /// <summary>\n /// Stack tensors in sequence depthwise (along third axis).\n /// </summary>\n /// <param name=\"tensors\"></param>\n /// <returns></returns>\n /// <remarks>This is equivalent to concatenation along the third axis after 1-D and 2-D tensors have been reshaped by torch.atleast_3d().</remarks>\n public static Tensor dstack(IList<Tensor> tensors)\n {\n using (var parray = new PinnedArray<IntPtr>()) {\n IntPtr tensorsRef = parray.CreateArray(tensors.Select(p => p.Handle).ToArray());\n\n var res = THSTensor_dstack(tensorsRef, parray.Array.Length);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n /// <summary>\n /// Stack tensors in sequence depthwise (along third axis).\n /// </summary>\n /// <param name=\"tensors\"></param>\n /// <returns></returns>\n /// <remarks>This is equivalent to concatenation along the third axis after 1-D and 2-D tensors have been reshaped by torch.atleast_3d().</remarks>\n public static Tensor dstack(IEnumerable<Tensor> tensors)\n {\n using var parray = new PinnedArray<IntPtr>();\n IntPtr tensorsRef = parray.CreateArray(tensors.Select(p => p.Handle).ToArray());\n var res = THSTensor_dstack(tensorsRef, parray.Array.Length);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n \n // https://pytorch.org/docs/stable/generated/torch.gather\n /// <summary>\n /// Gathers values along an axis specified by dim.\n /// </summary>\n public static Tensor gather(Tensor input, long dim, Tensor index) => input.gather(dim, index);\n\n // https://pytorch.org/docs/stable/generated/torch.gather\n // TODO: implement parameter sparse_grad\n public static Tensor gather(Tensor input, long dim, Tensor index, bool sparse_grad=false)\n => input.gather(dim, index);\n\n // https://pytorch.org/docs/stable/generated/torch.hsplit\n public static Tensor[] hsplit(Tensor input, Tensor indices_or_sections)\n => input.hsplit(indices_or_sections);\n\n // https://pytorch.org/docs/stable/generated/torch.hsplit\n public static Tensor[] hsplit(Tensor input, long indices_or_sections)\n => input.hsplit(indices_or_sections);\n\n // https://pytorch.org/docs/stable/generated/torch.hsplit\n public static Tensor[] hsplit(Tensor input, long[] indices_or_sections)\n => input.hsplit(indices_or_sections);\n\n // https://pytorch.org/docs/stable/generated/torch.hsplit\n public static Tensor[] hsplit(Tensor input, (long, long) indices_or_sections)\n => input.hsplit(new[]{\n indices_or_sections.Item1,\n indices_or_sections.Item2\n });\n\n // https://pytorch.org/docs/stable/generated/torch.hsplit\n public static Tensor[] hsplit(Tensor input, (long, long, long) indices_or_sections)\n => input.hsplit(new[]{\n indices_or_sections.Item1,\n indices_or_sections.Item2,\n indices_or_sections.Item3\n });\n\n // https://pytorch.org/docs/stable/generated/torch.hsplit\n public static Tensor[] hsplit(Tensor input, (long, long, long, long) indices_or_sections)\n => input.hsplit(new[]{\n indices_or_sections.Item1,\n indices_or_sections.Item2,\n indices_or_sections.Item3,\n indices_or_sections.Item4\n });\n\n // https://pytorch.org/docs/stable/generated/torch.hstack\n /// <summary>\n /// Stack tensors in sequence horizontally (column wise).\n /// </summary>\n /// <param name=\"tensors\"></param>\n /// <returns></returns>\n public static Tensor hstack(IList<Tensor> tensors)\n {\n using var parray = new PinnedArray<IntPtr>();\n IntPtr tensorsRef = parray.CreateArray(tensors.Select(p => p.Handle).ToArray());\n\n var res = THSTensor_hstack(tensorsRef, parray.Array.Length);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.hstack\n /// <summary>\n /// Stack tensors in sequence horizontally (column wise).\n /// </summary>\n /// <param name=\"tensors\"></param>\n /// <returns></returns>\n public static Tensor hstack(params Tensor[] tensors)\n {\n return hstack((IEnumerable<Tensor>)tensors);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.hstack\n /// <summary>\n /// Stack tensors in sequence horizontally (column wise).\n /// </summary>\n /// <param name=\"tensors\"></param>\n /// <returns></returns>\n public static Tensor hstack(IEnumerable<Tensor> tensors)\n {\n using var parray = new PinnedArray<IntPtr>();\n IntPtr tensorsRef = parray.CreateArray(tensors.Select(p => p.Handle).ToArray());\n\n var res = THSTensor_hstack(tensorsRef, parray.Array.Length);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.index_add\n /// <summary>\n /// Accumulate the elements of alpha times source into the input tensor by adding to the indices in the order given in index.\n ///\n /// For example, if dim == 0, index[i] == j, and alpha=-1, then the ith row of source is subtracted from the jth row of the input tensor.\n /// The dimth dimension of source must have the same size as the length of index(which must be a vector), and all other dimensions must match self, or an error will be raised.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">Dimension along which to index</param>\n /// <param name=\"index\">Indices of source to select from, should have dtype either torch.int64 or torch.int32</param>\n /// <param name=\"source\">The tensor containing values to add</param>\n /// <param name=\"alpha\">The scalar multiplier for source</param>\n /// <returns></returns>\n public static Tensor index_add(Tensor input, long dim, Tensor index, Tensor source, Scalar alpha)\n => input.index_add(dim, index, source, alpha);\n\n // https://pytorch.org/docs/stable/generated/torch.index_add\n /// <summary>\n /// Accumulate, in place, the elements of alpha times source into the input tensor by adding to the indices in the order given in index.\n ///\n /// For example, if dim == 0, index[i] == j, and alpha=-1, then the ith row of source is subtracted from the jth row of the input tensor.\n /// The dimth dimension of source must have the same size as the length of index(which must be a vector), and all other dimensions must match self, or an error will be raised.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">Dimension along which to index</param>\n /// <param name=\"index\">Indices of source to select from, should have dtype either torch.int64 or torch.int32</param>\n /// <param name=\"source\">The tensor containing values to add</param>\n /// <param name=\"alpha\">The scalar multiplier for source</param>\n /// <returns></returns>\n public static Tensor index_add_(Tensor input, long dim, Tensor index, Tensor source, Scalar alpha)\n => input.index_add_(dim, index, source, alpha);\n\n // https://pytorch.org/docs/stable/generated/torch.index_copy\n /// <summary>\n /// Copies the elements of the source tensor into the input tensor by selecting the indices in the order given in index.\n ///\n /// For example, if dim == 0 and index[i] == j, then the ith row of tensor is copied to the jth row of the input tensor.\n /// The dimth dimension of source must have the same size as the length of index(which must be a vector), and all other dimensions must match self, or an error will be raised.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">Dimension along which to index</param>\n /// <param name=\"index\">Indices of source to select from, should have dtype either torch.int64 or torch.int32</param>\n /// <param name=\"source\">The tensor containing values to copy</param>\n /// <returns></returns>\n public static Tensor index_copy(Tensor input, long dim, Tensor index, Tensor source)\n => input.index_copy(dim, index, source);\n\n // https://pytorch.org/docs/stable/generated/torch.index_copy\n /// <summary>\n /// Copies, in place, the elements of the source tensor into the input tensor by selecting the indices in the order given in index.\n ///\n /// For example, if dim == 0 and index[i] == j, then the ith row of tensor is copied to the jth row of the input tensor.\n /// The dimth dimension of source must have the same size as the length of index(which must be a vector), and all other dimensions must match self, or an error will be raised.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">Dimension along which to index</param>\n /// <param name=\"index\">Indices of source to select from, should have dtype either torch.int64 or torch.int32</param>\n /// <param name=\"source\">The tensor containing values to copy</param>\n /// <returns></returns>\n public static Tensor index_copy_(Tensor input, long dim, Tensor index, Tensor source)\n => input.index_copy_(dim, index, source);\n\n // https://pytorch.org/docs/stable/generated/torch.index_reduce\n [Obsolete(\"not implemented\", true)]\n public static Tensor index_reduce(Tensor input, long dim, Tensor index, Tensor source, Reduce reduce, bool include_self=true)\n => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.index_select\n /// <summary>\n /// Returns a new tensor which indexes the input tensor along dimension dim using the entries in index which is a LongTensor.\n /// </summary>\n public static Tensor index_select(Tensor input, long dim, Tensor index)\n => input.index_select(dim, index);\n\n // https://pytorch.org/docs/stable/generated/torch.masked_select\n public static Tensor masked_select(Tensor input, Tensor mask)\n => input.masked_select(mask);\n\n // https://pytorch.org/docs/stable/generated/torch.movedim\n public static Tensor movedim(Tensor input, long source, long destination)\n => input.movedim(new[]{source}, new[]{destination});\n\n // https://pytorch.org/docs/stable/generated/torch.movedim\n static Tensor movedim(Tensor input, (long, long) source, (long, long) destination)\n => input.movedim(\n new[]{source.Item1, source.Item2},\n new[]{destination.Item1, destination.Item2});\n\n // https://pytorch.org/docs/stable/generated/torch.movedim\n static Tensor movedim(Tensor input, (long, long, long) source, (long, long, long) destination)\n => input.movedim(\n new[]{source.Item1, source.Item2, source.Item3},\n new[]{destination.Item1, destination.Item2, destination.Item3});\n\n // https://pytorch.org/docs/stable/generated/torch.movedim\n static Tensor movedim(Tensor input, (long, long, long, long) source, (long, long, long, long) destination)\n => input.movedim(\n new[]{source.Item1, source.Item2, source.Item3, source.Item4},\n new[]{destination.Item1, destination.Item2, destination.Item3, destination.Item4});\n\n // https://pytorch.org/docs/stable/generated/torch.movedim\n public static Tensor movedim(Tensor input, long[] source, long[] destination)\n => input.movedim(source, destination);\n\n // https://pytorch.org/docs/stable/generated/torch.moveaxis\n public static Tensor moveaxis(Tensor input, long source, long destination)\n => input.moveaxis(new[]{source}, new[]{destination});\n\n // https://pytorch.org/docs/stable/generated/torch.moveaxis\n public static Tensor moveaxis(Tensor input, (long, long) source, (long, long) destination)\n => input.moveaxis(\n new[]{source.Item1, source.Item2 },\n new[]{ destination.Item1, destination.Item2 });\n\n // https://pytorch.org/docs/stable/generated/torch.moveaxis\n public static Tensor moveaxis(Tensor input, (long, long, long) source, (long, long, long) destination)\n => input.moveaxis(\n new[]{source.Item1, source.Item2, source.Item3 },\n new[]{ destination.Item1, destination.Item2, destination.Item3 });\n\n public static Tensor moveaxis(Tensor input, (long, long, long, long) source, (long, long, long, long) destination)\n => input.moveaxis(\n new[]{source.Item1, source.Item2, source.Item3, source.Item4 },\n new[]{ destination.Item1, destination.Item2, destination.Item3, destination.Item4 });\n\n public static Tensor moveaxis(Tensor input, long[] source, long[] destination)\n => input.moveaxis(source, destination);\n\n // https://pytorch.org/docs/stable/generated/torch.narrow\n public static Tensor narrow(Tensor input, long dim, long start, long length)\n => input.narrow(dim, start, length);\n\n // https://pytorch.org/docs/stable/generated/torch.nonzero\n /// <summary>\n /// Returns a tensor containing the indices of all non-zero elements of input.\n /// Each row in the result contains the indices of a non-zero element in input.\n /// The result is sorted lexicographically, with the last index changing the fastest (C-style).\n /// </summary>\n public static Tensor nonzero(Tensor input) => input.nonzero();\n\n // https://pytorch.org/docs/stable/generated/torch.permute\n /// <summary>\n /// Returns a view of the original tensor with its dimensions permuted.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"permutation\">The desired ordering of dimensions</param>\n public static Tensor permute(Tensor input, params long[] permutation) => input.permute(permutation);\n\n // https://pytorch.org/docs/stable/generated/torch.reshape\n /// <summary>\n /// Returns a tensor with the same data and number of elements as the input but with the specified shape.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"shape\">The new tensor shape.</param>\n public static Tensor reshape(Tensor input, params long[] shape) => input.reshape(shape);\n\n // https://pytorch.org/docs/stable/generated/torch.select\n public static Tensor select(Tensor input, long dim, long index)\n => input.select(dim, index);\n\n // https://pytorch.org/docs/stable/generated/torch.scatter\n /// <summary>\n /// Writes all values from the tensor src into input at the indices specified in the index tensor. For each\n /// value in src, its output index is specified by its index in src for dimension != dim and by the #\n /// corresponding value in index for dimension = dim.\n /// </summary>\n public static Tensor scatter(Tensor input, long dim, Tensor index, Tensor src)\n => input.scatter(dim, index, src);\n\n // https://pytorch.org/docs/stable/generated/torch.scatter\n /// <summary>\n /// Writes all values from the tensor src into input at the indices specified in the index tensor. For each\n /// value in src, its output index is specified by its index in src for dimension != dim and by the #\n /// corresponding value in index for dimension = dim.\n /// </summary>\n public static Tensor scatter_(Tensor input, long dim, Tensor index, Tensor src)\n => input.scatter_(dim, index, src);\n\n // https://pytorch.org/docs/stable/generated/torch.diagonal_scatter\n /// <summary>\n /// Embeds the values of the src tensor into input along the diagonal elements of input, with respect to dim1 and dim2.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"src\">The tensor to embed into 'this'.</param>\n /// <param name=\"offset\">Which diagonal to consider. Default: main diagonal.</param>\n /// <param name=\"dim1\">First dimension with respect to which to take diagonal.</param>\n /// <param name=\"dim2\">Second dimension with respect to which to take diagonal.</param>\n public static Tensor diagonal_scatter(Tensor input, Tensor src, long offset = 0L, long dim1 = 0L, long dim2 = 1L) => input.diagonal_scatter(src, offset, dim1, dim2);\n\n // https://pytorch.org/docs/stable/generated/torch.select_scatter\n /// <summary>\n /// Embeds the values of the src tensor into input at the given index. This function returns a tensor with fresh storage; it does not create a view.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"src\">The tensor to embed into 'this'</param>\n /// <param name=\"dim\">The dimension to insert the slice into</param>\n /// <param name=\"index\">The index to select with</param>\n /// <remarks>This function returns a tensor with fresh storage; it does not create a view.</remarks>\n public static Tensor select_scatter(Tensor input, Tensor src, long dim, long index) => input.select_scatter(src, dim, index);\n\n // https://pytorch.org/docs/stable/generated/torch.slice_scatter\n /// <summary>\n /// Embeds the values of the src tensor into input at the given dimension.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"src\">The tensor to embed into 'this'.</param>\n /// <param name=\"dim\">The dimension to insert the slice into</param>\n /// <param name=\"start\">The start index of where to insert the slice</param>\n /// <param name=\"end\">The end index of where to insert the slice</param>\n /// <param name=\"step\">How many elements to skip</param>\n public static Tensor slice_scatter(Tensor input, Tensor src, long dim = 0L, long? start = null, long? end = null, long step = 1L)\n => input.slice_scatter(src, dim, start, end, step);\n\n // https://pytorch.org/docs/stable/generated/torch.scatter_add\n /// <summary>\n /// Adds all values from the tensor other into input at the indices specified in the index tensor in a similar fashion as scatter_().\n /// For each value in src, it is added to an index in self which is specified by its index in src for dimension != dim and by the\n /// corresponding value in index for dimension = dim.\n /// </summary>\n public static Tensor scatter_add(Tensor input, long dim, Tensor index, Tensor src)\n => input.scatter_add(dim, index, src);\n\n // https://pytorch.org/docs/stable/generated/torch.scatter_reduce\n [Obsolete(\"not implemented\", true)]\n static Tensor scatter_reduce(\n Tensor input,\n long dim,\n Tensor index,\n Tensor src,\n Reduce reduce,\n bool include_self = true)\n => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.split\n public static Tensor[] split(Tensor tensor, long[] split_size_or_sections, long dim = 0L)\n => tensor.split(split_size_or_sections, dim);\n\n // https://pytorch.org/docs/stable/generated/torch.stack\n /// <summary>\n /// Concatenates a sequence of tensors along a new dimension.\n /// </summary>\n /// <returns></returns>\n /// <remarks>All tensors need to be of the same size.</remarks>\n public static Tensor stack(IEnumerable<Tensor> tensors, long dim = 0)\n {\n using var parray = new PinnedArray<IntPtr>();\n IntPtr tensorsRef = parray.CreateArray(tensors.Select(p => p.Handle).ToArray());\n\n var res = THSTensor_stack(tensorsRef, parray.Array.Length, dim);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.swapaxes\n public static Tensor swapaxes(Tensor input, long axis0, long axis1)\n => input.swapaxes(axis0, axis1);\n\n // https://pytorch.org/docs/stable/generated/torch.swapdims\n public static Tensor swapdims(Tensor input, long dim0, long dim1)\n => input.swapdims(dim0, dim1);\n\n // https://pytorch.org/docs/stable/generated/torch.t\n public static Tensor t(Tensor input)\n => input.t();\n\n // https://pytorch.org/docs/stable/generated/torch.take\n public static Tensor take(Tensor input, Tensor index)\n => input.take(index);\n\n // https://pytorch.org/docs/stable/generated/torch.take_along_dim\n public static Tensor take_along_dim(Tensor input, Tensor indices, long dim = 0L)\n => input.take_along_dim(indices, dim);\n\n // https://pytorch.org/docs/stable/generated/torch.take_along_dim\n public static Tensor take_along_dim(Tensor input, IEnumerable<long> indices, long dim = 0L)\n => input.take_along_dim(indices, dim);\n\n // https://pytorch.org/docs/stable/generated/torch.tensor_split\n public static Tensor[] tensor_split(Tensor input, long indices_or_sections, long dim = 0L)\n => input.tensor_split(indices_or_sections, dim);\n\n // https://pytorch.org/docs/stable/generated/torch.tensor_split\n public static Tensor[] tensor_split(Tensor input, long[] indices_or_sections, long dim = 0L)\n => input.tensor_split(indices_or_sections, dim);\n\n // https://pytorch.org/docs/stable/generated/torch.tensor_split\n public static Tensor[] tensor_split(Tensor input, Tensor indices_or_sections, long dim = 0L)\n => input.tensor_split(indices_or_sections, dim);\n\n // https://pytorch.org/docs/stable/generated/torch.tile\n /// <summary>\n /// Constructs a tensor by repeating the elements of input. The dims argument specifies the number of repetitions in each dimension.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dims\">The number of repetitions per dimension.</param>\n public static Tensor tile(Tensor input, long[] dims) => input.tile(dims);\n\n // https://pytorch.org/docs/stable/generated/torch.transpose\n public static Tensor transpose(Tensor input, long dim0, long dim1)\n => input.transpose(dim0, dim1);\n\n // https://pytorch.org/docs/stable/generated/torch.unbind\n public static Tensor[] unbind(Tensor input, long dim = 0L)\n => input.unbind(dim);\n\n // https://pytorch.org/docs/stable/generated/torch.unsqueeze\n /// <summary>\n /// Returns a new tensor with a dimension of size one inserted at the specified position.\n /// The returned tensor shares the same underlying data with this tensor.\n /// </summary>\n public static Tensor unsqueeze(Tensor input, long dim)\n => input.unsqueeze(dim);\n\n // https://pytorch.org/docs/stable/generated/torch.unsqueeze\n /// <summary>\n /// Returns a new tensor with a dimension of size one inserted at the specified position.\n /// The returned tensor shares the same underlying data with this tensor.\n /// </summary>\n public static Tensor unsqueeze_(Tensor input, long dim)\n => input.unsqueeze_(dim);\n\n // https://pytorch.org/docs/stable/generated/torch.vsplit\n public static Tensor[] vsplit(Tensor input, long[] indices_or_sections)\n => input.vsplit(indices_or_sections);\n\n // https://pytorch.org/docs/stable/generated/torch.vstack\n /// <summary>\n /// Stack tensors in sequence vertically (row wise).\n /// </summary>\n /// <param name=\"tensors\"></param>\n /// <returns></returns>\n public static Tensor vstack(IList<Tensor> tensors)\n {\n using var parray = new PinnedArray<IntPtr>();\n IntPtr tensorsRef = parray.CreateArray(tensors.Select(p => p.Handle).ToArray());\n\n var res = THSTensor_vstack(tensorsRef, parray.Array.Length);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n return new Tensor(res);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.where\n /// <summary>\n /// Return a tensor of elements selected from either x or y, depending on condition.\n /// </summary>\n /// <param name=\"condition\">When true, yield x, otherwise yield y.</param>\n /// <param name=\"x\">Values selected at indices where condition is true</param>\n /// <param name=\"y\">Values selected at indices where condition is false</param>\n /// <returns></returns>\n public static Tensor where(Tensor condition, Tensor x, Tensor y) => x.where(condition, y);\n\n // https://pytorch.org/docs/stable/generated/torch.where\n /// <summary>\n /// Returns a tuple of 1-D tensors, one for each dimension in input, each containing the indices (in that dimension) of all non-zero elements of input .\n /// If input has nn dimensions, then the resulting tuple contains nn tensors of size zz, where zz is the total number of non-zero elements in the input tensor.\n /// As a special case, when input has zero dimensions and a nonzero scalar value, it is treated as a one-dimensional tensor with one element.\n /// </summary>\n /// <param name=\"condition\">The input tensor</param>\n /// <returns></returns>\n /// <exception cref=\"ArgumentException\"></exception>\n public static Tensor[] where(Tensor condition)\n {\n if (condition.dtype != ScalarType.Bool) throw new ArgumentException(\"The condition to 'where' must be a boolean tensor.\");\n\n IntPtr[] ptrArray;\n\n using (var pa = new PinnedArray<IntPtr>()) {\n THSTensor_where_list(condition.Handle, pa.CreateArray);\n CheckForErrors();\n ptrArray = pa.Array;\n }\n\n return ptrArray.Select(x => new Tensor(x)).ToArray();\n }\n }\n}" }, { "alpha_fraction": 0.5130791664123535, "alphanum_fraction": 0.5197653770446777, "avg_line_length": 45.08648681640625, "blob_id": "e8830d173acb3a031c7329a7cb33cf9190070171", "content_id": "e0b4c495849cdc10d11ff96aad3d0ee6cbd35d5c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8525, "license_type": "permissive", "max_line_length": 130, "num_lines": 185, "path": "/src/TorchAudio/Transforms.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing TorchSharp.Transforms;\n\n// A number of implementation details in this file have been translated from the Python version of torchaudio,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/audio/blob/bb77cbebb620a46fdc0dc7e6dae2253eef3f37e2/torchaudio/transforms/_transforms.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/audio/blob/main/LICENSE\n//\n\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n public delegate torch.Tensor WindowFunction(long win_length);\n\n public static partial class transforms\n {\n /// <summary>\n /// Compute spectrograms from audio signals.\n /// </summary>\n /// <param name=\"n_fft\">The size of Fourier transform</param>\n /// <param name=\"hop_length\">The hop length</param>\n /// <param name=\"win_length\">The window length</param>\n /// <param name=\"pad\">Padding on the sides</param>\n /// <param name=\"window_fn\">The callback to create a window function</param>\n /// <param name=\"window\">The window function</param>\n /// <param name=\"power\">Exponent for the magnitude spectrogram</param>\n /// <param name=\"normalized\">Whether the output is normalized, or not.</param>\n /// <param name=\"center\">Whether the t-th frame is centered around t * hop_window, or not.</param>\n /// <param name=\"pad_mode\">The padding mode used when center is true.</param>\n /// <param name=\"onesided\">Whether the output is onesided or not.</param>\n /// <param name=\"return_complex\">Deprecated and not used.</param>\n /// <returns>ITransform to compute spectrograms of audio signals</returns>\n public static Spectrogram Spectrogram(\n long n_fft = 400,\n long? win_length = null,\n long? hop_length = null,\n long pad = 0,\n WindowFunction window_fn = null,\n Tensor window = null,\n double? power = 2.0,\n bool normalized = false,\n bool center = true,\n PaddingModes pad_mode = PaddingModes.Reflect,\n bool onesided = true,\n bool? return_complex = null)\n {\n return new Spectrogram(\n \"Spectrogram\",\n n_fft: n_fft,\n hop_length: hop_length,\n win_length: win_length,\n pad: pad,\n window_fn: window_fn,\n window: window,\n power: power,\n normalized: normalized,\n center: center,\n pad_mode: pad_mode,\n onesided: onesided,\n return_complex: return_complex);\n }\n\n /// <summary>\n /// Compute inverse of spectrogram.\n /// </summary>\n /// <param name=\"n_fft\">The size of Fourier transform</param>\n /// <param name=\"hop_length\">The hop length</param>\n /// <param name=\"win_length\">The window length</param>\n /// <param name=\"pad\">Padding on the sides</param>\n /// <param name=\"window_fn\">The callback to create a window function</param>\n /// <param name=\"window\">The window function</param>\n /// <param name=\"normalized\">Whether the output is normalized, or not.</param>\n /// <param name=\"center\">Whether the t-th frame is centered around t * hop_window, or not.</param>\n /// <param name=\"pad_mode\">The padding mode used when center is true.</param>\n /// <param name=\"onesided\">Whether the output is onesided or not.</param>\n /// <returns>ITransform to compute inverse of spectrogram</returns>\n public static InverseSpectrogram InverseSpectrogram(\n long n_fft = 400,\n long? win_length = null,\n long? hop_length = null,\n long pad = 0,\n WindowFunction window_fn = null,\n Tensor window = null,\n bool normalized = false,\n bool center = true,\n PaddingModes pad_mode = PaddingModes.Reflect,\n bool onesided = true)\n {\n return new InverseSpectrogram(\n \"InverseSpectrogram\",\n n_fft: n_fft,\n hop_length: hop_length,\n win_length: win_length,\n pad: pad,\n window_fn: window_fn,\n window: window,\n normalized: normalized,\n center: center,\n pad_mode: pad_mode,\n onesided: onesided);\n }\n\n /// <summary>\n /// Resample the waveform\n /// </summary>\n /// <param name=\"orig_freq\">The source sampling rate</param>\n /// <param name=\"new_freq\">The destination sampling rate</param>\n /// <param name=\"lowpass_filter_width\">The width of the filter</param>\n /// <param name=\"rolloff\">The roll-off frequency</param>\n /// <param name=\"resampling_method\">The resampling method</param>\n /// <param name=\"beta\">Beta for Keizer window</param>\n /// <param name=\"device\">The device</param>\n /// <param name=\"dtype\">The scalar type</param>\n /// <returns>The resampled waveform</returns>\n /// <exception cref=\"ArgumentOutOfRangeException\"></exception>\n public static Resample Resample(\n int orig_freq = 16000,\n int new_freq = 16000,\n ResamplingMethod resampling_method = ResamplingMethod.sinc_interpolation,\n int lowpass_filter_width = 6,\n double rolloff = 0.99,\n double? beta = null,\n torch.Device device = null,\n torch.ScalarType? dtype = null)\n {\n return new Resample(\n \"Resample\",\n orig_freq,\n new_freq,\n resampling_method,\n lowpass_filter_width,\n rolloff,\n beta,\n device,\n dtype);\n }\n\n /// <summary>\n /// Compute waveform from a linear scale magnitude spectrogram using the Griffin-Lim transformation.\n /// </summary>\n /// <param name=\"n_fft\">Size of FFT, creates ``n_fft // 2 + 1`` bins.</param>\n /// <param name=\"n_iter\">Number of iteration for phase recovery process.</param>\n /// <param name=\"win_length\">Window size.</param>\n /// <param name=\"hop_length\">Length of hop between STFT windows.</param>\n /// <param name=\"window_fn\">A function to create a window tensor\n /// that is applied/multiplied to each frame/window.</param>\n /// <param name=\"power\">Exponent for the magnitude spectrogram,\n /// (must be > 0) e.g., 1 for energy, 2 for power, etc.</param>\n /// <param name=\"momentum\">The momentum parameter for fast Griffin-Lim.</param>\n /// <param name=\"length\">Array length of the expected output.</param>\n /// <param name=\"rand_init\">Initializes phase randomly if True and to zero otherwise.</param>\n /// <returns></returns>\n public static GriffinLim GriffinLim(\n int n_fft = 400,\n int n_iter = 32,\n long? win_length = null,\n long? hop_length = null,\n WindowFunction window_fn = null,\n double power = 2.0,\n double momentum = 0.99,\n int? length = null,\n bool rand_init = true)\n {\n return new GriffinLim(\n \"GriffinLim\",\n n_fft,\n n_iter,\n win_length,\n hop_length,\n window_fn,\n power,\n momentum,\n length,\n rand_init);\n }\n }\n }\n}" }, { "alpha_fraction": 0.5553860068321228, "alphanum_fraction": 0.5590479373931885, "avg_line_length": 39.456790924072266, "blob_id": "5b0d4fdac7d305df1ea68710fcefcdd3e307543d", "content_id": "5df3b78737001a5b6cc9d47e0ecdfe7122d66648", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3277, "license_type": "permissive", "max_line_length": 172, "num_lines": 81, "path": "/src/TorchSharp/Distributions/Pareto.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n using static torch.distributions;\n\n namespace Modules\n {\n public class Pareto : TransformedDistribution\n {\n internal Pareto(Tensor scale, Tensor alpha, Distribution base_distribution, torch.distributions.transforms.Transform[] transforms, Generator generator = null) :\n base(base_distribution, transforms, generator)\n {\n this.scale = scale.alias().DetachFromDisposeScope();\n this.alpha = alpha.alias().DetachFromDisposeScope();\n }\n\n public Tensor scale { get; private set; }\n\n public Tensor alpha { get; private set; }\n\n public override Tensor mean {\n get {\n using var _ = torch.NewDisposeScope();\n var a = alpha.clamp(min: 1);\n return (a * scale / (a - 1)).MoveToOuterDisposeScope();\n }\n }\n\n public override Tensor mode => scale;\n\n public override Tensor variance {\n get {\n using var _ = torch.NewDisposeScope();\n var a = alpha.clamp(min: 2);\n return (scale.pow(2) * a / ((a - 1).pow(2) * (a - 2))).MoveToOuterDisposeScope();\n }\n }\n\n public override Distribution expand(Size batch_shape, Distribution instance = null)\n {\n var newDistribution = ((instance == null)\n ? torch.distributions.Pareto(scale.expand(batch_shape), alpha.expand(batch_shape), generator)\n : instance) as Pareto;\n return base.expand(batch_shape, newDistribution);\n }\n\n public override Tensor entropy() => torch.WrappedTensorDisposeScope(() => (scale / alpha).log() + 1 + alpha.reciprocal());\n }\n }\n\n\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Samples from a Pareto Type 1 distribution.\n /// </summary>\n /// <param name=\"scale\">Scale parameter of the distribution.</param>\n /// <param name=\"alpha\">Shape parameter of the distribution</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Pareto Pareto(Tensor scale, Tensor alpha, torch.Generator generator = null)\n {\n var scaleAlpha = torch.broadcast_tensors(scale, alpha);\n scale = scaleAlpha[0];\n alpha = scaleAlpha[1];\n var base_dist = Exponential(alpha, generator);\n var transforms = new torch.distributions.transforms.Transform[] {\n new torch.distributions.transforms.ExpTransform(),\n new torch.distributions.transforms.AffineTransform(loc:0, scale:scale)\n };\n return new Pareto(scale, alpha, base_dist, transforms, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5217464566230774, "alphanum_fraction": 0.5250704288482666, "avg_line_length": 46.97297286987305, "blob_id": "06c0944d9719839e4b8f2522cbd24ac54eec1855", "content_id": "250d9ac5ed563bf8e629b51eda263aaf0c37abfd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 17750, "license_type": "permissive", "max_line_length": 236, "num_lines": 370, "path": "/src/TorchSharp/Optimizers/SGD.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using System.IO;\n using Modules;\n\n public static partial class torch\n {\n public static partial class optim\n {\n /// <summary>\n /// Implements the stochastic gradient descent (optionally with momentum).\n ///\n /// The use of momentum is covered in:\n /// http://www.cs.toronto.edu/%7Ehinton/absps/momentum.pdf\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"learningRate\">Learning rate</param>\n /// <param name=\"momentum\">Momentum factor (default: 0)</param>\n /// <param name=\"dampening\">Dampening for momentum (default: 0)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"nesterov\">Enables Nesterov momentum (default: False)</param>\n /// <param name=\"maximize\"></param>\n /// <returns></returns>\n public static Modules.SGD SGD(IEnumerable<Parameter> parameters, double learningRate, double momentum = 0, double dampening = 0, double weight_decay = 0, bool nesterov = false, bool maximize = false)\n {\n return new Modules.SGD(parameters, learningRate, momentum, dampening, weight_decay, nesterov, maximize);\n }\n\n /// <summary>\n /// Implements the stochastic gradient descent (optionally with momentum).\n ///\n /// The use of momentum is covered in:\n /// http://www.cs.toronto.edu/%7Ehinton/absps/momentum.pdf\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"learningRate\">Learning rate</param>\n /// <param name=\"momentum\">Momentum factor (default: 0)</param>\n /// <param name=\"dampening\">Dampening for momentum (default: 0)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"nesterov\">Enables Nesterov momentum (default: False)</param>\n /// <param name=\"maximize\"></param>\n /// <returns></returns>\n public static Modules.SGD SGD(IEnumerable<(string name, Parameter parameter)> parameters, double learningRate, double momentum = 0, double dampening = 0, double weight_decay = 0, bool nesterov = false, bool maximize = false)\n {\n return new Modules.SGD(parameters.Select(np => np.parameter), learningRate, momentum, dampening, weight_decay, nesterov, maximize);\n }\n\n /// <summary>\n /// Implements the stochastic gradient descent (optionally with momentum).\n ///\n /// The use of momentum is covered in:\n /// http://www.cs.toronto.edu/%7Ehinton/absps/momentum.pdf\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"learningRate\">Learning rate</param>\n /// <param name=\"momentum\">Momentum factor (default: 0)</param>\n /// <param name=\"dampening\">Dampening for momentum (default: 0)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"nesterov\">Enables Nesterov momentum (default: False)</param>\n /// <param name=\"maximize\"></param>\n /// <returns></returns>\n public static Modules.SGD SGD(IEnumerable<SGD.ParamGroup> parameters, double learningRate, double momentum = 0.0, double dampening = 0, double weight_decay = 0, bool nesterov = false, bool maximize = false)\n {\n return new Modules.SGD(parameters, learningRate, momentum, dampening, weight_decay, nesterov, maximize);\n }\n }\n }\n namespace Modules\n {\n using static torch.optim;\n\n public class SGD : OptimizerHelper, IMomentum\n {\n /// <summary>\n /// Implements stochastic gradient descent (optionally with momentum).\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"lr\">Learning rate</param>\n /// <param name=\"momentum\">Momentum factor (default: 0)</param>\n /// <param name=\"dampening\">Dampening for momentum (default: 0)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"nesterov\">Enables Nesterov momentum (default: False)</param>\n /// <param name=\"maximize\"></param>\n /// <returns></returns>\n public SGD(IEnumerable<Parameter> parameters, double lr, double momentum = 0.0, double dampening = 0, double weight_decay = 0, bool nesterov = false, bool maximize = false)\n : this(new ParamGroup[] { new ParamGroup { Parameters = parameters } }, lr, momentum, dampening, weight_decay, nesterov, maximize)\n {\n }\n\n /// <summary>\n /// Implements stochastic gradient descent (optionally with momentum).\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"lr\">Learning rate</param>\n /// <param name=\"momentum\">Momentum factor (default: 0)</param>\n /// <param name=\"dampening\">Dampening for momentum (default: 0)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"nesterov\">Enables Nesterov momentum (default: False)</param>\n /// <param name=\"maximize\"></param>\n /// <returns></returns>\n public SGD(IEnumerable<ParamGroup> parameters, double lr, double momentum = 0.0, double dampening = 0, double weight_decay = 0, bool nesterov = false, bool maximize = false)\n {\n if (lr < 0.0) throw new ArgumentException($\"Invalid learning rate: {lr}\");\n if (momentum < 0.0) throw new ArgumentException($\"Invalid momentum value: {momentum}\");\n if (weight_decay < 0.0) throw new ArgumentException($\"Invalid weight_decay value: {weight_decay}\");\n if (nesterov && (momentum <= 0 || dampening != 0)) throw new ArgumentException(\"Nesterov momentum requires a momentum and zero dampening\");\n\n var options = new Options {\n LearningRate = lr,\n InitialLearningRate = lr,\n dampening = dampening,\n maximize = maximize,\n momentum = momentum,\n nesterov = nesterov,\n weight_decay = weight_decay\n };\n\n _defaults = options;\n _parameter_groups = new List<Modules.ParamGroup>();\n\n foreach (var g in parameters) {\n add_param_group(g);\n }\n }\n\n /// <summary>\n /// Performs a single optimization step (parameter update).\n /// </summary>\n /// <param name=\"closure\">A closure that reevaluates the model and returns the loss. Optional for most optimizers.</param>\n /// <returns></returns>\n public override Tensor step(Func<Tensor> closure = null)\n {\n return _step<ParamGroup>(group => {\n\n var options = group.Options;\n var momentum = options.momentum.Value;\n var dampening = options.dampening.Value;\n var weight_decay = options.weight_decay.Value;\n var nesterov = options.nesterov.Value;\n var maximize = options.maximize.Value;\n var lr = options.LearningRate.Value;\n\n foreach (var param in group.Parameters) {\n\n var state = (State)_state[param.handle];\n\n var grad = param.grad();\n\n if (grad is null) continue;\n\n if (weight_decay != 0) {\n grad = grad.add(param, alpha: weight_decay);\n }\n\n if (momentum != 0) {\n var buf = state.momentum_buffer;\n\n if (buf is null) {\n buf = grad.clone().detach().DetachFromDisposeScope();\n state.momentum_buffer = buf;\n } else {\n buf.mul_(momentum).add_(grad, alpha: (1 - dampening));\n }\n\n if (nesterov) {\n grad = grad.add(buf, alpha: momentum);\n } else {\n grad = buf;\n }\n\n state.momentum_buffer = buf;\n }\n\n var alpha = maximize ? lr : -lr;\n param.add_(grad, alpha: alpha);\n\n }\n }, closure);\n }\n\n protected override void Dispose(bool disposing)\n {\n base.Dispose(disposing);\n foreach (var kvp in _state) {\n var st = (State)kvp.Item2;\n if (st.momentum_buffer is not null) {\n st.momentum_buffer.Dispose();\n }\n }\n _state.Clear();\n }\n\n public sealed class State : OptimizerState, IDisposable\n {\n public Tensor momentum_buffer;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n private void Dispose(bool disposing)\n {\n if (disposing) {\n momentum_buffer?.Dispose();\n }\n }\n\n /// <summary>\n /// Move all the state to the indicated device.\n /// </summary>\n /// <param name=\"device\">The device to move all state to.</param>\n public override void to(Device device)\n {\n momentum_buffer = momentum_buffer?.to(device);\n }\n\n /// <summary>\n /// Load the optimizer parameter state from a stream.\n /// </summary>\n /// <param name=\"reader\">A binary reader connected to a stream open for reading.</param>\n public override void LoadStateDict(BinaryReader reader)\n {\n LoadConditionalStateTensor(reader, ref momentum_buffer);\n }\n\n /// <summary>\n /// Save the optimizer parameter state to a stream.\n /// </summary>\n /// <param name=\"writer\">A binary writer connected to a stream open for writing.</param>\n public override void SaveStateDict(BinaryWriter writer)\n {\n SaveConditionalStateTensor(writer, momentum_buffer);\n }\n\n /// <summary>\n /// Load optimizer parameter state from another optimizer.\n /// </summary>\n /// <param name=\"source\">An optimizer state record.</param>\n public override void LoadStateDict(OptimizerState source)\n {\n var st_state = source as State;\n if (momentum_buffer is not null) {\n momentum_buffer.Dispose();\n }\n momentum_buffer = st_state.momentum_buffer;\n }\n\n /// <summary>\n /// Useful for tests, allows comparison of one state with another.\n /// </summary>\n /// <param name=\"other\">The other optimizer state</param>\n /// <returns></returns>\n public override bool ApproximatelyEquals(OptimizerState other)\n {\n var rhs = other as State;\n return (rhs is not null) && (momentum_buffer is null || momentum_buffer.allclose(rhs.momentum_buffer));\n }\n }\n\n /// <summary>\n /// Add a param group to the Optimizer s param_groups.\n /// </summary>\n /// <param name=\"param_group\"></param>\n /// <remarks>This can be useful when fine tuning a pre-trained network as frozen layers can be made trainable and added to the Optimizer as training progresses.</remarks>\n public override void add_param_group(Modules.ParamGroup param_group)\n {\n var def = _defaults as Options;\n if (param_group.Options is null) {\n param_group.Options = new Options();\n }\n\n var opt = param_group.Options as Options;\n\n // Make sure all the options are set.\n if (!opt.LearningRate.HasValue) opt.LearningRate = def.LearningRate;\n if (!opt.momentum.HasValue) opt.momentum = def.momentum;\n if (!opt.dampening.HasValue) opt.dampening = def.dampening;\n if (!opt.weight_decay.HasValue) opt.weight_decay = def.weight_decay;\n if (!opt.nesterov.HasValue) opt.nesterov = def.nesterov;\n if (!opt.maximize.HasValue) opt.maximize = def.maximize;\n\n opt.InitialLearningRate = opt.LearningRate.Value;\n\n _parameter_groups.Add(param_group);\n\n foreach (var p in param_group.Parameters) {\n var state = new State();\n _state.Add((p.Handle,state));\n state.momentum_buffer = null;\n }\n }\n\n public class Options : Modules.OptimizerOptions\n {\n public double? momentum;\n public double? dampening;\n public double? weight_decay;\n public bool? nesterov;\n public bool? maximize;\n\n /// <summary>\n /// Load the optimizer options (param-group hyperparameters) from a stream.\n /// </summary>\n /// <param name=\"reader\">A binary reader connected to a stream open for reading.</param>\n public override void LoadStateDict(BinaryReader reader)\n {\n base.LoadStateDict(reader);\n momentum = reader.ReadDouble();\n dampening = reader.ReadDouble();\n weight_decay = reader.ReadDouble();\n nesterov = reader.ReadBoolean();\n maximize = reader.ReadBoolean();\n }\n\n /// <summary>\n /// Load optimizer options (param-group hyperparameters) from another optimizer.\n /// </summary>\n /// <param name=\"source\">An optimizer options record.</param>\n public override void LoadStateDict(OptimizerOptions source)\n {\n base.LoadStateDict(source);\n var opts = source as Options;\n momentum = opts.momentum;\n dampening = opts.dampening;\n weight_decay = opts.weight_decay;\n nesterov = opts.nesterov;\n maximize = opts.maximize;\n }\n\n /// <summary>\n /// Save the optimizer options (param-group hyperparameters) to a stream.\n /// </summary>\n /// <param name=\"writer\">A binary writer connected to a stream open for writing.</param>\n public override void SaveStateDict(BinaryWriter writer)\n {\n base.SaveStateDict(writer);\n writer.Write(momentum.Value);\n writer.Write(dampening.Value);\n writer.Write(weight_decay.Value);\n writer.Write(nesterov.Value);\n writer.Write(maximize.Value);\n }\n }\n\n public class ParamGroup : ParamGroup<Options>, IMomentum\n {\n public ParamGroup() { }\n\n public ParamGroup(IEnumerable<Parameter> parameters, Options options) : base(parameters, options) { }\n\n public ParamGroup(IEnumerable<Parameter> parameters, double lr = 1e-3, double momentum = 0.0, double dampening = 0, double weight_decay = 0, bool nesterov = false, bool maximize = false)\n : base(parameters, new SGD.Options { LearningRate = lr, dampening = dampening, momentum = momentum, weight_decay = weight_decay, nesterov = nesterov, maximize = maximize })\n {\n }\n\n public double Momentum { get => Options.momentum.Value; set => Options.momentum = value; }\n }\n\n public double Momentum { get => (_defaults as Options).momentum.Value; set => (_defaults as Options).momentum = value; }\n }\n }\n}\n" }, { "alpha_fraction": 0.535237193107605, "alphanum_fraction": 0.5380009412765503, "avg_line_length": 30.463768005371094, "blob_id": "5828959b8aa25fc858d2d99eeea6656e4b456a29", "content_id": "aedcf10155a9f7cad45aa0cab880239f49cc9582", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2171, "license_type": "permissive", "max_line_length": 161, "num_lines": 69, "path": "/src/TorchSharp/Utils/TensorDataset.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System;\nusing System.IO;\nusing System.Collections.Generic;\n\nnamespace TorchSharp\n{\n using System.Data;\n using System.Linq;\n using Modules;\n\n public static partial class torch\n {\n public static partial class utils\n {\n public static partial class data {\n\n /// <summary>\n /// Dataset wrapping tensors.\n ///\n /// Each sample will be retrieved by indexing tensors along the first dimension.\n /// </summary>\n /// <param name=\"tensors\">Tensors that have the same size of the first dimension.</param>\n public static TensorDataset TensorDataset(params torch.Tensor[] tensors) => new TensorDataset(tensors);\n }\n }\n }\n\n namespace Modules\n {\n public class TensorDataset : torch.utils.data.Dataset<IList<torch.Tensor>>\n {\n internal TensorDataset(torch.Tensor[] tensors)\n {\n if (tensors is null || tensors.Length == 0) throw new ArgumentNullException(nameof(tensors));\n long size1 = tensors[0].shape[0];\n if (!tensors.All(t => t.shape[0] == size1)) throw new ArgumentException(\"All tensors must have the same first dimension size.\", nameof(tensors));\n\n _tensors.AddRange(tensors);\n }\n\n /// <summary>\n /// Indexer\n /// </summary>\n public IList<torch.Tensor> this[long index] {\n\n get {\n return _tensors.Select(t => t[index]).ToList();\n }\n }\n\n /// <summary>\n /// Length of the dataset\n /// </summary>\n public override long Count {\n get { return _tensors.Count; }\n }\n\n public override IList<torch.Tensor> GetTensor(long index)\n {\n return this[index];\n }\n\n private List<torch.Tensor> _tensors = new List<torch.Tensor>();\n }\n\n }\n}\n" }, { "alpha_fraction": 0.532310426235199, "alphanum_fraction": 0.5464738607406616, "avg_line_length": 42.46154022216797, "blob_id": "62b29d7481339376d2112fe2571fcbda72356a57", "content_id": "6324757a29cdfd9ec0100fc63f5b275327869d6c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3389, "license_type": "permissive", "max_line_length": 130, "num_lines": 78, "path": "/src/TorchAudio/Datasets/YesnoDataset.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.IO;\nusing System.Linq;\n\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n public static partial class datasets\n {\n private class YesnoDataset : torch.utils.data.Dataset<YesnoDatasetItem>\n {\n public const string ArchiveChecksum = \"c3f49e0cca421f96b75b41640749167b52118f232498667ca7a5f9416aef8e73\";\n\n private readonly string[] audioPathList;\n\n public YesnoDataset(string directoryPathInArchive)\n {\n audioPathList = Directory.EnumerateFiles(directoryPathInArchive, \"*.wav\").ToArray();\n }\n\n public override long Count => audioPathList.LongLength;\n\n public override YesnoDatasetItem GetTensor(long index)\n {\n var (waveform, sample_rate) = torchaudio.load(audioPathList[index]);\n return new() {\n waveform = waveform,\n sample_rate = sample_rate,\n labels = null\n };\n }\n }\n\n /// <summary>\n /// Create a Yesno dataset\n /// </summary>\n /// <param name=\"root\">The path to the dataset</param>\n /// <param name=\"url\">The URL to download the dataset from</param>\n /// <param name=\"folder_in_archive\">The top directory of the dataset</param>\n /// <param name=\"download\">True to download the dataset</param>\n /// <returns>The dataset</returns>\n /// <exception cref=\"InvalidDataException\"></exception>\n public static torch.utils.data.Dataset<YesnoDatasetItem> YESNO(\n string root,\n string url = \"http://www.openslr.org/resources/1/waves_yesno.tar.gz\",\n string folder_in_archive = \"waves_yesno\",\n bool download = false)\n {\n var directoryPathInArchive = Path.Combine(root, folder_in_archive);\n var archiveFileName = GetFileNameFromUrl(url);\n var archivePath = Path.Combine(root, archiveFileName);\n if (download) {\n if (!Directory.Exists(directoryPathInArchive)) {\n if (!File.Exists(archivePath)) {\n torch.hub.download_url_to_file(url, archivePath, YesnoDataset.ArchiveChecksum);\n }\n utils.extract_archive(archivePath, root);\n }\n }\n if (!Directory.Exists(directoryPathInArchive)) {\n throw new InvalidDataException(\"Dataset not found. Please use `download=true` to download it.\");\n }\n return new YesnoDataset(directoryPathInArchive);\n }\n\n private static string GetFileNameFromUrl(string url)\n {\n int index = url.LastIndexOf('/');\n if (index < 0) throw new ArgumentException();\n var fileName = url.Substring(index + 1);\n if (string.IsNullOrWhiteSpace(fileName)) throw new ArgumentException();\n return fileName;\n }\n }\n }\n}" }, { "alpha_fraction": 0.8063063025474548, "alphanum_fraction": 0.8063063025474548, "avg_line_length": 23.77777862548828, "blob_id": "b3676c49ea15108b35c41a4b93af7e419eac305b", "content_id": "7a1bee53a7cc355bdf0a9996f7d9d5036ffc180c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 224, "license_type": "permissive", "max_line_length": 70, "num_lines": 9, "path": "/src/TorchSharp/DistanceFunctionNative.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "#nullable enable\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp\n{\n [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\n public delegate IntPtr DistanceFunctionNative(IntPtr x, IntPtr y);\n}" }, { "alpha_fraction": 0.7151066064834595, "alphanum_fraction": 0.7199258804321289, "avg_line_length": 38.37956237792969, "blob_id": "714c6ff073ebd7e04b490bd8a6ff7d33dd44f572", "content_id": "7b423e5a44cf0b990a3762d92384a44cb0e58628", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5395, "license_type": "permissive", "max_line_length": 410, "num_lines": 137, "path": "/docfx/articles/torchscript.md", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "# TorchScript\n\nTorchSchript is a PyTorch technology that lets you save a subset of PyTorch-based Python code without a dependency on a Python runtime. Such models can be loaded into native code, and therefore into .NET code.\n\nTorchScript is very powerful, because it allows you to save the logic and the weights of a model together, and it furthermore allows the module to be loaded into another program, __without any dependencies on the Python runtime.__ Thus, you can load a model that has been serialized using TorchScript and have it behave as any TorchScript module -- you can use it for training, or you can use it for inference.\n\n## Loading TorchScript Modules\n\nStarting with release 0.96.9, you can load TorchScript modules and functions that have been either traced or scripted in Pytorch. It is, however, not yet possible to create a TorchScript module from scratch using TorchSharp. \n\nIn Python, a TorchScript module can be a class derived from 'nn.Module,' or a function that operates on tensors and stays within the constraints that TorchScript places on it. The script can be formed by tracing or by compiling the code. Refer to the [Pytorch JIT](https://pytorch.org/docs/stable/jit.html) docs for information on the details.\n\nFor example, the following Python code creates a TorchScript module. Note the use of type annotations\n\n```Python\nfrom typing import Tuple\nimport torch\nfrom torch import nn\nfrom torch import Tensor\n\nclass MyModule(nn.Module):\n def __init__(self):\n super().__init__()\n self.p = nn.Parameter(torch.rand(10))\n\n def forward(self, x: Tensor, y: Tensor) -> Tuple[Tensor, Tensor]:\n return x + y, x - y\n \n @torch.jit.export\n def predict(self, x: Tensor) -> Tensor:\n return x + self.p\n\n @torch.jit.export\n def add_scalar(self, x: Tensor, i: int) -> Tensor:\n return x + i\n\nm = MyModule()\n\nm = torch.jit.script(m)\nm.save(\"exported.method.dat\")\n```\n\nThe following can also be used to create a TorchScript script:\n\n```Python\[email protected]\ndef a(x: Tensor, y: Tensor):\n return x + y, x - y\n```\n\nOnce you have a TorchScript file, you can load it into TorchSharp using:\n\n```C#\nvar m = torch.jit.load(\"file-name\");\n```\n\nIt returns a ScriptModule, which behaves just like any other TorchSharp module. Whether the original script came from a module or a function, it is deserialized as a module. You can use it for training of inference by calling either `train()` or `eval()`. ScriptModules always start out on the CPU, so you have to call `cuda()` in order to move it to a GPU.\n\nNote that if you used __tracing__ to create the TorchScript file in Pytorch, submodules that behave differently in training and eval modes will behave according to the mode they were traced in.\n\nIf you use the script module to train, you may want / need to save it afterwards. \n\nThat is easily done using `save()`:\n\n```C#\ntorch.jit.save(m, \"file-name\");\n```\n\nThere's also a type-safe version of `load()` that returns a script module that implements IModule<T1...,TResult>. For the above example(s) `torch.jit.load<Tensor,Tensor,(Tensor, Tensor)>` is the appropriate one to use:\n\n```C#\nvar m = torch.jit.load<Tensor,Tensor,Tensor>(\"file-name\");\n```\n\nWhile it is possible to save a modified ScriptModule from TorchSharp, it is not (yet) possible to create one _from scratch_ using either tracing or scripting.\n\nScript modules have a main `forward()` method, even if they were created from a function rather than a Module class. However, if the module was created from a class, and other methods have the 'torch.jit.export' annotation, then those methods are also callable from TorchSharp:\n\n```C#\nvar x = torch.rand(10);\nvar y = torch.rand(10);\nvar t0 = m.forward(x,y);\nvar t1 = m.invoke(\"predict\", x);\nvar t2 = m.invoke(\"add_scalar\", x, 3.14);\n```\n\nNote how methods other than `forward()` must be invoked with their name passed as a string. It may be useful to wrap such modules in a hand-written class, like:\n\n```C#\nclass TestScriptModule : Module<Tensor, Tensor, (Tensor, Tensor)>\n{\n internal TestScriptModule(string filename) : base(nameof(TestScriptModule))\n {\n m = torch.jit.load<(Tensor, Tensor)> (filename);\n }\n\n public override (Tensor, Tensor) forward(Tensor input1, Tensor input2)\n {\n return m.forward(input1, input2);\n }\n\n public Tensor predict(Tensor input)\n {\n return m.invoke<Tensor>(\"predict\", input);\n }\n\n public Tensor add_scalar(Tensor input, int i)\n {\n return m.invoke<Tensor>(\"add_scalar\", input, i);\n }\n\n private torch.jit.ScriptModule<Tensor, Tensor, (Tensor, Tensor)> m;\n}\n```\n\n## Compiling TorchScript from text\n\nBesides the ability to load TorchScript modules from files, TorchSharp also offers the ability to create them from Python source code directly using the `torch.jit.compile()` method. This results not in a ScriptModule, but a CompilationUnit, which can contain methods, classes, etc. \n\nRight now, TorchSharp only offers support for using methods compiled from source:\n\n```C#\nstring script = @\"\n def relu_script(a, b):\n return torch.relu(a + b)\n def add_i(x: Tensor, i: int) -> Tensor:\n return x + i\n\";\n\nusing var cu = torch.jit.compile(script);\n\nvar x = torch.randn(3, 4);\nvar y = torch.randn(3, 4);\n\nvar z = (Tensor)cu.invoke(\"relu_script\", x, y); // Return type is 'object'\nz = cu.invoke<Tensor>(\"add_i\", x, 1); // Type-safe return type.\n```\n" }, { "alpha_fraction": 0.5667069554328918, "alphanum_fraction": 0.5806126594543457, "avg_line_length": 43.702701568603516, "blob_id": "5de9405d5b0eed44bda48eef78b1bbc45385a791", "content_id": "57524da88b14e80e9703b708a438387be278e80f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4962, "license_type": "permissive", "max_line_length": 163, "num_lines": 111, "path": "/src/TorchVision/Ops/SqueezeExcitation.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchvision,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/vision/blob/a4f53308b2d0f1aa9191686e326f45c26053f686/torchvision/ops/misc.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/vision/blob/main/LICENSE\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class ops\n {\n /// <summary>\n /// This block implements the Squeeze-and-Excitation block from https://arxiv.org/abs/1709.01507\n /// Parameters ``activation``, and ``scale_activation`` correspond to ``delta`` and ``sigma`` in eq. 3.\n /// </summary>\n /// <param name=\"input_channels\">Number of channels in the input image</param>\n /// <param name=\"squeeze_channels\">Number of squeeze channels</param>\n /// <param name=\"activation\">`delta` activation.</param>\n /// <param name=\"scale_activation\">`sigma` activation</param>\n public static SqueezeExcitation SqueezeExcitation(\n long input_channels,\n long squeeze_channels,\n Func<nn.Module<Tensor, Tensor>>? activation = null,\n Func<nn.Module<Tensor, Tensor>>? scale_activation = null) => new SqueezeExcitation(input_channels, squeeze_channels, activation, scale_activation);\n }\n\n /// <summary>\n /// This block implements the Squeeze-and-Excitation block from https://arxiv.org/abs/1709.01507\n /// Parameters ``activation``, and ``scale_activation`` correspond to ``delta`` and ``sigma`` in eq. 3.\n /// </summary>\n public class SqueezeExcitation : torch.nn.Module<Tensor, Tensor>\n {\n private readonly nn.Module<Tensor, Tensor> avgpool;\n private readonly nn.Module<Tensor, Tensor> fc1;\n private readonly nn.Module<Tensor, Tensor> fc2;\n private readonly nn.Module<Tensor, Tensor> activation;\n private readonly nn.Module<Tensor, Tensor> scale_activation;\n\n private long input_channels;\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"input_channels\">Number of channels in the input image</param>\n /// <param name=\"squeeze_channels\">Number of squeeze channels</param>\n /// <param name=\"activation\">``delta`` activation</param>\n /// <param name=\"scale_activation\">``sigma`` activation.</param>\n public SqueezeExcitation(\n long input_channels,\n long squeeze_channels,\n Func<nn.Module<Tensor, Tensor>>? activation = null,\n Func<nn.Module<Tensor, Tensor>>? scale_activation = null) : base(nameof(SqueezeExcitation))\n {\n this.input_channels = input_channels;\n\n this.avgpool = torch.nn.AdaptiveAvgPool2d(1);\n this.fc1 = torch.nn.Conv2d(input_channels, squeeze_channels, 1);\n this.fc2 = torch.nn.Conv2d(squeeze_channels, input_channels, 1);\n this.activation = activation is null ? nn.ReLU() : activation();\n this.scale_activation = scale_activation is null ? nn.Sigmoid() : scale_activation();\n\n RegisterComponents();\n }\n\n private Tensor _scale(Tensor input)\n {\n var scale = this.avgpool.call(input);\n scale = this.fc1.call(scale);\n scale = this.activation.call(scale);\n scale = this.fc2.call(scale);\n return this.scale_activation.call(scale);\n }\n\n public override Tensor forward(Tensor input)\n {\n if ((input.ndim == 4 && input.shape[1] == input_channels) ||\n (input.ndim == 3 && input.shape[0] == input_channels)) {\n using var _ = NewDisposeScope();\n var scale = this._scale(input);\n return (scale * input).MoveToOuterDisposeScope();\n }\n throw new ArgumentException(\"Expected 3D (unbatched) or 4D (batched) input to SqueezeExcitation\");\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n avgpool.Dispose();\n fc1.Dispose();\n fc2.Dispose();\n activation.Dispose();\n scale_activation.Dispose();\n }\n base.Dispose(disposing);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5585940480232239, "alphanum_fraction": 0.5642493963241577, "avg_line_length": 48.889286041259766, "blob_id": "e5c4914f0bb26e0303e461ff7c2cb091ed78b6c2", "content_id": "f5e50f15ff6020d805fa60d4cf0a85deab505cda", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 13969, "license_type": "permissive", "max_line_length": 200, "num_lines": 280, "path": "/src/TorchSharp/Distributions/MultiVariateNormal.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using System.Numerics;\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// A multivariate normal (also called Gaussian) distribution parameterized by a mean vector and a covariance matrix.\n ///\n /// The multivariate normal distribution can be parameterized either in terms of a positive definite covariance matrix\n /// or a positive definite precision matrix or a lower-triangular matrix with positive-valued diagonal entries. This triangular matrix\n /// can be obtained via Cholesky decomposition of the covariance.\n /// </summary>\n public class MultivariateNormal : torch.distributions.Distribution\n {\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public override Tensor mean => loc;\n\n /// <summary>\n /// The mode of the distribution.\n /// </summary>\n public override Tensor mode => loc;\n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public override Tensor variance =>\n WrappedTensorDisposeScope(() => _unbroadcasted_scale_tril.pow(2).sum(-1).expand(batch_shape + event_shape));\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"loc\"></param>\n /// <param name=\"covariance_matrix\">Positive-definite covariance matrix</param>\n /// <param name=\"precision_matrix\">Positive-definite precision matrix</param>\n /// <param name=\"scale_tril\">The lower-triangular factor of covariance, with positive-valued diagonal</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <remarks>\n /// Only one of `covariance_matrix` or `precision_matrix` or `scale_tril` may be specified.\n ///\n /// Using `scale_tril` will be more efficient: all computations internally are based on `scale_tril`.\n /// If `covariance_matrix` or `precision_matrix` is passed instead, it is only used to compute\n /// the corresponding lower triangular matrices using a Cholesky decomposition.\n /// </remarks>\n public MultivariateNormal(Tensor loc, Tensor covariance_matrix = null, Tensor precision_matrix = null, Tensor scale_tril = null, torch.Generator generator = null) : base(generator)\n {\n var argCount = 0;\n argCount += (covariance_matrix is null ? 0 : 1);\n argCount += (precision_matrix is null ? 0 : 1);\n argCount += (scale_tril is null ? 0 : 1);\n\n if (argCount != 1)\n throw new ArgumentException(\"Exactly one of covariance_matrix or precision_matrix or scale_tril may be specified.\");\n\n using var _ = NewDisposeScope();\n\n if (scale_tril is not null) {\n if (scale_tril.dim() < 2) {\n throw new ArgumentException(\"scale_tril matrix must be at least two-dimensional, with optional leading batch dimensions\");\n }\n batch_shape = torch.broadcast_shapes(TakeAllBut(scale_tril.shape, 2), TakeAllBut(loc.shape, 1));\n this.scale_tril = scale_tril.expand(batch_shape + (-1, -1)).DetachFromDisposeScope();\n _unbroadcasted_scale_tril = scale_tril;\n } else if (covariance_matrix is not null) {\n if (covariance_matrix.dim() < 2) {\n throw new ArgumentException(\"covariance_matrix matrix must be at least two-dimensional, with optional leading batch dimensions\");\n }\n batch_shape = torch.broadcast_shapes(TakeAllBut(covariance_matrix.shape, 2).ToArray(), TakeAllBut(loc.shape, 1).ToArray());\n this.covariance_matrix = covariance_matrix.expand(batch_shape + (-1, -1)).DetachFromDisposeScope();\n _unbroadcasted_scale_tril = torch.linalg.cholesky(covariance_matrix).DetachFromDisposeScope();\n } else {\n if (precision_matrix.dim() < 2) {\n throw new ArgumentException(\"precision_matrix matrix must be at least two-dimensional, with optional leading batch dimensions\");\n }\n batch_shape = torch.broadcast_shapes(TakeAllBut(precision_matrix.shape, 2).ToArray(), TakeAllBut(loc.shape, 1).ToArray());\n this.precision_matrix = precision_matrix.expand(batch_shape + (-1, -1)).DetachFromDisposeScope();\n _unbroadcasted_scale_tril = PrecisionToScaleTril(precision_matrix).DetachFromDisposeScope();\n }\n\n this.loc = loc.expand(batch_shape + -1).DetachFromDisposeScope();\n\n this.event_shape = loc.shape[loc.shape.Length-1];\n }\n\n private MultivariateNormal(torch.Generator generator = null) : base(generator) { }\n\n private Tensor loc;\n private Tensor scale_tril;\n private Tensor precision_matrix;\n private Tensor covariance_matrix;\n\n private Tensor _unbroadcasted_scale_tril;\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n public override Tensor rsample(params long[] sample_shape)\n {\n using var _ = NewDisposeScope();\n\n var shape = ExtendedShape(sample_shape);\n var eps = torch.empty(shape, dtype: loc.dtype, device: loc.device).normal_(generator:generator);\n return (loc + BatchMV(_unbroadcasted_scale_tril, eps)).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor log_prob(Tensor value)\n {\n using var _ = NewDisposeScope();\n\n var diff = value - loc;\n var M = BatchMahalanobis(_unbroadcasted_scale_tril, diff);\n var half_log_det = _unbroadcasted_scale_tril.diagonal(dim1: -2, dim2: -1).log().sum(-1);\n return (-0.5 * (event_shape[0] * Math.Log(2 * Math.PI) + M) - half_log_det).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is MultivariateNormal))\n throw new ArgumentException(\"expand(): 'instance' must be a MultivariateNormal distribution\");\n\n var newDistribution = ((instance == null) ? new MultivariateNormal(generator) : instance) as MultivariateNormal;\n\n var loc_shape = batch_shape + event_shape;\n var cov_shape = batch_shape + event_shape + event_shape;\n\n newDistribution.loc = loc.expand(loc_shape);\n newDistribution._unbroadcasted_scale_tril = _unbroadcasted_scale_tril;\n newDistribution.scale_tril = scale_tril?.expand(cov_shape);\n newDistribution.covariance_matrix = covariance_matrix?.expand(cov_shape).DetachFromDisposeScope();\n newDistribution.precision_matrix = precision_matrix?.expand(cov_shape).DetachFromDisposeScope();\n\n newDistribution.batch_shape = batch_shape;\n newDistribution.event_shape = event_shape;\n\n return newDistribution;\n }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n /// <returns></returns>\n public override Tensor entropy()\n {\n using var _ = NewDisposeScope();\n\n var half_log_det = _unbroadcasted_scale_tril.diagonal(dim1: -2, dim2: -1).log().sum(-1);\n var H = 0.5 * event_shape[0] * (1 + Math.Log(2 * Math.PI)) + half_log_det;\n\n return ((batch_shape.Length == 0) ? H : H.expand(batch_shape)).MoveToOuterDisposeScope();\n }\n\n private Tensor BatchMV(Tensor bmat, Tensor bvec)\n {\n using var _ = NewDisposeScope();\n return torch.matmul(bmat, bvec.unsqueeze(-1)).squeeze(-1).MoveToOuterDisposeScope();\n }\n\n private IEnumerable<long> Range(long start, long end, long step = 1)\n {\n var result = new List<long>();\n for (long i = start; i < end; i += step) {\n result.Add(i);\n }\n return result;\n }\n\n private long[] TakeAllBut(long[] input, int count)\n {\n var result = new long[input.Length - count];\n for (int i = 0; i < result.Length; i++)\n result[i] = input[i];\n return result;\n }\n\n private Tensor BatchMahalanobis(Tensor bL, Tensor bx)\n {\n using var _ = NewDisposeScope();\n\n var n = bx.size(-1);\n var bx_batch_shape = TakeAllBut(bx.shape, 1);\n\n var bx_batch_dims = bx_batch_shape.Length;\n var bL_batch_dims = bL.dim() - 2;\n int outer_batch_dims = bx_batch_dims - (int)bL_batch_dims;\n var old_batch_dims = outer_batch_dims + bL_batch_dims;\n var new_batch_dims = outer_batch_dims + 2 * bL_batch_dims;\n\n var bx_new_shape = TakeAllBut(bx.shape, outer_batch_dims).ToList();\n\n for (int i = 0; i < bL.ndim - 2; i++) {\n var sL = bL.shape[i];\n var sx = bx.shape[outer_batch_dims + i];\n bx_new_shape.Add(sx / sL);\n bx_new_shape.Add(sL);\n }\n bx_new_shape.Add(n);\n bx = bx.reshape(bx_new_shape.ToArray());\n\n List<long> permute_dims = new List<long>();\n permute_dims.AddRange(Range(0, outer_batch_dims));\n permute_dims.AddRange(Range(outer_batch_dims, new_batch_dims, 2));\n permute_dims.AddRange(Range(outer_batch_dims + 1, new_batch_dims, 2));\n permute_dims.Add(new_batch_dims);\n\n bx = bx.permute(permute_dims.ToArray());\n\n var flat_L = bL.reshape(-1, n, n);\n var flat_x = bx.reshape(-1, flat_L.size(0), n);\n var flat_x_swap = flat_x.permute(1, 2, 0);\n\n var M_swap = torch.linalg.solve_triangular(flat_L, flat_x_swap, upper: false).pow(2).sum(-2);\n var M = M_swap.t();\n\n var permuted_M = M.reshape(TakeAllBut(bx.shape, 1));\n var permuted_inv_dims = Range(0, outer_batch_dims).ToList();\n for (int i = 0; i < bL_batch_dims; i++) {\n permuted_inv_dims.Add(outer_batch_dims + i);\n permuted_inv_dims.Add(old_batch_dims + i);\n }\n\n var reshaped_M = permuted_M.permute(permuted_inv_dims);\n\n return reshaped_M.reshape(bx_batch_shape).MoveToOuterDisposeScope();\n }\n\n private Tensor PrecisionToScaleTril(Tensor P)\n {\n using var _ = NewDisposeScope();\n var Lf = torch.linalg.cholesky(torch.flip(P, -2, -1));\n var L_inv = torch.transpose(torch.flip(Lf, -2, -1), -2, -1);\n var Id = torch.eye(P.shape[P.shape.Length - 1], dtype: P.dtype, device: P.device);\n var L = torch.linalg.solve_triangular(L_inv, Id, upper: false);\n return L.MoveToOuterDisposeScope();\n }\n }\n\n }\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a MultivariateNormal distribution parameterized by `probs` or `logits` (but not both).\n /// `total_count` must be broadcastable with `probs`/`logits`.\n /// </summary>\n /// <param name=\"loc\"></param>\n /// <param name=\"covariance_matrix\"></param>\n /// <param name=\"precision_matrix\"></param>\n /// <param name=\"scale_tril\"></param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static MultivariateNormal MultivariateNormal(Tensor loc, Tensor covariance_matrix = null, Tensor precision_matrix = null, Tensor scale_tril = null, torch.Generator generator = null)\n {\n return new MultivariateNormal(loc, covariance_matrix, precision_matrix, scale_tril, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5440872311592102, "alphanum_fraction": 0.5500094294548035, "avg_line_length": 60.491329193115234, "blob_id": "53720992fcb8093412dc8d366d603608250ddc7b", "content_id": "9536603d057629a83ddea7d3f52cc6a7d0e0da9d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 10638, "license_type": "permissive", "max_line_length": 306, "num_lines": 173, "path": "/src/TorchSharp/NN/Pooling/MaxPool3D.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Linq;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a MaxPool3D module.\n /// </summary>\n public sealed class MaxPool3d : torch.nn.Module<Tensor, Tensor>\n {\n internal MaxPool3d(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_MaxPool3d_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public (Tensor Values, Tensor Indices) forward_with_indices(Tensor tensor)\n {\n var res = THSNN_MaxPool3d_forward_with_indices(handle, tensor.Handle, out var indices);\n if (res == IntPtr.Zero || indices == IntPtr.Zero) { torch.CheckForErrors(); }\n return (new Tensor(res), new Tensor(indices));\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies a 3D max pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"kernelSize\">The size of the sliding window, must be > 0.</param>\n /// <param name=\"stride\">The stride of the sliding window, must be > 0. Default value is kernel_size.</param>\n /// <param name=\"padding\">Implicit negative infinity padding to be added on both sides, must be >= 0 and less than or equal to kernel_size / 2</param>\n /// <param name=\"dilation\">The stride between elements within a sliding window, must be > 0.</param>\n /// <param name=\"ceilMode\">If true, will use ceil instead of floor to compute the output shape. This ensures that every element in the input tensor is covered by a sliding window.</param>\n /// <returns></returns>\n public static MaxPool3d MaxPool3d(long kernelSize, long? stride = null, long? padding = null, long? dilation = null, bool ceilMode = false)\n {\n var pStride = stride.HasValue ? new long[] { stride.Value, stride.Value, stride.Value } : null;\n var pPadding = padding.HasValue ? new long[] { padding.Value, padding.Value, padding.Value } : null;\n var pDilation = dilation.HasValue ? new long[] { dilation.Value, dilation.Value, dilation.Value } : null;\n return MaxPool3d(new long[] { kernelSize, kernelSize, kernelSize }, pStride, pPadding, pDilation, ceilMode);\n }\n\n /// <summary>\n /// Applies a 3D max pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"kernelSize\">The size of the sliding window, must be > 0.</param>\n /// <param name=\"stride\">The stride of the sliding window, must be > 0. Default value is kernel_size.</param>\n /// <param name=\"padding\">Implicit negative infinity padding to be added on both sides, must be >= 0 and less than or equal to kernel_size / 2</param>\n /// <param name=\"dilation\">The stride between elements within a sliding window, must be > 0.</param>\n /// <param name=\"ceilMode\">If true, will use ceil instead of floor to compute the output shape. This ensures that every element in the input tensor is covered by a sliding window.</param>\n /// <returns></returns>\n public static MaxPool3d MaxPool3d((long, long, long) kernelSize, (long, long, long)? stride = null, (long, long, long)? padding = null, (long, long, long)? dilation = null, bool ceilMode = false)\n {\n var pStride = stride.HasValue ? new long[] { stride.Value.Item1, stride.Value.Item2, stride.Value.Item3 } : null;\n var pPadding = padding.HasValue ? new long[] { padding.Value.Item1, padding.Value.Item2, padding.Value.Item3 } : null;\n var pDilation = dilation.HasValue ? new long[] { dilation.Value.Item1, dilation.Value.Item2, dilation.Value.Item3 } : null;\n return MaxPool3d(new long[] { kernelSize.Item1, kernelSize.Item2, kernelSize.Item3 }, pStride, pPadding, pDilation, ceilMode);\n }\n\n /// <summary>\n /// Applies a 3D max pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"kernelSize\">The size of the sliding window, must be > 0.</param>\n /// <param name=\"strides\">The stride of the sliding window, must be > 0. Default value is kernel_size.</param>\n /// <param name=\"padding\">Implicit negative infinity padding to be added on both sides, must be >= 0 and less than or equal to kernel_size / 2</param>\n /// <param name=\"dilation\">The stride between elements within a sliding window, must be > 0.</param>\n /// <param name=\"ceilMode\">If true, will use ceil instead of floor to compute the output shape. This ensures that every element in the input tensor is covered by a sliding window.</param>\n /// <returns></returns>\n public static MaxPool3d MaxPool3d(long[] kernelSize, long[] strides = null, long[] padding = null, long[] dilation = null, bool ceilMode = false)\n {\n unsafe {\n fixed (long* pkernelSize = kernelSize, pstrides = strides, pPadding = padding, pDilation = dilation) {\n var handle = THSNN_MaxPool3d_ctor((IntPtr)pkernelSize, kernelSize.Length, (IntPtr)pstrides, (strides == null ? 0 : strides.Length), (IntPtr)pPadding, (padding == null ? 0 : padding.Length), (IntPtr)pDilation, (dilation == null ? 0 : dilation.Length), ceilMode, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new MaxPool3d(handle, boxedHandle);\n }\n }\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Applies a 3D max pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"kernelSize\"></param>\n /// <param name=\"strides\"></param>\n /// <param name=\"padding\"></param>\n /// <param name=\"dilation\"></param>\n /// <param name=\"ceil_mode\"></param>\n /// <returns></returns>\n public static Tensor max_pool3d(Tensor input, long[] kernelSize, long[] strides = null,\n long[] padding = null, long[] dilation = null, bool ceil_mode = false)\n {\n strides = strides ?? kernelSize.Select(x => 1L).ToArray();\n padding = padding ?? kernelSize.Select(x => 0L).ToArray();\n dilation = dilation ?? kernelSize.Select(x => 1L).ToArray();\n unsafe {\n fixed (long* pkernelSize = kernelSize, pstrides = strides, ppadding = padding, pdilation = dilation) {\n var res =\n THSTensor_max_pool3d(input.Handle,\n (IntPtr)pkernelSize, kernelSize.Length,\n (IntPtr)pstrides, strides.Length,\n (IntPtr)ppadding, padding.Length,\n (IntPtr)pdilation, dilation.Length,\n ceil_mode);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Applies a 3D max pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"kernelSize\"></param>\n /// <param name=\"strides\"></param>\n /// <param name=\"padding\"></param>\n /// <param name=\"dilation\"></param>\n /// <param name=\"ceil_mode\"></param>\n /// <returns></returns>\n public static (Tensor output, Tensor indices) max_pool3d_with_indices(Tensor input, long[] kernelSize, long[] strides = null,\n long[] padding = null, long[] dilation = null, bool ceil_mode = false)\n {\n strides = strides ?? kernelSize.Select(x => 1L).ToArray();\n padding = padding ?? kernelSize.Select(x => 0L).ToArray();\n dilation = dilation ?? kernelSize.Select(x => 1L).ToArray();\n IntPtr[] ptrArray;\n\n using (var pa = new PinnedArray<IntPtr>()) {\n unsafe {\n fixed (long* pkernelSize = kernelSize, pstrides = strides, ppadding = padding, pdilation = dilation) {\n THSTensor_max_pool3d_with_indices(input.Handle,\n pa.CreateArray,\n (IntPtr)pkernelSize, kernelSize.Length,\n (IntPtr)pstrides, strides.Length,\n (IntPtr)ppadding, padding.Length,\n (IntPtr)pdilation, dilation.Length,\n ceil_mode);\n torch.CheckForErrors();\n }\n }\n ptrArray = pa.Array;\n }\n return (new Tensor(ptrArray[0]), new Tensor(ptrArray[1]));\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5308775901794434, "alphanum_fraction": 0.5373781323432922, "avg_line_length": 33.8301887512207, "blob_id": "4db15dc01e676a64ce9aaf92ee908990b730c2b0", "content_id": "89cd0b5ae63ef42ef217d2a0532ebe9f52cd96df", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1846, "license_type": "permissive", "max_line_length": 130, "num_lines": 53, "path": "/src/TorchVision/AdjustGamma.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class AdjustGamma : ITransform\n {\n internal AdjustGamma(double gamma, double gain = 1.0)\n {\n if (gamma < 0.0)\n throw new ArgumentException($\"The saturation factor ({gamma}) must be non-negative.\");\n this.gamma = gamma;\n this.gain = gain;\n }\n\n public Tensor call(Tensor img)\n {\n var dtype = img.dtype;\n if (!torch.is_floating_point(img))\n img = transforms.ConvertImageDtype(torch.float32).call(img);\n\n img = (gain * img.pow(gamma)).clamp(0, 1);\n\n return transforms.ConvertImageDtype(dtype).call(img); ;\n }\n\n private double gamma;\n private double gain;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Perform gamma correction on an image.\n ///\n /// See: https://en.wikipedia.org/wiki/Gamma_correction\n /// </summary>\n /// <param name=\"gamma\">\n /// Non negative real number.\n /// gamma larger than 1 make the shadows darker, while gamma smaller than 1 make dark regions lighter.\n /// </param>\n /// <param name=\"gain\">The constant multiplier in the gamma correction equation.</param>\n /// <returns></returns>\n static public ITransform AdjustGamma(double gamma, double gain = 1.0)\n {\n return new AdjustGamma(gamma);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.580381453037262, "alphanum_fraction": 0.5953678488731384, "avg_line_length": 29.625, "blob_id": "608516b7c52ad86a70df5288f81f0524677cd051", "content_id": "7fa461630b74088004d0f3bbabb95c874d13ee92", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 734, "license_type": "permissive", "max_line_length": 92, "num_lines": 24, "path": "/test/TorchSharpTest/bug510.py", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "import torch\nimport src.Python.exportsd as exportsd\n\nclass BasicConv1d(torch.nn.Module):\n def __init__(self, in_channels, out_channels, **kwargs):\n super().__init__()\n \n self.stack = torch.nn.Sequential(\n torch.nn.Conv1d(in_channels, out_channels, kernel_size=3, bias=False, **kwargs),\n torch.nn.BatchNorm1d(out_channels),\n torch.nn.ReLU(inplace=True)\n )\n \n def forward(self, x):\n return self.stack(x)\n\nif __name__ == '__main__':\n # Create model\n model = BasicConv1d(1, 32)\n \n #Export model to .dat file for ingestion into TorchSharp\n f = open(\"bug510.dat\", \"wb\")\n exportsd.save_state_dict(model.to(\"cpu\").state_dict(), f)\n f.close()" }, { "alpha_fraction": 0.44665011763572693, "alphanum_fraction": 0.44665011763572693, "avg_line_length": 28.512195587158203, "blob_id": "e3a9f6c8e6e1a651fbdac3d68b6919beb5581516", "content_id": "a09356d4a6b9af6a4b6731b665d0f9f32fd346a1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1209, "license_type": "permissive", "max_line_length": 130, "num_lines": 41, "path": "/src/TorchAudio/Datasets/SpeechCommandsDatasetItem.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n public static partial class datasets\n {\n /// <summary>\n /// An item in SPEECHCOMMANDS dataset.\n /// </summary>\n public class SpeechCommandsDatasetItem\n {\n /// <summary>\n /// Samples of the audio clip\n /// </summary>\n public torch.Tensor waveform;\n\n /// <summary>\n /// Sampling rate of the audio clip\n /// </summary>\n public int sample_rate;\n\n /// <summary>\n /// Labels of the audio clip, 'bird', 'yes', ...\n /// </summary>\n public string label;\n\n /// <summary>\n /// Speaker ID\n /// </summary>\n public string speaker_id;\n\n /// <summary>\n /// Utterance number\n /// </summary>\n public int utterance_number;\n }\n }\n }\n}" }, { "alpha_fraction": 0.5736129283905029, "alphanum_fraction": 0.6063783168792725, "avg_line_length": 27.612499237060547, "blob_id": "34a02e4e1e1660cbb2b0e026c56ea2b3043be64f", "content_id": "ddd5432443e86bd624c76149ec46132af1999499", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2289, "license_type": "permissive", "max_line_length": 129, "num_lines": 80, "path": "/src/Python/importsd.py", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#\nimport torch\nimport leb128\nimport numpy as np\nfrom collections import OrderedDict\n\n\n_DTYPE_SIZE_MAP = {\n np.uint8: 1,\n np.int8: 1,\n np.int16: 2,\n np.int32: 4,\n np.int64: 8,\n np.float16: 2,\n np.float32: 4,\n np.float64: 8,\n}\n\n\ndef _get_elem_type(type_num: int):\n if type_num == 0:\n return np.uint8\n elif type_num == 1:\n return np.int8\n elif type_num == 2:\n return np.int16\n elif type_num == 3:\n return np.int32\n elif type_num == 4:\n return np.int64\n elif type_num == 5:\n return np.float16\n elif type_num == 6:\n return np.float32\n elif type_num == 7:\n return np.float64\n elif type_num == 11:\n # return torch.bool\n raise NotImplemented(\"Unsupported data type\")\n elif type_num == 15:\n # return torch.bfloat16\n raise NotImplemented(\"Unsupported data type\")\n elif type_num == 4711:\n raise NotImplemented(\"Unsupported data type\")\n else:\n raise ValueError(\"cannot decode the data type\")\n\n\ndef load_state_dict(stream):\n \"\"\"\n Loads a PyTorch state dictionary using the format that saved by TorchSharp.\n\n :param stream: An write stream opened for binary I/O.\n :return sd: A dictionary can be loaded by 'model.load_state_dict()'\n \"\"\"\n sd = OrderedDict()\n dict_len, _ = leb128.u.decode_reader(stream)\n for i in range(dict_len):\n key_len, _ = leb128.u.decode_reader(stream)\n key_name = stream.read(key_len).decode(\"utf-8\")\n\n ele_type, _ = leb128.u.decode_reader(stream)\n buffer_dtype = _get_elem_type(ele_type)\n\n buffer_shape_len, _ = leb128.u.decode_reader(stream)\n buffer_shape = tuple(leb128.u.decode_reader(stream)[0] for _ in range(buffer_shape_len))\n if buffer_shape:\n data_size = np.prod(buffer_shape)\n else:\n data_size = 1\n\n data_size_bytes = data_size * _DTYPE_SIZE_MAP[buffer_dtype]\n sd[key_name] = torch.from_numpy(\n np.frombuffer(\n stream.read(data_size_bytes), dtype=buffer_dtype, count=data_size\n ).reshape(buffer_shape)\n )\n return sd\n" }, { "alpha_fraction": 0.3953971564769745, "alphanum_fraction": 0.41745245456695557, "avg_line_length": 49.055999755859375, "blob_id": "4694733fc0957452a403e0919fee2d2ebba91426", "content_id": "edfccd899c6ed72317f94aa63570c01c0a664d63", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6257, "license_type": "permissive", "max_line_length": 218, "num_lines": 125, "path": "/src/TorchSharp/Utils/tensorboard/Utils.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System;\nusing System.Diagnostics;\nusing System.Linq;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class utils\n {\n public static partial class tensorboard\n {\n internal static partial class utils\n {\n /// <summary>\n /// Converts a 5D tensor [batchsize, time(frame), channel(color), height, width]\n /// into 4D tensor with dimension[time(frame), new_width, new_height, channel].\n /// A batch of images are spreaded to a grid, which forms a frame.\n /// e.g. Video with batchsize 16 will have a 4x4 grid.\n ///\n /// https://github.com/pytorch/pytorch/blob/master/torch/utils/tensorboard/_utils.py#L110\n /// </summary>\n /// <param name=\"V\"></param>\n /// <returns></returns>\n public static Tensor prepare_video(Tensor V)\n {\n long b = V.shape[0];\n long t = V.shape[1];\n long c = V.shape[2];\n long h = V.shape[3];\n long w = V.shape[4];\n\n if (V.dtype == ScalarType.Int8 || V.dtype == ScalarType.Byte)\n V = V.to_type(ScalarType.Float32) / 255.0;\n\n bool is_power2(long num)\n => num != 0 && ((num & (num - 1)) == 0);\n int bit_length(long value)\n => Convert.ToString(value, 2).Length;\n\n if (!is_power2(V.shape[0])) {\n int len_addition = Convert.ToInt32(Math.Pow(2, bit_length(V.shape[0])) - V.shape[0]);\n V = cat(new Tensor[] { V, zeros(new long[] { len_addition, t, c, h, w }, device: V.device) });\n }\n\n long n_rows = Convert.ToInt32(Math.Pow(2, (bit_length(V.shape[0]) - 1) / 2));\n long n_cols = V.shape[0] / n_rows;\n\n V = V.reshape(n_rows, n_cols, t, c, h, w);\n V = V.permute(2, 0, 4, 1, 5, 3);\n V = V.reshape(t, n_rows * h, n_cols * w, c);\n return V;\n }\n\n /// <summary>\n /// https://github.com/pytorch/pytorch/blob/6c30dc6ceed5542351b3be4f8043b28020f93f3a/torch/utils/tensorboard/_utils.py#L69\n /// </summary>\n /// <param name=\"I\"></param>\n /// <param name=\"ncols\"></param>\n /// <returns></returns>\n public static Tensor make_grid(Tensor I, long ncols = 8)\n {\n if (I.shape[1] == 1)\n I = I.expand(-1, 3);\n Trace.Assert(I.ndim == 4 && I.shape[1] == 3);\n long nimg = I.shape[0];\n long H = I.shape[2];\n long W = I.shape[3];\n ncols = Math.Min(ncols, nimg);\n long nrows = (long)Math.Ceiling((double)nimg / (double)ncols);\n Tensor canvas = zeros(new long[] { 3, H * nrows, W * ncols }, I.dtype);\n long i = 0;\n for (long r = 0; r < nrows; r++) {\n for (long c = 0; c < ncols; c++) {\n if (i >= nimg)\n break;\n canvas.narrow(1, r * H, H).narrow(2, c * W, W).copy_(I[i]);\n i++;\n }\n }\n return canvas;\n }\n\n /// <summary>\n /// https://github.com/pytorch/pytorch/blob/6c30dc6ceed5542351b3be4f8043b28020f93f3a/torch/utils/tensorboard/_utils.py#L95\n /// </summary>\n /// <param name=\"tensor\"> Image data </param>\n /// <param name=\"input_format\"> Image data format specification of the form NCHW, NHWC, CHW, HWC, HW, WH, etc. </param>\n /// <returns></returns>\n public static Tensor convert_to_HWC(Tensor tensor, string input_format)\n {\n Trace.Assert(tensor.shape.Length == input_format.Length, $\"size of input tensor and input format are different. tensor shape: ({string.Join(\", \", tensor.shape)}), input_format: {input_format}\");\n input_format = input_format.ToUpper();\n\n if (input_format.Length == 4) {\n long[] index = \"NCHW\".Select(c => Convert.ToInt64(input_format.IndexOf(c))).ToArray();\n Tensor tensor_NCHW = tensor.permute(index);\n Tensor tensor_CHW = make_grid(tensor_NCHW);\n return tensor_CHW.permute(1, 2, 0);\n }\n\n if (input_format.Length == 3) {\n long[] index = \"HWC\".Select(c => Convert.ToInt64(input_format.IndexOf(c))).ToArray();\n Tensor tensor_HWC = tensor.permute(index);\n if (tensor_HWC.shape[2] == 1)\n tensor_HWC = tensor_HWC.expand(-1, -1, 3);\n return tensor_HWC;\n }\n\n if (input_format.Length == 2) {\n long[] index = \"HW\".Select(c => Convert.ToInt64(input_format.IndexOf(c))).ToArray();\n tensor = tensor.permute(index);\n tensor = tensor.unsqueeze(-1).expand(-1, -1, 3);\n return tensor;\n }\n\n throw new NotImplementedException();\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6045751571655273, "alphanum_fraction": 0.6078431606292725, "avg_line_length": 20.85714340209961, "blob_id": "0123336db26ce17a05ed88e8a31040e8714237c9", "content_id": "292e094435f6d089b5204d844ebb4fdb7350fa89", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 306, "license_type": "permissive", "max_line_length": 130, "num_lines": 14, "path": "/src/TorchSharp/Tensor/Enums/HistogramBinSelector.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nnamespace TorchSharp\n{\n public enum HistogramBinSelector : byte\n {\n Doane = 0,\n Rice,\n Scott,\n Sqrt,\n Stone,\n Sturges\n }\n}\n" }, { "alpha_fraction": 0.6214463710784912, "alphanum_fraction": 0.6214463710784912, "avg_line_length": 40.79166793823242, "blob_id": "0762788f0bdbebeec9b9664996eb7f36d1ea24df", "content_id": "11598e5f7e2b77d8d49af18007d53285fa69c91a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2009, "license_type": "permissive", "max_line_length": 196, "num_lines": 48, "path": "/src/TorchVision/Perspective.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing static TorchSharp.torch;\n\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class Perspective : ITransform\n {\n internal Perspective(IList<IList<int>> startpoints, IList<IList<int>> endpoints, InterpolationMode interpolation, IList<float> fill = null)\n {\n if (interpolation != InterpolationMode.Nearest && interpolation != InterpolationMode.Bilinear)\n throw new ArgumentException($\"Invalid interpolation mode for 'Perspective': {interpolation}. Use 'nearest' or 'bilinear'.\");\n\n this.startpoints = startpoints;\n this.endpoints = endpoints;\n this.interpolation = interpolation;\n this.fill = fill;\n }\n\n public Tensor call(Tensor input)\n {\n return transforms.functional.perspective(input, startpoints, endpoints, interpolation, fill);\n }\n\n private IList<IList<int>> startpoints;\n private IList<IList<int>> endpoints;\n private InterpolationMode interpolation;\n private IList<float> fill;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Perform perspective transform of the given image.\n /// The image is expected to have […, H, W] shape, where … means an arbitrary number of leading dimensions.\n /// </summary>\n /// <returns></returns>\n static public ITransform Perspective(IList<IList<int>> startpoints, IList<IList<int>> endpoints, InterpolationMode interpolation = InterpolationMode.Bilinear, IList<float> fill = null)\n {\n return new Perspective(startpoints, endpoints, interpolation, fill);\n }\n }\n }\n}" }, { "alpha_fraction": 0.5039065480232239, "alphanum_fraction": 0.5209760665893555, "avg_line_length": 49.995094299316406, "blob_id": "2eac9d5f5a46248685f2e0372cdfd0e55079691d", "content_id": "77713e97cb7712d6292e39e6f2cf8a01f73fc83b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 51964, "license_type": "permissive", "max_line_length": 201, "num_lines": 1019, "path": "/src/TorchVision/models/ResNet.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Text.RegularExpressions;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class models\n {\n /// <summary>\n /// ResNet-18\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"zero_init_residual\">Whether to zero-initalize the residual block's norm layers.</param>\n /// <param name=\"groups\">The number of groups.</param>\n /// <param name=\"width_per_group\">The width of each group.</param>\n /// <param name=\"replace_stride_with_dilation\">Each element in the tuple indicates if we should replace the 2x2 stride with a dilated convolution instead</param>\n /// <param name=\"norm_layer\">The normalization layer to use -- a function creating a layer.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.resnet18(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.ResNet resnet18(\n int num_classes = 1000,\n bool zero_init_residual = false,\n int groups = 1,\n int width_per_group = 64,\n (bool, bool, bool)? replace_stride_with_dilation = null,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null)\n {\n return Modules.ResNet.ResNet18(num_classes,\n zero_init_residual,\n groups,\n width_per_group,\n replace_stride_with_dilation,\n norm_layer,\n weights_file, skipfc, device);\n }\n\n /// <summary>\n /// ResNet-34\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"zero_init_residual\">Whether to zero-initalize the residual block's norm layers.</param>\n /// <param name=\"groups\">The number of groups.</param>\n /// <param name=\"width_per_group\">The width of each group.</param>\n /// <param name=\"replace_stride_with_dilation\">Each element in the tuple indicates if we should replace the 2x2 stride with a dilated convolution instead</param>\n /// <param name=\"norm_layer\">The normalization layer to use -- a function creating a layer.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.resnet34(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.ResNet resnet34(\n int num_classes = 1000,\n bool zero_init_residual = false,\n int groups = 1,\n int width_per_group = 64,\n (bool, bool, bool)? replace_stride_with_dilation = null,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null)\n {\n return Modules.ResNet.ResNet34(num_classes,\n zero_init_residual,\n groups,\n width_per_group,\n replace_stride_with_dilation,\n norm_layer,\n weights_file, skipfc, device);\n }\n\n /// <summary>\n /// ResNet-50\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"zero_init_residual\">Whether to zero-initalize the residual block's norm layers.</param>\n /// <param name=\"groups\">The number of groups.</param>\n /// <param name=\"width_per_group\">The width of each group.</param>\n /// <param name=\"replace_stride_with_dilation\">Each element in the tuple indicates if we should replace the 2x2 stride with a dilated convolution instead</param>\n /// <param name=\"norm_layer\">The normalization layer to use -- a function creating a layer.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.resnet50(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.ResNet resnet50(\n int num_classes = 1000,\n bool zero_init_residual = false,\n int groups = 1,\n int width_per_group = 64,\n (bool, bool, bool)? replace_stride_with_dilation = null,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null)\n {\n return Modules.ResNet.ResNet50(num_classes,\n zero_init_residual,\n groups,\n width_per_group,\n replace_stride_with_dilation,\n norm_layer,\n weights_file, skipfc, device);\n }\n\n /// <summary>\n /// Wide ResNet-50-2 model from 'Wide Residual Networks' https://arxiv.org/abs/1605.07146_\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"zero_init_residual\">Whether to zero-initalize the residual block's norm layers.</param>\n /// <param name=\"groups\">The number of groups.</param>\n /// <param name=\"replace_stride_with_dilation\">Each element in the tuple indicates if we should replace the 2x2 stride with a dilated convolution instead</param>\n /// <param name=\"norm_layer\">The normalization layer to use -- a function creating a layer.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.wide_resnet50_2(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.ResNet wide_resnet50_2(\n int num_classes = 1000,\n bool zero_init_residual = false,\n int groups = 1,\n (bool, bool, bool)? replace_stride_with_dilation = null,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null)\n {\n return Modules.ResNet.ResNet50(num_classes,\n zero_init_residual,\n groups,\n 64 * 2,\n replace_stride_with_dilation,\n norm_layer,\n weights_file, skipfc, device);\n }\n\n /// <summary>\n /// ResNeXt-50 32x4d model from\n /// `Aggregated Residual Transformation for Deep Neural Networks https://arxiv.org/abs/1611.05431\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"zero_init_residual\">Whether to zero-initalize the residual block's norm layers.</param>\n /// <param name=\"replace_stride_with_dilation\">Each element in the tuple indicates if we should replace the 2x2 stride with a dilated convolution instead</param>\n /// <param name=\"norm_layer\">The normalization layer to use -- a function creating a layer.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.resnext50_32x4d(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.ResNet resnext50_32x4d(\n int num_classes = 1000,\n bool zero_init_residual = false,\n (bool, bool, bool)? replace_stride_with_dilation = null,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null)\n {\n return Modules.ResNet.ResNet50(num_classes,\n zero_init_residual,\n 32,\n 4,\n replace_stride_with_dilation,\n norm_layer,\n weights_file, skipfc, device);\n }\n\n /// <summary>\n /// ResNet-101\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"zero_init_residual\">Whether to zero-initalize the residual block's norm layers.</param>\n /// <param name=\"groups\">The number of groups.</param>\n /// <param name=\"width_per_group\">The width of each group.</param>\n /// <param name=\"replace_stride_with_dilation\">Each element in the tuple indicates if we should replace the 2x2 stride with a dilated convolution instead</param>\n /// <param name=\"norm_layer\">The normalization layer to use -- a function creating a layer.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.resnet101(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.ResNet resnet101(\n int num_classes = 1000,\n bool zero_init_residual = false,\n int groups = 1,\n int width_per_group = 64,\n (bool, bool, bool)? replace_stride_with_dilation = null,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null)\n {\n return Modules.ResNet.ResNet101(num_classes,\n zero_init_residual,\n groups,\n width_per_group,\n replace_stride_with_dilation,\n norm_layer,\n weights_file, skipfc, device);\n }\n\n /// <summary>\n /// ResNeXt-101 32x8d model from\n /// `Aggregated Residual Transformation for Deep Neural Networks https://arxiv.org/abs/1611.05431\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"zero_init_residual\">Whether to zero-initalize the residual block's norm layers.</param>\n /// <param name=\"replace_stride_with_dilation\">Each element in the tuple indicates if we should replace the 2x2 stride with a dilated convolution instead</param>\n /// <param name=\"norm_layer\">The normalization layer to use -- a function creating a layer.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.resnext101_32x8d(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.ResNet resnext101_32x8d(\n int num_classes = 1000,\n bool zero_init_residual = false,\n (bool, bool, bool)? replace_stride_with_dilation = null,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null)\n {\n return Modules.ResNet.ResNet50(num_classes,\n zero_init_residual,\n 32,\n 8,\n replace_stride_with_dilation,\n norm_layer,\n weights_file, skipfc, device);\n }\n\n /// <summary>\n /// ResNeXt-101 64x4d model from\n /// `Aggregated Residual Transformation for Deep Neural Networks https://arxiv.org/abs/1611.05431\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"zero_init_residual\">Whether to zero-initalize the residual block's norm layers.</param>\n /// <param name=\"replace_stride_with_dilation\">Each element in the tuple indicates if we should replace the 2x2 stride with a dilated convolution instead</param>\n /// <param name=\"norm_layer\">The normalization layer to use -- a function creating a layer.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.resnext101_32x8d(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.ResNet resnext101_64x4d(\n int num_classes = 1000,\n bool zero_init_residual = false,\n (bool, bool, bool)? replace_stride_with_dilation = null,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null)\n {\n return Modules.ResNet.ResNet50(num_classes,\n zero_init_residual,\n 64,\n 4,\n replace_stride_with_dilation,\n norm_layer,\n weights_file, skipfc, device);\n }\n\n /// <summary>\n /// Wide ResNet-101-2 model from 'Wide Residual Networks' https://arxiv.org/abs/1605.07146\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"zero_init_residual\">Whether to zero-initalize the residual block's norm layers.</param>\n /// <param name=\"groups\">The number of groups.</param>\n /// <param name=\"replace_stride_with_dilation\">Each element in the tuple indicates if we should replace the 2x2 stride with a dilated convolution instead</param>\n /// <param name=\"norm_layer\">The normalization layer to use -- a function creating a layer.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.resnet101(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.ResNet wide_resnet101_2(\n int num_classes = 1000,\n bool zero_init_residual = false,\n int groups = 1,\n (bool, bool, bool)? replace_stride_with_dilation = null,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null)\n {\n return Modules.ResNet.ResNet101(num_classes,\n zero_init_residual,\n groups,\n 64*2,\n replace_stride_with_dilation,\n norm_layer,\n weights_file, skipfc, device);\n }\n\n /// <summary>\n /// ResNet-152\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"zero_init_residual\">Whether to zero-initalize the residual block's norm layers.</param>\n /// <param name=\"groups\">The number of groups.</param>\n /// <param name=\"width_per_group\">The width of each group.</param>\n /// <param name=\"replace_stride_with_dilation\">Each element in the tuple indicates if we should replace the 2x2 stride with a dilated convolution instead</param>\n /// <param name=\"norm_layer\">The normalization layer to use -- a function creating a layer.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.resnet152(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.ResNet resnet152(\n int num_classes = 1000,\n bool zero_init_residual = false,\n int groups = 1,\n int width_per_group = 64,\n (bool, bool, bool)? replace_stride_with_dilation = null,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null)\n {\n return Modules.ResNet.ResNet152(num_classes,\n zero_init_residual,\n groups,\n width_per_group,\n replace_stride_with_dilation,\n norm_layer,\n weights_file, skipfc, device);\n }\n }\n }\n\n namespace Modules\n {\n public class ResNet : Module<Tensor, Tensor>\n {\n // The code here is based on\n // https://github.com/pytorch/vision/blob/main/torchvision/models/resnet.py\n // Licence and copypright notice at: https://github.com/pytorch/vision/blob/main/LICENSE\n\n private readonly Module<Tensor, Tensor> conv1;\n private readonly Module<Tensor, Tensor> bn1;\n private readonly Module<Tensor, Tensor> relu;\n private readonly Module<Tensor, Tensor> maxpool;\n\n private readonly Sequential layer1 = Sequential();\n private readonly Sequential layer2 = Sequential();\n private readonly Sequential layer3 = Sequential();\n private readonly Sequential layer4 = Sequential();\n\n private readonly Module<Tensor, Tensor> avgpool;\n private readonly Module<Tensor, Tensor> flatten;\n private readonly Module<Tensor, Tensor> fc;\n\n private readonly Func<int, Module<Tensor, Tensor>> norm_layer;\n\n private int in_planes = 64;\n private int dilation;\n private int groups;\n private int base_width;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n conv1.Dispose();\n bn1.Dispose();\n relu.Dispose();\n maxpool.Dispose();\n avgpool.Dispose();\n flatten.Dispose();\n fc.Dispose();\n layer1.Dispose(); layer2.Dispose();\n layer3.Dispose(); layer4.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public static ResNet ResNet18(\n int numClasses = 1000,\n bool zero_init_residual = false,\n int groups = 1,\n int width_per_group = 64,\n (bool, bool, bool)? replace_stride_with_dilation = null,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null)\n {\n return new ResNet(\n \"ResNet18\",\n (in_planes, planes, stride, downsample, groups, base_width, dilation, norm_layer) => new BasicBlock(in_planes, planes, stride, downsample, groups, base_width, dilation, norm_layer),\n BasicBlock.expansion, new int[] { 2, 2, 2, 2 },\n numClasses,\n zero_init_residual,\n groups,\n width_per_group,\n replace_stride_with_dilation,\n norm_layer,\n weights_file,\n skipfc,\n device);\n }\n\n public static ResNet ResNet34(\n int numClasses = 1000,\n bool zero_init_residual = false,\n int groups = 1,\n int width_per_group = 64,\n (bool, bool, bool)? replace_stride_with_dilation = null,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null)\n {\n return new ResNet(\n \"ResNet34\",\n (in_planes, planes, stride, downsample, groups, base_width, dilation, norm_layer) => new BasicBlock(in_planes, planes, stride, downsample, groups, base_width, dilation, norm_layer),\n BasicBlock.expansion, new int[] { 3, 4, 6, 3 },\n numClasses,\n zero_init_residual,\n groups,\n width_per_group,\n replace_stride_with_dilation,\n norm_layer,\n weights_file,\n skipfc,\n device);\n }\n\n public static ResNet ResNet50(\n int numClasses = 1000,\n bool zero_init_residual = false,\n int groups = 1,\n int width_per_group = 64,\n (bool, bool, bool)? replace_stride_with_dilation = null,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null)\n {\n return new ResNet(\n \"ResNet50\",\n (in_planes, planes, stride, downsample, groups, base_width, dilation, norm_layer) => new Bottleneck(in_planes, planes, stride, downsample, groups, base_width, dilation, norm_layer),\n Bottleneck.expansion, new int[] { 3, 4, 6, 3 },\n numClasses,\n zero_init_residual,\n groups,\n width_per_group,\n replace_stride_with_dilation,\n norm_layer,\n weights_file,\n skipfc,\n device);\n }\n\n public static ResNet ResNet101(\n int numClasses = 1000,\n bool zero_init_residual = false,\n int groups = 1,\n int width_per_group = 64,\n (bool, bool, bool)? replace_stride_with_dilation = null,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null)\n {\n return new ResNet(\n \"ResNet101\",\n (in_planes, planes, stride, downsample, groups, base_width, dilation, norm_layer) => new Bottleneck(in_planes, planes, stride, downsample, groups, base_width, dilation, norm_layer),\n Bottleneck.expansion, new int[] { 3, 4, 23, 3 },\n numClasses,\n zero_init_residual,\n groups,\n width_per_group,\n replace_stride_with_dilation,\n norm_layer,\n weights_file,\n skipfc,\n device);\n }\n\n public static ResNet ResNet152(\n int numClasses = 1000,\n bool zero_init_residual = false,\n int groups = 1,\n int width_per_group = 64,\n (bool, bool, bool)? replace_stride_with_dilation = null,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null)\n {\n return new ResNet(\n \"ResNet152\",\n (in_planes, planes, stride, downsample, groups, base_width, dilation, norm_layer) => new Bottleneck(in_planes, planes, stride, downsample, groups, base_width, dilation, norm_layer),\n Bottleneck.expansion, new int[] { 3, 8, 36, 3 },\n numClasses,\n zero_init_residual,\n groups,\n width_per_group,\n replace_stride_with_dilation,\n norm_layer,\n weights_file,\n skipfc,\n device);\n }\n\n public delegate Module<Tensor, Tensor> BlockFunc(\n int inplanes,\n int planes,\n int stride = 1,\n Module<Tensor, Tensor>? downsample = null,\n int groups = 1,\n int base_width = 64,\n int dilation = 1,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null);\n\n public ResNet(string name,\n BlockFunc block,\n int expansion,\n IList<int> layers,\n int numClasses = 1000,\n bool zero_init_residual = false,\n int groups = 1,\n int width_per_group = 64,\n (bool, bool, bool)? replace_stride_with_dilation = null,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null,\n string? weights_file = null,\n bool skipfc = true,\n Device? device = null) : base(name)\n {\n norm_layer = (norm_layer is not null) ? norm_layer : (planes) => BatchNorm2d(planes);\n this.norm_layer = norm_layer;\n\n this.in_planes = 64;\n this.dilation = 1;\n this.groups = groups;\n this.base_width = width_per_group;\n\n var rswd = replace_stride_with_dilation.HasValue ? replace_stride_with_dilation.Value : (false, false, false);\n\n conv1 = Conv2d(3, in_planes, kernelSize: 7, stride: 2, padding: 3, bias: false);\n bn1 = norm_layer(in_planes);\n relu = ReLU(inplace: true);\n maxpool = MaxPool2d(kernelSize: 3, stride: 2, padding: 1);\n\n MakeLayer(layer1, block, expansion, 64, layers[0], 1);\n MakeLayer(layer2, block, expansion, 128, layers[1], 2, rswd.Item1);\n MakeLayer(layer3, block, expansion, 256, layers[2], 2, rswd.Item2);\n MakeLayer(layer4, block, expansion, 512, layers[3], 2, rswd.Item3);\n\n avgpool = nn.AdaptiveAvgPool2d(new long[] { 1, 1 });\n flatten = Flatten();\n fc = Linear(512 * expansion, numClasses);\n\n RegisterComponents();\n\n if (string.IsNullOrEmpty(weights_file)) {\n\n foreach (var (_, m) in named_modules()) {\n switch (m) {\n case TorchSharp.Modules.Conv2d conv:\n torch.nn.init.kaiming_normal_(conv.weight, mode: init.FanInOut.FanOut, nonlinearity: init.NonlinearityType.ReLU);\n break;\n case TorchSharp.Modules.BatchNorm2d bn:\n torch.nn.init.constant_(bn.weight, 1);\n torch.nn.init.constant_(bn.bias, 0);\n break;\n case TorchSharp.Modules.GroupNorm gn:\n torch.nn.init.constant_(gn.weight, 1);\n torch.nn.init.constant_(gn.bias, 0);\n break;\n }\n }\n\n if (zero_init_residual) {\n foreach (var (_, m) in named_modules()) {\n\n switch (m) {\n case BasicBlock bb:\n if (bb.bn2 is TorchSharp.Modules.BatchNorm2d bb2d) {\n torch.nn.init.constant_(bb2d.weight, 0);\n }\n break;\n case Bottleneck bn:\n if (bn.bn3 is TorchSharp.Modules.BatchNorm2d bn2d) {\n torch.nn.init.constant_(bn2d.weight, 0);\n }\n break;\n }\n }\n\n }\n\n } else {\n\n this.load(weights_file, skip: skipfc ? new[] { \"fc.weight\", \"fc.bias\" } : null);\n }\n\n if (device != null && device.type == DeviceType.CUDA)\n this.to(device);\n }\n\n private void MakeLayer(Sequential modules, BlockFunc block, int expansion, int planes, int blocks, int stride, bool dilate = false)\n {\n Sequential? downsample = null;\n var previous_dilation = this.dilation;\n\n if (dilate) {\n this.dilation *= stride;\n stride = 1;\n }\n\n if (stride != 1 || in_planes != planes * expansion) {\n downsample = Sequential(\n Conv2d(in_planes, planes * expansion, kernelSize: 1, stride: stride, bias: false),\n norm_layer(planes * expansion)\n );\n }\n\n modules.append(block(in_planes, planes, stride, downsample, groups, base_width, previous_dilation, norm_layer));\n\n this.in_planes = planes * expansion;\n\n for (int i = 1; i < blocks; i++) {\n modules.append(block(in_planes, planes, 1, null, groups, base_width, dilation, norm_layer));\n }\n }\n\n public override Tensor forward(Tensor input)\n {\n using (var scope = NewDisposeScope()) {\n\n var x = maxpool.call(relu.call(bn1.call(conv1.call(input))));\n\n x = layer1.call(x);\n x = layer2.call(x);\n x = layer3.call(x);\n x = layer4.call(x);\n\n var res = fc.call(flatten.call(avgpool.call(x)));\n scope.MoveToOuter(res);\n return res;\n }\n }\n\n class BasicBlock : Module<Tensor, Tensor>\n {\n public BasicBlock(\n int in_planes,\n int planes,\n int stride,\n Module<Tensor, Tensor>? downsample = null,\n int groups = 1,\n int base_width = 64,\n int dilation = 1,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null) : base(\"BasicBlock\")\n {\n if (groups != 1 || base_width != 64) throw new ArgumentException(\"BasicBlock only supports groups=1 and base_width=64\");\n if (dilation > 1) throw new NotImplementedException(\"dilation > 1 not supported in BasicBlock\");\n\n if (norm_layer is null) {\n norm_layer = (planes) => BatchNorm2d(planes);\n }\n\n conv1 = Conv2d(in_planes, planes, kernelSize: 3, stride: stride, padding: 1, bias: false);\n bn1 = norm_layer(planes);\n relu1 = ReLU(inplace: true);\n conv2 = Conv2d(planes, planes, kernelSize: 3, stride: 1, padding: 1, bias: false);\n bn2 = norm_layer(planes);\n this.downsample = downsample;\n\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor input)\n {\n var identity = input;\n\n var x = relu1.call(bn1.call(conv1.call(input)));\n x = bn2.call(conv2.call(x));\n\n if (downsample is not null) {\n identity = downsample.call(input);\n }\n\n return x.add_(identity).relu_();\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n conv1.Dispose();\n bn1.Dispose();\n conv2.Dispose();\n bn2.Dispose();\n relu1.Dispose();\n downsample?.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public static int expansion = 1;\n\n private readonly Module<Tensor, Tensor> conv1;\n private readonly Module<Tensor, Tensor> bn1;\n private readonly Module<Tensor, Tensor> conv2;\n internal readonly Module<Tensor, Tensor> bn2;\n private readonly Module<Tensor, Tensor> relu1;\n private readonly Module<Tensor, Tensor>? downsample;\n }\n\n class Bottleneck : Module<Tensor, Tensor>\n {\n public Bottleneck(\n int in_planes,\n int planes,\n int stride,\n Module<Tensor, Tensor>? downsample = null,\n int groups = 1,\n int base_width = 64,\n int dilation = 1,\n Func<int, Module<Tensor, Tensor>>? norm_layer = null) : base(\"Bottleneck\")\n {\n if (norm_layer is null) {\n norm_layer = (planes) => BatchNorm2d(planes);\n }\n\n var width = (int)(planes * (base_width / 64.0)) * groups;\n\n conv1 = Conv2d(in_planes, width, kernelSize: 1, bias: false);\n bn1 = norm_layer(width);\n relu1 = ReLU(inplace: true);\n conv2 = Conv2d(width, width, kernelSize: 3, stride: stride, groups: groups, padding: dilation, dilation: dilation, bias: false);\n bn2 = norm_layer(width);\n relu2 = ReLU(inplace: true);\n conv3 = Conv2d(width, expansion * planes, kernelSize: 1, bias: false);\n bn3 = norm_layer(expansion * planes);\n\n this.downsample = downsample;\n\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor input)\n {\n var identity = input;\n\n var x = relu1.call(bn1.call(conv1.call(input)));\n x = relu2.call(bn2.call(conv2.call(x)));\n x = bn3.call(conv3.call(x));\n\n if (downsample is not null) {\n identity = downsample.call(input);\n }\n\n return x.add_(identity).relu_();\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n conv1.Dispose();\n bn1.Dispose();\n conv2.Dispose(); conv3.Dispose();\n bn2.Dispose(); bn3.Dispose();\n relu1.Dispose(); relu2.Dispose();\n downsample?.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public static int expansion = 4;\n\n private readonly Module<Tensor, Tensor> conv1;\n private readonly Module<Tensor, Tensor> bn1;\n private readonly Module<Tensor, Tensor> conv2;\n private readonly Module<Tensor, Tensor> bn2;\n private readonly Module<Tensor, Tensor> conv3;\n internal readonly Module<Tensor, Tensor> bn3;\n private readonly Module<Tensor, Tensor> relu1;\n private readonly Module<Tensor, Tensor> relu2;\n\n private readonly Module<Tensor, Tensor>? downsample;\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5336246490478516, "alphanum_fraction": 0.5448733568191528, "avg_line_length": 38.47923278808594, "blob_id": "09dd025be8f42bfcd6fbf9b07ec06d78f9dd6fc7", "content_id": "1988b7d792a81e64ac14dddb1f689eedd5522658", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 12357, "license_type": "permissive", "max_line_length": 183, "num_lines": 313, "path": "/src/Examples/SequenceToSequence.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\n\nnamespace TorchSharp.Examples\n{\n\n /// <summary>\n /// This example is based on the PyTorch tutorial at:\n ///\n /// https://pytorch.org/tutorials/beginner/transformer_tutorial.html\n ///\n /// It relies on the WikiText2 dataset, which can be downloaded at:\n ///\n /// https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-v1.zip\n ///\n /// After downloading, extract the files using the defaults (Windows only).\n /// </summary>\n public class SequenceToSequence\n {\n // This path assumes that you're running this on Windows.\n#if NET472_OR_GREATER\n private readonly static string _dataLocation = NSPath.Join(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), \"..\", \"Downloads\", \"wikitext-2-v1\");\n#else\n private readonly static string _dataLocation = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), \"..\", \"Downloads\", \"wikitext-2-v1\");\n#endif // NET472_OR_GREATER\n\n private const long emsize = 200;\n private const long nhid = 200;\n private const long nlayers = 2;\n private const long nhead = 2;\n private const double dropout = 0.2;\n\n private const int batch_size = 64;\n private const int eval_batch_size = 32;\n\n private const int epochs = 10;\n\n internal static void Main(string[] args)\n\n {\n torch.random.manual_seed(1);\n\n var cwd = Environment.CurrentDirectory;\n\n var device = torch.cuda.is_available() ? torch.CUDA : torch.CPU;\n Console.WriteLine($\"Running SequenceToSequence on {device.type.ToString()} for {epochs} epochs.\");\n\n var vocab_iter = TorchText.Datasets.WikiText2(\"train\", _dataLocation);\n var tokenizer = TorchText.Data.Utils.get_tokenizer(\"basic_english\");\n\n var counter = new TorchText.Vocab.Counter<string>();\n foreach (var item in vocab_iter) {\n counter.update(tokenizer(item));\n }\n\n var vocab = new TorchText.Vocab.Vocab(counter);\n\n var (train_iter, valid_iter, test_iter) = TorchText.Datasets.WikiText2(_dataLocation);\n\n var train_data = Batchify(ProcessInput(train_iter, tokenizer, vocab), batch_size).to((Device)device);\n var valid_data = Batchify(ProcessInput(valid_iter, tokenizer, vocab), eval_batch_size).to((Device)device);\n var test_data = Batchify(ProcessInput(test_iter, tokenizer, vocab), eval_batch_size).to((Device)device);\n\n var bptt = 32;\n\n var ntokens = vocab.Count;\n\n var model = new TransformerModel(ntokens, emsize, nhead, nhid, nlayers, dropout).to((Device)device);\n var loss = CrossEntropyLoss();\n var lr = 2.50;\n var optimizer = torch.optim.SGD(model.parameters(), lr);\n var scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1, 0.95, last_epoch: 15);\n\n var totalTime = new Stopwatch();\n totalTime.Start();\n\n foreach (var epoch in Enumerable.Range(1, epochs)) {\n\n var sw = new Stopwatch();\n sw.Start();\n\n train(epoch, train_data, model, loss, bptt, ntokens, optimizer);\n\n var val_loss = evaluate(valid_data, model, loss, bptt, ntokens, optimizer);\n sw.Stop();\n\n var pgFirst = optimizer.ParamGroups.First();\n Console.WriteLine($\"\\nEnd of epoch: {epoch} | lr: {pgFirst.LearningRate:0.00} | time: {sw.Elapsed.TotalSeconds:0.0}s | loss: {val_loss:0.00}\\n\");\n scheduler.step();\n }\n\n var tst_loss = evaluate(test_data, model, loss, bptt, ntokens, optimizer);\n totalTime.Stop();\n\n Console.WriteLine($\"\\nEnd of training | time: {totalTime.Elapsed.TotalSeconds:0.0}s | loss: {tst_loss:0.00}\\n\");\n }\n\n private static void train(int epoch, Tensor train_data, TransformerModel model, Loss<Tensor, Tensor, Tensor> criterion, int bptt, int ntokens, torch.optim.Optimizer optimizer)\n {\n model.train();\n\n using (var d = torch.NewDisposeScope()) {\n\n var total_loss = 0.0f;\n\n var batch = 0;\n var log_interval = 200;\n\n var src_mask = model.GenerateSquareSubsequentMask(bptt);\n\n var tdlen = train_data.shape[0];\n\n\n for (int i = 0; i < tdlen - 1; batch++, i += bptt) {\n\n var (data, targets) = GetBatch(train_data, i, bptt);\n optimizer.zero_grad();\n\n if (data.shape[0] != bptt) {\n src_mask = model.GenerateSquareSubsequentMask(data.shape[0]);\n }\n\n using (var output = model.call(data, src_mask)) {\n var loss = criterion.call(output.view(-1, ntokens), targets);\n loss.backward();\n torch.nn.utils.clip_grad_norm_(model.parameters().ToArray(), 0.5);\n optimizer.step();\n\n total_loss += loss.to(torch.CPU).item<float>();\n }\n\n if ((batch % log_interval == 0 && batch > 0) || (batch == tdlen / bptt)) {\n var cur_loss = total_loss / log_interval;\n Console.WriteLine($\"epoch: {epoch} | batch: {batch} / {tdlen / bptt} | loss: {cur_loss:0.00}\");\n total_loss = 0;\n }\n\n d.DisposeEverythingBut(src_mask);\n }\n }\n }\n\n private static double evaluate(Tensor eval_data, TransformerModel model, Loss<Tensor, Tensor, Tensor> criterion, int bptt, int ntokens, torch.optim.Optimizer optimizer)\n {\n model.eval();\n\n using (var d = torch.NewDisposeScope()) {\n\n var src_mask = model.GenerateSquareSubsequentMask(bptt);\n\n var total_loss = 0.0f;\n var batch = 0;\n\n\n for (int i = 0; i < eval_data.shape[0] - 1; batch++, i += bptt) {\n\n var (data, targets) = GetBatch(eval_data, i, bptt);\n if (data.shape[0] != bptt) {\n src_mask = model.GenerateSquareSubsequentMask(data.shape[0]);\n }\n using (var output = model.call(data, src_mask)) {\n var loss = criterion.call(output.view(-1, ntokens), targets);\n total_loss += data.shape[0] * loss.to(torch.CPU).item<float>();\n }\n\n data.Dispose();\n targets.Dispose();\n\n d.DisposeEverythingBut(src_mask);\n }\n\n return total_loss / eval_data.shape[0];\n }\n }\n\n static Tensor ProcessInput(IEnumerable<string> iter, Func<string, IEnumerable<string>> tokenizer, TorchText.Vocab.Vocab vocab)\n {\n List<Tensor> data = new List<Tensor>();\n foreach (var item in iter) {\n List<long> itemData = new List<long>();\n foreach (var token in tokenizer(item)) {\n itemData.Add(vocab[token]);\n }\n data.Add(torch.tensor(itemData.ToArray(), torch.int64));\n }\n\n var result = torch.cat(data.Where(t => t.NumberOfElements > 0).ToList(), 0);\n return result;\n }\n\n static Tensor Batchify(Tensor data, int batch_size)\n {\n var nbatch = data.shape[0] / batch_size;\n return data.narrow(0, 0, nbatch * batch_size).view(batch_size, -1).t().contiguous();\n }\n\n static (Tensor, Tensor) GetBatch(Tensor source, int index, int bptt)\n {\n var len = Math.Min(bptt, source.shape[0] - 1 - index);\n var data = source[TensorIndex.Slice(index, index + len)];\n var target = source[TensorIndex.Slice(index + 1, index + 1 + len)].reshape(-1);\n return (data, target);\n }\n\n class TransformerModel : Module<Tensor, Tensor, Tensor>\n {\n private Modules.TransformerEncoder transformer_encoder;\n private PositionalEncoding pos_encoder;\n private Modules.Embedding encoder;\n private Modules.Linear decoder;\n\n private long ninputs;\n private Device device;\n\n public TransformerModel(long ntokens, long ninputs, long nheads, long nhidden, long nlayers, double dropout = 0.5) : base(\"Transformer\")\n {\n this.ninputs = ninputs;\n\n pos_encoder = new PositionalEncoding(ninputs, dropout);\n var encoder_layers = TransformerEncoderLayer(ninputs, nheads, nhidden, dropout);\n transformer_encoder = TransformerEncoder(encoder_layers, nlayers);\n encoder = Embedding(ntokens, ninputs);\n decoder = Linear(ninputs, ntokens);\n InitWeights();\n\n RegisterComponents();\n }\n\n public Tensor GenerateSquareSubsequentMask(long size)\n {\n var mask = (torch.ones(new long[] { size, size }) == 1).triu().transpose(0, 1);\n return mask.to_type(ScalarType.Float32)\n .masked_fill(mask == 0, float.NegativeInfinity)\n .masked_fill(mask == 1, 0.0f).to(device);\n }\n\n private void InitWeights()\n {\n var initrange = 0.1;\n\n init.uniform_(encoder.weight, -initrange, initrange);\n init.zeros_(decoder.bias);\n init.uniform_(decoder.weight, -initrange, initrange);\n }\n\n public override Tensor forward(Tensor t, Tensor mask)\n {\n var src = pos_encoder.call(encoder.call(t) * MathF.Sqrt(ninputs));\n var enc = transformer_encoder.call(src, mask);\n return decoder.call(enc);\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n transformer_encoder.Dispose();\n pos_encoder.Dispose();\n encoder.Dispose();\n decoder.Dispose();\n ClearModules();\n }\n base.Dispose(disposing);\n }\n\n protected override Module _to(DeviceType deviceType, int deviceIndex = -1)\n {\n this.device = new Device(deviceType, deviceIndex);\n return base._to(deviceType, deviceIndex);\n }\n }\n\n class PositionalEncoding : Module<Tensor, Tensor>\n {\n private Module<Tensor, Tensor> dropout;\n private Tensor pe;\n\n public PositionalEncoding(long dmodel, double dropout, int maxLen = 5000) : base(\"PositionalEncoding\")\n {\n this.dropout = Dropout(dropout);\n var pe = torch.zeros(new long[] { maxLen, dmodel });\n var position = torch.arange(0, maxLen, 1).unsqueeze(1);\n var divTerm = (torch.arange(0, dmodel, 2) * (-Math.Log(10000.0) / dmodel)).exp();\n pe[TensorIndex.Ellipsis, TensorIndex.Slice(0, null, 2)] = (position * divTerm).sin();\n pe[TensorIndex.Ellipsis, TensorIndex.Slice(1, null, 2)] = (position * divTerm).cos();\n this.pe = pe.unsqueeze(0).transpose(0, 1);\n\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor t)\n {\n using var x = t + pe[TensorIndex.Slice(null, t.shape[0]), TensorIndex.Slice()];\n return dropout.call(x);\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n dropout.Dispose();\n pe.Dispose();\n ClearModules();\n }\n base.Dispose(disposing);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5054945349693298, "alphanum_fraction": 0.5054945349693298, "avg_line_length": 28.1200008392334, "blob_id": "2b4624bb37ccd65df9f08b938db248eb4d789c20", "content_id": "0b7dec35775bd78675d10d5a0ff10d99ab80f657", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1456, "license_type": "permissive", "max_line_length": 130, "num_lines": 50, "path": "/src/TorchVision/Compose.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class ComposedTransforms : IDisposable, ITransform\n {\n public ComposedTransforms(ITransform[] transforms)\n {\n this.transforms = transforms;\n }\n\n public void Dispose()\n {\n foreach (var t in transforms) {\n if (t is IDisposable) {\n ((IDisposable)t).Dispose();\n }\n }\n }\n\n public Tensor call(Tensor input)\n {\n foreach (var t in transforms) {\n input = t.call(input);\n }\n return input;\n }\n\n private ITransform[] transforms;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Composes several transforms together.\n /// </summary>\n /// <param name=\"transforms\">A list of transforms to compose serially.</param>\n /// <returns></returns>\n static public ITransform Compose(params ITransform[] transforms)\n {\n return new ComposedTransforms(transforms);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6159601211547852, "alphanum_fraction": 0.6221945285797119, "avg_line_length": 36.015384674072266, "blob_id": "442c53a4e01cfe622efca8238cb98b161d1bac5c", "content_id": "df0cb54044067fb7e1f625999bf57b0e5a1476df", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2406, "license_type": "permissive", "max_line_length": 130, "num_lines": 65, "path": "/src/TorchSharp/Utils/Decompress.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing ICSharpCode.SharpZipLib.Core;\nusing ICSharpCode.SharpZipLib.GZip;\nusing ICSharpCode.SharpZipLib.Tar;\n\n// This code was inspired by code found in the SciSharpStack-Examples repository located at:\n//\n// https://github.com/SciSharp/SciSharp-Stack-Examples\n//\n// Original License: https://github.com/SciSharp/SciSharp-Stack-Examples/blob/master/LICENSE\n//\n// Original copyright information was not found at the above location.\n\nnamespace TorchSharp.Utils\n{\n public static class Decompress\n {\n public static void DecompressGZipFile(string gzipFileName, string targetDir)\n {\n byte[] buf = new byte[4096];\n\n using (var fs = File.OpenRead(gzipFileName))\n using (var gzipStream = new GZipInputStream(fs)) {\n\n string fnOut = Path.Combine(targetDir, Path.GetFileNameWithoutExtension(gzipFileName));\n\n using (var fsOut = File.Create(fnOut)) {\n StreamUtils.Copy(gzipStream, fsOut, buf);\n }\n }\n }\n public static void ExtractTGZ(string gzArchiveName, string destFolder)\n {\n var flag = gzArchiveName.Split(Path.DirectorySeparatorChar).Last().Split('.').First() + \".bin\";\n if (File.Exists(Path.Combine(destFolder, flag))) return;\n\n Console.WriteLine($\"Extracting.\");\n var task = Task.Run(() => {\n using (var inStream = File.OpenRead(gzArchiveName)) {\n using (var gzipStream = new GZipInputStream(inStream)) {\n#pragma warning disable CS0618 // Type or member is obsolete\n using (TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream))\n#pragma warning restore CS0618 // Type or member is obsolete\n tarArchive.ExtractContents(destFolder);\n }\n }\n });\n\n while (!task.IsCompleted) {\n Thread.Sleep(200);\n Console.Write(\".\");\n }\n\n File.Create(Path.Combine(destFolder, flag));\n Console.WriteLine(\"\");\n Console.WriteLine(\"Extraction completed.\");\n }\n\n }\n}\n" }, { "alpha_fraction": 0.4355202317237854, "alphanum_fraction": 0.43863415718078613, "avg_line_length": 34.613765716552734, "blob_id": "1a9ef997c198e7cf1935de02ed247328a8bd3182", "content_id": "35515c05407e574f9952002c50b3beef28ed453a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 18626, "license_type": "permissive", "max_line_length": 150, "num_lines": 523, "path": "/src/TorchSharp/Tensor/Storage.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n /// <summary>\n /// A torch.Storage is a contiguous, one-dimensional array of a single data type.\n /// Every tensor has a corresponding storage of the same data type.\n /// </summary>\n public abstract class Storage\n {\n protected Storage()\n {\n }\n\n protected Storage(Tensor tensor)\n {\n _tensor = tensor;\n data_ptr();\n }\n\n protected Storage(Tensor tensor, IntPtr data_ptr)\n {\n _tensor = tensor;\n _tensor_data_ptr = (data_ptr == IntPtr.Zero) ? this.data_ptr() : data_ptr;\n }\n\n internal static Storage<T> Create<T>(Tensor tensor) where T : unmanaged\n {\n var type = typeof(T);\n switch (type) {\n case Type _ when type == typeof(byte):\n return new Storage<T>(tensor.@byte());\n case Type _ when type == typeof(bool):\n return new Storage<T>(tensor.@bool());\n case Type _ when type == typeof(int):\n return new Storage<T>(tensor.@int());\n case Type _ when type == typeof(long):\n return new Storage<T>(tensor.@long());\n case Type _ when type == typeof(float):\n return new Storage<T>(tensor.@float());\n case Type _ when type == typeof(double):\n return new Storage<T>(tensor.@double());\n case Type _ when type == typeof((float,float)):\n return new Storage<T>(tensor.to_type(ScalarType.ComplexFloat32));\n case Type _ when type == typeof(System.Numerics.Complex):\n return new Storage<T>(tensor.to_type(ScalarType.ComplexFloat64));\n default:\n throw new NotSupportedException();\n }\n }\n\n protected static Tensor CreateTypedTensor<T>(ScalarType dtype, IList<T> rawArray)\n {\n switch (dtype) {\n case ScalarType.Int8:\n return torch.tensor(rawArray as IList<byte>);\n case ScalarType.Bool:\n return torch.tensor(rawArray as IList<bool>);\n case ScalarType.Int32:\n return torch.tensor(rawArray as IList<int>);\n case ScalarType.Int64:\n return torch.tensor(rawArray as IList<long>);\n case ScalarType.Float32:\n return torch.tensor(rawArray as IList<float>);\n case ScalarType.Float64:\n return torch.tensor(rawArray as IList<double>);\n case ScalarType.ComplexFloat32:\n return torch.tensor(rawArray as IList<(float, float)>);\n case ScalarType.ComplexFloat64:\n return torch.tensor(rawArray as IList<System.Numerics.Complex>);\n default:\n throw new NotSupportedException();\n }\n }\n\n protected torch.Tensor _tensor; // Keeping it alive.\n protected IntPtr _tensor_data_ptr;\n\n /// <summary>\n /// Convert to bool storage.\n /// </summary>\n /// <returns></returns>\n public Storage<bool> @bool() => _tensor.to_type(ScalarType.Bool).storage<bool>();\n\n /// <summary>\n /// Convert to byte storage.\n /// </summary>\n public Storage<byte> @byte() => _tensor.to_type(ScalarType.Byte).storage<byte>();\n\n /// <summary>\n /// Convert to char storage.\n /// </summary>\n public Storage<char> @char() => _tensor.to_type(ScalarType.Int8).storage<char>();\n\n /// <summary>\n /// Convert to int storage.\n /// </summary>\n public Storage<int> @int() => _tensor.to_type(ScalarType.Int32).storage<int>();\n\n /// <summary>\n /// Convert to long storage.\n /// </summary>\n public Storage<long> @long() => _tensor.to_type(ScalarType.Int64).storage<long>();\n\n /// <summary>\n /// Convert to float storage.\n /// </summary>\n public Storage<float> @float() => _tensor.to_type(ScalarType.Float32).storage<float>();\n\n /// <summary>\n /// Convert to double storage.\n /// </summary>\n public Storage<double> @double() => _tensor.to_type(ScalarType.Float64).storage<double>();\n\n /// <summary>\n /// Convert to 32-bit complex storage.\n /// </summary>\n public Storage<(float,float)> complex_float() => _tensor.to_type(ScalarType.ComplexFloat32).storage<(float, float)>();\n\n /// <summary>\n /// Convert to 64-bit complex storage.\n /// </summary>\n public Storage<System.Numerics.Complex> complex_double() => _tensor.to_type(ScalarType.ComplexFloat64).storage<System.Numerics.Complex>();\n\n /// <summary>\n /// The size of each storage element.\n /// </summary>\n /// <returns></returns>\n public abstract int element_size();\n\n /// <summary>\n /// A pointer to the raw data in memory.\n /// </summary>\n /// <returns></returns>\n protected IntPtr data_ptr()\n {\n if (_tensor_data_ptr != IntPtr.Zero)\n return _tensor_data_ptr;\n\n var res = THSStorage_data_ptr(_tensor.Handle);\n if (res == IntPtr.Zero) { CheckForErrors(); }\n _tensor_data_ptr = res;\n return res;\n }\n\n /// <summary>\n /// The number of bytes allocated to the storage.\n /// </summary>\n /// <returns></returns>\n public ulong nbytes()\n {\n var res = THSStorage_nbytes(_tensor.Handle);\n CheckForErrors();\n return res;\n }\n }\n\n /// <summary>\n /// A torch.Storage is a contiguous, one-dimensional array of a single data type.\n /// Every tensor has a corresponding storage of the same data type.\n /// </summary>\n public sealed class Storage<T> : torch.Storage, IDisposable, IEnumerable<T> where T : unmanaged\n {\n internal Storage(torch.Tensor tensor, int count = -1) : base(tensor, IntPtr.Zero)\n {\n _count = count;\n }\n\n internal Storage(IntPtr data_ptr, ScalarType dtype, int count = -1) : base(null, data_ptr)\n {\n _count = count;\n _tensor = CreateTypedTensor<T>(dtype, this.ToArray());\n }\n\n internal Storage(T value) : base()\n {\n _scalarValue = value;\n }\n\n private T _scalarValue = default(T);\n\n /// <summary>\n /// Size of each storage element.\n /// </summary>\n /// <returns></returns>\n public override int element_size()\n {\n ValidateNotScalar();\n unsafe {\n return sizeof(T);\n }\n }\n\n /// <summary>\n /// The device where the storage is located.\n /// </summary>\n public Device device {\n get {\n ValidateNotScalar();\n return _tensor.device;\n }\n }\n\n /// <summary>\n /// Move the storage to a CUDA device.\n /// </summary>\n public Storage<T> cuda(Device device = null)\n {\n ValidateNotScalar();\n return _tensor.cuda(device).storage<T>();\n }\n\n /// <summary>\n /// Move the storage to the CPU.\n /// </summary>\n public Storage<T> cpu()\n {\n ValidateNotScalar();\n return _tensor.cpu().storage<T>();\n }\n\n /// <summary>\n /// Convert the storage instance to a .NET array, copying its data.\n /// </summary>\n /// <returns></returns>\n public T[] ToArray()\n {\n ValidateNotScalar();\n var result = new T[Count];\n CopyTo(result, 0);\n return result;\n }\n\n /// <summary>\n /// Accesses a single element of a storage.\n /// </summary>\n /// <param name=\"index\">The index of the element.</param>\n /// <returns></returns>\n public T this[int index] {\n get {\n ValidateNotScalar();\n CheckIndex(index);\n unsafe {\n T* ptr = (T*)_tensor_data_ptr;\n return ptr[index];\n }\n }\n set {\n ValidateNotScalar();\n CheckIndex(index);\n unsafe {\n T* ptr = (T*)_tensor_data_ptr;\n ptr[index] = value;\n }\n }\n }\n\n /// <summary>\n /// Accesses a slice of a storage instance.\n /// </summary>\n /// <param name=\"range\">The range, expressed as a tuple [start,end)</param>\n public Storage<T> this[(int? start, int? end) range] {\n get {\n ValidateNotScalar();\n if (range.end < range.start)\n throw new ArgumentException(\"end < start\");\n var start = CheckIndex(range.start.HasValue? range.start.Value : 0);\n var end = CheckIndex(range.end.HasValue ? range.end.Value : Count);\n var count = end - start;\n unsafe {\n var ptr = _tensor_data_ptr + sizeof(T) * start;\n return new Storage<T>(ptr, _tensor.dtype, count);\n }\n }\n set {\n ValidateNotScalar();\n if (value._tensor is not null || value._tensor_data_ptr != IntPtr.Zero)\n throw new InvalidOperationException();\n if (range.end < range.start)\n throw new ArgumentException(\"end < start\");\n var v = value._scalarValue;\n var start = CheckIndex(range.start.HasValue ? range.start.Value : 0);\n var end = CheckIndex(range.end.HasValue ? range.end.Value : Count);\n unsafe {\n T* ptr = (T*)_tensor_data_ptr;\n for (int i = start; i < end; i++)\n ptr[i] = v;\n }\n }\n }\n\n#if !NETSTANDARD2_0_OR_GREATER\n /// <summary>\n /// Accesses a slice of a storage instance.\n /// </summary>\n /// <param name=\"range\">The range.</param>\n public Storage<T> this[System.Range range] {\n get {\n var start = CheckIndex(range.Start);\n var end = CheckIndex(range.End);\n return this[(start, end)];\n }\n set {\n var start = CheckIndex(range.Start);\n var end = CheckIndex(range.End);\n this[(start, end)] = value;\n }\n }\n\n private int CheckIndex(System.Index index)\n {\n var i = index.IsFromEnd ? Count - index.Value : index.Value;\n if (i < 0 || i >= Count)\n throw new IndexOutOfRangeException();\n return i;\n }\n#endif\n\n private int CheckIndex(int index) {\n if (index < 0 || index >= Count)\n throw new IndexOutOfRangeException();\n return index;\n }\n\n private void ValidateNotScalar()\n {\n if (_tensor is null &&_tensor_data_ptr == IntPtr.Zero)\n throw new InvalidOperationException(\"Invalid use of a scalar Storage instance.\");\n }\n\n /// <summary>\n /// The number of elements in the storage.\n /// </summary>\n public int Count {\n get {\n ValidateNotScalar();\n if (_count == -1) {\n unsafe {\n _count = (int)nbytes() / sizeof(T);\n }\n }\n return _count;\n }\n }\n\n private int _count = -1;\n\n public static implicit operator Storage<T>(T value)\n {\n return new Storage<T>(value);\n }\n\n /// <summary>\n /// Copy data from an array into a storage instance.\n /// </summary>\n /// <param name=\"array\"></param>\n public void copy_(IList<T> array)\n {\n ValidateNotScalar();\n CopyFrom(array, 0);\n }\n\n /// <summary>\n /// Fill a storage instance with a single value.\n /// </summary>\n /// <param name=\"value\"></param>\n public void fill_(T value)\n {\n ValidateNotScalar();\n unsafe {\n var ptr = (T*)data_ptr();\n for (int i = 0; i < Count; i++)\n ((T*)ptr)[i] = value;\n }\n }\n\n /// <summary>\n /// Convert the storage to a .NET list.\n /// </summary>\n /// <returns></returns>\n public IList<T> tolist()\n {\n ValidateNotScalar();\n var result = new T[Count];\n CopyTo(result, 0);\n return result;\n }\n\n public bool IsReadOnly => false;\n\n public bool Contains(T item)\n {\n ValidateNotScalar();\n unsafe {\n var ptr = (T*)data_ptr();\n for (int i = 0; i < Count; i++)\n if (((T*)ptr)[i].Equals(item)) return true;\n }\n return false;\n }\n\n /// <summary>\n /// Copy the contents of the Storage instance into the provided array, starting at 'arrayIndex'\n /// </summary>\n /// <param name=\"array\">A target array.</param>\n /// <param name=\"arrayIndex\">The first offset in the array to write data to.</param>\n public void CopyTo(IList<T> array, int arrayIndex)\n {\n ValidateNotScalar();\n\n unsafe {\n var ptr = (T*)data_ptr();\n for (int i = 0; i < Count && i < array.Count-arrayIndex; i++)\n array[i + arrayIndex] = ((T*)ptr)[i];\n }\n }\n\n /// <summary>\n /// Copy the contents of the provided array into the Storage instance, starting at 'arrayIndex' in the array.\n /// </summary>\n /// <param name=\"array\">A source array.</param>\n /// <param name=\"arrayIndex\">The first offset in the array to read data from.</param>\n public void CopyFrom(IList<T> array, int arrayIndex)\n {\n ValidateNotScalar();\n\n unsafe {\n var ptr = (T*)data_ptr();\n for (int i = 0; i < Count && i < array.Count-arrayIndex; i++)\n ((T*)ptr)[i] = array[i+arrayIndex];\n }\n }\n\n /// <summary>\n /// Look up a value and return the first index where it can be found.\n /// </summary>\n /// <param name=\"item\">The item to look for.</param>\n /// <returns></returns>\n public int IndexOf(T item)\n {\n unsafe {\n var ptr = (T*)data_ptr();\n for (int i = 0; i < Count; i++)\n if (((T*)ptr)[i].Equals(item)) return i;\n }\n return -1;\n }\n\n public IEnumerator<T> GetEnumerator()\n {\n ValidateNotScalar();\n return new StorageEnumerator(this);\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n ValidateNotScalar();\n return new StorageEnumerator(this);\n }\n\n public void Dispose()\n {\n _tensor_data_ptr = IntPtr.Zero;\n _tensor = null;\n }\n\n private struct StorageEnumerator: IEnumerator<T>\n {\n private Storage<T> _span;\n private readonly long _count;\n\n // State.\n private long _index;\n private T _current;\n\n public StorageEnumerator(Storage<T> span)\n {\n _span = span;\n _count = span.Count;\n Debug.Assert(_count > 0);\n _index = -1;\n _current = default;\n }\n\n public T Current => _current;\n\n object IEnumerator.Current => Current;\n\n public void Dispose()\n {\n _span = null;\n Reset();\n }\n\n public bool MoveNext()\n {\n if (_index >= _count - 1) {\n Reset();\n return false;\n }\n\n _index += 1;\n\n unsafe { _current = ((T*)_span._tensor_data_ptr)[_index]; }\n return true;\n }\n\n public void Reset()\n {\n _index = -1;\n _current = default;\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.581882894039154, "alphanum_fraction": 0.5842563509941101, "avg_line_length": 37.89230728149414, "blob_id": "cd9081aadae5815e1138b136ef3a7ccc19016018", "content_id": "ff812dfb33350b9627983246cb8264f1a973c120", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2528, "license_type": "permissive", "max_line_length": 164, "num_lines": 65, "path": "/src/TorchSharp/Distributions/LogNormal.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n using static torch.distributions;\n\n namespace Modules\n {\n public class LogNormal : TransformedDistribution\n {\n internal LogNormal(Tensor loc, Tensor scale, torch.Generator generator = null) :\n base(Normal(loc, scale, generator), new torch.distributions.transforms.Transform[] { new torch.distributions.transforms.ExpTransform() }, generator)\n {\n this.loc = loc.alias().DetachFromDisposeScope();\n this.scale = scale.alias().DetachFromDisposeScope();\n }\n\n public Tensor loc { get; private set; }\n\n public Tensor scale { get; private set; }\n\n public override Tensor mean => torch.WrappedTensorDisposeScope(() => (loc + scale.pow(2) / 2).exp());\n\n public override Tensor mode => torch.WrappedTensorDisposeScope(() => (loc - scale.square()).exp());\n\n public override Tensor variance => torch.WrappedTensorDisposeScope(() => (scale.pow(2).exp() - 1) * (2 * loc + scale.pow(2)).exp());\n\n public override Tensor entropy()\n {\n return base_distribution.entropy() + loc;\n }\n\n public override Distribution expand(Size batch_shape, Distribution instance = null)\n {\n var newDistribution = ((instance == null)\n ? new LogNormal(loc.expand(batch_shape), scale.expand(batch_shape), generator)\n : instance) as LogNormal;\n return base.expand(batch_shape, newDistribution);\n }\n }\n }\n\n\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a log-normal distribution parameterized by `loc` and `scale`\n /// </summary>\n /// <param name=\"loc\">Mode or median of the distribution.</param>\n /// <param name=\"scale\">Standard deviation.</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static LogNormal LogNormal(Tensor loc, Tensor scale, torch.Generator generator = null)\n {\n \n return new LogNormal(loc, scale, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5458303689956665, "alphanum_fraction": 0.5670561790466309, "avg_line_length": 28.321678161621094, "blob_id": "c8a157aed65a0f581f3793d3d30a8e2b9722cbfe", "content_id": "9bd62666271cf80ade6d0671f7dd3e7953d05d71", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12579, "license_type": "permissive", "max_line_length": 129, "num_lines": 429, "path": "/src/Python/exportsd.py", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#\nimport io\nimport torch\nimport leb128\nimport numpy as np\n\ndef _elem_type(t):\n dt = t.dtype\n\n if dt == torch.uint8:\n return 0\n elif dt == torch.int8:\n return 1\n elif dt == torch.int16:\n return 2\n elif dt == torch.int32:\n return 3\n elif dt == torch.int64:\n return 4\n elif dt == torch.float16:\n return 5\n elif dt == torch.float32:\n return 6\n elif dt == torch.float64:\n return 7\n elif dt == torch.bool:\n return 11\n elif dt == torch.bfloat16:\n return 15\n else:\n return 4711\n\ndef _write_tensor(t, stream):\n stream.write(leb128.u.encode(_elem_type(t)))\n stream.write(leb128.u.encode(len(t.shape)))\n for s in t.shape:\n stream.write(leb128.u.encode(s))\n stream.write(t.numpy().tobytes())\n\ndef save_state_dict(sd, stream):\n \"\"\"\n Saves a PyToch state dictionary using the format that TorchSharp can\n read.\n\n :param sd: A dictionary produced by 'model.state_dict()'\n :param stream: An write stream opened for binary I/O.\n \"\"\"\n stream.write(leb128.u.encode(len(sd)))\n for entry in sd:\n stream.write(leb128.u.encode(len(entry)))\n stream.write(bytes(entry, 'utf-8'))\n _write_tensor(sd[entry], stream)\n\ndef _write_encoded_int64(value, stream):\n stream.write(leb128.u.encode(value))\n\ndef _write_optim_name(name, stream):\n _write_encoded_int64(len(name),stream)\n stream.write(bytes(name, 'utf-8'))\n\ndef _write_bool(value, stream):\n stream.write(value.to_bytes(1, 'little'))\n\ndef _write_int32(value, stream):\n stream.write(value.to_bytes(4, 'little'))\n\ndef _write_int64(value, stream):\n stream.write(value.to_bytes(8, 'little'))\n\ndef _write_conditional_state_tensor(name, state, stream):\n if name not in state:\n _write_bool(False, stream)\n else: \n buf = state[name]\n if buf == None:\n _write_bool(False, stream)\n else:\n _write_bool(True, stream)\n _write_tensor(buf, stream)\n\ndef save_sgd(optim, stream):\n\n sd = optim.state_dict()\n\n _write_optim_name('SGD', stream)\n\n _write_encoded_int64(len(optim.param_groups), stream)\n _write_encoded_int64(len(optim.state), stream)\n\n # Write options\n\n for pg in optim.param_groups:\n floats = np.empty(5,dtype=np.float64)\n floats[0] = pg['lr'] \n floats[1] = pg['lr']\n floats[2] = pg['momentum']\n floats[3] = pg['dampening']\n floats[4] = pg['weight_decay']\n stream.write(floats.tobytes())\n _write_bool(pg['nesterov'], stream)\n _write_bool(pg['maximize'], stream)\n\n # Write state\n for group in optim.param_groups:\n for p in group['params']:\n st = optim.state[p]\n _write_conditional_state_tensor('momentum_buffer', st, stream) \n\ndef save_asgd(optim, stream):\n\n sd = optim.state_dict()\n\n _write_optim_name('ASGD', stream)\n\n _write_encoded_int64(len(optim.param_groups), stream)\n _write_encoded_int64(len(optim.state), stream)\n\n # Write options\n\n for pg in optim.param_groups:\n floats = np.empty(2,dtype=np.float64)\n floats[0] = pg['lr'] \n floats[1] = pg['lr']\n stream.write(floats.tobytes())\n _write_bool(pg['maximize'], stream)\n floats = np.empty(4,dtype=np.float64)\n floats[0] = pg['lambd']\n floats[1] = pg['alpha']\n floats[2] = pg['weight_decay']\n floats[3] = pg['t0']\n stream.write(floats.tobytes())\n\n # Write state\n for group in optim.param_groups:\n for p in group['params']:\n st = optim.state[p]\n _write_int64(int(st[\"step\"].item()), stream)\n floats = np.empty(2,dtype=np.float64)\n floats[0] = st['eta'] \n floats[1] = st['mu']\n stream.write(floats.tobytes())\n _write_tensor(st['ax'], stream)\n\ndef save_rprop(optim, stream):\n\n sd = optim.state_dict()\n\n _write_optim_name('Rprop', stream)\n\n _write_encoded_int64(len(optim.param_groups), stream)\n _write_encoded_int64(len(optim.state), stream)\n\n # Write options\n\n for pg in optim.param_groups:\n floats = np.empty(2,dtype=np.float64)\n floats[0] = pg['lr'] \n floats[1] = pg['lr']\n stream.write(floats.tobytes())\n _write_bool(pg['maximize'], stream)\n floats = np.empty(4,dtype=np.float64)\n etaminus, etaplus = pg['etas']\n min_step, max_step = pg['step_sizes']\n floats[0] = etaminus\n floats[1] = etaplus\n floats[2] = min_step\n floats[3] = max_step\n stream.write(floats.tobytes())\n\n # Write state\n for group in optim.param_groups:\n for p in group['params']:\n st = optim.state[p]\n _write_int64(st[\"step\"], stream)\n _write_tensor(st['prev'], stream)\n _write_tensor(st['step_size'], stream)\n\ndef save_rmsprop(optim, stream):\n\n sd = optim.state_dict()\n\n _write_optim_name('RMSProp', stream)\n\n _write_encoded_int64(len(optim.param_groups), stream)\n _write_encoded_int64(len(optim.state), stream)\n\n # Write options\n\n for pg in optim.param_groups:\n floats = np.empty(2,dtype=np.float64)\n floats[0] = pg['lr'] \n floats[1] = pg['lr']\n stream.write(floats.tobytes())\n _write_bool(pg['maximize'], stream)\n floats = np.empty(4,dtype=np.float64)\n floats[0] = pg['momentum']\n floats[1] = pg['alpha']\n floats[2] = pg['eps']\n floats[3] = pg['weight_decay']\n stream.write(floats.tobytes())\n _write_bool(pg['centered'], stream)\n\n # Write state\n for group in optim.param_groups:\n for p in group['params']:\n st = optim.state[p]\n _write_int64(st[\"step\"], stream)\n _write_tensor(st['square_avg'], stream)\n _write_conditional_state_tensor('momentum_buffer', st, stream)\n _write_conditional_state_tensor('grad_avg', st, stream)\n\ndef save_adam(optim, stream):\n\n sd = optim.state_dict()\n\n _write_optim_name('Adam', stream)\n\n _write_encoded_int64(len(optim.param_groups), stream)\n _write_encoded_int64(len(optim.state), stream)\n\n # Write options\n\n for pg in optim.param_groups:\n floats = np.empty(6,dtype=np.float64)\n floats[0] = pg['lr'] \n floats[1] = pg['lr']\n beta1, beta2 = pg['betas']\n floats[2] = beta1\n floats[3] = beta2\n floats[4] = pg['eps']\n floats[5] = pg['weight_decay']\n stream.write(floats.tobytes())\n _write_bool(pg['amsgrad'], stream)\n _write_bool(pg['maximize'], stream)\n\n # Write state\n for group in optim.param_groups:\n for p in group['params']:\n st = optim.state[p]\n _write_int64(int(st[\"step\"].item()), stream)\n _write_tensor(st['exp_avg'], stream)\n _write_tensor(st['exp_avg_sq'], stream)\n _write_conditional_state_tensor('max_exp_avg_sq', st, stream)\n\ndef save_adamw(optim, stream):\n\n sd = optim.state_dict()\n\n _write_optim_name('AdamW', stream)\n\n _write_encoded_int64(len(optim.param_groups), stream)\n _write_encoded_int64(len(optim.state), stream)\n\n # Write options\n\n for pg in optim.param_groups:\n floats = np.empty(6,dtype=np.float64)\n floats[0] = pg['lr'] \n floats[1] = pg['lr']\n beta1, beta2 = pg['betas']\n floats[2] = beta1\n floats[3] = beta2\n floats[4] = pg['eps']\n floats[5] = pg['weight_decay']\n stream.write(floats.tobytes())\n _write_bool(pg['amsgrad'], stream)\n _write_bool(pg['maximize'], stream)\n\n # Write state\n for group in optim.param_groups:\n for p in group['params']:\n st = optim.state[p]\n _write_int64(int(st[\"step\"].item()), stream)\n _write_tensor(st['exp_avg'], stream)\n _write_tensor(st['exp_avg_sq'], stream)\n _write_conditional_state_tensor('max_exp_avg_sq', st, stream)\n\ndef save_nadam(optim, stream):\n\n sd = optim.state_dict()\n\n _write_optim_name('NAdam', stream)\n\n _write_encoded_int64(len(optim.param_groups), stream)\n _write_encoded_int64(len(optim.state), stream)\n\n # Write options\n\n for pg in optim.param_groups:\n floats = np.empty(7,dtype=np.float64)\n floats[0] = pg['lr'] \n floats[1] = pg['lr']\n beta1, beta2 = pg['betas']\n floats[2] = beta1\n floats[3] = beta2\n floats[4] = pg['eps']\n floats[5] = pg['weight_decay']\n floats[6] = pg['momentum_decay']\n stream.write(floats.tobytes())\n\n # Write state\n for group in optim.param_groups:\n for p in group['params']:\n st = optim.state[p]\n _write_int64(int(st[\"step\"].item()), stream)\n floats = np.empty(1,dtype=np.float64)\n floats[0] = float(st[\"mu_product\"].item()) \n stream.write(floats.tobytes())\n _write_tensor(st['exp_avg'], stream)\n _write_tensor(st['exp_avg_sq'], stream)\n\ndef save_radam(optim, stream):\n\n sd = optim.state_dict()\n\n _write_optim_name('RAdam', stream)\n\n _write_encoded_int64(len(optim.param_groups), stream)\n _write_encoded_int64(len(optim.state), stream)\n\n # Write options\n\n for pg in optim.param_groups:\n floats = np.empty(6,dtype=np.float64)\n floats[0] = pg['lr'] \n floats[1] = pg['lr']\n beta1, beta2 = pg['betas']\n floats[2] = beta1\n floats[3] = beta2\n floats[4] = pg['eps']\n floats[5] = pg['weight_decay']\n stream.write(floats.tobytes())\n\n # Write state\n for group in optim.param_groups:\n for p in group['params']:\n st = optim.state[p]\n _write_int64(int(st[\"step\"].item()), stream)\n _write_tensor(st['exp_avg'], stream)\n _write_tensor(st['exp_avg_sq'], stream)\n\ndef save_adamax(optim, stream):\n\n sd = optim.state_dict()\n\n _write_optim_name('Adamax', stream)\n\n _write_encoded_int64(len(optim.param_groups), stream)\n _write_encoded_int64(len(optim.state), stream)\n\n # Write options\n\n for pg in optim.param_groups:\n floats = np.empty(6,dtype=np.float64)\n floats[0] = pg['lr'] \n floats[1] = pg['lr']\n beta1, beta2 = pg['betas']\n floats[2] = beta1\n floats[3] = beta2\n floats[4] = pg['eps']\n floats[5] = pg['weight_decay']\n stream.write(floats.tobytes())\n\n # Write state\n for group in optim.param_groups:\n for p in group['params']:\n st = optim.state[p]\n _write_int64(int(st[\"step\"].item()), stream)\n _write_tensor(st['exp_avg'], stream)\n _write_tensor(st['exp_inf'], stream)\n\ndef save_adadelta(optim, stream):\n\n sd = optim.state_dict()\n\n _write_optim_name('Adadelta', stream)\n\n _write_encoded_int64(len(optim.param_groups), stream)\n _write_encoded_int64(len(optim.state), stream)\n\n # Write options\n\n for pg in optim.param_groups:\n floats = np.empty(5,dtype=np.float64)\n floats[0] = pg['lr'] \n floats[1] = pg['lr']\n floats[2] = pg['rho']\n floats[3] = pg['eps']\n floats[4] = pg['weight_decay']\n stream.write(floats.tobytes())\n _write_bool(pg['maximize'], stream)\n\n # Write state\n for group in optim.param_groups:\n for p in group['params']:\n st = optim.state[p]\n _write_int64(st[\"step\"], stream)\n _write_tensor(st['square_avg'], stream)\n _write_tensor(st['acc_delta'], stream)\n\ndef save_adagrad(optim, stream):\n\n sd = optim.state_dict()\n\n _write_optim_name('Adagrad', stream)\n\n _write_encoded_int64(len(optim.param_groups), stream)\n _write_encoded_int64(len(optim.state), stream)\n\n # Write options\n\n for pg in optim.param_groups:\n floats = np.empty(6,dtype=np.float64)\n floats[0] = pg['lr'] \n floats[1] = pg['lr']\n floats[2] = pg['lr_decay']\n floats[3] = pg['initial_accumulator_value']\n floats[4] = pg['eps']\n floats[5] = pg['weight_decay']\n stream.write(floats.tobytes())\n\n # Write state\n for group in optim.param_groups:\n for p in group['params']:\n st = optim.state[p]\n _write_int64(int(st[\"step\"].item()), stream)\n _write_tensor(st['sum'], stream)\n" }, { "alpha_fraction": 0.7192075848579407, "alphanum_fraction": 0.7245908975601196, "avg_line_length": 54.61676788330078, "blob_id": "fb91138d748b56a2c3c40b3b90d26bbd2ecaf663", "content_id": "4a0298a15dfd95f114145473bfd8ef4981349693", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9288, "license_type": "permissive", "max_line_length": 244, "num_lines": 167, "path": "/src/TorchSharp/PInvoke/LibTorchSharp.THSLinalg.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Runtime.InteropServices;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp.PInvoke\n{\n#pragma warning disable CA2101\n internal static partial class NativeMethods\n {\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_cholesky(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_cholesky_ex(IntPtr tensor, [MarshalAs(UnmanagedType.U1)] bool check_errors, out IntPtr pInfo);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_cond_int(IntPtr tensor, int p);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_cond_float(IntPtr tensor, double p);\n\n [DllImport(\"LibTorchSharp\", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]\n internal static extern IntPtr THSLinalg_cond_str(IntPtr tensor, [MarshalAs(UnmanagedType.LPStr)] string p);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_cond_none(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_cross(IntPtr input, IntPtr other, long dim);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_det(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_slogdet(IntPtr tensor, out IntPtr pLogabsdet);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_eig(IntPtr tensor, out IntPtr pEigenvectors);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSTensor_geqrf(IntPtr tensor, out IntPtr tau);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_eigh(IntPtr tensor, byte UPLO, out IntPtr pEigenvectors);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_eigvals(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_eigvalsh(IntPtr tensor, byte UPLO);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_householder_product(IntPtr tensor, IntPtr tau);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_inv(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_inv_ex(IntPtr tensor, [MarshalAs(UnmanagedType.U1)] bool check_errors, out IntPtr pInfo);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_lstsq_none(IntPtr tensor, IntPtr other, out IntPtr pResiduals, out IntPtr pRank, out IntPtr pSingularValues);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_lstsq_rcond(IntPtr tensor, IntPtr other, double rcond, out IntPtr pResiduals, out IntPtr pRank, out IntPtr pSingularValues);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_ldl_factor(IntPtr A, [MarshalAs(UnmanagedType.U1)] bool hermitian, out IntPtr pivots);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_ldl_factor_ex(IntPtr A, [MarshalAs(UnmanagedType.U1)] bool hermitian, [MarshalAs(UnmanagedType.U1)] bool check_errors, out IntPtr pivots, out IntPtr info);\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_ldl_solve(IntPtr LD, IntPtr pivots, IntPtr B, [MarshalAs(UnmanagedType.U1)] bool hermitian);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_lu(IntPtr tensor, [MarshalAs(UnmanagedType.U1)] bool pivot, out IntPtr pL, out IntPtr pU);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_lu_factor(IntPtr tensor, [MarshalAs(UnmanagedType.U1)] bool pivot, out IntPtr pPivots);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_matrix_norm_fronuc(IntPtr tensor, byte fronuc, IntPtr dim, int dim_length, [MarshalAs(UnmanagedType.U1)] bool keepdim);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_matrix_norm(IntPtr tensor, IntPtr ord, IntPtr dim, int dim_length, [MarshalAs(UnmanagedType.U1)] bool keepdim);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_matrix_rank(IntPtr tensor, double atol, [MarshalAs(UnmanagedType.U1)] bool has_atol, double rtol, [MarshalAs(UnmanagedType.U1)] bool has_rtol, [MarshalAs(UnmanagedType.U1)] bool hermitian);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_matrix_rank_tensor(IntPtr tensor, IntPtr atol, IntPtr rtol, [MarshalAs(UnmanagedType.U1)] bool hermitian);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_dot(IntPtr tensor, int len);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_multi_dot(IntPtr tensor, int len);\n\n [DllImport(\"LibTorchSharp\", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]\n internal static extern IntPtr THSLinalg_norm_str(IntPtr tensor, [MarshalAs(UnmanagedType.LPStr)] string p, IntPtr dim, int dim_length, [MarshalAs(UnmanagedType.U1)] bool keepdim);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_norm_float(IntPtr tensor, double p, IntPtr dim, int dim_length, [MarshalAs(UnmanagedType.U1)] bool keepdim);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_norm_int(IntPtr tensor, int p, IntPtr dim, int dim_length, [MarshalAs(UnmanagedType.U1)] bool keepdim);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_norm_opt(IntPtr tensor, IntPtr dim, int dim_length, [MarshalAs(UnmanagedType.U1)] bool keepdim);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_pinv(IntPtr tensor, double atol, [MarshalAs(UnmanagedType.U1)] bool has_atol, double rtol, [MarshalAs(UnmanagedType.U1)] bool has_rtol, [MarshalAs(UnmanagedType.U1)] bool hermitian);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_pinv_tensor(IntPtr tensor, IntPtr atol, IntPtr rtol, [MarshalAs(UnmanagedType.U1)] bool hermitian);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_qr(IntPtr tensor, byte mode, out IntPtr pR);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_solve(IntPtr tensor, IntPtr other, [MarshalAs(UnmanagedType.U1)] bool left);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_solve_ex(IntPtr tensor, IntPtr other, [MarshalAs(UnmanagedType.U1)] bool left, [MarshalAs(UnmanagedType.U1)] bool check_errors, out IntPtr infos);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_solve_triangular(IntPtr tensor, IntPtr other, [MarshalAs(UnmanagedType.U1)] bool upper, [MarshalAs(UnmanagedType.U1)] bool left, [MarshalAs(UnmanagedType.U1)] bool unitriangular);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_solve_triangular_out(IntPtr tensor, IntPtr other, [MarshalAs(UnmanagedType.U1)] bool upper, [MarshalAs(UnmanagedType.U1)] bool left, [MarshalAs(UnmanagedType.U1)] bool unitriangular, IntPtr _out);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_svd(IntPtr tensor, [MarshalAs(UnmanagedType.U1)] bool fullMatrices, out IntPtr pS, out IntPtr pVh);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_svdvals(IntPtr tensor);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_tensorinv(IntPtr tensor, long ind);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_tensorsolve(IntPtr tensor, IntPtr other, IntPtr dim, int dim_length);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_vector_norm(IntPtr tensor, IntPtr ord, IntPtr dim, int dim_length, [MarshalAs(UnmanagedType.U1)] bool keepdim);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_matrix_power(IntPtr tensor, long n);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_pinverse(IntPtr tensor, double rcond, [MarshalAs(UnmanagedType.U1)] bool hermitian);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_vander(IntPtr tensor, long N);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_vecdot(IntPtr x, IntPtr y, long dim, IntPtr output);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_lu_solve(IntPtr B, IntPtr LU, IntPtr pivots, [MarshalAs(UnmanagedType.U1)] bool left, [MarshalAs(UnmanagedType.U1)] bool adjoint, IntPtr output);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSLinalg_tensordot(IntPtr input1, IntPtr input2, IntPtr dims1, int dims1_length, IntPtr dims2, int dims2_length);\n }\n#pragma warning restore CA2101\n}\n" }, { "alpha_fraction": 0.7365591526031494, "alphanum_fraction": 0.7708333134651184, "avg_line_length": 56.269229888916016, "blob_id": "b80a330e1aa66c6562079c4f47a4e57a164dcbd5", "content_id": "c4d00be17cffa18409e0d993ccf868be25442bb2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1488, "license_type": "permissive", "max_line_length": 204, "num_lines": 26, "path": "/src/Native/LibTorchSharp/THSVision.h", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#pragma once\n\n#include \"../Stdafx.h\"\n\n#include \"torch/torch.h\"\n\n#include \"Utils.h\"\n\n// API\n\nEXPORT_API(Tensor) THSVision_AdjustHue(const Tensor img, const double hue_factor);\n\nEXPORT_API(Tensor) THSVision_GenerateAffineGrid(Tensor theta, const int64_t w, const int64_t h, const int64_t ow, const int64_t oh);\nEXPORT_API(Tensor) THSVision_ApplyGridTransform(Tensor i, Tensor g, const int8_t m, const float* fill, const int64_t fill_length);\n\nEXPORT_API(Tensor) THSVision_PerspectiveGrid(const float* coeffs, const int64_t coeffs_length, const int64_t ow, const int64_t oh, const int8_t scalar_type, const int device_type, const int device_index);\n\nEXPORT_API(Tensor) THSVision_ScaleChannel(Tensor ic);\n\nEXPORT_API(void) THSVision_ComputeOutputSize(const float* matrix, const int64_t matrix_length, const int64_t w, const int64_t h, int32_t* first, int32_t* second);\n\nEXPORT_API(void) THSVision_BRGA_RGB(const uint8_t* inputBytes, uint8_t* redBytes, uint8_t* greenBytes, uint8_t* blueBytes, int64_t inputChannelCount, int64_t imageSize);\nEXPORT_API(void) THSVision_BRGA_RGBA(const uint8_t* inputBytes, uint8_t* redBytes, uint8_t* greenBytes, uint8_t* blueBytes, uint8_t* alphaBytes, int64_t inputChannelCount, int64_t imageSize);\n\nEXPORT_API(void) THSVision_RGB_BRGA(const uint8_t* inputBytes, uint8_t* outBytes, int64_t inputChannelCount, int64_t imageSize);" }, { "alpha_fraction": 0.6682669520378113, "alphanum_fraction": 0.6692270636558533, "avg_line_length": 35.561405181884766, "blob_id": "93f1a1cf7619ff5937db70a53389a95d5d228d07", "content_id": "0a4c959fc485f6ae6ab2fa23bf807cb501e79c00", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2083, "license_type": "permissive", "max_line_length": 130, "num_lines": 57, "path": "/src/TorchSharp/DisposeScopeManager.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\n\n#nullable enable\nnamespace TorchSharp\n{\n /// <summary>\n /// Manages dispose scopes, that can make automatic tensor disposal easier. Note that the\n /// DisposeManager is thread local. The DisposeScopeManager can also manage other disposables, such as training\n /// batches and the like.\n /// </summary>\n public class DisposeScopeManager\n {\n [ThreadStatic] private static DisposeScopeManager? _threadSingleton;\n internal ThreadDisposeScopeStatistics StatisticsInstance { get; } = new ThreadDisposeScopeStatistics();\n\n internal static DisposeScopeManager ThreadSingleton => (_threadSingleton ??= new DisposeScopeManager());\n internal Stack<DisposeScope> DisposeScopeStack { get; } = new();\n\n public static ThreadDisposeScopeStatistics Statistics => ThreadSingleton.StatisticsInstance;\n\n internal DisposeScope? RegisterOnCurrentDisposeScope(IDisposable disposable)\n {\n if (DisposeScopeStack.Count == 0) {\n StatisticsInstance.CreatedOutsideScopeCount++;\n return null;\n }\n\n StatisticsInstance.CreatedInScopeCount++;\n var current = DisposeScopeStack.Peek();\n current.Include(disposable);\n return current;\n }\n\n internal static DisposeScope NewDisposeScope()\n {\n return ThreadSingleton.InnerNewDisposeScope();\n }\n\n internal void RemoveDisposeScope(DisposeScope disposeScope)\n {\n Debug.Assert(DisposeScopeStack.Count > 0);\n Debug.Assert(DisposeScopeStack.Peek() == disposeScope);\n DisposeScopeStack.Pop();\n }\n\n private DisposeScope InnerNewDisposeScope()\n {\n var disposeScope = new DisposeScope(this);\n DisposeScopeStack.Push(disposeScope);\n return disposeScope;\n }\n }\n}" }, { "alpha_fraction": 0.4377593398094177, "alphanum_fraction": 0.440248966217041, "avg_line_length": 26.089887619018555, "blob_id": "73f93464bf6cbbb6b2dd3326ff48d7517cbea865", "content_id": "4134ccc6837798d0cb8b902c375dab3841707fea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2410, "license_type": "permissive", "max_line_length": 81, "num_lines": 89, "path": "/src/TorchSharp/Utils/FisherYatesShuffler.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\n\nnamespace TorchSharp.Utils\n{\n public class FisherYatesShuffler : IEnumerable<long>\n {\n private long size;\n private int? seed;\n\n public FisherYatesShuffler(long size, int? seed = null)\n {\n this.size = size;\n this.seed = seed;\n }\n\n public IEnumerator<long> GetEnumerator()\n => seed == null\n ? new FisherYatesShufflerEnumerable(size)\n : new FisherYatesShufflerEnumerable(size, seed.Value);\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n private class FisherYatesShufflerEnumerable : IEnumerator<long>\n {\n public FisherYatesShufflerEnumerable(long size)\n {\n this.size = size;\n this.seed = null;\n Reset();\n }\n\n public FisherYatesShufflerEnumerable(long size, int seed)\n {\n this.size = size;\n this.seed = seed;\n Reset();\n }\n\n private int? seed;\n private long size;\n private Dictionary<long, long> indexs = new();\n private Random r;\n private long current = -1;\n\n public bool MoveNext()\n {\n current++;\n return current < size;\n }\n\n public void Reset()\n {\n r = seed == null ? new Random() : new Random(seed.Value);\n current = -1;\n indexs.Clear();\n for (var i = 0L; i < size; i++) {\n var rndidx = GetRandomLong(i);\n if (rndidx == i)\n indexs[i] = i;\n else {\n indexs[i] = indexs[rndidx];\n indexs[rndidx] = i;\n }\n }\n }\n\n public long Current => indexs[current];\n\n object IEnumerator.Current => Current;\n\n public void Dispose()\n {\n /* Ignore */\n }\n\n private long GetRandomLong(long l)\n {\n unchecked {\n return (((long) r.Next() << 32) + (uint) r.Next()) % (l + 1);\n }\n }\n }\n }\n}" }, { "alpha_fraction": 0.4176732301712036, "alphanum_fraction": 0.424348384141922, "avg_line_length": 33.206520080566406, "blob_id": "cac90bf025e2cfd5542bf0f7d098a570ad2b99f9", "content_id": "c54bbf60fdbfe161fff37cc08c13cd4037269ee6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3146, "license_type": "permissive", "max_line_length": 130, "num_lines": 92, "path": "/src/TorchSharp/ConsoleProgressBar.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Diagnostics;\n\nnamespace TorchSharp\n{\n internal class ConsoleProgressBar : IProgressBar\n {\n private const long DisplayEveryMilliseconds = 100;\n\n private readonly int _displayWidth;\n private readonly Stopwatch _stopWatch;\n private bool _hidden;\n private long _value;\n private long? _maximum;\n\n internal ConsoleProgressBar(bool hidden)\n {\n this._hidden = hidden;\n try {\n // This fails when console is not available.\n this._displayWidth = Console.BufferWidth;\n } catch {\n this._displayWidth = 80;\n }\n this._stopWatch = new Stopwatch();\n this._stopWatch.Start();\n }\n\n public long Value {\n set {\n if (value > this._maximum) {\n value = this._maximum.Value;\n }\n this._value = value;\n Display();\n }\n get {\n return _value;\n }\n }\n\n public long? Maximum {\n get {\n return _maximum;\n }\n set {\n if (value < this._value) {\n this._value = value.Value;\n }\n this._maximum = value;\n Display();\n }\n }\n\n public void Dispose()\n {\n if (!_hidden) {\n Console.Error.WriteLine();\n }\n }\n\n private void Display()\n {\n if (!_hidden) {\n if (_value == 0 || _value == _maximum || this._stopWatch.ElapsedMilliseconds > DisplayEveryMilliseconds) {\n this._stopWatch.Restart();\n if (this.Maximum == null) {\n Console.Error.Write(\"\\r{0}\", _value);\n } else {\n string left = string.Format(\"{0,3}%[\", 100 * _value / _maximum);\n string right = string.Format(\"] {0}/{1}\", _value, _maximum);\n int barContainerWidth = this._displayWidth - left.Length - right.Length - 1;\n string center = string.Empty;\n if (barContainerWidth > 0) {\n int barWidth = (int)(barContainerWidth * _value / _maximum);\n if (barWidth > 0) {\n center = new string('=', barWidth);\n if (this._displayWidth - barWidth > 0) {\n center += new string(' ', barContainerWidth - barWidth);\n }\n } else {\n center = new string(' ', barContainerWidth);\n }\n }\n Console.Error.Write(\"\\r{0}{1}{2}\", left, center, right);\n }\n }\n }\n }\n }\n}" }, { "alpha_fraction": 0.4960475564002991, "alphanum_fraction": 0.5081413388252258, "avg_line_length": 48.42070007324219, "blob_id": "4097f97cca7412692aa61b51b9535d9e70bdc698", "content_id": "fdbfb37be80812573ab6f389dc6981f05e264a41", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 29602, "license_type": "permissive", "max_line_length": 319, "num_lines": 599, "path": "/src/TorchAudio/Functional.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing static TorchSharp.torch;\nusing System.Diagnostics;\n\n// A number of implementation details in this file have been translated from the Python version of torchaudio,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/audio/blob/39c2c0a77e11b82ce152d60df3a92f6854d5f52b/torchaudio/functional/functional.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/audio/blob/main/LICENSE\n//\n\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n public static partial class functional\n {\n /// <summary>\n /// Compute spectrograms from audio signals.\n /// </summary>\n /// <param name=\"waveform\">The audio signal tensor</param>\n /// <param name=\"pad\">Padding on the sides</param>\n /// <param name=\"window\">The window function</param>\n /// <param name=\"n_fft\">The size of Fourier transform</param>\n /// <param name=\"hop_length\">The hop length</param>\n /// <param name=\"win_length\">The window length</param>\n /// <param name=\"power\">Exponent for the magnitude spectrogram</param>\n /// <param name=\"normalized\">Whether the output is normalized, or not.</param>\n /// <param name=\"center\">Whether the t-th frame is centered around t * hop_window, or not.</param>\n /// <param name=\"pad_mode\">The padding mode used when center is true.</param>\n /// <param name=\"onesided\">Whether the output is onesided or not.</param>\n /// <param name=\"return_complex\">Deprecated and not used.</param>\n /// <returns>Spectrograms of audio signals</returns>\n public static torch.Tensor spectrogram(torch.Tensor waveform, long pad, torch.Tensor window, long n_fft, long hop_length, long win_length, double? power, bool normalized, bool center = true, PaddingModes pad_mode = PaddingModes.Reflect, bool onesided = true, bool? return_complex = null)\n {\n using (var d = torch.NewDisposeScope()) {\n\n if (pad > 0) {\n // The original torchaudio doesn't have `torch.no_grad()' here to\n // avoid issues with JIT.\n // https://github.com/pytorch/audio/commit/a420cced7e60fcf9ba6efcff3a2e8bee3ac67d05#diff-ab14255549624af556aa0d1dfaf83241a95e05c3dd6a668cd2607655839f7a09\n using (torch.no_grad()) {\n waveform = torch.nn.functional.pad(waveform, new long[] { pad, pad }, PaddingModes.Constant);\n }\n }\n\n // pack batch\n var shape = waveform.size();\n waveform = waveform.reshape(-1, shape[shape.Length - 1]);\n\n // default values are consistent with librosa.core.spectrum._spectrogram\n var spec_f = torch.stft(\n input: waveform,\n n_fft: n_fft,\n hop_length: hop_length,\n win_length: win_length,\n window: window,\n center: center,\n pad_mode: pad_mode,\n normalized: false,\n onesided: onesided,\n return_complex: true);\n\n // unpack batch\n var spec_shape = new long[shape.Length + spec_f.dim() - 2];\n Array.Copy(shape, spec_shape, shape.Length - 1);\n Array.Copy(spec_f.shape, 1, spec_shape, shape.Length - 1, spec_f.dim() - 1);\n spec_f = spec_f.reshape(spec_shape);\n\n if (normalized) {\n spec_f /= window.pow(2.0).sum().sqrt();\n }\n\n if (power.HasValue) {\n if (power.Value == 1.0) {\n spec_f = spec_f.abs();\n } else {\n spec_f = spec_f.abs().pow(power.Value);\n }\n }\n\n return d.MoveToOuter(spec_f);\n }\n }\n\n /// <summary>\n /// Compute inverse of spectrogram.\n /// </summary>\n /// <param name=\"spectrogram\">The spectrogram tensor</param>\n /// <param name=\"length\">The length of the output tensor</param>\n /// <param name=\"pad\">Padding on the sides</param>\n /// <param name=\"window\">The window function</param>\n /// <param name=\"n_fft\">The size of Fourier transform</param>\n /// <param name=\"hop_length\">The hop length</param>\n /// <param name=\"win_length\">The window length</param>\n /// <param name=\"normalized\">Whether the output is normalized, or not.</param>\n /// <param name=\"center\">Whether the t-th frame is centered around t * hop_window, or not.</param>\n /// <param name=\"pad_mode\">The padding mode used when center is true.</param>\n /// <param name=\"onesided\">Whether the output is onesided or not.</param>\n /// <returns>Inverse of spectrogram</returns>\n public static torch.Tensor inverse_spectrogram(torch.Tensor spectrogram, long? length, long pad, torch.Tensor window, long n_fft, long hop_length, long win_length, bool normalized, bool center = true, PaddingModes pad_mode = PaddingModes.Reflect, bool onesided = true)\n {\n if (!spectrogram.is_complex()) {\n throw new ArgumentException(\"Expected `spectrogram` to be complex dtype.\");\n }\n\n using (var d = torch.NewDisposeScope()) {\n\n if (normalized) {\n spectrogram = spectrogram * window.pow(2.0).sum().sqrt();\n }\n\n // pack batch\n var shape = spectrogram.size();\n spectrogram = spectrogram.reshape(-1, shape[shape.Length - 2], shape[shape.Length - 1]);\n\n // default values are consistent with librosa.core.spectrum._spectrogram\n var waveform = torch.istft(\n input: spectrogram,\n n_fft: n_fft,\n hop_length: hop_length,\n win_length: win_length,\n window: window,\n center: center,\n normalized: false,\n onesided: onesided,\n length: length.HasValue ? length.Value + 2 * pad : -1,\n return_complex: false\n );\n\n if (length.HasValue && pad > 0) {\n // remove padding from front and back\n waveform = waveform[TensorIndex.Colon, TensorIndex.Slice(pad, -pad)];\n }\n\n // unpack batch\n var waveform_shape = new long[shape.Length - 1];\n Array.Copy(shape, waveform_shape, shape.Length - 2);\n waveform_shape[waveform_shape.Length - 1] = waveform.shape[waveform.dim() - 1];\n waveform = waveform.reshape(waveform_shape);\n\n return d.MoveToOuter(waveform);\n }\n }\n\n private static ScalarType _get_complex_dtype(torch.ScalarType real_dtype)\n {\n if (real_dtype == ScalarType.Float64)\n return ScalarType.ComplexFloat64;\n if (real_dtype == ScalarType.Float32)\n return ScalarType.ComplexFloat32;\n if (real_dtype == ScalarType.Float16)\n return ScalarType.ComplexFloat32;\n throw new ArgumentException($\"Unexpected dtype {real_dtype}\");\n }\n\n /// <summary>\n /// Compute waveform from a linear scale magnitude spectrogram using the Griffin-Lim transformation.\n /// </summary>\n /// <param name=\"specgram\">A magnitude-only STFT spectrogram of dimension `(..., freq, frames)` where freq is ``n_fft // 2 + 1``.</param>\n /// <param name=\"window\">Window tensor that is applied/multiplied to each frame/window</param>\n /// <param name=\"n_fft\">Size of FFT, creates ``n_fft // 2 + 1`` bins</param>\n /// <param name=\"hop_length\">Length of hop between STFT windows.</param>\n /// <param name=\"win_length\">Window size.</param>\n /// <param name=\"power\">Exponent for the magnitude spectrogram, (must be > 0) e.g., 1 for energy, 2 for power, etc.</param>\n /// <param name=\"n_iter\">Number of iteration for phase recovery process.</param>\n /// <param name=\"momentum\">The momentum parameter for fast Griffin-Lim.</param>\n /// <param name=\"length\">Array length of the expected output.</param>\n /// <param name=\"rand_init\">Initializes phase randomly if True, to zero otherwise.</param>\n /// <returns></returns>\n /// <exception cref=\"ArgumentOutOfRangeException\"></exception>\n public static Tensor griffinlim(Tensor specgram, Tensor window, long n_fft, long hop_length, long win_length, double power, int n_iter, double momentum, long? length, bool rand_init)\n {\n if (momentum < 0.0 || 1.0 <= momentum) {\n throw new ArgumentOutOfRangeException($\"momentum must be in range [0, 1). Found: {momentum}\");\n }\n momentum = momentum / (1 + momentum);\n\n // pack batch\n var shape = specgram.size();\n specgram = specgram.reshape(new long[] { -1, shape[shape.Length - 2], shape[shape.Length - 1] });\n\n specgram = specgram.pow(1 / power);\n\n // initialize the phase\n Tensor angles;\n if (rand_init) {\n angles = torch.rand(specgram.size(), dtype: _get_complex_dtype(specgram.dtype), device: specgram.device);\n } else {\n angles = torch.full(specgram.size(), 1, dtype: _get_complex_dtype(specgram.dtype), device: specgram.device);\n }\n\n // And initialize the previous iterate to 0\n var tprev = torch.tensor(0.0, dtype: specgram.dtype, device: specgram.device);\n for (int i = 0; i < n_iter; i++) {\n // Invert with our current estimate of the phases\n var inverse = torch.istft(\n specgram * angles, n_fft: n_fft, hop_length: hop_length, win_length: win_length, window: window, length: length ?? -1\n );\n\n // Rebuild the spectrogram\n var rebuilt = torch.stft(\n input: inverse,\n n_fft: n_fft,\n hop_length: hop_length,\n win_length: win_length,\n window: window,\n center: true,\n pad_mode: PaddingModes.Reflect,\n normalized: false,\n onesided: true,\n return_complex: true);\n\n // Update our phase estimates\n angles = rebuilt;\n if (momentum > 0.0) {\n angles = angles - tprev.mul_(momentum);\n }\n angles = angles.div(angles.abs().add(1e-16));\n\n // Store the previous iterate\n tprev = rebuilt;\n }\n\n // Return the final phase estimates\n var waveform = torch.istft(\n specgram * angles, n_fft: n_fft, hop_length: hop_length, win_length: win_length, window: window, length: length ?? -1\n );\n\n // unpack batch\n var new_shape = new long[shape.Length - 1];\n Array.Copy(shape, new_shape, shape.Length - 2);\n new_shape[new_shape.Length - 1] = waveform.shape[waveform.dim() - 1];\n waveform = waveform.reshape(new_shape);\n\n return waveform;\n }\n\n /// <summary>\n /// Turn a spectrogram from the power/amplitude scale to the decibel scale.\n /// </summary>\n /// <param name=\"x\">Input spectrogram(s) before being converted to decibel scale.</param>\n /// <param name=\"multiplier\">Use 10. for power and 20. for amplitude</param>\n /// <param name=\"amin\">Number to clamp x</param>\n /// <param name=\"db_multiplier\">Log10(max(reference value and amin))</param>\n /// <param name=\"top_db\">Minimum negative cut-off in decibels.</param>\n /// <returns>Output tensor in decibel scale</returns>\n public static Tensor amplitude_to_DB(Tensor x, double multiplier, double amin, double db_multiplier, double? top_db = null)\n {\n var x_db = multiplier * torch.log10(torch.clamp(x, min: amin));\n x_db -= multiplier * db_multiplier;\n\n if (top_db != null) {\n // Expand batch\n var shape = x_db.size();\n var packed_channels = x_db.dim() > 2 ? shape[shape.Length - 3] : 1;\n x_db = x_db.reshape(-1, packed_channels, shape[shape.Length - 2], shape[shape.Length - 1]);\n\n x_db = torch.maximum(x_db, (x_db.amax(dims: new long[] { -3, -2, -1 }) - top_db).view(-1, 1, 1, 1));\n\n // Repack batch\n x_db = x_db.reshape(shape);\n }\n return x_db;\n }\n\n /// <summary>\n /// Turn a tensor from the decibel scale to the power/amplitude scale.\n /// </summary>\n /// <param name=\"x\">Input tensor before being converted to power/amplitude scale.</param>\n /// <param name=\"ref\">Reference which the output will be scaled by.</param>\n /// <param name=\"power\">If power equals 1, will compute DB to power. If 0.5, will compute DB to amplitude.</param>\n /// <returns>Output tensor in power/amplitude scale.</returns>\n public static Tensor DB_to_amplitude(Tensor x, double @ref, double power)\n {\n return @ref * torch.pow(torch.pow(10.0, 0.1 * x), power);\n }\n\n private static double _hz_to_mel(double freq, MelScale mel_scale = MelScale.htk)\n {\n if (mel_scale == MelScale.htk) {\n return 2595.0 * Math.Log10(1.0 + freq / 700.0);\n }\n\n // Fill in the linear part\n var f_min = 0.0;\n var f_sp = 200.0 / 3;\n\n var mels = (freq - f_min) / f_sp;\n\n // Fill in the log-scale part\n var min_log_hz = 1000.0;\n var min_log_mel = (min_log_hz - f_min) / f_sp;\n var logstep = Math.Log(6.4) / 27.0;\n\n if (freq >= min_log_hz) {\n mels = min_log_mel + Math.Log(freq / min_log_hz) / logstep;\n }\n\n return mels;\n }\n\n private static Tensor _mel_to_hz(Tensor mels, MelScale mel_scale = MelScale.htk)\n {\n if (mel_scale == MelScale.htk) {\n return 700.0 * (torch.pow(10.0, mels / 2595.0) - 1.0);\n }\n\n // Fill in the linear scale\n var f_min = 0.0;\n var f_sp = 200.0 / 3;\n\n var freqs = f_min + f_sp * mels;\n\n // And now the nonlinear scale\n var min_log_hz = 1000.0;\n var min_log_mel = (min_log_hz - f_min) / f_sp;\n var logstep = Math.Log(6.4) / 27.0;\n\n var log_t = mels >= min_log_mel;\n freqs[log_t] = min_log_hz * torch.exp(logstep * (mels[log_t] - min_log_mel));\n\n return freqs;\n }\n\n private static Tensor _create_triangular_filterbank(Tensor all_freqs, Tensor f_pts)\n {\n // Adopted from Librosa\n // calculate the difference between each filter mid point and each stft freq point in hertz\n var f_diff = f_pts[TensorIndex.Slice(1, null)] - f_pts[TensorIndex.Slice(null, -1)]; // (n_filter + 1)\n var slopes = f_pts.unsqueeze(0) - all_freqs.unsqueeze(1); // (n_freqs, n_filter + 2)\n // create overlapping triangles\n var zero = torch.zeros(1);\n var down_slopes = (-1.0 * slopes[TensorIndex.Colon, TensorIndex.Slice(null, -2)]) / f_diff[TensorIndex.Slice(null, -1)]; // (n_freqs, n_filter)\n var up_slopes = slopes[TensorIndex.Colon, TensorIndex.Slice(2, null)] / f_diff[TensorIndex.Slice(1, null)]; // (n_freqs, n_filter)\n var fb = torch.maximum(zero, torch.minimum(down_slopes, up_slopes));\n\n return fb;\n }\n\n /// <summary>\n /// Create a frequency bin conversion matrix.\n /// </summary>\n /// <param name=\"n_freqs\">Number of frequencies to highlight/apply</param>\n /// <param name=\"f_min\">Minimum frequency(Hz)</param>\n /// <param name=\"f_max\">Maximum frequency(Hz)</param>\n /// <param name=\"n_mels\">Number of mel filterbanks</param>\n /// <param name=\"sample_rate\">Sample rate of the audio waveform</param>\n /// <param name=\"norm\">If MelNorm.slaney, divide the triangular mel weights by the width of the mel band</param>\n /// <param name=\"mel_scale\">Scale to use</param>\n /// <returns>Triangular filter banks</returns>\n public static Tensor melscale_fbanks(long n_freqs, double f_min, double f_max, long n_mels, long sample_rate, MelNorm norm = MelNorm.none, MelScale mel_scale = MelScale.htk)\n {\n // freq bins\n var all_freqs = torch.linspace(0, sample_rate / 2, n_freqs);\n\n // calculate mel freq bins\n var m_min = _hz_to_mel(f_min, mel_scale: mel_scale);\n var m_max = _hz_to_mel(f_max, mel_scale: mel_scale);\n\n var m_pts = torch.linspace(m_min, m_max, n_mels + 2);\n var f_pts = _mel_to_hz(m_pts, mel_scale: mel_scale);\n\n // create filterbank\n var fb = _create_triangular_filterbank(all_freqs, f_pts);\n\n if (norm == MelNorm.slaney) {\n // Slaney-style mel is scaled to be approx constant energy per channel\n var enorm = 2.0 / (f_pts[TensorIndex.Slice(2, n_mels + 2)] - f_pts[TensorIndex.Slice(null, n_mels)]);\n fb *= enorm.unsqueeze(0);\n }\n\n if ((fb.max(dim: 0).values == 0.0).any().item<bool>()) {\n Debug.Print(\n \"At least one mel filterbank has all zero values. \" +\n $\"The value for `n_mels` ({n_mels}) may be set too high. \" +\n $\"Or, the value for `n_freqs` ({n_freqs}) may be set too low.\"\n );\n }\n\n return fb;\n }\n\n /// <summary>\n /// Creates a linear triangular filterbank.\n /// </summary>\n /// <param name=\"n_freqs\">Number of frequencies to highlight/apply</param>\n /// <param name=\"f_min\">Minimum frequency (Hz)</param>\n /// <param name=\"f_max\">Maximum frequency (Hz)</param>\n /// <param name=\"n_filter\">Number of (linear) triangular filter</param>\n /// <param name=\"sample_rate\">Sample rate of the audio waveform</param>\n /// <returns>Triangular filter banks</returns>\n public static Tensor linear_fbanks(int n_freqs, double f_min, double f_max, int n_filter, int sample_rate)\n {\n // freq bins\n var all_freqs = torch.linspace(0, sample_rate / 2, n_freqs);\n\n // filter mid-points\n var f_pts = torch.linspace(f_min, f_max, n_filter + 2);\n\n // create filterbank\n var fb = _create_triangular_filterbank(all_freqs, f_pts);\n\n return fb;\n }\n\n /// <summary>\n /// Create a DCT transformation matrix with shape (``n_mels``, ``n_mfcc``)\n /// </summary>\n /// <param name=\"n_mfcc\">Number of mfc coefficients to retain</param>\n /// <param name=\"n_mels\">Number of mel filterbanks</param>\n /// <param name=\"norm\">Norm to use</param>\n /// <returns>The transformation matrix</returns>\n public static Tensor create_dct(int n_mfcc, int n_mels, DCTNorm norm)\n {\n // http://en.wikipedia.org/wiki/Discrete_cosine_transform#DCT-II\n var n = torch.arange((float)n_mels);\n var k = torch.arange((float)n_mfcc).unsqueeze(1);\n var dct = torch.cos(Math.PI / n_mels * (n + 0.5) * k);\n\n if (norm == DCTNorm.none) {\n dct *= 2.0;\n } else {\n dct[0] *= 1.0 / Math.Sqrt(2.0);\n dct *= Math.Sqrt(2.0 / n_mels);\n }\n return dct.t();\n }\n\n /// <summary>\n /// Encode signal based on mu-law companding.\n /// </summary>\n /// <param name=\"x\">Input tensor</param>\n /// <param name=\"quantization_channels\">Number of channels</param>\n /// <returns>Input after mu-law encoding</returns>\n /// <exception cref=\"ArgumentException\"></exception>\n public static Tensor mu_law_encoding(Tensor x, int quantization_channels)\n {\n if (!x.is_floating_point()) {\n throw new ArgumentException(\"The input Tensor must be of floating type. \");\n }\n var mu = torch.tensor(quantization_channels - 1.0, dtype: x.dtype);\n var x_mu = torch.sign(x) * torch.log1p(mu * torch.abs(x)) / torch.log1p(mu);\n x_mu = ((x_mu + 1) / 2 * mu + 0.5).to(torch.int64);\n return x_mu;\n }\n\n /// <summary>\n /// Decode mu-law encoded signal.\n /// </summary>\n /// <param name=\"x_mu\">Input tensor</param>\n /// <param name=\"quantization_channels\">Number of channels</param>\n /// <returns>Input after mu-law decoding</returns>\n public static Tensor mu_law_decoding(Tensor x_mu, int quantization_channels)\n {\n if (!x_mu.is_floating_point()) {\n x_mu = x_mu.to(torch.@float);\n }\n var mu = torch.tensor(quantization_channels - 1.0, dtype: x_mu.dtype);\n var x = x_mu / mu * 2 - 1.0;\n x = torch.sign(x) * (torch.exp(torch.abs(x) * torch.log1p(mu)) - 1.0) / mu;\n return x;\n }\n\n /// <summary>\n /// Resample the waveform\n /// </summary>\n /// <param name=\"waveform\">The input waveform</param>\n /// <param name=\"orig_freq\">The source sampling rate</param>\n /// <param name=\"new_freq\">The destination sampling rate</param>\n /// <param name=\"lowpass_filter_width\">The width of the filter</param>\n /// <param name=\"rolloff\">The roll-off frequency</param>\n /// <param name=\"resampling_method\">The resampling method</param>\n /// <param name=\"beta\">Beta for Keizer window</param>\n /// <returns>The resampled waveform</returns>\n /// <exception cref=\"ArgumentOutOfRangeException\"></exception>\n public static torch.Tensor resample(torch.Tensor waveform, int orig_freq, int new_freq, int lowpass_filter_width = 6, double rolloff = 0.99, ResamplingMethod resampling_method = ResamplingMethod.sinc_interpolation, double? beta = null)\n {\n if (orig_freq <= 0 || new_freq <= 0) {\n throw new ArgumentOutOfRangeException();\n }\n\n using (var d = torch.NewDisposeScope()) {\n if (orig_freq == new_freq) {\n return d.MoveToOuter(waveform.alias());\n }\n\n int gcd = Gcd(orig_freq, new_freq);\n\n var (kernel, width) = _get_sinc_resample_kernel(\n orig_freq,\n new_freq,\n gcd,\n lowpass_filter_width,\n rolloff,\n resampling_method,\n beta,\n waveform.device,\n waveform.dtype);\n var resampled = _apply_sinc_resample_kernel(waveform, orig_freq, new_freq, gcd, kernel, width);\n return d.MoveToOuter(resampled);\n }\n }\n\n internal static int Gcd(int a, int b)\n {\n if (a <= 0 || b <= 0) {\n throw new ArgumentOutOfRangeException();\n }\n\n while (b > 1) {\n (a, b) = (b, a % b);\n }\n\n return a;\n }\n\n internal static (torch.Tensor, int) _get_sinc_resample_kernel(int orig_freq, int new_freq, int gcd, int lowpass_filter_width = 6, double rolloff = 0.99, ResamplingMethod resampling_method = ResamplingMethod.sinc_interpolation, double? beta = null, torch.Device device = null, torch.ScalarType? dtype = null)\n {\n orig_freq = orig_freq / gcd;\n new_freq = new_freq / gcd;\n\n if (lowpass_filter_width <= 0) {\n throw new ArgumentOutOfRangeException();\n }\n\n var kernels_list = new List<torch.Tensor>();\n double base_freq = Math.Min(orig_freq, new_freq);\n base_freq *= rolloff;\n\n var width = (int)Math.Ceiling(((double)lowpass_filter_width) * orig_freq / base_freq);\n var idx_dtype = dtype ?? torch.float64;\n var idx = torch.arange(-width, width + orig_freq, device: device, dtype: idx_dtype);\n\n for (int i = 0; i < new_freq; i++) {\n var t = (-i / new_freq + idx / orig_freq) * base_freq;\n t = t.clamp_(-lowpass_filter_width, lowpass_filter_width);\n\n torch.Tensor window;\n if (resampling_method == ResamplingMethod.sinc_interpolation) {\n window = torch.square(torch.cos(t * Math.PI / lowpass_filter_width / 2));\n } else {\n // kaiser_window\n if (!beta.HasValue) {\n beta = 14.769656459379492;\n }\n var beta_tensor = torch.tensor(beta.Value);\n window = torch.special.i0(beta_tensor * torch.sqrt(1 - torch.square(t / lowpass_filter_width))) / torch.special.i0(beta_tensor);\n }\n t *= Math.PI;\n // Tensor.to(Tensor) of TorchSharp desn't change dtype.\n var kernel = torch.where(t == 0, torch.tensor(1.0).to(t).type_as(t), torch.sin(t) / t);\n kernel.mul_(window);\n kernels_list.Add(kernel);\n }\n\n var scale = ((double)base_freq) / orig_freq;\n var kernels = torch.stack(kernels_list.ToArray()).view(new_freq, 1, -1).mul_(scale);\n if (dtype == null) {\n kernels = kernels.to(torch.float32);\n }\n return (kernels, width);\n }\n\n internal static torch.Tensor _apply_sinc_resample_kernel(torch.Tensor waveform, int orig_freq, int new_freq, int gcd, torch.Tensor kernel, int width)\n {\n if (!waveform.is_floating_point()) {\n throw new ArgumentException($\"Expected floating point type for waveform tensor, but received {waveform.dtype}.\");\n }\n\n orig_freq = orig_freq / gcd;\n new_freq = new_freq / gcd;\n\n // pack batch\n var shape = waveform.size();\n waveform = waveform.view(-1, shape[waveform.dim() - 1]);\n\n var num_wavs = waveform.shape[0];\n var length = waveform.shape[1];\n\n waveform = torch.nn.functional.pad(waveform, (width, width + orig_freq));\n var resampled = torch.nn.functional.conv1d(waveform.unsqueeze(1), kernel, stride: orig_freq);\n resampled = resampled.transpose(1, 2).reshape(num_wavs, -1);\n int target_length = (int)Math.Ceiling(((double)new_freq) * length / orig_freq);\n resampled = resampled[TensorIndex.Ellipsis, TensorIndex.Slice(0, target_length)];\n\n // unpack batch\n shape[shape.Length - 1] = resampled.shape[resampled.dim() - 1];\n resampled = resampled.view(shape);\n return resampled;\n }\n }\n }\n}" }, { "alpha_fraction": 0.5502307415008545, "alphanum_fraction": 0.5512956976890564, "avg_line_length": 39.826087951660156, "blob_id": "3db6efef8640e9c424e98f2384dd2cf400fe4428", "content_id": "e6d3f120a3326d8e31c29798c867fef4f4e3138c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2817, "license_type": "permissive", "max_line_length": 193, "num_lines": 69, "path": "/src/TorchSharp/NN/PixelUnshuffle.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a dropout module.\n /// </summary>\n public sealed class PixelUnshuffle : torch.nn.Module<Tensor, Tensor>\n {\n internal PixelUnshuffle(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n /// <summary>\n /// Forward pass.\n /// </summary>\n /// <param name=\"tensor\">Input tensor</param>\n /// <returns></returns>\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_PixelUnshuffle_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n\n /// <summary>\n /// Reverses the PixelShuffle operation by rearranging elements in a tensor of shape (*, C, H * r, W * r) to a tensor of shape (*, C * r^2, H, W), where r is an downscale factor.\n /// </summary>\n /// <param name=\"downscaleFactor\">Factor to increase spatial resolution by</param>\n /// <returns></returns>\n public static PixelUnshuffle PixelUnshuffle(long downscaleFactor)\n {\n var handle = THSNN_PixelUnshuffle_ctor(downscaleFactor, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new PixelUnshuffle(handle, boxedHandle);\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Reverses the PixelShuffle operation by rearranging elements in a tensor of shape (*, C * r^2, H, W) to a tensor of shape(*, C, H * r, W * r), where r is an downscale factor.\n /// This is useful for implementing efficient sub-pixel convolution with a stride of 1/r.\n /// </summary>\n /// <param name=\"x\">Input tensor</param>\n /// <param name=\"downscaleFactor\">Factor to increase spatial resolution by</param>\n /// <returns></returns>\n /// <returns></returns>\n public static Tensor pixel_unshuffle(Tensor x, long downscaleFactor)\n {\n using (var d = nn.PixelUnshuffle(downscaleFactor)) {\n return d.call(x);\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6845647096633911, "alphanum_fraction": 0.7034650444984436, "avg_line_length": 20.426380157470703, "blob_id": "2cc99c44c7be80d3c878641ec9ecbf45d26ef6aa", "content_id": "b846557bc05ce1a8a6bb4a97b9a8a32c1f708331", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6984, "license_type": "permissive", "max_line_length": 130, "num_lines": 326, "path": "/src/Native/LibTorchSharp/THSTorch.cpp", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#include \"THSTorch.h\"\n\n#include \"torch/torch.h\"\n#include \"torch/cuda.h\"\n\nvoid THSTorch_manual_seed(const int64_t seed)\n{\n torch::manual_seed(seed);\n}\n\nGenerator THSGenerator_manual_seed(const int64_t seed)\n{\n auto gen = at::globalContext().defaultGenerator(at::DeviceType::CPU);\n gen.set_current_seed(seed);\n return new at::Generator(gen.getIntrusivePtr());\n}\n\nvoid THSCuda_manual_seed(const int64_t seed)\n{\n CATCH(torch::cuda::manual_seed(seed);)\n}\n\nvoid THSCuda_manual_seed_all(const int64_t seed)\n{\n CATCH(torch::cuda::manual_seed_all(seed);)\n}\n\nbool THSBackend_cublas_get_allow_tf32()\n{\n auto result = false;\n CATCH(result = at::globalContext().allowTF32CuBLAS(););\n return result;\n}\n\nvoid THSBackend_cublas_set_allow_tf32(const bool flag)\n{\n CATCH(at::globalContext().setAllowTF32CuBLAS(flag););\n}\n\nbool THSBackend_cudnn_get_allow_tf32()\n{\n auto result = false;\n CATCH(result = at::globalContext().allowTF32CuDNN(););\n return result;\n}\n\nvoid THSBackend_cudnn_set_allow_tf32(const bool flag)\n{\n CATCH(at::globalContext().setAllowTF32CuDNN(flag););\n}\n\nbool THSBackend_cuda_get_allow_fp16_reduced_precision_reduction()\n{\n auto result = false;\n CATCH(result = at::globalContext().allowFP16ReductionCuBLAS(););\n return result;\n}\n\nvoid THSBackend_cuda_set_allow_fp16_reduced_precision_reduction(const bool flag)\n{\n CATCH(at::globalContext().setAllowFP16ReductionCuBLAS(flag););\n}\n\nbool THSBackend_cuda_get_enable_flash_sdp()\n{\n auto result = false;\n CATCH(result = at::globalContext().userEnabledFlashSDP(););\n return result;\n}\n\nvoid THSBackend_cuda_set_enable_flash_sdp(const bool flag)\n{\n CATCH(at::globalContext().setSDPUseFlash(flag););\n}\n\nbool THSBackend_cuda_get_enable_math_sdp()\n{\n auto result = false;\n CATCH(result = at::globalContext().userEnabledMathSDP(););\n return result;\n}\n\nvoid THSBackend_cuda_set_enable_math_sdp(const bool flag)\n{\n CATCH(at::globalContext().setSDPUseMath(flag););\n}\n\nvoid THSGenerator_gen_manual_seed(const Generator generator, const int64_t seed)\n{\n generator->set_current_seed(seed);\n}\n\nGenerator THSGenerator_default_generator()\n{\n auto gen = at::globalContext().defaultGenerator(at::DeviceType::CPU);\n return new at::Generator(gen.getIntrusivePtr());\n}\n\nint64_t THSGenerator_initial_seed(const Generator gen)\n{\n return gen->current_seed();\n}\n\nTensor THSGenerator_get_rng_state(const Generator gen)\n{\n CATCH_TENSOR(gen->get_state());\n}\n\nvoid THSGenerator_set_rng_state(const Generator gen, const Tensor tensor)\n{\n gen->set_state(*tensor);\n}\n\n\nGenerator THSGenerator_new(uint64_t seed, int64_t device, int64_t index)\n{\n // TODO: Support creation of GPU RNGs. 'device' and 'index' are in the\n // function signature in preparation thereof.\n return new at::Generator(at::detail::createCPUGenerator(seed));\n}\n\nvoid THSGenerator_dispose(const Generator generator)\n{\n delete generator;\n}\n\nint THSTorchCuda_is_available()\n{\n return torch::cuda::is_available();\n}\n\nint THSTorchCuda_cudnn_is_available()\n{\n return torch::cuda::cudnn_is_available();\n}\n\nint THSTorchCuda_device_count()\n{\n return (int)torch::cuda::device_count();\n}\n\nvoid THSTorchCuda_synchronize(const int64_t device_index)\n{\n CATCH(torch::cuda::synchronize(device_index);)\n}\n\n\nconst char * THSTorch_get_and_reset_last_err()\n{\n char *tmp = torch_last_err;\n torch_last_err = nullptr;\n return tmp;\n}\n\nint THSTorch_get_num_threads()\n{\n CATCH_RETURN_RES(int, -1, res = torch::get_num_threads());\n}\n\nvoid THSTorch_set_num_threads(const int threads)\n{\n torch::set_num_threads(threads);\n}\n\nint THSTorch_get_num_interop_threads()\n{\n CATCH_RETURN_RES(int, -1, res = torch::get_num_interop_threads());\n}\n\nvoid THSTorch_set_num_interop_threads(const int threads)\n{\n torch::set_num_interop_threads(threads);\n}\n\nint THSTorch_can_cast(const int type1, const int type2)\n{\n CATCH_RETURN_RES(int, -1, res = (int)torch::can_cast((c10::ScalarType)type1, (c10::ScalarType)type2));\n}\n\nint THSTorch_promote_types(const int type1, const int type2)\n{\n CATCH_RETURN_RES(int, -1, res = (int)torch::promote_types((c10::ScalarType)type1, (c10::ScalarType)type2));\n}\n\n\nScalar THSTorch_int8_to_scalar(int8_t value)\n{\n return new torch::Scalar(value);\n}\n\nScalar THSTorch_uint8_to_scalar(uint8_t value)\n{\n return new torch::Scalar(value);\n}\n\nScalar THSTorch_int16_to_scalar(short value)\n{\n return new torch::Scalar(value);\n}\n\nScalar THSTorch_int32_to_scalar(int value)\n{\n return new torch::Scalar(value);\n}\n\nScalar THSTorch_int64_to_scalar(long value)\n{\n return new torch::Scalar(int64_t(value));\n}\n\nScalar THSTorch_float32_to_scalar(float value)\n{\n return new torch::Scalar(value);\n}\n\nScalar THSTorch_float64_to_scalar(double value)\n{\n return new torch::Scalar(value);\n}\n\nScalar THSTorch_float16_to_scalar(float value)\n{\n return new torch::Scalar((c10::Half)value);\n}\n\nScalar THSTorch_bfloat16_to_scalar(float value)\n{\n return new torch::Scalar((c10::BFloat16)value);\n}\n\nScalar THSTorch_bool_to_scalar(bool value)\n{\n return new torch::Scalar(value);\n}\n\nScalar THSTorch_complex32_to_scalar(float real, float imaginary)\n{\n return new torch::Scalar(c10::complex<float>(real, imaginary));\n}\n\nScalar THSTorch_complex64_to_scalar(double real, double imaginary)\n{\n return new torch::Scalar(c10::complex<double>(real, imaginary));\n}\n\nint8_t THSTorch_scalar_to_int8(Scalar value)\n{\n return value->toChar();\n}\n\nuint8_t THSTorch_scalar_to_uint8(Scalar value)\n{\n return value->toByte();\n}\n\nint16_t THSTorch_scalar_to_int16(Scalar value)\n{\n return value->toShort();\n}\n\nint32_t THSTorch_scalar_to_int32(Scalar value)\n{\n return value->toInt();\n}\n\nint64_t THSTorch_scalar_to_int64(Scalar value)\n{\n return value->toLong();\n}\n\nfloat THSTorch_scalar_to_float32(Scalar value)\n{\n return value->toFloat();\n}\n\ndouble THSTorch_scalar_to_float64(Scalar value)\n{\n return value->toDouble();\n}\n\nvoid THSTorch_scalar_to_float16(Scalar value, unsigned short *res)\n{\n *res = value->toHalf().x;\n}\n\nvoid THSTorch_scalar_to_complex32(Scalar value, float* (*allocator)(size_t length))\n{\n auto result = value->toComplexFloat();\n auto space = allocator(2);\n space[0] = result.real();\n space[1] = result.imag();\n}\n\nvoid THSTorch_scalar_to_complex64(Scalar value, double* (*allocator)(size_t length))\n{\n auto result = value->toComplexDouble();\n auto space = allocator(2);\n space[0] = result.real();\n space[1] = result.imag();\n}\n\nbool THSTorch_scalar_to_bool(Scalar value)\n{\n return value->toBool();\n}\n\nint8_t THSTorch_scalar_type(Scalar value)\n{\n return (int8_t)value->type();\n}\n\nvoid THSTorch_dispose_scalar(Scalar scalar)\n{\n delete scalar;\n}\n\ndouble THSSpecial_erf_scalar(const double x)\n{\n return erf(x);\n}\n\ndouble THSSpecial_erfc_scalar(const double x)\n{\n return erfc(x);\n}" }, { "alpha_fraction": 0.5176693797111511, "alphanum_fraction": 0.5251898169517517, "avg_line_length": 55.82987594604492, "blob_id": "b79b20c440ec1ec6fbeabd62d535f32071a5bfdb", "content_id": "144dab863ca37abb4052b8dedf942dadd4bde27d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 13699, "license_type": "permissive", "max_line_length": 318, "num_lines": 241, "path": "/src/TorchSharp/NN/Pooling/AvgPool2D.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a AvgPool2D module.\n /// </summary>\n public sealed class AvgPool2d : torch.nn.Module<Tensor, Tensor>\n {\n internal AvgPool2d(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_AvgPool2d_forward(handle.DangerousGetHandle(), tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies a 2D average pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"kernel_size\">The size of the window</param>\n /// <param name=\"strides\">The stride of the window. Default value is kernel_size</param>\n /// <param name=\"padding\">implicit zero padding to be added on both sides</param>\n /// <param name=\"ceil_mode\">Whether to use ceil instead of floor to compute the output shape</param>\n /// <param name=\"count_include_pad\">Whether to include the zero-padding in the averaging calculation</param>\n /// <param name=\"divisor_override\">If specified, it will be used as divisor, otherwise size of the pooling region will be used</param>\n public static unsafe AvgPool2d AvgPool2d(long[] kernel_size, long[] strides = null, long[] padding = null, bool ceil_mode = false, bool count_include_pad = true, long? divisor_override = null)\n {\n fixed (long* pkernelSize = kernel_size, pstrides = strides, ppadding = padding) {\n var handle = THSNN_AvgPool2d_ctor((IntPtr)pkernelSize, kernel_size.Length, (IntPtr)pstrides, (strides == null ? 0 : strides.Length), (IntPtr)ppadding, (padding == null ? 0 : padding.Length), ceil_mode, count_include_pad, divisor_override.HasValue ? divisor_override.Value : 0, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new AvgPool2d(handle, boxedHandle);\n }\n }\n\n /// <summary>\n /// Applies a 2D average pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"kernel_size\">The size of the window</param>\n /// <param name=\"stride\">The stride of the window.</param>\n /// <param name=\"padding\">implicit zero padding to be added on both sides</param>\n /// <param name=\"ceil_mode\">Whether to use ceil instead of floor to compute the output shape</param>\n /// <param name=\"count_include_pad\">Whether to include the zero-padding in the averaging calculation</param>\n /// <param name=\"divisor_override\">If specified, it will be used as divisor, otherwise size of the pooling region will be used</param>\n public static unsafe AvgPool2d AvgPool2d((long,long) kernel_size, (long,long)? stride = null, (long,long)? padding = null, bool ceil_mode = false, bool count_include_pad = true, long? divisor_override = null)\n {\n long svalue1 = (stride == null) ? kernel_size.Item1 : stride.Value.Item1;\n long svalue2 = (stride == null) ? kernel_size.Item2 : stride.Value.Item2;\n\n long pvalue1 = (padding == null) ? 0 : stride.Value.Item1;\n long pvalue2 = (padding == null) ? 0 : stride.Value.Item2;\n\n long* pkernelSize = stackalloc long[2] { kernel_size.Item1, kernel_size.Item2 };\n long* pstrides = stackalloc long[2] { svalue1, svalue2 };\n long* ppadding = stackalloc long[2] { pvalue1, pvalue2 };\n\n var handle = THSNN_AvgPool2d_ctor((IntPtr)pkernelSize, 2, (IntPtr)pstrides, 2, (IntPtr)ppadding, 2, ceil_mode, count_include_pad, divisor_override.HasValue ? divisor_override.Value : 0, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new AvgPool2d(handle, boxedHandle);\n }\n\n /// <summary>\n /// Applies a 2D average pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"kernel_size\">The size of the window</param>\n /// <param name=\"stride\">The stride of the window.</param>\n /// <param name=\"padding\">implicit zero padding to be added on both sides</param>\n /// <param name=\"ceil_mode\">Whether to use ceil instead of floor to compute the output shape</param>\n /// <param name=\"count_include_pad\">Whether to include the zero-padding in the averaging calculation</param>\n /// <param name=\"divisor_override\">If specified, it will be used as divisor, otherwise size of the pooling region will be used</param>\n public static unsafe AvgPool2d AvgPool2d(long kernel_size, long? stride = null, long? padding = null, bool ceil_mode = false, bool count_include_pad = true, long? divisor_override = null)\n {\n long svalue = (stride == null) ? kernel_size : stride.Value;\n long pvalue = (padding == null) ? 0 : padding.Value;\n\n long* pkernelSize = stackalloc long[2] { kernel_size, kernel_size };\n long* pstrides = stackalloc long[2] { svalue, svalue };\n long* ppadding = stackalloc long[2] { pvalue, pvalue };\n\n var handle = THSNN_AvgPool2d_ctor((IntPtr)pkernelSize, 2, (IntPtr)pstrides, 2, (IntPtr)ppadding, 2, ceil_mode, count_include_pad, divisor_override.HasValue ? divisor_override.Value : 0, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new AvgPool2d(handle, boxedHandle);\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Applies 2D average-pooling operation in kH × kW regions by step size sH * sW steps. The number of output features is equal to the number of input planes.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"kernelSizes\"></param>\n /// <param name=\"strides\"></param>\n /// <param name=\"paddings\"></param>\n /// <param name=\"ceil_mode\"></param>\n /// <param name=\"count_include_pad\"></param>\n /// <returns></returns>\n public static Tensor avg_pool2d(Tensor input, long[] kernelSizes,\n long[] strides = null,\n long[] paddings = null,\n bool ceil_mode = false,\n bool count_include_pad = true)\n {\n strides = (strides == null) ? new long[] { 1 } : strides;\n paddings = (paddings == null) ? new long[] { 0 } : paddings;\n unsafe {\n fixed (long* pkernelSize = kernelSizes, pstrides = strides, ppadding = paddings) {\n var res =\n THSTensor_avg_pool2d(input.Handle,\n (IntPtr)pkernelSize, kernelSizes.Length,\n (IntPtr)pstrides, strides.Length,\n (IntPtr)ppadding, paddings.Length,\n ceil_mode,\n count_include_pad);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Applies 2D average-pooling operation in kH × kW regions by step size sH * sW steps. The number of output features is equal to the number of input planes.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"kernelSize\"></param>\n /// <param name=\"stride\"></param>\n /// <param name=\"padding\"></param>\n /// <param name=\"ceil_mode\"></param>\n /// <param name=\"count_include_pad\"></param>\n /// <returns></returns>\n public static unsafe Tensor avg_pool2d(Tensor input, long kernelSize,\n long? stride = null,\n long padding = 0,\n bool ceil_mode = false,\n bool count_include_pad = true)\n {\n long svalue = (stride == null) ? kernelSize : stride.Value;\n\n long* pkernelSize = stackalloc long[2] { kernelSize, kernelSize };\n long* pstrides = stackalloc long[2] { svalue, svalue };\n long* ppadding = stackalloc long[2] { padding, padding };\n\n var res =\n THSTensor_avg_pool2d(input.Handle,\n (IntPtr)pkernelSize, 2,\n (IntPtr)pstrides, 2,\n (IntPtr)ppadding, 2,\n ceil_mode,\n count_include_pad);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Applies 2D average-pooling operation in kH × kW regions by step size sH * sW steps. The number of output features is equal to the number of input planes.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"kernelSize\"></param>\n /// <param name=\"stride\"></param>\n /// <param name=\"padding\"></param>\n /// <param name=\"ceil_mode\"></param>\n /// <param name=\"count_include_pad\"></param>\n /// <returns></returns>\n public static unsafe Tensor avg_pool2d(Tensor input, (long, long) kernelSize,\n (long, long)? stride = null,\n (long, long)? padding = null,\n bool ceil_mode = false,\n bool count_include_pad = true)\n {\n long svalue1 = (stride == null) ? kernelSize.Item1 : stride.Value.Item1;\n long svalue2 = (stride == null) ? kernelSize.Item2 : stride.Value.Item2;\n long pvalue1 = padding != null ? padding.Value.Item1 : 0;\n long pvalue2 = padding != null ? padding.Value.Item2 : 0;\n\n long* pstrides = stackalloc long[2] { svalue1, svalue2 };\n long* ppadding = stackalloc long[2] { pvalue1, pvalue2 };\n\n long* pkernelSize = stackalloc long[2] { kernelSize.Item1, kernelSize.Item2 };\n\n var res =\n THSTensor_avg_pool2d(input.Handle,\n (IntPtr)pkernelSize, 2,\n (IntPtr)pstrides, 2,\n (IntPtr)ppadding, 2,\n ceil_mode,\n count_include_pad);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public static Tensor avg_pool2d_backward(Tensor input, Tensor originalInput,\n long[] kernelSizes,\n long[] strides = null,\n long[] paddings = null,\n bool ceil_mode = false,\n bool count_include_pad = true,\n long divisorOverride = 0)\n {\n strides = (strides == null) ? new long[] { 1 } : strides;\n paddings = (paddings == null) ? new long[] { 0 } : paddings;\n unsafe {\n fixed (long* pkernelSize = kernelSizes, pstrides = strides, ppadding = paddings) {\n var res =\n THSTensor_avg_pool2d_backward(input.Handle, originalInput.Handle,\n (IntPtr)pkernelSize, kernelSizes.Length,\n (IntPtr)pstrides, strides.Length,\n (IntPtr)ppadding, paddings.Length,\n ceil_mode,\n count_include_pad,\n divisorOverride);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6172727942466736, "alphanum_fraction": 0.6174814105033875, "avg_line_length": 58.67219924926758, "blob_id": "914304d966c8214bb42104e1f8d5ab4712c95758", "content_id": "e8fa5fbcab053d4cfa218e333a012d93663859d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 14431, "license_type": "permissive", "max_line_length": 205, "num_lines": 241, "path": "/src/TorchSharp/Autograd.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Linq;\nusing System.Collections.Generic;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n /// <summary>\n /// Helper class, relying on IDisposable to implement block-based scoping of autograd settings.\n /// </summary>\n internal class AutoGradMode : IDisposable\n {\n private readonly bool _isPrevGrad;\n\n public AutoGradMode(bool enabled)\n {\n _isPrevGrad = THSAutograd_isGradEnabled();\n THSAutograd_setGrad(enabled);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n public void Dispose(bool disposing)\n {\n if (disposing)\n {\n THSAutograd_setGrad(_isPrevGrad);\n }\n }\n\n public static bool IsEnabled { get => THSAutograd_isGradEnabled(); }\n }\n\n /// <summary>\n /// Helper class, relying on IDisposable to implement block-based scoping of anomaly settings.\n /// </summary>\n public class AnomalyMode : IDisposable\n {\n private readonly bool _isPrevGrad;\n private readonly bool _shouldCheckNaN;\n\n public AnomalyMode(bool enabled, bool check_nan = true)\n {\n _isPrevGrad = THSAutograd_isAnomalyEnabled();\n _shouldCheckNaN = THSAutograd_shouldCheckNaN();\n THSAutograd_setAnomaly(enabled, check_nan);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (disposing) {\n THSAutograd_setAnomaly(_isPrevGrad, _shouldCheckNaN);\n }\n }\n\n public static bool IsEnabled { get => THSAutograd_isAnomalyEnabled(); }\n\n public static bool ShouldCheckNaN { get => THSAutograd_shouldCheckNaN(); }\n }\n\n public static partial class torch\n {\n public static partial class autograd\n {\n /// <summary>\n /// Computes and returns the sum of gradients of outputs with respect to the inputs.\n /// </summary>\n /// <param name=\"outputs\">Outputs of the differentiated function.</param>\n /// <param name=\"inputs\">Inputs w.r.t. which the gradient will be returned (and not accumulated into .grad)..</param>\n /// <param name=\"grad_outputs\">\n /// The “vector” in the Jacobian-vector product. Usually gradients w.r.t. each output.\n /// Null values can be specified for scalar Tensors or ones that don’t require grad.\n /// If a null value would be acceptable for all grad_tensors, then this argument is optional.\n /// </param>\n /// <param name=\"retain_graph\">\n /// If false, the graph used to compute the grad will be freed.\n /// Note that in nearly all cases setting this option to true is not needed and often can be worked around in a much more efficient way. Defaults to the value of create_graph.\n /// </param>\n /// <param name=\"create_graph\">\n /// If true, graph of the derivative will be constructed, allowing to compute higher order derivative products.\n /// </param>\n /// <param name=\"allow_unused\">\n /// If false, specifying inputs that were not used when computing outputs (and therefore their grad is always zero) is an error.\n /// </param>\n /// <returns></returns>\n public static IList<Tensor> grad(IList<Tensor> outputs, IList<Tensor> inputs, IList<Tensor> grad_outputs = null, bool retain_graph = false, bool create_graph = false, bool allow_unused = false)\n {\n using var outs = new PinnedArray<IntPtr>();\n using var ins = new PinnedArray<IntPtr>();\n using var grads = new PinnedArray<IntPtr>();\n using var results = new PinnedArray<IntPtr>();\n\n IntPtr outsRef = outs.CreateArray(outputs.Select(p => p.Handle).ToArray());\n IntPtr insRef = ins.CreateArray(inputs.Select(p => p.Handle).ToArray());\n IntPtr gradsRef = grad_outputs == null ? IntPtr.Zero : grads.CreateArray(grad_outputs.Select(p => p.Handle).ToArray());\n long gradsLength = grad_outputs == null ? 0 : grads.Array.Length;\n\n THSAutograd_grad(outsRef, outs.Array.Length, insRef, ins.Array.Length, gradsRef, gradsLength, retain_graph, create_graph, allow_unused, results.CreateArray);\n CheckForErrors();\n return results.Array.Select(x => new Tensor(x)).ToList();\n }\n\n /// <summary>\n /// Computes the sum of gradients of given tensors with respect to graph leaves.\n /// </summary>\n /// <param name=\"tensors\">Tensors of which the derivative will be computed.</param>\n /// <param name=\"grad_tensors\">\n /// The “vector” in the Jacobian-vector product, usually gradients w.r.t. each element of corresponding tensors.\n /// Null values can be specified for scalar Tensors or ones that don’t require grad.\n /// If a null value would be acceptable for all grad_tensors, then this argument is optional.\n /// </param>\n /// <param name=\"retain_graph\">If false, the graph used to compute the grad will be freed.\n /// Note that in nearly all cases setting this option to true is not needed and often can be worked around in a much more efficient way.\n /// Defaults to the value of create_graph.</param>\n /// <param name=\"create_graph\">If true, graph of the derivative will be constructed, allowing to compute higher order derivative products. Defaults to false.</param>\n /// <param name=\"inputs\">\n /// Inputs w.r.t. which the gradient be will accumulated into .grad. All other Tensors will be ignored.\n /// If not provided, the gradient is accumulated into all the leaf Tensors that were used to compute the attr::tensors.\n /// </param>\n /// <remarks>\n /// The graph is differentiated using the chain rule. If any of tensors are non-scalar (i.e. their data has more than one element) and require gradient,\n /// then the Jacobian-vector product would be computed, in this case the function additionally requires specifying grad_tensors.\n ///\n /// It should be a sequence of matching length, that contains the “vector” in the Jacobian-vector product, usually the gradient of the differentiated\n /// function w.r.t. corresponding tensors (null is an acceptable value for all tensors that don’t need gradient tensors).\n ///\n /// This function accumulates gradients in the leaves - you might need to zero the .grad properties or set them to null before calling it.\n /// </remarks>\n public static void backward(IList<Tensor> tensors, IList<Tensor> grad_tensors = null, bool? retain_graph = null, bool create_graph = false, IList<Tensor> inputs = null)\n {\n bool rt = retain_graph ?? create_graph;\n\n using var ts = new PinnedArray<IntPtr>();\n using var gts = new PinnedArray<IntPtr>();\n using var ins = new PinnedArray<IntPtr>();\n IntPtr tensRef = ts.CreateArray(tensors.Select(p => p.Handle).ToArray());\n IntPtr gradsRef = grad_tensors == null ? IntPtr.Zero : gts.CreateArray(grad_tensors.Select(p => p.Handle).ToArray());\n IntPtr insRef = inputs == null ? IntPtr.Zero : ins.CreateArray(inputs.Select(p => p.Handle).ToArray());\n long insLength = inputs == null ? 0 : ins.Array.Length;\n long gradsLength = grad_tensors == null ? 0 : gts.Array.Length;\n\n THSAutograd_backward(tensRef, ts.Array.Length, gradsRef, gradsLength, rt, create_graph, insRef, insLength);\n CheckForErrors();\n }\n\n /// <summary>\n /// Computes the sum of gradients of given tensors with respect to graph leaves.\n /// </summary>\n /// <param name=\"tensor\">Tensor of which the derivative will be computed.</param>\n /// <param name=\"grad_tensors\">\n /// The “vector” in the Jacobian-vector product, usually gradients w.r.t. each element of corresponding tensors.\n /// Null values can be specified for scalar Tensors or ones that don’t require grad.\n /// If a null value would be acceptable for all grad_tensors, then this argument is optional.\n /// </param>\n /// <param name=\"retain_graph\">If false, the graph used to compute the grad will be freed.\n /// Note that in nearly all cases setting this option to true is not needed and often can be worked around in a much more efficient way.\n /// Defaults to the value of create_graph.</param>\n /// <param name=\"create_graph\">If true, graph of the derivative will be constructed, allowing to compute higher order derivative products. Defaults to false.</param>\n /// <param name=\"inputs\">\n /// Inputs w.r.t. which the gradient be will accumulated into .grad. All other Tensors will be ignored.\n /// If not provided, the gradient is accumulated into all the leaf Tensors that were used to compute the attr::tensors.\n /// </param>\n /// <remarks>\n /// The graph is differentiated using the chain rule. If any of tensors are non-scalar (i.e. their data has more than one element) and require gradient,\n /// then the Jacobian-vector product would be computed, in this case the function additionally requires specifying grad_tensors.\n ///\n /// It should be a sequence of matching length, that contains the “vector” in the Jacobian-vector product, usually the gradient of the differentiated\n /// function w.r.t. corresponding tensors (null is an acceptable value for all tensors that don’t need gradient tensors).\n ///\n /// This function accumulates gradients in the leaves - you might need to zero the .grad properties or set them to null before calling it.\n /// </remarks>\n public static void backward(Tensor tensor, IList<Tensor> grad_tensors = null, bool? retain_graph = null, bool create_graph = false, IList<Tensor> inputs = null)\n {\n backward(new[] { tensor }, grad_tensors, retain_graph, create_graph, inputs);\n }\n\n /// <summary>\n /// Computes the sum of gradients of given tensors with respect to graph leaves.\n /// </summary>\n /// <param name=\"tensor\">Tensor of which the derivative will be computed.</param>\n /// <param name=\"grad_tensor\">\n /// The “vector” in the Jacobian-vector product, usually gradients w.r.t. each element of corresponding tensors.\n /// Null values can be specified for scalar Tensors or ones that don’t require grad.\n /// If a null value would be acceptable for all grad_tensors, then this argument is optional.\n /// </param>\n /// <param name=\"retain_graph\">If false, the graph used to compute the grad will be freed.\n /// Note that in nearly all cases setting this option to true is not needed and often can be worked around in a much more efficient way.\n /// Defaults to the value of create_graph.</param>\n /// <param name=\"create_graph\">If true, graph of the derivative will be constructed, allowing to compute higher order derivative products. Defaults to false.</param>\n /// <param name=\"inputs\">\n /// Inputs w.r.t. which the gradient be will accumulated into .grad. All other Tensors will be ignored.\n /// If not provided, the gradient is accumulated into all the leaf Tensors that were used to compute the attr::tensors.\n /// </param>\n /// <remarks>\n /// The graph is differentiated using the chain rule. If any of tensors are non-scalar (i.e. their data has more than one element) and require gradient,\n /// then the Jacobian-vector product would be computed, in this case the function additionally requires specifying grad_tensors.\n ///\n /// It should be a sequence of matching length, that contains the “vector” in the Jacobian-vector product, usually the gradient of the differentiated\n /// function w.r.t. corresponding tensors (null is an acceptable value for all tensors that don’t need gradient tensors).\n ///\n /// This function accumulates gradients in the leaves - you might need to zero the .grad properties or set them to null before calling it.\n /// </remarks>\n public static void backward(Tensor tensor, Tensor grad_tensor, bool? retain_graph = null, bool create_graph = false, IList<Tensor> inputs = null)\n {\n backward(new[] { tensor }, new[] { grad_tensor }, retain_graph, create_graph, inputs);\n }\n\n /// <summary>\n /// Context-manager that enable anomaly detection for the autograd engine.\n /// </summary>\n /// <param name=\"check_nan\">Flag whether to raise an error when the backward generate “nan”</param>\n /// <returns></returns>\n public static AnomalyMode detect_anomaly(bool check_nan = true)\n {\n return new AnomalyMode(true, check_nan);\n }\n\n /// <summary>\n /// Context-manager that enable anomaly detection for the autograd engine.\n /// </summary>\n /// <param name=\"mode\">Flag whether to enable anomaly detection (true), or disable (false)</param>\n /// <param name=\"check_nan\">Flag whether to raise an error when the backward generate “nan”</param>\n /// <returns></returns>\n public static AnomalyMode set_detect_anomaly(bool mode, bool check_nan = true)\n {\n return new AnomalyMode(mode, check_nan);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5682805180549622, "alphanum_fraction": 0.5745536684989929, "avg_line_length": 46.45801544189453, "blob_id": "081b922112cb27169ac09275c8dc5d83e506692f", "content_id": "02ccab3116dc8da5d926e64b9c6e594cf89d7a19", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6217, "license_type": "permissive", "max_line_length": 224, "num_lines": 131, "path": "/src/TorchSharp/Tensor/Factories/full.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torch\n {\n /// <summary>\n /// Create a new tensor filled with a given value\n /// </summary>\n public static Tensor full(long[] size, Scalar value, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _full(size, value, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new tensor filled with a given value\n /// </summary>\n public static Tensor full(ReadOnlySpan<long> size, Scalar value, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _full(size, value, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 1-D tensor filled with given value\n /// </summary>\n public static Tensor full(long size, Scalar value, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _full(stackalloc long[] { size }, value, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 2-D tensor filled with given value\n /// </summary>\n public static Tensor full(long rows, long columns, Scalar value, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _full(stackalloc long[] { rows, columns }, value, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 3-D tensor filled with given value\n /// </summary>\n public static Tensor full(long dim0, long dim1, long dim2, Scalar value, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _full(stackalloc long[] { dim0, dim1, dim2 }, value, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 4-D tensor filled with given value\n /// </summary>\n public static Tensor full(long dim0, long dim1, long dim2, long dim3, Scalar value, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _full(stackalloc long[] { dim0, dim1, dim2, dim3 }, value, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 1-D tensor filled with given value\n /// </summary>\n public static Tensor full(int size, Scalar value, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _full(stackalloc long[] { size }, value, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 2-D tensor filled with given value\n /// </summary>\n public static Tensor full(int rows, int columns, Scalar value, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _full(stackalloc long[] { rows, columns }, value, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 3-D tensor filled with given value\n /// </summary>\n public static Tensor full(int dim0, int dim1, int dim2, Scalar value, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _full(stackalloc long[] { dim0, dim1, dim2 }, value, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a new 4-D tensor filled with given value\n /// </summary>\n public static Tensor full(int dim0, int dim1, int dim2, int dim3, Scalar value, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _full(stackalloc long[] { dim0, dim1, dim2, dim3 }, value, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Returns a tensor with the same size as input filled with 'value.'\n /// </summary>\n public static Tensor full_like(Tensor input, Scalar value, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null) => input.full_like(value, dtype, device, requires_grad);\n\n /// <summary>\n /// Create a new tensor filled with a given value\n /// </summary>\n private static Tensor _full(ReadOnlySpan<long> size, Scalar value, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n device = InitializeDevice(device);\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n if (value.Type.IsIntegral()) {\n dtype = ScalarType.Int64;\n } else {\n dtype = get_default_dtype();\n }\n }\n\n unsafe {\n fixed (long* psizes = size) {\n var handle = THSTensor_full((IntPtr)psizes, size.Length, value.Handle, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_full((IntPtr)psizes, size.Length, value.Handle, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n var result = new Tensor(handle);\n\n if (names != null && names.Length > 0) {\n\n result.rename_(names);\n }\n\n return result;\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5659258961677551, "alphanum_fraction": 0.5804938077926636, "avg_line_length": 40.75257873535156, "blob_id": "8f6eab5981f3c29beda81e7bb79e56ce382304e4", "content_id": "6fed5c29617f34645418b081c451ed8f325ef560", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4050, "license_type": "permissive", "max_line_length": 147, "num_lines": 97, "path": "/src/TorchVision/Ops/FrozenBatchNorm2d.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchvision,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/vision/blob/a4f53308b2d0f1aa9191686e326f45c26053f686/torchvision/ops/misc.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/vision/blob/main/LICENSE\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.Runtime.CompilerServices;\nusing static TorchSharp.torch;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class ops\n {\n /// <summary>\n /// BatchNorm2d where the batch statistics and the affine parameters are fixed\n /// </summary>\n /// <param name=\"num_features\">Number of features C from an expected input of size (N, C, H, W)</param>\n /// <param name=\"eps\">A value added to the denominator for numerical stability.</param>\n /// <param name=\"device\">The target device for all buffers.</param>\n public static Modules.FrozenBatchNorm2d FrozenBatchNorm2d(int num_features, double eps = 1e-5, Device? device = null)\n {\n return new Modules.FrozenBatchNorm2d(num_features, eps, device);\n }\n }\n }\n\n namespace Modules\n {\n /// <summary>\n /// BatchNorm2d where the batch statistics and the affine parameters are fixed\n /// </summary>\n public class FrozenBatchNorm2d : nn.Module<Tensor, Tensor>\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"num_features\">Number of features C from an expected input of size (N, C, H, W)</param>\n /// <param name=\"eps\">A value added to the denominator for numerical stability.</param>\n /// <param name=\"device\">The target device for all buffers.</param>\n protected internal FrozenBatchNorm2d(int num_features, double eps = 1e-5, Device? device = null) : base(nameof(FrozenBatchNorm2d))\n {\n this.eps = eps;\n\n weight = torch.ones(num_features, device: device);\n bias = torch.zeros(num_features, device: device);\n running_mean = torch.zeros(num_features, device: device);\n running_var = torch.ones(num_features, device: device);\n\n register_buffer(nameof(weight), weight);\n register_buffer(nameof(bias), bias);\n register_buffer(nameof(running_mean), running_mean);\n register_buffer(nameof(running_var), running_var);\n }\n\n private double eps;\n\n public Tensor weight { get; protected set; }\n public Tensor bias { get; protected set; }\n public Tensor running_mean { get; protected set; }\n public Tensor running_var { get; protected set; }\n\n public override Tensor forward(Tensor x)\n {\n if (x.Dimensions != 4) throw new ArgumentException($\"Invalid number of dimensions for FrozenBatchNorm2d argument: {x.Dimensions}\");\n var w = weight.reshape(1, -1, 1, 1);\n var b = bias.reshape(1, -1, 1, 1);\n var rv = running_var.reshape(1, -1, 1, 1);\n var rm = running_mean.reshape(1, -1, 1, 1);\n var scale = w * (rv + eps).rsqrt();\n bias = b - rm * scale;\n return x * scale + bias;\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n weight.Dispose();\n bias.Dispose();\n running_mean.Dispose();\n running_var.Dispose();\n }\n base.Dispose(disposing);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.43833625316619873, "alphanum_fraction": 0.4447353184223175, "avg_line_length": 26.733871459960938, "blob_id": "80d78df4e063d79aeff2e85b2b7d26b9c6eda1d7", "content_id": "7b2b7d7b25264e571eb7f5048ce75cb861cb3bf0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3438, "license_type": "permissive", "max_line_length": 130, "num_lines": 124, "path": "/src/TorchSharp/Utils/FastShuffler.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n//Algorithm from https://github.com/lemire/Code-used-on-Daniel-Lemire-s-blog/blob/master/2017/09/18_2/VisitInDisorder.java\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\n\nnamespace TorchSharp.Utils\n{\n class FastShuffler : IEnumerable<long>\n {\n private long size;\n private int? seed;\n\n public FastShuffler(long size, int? seed = null)\n {\n this.size = size;\n this.seed = seed;\n }\n\n private class ShuffleEnumerator : IEnumerator<long>\n {\n long maxrange;\n long prime;\n long index;\n long offset;\n long runningvalue;\n private Random rand;\n private int? seed;\n private long size;\n\n public ShuffleEnumerator(long size, int? seed = null)\n {\n this.seed = seed;\n this.size = size;\n Reset();\n }\n\n private const long MAX_COUNT = long.MaxValue;\n\n long SelectCoPrimeResev(long min, long target)\n {\n var count = 0L;\n var selected = 0L;\n for (var val = min; val < target; ++val) {\n if (Coprime(val, target)) {\n count += 1;\n if ((count == 1) || (NextLong(rand, count) < 1)) {\n selected = val;\n }\n }\n\n if (count == MAX_COUNT) return val;\n }\n\n return selected;\n }\n\n static bool Coprime(long u, long v) => Gcd(u, v) == 1;\n\n private static long Gcd(long a, long b)\n {\n while (a != 0 && b != 0)\n if (a > b) a %= b;\n else b %= a;\n\n return a | b;\n }\n\n private static long NextLong(Random r, long l)\n {\n var bytebuffer = new byte[8];\n r.NextBytes(bytebuffer);\n var t = 0L;\n foreach (var b in bytebuffer) {\n t <<= 8;\n t += b;\n }\n\n return t % l;\n }\n\n public bool MoveNext()\n {\n\n if (index >= maxrange) return false;\n runningvalue += prime;\n if (runningvalue >= maxrange) runningvalue -= maxrange;\n index++;\n return true;\n }\n\n public void Reset()\n {\n rand = seed is null ? new Random() : new Random(seed.Value);\n var min = size / 2;\n maxrange = size;\n prime = SelectCoPrimeResev(min, size);\n offset = NextLong(rand, size);\n index = 0;\n runningvalue = offset;\n }\n\n object IEnumerator.Current => Current;\n\n public long Current => runningvalue;\n\n public void Dispose()\n {\n\n }\n }\n\n public IEnumerator<long> GetEnumerator()\n {\n return new ShuffleEnumerator(size, seed);\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n }\n}" }, { "alpha_fraction": 0.4909479022026062, "alphanum_fraction": 0.510158896446228, "avg_line_length": 43.07316970825195, "blob_id": "21a52c29abcd4303ae1787aeb28e86d55f7ab74c", "content_id": "921edff5a023bf3775802817b5d6e39128d889b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 12649, "license_type": "permissive", "max_line_length": 133, "num_lines": 287, "path": "/src/TorchVision/dsets/CelebA.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\nusing static TorchSharp.torch.utils.data;\nusing static TorchSharp.torchvision.datasets;\nusing static TorchSharp.torchvision.datasets.utils;\n\n// A number of implementation details in this file have been translated from the Python version of torchvision,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/vision/blob/b78d98bb152ffb9c0c0f5365f59f475c70b1784e/torchvision/datasets/celeba.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/vision/blob/main/LICENSE\n//\n\n#nullable enable\nnamespace TorchSharp\n{\n namespace Modules\n {\n internal sealed class CelebA : Dataset\n {\n private static readonly (string, string, string)[] file_list = new (string, string, string)[] {\n // File ID MD5 Hash Filename\n (\"0B7EVK8r0v71pZjFTYXZWM3FlRnM\", \"00d2c5bc6d35e252742224ab0c1e8fcb\", \"img_align_celeba.zip\"),\n // (\"0B7EVK8r0v71pbWNEUjJKdDQ3dGc\",\"b6cd7e93bc7a96c2dc33f819aa3ac651\", \"img_align_celeba_png.7z\"),\n // (\"0B7EVK8r0v71peklHb0pGdDl6R28\", \"b6cd7e93bc7a96c2dc33f819aa3ac651\", \"img_celeba.7z\"),\n (\"0B7EVK8r0v71pblRyaVFSWGxPY0U\", \"75e246fa4810816ffd6ee81facbd244c\", \"list_attr_celeba.txt\"),\n (\"1_ee_0u7vcNLOfNLegJRHmolfH5ICW-XS\", \"32bd1bd63d3c78cd57e08160ec5ed1e2\", \"identity_CelebA.txt\"),\n (\"0B7EVK8r0v71pbThiMVRxWXZ4dU0\", \"00566efa6fedff7a56946cd1c10f1c16\", \"list_bbox_celeba.txt\"),\n (\"0B7EVK8r0v71pd0FJY3Blby1HUTQ\", \"cc24ecafdb5b50baae59b03474781f8c\", \"list_landmarks_align_celeba.txt\"),\n // (\"0B7EVK8r0v71pTzJIdlJWdHczRlU\", \"063ee6ddb681f96bc9ca28c6febb9d1a\", \"list_landmarks_celeba.txt\"),\n (\"0B7EVK8r0v71pY0NSMzRuSXJEVkk\", \"d32c9cbf5e040fd4025c592c306e6668\", \"list_eval_partition.txt\"),\n };\n\n private const string base_folder = \"celeba\";\n private readonly string root;\n private readonly CelebADatasetSplit split;\n private readonly string[] target_type;\n private readonly IModule<Tensor, Tensor>? transform;\n private readonly IModule<Tensor, Tensor>? target_transform;\n private string[]? filename;\n private Tensor? identity;\n private Tensor? bbox;\n private Tensor? landmarks_align;\n private Tensor? attr;\n private string[]? attr_names;\n\n internal CelebA(\n string root,\n CelebADatasetSplit split,\n string[] target_type,\n IModule<Tensor, Tensor>? transform,\n IModule<Tensor, Tensor>? target_transform)\n {\n this.root = root;\n this.split = split;\n this.target_type = target_type;\n this.transform = transform;\n this.target_transform = target_transform;\n }\n\n public override long Count => this.attr is null ? 0 : this.attr.shape[0];\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n identity?.Dispose();\n bbox?.Dispose();\n landmarks_align?.Dispose();\n attr?.Dispose();\n }\n }\n\n internal void Load()\n {\n if (!this.CheckIntegrity()) {\n throw new InvalidDataException(\"Dataset not found or corrupted. You can use download=True to download it\");\n }\n\n var splits = this.LoadCsv(\"list_eval_partition.txt\");\n var identity = this.LoadCsv(\"identity_CelebA.txt\");\n var bbox = this.LoadCsv(\"list_bbox_celeba.txt\", header: 1);\n var landmarks_align = this.LoadCsv(\"list_landmarks_align_celeba.txt\", header: 1);\n var attr = this.LoadCsv(\"list_attr_celeba.txt\", header: 1);\n\n if (this.split == CelebADatasetSplit.All) {\n this.filename = splits.index;\n\n this.identity = identity.data;\n this.bbox = bbox.data;\n this.landmarks_align = landmarks_align.data;\n this.attr = attr.data;\n } else {\n var mask = (splits.data == (long)this.split).squeeze();\n\n var x = torch.squeeze(torch.nonzero(mask), dim: null);\n var y = new List<string>();\n for (int i = 0; i < x.shape[0]; i++) {\n y.Add(splits.index[x[i].item<long>()]);\n }\n this.filename = y.ToArray();\n\n this.identity = identity.data[mask];\n this.bbox = bbox.data[mask];\n this.landmarks_align = landmarks_align.data[mask];\n this.attr = attr.data[mask];\n }\n // map from {-1, 1} to {0, 1}\n this.attr = torch.div(this.attr + 1, 2, rounding_mode: RoundingMode.floor).to(this.attr.dtype);\n this.attr_names = attr.header;\n }\n\n private CSV LoadCsv(string filename, int? header = null)\n {\n IList<string[]> data = (\n File.ReadAllLines(Path.Combine(this.root, base_folder, filename))\n .Select(line => line.TrimStart().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries))).ToList();\n\n string[]? headers;\n if (header is not null) {\n headers = data[(int)header];\n data = data.Skip((int)header + 1).ToList();\n } else {\n headers = null;\n }\n\n var indices = data.Select(row => row[0]).ToArray();\n\n data = data.Select(row => row.AsSpan(1).ToArray()).ToList();\n var data_long = new long[data.Count, data[0].Length];\n for (int i = 0; i < data_long.GetLength(0); i++) {\n for (int j = 0; j < data_long.GetLength(1); j++) {\n if (data[i].Length != data_long.GetLength(1)) {\n throw new Exception();\n }\n long result = long.TryParse(data[i][j], out result) ? result : 0;\n data_long[i, j] = result;\n }\n }\n return new CSV(headers, indices, torch.tensor(data_long));\n }\n\n /// <summary>\n /// Get tensor according to index\n /// </summary>\n /// <param name=\"index\">Index for tensor</param>\n /// <returns>Tensors of index.</returns>\n public override Dictionary<string, Tensor> GetTensor(long index)\n {\n if (this.filename is null) throw new InvalidOperationException();\n Tensor X = torchvision.io.read_image(Path.Combine(this.root, base_folder, \"img_align_celeba\", this.filename[index]));\n\n var result = new Dictionary<string, Tensor>();\n foreach (var t in this.target_type) {\n if (t == \"attr\") {\n if (this.attr is null) throw new InvalidDataException();\n result[t] = this.attr[index, TensorIndex.Colon];\n } else if (t == \"identity\") {\n if (this.identity is null) throw new InvalidDataException();\n result[t] = this.identity[index, 0];\n } else if (t == \"bbox\") {\n if (this.bbox is null) throw new InvalidDataException();\n result[t] = this.bbox[index, TensorIndex.Colon];\n } else if (t == \"landmarks\") {\n if (this.landmarks_align is null) throw new InvalidDataException();\n result[t] = this.landmarks_align[index, TensorIndex.Colon];\n } else {\n throw new InvalidDataException($\"Target type \\\"{t}\\\" is not recognized.\");\n }\n }\n\n if (this.transform is not null) {\n X = this.transform.call(X);\n }\n result[\"input\"] = X;\n if (this.target_transform is not null) {\n string t = this.target_type[0];\n result[t] = this.target_transform.call(result[t]);\n }\n return result;\n }\n\n private bool CheckIntegrity()\n {\n foreach (var (_, md5, filename) in file_list) {\n var fpath = Path.Combine(this.root, base_folder, filename);\n var ext = Path.GetExtension(filename);\n // Allow original archive to be deleted (zip and 7z)\n // Only need the extracted images\n if (ext != \".zip\" && ext != \".7z\" && !torchvision.io.GDriveDownload.CheckIntegrity(fpath, md5)) {\n return false;\n }\n }\n\n // Should check a hash of the images\n return Directory.Exists(Path.Combine(this.root, base_folder, \"img_align_celeba\"));\n }\n\n public void download()\n {\n if (this.CheckIntegrity()) {\n Console.WriteLine(\"Files already downloaded and verified\");\n return;\n }\n\n foreach (var (file_id, md5, filename) in file_list) {\n download_file_from_google_drive(file_id, Path.Combine(this.root, base_folder), filename, md5);\n }\n\n extract_archive(Path.Combine(this.root, base_folder, \"img_align_celeba.zip\"));\n }\n\n private struct CSV\n {\n public string[]? header;\n public string[] index;\n public torch.Tensor data;\n public CSV(string[]? header, string[] index, torch.Tensor data)\n {\n this.header = header;\n this.index = index;\n this.data = data;\n }\n }\n }\n }\n\n public static partial class torchvision\n {\n public static partial class datasets\n {\n public enum CelebADatasetSplit\n {\n Train = 0,\n Valid = 1,\n Test = 2,\n All = -1,\n }\n\n /// <summary>\n /// `Large-scale CelebFaces Attributes (CelebA) Dataset http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html Dataset.\n /// </summary>\n /// <param name=\"root\">Root directory where images are downloaded to.</param>\n /// <param name=\"split\">One of Train, Valid, Test, All.\n /// Accordingly dataset is selected.</param>\n /// <param name=\"target_type\">Type of target to use, ``attr``, ``identity``, ``bbox``,\n /// or ``landmarks``.</param>\n /// <param name=\"transform\">A function/transform that takes in an PIL image\n /// and returns a transformed version.</param>\n /// <param name=\"target_transform\">A function/transform that takes in the\n /// target and transforms it.</param>\n /// <param name=\"download\">If true, downloads the dataset from the internet and\n /// puts it in root directory. If dataset is already downloaded, it is not\n /// downloaded again.</param>\n public static Dataset CelebA(\n string root,\n CelebADatasetSplit split = CelebADatasetSplit.Train,\n string[]? target_type = null,\n IModule<Tensor, Tensor>? transform = null,\n IModule<Tensor, Tensor>? target_transform = null,\n bool download = false)\n {\n if (target_type == null) {\n target_type = new string[] { \"attr\" };\n }\n var dataset = new Modules.CelebA(\n root,\n split,\n target_type,\n transform,\n target_transform);\n if (download) {\n dataset.download();\n }\n dataset.Load();\n return dataset;\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5027042627334595, "alphanum_fraction": 0.5125908851623535, "avg_line_length": 45.72554397583008, "blob_id": "670c3a05857ce9a21925cccff8132d68de6820bb", "content_id": "2a67102df5823af76f42a14074c4aa600fde98a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 17195, "license_type": "permissive", "max_line_length": 220, "num_lines": 368, "path": "/src/TorchSharp/Optimizers/ASGD.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n public static partial class torch\n {\n public static partial class optim\n {\n\n /// <summary>\n /// Implements the Averaged Stochastic Gradient Descent.\n ///\n /// It has been proposed in Acceleration of stochastic approximation by averaging.\n /// https://dl.acm.org/citation.cfm?id=131098\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"lr \">Learning rate</param>\n /// <param name=\"lambd\">Decay term (default: 1e-4)</param>\n /// <param name=\"alpha\">Power for eta update (default: 0.75)</param>\n /// <param name=\"t0\">Point at which to start averaging (default: 1e6)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"maximize\">Maximize the params based on the objective, instead of minimizing.</param>\n public static ASGD ASGD(IEnumerable<Parameter> parameters, double lr = 1e-3, double lambd = 1e-4, double alpha = 0.75, double t0 = 1e6, double weight_decay = 0, bool maximize = false)\n {\n return new Modules.ASGD(parameters, lr, lambd, alpha, t0, weight_decay, maximize);\n }\n\n /// <summary>\n /// Implements the Averaged Stochastic Gradient Descent.\n ///\n /// It has been proposed in Acceleration of stochastic approximation by averaging.\n /// https://dl.acm.org/citation.cfm?id=131098\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"lr \">Learning rate</param>\n /// <param name=\"lambd\">Decay term (default: 1e-4)</param>\n /// <param name=\"alpha\">Power for eta update (default: 0.75)</param>\n /// <param name=\"t0\">Point at which to start averaging (default: 1e6)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"maximize\">Maximize the params based on the objective, instead of minimizing.</param>\n public static ASGD ASGD(IEnumerable<(string name, Parameter parameter)> parameters, double lr = 1e-3, double lambd = 1e-4, double alpha = 0.75, double t0 = 1e6, double weight_decay = 0, bool maximize = false)\n {\n return new Modules.ASGD(parameters.Select(np => np.parameter), lr, lambd, alpha, t0, weight_decay, maximize);\n }\n\n /// <summary>\n /// Implements the Averaged Stochastic Gradient Descent.\n ///\n /// It has been proposed in Acceleration of stochastic approximation by averaging.\n /// https://dl.acm.org/citation.cfm?id=131098\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"lr \">Learning rate</param>\n /// <param name=\"lambd\">Decay term (default: 1e-4)</param>\n /// <param name=\"alpha\">Power for eta update (default: 0.75)</param>\n /// <param name=\"t0\">Point at which to start averaging (default: 1e6)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"maximize\">Maximize the params based on the objective, instead of minimizing.</param>\n public static ASGD ASGD(IEnumerable<ParamGroup<ASGD.Options>> parameters, double lr = 1e-3, double lambd = 1e-4, double alpha = 0.75, double t0 = 1e6, double weight_decay = 0, bool maximize = false)\n {\n return new Modules.ASGD(parameters, lr, lambd, alpha, t0, weight_decay, maximize);\n }\n }\n }\n\n namespace Modules\n {\n public class ASGD : OptimizerHelper\n {\n /// <summary>\n /// Implements ASGD algorithm (a variant of Adam based on infinity norm).\n ///\n /// It has been proposed in Adam: A Method for Stochastic Optimization.\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"lr \">Learning rate</param>\n /// <param name=\"lambd\">Decay term (default: 1e-4)</param>\n /// <param name=\"alpha\">Power for eta update (default: 0.75)</param>\n /// <param name=\"t0\">Point at which to start averaging (default: 1e6)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"maximize\">Maximize the params based on the objective, instead of minimizing.</param>\n public ASGD(IEnumerable<Parameter> parameters, double lr = 0.01, double lambd = 1e-4, double alpha = 0.75, double t0 = 1e6, double weight_decay = 0, bool maximize = false)\n : this(new ParamGroup[] { new() { Parameters = parameters } }, lr, lambd, alpha, t0, weight_decay, maximize)\n {\n }\n\n /// <summary>\n /// Implements ASGD algorithm (a variant of Adam based on infinity norm).\n ///\n /// It has been proposed in Adam: A Method for Stochastic Optimization.\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"lr \">Learning rate</param>\n /// <param name=\"lambd\">Decay term (default: 1e-4)</param>\n /// <param name=\"alpha\">Power for eta update (default: 0.75)</param>\n /// <param name=\"t0\">Point at which to start averaging (default: 1e6)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"maximize\">Maximize the params based on the objective, instead of minimizing.</param>\n /// <returns></returns>\n public ASGD(IEnumerable<ParamGroup<Options>> parameters, double lr = 0.01, double lambd = 1e-4, double alpha = 0.75, double t0 = 1e6, double weight_decay = 0, bool maximize = false)\n {\n if (lr < 0.0) throw new ArgumentException($\"Invalid learning rate: {lr}\");\n\n var options = new Options {\n LearningRate = lr,\n InitialLearningRate = lr,\n maximize = maximize,\n lambd = lambd,\n alpha = alpha,\n t0 = t0,\n weight_decay = weight_decay\n };\n\n _defaults = options;\n _parameter_groups = new List<Modules.ParamGroup>();\n\n foreach (var g in parameters) {\n add_param_group(g);\n }\n }\n\n /// <summary>\n /// Performs a single optimization step (parameter update).\n /// </summary>\n /// <param name=\"closure\">A closure that reevaluates the model and returns the loss. Optional for most optimizers.</param>\n /// <returns></returns>\n public override Tensor step(Func<Tensor> closure = null)\n {\n return _step<ParamGroup>(group => {\n\n var options = group.Options as Options;\n var maximize = options.maximize.Value;\n var lambd = options.lambd.Value;\n var alpha = options.alpha.Value;\n var weight_decay = options.weight_decay.Value;\n var t0 = options.t0.Value;\n var lr = options.LearningRate.Value;\n\n foreach (var param in group.Parameters) {\n\n var grad = param.grad();\n\n if (grad is null) continue;\n\n if (grad.is_sparse) throw new ArgumentException(\"ASGD does not support sparse gradients\");\n\n if (maximize) grad = -grad;\n\n var state = (State)_state[param.handle];\n\n state.step += 1;\n\n grad = (weight_decay != 0)\n ? grad.add(param, alpha: weight_decay)\n : grad.alias();\n\n param.mul_(1 - lambd * state.eta);\n param.add_(grad, alpha: -state.eta);\n\n if (state.mu != 1) {\n state.ax.add_(param.sub(state.ax).mul(state.mu));\n } else {\n state.ax.copy_(param);\n }\n\n state.eta = lr / Math.Pow((1 + lambd * lr * state.step), alpha);\n state.mu = 1 / Math.Max(1, state.step - t0);\n }\n }, closure);\n }\n\n protected override void Dispose(bool disposing)\n {\n base.Dispose(disposing);\n foreach (var kvp in _state) {\n ((State)kvp.Item2).Dispose();\n }\n _state.Clear();\n }\n\n public sealed class State : OptimizerState, IDisposable\n {\n public long step;\n public double eta;\n public double mu;\n public Tensor ax;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n private void Dispose(bool disposing)\n {\n if (disposing) {\n ax.Dispose();\n }\n }\n\n /// <summary>\n /// Move all the state to the indicated device.\n /// </summary>\n /// <param name=\"device\">The device to move all state to.</param>\n public override void to(Device device)\n {\n ax = ax.to(device);\n }\n\n /// <summary>\n /// Load the optimizer parameter state from a stream.\n /// </summary>\n /// <param name=\"reader\">A binary reader connected to a stream open for reading.</param>\n public override void LoadStateDict(BinaryReader reader)\n {\n step = reader.ReadInt64();\n eta = reader.ReadDouble();\n mu = reader.ReadDouble();\n ax.Load(reader);\n }\n\n /// <summary>\n /// Load optimizer parameter state from another optimizer.\n /// </summary>\n /// <param name=\"source\">An optimizer state record.</param>\n public override void LoadStateDict(OptimizerState source)\n {\n var st_state = source as State;\n step = st_state.step;\n eta = st_state.eta;\n mu = st_state.mu;\n ax.Dispose();\n ax = st_state.ax;\n }\n\n /// <summary>\n /// Save the optimizer parameter state to a stream.\n /// </summary>\n /// <param name=\"writer\">A binary writer connected to a stream open for writing.</param>\n public override void SaveStateDict(BinaryWriter writer)\n {\n writer.Write(step);\n writer.Write(eta);\n writer.Write(mu);\n ax.Save(writer);\n }\n\n /// <summary>\n /// Useful for tests, allows comparison of one state with another.\n /// </summary>\n /// <param name=\"other\">The other optimizer state</param>\n /// <returns></returns>\n public override bool ApproximatelyEquals(OptimizerState other)\n {\n var rhs = other as State;\n return (rhs is not null) && step == rhs.step && eta == rhs.eta && mu == rhs.mu && ax.allclose(rhs.ax);\n }\n }\n\n /// <summary>\n /// Add a param group to the Optimizer s param_groups.\n /// </summary>\n /// <param name=\"param_group\"></param>\n /// <remarks>This can be useful when fine tuning a pre-trained network as frozen layers can be made trainable and added to the Optimizer as training progresses.</remarks>\n public override void add_param_group(Modules.ParamGroup param_group)\n {\n var def = _defaults as Options;\n if (param_group.Options is null) {\n param_group.Options = new Options();\n }\n\n var opt = param_group.Options as Options;\n\n // Make sure all the options are set.\n if (!opt.maximize.HasValue) opt.maximize = def.maximize;\n if (!opt.LearningRate.HasValue) opt.LearningRate = def.LearningRate;\n if (!opt.lambd.HasValue) opt.lambd = def.lambd;\n if (!opt.alpha.HasValue) opt.alpha = def.alpha;\n if (!opt.weight_decay.HasValue) opt.weight_decay = def.weight_decay;\n if (!opt.t0.HasValue) opt.t0 = def.t0;\n\n opt.InitialLearningRate = opt.LearningRate.Value;\n\n _parameter_groups.Add(param_group);\n\n foreach (var p in param_group.Parameters) {\n var state = new State();\n _state[p.Handle] = state;\n state.step = 0;\n state.eta = param_group.LearningRate;\n state.mu = 1;\n state.ax = torch.zeros_like(p).DetachFromDisposeScope();\n }\n }\n\n public class Options : OptimizerOptions\n {\n public bool? maximize;\n public double? lambd;\n public double? alpha;\n public double? weight_decay;\n public double? t0;\n\n /// <summary>\n /// Load optimizer options (param-group hyperparameters) from another optimizer.\n /// </summary>\n /// <param name=\"source\">An optimizer options record.</param>\n public override void LoadStateDict(OptimizerOptions source)\n {\n base.LoadStateDict(source);\n var opts = source as Options;\n maximize = opts.maximize;\n lambd = opts.lambd;\n alpha = opts.alpha;\n weight_decay = opts.weight_decay;\n t0 = opts.t0;\n }\n\n /// <summary>\n /// Load the optimizer options (param-group hyperparameters) from a stream.\n /// </summary>\n /// <param name=\"reader\">A binary reader connected to a stream open for reading.</param>\n public override void LoadStateDict(BinaryReader reader)\n {\n base.LoadStateDict(reader);\n maximize = reader.ReadBoolean();\n lambd = reader.ReadDouble();\n alpha = reader.ReadDouble();\n weight_decay = reader.ReadDouble();\n t0 = reader.ReadDouble();\n }\n\n /// <summary>\n /// Save the optimizer options (param-group hyperparameters) to a stream.\n /// </summary>\n /// <param name=\"writer\">A binary writer connected to a stream open for writing.</param>\n public override void SaveStateDict(BinaryWriter writer)\n {\n base.SaveStateDict(writer);\n writer.Write(maximize.Value);\n writer.Write(lambd.Value);\n writer.Write(alpha.Value);\n writer.Write(weight_decay.Value);\n writer.Write(t0.Value);\n }\n }\n\n public class ParamGroup : ParamGroup<Options>\n {\n public ParamGroup() { }\n\n public ParamGroup(IEnumerable<Parameter> parameters, Options options) : base(parameters, options) { }\n\n public ParamGroup(IEnumerable<Parameter> parameters, double lr = 0.01, double lambd = 1e-4, double alpha = 0.75, double t0 = 1e6, double weight_decay = 0)\n : base(parameters, new ASGD.Options { LearningRate = lr, lambd = lambd, alpha = alpha, t0 = t0, weight_decay = weight_decay })\n {\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.7460804581642151, "alphanum_fraction": 0.7654510140419006, "avg_line_length": 59.9100341796875, "blob_id": "ae27bd45421292abb8f480de8627c8dd32173b40", "content_id": "e9ce1eec771fd705803b46f724e0c73bdf832d7a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 17604, "license_type": "permissive", "max_line_length": 640, "num_lines": 289, "path": "/DEVGUIDE.md", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "\n# Building\n\n dotnet build /p:SkipNative=true\n dotnet build # for cuda support on Windows and Linux\n dotnet test\n dotnet pack\n\n## Windows\n\nRequirements:\n- Visual Studio\n- git\n- cmake (tested with 3.18)\n\n__NOTE:__ At this moment, VS versions 17.4.X will not build the native code library. Use 17.3.X until further notice. See: https://github.com/dotnet/TorchSharp/issues/858 for more information.\n\n\n## Linux\n\nRequirements:\n- requirements to run .NET Core 3.1\n- git\n- cmake (tested with 3.14)\n- clang 6.x +\n\nExample to fulfill the requirements in Ubuntu 16:\n```\nwget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add -\nsudo apt-add-repository \"deb https://apt.llvm.org/xenial/ llvm-toolchain-xenial-6.0 main\"\nsudo apt-get -y update\nsudo apt-get -y install clang-6.0 git cmake libunwind8 curl libomp-dev\n```\n\nCommands:\n\n## Mac\n\nRequirements:\n- Clang/LLVM 12.0.0\n- git\n- .NET SDK 5.0.300\n- Cmake 3.20.3\n\nBuild with\n\n dotnet build /p:SkipNative=true\n\n## Packages\n\nAn ephemeral feed of packages from Azure DevOps CI is available for those \n\n* View link: https://dotnet.visualstudio.com/TorchSharp/_packaging?_a=feed&feed=SignedPackages\n* Nuget feed: https://dotnet.pkgs.visualstudio.com/TorchSharp/_packaging/SignedPackages/nuget/v3/index.json\n\nSome releases are pushed to nuget\n\n## Building the TorchSharp package\n\n dotnet build\n dotnet pack\n\nLocally built packages have names like this, names update every day. If repeatedly rebuilding them locally you may have to remove them\nfrom your local `.nuget` package cache.\n\n bin/packages/Debug/TorchSharp.0.3.0-local-Debug-20200520.nupkg\n bin/packages/Release/TorchSharp.0.3.0-local-Release-20200520.nupkg\n\nTo change the TorchSharp package version update this [file](https://github.com/dotnet/TorchSharp/blob/main/build/BranchInfo.props).\n\n## Doing releases of the TorchSharp package\n\nThe TorchSharp package is pushed to nuget.org via Azure DevOps CI release pipeline. Assuming you're not building or updating the LibTorch packages\n(`BuildLibTorchPackages` is `false` in [azure-pipelines.yml](azure-pipelines.yml)) this is pretty simple once you have the permissions:\n\n1. Update the version number in [./build/BranchInfo.props](./build/BranchInfo.props) and in the [Release Notes](./RELEASENOTES.md) file and then submit a PR. \n\n Updating the major or minor version number should only be done after a discussion with repo admins. The patch number should be incremented by one each release and set to zero after a change to the major or minor version.\n2. Integrate code to main and wait for CI to process\n3. Go to [releases](https://donsyme.visualstudio.com/TorchSharp/_release) and choose \"Create Release\" (top right)\n4. Under \"Artifacts-->Version\" choose the pipeline build corresponding to the thing you want to release. It should be a successful build on main\n5. Press \"Create\"\n\n6. Once the package has been successfully pushed and is available in the NuGet gallery, create a GitHub tag in the 'main' branch with the version as the name of the tag.\n\n# The libtorch packages\n\nThe libtorch packages are huge (~3GB compressed combined for CUDA Windows) and cause a\nlot of problems to make and deliver due to NuGet package size restrictions.\n\nThese problems include:\n\n1. A massive 2GB binary in the linux CUDA package and multiple 1.0GB binaries in Windows CUDA package\n\n2. Size limitations of about ~500MB on NuGet packages on the Azure DevOps CI system and about ~250MB on `nuget.org`\n\n4. Regular download/upload failures on these systems due to network interruptions for packages of this size\n\n5. 10GB VM image size restrictions for the containers userd to build these packages in the Azure DevOps CI system, we can easily run out of room.\n\n6. Complete libtorch-cpu packages can't be built using your local machine alone, since they won't contain the\n full range of native bits. Instead they are built using Azure Pipelines by combining builds\n\nFor this reason, we do the following\n\n1. The head, referenceable packages that deliver a functioning runtime are any of:\n\n libtorch-cpu\n libtorch-cuda-11.7-linux-x64\n libtorch-cuda-11.7-win-x64\n\n2. These packages are combo packages that reference multiple parts. The parts are **not** independently useful.\n Some parts deliver a single vast file via `primary` and `fragment` packages. A build task is then used to \"stitch\" these files back together\n to one file on the target machine with a SHA check. This is a hack but there is no other realistic way to deliver\n these vast files as packages (the alternative is to abandon packaging and require a manual\n install/detect/link of PyTorch CUDA on all downstream systems, whcih is extremely problematic\n for many practical reasons).\n\n For example, the CUDA package fragments are defined in [libtorch-cuda](src/Redist/libtorch-cuda-11.7/libtorch-cuda-11.7.proj). See more details later in this document.\n\n3. The `libtorch-*` packages are built in Azure DevOps CI\n [using this build pipeline](https://donsyme.visualstudio.com/TorchSharp/_build?definitionId=1&_a=summary) but only in main\n branch and only when `BuildLibTorchPackages` is set to true in [azure-pipelines.yml](azure-pipelines.yml) in the main branch.\n You must currently manually edit this and submit to main to get new `libtorch-*` packages\n built. Also increment `LibTorchPackageVersion` if necessary. Do a push to main and the packages will build. This process could be adjusted but at least gets us off the ground.\n\n4. After a successful build, the `libtorch-*` packages can be trialled using the package feed from CI (see above). When\n they are appropriate they can be pushed to nuget using\n [this manually invoked release pipeline](https://donsyme.visualstudio.com/TorchSharp/_release?_a=releases&view=mine&definitionId=1) in\n Azure DevOps CI (so they don't have to be manually downloaded and pushed to `nuget.org`)\n\n a. [Go to release pipeline](https://donsyme.visualstudio.com/TorchSharp/_release?_a=releases&view=mine&definitionId=1)\n\n b. Press 'New Release'\n\n c. Select the successful main CI build that includes the `libtorch` packages, create the release and wait for it to finish. You should\n see `Initialize job`, `Download artifact - dotnet.TorchSharp - packages`, `NuGet push`, `Finalize Job` succeeded.\n\n d. All packages should now be pushed to `nuget.org` and will appear after indexing.\n\n6. If updating libtorch packages, remember to delete all massive artifacts from Azure DevOps and reset this `BuildLibTorchPackages` in [azure-pipelines.yml](azure-pipelines.yml) in main branch.\n\n### Updating PyTorch version for new libtorch packages\n\nThis project grabs LibTorch and makes a C API wrapper for it, then calls these from C#. When updating to a newer\nversion of PyTorch then quite a lot of careful work needs to be done.\n\n0. Make sure you have plenty of disk space, e.g. 15GB\n\n0. Clean and reset to main\n\n git checkout main\n git clean -xfd .\n\n1. Familiarise yourself with download links. See https://pytorch.org/get-started/locally/ for download links.\n\n For example Linux, LibTorch 2.0.1 CPU download uses the link:\n\n https://download.pytorch.org/libtorch/cpu/libtorch-shared-with-deps-2.0.1%2Bcpu.zip\n\n Don't download anything yet, or manually. The downloads are acquired automatically in step 2.\n \n To update the version, update this in [Dependencies.props](build/Dependencies.props):\n\n <LibTorchVersion>2.0.1</LibTorchVersion>\n\n The libtorch version number is also referenced in source code, in the file 'src/TorchSharp/Torch.cs':\n\n ```C#\n const string libtorchPackageVersion = \"2.0.1.1\";\n ```\n\n2. Run these to test downloads and update SHA hashes for the various LibTorch downloads:\n\n dotnet build src\\Redist\\libtorch-cpu\\libtorch-cpu.proj /p:UpdateSHA=true /p:TargetOS=linux /p:Configuration=Release /t:Build /p:IncludeLibTorchCpuPackages=true\n dotnet build src\\Redist\\libtorch-cpu\\libtorch-cpu.proj /p:UpdateSHA=true /p:TargetOS=mac /p:Configuration=Release /t:Build /p:IncludeLibTorchCpuPackages=true\n dotnet build src\\Redist\\libtorch-cpu\\libtorch-cpu.proj /p:UpdateSHA=true /p:TargetOS=windows /p:Configuration=Release /t:Build /p:IncludeLibTorchCpuPackages=true \n dotnet build src\\Redist\\libtorch-cpu\\libtorch-cpu.proj /p:UpdateSHA=true /p:TargetOS=windows /p:Configuration=Debug /t:Build /p:IncludeLibTorchCpuPackages=true\n\n dotnet build src\\Redist\\libtorch-cuda-11.7\\libtorch-cuda-11.7.proj /p:UpdateSHA=true /p:TargetOS=linux /p:Configuration=Release /t:Build /p:IncludeLibTorchCudaPackages=true\n dotnet build src\\Redist\\libtorch-cuda-11.7\\libtorch-cuda-11.7.proj /p:UpdateSHA=true /p:TargetOS=windows /p:Configuration=Release /t:Build /p:IncludeLibTorchCudaPackages=true\n dotnet build src\\Redist\\libtorch-cuda-11.7\\libtorch-cuda-11.7.proj /p:UpdateSHA=true /p:TargetOS=windows /p:Configuration=Debug /t:Build /p:IncludeLibTorchCudaPackages=true\n\n Each of these will take a **very very long time** depending on your broadband connection. This can't currently be done in CI.\n\n If file names in the distribution have changed, or files have been removed, you will get errors saying that files cannot be found. That's okay and will be taken care of in the next step.\n\n3. At this point you must **very very carefully** update the `<File Include= ...` entries under src\\Redist projects for\n [libtorch-cpu](src/Redist/libtorch-cpu/libtorch-cpu.proj) and [libtorch-cuda](src/Redist/libtorch-cuda-11.7/libtorch-cuda-11.7.proj).\n\n This is the step in the upgrade process that takes the most effort and time. It requires extreme care.\n\n Check the contents of the unzip of the archive, e.g.\n\n bin\\obj\\x64.Debug\\libtorch-cpu\\libtorch-shared-with-deps-2.0.1\\libtorch\\lib\n\n You may also need to precisely refactor the CUDA binaries into multiple parts so each package ends up under ~300MB. The NuGet gallery does not allow packages larger than 250MB, so if files are\n 300MB, after compression, they are likely to be smaller than 250MB. However, you have to look out: if the compression is poor, then packages may end up larger. Note that it is 250 million\n bytes that is the limit, **not** 250*1024*1024. In other words, it is 250 MB, not 250 MiB. Note that Windows Explorer will show file sizes in KiB, not thousands of bytes. Use 'dir' from a CMD window to get the\n exact size in bytes for each file. For example -- the file `libtorch_cpu.so` shows up as 511,872 KB in Windows Explorer, but 524,156,144 bytes in CMD. The 2.4% difference can be significant.\n\n If the combined size of the files going into a part is smaller than 250MB, then everything is fine, and there is no need to split the part. It can be singular. If that is not the case, then the part should be fragmented into two or more parts that are linked together by their names.\n\n For example, the following snippet spreads the `torch_cuda_cu.dll` binary file into four fragments of 250 MB each. After compression, they will be even smaller.\n\n ```xml\n <File Include= \"libtorch\\lib\\torch_cuda_cu.dll\" PackageSuffix=\"part9-primary\" FileUnstitchIndex=\"0\" FileUnstitchStart=\"0\" FileUnstitchSize=\"250000000\" />\n <File Include= \"libtorch\\lib\\torch_cuda_cu.dll\" PackageSuffix=\"part9-fragment1\" FileUnstitchIndex=\"1\" FileUnstitchStart=\"250000000\" FileUnstitchSize=\"250000000\" />\n <File Include= \"libtorch\\lib\\torch_cuda_cu.dll\" PackageSuffix=\"part9-fragment2\" FileUnstitchIndex=\"2\" FileUnstitchStart=\"500000000\" FileUnstitchSize=\"250000000\" />\n <File Include= \"libtorch\\lib\\torch_cuda_cu.dll\" PackageSuffix=\"part9-fragment3\" FileUnstitchIndex=\"3\" FileUnstitchStart=\"750000000\" FileUnstitchSize=\"-1\" />\n ```\n\n They must all be called either 'primary,' which should be the first fragment, or 'fragmentN' where 'N' is the ordinal number of the fragment, starting with '1'. The current logic allows for as many as 10 non-primary fragments. If more are needed, the code in [FileRestitcher.cs](pkg/FileRestitcher/FileRestitcher/FileRestitcher.cs) and [RestitchPackage.targets](pkg/common/RestitchPackage.targets) needs to be updated. Note that the size of each fragment is expressed in bytes, and that fragment start must be\n the sum of the size of all previous fragments. A '-1' should be used for the last fragment (and only for the last fragment): it means that the fragment size will be based on how much there is still left of the file.\n\n Each part, whether singular or fragmented, should have its own .nupkgproj file in its own folder under pkg. The folder and file should have the same name as the part. If you need to add new fragments, it is straightforward to just copy an existing fragment folder and rename it as well as the project file to the new fragment. If you must fragment a previously singular part, it is best to rename the existing folder and file to '-fragment1' and then copy a '-primary' folder and rename with the right part name. This is because the primary .nupkgproj files look different from others. Specifically, they include different build targets:\n\n```\n<Content Include=\"..\\common\\NormalPackage.props\" Pack=\"true\" PackagePath=\"buildTransitive\\netstandard2.0\\$(MSBuildProjectName).props\" />\n<Content Include=\"..\\common\\NormalPackage.targets\" Pack=\"true\" PackagePath=\"buildTransitive\\netstandard2.0\\$(MSBuildProjectName).targets\" />\n```\nvs.\n```\n<Content Include=\"..\\common\\RestitchPackage.props\" Pack=\"true\" PackagePath=\"buildTransitive\\netstandard2.0\\$(MSBuildProjectName).props\" />\n<Content Include=\"..\\common\\RestitchPackage.targets\" Pack=\"true\" PackagePath=\"buildTransitive\\netstandard2.0\\$(MSBuildProjectName).targets\" />\n```\n\n It is the 'RestitchPackage.targets' that will trigger restitching packages on first build after a download.\n\n Because file sizes change from release to release, it may be necessary to add or remove fragments. When you add a fragment, you also need to add a corresponding project folder under the `pkg/` top-level folder. The process of doing so is copy-paste-rename of existing folders. The same goes for adding parts (whether fragmented or not): you should add a corresponding folder and project file. If you remove a fragment (or part), you should remove the corresponding folder, or CI will end up building empty packages.\n\n Once you have carefully edited the parts and the files that go into them, clean the build directory and re-issue the libtorch downloads commands until there are no errors.\n\n4. Add the SHA files:\n\n git add src\\Redist\\libtorch-cpu\\*.sha\n git add src\\Redist\\libtorch-cuda-11.7\\*.sha\n\n After this you may as well submit to CI just to see what happens, though keep going with the other steps below as well.\n\n5. Build the native and managed code without CUDA\n\n dotnet build /p:SkipCuda=true\n\n The first stage unzips the archives, then CMAKE is run.\n\n Unzipping the archives may take quite a while\n\n Note that things may have changed in the LibTorch header files, linking flags etc. There is a CMakeLists.txt that acquires\n the cmake information delievered in the LibTorch download. It can be subtle.\n\n If the vxcproj for the native code gets configured by cmake then you should now be able to start developing the C++ code in Visual Studio. In order to get the correct environment variables and PATH, start VS from the command line, not from the Start menu:\n\n devenv TorchSharp.sln\n\n e.g. the vcxproj is created here:\n\n bin\\obj\\x64.Debug\\Native\\LibTorchSharp\\LibTorchSharp.vcxproj\n\n6. Similarly build the native code with CUDA\n\n dotnet build\n\n7. You must also adjust the set of binaries referenced for tests, see various files under `tests` and `NativeAssemblyReference` in `TorchSharp\\Directory.Build.targets`.\n\n8. Run tests\n\n dotnet test -c Debug\n dotnet test -c Release\n\n9. Try building packages locally. The build (including CI) doesn't build `libtorch-*` packages by default, just the managed package. To\n get CI to build new `libtorch-*` packages update this version and set `BuildLibTorchPackages` in [azure-pipelines.yml](azure-pipelines.yml):\n\n <LibTorchPackageVersion>2.0.1.1</LibTorchPackageVersion>\n\n dotnet pack -c Release -v:n /p:SkipNative=true /p:SkipTests=true /p:IncludeTorchSharpPackage=true /p:IncludeLibTorchCpuPackages=true /p:IncludeLibTorchCudaPackages=true \n dotnet pack -c Release -v:n /p:SkipNative=true /p:SkipTests=true /p:TargetOS=linux /p:IncludeTorchSharpPackage=true /p:IncludeLibTorchCpuPackages=true /p:IncludeLibTorchCudaPackages=true \n\n Once these finish, the output can be found in `bin\\packages\\Release`. Look at the file sizes -- if anything is larger than 250,000,000 bytes, you need to go back to #3 above and redefine the package contents and fragmentation scheme. It maybe necessary to introduce new fragments.\n\n\t**Note:** The locally built TorchSharp packages will only contain binaries for the local platform, so they cannot be used with other platforms. Therefore, only the packages built in Azure Pipelines can be used across platforms.\n\n10. Submit to CI and debug problems.\n\n11. Remember to delete all massive artifacts from Azure DevOps and reset this `BuildLibTorchPackages` in in [azure-pipelines.yml](azure-pipelines.yml)\n\n\n## Building with Visual Studio\n\nIn order for builds to work properly using Visual Studio 2019 or 2022, you must start VS from the 'x64 Native Tools Command Prompt for VS 2022' (or 2019) in order for the full environment to be set up correctly. Starting VS from the desktop or taskbar will not work properly.\n" }, { "alpha_fraction": 0.5828996300697327, "alphanum_fraction": 0.5828996300697327, "avg_line_length": 29.56818199157715, "blob_id": "2b087b3d91125673cf2ede27866c749d34cf855a", "content_id": "75fbb7fe1670679337ea08e3334aa33fcc755db2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1345, "license_type": "permissive", "max_line_length": 130, "num_lines": 44, "path": "/src/TorchVision/ConvertImageDType.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System;\nusing static TorchSharp.torch;\n\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class ConvertImageDType : ITransform\n {\n internal ConvertImageDType(ScalarType dtype)\n {\n this.dtype = dtype;\n }\n\n public Tensor call(Tensor image)\n {\n return transforms.functional.convert_image_dtype(image, dtype);\n }\n\n private ScalarType dtype;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Convert a tensor image to the given dtype and scale the values accordingly\n /// </summary>\n /// <param name=\"dtype\">Desired data type of the output</param>\n static public ITransform ConvertImageDtype(ScalarType dtype)\n {\n return new ConvertImageDType(dtype);\n }\n\n [Obsolete(\"Deprecating misspelled transform. Use 'ConvertImageDtype' instead.\", false)]\n static public ITransform ConvertImageDType(ScalarType dtype)\n {\n return new ConvertImageDType(dtype);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6029554605484009, "alphanum_fraction": 0.6115756034851074, "avg_line_length": 55.10545349121094, "blob_id": "855079652f749440f763aacecbbbe169c7858425", "content_id": "ca0beb8da07f1d446c03c6ab29da504e8fb52924", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 15429, "license_type": "permissive", "max_line_length": 254, "num_lines": 275, "path": "/src/TorchSharp/Tensor/Factories/tensor_Complex.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torch\n {\n /// <summary>\n /// Create a scalar tensor from a single value\n /// </summary>\n public static Tensor tensor(System.Numerics.Complex scalar, ScalarType? dtype = null, Device? device = null, bool requires_grad = false)\n {\n device = InitializeDevice(device);\n var handle = THSTensor_newComplexFloat64Scalar(scalar.Real, scalar.Imaginary, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) { CheckForErrors(); }\n var tensor = new Tensor(handle);\n tensor = dtype.HasValue ? tensor.to(dtype.Value, device) : tensor.to(device);\n return tensor;\n }\n\n /// <summary>\n /// Create a tensor from an array of values, shaping it based on the shape passed in.\n /// </summary>\n /// <remarks>The Torch runtime does not take ownership of the data, so there is no device argument.</remarks>\n [Pure]\n public static Tensor tensor(IList<(float Real, float Imaginary)> rawArray, ReadOnlySpan<long> dimensions, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return tensor(rawArray.ToArray(), dimensions, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a tensor from an array of values, shaping it based on the shape passed in.\n /// </summary>\n [Pure]\n public static Tensor tensor((float Real, float Imaginary)[] rawArray, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n var dataArray = new float[rawArray.Length * 2];\n for (var i = 0; i < rawArray.Length; i++) {\n dataArray[i * 2] = rawArray[i].Real;\n dataArray[i * 2 + 1] = rawArray[i].Imaginary;\n }\n\n return _tensor_generic(dataArray, stackalloc long[] { rawArray.LongLength }, (sbyte)ScalarType.ComplexFloat32, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a tensor from an array of values, shaping it based on the shape passed in.\n /// </summary>\n [Pure]\n public static Tensor tensor((float Real, float Imaginary)[] rawArray, ReadOnlySpan<long> dimensions, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n var dataArray = new float[rawArray.Length * 2];\n for (var i = 0; i < rawArray.Length; i++) {\n dataArray[i * 2] = rawArray[i].Real;\n dataArray[i * 2 + 1] = rawArray[i].Imaginary;\n }\n\n return _tensor_generic(dataArray, dimensions, (sbyte)ScalarType.ComplexFloat32, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a 1-D tensor from an array of values, shaping it based on the input array.\n /// </summary>\n /// <remarks>The Torch runtime does not take ownership of the data, so there is no device argument.</remarks>\n [Pure]\n public static Tensor tensor(IList<(float Real, float Imaginary)> rawArray, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return tensor(rawArray, stackalloc long[] { (long)rawArray.Count }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a tensor from an array of values, organizing it as a two-dimensional tensor.\n /// </summary>\n /// <remarks>\n /// The Torch runtime does not take ownership of the data, so there is no device argument.\n /// The input array must have rows * columns elements.\n /// </remarks>\n [Pure]\n public static Tensor tensor(IList<(float Real, float Imaginary)> rawArray, long rows, long columns, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return tensor(rawArray, stackalloc long[] { rows, columns }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a tensor from an array of values, organizing it as a three-dimensional tensor.\n /// </summary>\n /// <remarks>\n /// The Torch runtime does not take ownership of the data, so there is no device argument.\n /// The input array must have dim0*dim1*dim2 elements.\n /// </remarks>\n [Pure]\n public static Tensor tensor(IList<(float Real, float Imaginary)> rawArray, long dim0, long dim1, long dim2, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return tensor(rawArray, stackalloc long[] { dim0, dim1, dim2 }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a tensor from an array of values, organizing it as a four-dimensional tensor.\n /// </summary>\n /// <remarks>\n /// The Torch runtime does not take ownership of the data, so there is no device argument.\n /// The input array must have dim0*dim1*dim2*dim3 elements.\n /// </remarks>\n [Pure]\n public static Tensor tensor(IList<(float Real, float Imaginary)> rawArray, long dim0, long dim1, long dim2, long dim3, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return tensor(rawArray, stackalloc long[] { dim0, dim1, dim2, dim3 }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a two-dimensional tensor from a two-dimensional array of values.\n /// </summary>\n [Pure]\n public static Tensor tensor((float Real, float Imaginary)[,] rawArray, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n var dataArray = new float[rawArray.GetLongLength(0), rawArray.GetLongLength(1) * 2];\n for (var i = 0; i < rawArray.GetLongLength(0); i++) {\n for (var j = 0; j < rawArray.GetLongLength(1); j++) {\n dataArray[i, j * 2] = rawArray[i, j].Real;\n dataArray[i, j * 2 + 1] = rawArray[i, j].Imaginary;\n }\n }\n\n return _tensor_generic(dataArray, stackalloc long[] { rawArray.GetLongLength(0), rawArray.GetLongLength(1) }, (sbyte)ScalarType.ComplexFloat32, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a three-dimensional tensor from a three-dimensional array of values.\n /// </summary>\n [Pure]\n public static Tensor tensor((float Real, float Imaginary)[,,] rawArray, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n var dataArray = new float[rawArray.GetLongLength(0), rawArray.GetLongLength(1), rawArray.GetLongLength(2) * 2];\n for (var i = 0; i < rawArray.GetLongLength(0); i++) {\n for (var j = 0; j < rawArray.GetLongLength(1); j++) {\n for (var k = 0; k < rawArray.GetLongLength(2); k++) {\n dataArray[i, j, k * 2] = rawArray[i, j, k].Real;\n dataArray[i, j, k * 2 + 1] = rawArray[i, j, k].Imaginary;\n }\n }\n }\n\n return _tensor_generic(dataArray, stackalloc long[] { rawArray.GetLongLength(0), rawArray.GetLongLength(1), rawArray.GetLongLength(2) }, (sbyte)ScalarType.ComplexFloat32, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a four-dimensional tensor from a four-dimensional array of values.\n /// </summary>\n [Pure]\n public static Tensor tensor((float Real, float Imaginary)[,,,] rawArray, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n var dataArray = new float[rawArray.GetLongLength(0), rawArray.GetLongLength(1), rawArray.GetLongLength(2), rawArray.GetLongLength(3) * 2];\n for (var i = 0; i < rawArray.GetLongLength(0); i++) {\n for (var j = 0; j < rawArray.GetLongLength(1); j++) {\n for (var k = 0; k < rawArray.GetLongLength(2); k++) {\n for (var l = 0; l < rawArray.GetLongLength(3); l++) {\n dataArray[i, j, k, l * 2] = rawArray[i, j, k, l].Real;\n dataArray[i, j, k, l * 2 + 1] = rawArray[i, j, k, l].Imaginary;\n }\n }\n }\n }\n\n return _tensor_generic(dataArray, stackalloc long[] { rawArray.GetLongLength(0), rawArray.GetLongLength(1), rawArray.GetLongLength(2), rawArray.GetLongLength(3) }, (sbyte)ScalarType.ComplexFloat32, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a tensor from an array of values, shaping it based on the shape passed in.\n /// </summary>\n /// <remarks>The Torch runtime does not take ownership of the data, so there is no device argument.</remarks>\n [Pure]\n public static Tensor tensor(IList<System.Numerics.Complex> rawArray, ReadOnlySpan<long> dimensions, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return tensor(rawArray.ToArray(), dimensions, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a tensor from an array of values, shaping it based on the shape passed in.\n /// </summary>\n [Pure]\n public static Tensor tensor(System.Numerics.Complex[] rawArray, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _tensor_generic(rawArray, stackalloc long[] { rawArray.LongLength }, (sbyte)ScalarType.ComplexFloat64, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a tensor from an array of values, shaping it based on the shape passed in.\n /// </summary>\n [Pure]\n public static Tensor tensor(System.Numerics.Complex[] rawArray, ReadOnlySpan<long> dimensions, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _tensor_generic(rawArray, dimensions, (sbyte)ScalarType.ComplexFloat64, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a 1-D tensor from an array of values, shaping it based on the input array.\n /// </summary>\n /// <remarks>The Torch runtime does not take ownership of the data, so there is no device argument.</remarks>\n [Pure]\n public static Tensor tensor(IList<System.Numerics.Complex> rawArray, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return tensor(rawArray, stackalloc long[] { (long)rawArray.Count }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a tensor from an array of values, organizing it as a two-dimensional tensor.\n /// </summary>\n /// <remarks>\n /// The Torch runtime does not take ownership of the data, so there is no device argument.\n /// The input array must have rows * columns elements.\n /// </remarks>\n [Pure]\n public static Tensor tensor(IList<System.Numerics.Complex> rawArray, long rows, long columns, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return tensor(rawArray, stackalloc long[] { rows, columns }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a tensor from an array of values, organizing it as a three-dimensional tensor.\n /// </summary>\n /// <remarks>\n /// The Torch runtime does not take ownership of the data, so there is no device argument.\n /// The input array must have dim0*dim1*dim2 elements.\n /// </remarks>\n [Pure]\n public static Tensor tensor(IList<System.Numerics.Complex> rawArray, long dim0, long dim1, long dim2, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return tensor(rawArray, stackalloc long[] { dim0, dim1, dim2 }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a tensor from an array of values, organizing it as a four-dimensional tensor.\n /// </summary>\n /// <remarks>\n /// The Torch runtime does not take ownership of the data, so there is no device argument.\n /// The input array must have dim0*dim1*dim2*dim3 elements.\n /// </remarks>\n public static Tensor tensor(IList<System.Numerics.Complex> rawArray, long dim0, long dim1, long dim2, long dim3, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return tensor(rawArray, stackalloc long[] { dim0, dim1, dim2, dim3 }, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a two-dimensional tensor from a two-dimensional array of values.\n /// </summary>\n [Pure]\n public static Tensor tensor(System.Numerics.Complex[,] rawArray, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _tensor_generic(rawArray, stackalloc long[] { rawArray.GetLongLength(0), rawArray.GetLongLength(1) }, (sbyte)ScalarType.ComplexFloat64, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a three-dimensional tensor from a three-dimensional array of values.\n /// </summary>\n [Pure]\n public static Tensor tensor(System.Numerics.Complex[,,] rawArray, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _tensor_generic(rawArray, stackalloc long[] { rawArray.GetLongLength(0), rawArray.GetLongLength(1), rawArray.GetLongLength(2) }, (sbyte)ScalarType.ComplexFloat64, dtype, device, requires_grad, names: names);\n }\n\n /// <summary>\n /// Create a four-dimensional tensor from a four-dimensional array of values.\n /// </summary>\n [Pure]\n public static Tensor tensor(System.Numerics.Complex[,,,] rawArray, ScalarType? dtype = null, Device? device = null, bool requires_grad = false, string[]? names = null)\n {\n return _tensor_generic(rawArray, stackalloc long[] { rawArray.GetLongLength(0), rawArray.GetLongLength(1), rawArray.GetLongLength(2), rawArray.GetLongLength(3) }, (sbyte)ScalarType.ComplexFloat64, dtype, device, requires_grad, names: names);\n }\n }\n}\n" }, { "alpha_fraction": 0.5445655584335327, "alphanum_fraction": 0.5601370334625244, "avg_line_length": 27.168420791625977, "blob_id": "9d1758d9c9b3184f3ed8c0563d3114210bed1353", "content_id": "f499fcb94f1eba7639ccd7d62baf9a6f9c67faf0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 16055, "license_type": "permissive", "max_line_length": 228, "num_lines": 570, "path": "/src/Native/LibTorchSharp/THSJIT.cpp", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "//// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#include \"THSJIT.h\"\n\nJITModule THSJIT_load(const char* filename, int64_t device, int64_t index)\n{\n c10::DeviceType dev = c10::kCPU;\n if (device == 1)\n dev = c10::kCUDA;\n\n CATCH(\n auto res = torch::jit::load(filename, torch::Device(dev, index));\n auto copy = new torch::jit::Module(res);\n return new std::shared_ptr<torch::jit::Module>(copy);\n );\n\n return nullptr;\n}\n\nJITCompilationUnit THSJIT_compile(const char* script)\n{\n CATCH(\n auto res = torch::jit::compile(script);\n return new std::shared_ptr<torch::jit::CompilationUnit>(res);\n );\n\n return nullptr;\n}\n\nvoid THSJIT_save(JITModule module, const char* filename)\n{\n CATCH(\n (*module)->save(filename);\n );\n}\n\nint THSJIT_Module_is_training(JITModule module)\n{\n return (*module)->is_training();\n}\n\nvoid THSJIT_Module_train(JITModule module, bool on)\n{\n (*module)->train(on);\n}\n\nvoid THSJIT_Module_eval(JITModule module)\n{\n (*module)->eval();\n}\n\nvoid THSJIT_Module_to_device_dtype(JITModule module, int8_t dtype, int64_t device, int64_t index)\n{\n c10::DeviceType dev = c10::kCPU;\n if (device == 1)\n dev = c10::kCUDA;\n (*module)->to(torch::Device(dev, index), (at::ScalarType)dtype);\n}\n\nvoid THSJIT_Module_to_device(JITModule module, int64_t device, int64_t index)\n{\n c10::DeviceType dev = c10::kCPU;\n if (device == 1)\n dev = c10::kCUDA;\n (*module)->to(torch::Device(dev, index));\n}\n\nvoid THSJIT_Module_to_dtype(JITModule module, int8_t dtype)\n{\n (*module)->to((at::ScalarType)dtype);\n}\n\nvoid THSJIT_Module_modules(const JITModule module, JITModule* (*allocator)(size_t length))\n{\n auto modules = (*module)->modules();\n JITModule* result = allocator(modules.size());\n int i = 0;\n for (const auto& child : modules) {\n auto copy = new torch::jit::Module(child);\n result[i++] = new std::shared_ptr<torch::jit::Module>(copy);\n }\n}\n\nvoid THSJIT_Module_named_modules(const JITModule module,\n JITModule* (*allocator)(size_t length),\n const char** (*allocator2)(size_t length))\n{\n auto modules = (*module)->named_modules();\n JITModule* result = allocator(modules.size());\n const char** names = allocator2(modules.size());\n int i = 0;\n for (const auto& child : modules) {\n auto copy = new torch::jit::Module(child.value);\n result[i] = new std::shared_ptr<torch::jit::Module>(copy);\n names[i] = make_sharable_string(child.name);\n i++;\n }\n}\n\nvoid THSJIT_Module_named_children(const JITModule module,\n JITModule* (*allocator)(size_t length),\n const char** (*allocator2)(size_t length))\n{\n auto modules = (*module)->named_children();\n JITModule* result = allocator(modules.size());\n const char** names = allocator2(modules.size());\n int i = 0;\n for (const auto& child : modules) {\n auto copy = new torch::jit::Module(child.value);\n result[i] = new std::shared_ptr<torch::jit::Module>(copy);\n names[i] = make_sharable_string(child.name);\n i++;\n }\n}\n\nvoid THSJIT_Module_parameters(const JITModule module, Tensor* (*allocator)(size_t length))\n{\n auto parameters = (*module)->parameters();\n Tensor* result = allocator(parameters.size());\n int i = 0;\n for (const auto& child : parameters) {\n result[i++] = new torch::Tensor(child);\n }\n}\n\nvoid THSJIT_Module_named_parameters(const JITModule module,\n Tensor* (*allocator)(size_t length),\n const char** (*allocator2)(size_t length))\n{\n auto parameters = (*module)->named_parameters();\n Tensor* result = allocator(parameters.size());\n const char** names = allocator2(parameters.size());\n int i = 0;\n for (const auto& child : parameters) {\n result[i] = new torch::Tensor(child.value);\n names[i] = make_sharable_string(child.name);\n i++;\n }\n}\n\nvoid THSJIT_Module_named_buffers(const JITModule module,\n Tensor* (*allocator)(size_t length),\n const char** (*allocator2)(size_t length))\n{\n auto parameters = (*module)->named_buffers();\n Tensor* result = allocator(parameters.size());\n const char** names = allocator2(parameters.size());\n int i = 0;\n for (const auto& child : parameters) {\n result[i] = new torch::Tensor(child.value);\n names[i] = make_sharable_string(child.name);\n i++;\n }\n}\n\nJITMethod THSJIT_Module_get_method(const JITModule module, const char* name)\n{\n auto method = (*module)->get_method(name);\n auto copy = new torch::jit::Method(method);\n return new std::shared_ptr<torch::jit::Method>(copy);\n}\n\nTensorOrScalar* ReturnHelper(c10::IValue result, TensorOrScalar* (*allocator)(int32_t idx, size_t length), int8_t* typeCode, int32_t* idx)\n{\n // TypeCode:\n //\n // 0 -- Not supported\n // 1 -- Single tensor\n // 2 -- Tuple of tensors\n // 3 -- List of tensors\n // 4 -- Single scalar\n // 5 -- Scalar tuple\n // 6 -- List of scalars\n // 7 -- List of scalars and tensors\n // 8 -- None / null\n // 9 -- List of anything\n // 10 -- Tuple of anything\n\n if (result.isNone())\n {\n TensorOrScalar* output = allocator(idx[0]++, 1);\n output[0] = { 8, -1, (ptrdiff_t)0 };\n *typeCode = 8;\n return output;\n }\n\n if (result.isScalar())\n {\n TensorOrScalar* output = allocator(idx[0]++, 1);\n output[0] = { 0, -1, (ptrdiff_t)new torch::Scalar(result.toScalar()) };\n *typeCode = 4;\n return output;\n }\n\n if (result.isTensor()) {\n TensorOrScalar* output = allocator(idx[0]++, 1);\n output[0] = { 0, -1, (ptrdiff_t)ResultTensor(result.toTensor()) };\n *typeCode = 1;\n return output;\n }\n\n if (result.isTensorList()) {\n auto list = result.toTensorList();\n *typeCode = 3;\n TensorOrScalar* output = allocator(idx[0]++, list.size());\n for (size_t i = 0; i < list.size(); i++)\n output[i] = { 0, -1, (ptrdiff_t)ResultTensor(list[i]) };\n return output;\n }\n\n if (result.isList())\n {\n int foundTensor = 0;\n int foundScalar = 0;\n int foundNull = 0;\n int foundListOrTuple = 0;\n\n auto list = result.toList();\n TensorOrScalar* output = allocator(idx[0]++, list.size());\n\n for (int i = 0; i < list.size(); ++i)\n {\n output[i].Handle = -1;\n c10::IValue value = list[i];\n\n if (value.isTensor())\n {\n output[i] = { 0, -1, (ptrdiff_t)ResultTensor(value.toTensor()) };\n foundTensor += 1;\n continue;\n }\n if (value.isScalar())\n {\n output[i] = { 4, -1, (ptrdiff_t)new torch::Scalar(value.toScalar()) };\n foundScalar += 1;\n continue;\n }\n if (value.isNone())\n {\n output[i] = { 8, -1, (ptrdiff_t)0 };\n foundNull += 1;\n continue;\n }\n else {\n int8_t nestedTC = 0;\n int64_t arrIdx = idx[0];\n auto nested = ReturnHelper(value, allocator, &nestedTC, idx);\n foundListOrTuple += 1;\n output[i] = { nestedTC, arrIdx, (ptrdiff_t)nested };\n }\n }\n\n if (foundListOrTuple > 0) {\n *typeCode = 9;\n }\n else {\n *typeCode = 7;\n if (foundScalar == 0 && foundNull == 0)\n *typeCode = 3;\n if (foundTensor == 0 && foundNull == 0)\n *typeCode = 6;\n }\n return output;\n }\n\n if (result.isTuple()) {\n int foundTensor = 0;\n int foundScalar = 0;\n int foundNull = 0;\n int foundListOrTuple = 0;\n\n auto& list = result.toTuple()->elements();\n TensorOrScalar* output = allocator(idx[0]++, list.size());\n\n for (int i = 0; i < list.size(); ++i)\n {\n output[i].Handle = -1;\n c10::IValue value = list[i];\n\n if (value.isTensor())\n {\n output[i] = { 0, -1, (ptrdiff_t)ResultTensor(value.toTensor()) };\n foundTensor += 1;\n continue;\n }\n if (value.isScalar())\n {\n output[i] = { 4, -1, (ptrdiff_t)new torch::Scalar(value.toScalar()) };\n foundScalar += 1;\n continue;\n }\n if (value.isNone())\n {\n output[i] = { 8, -1, (ptrdiff_t)0 };\n foundNull += 1;\n continue;\n }\n else {\n int8_t nestedTC = 0;\n int64_t arrIdx = idx[0];\n auto nested = ReturnHelper(value, allocator, &nestedTC, idx);\n foundListOrTuple += 1;\n output[i] = { nestedTC, arrIdx, (ptrdiff_t)nested };\n }\n }\n\n *typeCode = 10;\n if (foundListOrTuple == 0) {\n if (foundScalar == 0 && foundNull == 0)\n *typeCode = 2;\n if (foundTensor == 0 && foundNull == 0)\n *typeCode = 5;\n }\n\n return output;\n }\n\n *typeCode = 0;\n return nullptr;\n}\n\nc10::impl::GenericList toScalarValueList(const TensorOrScalar* tensorPtrs, const int length)\n{\n auto list = c10::impl::GenericList(c10::ScalarTypeType::get());\n\n if (tensorPtrs != nullptr) {\n for (int i = 0; i < length; i++)\n {\n switch (tensorPtrs[i].TypeCode) {\n case 1:\n list.push_back(*(torch::Scalar*)(tensorPtrs[i].Handle));\n break;\n }\n }\n }\n\n return list;\n}\n\nc10::impl::GenericList toTensorValueList(const TensorOrScalar* tensorPtrs, const int length)\n{\n auto list = c10::impl::GenericList(c10::TensorType::get());\n\n if (tensorPtrs != nullptr) {\n for (int i = 0; i < length; i++)\n {\n switch (tensorPtrs[i].TypeCode) {\n case 0:\n list.push_back(*(torch::Tensor*)(tensorPtrs[i].Handle));\n break;\n }\n }\n }\n\n return list;\n}\n\nstd::vector<c10::IValue> toIValue(const TensorOrScalar* tensorPtrs, const int length)\n{\n // TypeCode:\n //\n // 0 -- Single tensor\n // 1 -- Single scalar\n // 2 -- Boolean\n // 3 -- Int32\n // 5 -- List of tensors\n // 6 -- List of scalars\n // 8 -- None / null\n\n std::vector<c10::IValue> tensors;\n\n if (tensorPtrs != nullptr) {\n for (int i = 0; i < length; i++)\n {\n switch (tensorPtrs[i].TypeCode) {\n case 0:\n tensors.push_back(*(torch::Tensor*)(tensorPtrs[i].Handle));\n break;\n case 1:\n tensors.push_back(*(torch::Scalar*)(tensorPtrs[i].Handle));\n break;\n case 2:\n tensors.push_back(tensorPtrs[i].Handle != 0);\n break;\n case 3:\n tensors.push_back((int)tensorPtrs[i].Handle);\n break;\n case 5:\n {\n auto ts = toTensorValueList(reinterpret_cast<const TensorOrScalar*>(tensorPtrs[i].Handle), (int)tensorPtrs[i].ArrayIndex);\n tensors.push_back(ts);\n break;\n }\n case 6:\n {\n auto ts = toScalarValueList(reinterpret_cast<const TensorOrScalar*>(tensorPtrs[i].Handle), (int)tensorPtrs[i].ArrayIndex);\n tensors.push_back(ts);\n break;\n }\n //case 4:\n // tensors.push_back(c10::IValue(tensorPtrs[i].Handle)); // Clang on MacOS doesn't like. Pass as Scalar from .NET.\n // break;\n case 8:\n tensors.push_back(c10::nullopt);\n break;\n }\n }\n }\n return tensors;\n}\n\nvoid THSJIT_Module_forward(const JITModule module, const TensorOrScalar* tensorPtrs, const int length, TensorOrScalar* (*allocator)(int32_t idx, size_t length), int8_t* typeCode, int32_t idx)\n{\n *typeCode = 0;\n\n CATCH(\n auto result = (*module)->forward(toIValue(tensorPtrs, length));\n ReturnHelper(result, allocator, typeCode, &idx);\n )\n}\n\nvoid THSJIT_Module_invoke(const JITModule module, const char* name, const TensorOrScalar* tensorPtrs, const int length, TensorOrScalar* (*allocator)(int32_t idx, size_t length), int8_t* typeCode, int32_t idx)\n{\n *typeCode = 0;\n\n CATCH(\n auto method = (*module)->get_method(name);\n auto result = method(toIValue(tensorPtrs, length));\n ReturnHelper(result, allocator, typeCode, &idx);\n )\n}\n\nvoid THSJIT_CompilationUnit_Invoke(const JITCompilationUnit module, const char* method, const TensorOrScalar* tensorPtrs, const int length, TensorOrScalar* (*allocator)(int32_t idx, size_t length), int8_t* typeCode, int32_t idx)\n{\n *typeCode = 0;\n\n CATCH(\n auto args = toIValue(tensorPtrs, length);\n auto func = (*module)->find_function(method);\n auto result = (*func)(args);\n ReturnHelper(result, allocator, typeCode, &idx);\n )\n}\n\nvoid THSJIT_Module_dispose(const JITModule module)\n{\n delete module;\n}\n\nconst char* THSJIT_Method_name(const JITMethod method)\n{\n return make_sharable_string((*method)->name());\n}\n\nint THSJIT_Method_num_inputs(const JITMethod method)\n{\n return (int)(*method)->num_inputs();\n}\n\nint THSJIT_Module_num_inputs(const JITModule module)\n{\n return (int)(*module)->get_method(\"forward\").num_inputs() - 1; // Don't count the 'self' argument.\n}\n\nint THSJIT_Module_num_outputs(const JITModule module)\n{\n return (int)(*module)->get_method(\"forward\").function().getSchema().returns().size();\n}\n\nJITFunction THSJIT_Method_function(const JITMethod method)\n{\n return new std::shared_ptr<torch::jit::Function>(&(*method)->function());\n}\n\nvoid THSJIT_Method_dispose(const JITMethod method)\n{\n delete method;\n}\n\n\n//-------------------------------------------------------------------------------------\n// JITFunction\n\nint THSJIT_Function_num_inputs(const JITFunction function)\n{\n return (int)(*function)->num_inputs();\n}\n\n// TODO other function operations\n\nvoid THSJIT_Function_dispose(const JITFunction function)\n{\n delete function;\n}\n\nvoid THSJIT_Type_dispose(const JITType type)\n{\n delete type;\n}\n\nvoid THSJIT_TensorType_dispose(const JITTensorType type)\n{\n delete type;\n}\n\nvoid THSJIT_CompilationUnit_dispose(const JITCompilationUnit module)\n{\n delete module;\n}\n\nvoid* THSJIT_Type_cast(const JITType type)\n{\n switch ((*type)->kind())\n {\n case c10::TypeKind::TensorType:\n return new std::shared_ptr<torch::jit::TensorType>((*type)->cast<c10::TensorType>());\n default:\n return nullptr;\n }\n}\n\nint8_t THSJIT_TensorType_dtype(const JITTensorType type)\n{\n auto scT = (*type)->scalarType();\n if (scT.has_value()) {\n return (int8_t)scT.value();\n }\n else {\n return -1;\n }\n}\n\nvoid THSJIT_TensorType_sizes(const JITTensorType type, int64_t* (*allocator)(int64_t length))\n{\n //CATCH(\n auto& t = *type;\n auto dim = t->dim();\n auto res = (*type)->sizes().concrete_sizes();\n if (res.has_value()) {\n const size_t sz = res.value().size();\n auto& vec = res.value();\n int64_t* result = allocator(sz);\n for (size_t i = 0; i < sz; i++)\n result[i] = vec[i];\n }\n //);\n}\n\nint8_t THSJIT_Type_kind(const JITType type)\n{\n switch ((*type)->kind())\n {\n case c10::TypeKind::TensorType:\n return (int8_t)TypeKind::TensorType;\n default:\n return -1;\n }\n}\n\nJITType THSJIT_Module_getInputType(JITModule module, int8_t index)\n{\n auto typ = (*module)->type();\n c10::TypeKind kind = typ->kind();\n auto& schema = typ->getMethod(\"forward\").getSchema();\n return new std::shared_ptr<c10::Type>(schema.arguments()[1 + index].type()->cast<c10::TensorType>());\n}\n\nvoid THSJIT_typeDispose(const JITType type)\n{\n delete type;\n}" }, { "alpha_fraction": 0.5610817670822144, "alphanum_fraction": 0.5654336214065552, "avg_line_length": 41.893333435058594, "blob_id": "294f19d6ce8e73ac9d7f3f89c6c3b83343b0db61", "content_id": "269d5aeec9b37db8c643bdd8a0eb80e90278a1d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3217, "license_type": "permissive", "max_line_length": 130, "num_lines": 75, "path": "/src/TorchSharp/NN/Pooling/AdaptiveMaxPool1D.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a AdaptiveMaxPool1D module.\n /// </summary>\n public sealed class AdaptiveMaxPool1d : torch.nn.Module<Tensor, Tensor>\n {\n internal AdaptiveMaxPool1d(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_AdaptiveMaxPool1d_forward(handle.DangerousGetHandle(), tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies a 1D adaptive max pooling over an input signal composed of several input planes.\n /// The output size is H, for any input size.The number of output features is equal to the number of input planes.\n /// </summary>\n /// <param name=\"outputSize\">The target output size H.</param>\n /// <returns></returns>\n public static AdaptiveMaxPool1d AdaptiveMaxPool1d(long outputSize)\n {\n unsafe {\n fixed (long* pkernelSize = new long[] { outputSize }) {\n var handle = THSNN_AdaptiveMaxPool1d_ctor((IntPtr)pkernelSize, 1, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new AdaptiveMaxPool1d(handle, boxedHandle);\n }\n }\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Applies a 1D adaptive max pooling over an input signal composed of several input planes.\n /// The output size is H, for any input size.The number of output features is equal to the number of input planes.\n /// </summary>\n /// <param name=\"x\"></param>\n /// <param name=\"outputSize\">The target output size H.</param>\n /// <returns></returns>\n public static Tensor adaptive_max_pool1d(Tensor x, long outputSize)\n {\n using (var d = nn.AdaptiveMaxPool1d(outputSize)) {\n return d.call(x);\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5511892437934875, "alphanum_fraction": 0.5511892437934875, "avg_line_length": 27.47058868408203, "blob_id": "6f27f657ce50c7b10abdd1abf3c693a2ae03117e", "content_id": "65cafa76d81cc8e1f60dd503b263689ad61b7156", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 967, "license_type": "permissive", "max_line_length": 130, "num_lines": 34, "path": "/src/TorchVision/Equalize.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class Equalize : ITransform\n {\n internal Equalize()\n {\n }\n\n public Tensor call(Tensor input)\n {\n return transforms.functional.equalize(input);\n }\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Equalize the histogram of an image by applying a non-linear mapping to the input\n /// in order to create a uniform distribution of grayscale values in the output.\n /// </summary>\n /// <returns></returns>\n static public ITransform Equalize()\n {\n return new Equalize();\n }\n }\n }\n}" }, { "alpha_fraction": 0.5818631052970886, "alphanum_fraction": 0.5931545495986938, "avg_line_length": 36.78666687011719, "blob_id": "1e4ceedc0f7af79c81dfd748726227cbb74e59fa", "content_id": "1b7c04be6aee2408f8f9acddbd8b1e854c004237", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2834, "license_type": "permissive", "max_line_length": 147, "num_lines": 75, "path": "/src/TorchAudio/Transforms/Resample.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\nusing static TorchSharp.torchaudio;\n\n// A number of implementation details in this file have been translated from the Python version of torchaudio,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/audio/blob/bb77cbebb620a46fdc0dc7e6dae2253eef3f37e2/torchaudio/transforms/_transforms.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/audio/blob/main/LICENSE\n//\n\nnamespace TorchSharp.Transforms\n{\n public sealed class Resample : nn.Module<Tensor, Tensor>, ITransform\n {\n private readonly int orig_freq;\n private readonly int new_freq;\n private readonly int gcd;\n private readonly ResamplingMethod resampling_method;\n private readonly int lowpass_filter_width;\n private readonly double rolloff;\n private readonly double? beta;\n public readonly torch.Tensor kernel;\n private readonly int width;\n\n internal Resample(\n string name,\n int orig_freq = 16000,\n int new_freq = 16000,\n ResamplingMethod resampling_method = ResamplingMethod.sinc_interpolation,\n int lowpass_filter_width = 6,\n double rolloff = 0.99,\n double? beta = null,\n torch.Device device = null,\n torch.ScalarType? dtype = null) : base(name)\n {\n this.orig_freq = orig_freq;\n this.new_freq = new_freq;\n this.gcd = functional.Gcd(this.orig_freq, this.new_freq);\n this.resampling_method = resampling_method;\n this.lowpass_filter_width = lowpass_filter_width;\n this.rolloff = rolloff;\n this.beta = beta;\n\n if (this.orig_freq != this.new_freq) {\n (this.kernel, this.width) = functional._get_sinc_resample_kernel(\n this.orig_freq,\n this.new_freq,\n this.gcd,\n this.lowpass_filter_width,\n this.rolloff,\n this.resampling_method,\n beta,\n device: device,\n dtype: dtype);\n }\n }\n\n public override Tensor forward(Tensor waveform)\n {\n using (var d = torch.NewDisposeScope()) {\n\n if (this.orig_freq == this.new_freq) {\n return d.MoveToOuter(waveform.alias());\n }\n var resampled = functional._apply_sinc_resample_kernel(waveform, this.orig_freq, this.new_freq, this.gcd, this.kernel, this.width);\n return d.MoveToOuter(resampled);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.7683320641517639, "alphanum_fraction": 0.7683320641517639, "avg_line_length": 57.30434799194336, "blob_id": "a9364ee07f8e08f08ac001c315ec37eb79442958", "content_id": "1449475a37a38f419d645e9e92b9f2ac7cbf81f7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4023, "license_type": "permissive", "max_line_length": 554, "num_lines": 69, "path": "/docfx/articles/saveload.md", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "# Saving and Restoring Model Weights and Buffers\n\nThere are typically two kinds of state in a model -- parameters, which contain trained weights, and buffers, which contain data that is not trained, but still essential for the functioning of the model. Both should generally be saved and loaded when serializing models.\n\nWhen using PyTorch, the expected pattern to use when saving and later restoring models from disk or other permanent storage media, is to get the model's state and pickle that using the standard Python format, which is what torch.save() does.\n\n```Python\ntorch.save(model.state_dict(), 'model_weights.pth')\n```\n\nWhen restoring the model, you are expected to first create a model of the exact same structure as the original, with random weights, then restore the state from a unpickled object:\n\n```Python\nmodel = [...]\nmodel.load_state_dict(torch.load('model_weights.pth'))\n```\n\nThis presents a couple of problems for a .NET implementation. \n\nPython pickling is intimately coupled to Python and its runtime object model. It is a complex format that supports object graphs forming DAGs, faithfully maintaining all object state in the way necessary to restore the Python object later.\n\nIn order to share models between .NET applications, Python pickling is not at all necessary, and even for moving model state from Python to .NET, it is overkill. The state of a model is a simple dictionary where the keys are strings and the values are tensors.\n\nTherefore, TorchSharp, in its current form, implements its own very simple model serialization format, which allows models originating in either .NET or Python to be loaded using .NET, as long as the model was saved using the special format.\n\nThe MNIST and AdversarialExampleGeneration examples in this repo rely on saving and restoring model state -- the latter example relies on a pre-trained model from MNST.\n\n><br/>A future version of TorchSharp may include support for reading and writing Python pickle files directly.<br/><br/>\n\n## How to use the TorchSharp format\n\nIn C#, saving a model looks like this:\n\n```C#\nmodel.save(\"model_weights.dat\");\n```\n\nAnd loading it again is done by:\n\n```C#\nmodel = [...];\nmodel.load(\"model_weights.dat\");\n```\n\nFor efficient memory management, the model should be created on the CPU before loading weights, then moved to the target device. \n\n><br/>It is __critical__ that all submodules and buffers in a custom module or composed by a Sequential object have exactly the same name in the original and target models, since that is how persisted tensors are associated with the model into which they are loaded.<br/><br/>The CustomModule 'RegisterComponents' will automatically find all fields that are either modules or tensors, register the former as modules, and the latter as buffers. It registers all of these using the name of the field, just like the PyTorch Module base class does.<br/><br/>\n\n### Saving a TorchSharp format model in Python\n\nIf the model starts out in Python, there's a simple script that allows you to use code that is very similar to the Pytorch API to save models to the TorchSharp format. Rather than placing this trivial script in a Python package and publishing it, we choose to just refer you to the script file itself, [exportsd.py](../../src/Python/exportsd.py), which has all the necessary code.\n\n```Python\nf = open(\"model_weights.dat\", \"wb\")\nexportsd.save_state_dict(model.to(\"cpu\").state_dict(), f)\nf.close()\n```\n\n### Loading a TorchSharp format model in Python\n\nIf the model starts out in TorchSharp, there's also a simple script that allows you to load TorchSharp models in Python. All the necessary code can be found in [importsd.py](../../src/Python/importsd.py). And there is an example for using the script:\n\n```Python\nf = open(\"model_weights.dat\", \"rb\")\nmodel.load_state_dict(importsd.load_state_dict(f))\nf.close()\n```\n\nAlso, you can check [TestSaveSD.cs](../../test/TorchSharpTest/TestSaveSD.cs) and [pyimporttest.py](../../test/TorchSharpTest/pyimporttest.py) for more examples.\n" }, { "alpha_fraction": 0.5555388927459717, "alphanum_fraction": 0.5616931915283203, "avg_line_length": 42.828948974609375, "blob_id": "80811e6f5af309d9ece46b0526897c28d45cfbc1", "content_id": "a64c2cf4e14e6a5efcf693bc379ab22a20581ce8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6664, "license_type": "permissive", "max_line_length": 174, "num_lines": 152, "path": "/src/TorchSharp/Distributions/Dirichlet.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using System.Reflection;\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// A Dirichlet distribution parameterized by shape `concentration` and `rate`.\n /// </summary>\n public class Dirichlet : torch.distributions.ExponentialFamily\n {\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public override Tensor mean => WrappedTensorDisposeScope(() => concentration / concentration.sum(-1, true));\n\n public override Tensor mode\n {\n get {\n using var _ = NewDisposeScope();\n var concentrationm1 = (concentration - 1).clamp(min: 0.0);\n var mode = concentrationm1 / concentrationm1.sum(-1, true);\n var mask = (concentration < 1).all(dim: -1);\n mode[mask] = torch.nn.functional.one_hot(mode[mask].argmax(dim: -1), concentrationm1.shape[concentrationm1.ndim-1]).to(mode);\n return mode.MoveToOuterDisposeScope();\n }\n }\n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public override Tensor variance {\n get {\n using var _ = NewDisposeScope();\n var con0 = concentration.sum(-1, true);\n return (concentration * (con0 - concentration) / (con0.pow(2) * (con0 + 1))).MoveToOuterDisposeScope();\n }\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"concentration\">Shape parameter of the distribution (often referred to as 'α')</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n public Dirichlet(Tensor concentration, torch.Generator generator = null) : base(generator)\n {\n var cshape = concentration.shape;\n this.batch_shape = cshape.Take(cshape.Length - 1).ToArray();\n this.event_shape = new long[] { cshape[cshape.Length - 1] };\n this.concentration = concentration.alias().DetachFromDisposeScope();\n }\n\n internal Tensor concentration;\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n public override Tensor rsample(params long[] sample_shape)\n {\n var shape = ExtendedShape(sample_shape);\n var con = concentration.expand(shape);\n return torch._sample_dirichlet(con, generator);\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor log_prob(Tensor value)\n {\n return (concentration - 1).xlogy(value).sum(-1) + torch.lgamma(concentration.sum(-1)) - torch.lgamma(concentration).sum(-1);\n }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n /// <returns></returns>\n public override Tensor entropy()\n {\n var k = concentration.size(-1);\n var a0 = concentration.sum(-1);\n\n return torch.lgamma(concentration).sum(-1) - torch.lgamma(a0) - (k - a0) * torch.digamma(a0) - ((concentration - 1.0) * torch.digamma(concentration)).sum(-1);\n }\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n /// <returns></returns>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is Dirichlet))\n throw new ArgumentException(\"expand(): 'instance' must be a Dirichlet distribution\");\n\n var shape = new List<long>();\n shape.AddRange(batch_shape);\n shape.AddRange(event_shape);\n\n var c = concentration.expand(shape.ToArray());\n\n var newDistribution = ((instance == null) ? new Dirichlet(c, generator) : instance) as Dirichlet;\n\n newDistribution.batch_shape = batch_shape;\n if (newDistribution == instance) {\n newDistribution.concentration = c;\n }\n return newDistribution;\n }\n\n protected override IList<Tensor> NaturalParams => new Tensor[] { concentration - 1 };\n\n protected override Tensor MeanCarrierMeasure => new Tensor(IntPtr.Zero);\n\n protected override Tensor LogNormalizer(params Tensor[] parameters)\n {\n var x = parameters[0];\n\n return x.lgamma().sum(-1) - x.sum(-1).lgamma();\n }\n }\n\n }\n\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a Dirichlet distribution parameterized by shape `concentration` and `rate`.\n /// </summary>\n /// <param name=\"concentration\">Shape parameter of the distribution (often referred to as 'α')</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n public static Dirichlet Dirichlet(Tensor concentration, torch.Generator generator = null)\n {\n return new Dirichlet(concentration, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6019668579101562, "alphanum_fraction": 0.6107660531997681, "avg_line_length": 41.93333435058594, "blob_id": "34943468d063eab1bd7d1795d69cc6214ebe07be", "content_id": "e1a05c2c1ff50a98a014898b866de336a8b34cb9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1932, "license_type": "permissive", "max_line_length": 130, "num_lines": 45, "path": "/src/Examples.Utils/Datasets.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace TorchText\n{\n /// <summary>\n /// This belongs in its own package, 'TorchText'.\n /// For now, it's useful to keep it with the examples that use it.\n /// </summary>\n public static class Datasets\n {\n /// <summary>\n /// WikiText2\n /// </summary>\n /// <param name=\"split\">One of 'train', 'valid', or 'test'</param>\n /// <param name=\"root\">The folder where the WikiText2 data set was downloaded and extracted.</param>\n /// <returns>An enumeration of lines from the text.</returns>\n /// <remarks>\n /// Download the data set at:\n /// https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-v1.zip\n /// </remarks>\n public static IEnumerable<string> WikiText2(string split, string root = \".data\")\n {\n var dataPath = Path.Combine(root, \"wikitext-2\", $\"wiki.{split}.tokens\");\n return File.ReadLines(dataPath).Select(line => line.Trim()).Where(line => line.Length > 0);\n }\n\n /// <summary>\n /// WikiText2\n /// </summary>\n /// <param name=\"root\">The folder where the WikiText2 data set was downloaded and extracted.</param>\n /// <returns>An enumeration of lines from the text for each of the data sets (training, validation, and test).</returns>\n /// <remarks>\n /// Download the data set at:\n /// https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-v1.zip\n /// </remarks>\n public static (IEnumerable<string>, IEnumerable<string>, IEnumerable<string>) WikiText2(string root = \".data\")\n {\n return (WikiText2(\"train\", root), WikiText2(\"valid\", root), WikiText2(\"test\", root));\n }\n }\n}\n" }, { "alpha_fraction": 0.56749027967453, "alphanum_fraction": 0.5711507797241211, "avg_line_length": 48.95428466796875, "blob_id": "c0b1df898de4c1b9016ebf756a5bcb14d4d8b619", "content_id": "a98f3e46cd370e6c77a26ba8fcce35404eb25b14", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8742, "license_type": "permissive", "max_line_length": 282, "num_lines": 175, "path": "/src/TorchSharp/NN/Recurrent/RNN.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n public sealed class RNN : torch.nn.Module<Tensor, Tensor?, (Tensor, Tensor)>\n {\n internal RNN(IntPtr handle, IntPtr boxedHandle, long hiddenSize, long numLayers, bool batchFirst, bool bidirectional) : base(handle, boxedHandle)\n {\n _hidden_size = hiddenSize;\n _num_layers = numLayers;\n _bidirectional = bidirectional;\n _batch_first = batchFirst;\n }\n\n private long _hidden_size;\n private long _num_layers;\n private bool _bidirectional;\n private bool _batch_first;\n\n /// <summary>\n /// Applies a multi-layer Elman RNN with \\tanhtanh or \\text{ReLU}ReLU non-linearity to an input sequence.\n /// </summary>\n /// <param name=\"input\">Tensor of shape (seq_len, batch, input_size) containing the features of the input sequence.</param>\n /// <param name=\"h0\">Tensor of shape (num_layers * num_directions, batch, hidden_size)containing the initial hidden state for each element in the batch.\n /// Defaults to 0 if not provided. If the RNN is bidirectional, num_directions should be 2, else it should be 1.</param>\n /// <returns></returns>\n public override (Tensor, Tensor) forward(Tensor input, Tensor? h0)\n {\n if (h0 is null) {\n var N = _batch_first ? input.shape[0] : input.shape[1];\n var D = _bidirectional ? 2 : 1;\n\n h0 = torch.zeros(D * _num_layers, N, _hidden_size, dtype: input.dtype, device: input.device);\n }\n\n var res = THSNN_RNN_forward(handle, input.Handle, h0.Handle, out IntPtr hN);\n if (res == IntPtr.Zero || hN == IntPtr.Zero) { torch.CheckForErrors(); }\n return (new Tensor(res), new Tensor(hN));\n }\n\n public new (Tensor, Tensor) call(Tensor input, Tensor? h0 = null) => base.call(input, h0);\n\n /// <summary>\n /// Applies a multi-layer Elman RNN with \\tanhtanh or \\text{ReLU}ReLU non-linearity to an input sequence.\n /// </summary>\n /// <param name=\"input\">PackedSequence containing the features of the input sequence.</param>\n /// <param name=\"h0\">Tensor of shape (num_layers * num_directions, batch, hidden_size)containing the initial hidden state for each element in the batch.\n /// Defaults to 0 if not provided. If the RNN is bidirectional, num_directions should be 2, else it should be 1.</param>\n /// <returns></returns>\n public (torch.nn.utils.rnn.PackedSequence, Tensor) call(torch.nn.utils.rnn.PackedSequence input, Tensor? h0 = null)\n {\n if (h0 is null) {\n var data = input.data;\n var batch_sizes = input.batch_sizes;\n var N = batch_sizes[0].item<long>();\n var D = _bidirectional ? 2 : 1;\n\n h0 = torch.zeros(D * _num_layers, N, _hidden_size, dtype: data.dtype, device: data.device);\n }\n\n var res = THSNN_RNN_forward_with_packed_input(handle, input.Handle, h0.Handle, out IntPtr hN);\n if (res.IsInvalid || hN == IntPtr.Zero) { torch.CheckForErrors(); }\n return (new torch.nn.utils.rnn.PackedSequence(res), new Tensor(hN));\n }\n\n public void flatten_parameters()\n {\n THSNN_RNN_flatten_parameters(handle);\n torch.CheckForErrors();\n }\n\n public Parameter? get_bias_ih(long idx)\n {\n var res = THSNN_RNN_bias_ih(handle, idx);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return ((res == IntPtr.Zero) ? null : new Parameter(res));\n }\n\n public Parameter? get_bias_hh(long idx)\n {\n var res = THSNN_RNN_bias_hh(handle, idx);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return ((res == IntPtr.Zero) ? null : new Parameter(res));\n }\n\n#if false // Disabled until we can figure out how to set the native code parameters.\n\n public void set_bias_ih(Tensor? value, long idx)\n {\n THSNN_RNN_set_bias_ih(handle, (value is null ? IntPtr.Zero : value.Handle), idx);\n torch.CheckForErrors();\n ConditionallyRegisterParameter($\"bias_ih_l{idx}\", value);\n }\n\n public void set_bias_hh(Tensor? value, long idx)\n {\n THSNN_RNN_set_bias_hh(handle, (value is null ? IntPtr.Zero : value.Handle), idx);\n torch.CheckForErrors();\n ConditionallyRegisterParameter($\"bias_hh_l{idx}\", value);\n }\n#endif\n\n public Parameter? get_weight_ih(long idx)\n {\n var res = THSNN_RNN_weight_ih(handle, idx);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n\n public Parameter? get_weight_hh(long idx)\n {\n var res = THSNN_RNN_weight_hh(handle, idx);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n\n#if false // Disabled until we can figure out how to set the native code parameters.\n public void set_weight_ih(Tensor? value, long idx)\n {\n THSNN_RNN_set_weight_ih(handle, (value is null ? IntPtr.Zero : value.Handle), idx);\n torch.CheckForErrors();\n ConditionallyRegisterParameter($\"weight_ih_l{idx}\", value);\n }\n\n public void set_weight_hh(Tensor? value, long idx)\n {\n THSNN_RNN_set_weight_hh(handle, (value is null ? IntPtr.Zero : value.Handle), idx);\n torch.CheckForErrors();\n ConditionallyRegisterParameter($\"weight_hh_l{idx}\", value);\n }\n#endif\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n public enum NonLinearities\n {\n ReLU = 0,\n Tanh = 1\n }\n\n /// <summary>\n /// Creates an Elman RNN module with tanh or ReLU non-linearity.\n /// </summary>\n /// <param name=\"inputSize\">The number of expected features in the input x</param>\n /// <param name=\"hiddenSize\">The number of features in the hidden state h</param>\n /// <param name=\"numLayers\">Number of recurrent layers. Default: 1</param>\n /// <param name=\"nonLinearity\">The non-linearity to use. Can be either 'tanh' or 'relu'. Default: 'tanh'</param>\n /// <param name=\"bias\">If False, then the layer does not use bias weights b_ih and b_hh. Default: True</param>\n /// <param name=\"batchFirst\">if true, then the input and output tensors are provided as (batch, seq, feature). Default: False</param>\n /// <param name=\"dropout\">If non-zero, introduces a Dropout layer on the outputs of each RNN layer except the last layer, with dropout probability equal to dropout. Default: 0</param>\n /// <param name=\"bidirectional\">if true, becomes a bidirectional RNN. Default: False</param>\n /// <param name=\"device\">The desired device of the parameters and buffers in this module</param>\n /// <param name=\"dtype\">The desired floating point or complex dtype of the parameters and buffers in this module</param>\n /// <returns></returns>\n public static RNN RNN(long inputSize, long hiddenSize, long numLayers = 1, NonLinearities nonLinearity = nn.NonLinearities.Tanh, bool bias = true, bool batchFirst = false, double dropout = 0.0, bool bidirectional = false, Device? device = null, ScalarType? dtype = null)\n {\n var res = THSNN_RNN_ctor(inputSize, hiddenSize, numLayers, (long)nonLinearity, bias, batchFirst, dropout, bidirectional, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new RNN(res, boxedHandle, hiddenSize, numLayers, batchFirst, bidirectional).MoveModule<RNN>(device, dtype);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6434804797172546, "alphanum_fraction": 0.6513090133666992, "avg_line_length": 25.06354522705078, "blob_id": "1a6cf08481212f8c5c65005be864abb32d2fda25", "content_id": "9fa77de5c5575bb5e9f3ac108ec1c31cf2ed4839", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7792, "license_type": "permissive", "max_line_length": 130, "num_lines": 299, "path": "/src/Native/LibTorchSharp/Utils.h", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#pragma once\n\n#include <string>\n\n#include \"torch/torch.h\"\n\nextern thread_local char *torch_last_err;\n\ntypedef torch::Tensor *Tensor;\ntypedef torch::Scalar *Scalar;\ntypedef torch::Generator* Generator;\ntypedef c10::Storage* Storage;\ntypedef torch::nn::utils::rnn::PackedSequence* PackedSequence;\n\ntypedef std::shared_ptr<torch::nn::Module> * NNModule;\ntypedef std::shared_ptr<torch::nn::AnyModule> * NNAnyModule;\ntypedef std::shared_ptr<torch::optim::Optimizer> * Optimizer;\ntypedef std::shared_ptr<torch::jit::CompilationUnit> * JITCompilationUnit;\ntypedef std::shared_ptr<torch::jit::Module>* JITModule;\ntypedef std::shared_ptr<torch::jit::Method>* JITMethod;\ntypedef std::shared_ptr<torch::jit::Function> * JITFunction;\ntypedef std::shared_ptr<c10::Type> * JITType;\ntypedef std::shared_ptr<c10::TensorType>* JITTensorType;\n\n//typedef std::shared_ptr<torch::jit::DimensionedTensorType>* JITDimensionedTensorType;\n\n#define THS_API TH_API\n\n#define CATCH(x) \\\n try { \\\n torch_last_err = 0; \\\n x \\\n } catch (const c10::Error e) { \\\n torch_last_err = strdup(e.what()); \\\n } catch (const std::runtime_error e) { \\\n torch_last_err = strdup(e.what()); \\\n }\n\n#define CATCH_RETURN_RES(ty, dflt, stmt) \\\n ty res = dflt; \\\n CATCH( \\\n stmt; \\\n ); \\\n return res;\n\n#define CATCH_RETURN(ty, dflt, expr) CATCH_RETURN_RES(ty, dflt, res = expr)\n#define CATCH_RETURN_NNModule(stmt) CATCH_RETURN_RES(NNModule, nullptr, stmt)\n#define CATCH_RETURN_Tensor(stmt) CATCH_RETURN_RES(Tensor, nullptr, stmt)\n\n// Return undefined tensors as nullptr to C#\ninline Tensor ResultTensor(const at::Tensor & res)\n{\n if (res.defined())\n return new torch::Tensor(res);\n else\n return nullptr;\n}\n\n#define CATCH_TENSOR(expr) \\\n at::Tensor res = at::Tensor(); \\\n CATCH( \\\n res = expr; \\\n ); \\\n return ResultTensor(res);\n\n#define CATCH_TENSORS_2(expr) \\\n at::Tensor fst = at::Tensor(); \\\n at::Tensor snd = at::Tensor(); \\\n CATCH( \\\n std::tie(fst,snd) = expr; \\\n ); \\\n res1 = ResultTensor(fst); \\\n res2 = ResultTensor(snd); \n\n#define CATCH_SCALAR(expr) \\\n at::Scalar res = at::Scalar(); \\\n CATCH( \\\n res = expr; \\\n ); \\\n return ResultTensor(res);\n\n\n// Utility method used to built sharable strings.\nconst char * make_sharable_string(const std::string str);\n\n// Method concerting arrays of tensor pointers into arrays of tensors.\ntemplate<class T>\nstd::vector<T> toTensors(torch::Tensor ** tensorPtrs, const int length)\n{\n std::vector<T> tensors;\n\n if (tensorPtrs != nullptr) {\n for (int i = 0; i < length; i++)\n {\n tensors.push_back(*tensorPtrs[i]);\n }\n }\n return tensors;\n}\n\n// Utilities for NN namespace.\n\ntemplate <typename T>\nTensor get_weight(const NNModule module)\n{\n CATCH_TENSOR((*module)->as<T>()->weight);\n}\n\ntemplate <typename T>\nvoid set_weight(const NNModule module, const Tensor weights)\n{\n CATCH(\n (*module)->as<T>()->weight = *weights;\n );\n}\n\ntemplate <typename T>\nTensor get_bias(const NNModule module)\n{\n CATCH_TENSOR((*module)->as<T>()->bias);\n}\n\ntemplate <typename T>\nvoid set_bias(const NNModule module, const Tensor bias)\n{\n CATCH(\n (*module)->as<T>()->bias = *bias;\n );\n}\n\ntemplate <typename T>\nTensor get_weight_ih(const NNModule module)\n{\n CATCH_TENSOR((*module)->as<T>()->weight_ih);\n}\n\ntemplate <typename T>\nTensor get_weight_hh(const NNModule module)\n{\n CATCH_TENSOR((*module)->as<T>()->weight_hh);\n}\n\ntemplate <typename T>\nvoid set_weight_ih(const NNModule module, const Tensor weights)\n{\n CATCH(\n (*module)->as<T>()->weight_ih = *weights;\n );\n}\n\ntemplate <typename T>\nvoid set_weight_hh(const NNModule module, const Tensor weights)\n{\n CATCH(\n (*module)->as<T>()->weight_hh = *weights;\n );\n}\n\ntemplate <typename T>\nTensor get_bias_ih(const NNModule module)\n{\n CATCH_TENSOR((*module)->as<T>()->bias_ih);\n}\n\ntemplate <typename T>\nTensor get_bias_hh(const NNModule module)\n{\n CATCH_TENSOR((*module)->as<T>()->bias_hh);\n}\n\ntemplate <typename T>\nvoid set_bias_ih(const NNModule module, const Tensor bias)\n{\n CATCH(\n (*module)->as<T>()->bias_ih = *bias;\n );\n}\n\ntemplate <typename T>\nvoid set_bias_hh(const NNModule module, const Tensor bias)\n{\n CATCH(\n (*module)->as<T>()->bias_hh = *bias;\n );\n}\n\n#define WIH_BASE 0\n#define WHH_BASE 1\n#define BIH_BASE 2\n#define BHH_BASE 3\n\ntemplate <typename T>\nTensor get_weight_ih(const NNModule module, const int64_t idx)\n{\n CATCH_TENSOR((*module)->as<T>()->all_weights()[WIH_BASE + idx * 4]);\n}\n\ntemplate <typename T>\nTensor get_weight_hh(const NNModule module, const int64_t idx)\n{\n CATCH_TENSOR((*module)->as<T>()->all_weights()[WHH_BASE + idx * 4]);\n}\n\ntemplate <typename T>\nvoid set_weight_ih(const NNModule module, const Tensor weights, const int64_t idx)\n{\n CATCH(\n (*module)->as<T>()->all_weights()[WIH_BASE + idx * 4] = *weights;\n );\n}\n\ntemplate <typename T>\nvoid set_weight_hh(const NNModule module, const Tensor weights, const int64_t idx)\n{\n CATCH(\n (*module)->as<T>()->all_weights()[WHH_BASE + idx * 4] = *weights;\n );\n}\n\ntemplate <typename T>\nTensor get_bias_ih(const NNModule module, const int64_t idx)\n{\n CATCH_TENSOR((*module)->as<T>()->all_weights()[BIH_BASE + idx * 4]);\n}\n\ntemplate <typename T>\nTensor get_bias_hh(const NNModule module, const int64_t idx)\n{\n CATCH_TENSOR((*module)->as<T>()->all_weights()[BHH_BASE + idx * 4]);\n}\n\ntemplate <typename T>\nvoid set_bias_ih(const NNModule module, const Tensor bias, const int64_t idx)\n{\n CATCH(\n (*module)->as<T>()->all_weights()[BIH_BASE + idx * 4] = *bias;\n );\n}\n\ntemplate <typename T>\nvoid set_bias_hh(const NNModule module, const Tensor bias, const int64_t idx)\n{\n CATCH(\n (*module)->as<T>()->all_weights()[BHH_BASE + idx * 4] = *bias;\n );\n}\n\ntemplate<typename TImpl>\nNNModule create_module(NNAnyModule* outAsAnyModule)\n{\n auto mod = std::make_shared<TImpl>();\n\n // Keep a boxed version of the module in case we add it to a Sequential later (the C++ templating means\n // a Module can only be boxed to AnyModule at the point its static type is known).\n if (outAsAnyModule != nullptr)\n {\n auto wrapped = std::make_shared<torch::nn::AnyModule>(torch::nn::ModuleHolder<TImpl>(*mod));\n *outAsAnyModule = new std::shared_ptr<torch::nn::AnyModule>(wrapped);\n }\n\n return new std::shared_ptr<torch::nn::Module>(mod);\n}\n\ntemplate<typename TImpl, typename TOptions>\nNNModule create_module(const TOptions& opts, NNAnyModule* outAsAnyModule)\n{\n auto mod = std::make_shared<TImpl>(opts);\n\n // Keep a boxed version of the module in case we add it to a Sequential later (the C++ templating means\n // a Module can only be boxed to AnyModule at the point its static type is known).\n if (outAsAnyModule != nullptr)\n {\n auto wrapped = std::make_shared<torch::nn::AnyModule>(torch::nn::ModuleHolder<TImpl>(*mod));\n *outAsAnyModule = new std::shared_ptr<torch::nn::AnyModule>(wrapped);\n }\n\n return new std::shared_ptr<torch::nn::Module>(mod);\n}\n\ninline\ntorch::nn::init::NonlinearityType get_nl_type(const int64_t nl)\n{\n switch (nl)\n {\n default:\n case 0: return torch::kLinear;\n case 1: return torch::kConv1D;\n case 2: return torch::kConv2D;\n case 3: return torch::kConv3D;\n case 4: return torch::kConvTranspose1D;\n case 5: return torch::kConvTranspose2D;\n case 6: return torch::kConvTranspose3D;\n case 7: return torch::kSigmoid;\n case 8: return torch::kTanh;\n case 9: return torch::kReLU;\n case 10: return torch::kLeakyReLU;\n }\n}" }, { "alpha_fraction": 0.5233196020126343, "alphanum_fraction": 0.5345221757888794, "avg_line_length": 38.0625, "blob_id": "0ca611ea1c431fc13899ff0bd97049216c2c92f6", "content_id": "7c8c36e1af89a399d344fe423f7276f8cf3c819f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4374, "license_type": "permissive", "max_line_length": 140, "num_lines": 112, "path": "/src/TorchAudio/Transforms/MelScale.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchaudio,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/audio/blob/bb77cbebb620a46fdc0dc7e6dae2253eef3f37e2/torchaudio/transforms/_transforms.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/audio/blob/main/LICENSE\n//\n\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\nusing static TorchSharp.torchaudio;\nusing F = TorchSharp.torchaudio.functional;\n\nnamespace TorchSharp\n{\n namespace Transforms\n {\n public class MelScale : Module<Tensor, Tensor>\n {\n public readonly long n_mels;\n public readonly long sample_rate;\n public readonly double f_max;\n public readonly double f_min;\n public readonly MelNorm norm;\n public readonly torchaudio.MelScale mel_scale;\n public readonly Tensor fb;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n fb.Dispose();\n }\n base.Dispose(disposing);\n }\n\n internal MelScale(\n string name,\n long n_mels = 128,\n long sample_rate = 16000,\n double f_min = 0.0,\n double? f_max = null,\n long n_stft = 201,\n MelNorm norm = MelNorm.none,\n torchaudio.MelScale mel_scale = torchaudio.MelScale.htk) : base(name)\n {\n this.n_mels = n_mels;\n this.sample_rate = sample_rate;\n this.f_max = f_max ?? (sample_rate / 2);\n this.f_min = f_min;\n this.norm = norm;\n this.mel_scale = mel_scale;\n\n if (f_min > this.f_max) {\n throw new ArgumentOutOfRangeException($\"Require f_min: {f_min} < f_max: {this.f_max}\");\n }\n this.fb = F.melscale_fbanks(n_stft, this.f_min, this.f_max, this.n_mels, this.sample_rate, this.norm, this.mel_scale);\n this.register_buffer(\"fb\", fb);\n }\n\n /// <param name=\"specgram\">A spectrogram STFT of dimension (..., freq, time).</param>\n /// <returns>Mel frequency spectrogram of size (..., ``n_mels``, time).</returns>\n public override Tensor forward(Tensor specgram)\n {\n var mel_specgram = torch.matmul(specgram.transpose(-1, -2), this.fb).transpose(-1, -2);\n\n return mel_specgram;\n }\n }\n }\n\n public partial class torchaudio\n {\n public partial class transforms\n {\n /// <summary>\n /// Turn a normal STFT into a mel frequency STFT with triangular filter banks.\n /// </summary>\n /// <param name=\"n_mels\">Number of mel filterbanks.</param>\n /// <param name=\"sample_rate\">Sample rate of audio signal.</param>\n /// <param name=\"f_min\">Minimum frequency.</param>\n /// <param name=\"f_max\">Maximum frequency.</param>\n /// <param name=\"n_stft\">Number of bins in STFT. See ``n_fft`` in :class:`Spectrogram`.</param>\n /// <param name=\"norm\">If 'slaney', divide the triangular mel weights by the width of the mel band (area normalization).</param>\n /// <param name=\"mel_scale\">Scale to use: ``htk`` or ``slaney``.</param>\n /// <returns></returns>\n public static Transforms.MelScale MelScale(\n long n_mels = 128,\n long sample_rate = 16000,\n double f_min = 0.0,\n double? f_max = null,\n long n_stft = 201,\n MelNorm norm = MelNorm.none,\n torchaudio.MelScale mel_scale = torchaudio.MelScale.htk)\n {\n return new Transforms.MelScale(\n \"MelScale\",\n n_mels,\n sample_rate,\n f_min,\n f_max,\n n_stft,\n norm,\n mel_scale);\n }\n }\n }\n}" }, { "alpha_fraction": 0.5602758526802063, "alphanum_fraction": 0.5664827823638916, "avg_line_length": 50.78571319580078, "blob_id": "88660fcb39b3450174e2fe236fb65c7eff35f3e6", "content_id": "862bf0b0282d9d6e7ea6160c6ccc0bd6e72ac444", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7250, "license_type": "permissive", "max_line_length": 137, "num_lines": 140, "path": "/src/TorchSharp/NN/Pooling/AdaptiveAvgPool3D.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a AdaptiveAvgPool3D module.\n /// </summary>\n public sealed class AdaptiveAvgPool3d : torch.nn.Module<Tensor, Tensor>\n {\n internal AdaptiveAvgPool3d(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_AdaptiveAvgPool3d_forward(handle.DangerousGetHandle(), tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies a 3D adaptive average pooling over an input signal composed of several input planes.\n /// The output is of size D x H x W, for any input size.The number of output features is equal to the number of input planes.\n /// </summary>\n /// <param name=\"outputSize\">The target output size of the image of the form D x H x W.</param>\n /// <returns></returns>\n public static unsafe AdaptiveAvgPool3d AdaptiveAvgPool3d(long[] outputSize)\n {\n fixed (long* pkernelSize = outputSize) {\n var handle = THSNN_AdaptiveAvgPool3d_ctor((IntPtr)pkernelSize, outputSize.Length, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new AdaptiveAvgPool3d(handle, boxedHandle);\n }\n }\n\n /// <summary>\n /// Applies a 3D adaptive average pooling over an input signal composed of several input planes.\n /// The output is of size D x H x W, for any input size.The number of output features is equal to the number of input planes.\n /// </summary>\n /// <param name=\"outputSize\">The target output size (D,H,W) of the image of the form D x H x W.</param>\n /// <returns></returns>\n public static unsafe AdaptiveAvgPool3d AdaptiveAvgPool3d((long, long, long) outputSize)\n {\n long* pkernelSize = stackalloc long[3] { outputSize.Item1, outputSize.Item2, outputSize.Item3 };\n\n var handle = THSNN_AdaptiveAvgPool3d_ctor((IntPtr)pkernelSize, 3, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new AdaptiveAvgPool3d(handle, boxedHandle);\n }\n\n /// <summary>\n /// Applies a 3D adaptive average pooling over an input signal composed of several input planes.\n /// The output is of size D x H x W, for any input size.The number of output features is equal to the number of input planes.\n /// </summary>\n /// <param name=\"outputSize\">The target output size (D,H,W) of the image of the form H x W.</param>\n /// <returns></returns>\n public static unsafe AdaptiveAvgPool3d AdaptiveAvgPool3d(long outputSize)\n {\n long* pkernelSize = stackalloc long[3] { outputSize, outputSize, outputSize };\n var handle = THSNN_AdaptiveAvgPool3d_ctor((IntPtr)pkernelSize, 3, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new AdaptiveAvgPool3d(handle, boxedHandle);\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Applies a 3D adaptive average pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"output_size\"></param>\n /// <returns></returns>\n public static unsafe Tensor adaptive_avg_pool3d(Tensor input, long[] output_size)\n {\n fixed (long* poutputSize = output_size) {\n var res =\n THSTensor_adaptive_avg_pool3d(input.Handle, (IntPtr)poutputSize, output_size.Length);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n /// <summary>\n /// Applies a 2D adaptive average pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"output_size\"></param>\n /// <returns></returns>\n public static unsafe Tensor adaptive_avg_pool3d(Tensor input, (long, long, long) output_size)\n {\n long* poutputSize = stackalloc long[3] { output_size.Item1, output_size.Item2, output_size.Item3 };\n var res = THSTensor_adaptive_avg_pool3d(input.Handle, (IntPtr)poutputSize, 3);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Applies a 2D adaptive average pooling over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"output_size\"></param>\n /// <returns></returns>\n public static unsafe Tensor adaptive_avg_pool3d(Tensor input, long output_size)\n {\n var os = new long[] { output_size, output_size, output_size };\n long* poutputSize = stackalloc long[3] { output_size, output_size, output_size };\n var res = THSTensor_adaptive_avg_pool3d(input.Handle, (IntPtr)poutputSize, 3);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public static Tensor adaptive_avg_pool3d_backward(Tensor gradInput, Tensor gradOutput, Tensor originalInput)\n {\n var res = THSTensor_adaptive_avg_pool3d_backward_out(gradInput.Handle, gradOutput.Handle, originalInput.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6364205479621887, "alphanum_fraction": 0.6364205479621887, "avg_line_length": 36.1860466003418, "blob_id": "6dc1bbc272e6c410ef62828c298181f82843ac30", "content_id": "f1b162cbbfe5f8a00d860be63cce34fa2e184e6b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1598, "license_type": "permissive", "max_line_length": 111, "num_lines": 43, "path": "/test/TorchSharpTest/FactIgnoreOnPlattformAttribute.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "#nullable enable\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing Xunit;\n\nnamespace TorchSharp\n{\n /// <summary>\n /// To ignore an xUnit <see cref=\"FactAttribute\">Fact</see> on a given platform or architecture.\n /// </summary>\n public sealed class FactIgnoreOnPlatformAttribute : FactAttribute\n {\n public FactIgnoreOnPlatformAttribute(string skip, params string[] platforms)\n {\n if (platforms.Any(p => RuntimeInformation.IsOSPlatform(OSPlatform.Create(p.ToUpperInvariant())))) {\n Skip = skip;\n }\n }\n\n public FactIgnoreOnPlatformAttribute(params string[] platforms)\n {\n if (platforms.Any(p => RuntimeInformation.IsOSPlatform(OSPlatform.Create(p.ToUpperInvariant())))) {\n Skip = $\"based on platform {RuntimeInformation.OSDescription}\";\n }\n }\n\n public FactIgnoreOnPlatformAttribute(string skip, string platform, Architecture architecture)\n {\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Create(platform.ToUpperInvariant()))\n && RuntimeInformation.ProcessArchitecture == architecture) {\n Skip = skip;\n }\n }\n\n public FactIgnoreOnPlatformAttribute(string platform, Architecture architecture)\n {\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Create(platform.ToUpperInvariant()))\n && RuntimeInformation.ProcessArchitecture == architecture) {\n Skip = $\"based on platform {platform} {architecture}\";\n }\n }\n }\n}" }, { "alpha_fraction": 0.5757042169570923, "alphanum_fraction": 0.5757042169570923, "avg_line_length": 27.450000762939453, "blob_id": "63ce94dcd20f5f76c20d49c40909fa1c6a48528f", "content_id": "e65a649f3cc4ce64f91ccc49fe64897386af0593", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 568, "license_type": "permissive", "max_line_length": 130, "num_lines": 20, "path": "/src/TorchSharp/JIT/Type/DynamicType .cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n\n public static partial class jit\n {\n public sealed class DynamicType : Type\n {\n internal DynamicType(IntPtr handle) : base(handle, Type.TypeKind.AnyType)\n {\n this.handle = new HType(handle, true, Type.TypeKind.AnyType);\n }\n }\n }\n }\n}" }, { "alpha_fraction": 0.7560219168663025, "alphanum_fraction": 0.7762938141822815, "avg_line_length": 44.086021423339844, "blob_id": "345b2ce610fd0ee7a4ac2f09d04d910d97237f91", "content_id": "9ab80e8280607b20ecc50566181f980edf4ffcc0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4193, "license_type": "permissive", "max_line_length": 130, "num_lines": 93, "path": "/src/Native/LibTorchSharp/THSTorch.h", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#pragma once\n\n#include \"../Stdafx.h\"\n\n#include \"Utils.h\"\n\n// API.\n\n// Sets manually the seed.\nEXPORT_API(void) THSTorch_manual_seed(const int64_t seed);\nEXPORT_API(void) THSCuda_manual_seed(const int64_t seed);\nEXPORT_API(void) THSCuda_manual_seed_all(const int64_t seed);\n\nEXPORT_API(Generator) THSGenerator_manual_seed(const int64_t seed);\nEXPORT_API(void) THSGenerator_gen_manual_seed(const Generator gen, const int64_t seed);\n\nEXPORT_API(Tensor) THSGenerator_get_rng_state(const Generator gen);\nEXPORT_API(void) THSGenerator_set_rng_state(const Generator gen, const Tensor tensor);\n\nEXPORT_API(Generator) THSGenerator_default_generator();\nEXPORT_API(Generator) THSGenerator_new(uint64_t seed, int64_t device, int64_t index);\nEXPORT_API(int64_t) THSGenerator_initial_seed(const Generator gen);\nEXPORT_API(void) THSGenerator_dispose(const Generator generator);\n\nEXPORT_API(int) THSTorchCuda_is_available();\nEXPORT_API(int) THSTorchCuda_cudnn_is_available();\nEXPORT_API(int) THSTorchCuda_device_count();\nEXPORT_API(void) THSTorchCuda_synchronize(const int64_t device);\n\nEXPORT_API(bool) THSBackend_cublas_get_allow_tf32();\nEXPORT_API(void) THSBackend_cublas_set_allow_tf32(const bool flag);\nEXPORT_API(bool) THSBackend_cudnn_get_allow_tf32();\nEXPORT_API(void) THSBackend_cudnn_set_allow_tf32(const bool flag);\n\nEXPORT_API(bool) THSBackend_cuda_get_allow_fp16_reduced_precision_reduction();\nEXPORT_API(void) THSBackend_cuda_set_allow_fp16_reduced_precision_reduction(const bool flag);\n\nEXPORT_API(bool) THSBackend_cuda_get_enable_flash_sdp();\nEXPORT_API(void) THSBackend_cuda_set_enable_flash_sdp(const bool flag);\nEXPORT_API(bool) THSBackend_cuda_get_enable_math_sdp();\nEXPORT_API(void) THSBackend_cuda_set_enable_math_sdp(const bool flag);\n\nEXPORT_API(int) THSTorch_get_num_threads();\nEXPORT_API(void) THSTorch_set_num_threads(const int threads);\n\nEXPORT_API(int) THSTorch_get_num_interop_threads();\nEXPORT_API(void) THSTorch_set_num_interop_threads(const int threads);\n\n// Returns the latest error. This is thread-local.\n\nEXPORT_API(const char *) THSTorch_get_and_reset_last_err();\n\nEXPORT_API(int) THSTorch_can_cast(const int type1, const int type2);\nEXPORT_API(int) THSTorch_promote_types(const int type1, const int type2);\n\nEXPORT_API(Scalar) THSTorch_int8_to_scalar(int8_t value);\nEXPORT_API(Scalar) THSTorch_uint8_to_scalar(uint8_t value);\nEXPORT_API(Scalar) THSTorch_int16_to_scalar(short value);\nEXPORT_API(Scalar) THSTorch_int32_to_scalar(int value);\nEXPORT_API(Scalar) THSTorch_int64_to_scalar(long value);\nEXPORT_API(Scalar) THSTorch_float32_to_scalar(float value);\nEXPORT_API(Scalar) THSTorch_float64_to_scalar(double value);\nEXPORT_API(Scalar) THSTorch_bool_to_scalar(bool value);\nEXPORT_API(Scalar) THSTorch_float16_to_scalar(float value);\nEXPORT_API(Scalar) THSTorch_bfloat16_to_scalar(float value);\n\nEXPORT_API(Scalar) THSTorch_complex32_to_scalar(float real, float imaginary);\nEXPORT_API(Scalar) THSTorch_complex64_to_scalar(double real, double imaginary);\n\nEXPORT_API(int8_t) THSTorch_scalar_to_int8(Scalar value);\nEXPORT_API(uint8_t) THSTorch_scalar_to_uint8(Scalar value);\nEXPORT_API(int16_t) THSTorch_scalar_to_int16(Scalar value);\nEXPORT_API(int32_t) THSTorch_scalar_to_int32(Scalar value);\nEXPORT_API(int64_t) THSTorch_scalar_to_int64(Scalar value);\nEXPORT_API(float) THSTorch_scalar_to_float32(Scalar value);\nEXPORT_API(double) THSTorch_scalar_to_float64(Scalar value);\nEXPORT_API(bool) THSTorch_scalar_to_bool(Scalar value);\n\nEXPORT_API(void) THSTorch_scalar_to_float16(Scalar value, unsigned short* res);\n\nEXPORT_API(void) THSTorch_scalar_to_complex32(Scalar value, float* (*allocator)(size_t length));\nEXPORT_API(void) THSTorch_scalar_to_complex64(Scalar value, double* (*allocator)(size_t length));\n\nEXPORT_API(int8_t) THSTorch_scalar_type(Scalar value);\n\n// Dispose the scalar.\nEXPORT_API(void) THSTorch_dispose_scalar(Scalar scalar);\n\n// Math functions not available in .NET standard libs\n\nEXPORT_API(double) THSSpecial_erf_scalar(const double x);\nEXPORT_API(double) THSSpecial_erfc_scalar(const double x);\n" }, { "alpha_fraction": 0.5712489485740662, "alphanum_fraction": 0.5716680884361267, "avg_line_length": 41.625, "blob_id": "444c170c743025b7e2dfcf77d8b912edcbb8dd59", "content_id": "ff326db1228e1d32ffd3cf28bef4cb27291ad725", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2386, "license_type": "permissive", "max_line_length": 130, "num_lines": 56, "path": "/src/TorchVision/ResizedCrop.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class ResizedCrop : ITransform\n {\n internal ResizedCrop(int top, int left, int height, int width, int newHeight, int newWidth)\n {\n cropper = transforms.Crop(top, left, height, width);\n resizer = transforms.Resize(newHeight, newWidth);\n }\n\n public Tensor call(Tensor input)\n {\n using var cr = cropper.call(input);\n return resizer.call(cr);\n }\n\n private ITransform cropper;\n private ITransform resizer;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Crop the given image and resize it to desired size.\n /// </summary>\n /// <param name=\"top\">Vertical component of the top left corner of the crop box.</param>\n /// <param name=\"left\">Horizontal component of the top left corner of the crop box.</param>\n /// <param name=\"height\">Height of the crop box.</param>\n /// <param name=\"width\">Width of the crop box.</param>\n /// <param name=\"newHeight\">New height.</param>\n /// <param name=\"newWidth\">New width.</param>\n static public ITransform ResizedCrop(int top, int left, int height, int width, int newHeight, int newWidth)\n {\n return new ResizedCrop(top, left, height, width, newHeight, newWidth);\n }\n\n /// <summary>\n /// Crop the given image and resize it to desired (square) size.\n /// </summary>\n /// <param name=\"top\">Vertical component of the top left corner of the crop box.</param>\n /// <param name=\"left\">Horizontal component of the top left corner of the crop box.</param>\n /// <param name=\"size\">Height and width of the crop box.</param>\n /// <param name=\"newSize\">New height and width.</param>\n static public ITransform ResizedCrop(int top, int left, int size, int newSize)\n {\n return new ResizedCrop(top, left, size, size, newSize, -1);\n }\n }\n }\n}" }, { "alpha_fraction": 0.5909352898597717, "alphanum_fraction": 0.5972728729248047, "avg_line_length": 48.590476989746094, "blob_id": "0dd0d5fc172516968490d8dca5a9c578fff2f205", "content_id": "1249b5ba570d01073a7a680c1c08e871e820b408", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5207, "license_type": "permissive", "max_line_length": 245, "num_lines": 105, "path": "/src/TorchSharp/Optimizers/LBFGS.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n public static partial class torch\n {\n public static partial class optim\n {\n /// <summary>\n /// Implements the L-BFGS algorithm, heavily inspired by `minFunc`\n ///\n /// https://www.cs.ubc.ca/~schmidtm/Software/minFunc.html\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize</param>\n /// <param name=\"lr\">Learning rate (default: 1e-2)</param>\n /// <param name=\"max_iter\">Maximal number of iterations per optimization step</param>\n /// <param name=\"max_eval\">Maximal number of function evaluations per optimization step</param>\n /// <param name=\"tolerange_grad\">Termination tolerance on first order optimality</param>\n /// <param name=\"tolerance_change\">Termination tolerance on function value/parameter changes</param>\n /// <param name=\"history_size\">Update history size</param>\n public static LBFGS LBFGS(IEnumerable<(string name, Parameter parameter)> parameters, double lr = 0.01, long max_iter = 20, long? max_eval = null, double tolerange_grad = 1e-5, double tolerance_change = 1e-9, long history_size = 100)\n {\n return LBFGS(parameters.Select(np => np.parameter), lr, max_iter, max_eval.Value, tolerange_grad, tolerance_change, history_size);\n }\n\n /// <summary>\n /// Implements the L-BFGS algorithm, heavily inspired by `minFunc`\n ///\n /// https://www.cs.ubc.ca/~schmidtm/Software/minFunc.html\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize</param>\n /// <param name=\"lr\">Learning rate (default: 1e-2)</param>\n /// <param name=\"max_iter\">Maximal number of iterations per optimization step</param>\n /// <param name=\"max_eval\">Maximal number of function evaluations per optimization step</param>\n /// <param name=\"tolerange_grad\">Termination tolerance on first order optimality</param>\n /// <param name=\"tolerance_change\">Termination tolerance on function value/parameter changes</param>\n /// <param name=\"history_size\">Update history size</param>\n public static LBFGS LBFGS(IEnumerable<Parameter> parameters, double lr = 0.01, long max_iter = 20, long? max_eval = null, double tolerange_grad = 1e-5, double tolerance_change = 1e-9, long history_size = 100)\n {\n if (!max_eval.HasValue) max_eval = 5 * max_iter / 4;\n\n using var parray = new PinnedArray<IntPtr>();\n IntPtr paramsRef = parray.CreateArray(parameters.Select(p => p.Handle).ToArray());\n\n var res = THSNN_LBFGS_ctor(paramsRef, parray.Array.Length, lr, max_iter, max_eval.Value, tolerange_grad, tolerance_change, history_size);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new LBFGS(res, lr);\n }\n }\n }\n\n namespace Modules\n {\n using static torch.optim;\n\n // LBGFS does not allow for param groups, so there's no need to use anything but the native implementation.\n public class LBFGS : Optimizer, ILearningRateController\n {\n /// <summary>\n /// Implements L-BFGS algorithm, heavily inspired by `minFunc`\n ///\n /// </summary>\n /// <param name=\"handle\"></param>\n /// <param name=\"lr\"></param>\n public LBFGS(IntPtr handle, double lr) : base(handle)\n {\n _rate = lr;\n InitialLearningRate = lr;\n _paramGroups = new ParamGroup[] { new ParamGroup { Parameters = this.parameters(), Options = new() { LearningRate = lr, InitialLearningRate = lr } } };\n }\n\n public double LearningRate {\n get { return _rate; }\n set { THSNN_LBFGS_set_lr(handle, value); torch.CheckForErrors(); _rate = value; }\n }\n\n public double InitialLearningRate { get; set; }\n\n public override IEnumerable<ILearningRateController> ParamGroups { get => _paramGroups; }\n\n\n /// <summary>\n /// Performs a single optimization step (parameter update).\n /// </summary>\n /// <param name=\"closure\">A closure that reevaluates the model and returns the loss. Optional for most optimizers.</param>\n /// <returns></returns>\n public override Tensor step(Func<Tensor> closure)\n {\n if (closure == null)\n throw new ArgumentNullException(\"'closure' must be non-null when using the LBFGS optimizer. See: https://pytorch.org/docs/1.9.0/optim.html\");\n return base.step(closure);\n }\n\n public double _rate;\n private ParamGroup[] _paramGroups;\n }\n }\n}\n" }, { "alpha_fraction": 0.5266386866569519, "alphanum_fraction": 0.5404423475265503, "avg_line_length": 40.85135269165039, "blob_id": "6fa6144d3f8ee081bcd47c76f9dba662e5bd9dc3", "content_id": "e91971e5aa397067ea2b5f709543f7e2081e2f08", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 12388, "license_type": "permissive", "max_line_length": 255, "num_lines": 296, "path": "/src/Examples/SpeechCommands.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing static TorchSharp.torch;\n\nusing static TorchSharp.torch.nn;\nusing static TorchSharp.torch.nn.functional;\nusing static TorchSharp.torch.utils.data;\nusing static TorchSharp.torchaudio.datasets;\n\nnamespace TorchSharp.Examples\n{\n /// <summary>\n /// SpeechCommands model with convolusions.\n /// </summary>\n /// <remarks>\n /// Translated from Python implementation\n /// https://pytorch.org/tutorials/intermediate/speech_command_classification_with_torchaudio_tutorial.html\n /// </remarks>\n public class SpeechCommands\n {\n private static readonly string[] Labels = new string[] {\n \"bed\", \"bird\", \"backward\", \"cat\", \"dog\", \"down\", \"eight\",\n \"five\", \"follow\", \"forward\", \"four\", \"go\", \"happy\", \"house\",\n \"learn\", \"left\", \"marvin\", \"nine\", \"no\", \"off\", \"on\", \"one\",\n \"right\", \"seven\", \"six\", \"sheila\", \"stop\", \"three\", \"tree\",\n \"two\", \"up\", \"visual\", \"wow\", \"yes\", \"zero\"\n };\n\n private static int _epochs = 1;\n private static int _trainBatchSize = 64;\n private static int _testBatchSize = 128;\n private static int _sample_rate = 16000;\n private static int _new_sample_rate = 8000;\n\n private readonly static int _logInterval = 200;\n\n private static IDictionary<string, int> _labelToIndex;\n\n internal static void Main(string[] args)\n {\n var dataset = args.Length > 0 ? args[0] : \"speechcommands\";\n var datasetPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n\n torchaudio.backend.utils.set_audio_backend(new WaveAudioBackend());\n torch.random.manual_seed(1);\n\n var cwd = Environment.CurrentDirectory;\n Console.WriteLine(datasetPath);\n\n var device = torch.device(torch.cuda.is_available() ? \"cuda\" : \"cpu\");\n\n Console.WriteLine($\"Running SpeechCommands on {device.type.ToString()}\");\n Console.WriteLine($\"Dataset: {dataset}\");\n\n if (device.type == DeviceType.CUDA) {\n _trainBatchSize *= 4;\n _testBatchSize *= 4;\n }\n\n var model = new M5(\"model\");\n model.to(device);\n\n var transform = torchaudio.transforms.Resample(_sample_rate, _new_sample_rate, device: device);\n\n _labelToIndex = Labels.Select((label, index) => (label, index)).ToDictionary(t => t.label, t => t.index);\n using (var train_data = SPEECHCOMMANDS(datasetPath, subset: \"training\", download: true))\n using (var test_data = SPEECHCOMMANDS(datasetPath, subset: \"testing\", download: true)) {\n TrainingLoop(\"speechcommands\", device, model, transform, train_data, test_data);\n }\n }\n\n private static BatchItem Collate(IEnumerable<SpeechCommandsDatasetItem> items, torch.Device device)\n {\n var audio_sequences = items.Select(item => item.waveform.t());\n var padded_audio = torch.nn.utils.rnn.pad_sequence(audio_sequences, batch_first: true, padding_value: 0.0);\n padded_audio = padded_audio.permute(0, 2, 1);\n var labels = items.Select(item => _labelToIndex[item.label]).ToArray();\n return new BatchItem {\n audio = padded_audio.to(device),\n label = torch.tensor(labels, dtype: torch.int64, device: device)\n };\n }\n\n internal static void TrainingLoop(string dataset, Device device, M5 model, nn.IModule<Tensor, Tensor> transform, Dataset<SpeechCommandsDatasetItem> train_data, Dataset<SpeechCommandsDatasetItem> test_data)\n {\n using (var train_loader = new DataLoader<SpeechCommandsDatasetItem, BatchItem>(\n train_data, _trainBatchSize, Collate, shuffle: true, device: device))\n using (var test_loader = new DataLoader<SpeechCommandsDatasetItem, BatchItem>(\n test_data, _testBatchSize, Collate, shuffle: false, device: device)) {\n if (device.type == DeviceType.CUDA) {\n _epochs *= 4;\n }\n\n var optimizer = optim.Adam(model.parameters(), lr: 0.01, weight_decay: 0.0001);\n var scheduler = optim.lr_scheduler.StepLR(optimizer, step_size: 20, gamma: 0.1);\n\n Stopwatch sw = new Stopwatch();\n sw.Start();\n\n for (var epoch = 1; epoch <= _epochs; epoch++) {\n Train(model, transform, optimizer, torch.nn.NLLLoss(reduction: torch.nn.Reduction.Mean), train_loader, epoch, train_data.Count);\n Test(model, transform, torch.nn.NLLLoss(reduction: torch.nn.Reduction.Sum), test_loader, test_data.Count);\n\n Console.WriteLine($\"End-of-epoch memory use: {GC.GetTotalMemory(false)}\");\n scheduler.step();\n }\n\n sw.Stop();\n Console.WriteLine($\"Elapsed time: {sw.Elapsed.TotalSeconds:F1} s.\");\n\n Console.WriteLine(\"Saving model to '{0}'\", dataset + \".model.bin\");\n model.save(dataset + \".model.bin\");\n }\n }\n\n private static void Train(\n M5 model,\n nn.IModule<Tensor, Tensor> transform,\n torch.optim.Optimizer optimizer,\n Loss<Tensor,Tensor,Tensor> criteria,\n DataLoader<SpeechCommandsDatasetItem, BatchItem> dataLoader,\n int epoch,\n long size)\n {\n int batchId = 1;\n long total = 0;\n\n Console.WriteLine($\"Epoch: {epoch}...\");\n\n using (var d = torch.NewDisposeScope()) {\n\n model.train();\n foreach (var batch in dataLoader) {\n var audio = transform.call(batch.audio);\n var target = batch.label;\n var output = model.call(batch.audio).squeeze();\n var loss = criteria.call(output, target);\n optimizer.zero_grad();\n loss.backward();\n optimizer.step();\n total += target.shape[0];\n\n if (batchId % _logInterval == 0 || total == size) {\n Console.WriteLine($\"\\rTrain: epoch {epoch} [{total} / {size}] Loss: {loss.ToSingle():F4}\");\n }\n\n batchId++;\n\n d.DisposeEverything();\n }\n }\n }\n\n private static void Test(\n M5 model,\n nn.IModule<Tensor, Tensor> transform,\n Loss<Tensor, Tensor, Tensor> criteria,\n DataLoader<SpeechCommandsDatasetItem, BatchItem> dataLoader,\n long size)\n {\n model.eval();\n\n double testLoss = 0;\n int correct = 0;\n\n using (var d = torch.NewDisposeScope()) {\n\n foreach (var batch in dataLoader) {\n var audio = transform.call(batch.audio);\n var target = batch.label;\n var output = model.call(batch.audio).squeeze();\n var loss = criteria.call(output, target);\n testLoss += loss.ToSingle();\n\n var pred = output.argmax(1);\n correct += pred.eq(batch.label).sum().ToInt32();\n\n d.DisposeEverything();\n }\n }\n\n Console.WriteLine($\"Size: {size}, Total: {size}\");\n\n Console.WriteLine($\"\\rTest set: Average loss {(testLoss / size):F4} | Accuracy {((double)correct / size):P2}\");\n }\n\n private class WaveAudioBackend : torchaudio.backend.AudioBackend\n {\n public override (torch.Tensor, int) load(string filepath, long frame_offset = 0, long num_frames = -1, bool normalize = true, bool channels_first = true, torchaudio.AudioFormat? format = null)\n {\n byte[] data = File.ReadAllBytes(filepath);\n // In many cases, the first 44 bytes are for RIFF header.\n short[] waveform = MemoryMarshal.Cast<byte, short>(data.AsSpan(11 * 4)).ToArray();\n return (torch.tensor(waveform).unsqueeze(0).to(torch.float32) / short.MaxValue, 16000);\n }\n\n public override void save(string filepath, torch.Tensor src, int sample_rate, bool channels_first = true, float? compression = null, torchaudio.AudioFormat? format = null, torchaudio.AudioEncoding? encoding = null, int? bits_per_sample = null)\n {\n throw new NotImplementedException();\n }\n\n public override torchaudio.AudioMetaData info(string filepath, torchaudio.AudioFormat? format = null)\n {\n throw new NotImplementedException();\n }\n }\n\n private class BatchItem\n {\n public torch.Tensor audio;\n public torch.Tensor label;\n }\n\n internal class M5 : Module<Tensor, Tensor>\n {\n private readonly Module<Tensor, Tensor> conv1;\n private readonly Module<Tensor, Tensor> bn1;\n private readonly Module<Tensor, Tensor> pool1;\n private readonly Module<Tensor, Tensor> conv2;\n private readonly Module<Tensor, Tensor> bn2;\n private readonly Module<Tensor, Tensor> pool2;\n private readonly Module<Tensor, Tensor> conv3;\n private readonly Module<Tensor, Tensor> bn3;\n private readonly Module<Tensor, Tensor> pool3;\n private readonly Module<Tensor, Tensor> conv4;\n private readonly Module<Tensor, Tensor> bn4;\n private readonly Module<Tensor, Tensor> pool4;\n private readonly Module<Tensor, Tensor> fc1;\n\n public M5(string name, int n_input = 1, int n_output = 35, int stride = 16, int n_channel = 32) : base(name)\n {\n conv1 = nn.Conv1d(n_input, n_channel, kernelSize: 80, stride: stride);\n bn1 = nn.BatchNorm1d(n_channel);\n pool1 = nn.MaxPool1d(4);\n conv2 = nn.Conv1d(n_channel, n_channel, kernelSize: 3);\n bn2 = nn.BatchNorm1d(n_channel);\n pool2 = nn.MaxPool1d(4);\n conv3 = nn.Conv1d(n_channel, 2 * n_channel, kernelSize: 3);\n bn3 = nn.BatchNorm1d(2 * n_channel);\n pool3 = nn.MaxPool1d(4);\n conv4 = nn.Conv1d(2 * n_channel, 2 * n_channel, kernelSize: 3);\n bn4 = nn.BatchNorm1d(2 * n_channel);\n pool4 = nn.MaxPool1d(4);\n fc1 = nn.Linear(2 * n_channel, n_output);\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor input)\n {\n var x = input;\n x = conv1.call(x);\n x = relu(bn1.call(x));\n x = pool1.call(x);\n x = conv2.call(x);\n x = relu(bn2.call(x));\n x = pool2.call(x);\n x = conv3.call(x);\n x = relu(bn3.call(x));\n x = pool3.call(x);\n x = conv4.call(x);\n x = relu(bn4.call(x));\n x = pool4.call(x);\n x = avg_pool1d(x, x.shape[x.dim() - 1]);\n x = x.permute(0, 2, 1);\n x = fc1.call(x);\n return log_softmax(x, dim: 2);\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n pool1.Dispose();\n pool2.Dispose();\n pool3.Dispose();\n pool4.Dispose();\n conv1.Dispose();\n conv2.Dispose();\n conv3.Dispose();\n conv4.Dispose();\n bn1.Dispose();\n bn2.Dispose();\n bn3.Dispose();\n bn4.Dispose();\n fc1.Dispose();\n ClearModules();\n }\n base.Dispose(disposing);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.632435142993927, "alphanum_fraction": 0.6376579999923706, "avg_line_length": 59.60685348510742, "blob_id": "8d3af93b72a7cab20184e4baeacf39d5606e6015", "content_id": "ff6f4d6b17f64f9f4a56794aee36871b75d24fd1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 30084, "license_type": "permissive", "max_line_length": 232, "num_lines": 496, "path": "/src/TorchSharp/Tensor/torch.BlasAndLapackOperations.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\n\nusing System;\nusing System.Collections.Generic;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n // https://pytorch.org/docs/stable/torch#blas-and-lapack-operations\n public static partial class torch\n {\n public enum LobpcgMethod\n {\n basic,\n ortho\n }\n\n // https://pytorch.org/docs/stable/generated/torch.addbmm\n /// <summary>\n /// Performs a batch matrix-matrix product of matrices stored in batch1 and batch2, with a reduced\n /// add step (all matrix multiplications get accumulated along the first dimension).\n /// input is added to the final result.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"batch1\">The first batch of matrices to be multiplied</param>\n /// <param name=\"batch2\">The second batch of matrices to be multiplied</param>\n /// <param name=\"beta\">Nultiplier for input (β)</param>\n /// <param name=\"alpha\">Multiplier for batch1 @ batch2 (α)</param>\n public static Tensor addbmm(Tensor input, Tensor batch1, Tensor batch2, float beta = 1, float alpha = 1)\n => input.addbmm(batch1, batch2, beta, alpha);\n\n /// <summary>\n /// Performs a batch matrix-matrix product of matrices stored in batch1 and batch2, with a reduced\n /// add step (all matrix multiplications get accumulated along the first dimension).\n /// input is added to the final result.\n /// In-place version of addbmm.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"batch1\">The first batch of matrices to be multiplied</param>\n /// <param name=\"batch2\">The second batch of matrices to be multiplied</param>\n /// <param name=\"beta\">Nultiplier for input (β)</param>\n /// <param name=\"alpha\">Multiplier for batch1 @ batch2 (α)</param>\n public static Tensor addbmm_(Tensor input, Tensor batch1, Tensor batch2, float beta = 1, float alpha = 1)\n => input.addbmm_(batch1, batch2, beta, alpha);\n\n // https://pytorch.org/docs/stable/generated/torch.addmm\n /// <summary>\n /// Performs a matrix multiplication of the matrices mat1 and mat2. The matrix input is added to the final result.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"mat1\">First matrix</param>\n /// <param name=\"mat2\">Second matrix</param>\n /// <param name=\"beta\">Input scale factor</param>\n /// <param name=\"alpha\">Matrix multiplication scale factor</param>\n public static Tensor addmm(Tensor input, Tensor mat1, Tensor mat2, float beta, float alpha) => input.addmm(mat1, mat2, beta, alpha);\n\n // https://pytorch.org/docs/stable/generated/torch.addmm\n /// <summary>\n /// Performs a matrix multiplication of the matrices mat1 and mat2. The matrix input is added to the final result.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"mat1\">First matrix</param>\n /// <param name=\"mat2\">Second matrix</param>\n /// <param name=\"beta\">Input scale factor</param>\n /// <param name=\"alpha\">Matrix multiplication scale factor</param>\n public static Tensor addmm_(Tensor input, Tensor mat1, Tensor mat2, float beta, float alpha) => input.addmm_(mat1, mat2, beta, alpha);\n\n // https://pytorch.org/docs/stable/generated/torch.addmv\n\n /// <summary>\n /// Performs a matrix multiplication of the matrices mat1 and mat2. The matrix input is added to the final result.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"mat1\">First matrix</param>\n /// <param name=\"mat2\">Second matrix</param>\n /// <param name=\"beta\">Input scale factor</param>\n /// <param name=\"alpha\">Matrix multiplication scale factor</param>\n public static Tensor addmv(Tensor input, Tensor mat1, Tensor mat2, float beta, float alpha) => input.addmv(mat1, mat2, beta, alpha);\n\n /// <summary>\n /// Performs a matrix multiplication of the matrices mat1 and mat2. The matrix input is added to the final result.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"mat1\">First matrix</param>\n /// <param name=\"mat2\">Second matrix</param>\n /// <param name=\"beta\">Input scale factor</param>\n /// <param name=\"alpha\">Matrix multiplication scale factor</param>\n public static Tensor addmv_(Tensor input, Tensor mat1, Tensor mat2, float beta, float alpha) => input.addmv_(mat1, mat2, beta, alpha);\n\n // https://pytorch.org/docs/stable/generated/torch.addr\n /// <summary>\n /// Performs the outer-product of vectors vec1 and vec2 and adds it to the input tensor.\n /// </summary>\n /// <returns></returns>\n public static Tensor addr(Tensor input, Tensor vec1, Tensor vec2, float beta = 1.0f, float alpha = 1.0f) => input.addr(vec1, vec2, beta, alpha);\n\n // https://pytorch.org/docs/stable/generated/torch.addr\n /// <summary>\n /// Performs the outer-product of vectors vec1 and vec2 and adds it to the input tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"vec1\">The first vector of the outer product</param>\n /// <param name=\"vec2\">The second vector of the outer product</param>\n /// <param name=\"beta\">Input scale factor</param>\n /// <param name=\"alpha\">Outer-product scale factor</param>\n public static Tensor addr_(Tensor input, Tensor vec1, Tensor vec2, float beta = 1.0f, float alpha = 1.0f) => input.addr_(vec1, vec2, beta, alpha);\n\n // https://pytorch.org/docs/stable/generated/torch.baddbmm\n /// <summary>\n /// Performs a batch matrix-matrix product of matrices in batch1 and batch2. input is added to the final result.\n /// batch1 and batch2 must be 3-D tensors each containing the same number of matrices.\n /// </summary>\n /// <param name=\"input\">The tensor to be added</param>\n /// <param name=\"batch1\">The first batch of matrices to be multiplied</param>\n /// <param name=\"batch2\">The second batch of matrices to be multiplied</param>\n /// <param name=\"beta\">A multiplier for input</param>\n /// <param name=\"alpha\">A multiplier for batch1 @ batch2</param>\n public static Tensor baddbmm(Tensor input, Tensor batch1, Tensor batch2, float beta = 1, float alpha = 1) => input.baddbmm(batch1, batch2, beta, alpha);\n\n // https://pytorch.org/docs/stable/generated/torch.bmm\n /// <summary>\n /// Performs a batch matrix-matrix product of matrices stored in input and mat2.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"batch2\">the second batch of matrices to be multiplied</param>\n public static Tensor bmm(Tensor input, Tensor batch2) => input.bmm(batch2);\n\n // https://pytorch.org/docs/stable/generated/torch.chain_matmul\n public static Tensor chain_matmul(params Tensor[] matrices) => torch.linalg.multi_dot(matrices);\n\n // https://pytorch.org/docs/stable/generated/torch.cholesky\n\n public static Tensor cholesky(Tensor input) => input.cholesky();\n\n // https://pytorch.org/docs/stable/generated/torch.cholesky_inverse\n /// <summary>\n /// Computes the inverse of a symmetric positive-definite matrix AA using its Cholesky factor uu : returns matrix inv\n /// </summary>\n /// <returns></returns>\n public static Tensor cholesky_inverse(Tensor input, bool upper = false)\n => input.cholesky_inverse(upper);\n\n // https://pytorch.org/docs/stable/generated/torch.cholesky_solve\n /// <summary>\n /// Solves a linear system of equations with a positive semidefinite matrix to be inverted given its Cholesky factor matrix u.\n /// </summary>\n /// <returns></returns>\n public static Tensor cholesky_solve(Tensor input, Tensor input2, bool upper = false)\n => input.cholesky_solve(input2, upper);\n\n // https://pytorch.org/docs/stable/generated/torch.dot\n /// <summary>\n /// Computes the dot product of two 1D tensors.\n /// </summary>\n public static Tensor dot(Tensor input, Tensor other) => input.dot(other);\n\n // https://pytorch.org/docs/stable/generated/torch.eig\n [Obsolete(\"Method removed in Pytorch. Please use the `torch.linalg.eig` function instead.\", true)]\n public static (Tensor eigenvalues, Tensor eigenvectors) eig(Tensor input, bool eigenvectors = false) => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.geqrf\n /// <summary>\n /// This is a low-level function for calling LAPACK’s geqrf directly.\n /// This function returns a namedtuple (a, tau) as defined in LAPACK documentation for geqrf.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <remarks>\n /// Computes a QR decomposition of input. Both Q and R matrices are stored in the same output tensor a.\n /// The elements of R are stored on and above the diagonal. Elementary reflectors (or Householder vectors)\n /// implicitly defining matrix Q are stored below the diagonal. The results of this function can be used\n /// together with torch.linalg.householder_product() to obtain the Q matrix or with torch.ormqr(), which\n /// uses an implicit representation of the Q matrix, for an efficient matrix-matrix multiplication.\n /// </remarks>\n public static (Tensor a, Tensor tau) geqrf(Tensor input) => input.geqrf();\n\n // https://pytorch.org/docs/stable/generated/torch.ger\n /// <summary>\n /// Outer product of input and vec2.\n /// </summary>\n /// <param name=\"input\">The input vector.</param>\n /// <param name=\"vec2\">1-D input vector.</param>\n /// <remarks>If input is a vector of size n and vec2 is a vector of size m, then out must be a matrix of size n×m.</remarks>\n public static Tensor ger(Tensor input, Tensor vec2) => input.ger(vec2);\n\n // https://pytorch.org/docs/stable/generated/torch.inner\n /// <summary>\n /// Computes the dot product for 1D tensors.\n /// For higher dimensions, sums the product of elements from input and other along their last dimension.\n /// </summary>\n public static Tensor inner(Tensor input, Tensor vec2) => input.inner(vec2);\n\n // https://pytorch.org/docs/stable/generated/torch.inverse\n /// <summary>\n /// Alias for torch.linalg.inv()\n /// </summary>\n public static Tensor inverse(Tensor input) => linalg.inv(input);\n\n // https://pytorch.org/docs/stable/generated/torch.det\n /// <summary>\n /// Computes the determinant of a square matrix.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor det(Tensor input) => input.det();\n\n // https://pytorch.org/docs/stable/generated/torch.logdet\n public static Tensor logdet(Tensor input) => input.logdet();\n\n // https://pytorch.org/docs/stable/generated/torch.slogdet\n public static (Tensor res, Tensor logabsdet) slogdet(Tensor A) => torch.linalg.slogdet(A);\n\n // https://pytorch.org/docs/stable/generated/torch.lstsq\n /// <summary>\n /// Computes the solution to the least squares and least norm problems for a full rank matrix A of size m×n and a matrix B of size m×k.\n /// </summary>\n /// <param name=\"A\">the m by n matrix AA</param>\n /// <param name=\"B\">the matrix BB</param>\n /// <returns></returns>\n public static (Tensor Solution, Tensor QR) lstsq(Tensor B, Tensor A)\n {\n var solution = THSTorch_lstsq(B.Handle, A.Handle, out var qr);\n if (solution == IntPtr.Zero || qr == IntPtr.Zero)\n CheckForErrors();\n return (new Tensor(solution), new Tensor(qr));\n }\n\n // https://pytorch.org/docs/stable/generated/torch.lu\n /// <summary>\n /// Computes the LU factorization of a matrix or batches of matrices A. Returns a tuple containing the LU factorization and pivots of A. Pivoting is done if pivot is set to true.\n /// </summary>\n /// <param name=\"A\">The tensor to factor of size (∗,m,n)</param>\n /// <param name=\"pivot\">Controls whether pivoting is done. Default: true</param>\n /// <param name=\"get_infos\">If set to True, returns an info IntTensor. Default: false</param>\n /// <returns></returns>\n public static (Tensor A_LU, Tensor? pivots, Tensor? infos) lu(Tensor A, bool pivot = true, bool get_infos = false)\n {\n var solution = THSTensor_lu(A.Handle, pivot, get_infos, out var infos, out var pivots);\n if (solution == IntPtr.Zero)\n torch.CheckForErrors();\n return (new Tensor(solution), pivots == IntPtr.Zero ? null : new Tensor(pivots), infos == IntPtr.Zero ? null : new Tensor(infos));\n }\n\n // https://pytorch.org/docs/stable/generated/torch.lu_solve\n /// <summary>\n /// Returns the LU solve of the linear system Ax = b using the partially pivoted LU factorization of A from torch.lu().\n /// </summary>\n /// <param name=\"b\">The RHS tensor of size (∗,m,k), where *∗ is zero or more batch dimensions.</param>\n /// <param name=\"LU_data\">The pivoted LU factorization of A from torch.lu() of size (∗,m,m), where *∗ is zero or more batch dimensions.</param>\n /// <param name=\"LU_pivots\">\n /// The pivots of the LU factorization from torch.lu() of size (∗,m), where *∗ is zero or more batch dimensions.\n /// The batch dimensions of LU_pivots must be equal to the batch dimensions of LU_data.</param>\n /// <returns></returns>\n public static Tensor lu_solve(Tensor b, Tensor LU_data, Tensor LU_pivots)\n {\n var solution = THSTensor_lu_solve(b.Handle, LU_data.Handle, LU_pivots.Handle);\n if (solution == IntPtr.Zero)\n CheckForErrors();\n return new Tensor(solution);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.lu_unpack\n /// <summary>\n /// Unpacks the data and pivots from a LU factorization of a tensor into tensors L and U and a permutation tensor P.\n /// </summary>\n /// <param name=\"LU_data\">The packed LU factorization data</param>\n /// <param name=\"LU_pivots\">The packed LU factorization pivots</param>\n /// <param name=\"unpack_data\">A flag indicating if the data should be unpacked. If false, then the returned L and U are null. Default: true</param>\n /// <param name=\"unpack_pivots\">A flag indicating if the pivots should be unpacked into a permutation matrix P. If false, then the returned P is null. Default: true</param>\n /// <returns>A tuple of three tensors to use for the outputs (P, L, U)</returns>\n public static (Tensor P, Tensor? L, Tensor? U) lu_unpack(Tensor LU_data, Tensor LU_pivots, bool unpack_data = true, bool unpack_pivots = true)\n {\n var solution = THSTensor_lu_unpack(LU_data.Handle, LU_pivots.Handle, unpack_data, unpack_pivots, out var L, out var U);\n if (solution == IntPtr.Zero)\n CheckForErrors();\n return (new Tensor(solution), L == IntPtr.Zero ? null : new Tensor(L), U == IntPtr.Zero ? null : new Tensor(U));\n }\n\n // https://pytorch.org/docs/stable/generated/torch.matmul\n /// <summary>\n /// Matrix product of two tensors.\n /// </summary>\n /// <returns></returns>\n /// <remarks>\n /// The behavior depends on the dimensionality of the tensors as follows:\n /// 1. If both tensors are 1-dimensional, the dot product (scalar) is returned\n /// 2. If both arguments are 2-dimensional, the matrix-matrix product is returned.\n /// 3. If the first argument is 1-dimensional and the second argument is 2-dimensional, a 1 is prepended to its dimension for the purpose of the matrix multiply. After the matrix multiply, the prepended dimension is removed.\n /// 4. If the first argument is 2-dimensional and the second argument is 1-dimensional, the matrix-vector product is returned.\n /// 5. If both arguments are at least 1-dimensional and at least one argument is N-dimensional (where N > 2), then a batched matrix multiply is returned.\n /// </remarks>\n public static Tensor matmul(Tensor input, Tensor target) => input.matmul(target);\n\n // https://pytorch.org/docs/stable/generated/torch.matrix_power\n /// <summary>\n /// Computes the n-th power of a square matrix for an integer n.\n /// </summary>\n /// <param name=\"input\">The input square matrix.</param>\n /// <param name=\"n\">The exponent</param>\n /// <returns></returns>\n /// <remarks>Input tensor must be of shape (*, m, m) where * is zero or more batch dimensions.</remarks>\n public static Tensor matrix_power(Tensor input, int n) => input.matrix_power(n);\n\n // https://pytorch.org/docs/stable/generated/torch.matrix_rank\n [Obsolete(\"This function was deprecated since version 1.9 and is now removed. Please use the 'torch.linalg.matrix_rank' function instead.\", true)]\n public static Tensor matrix_rank(Tensor input, float? tol = null, bool symmetric = false) => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.matrix_exp\n /// <summary>\n /// Computes the matrix exponential of a square matrix or of each square matrix in a batch.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n public static Tensor matrix_exp(Tensor input) => input.matrix_exp();\n\n // https://pytorch.org/docs/stable/generated/torch.mm\n /// <summary>\n /// Performs a matrix multiplication of the matrices input and mat2.\n /// </summary>\n /// <returns></returns>\n public static Tensor mm(Tensor input, Tensor target) => input.mm(target);\n\n // https://pytorch.org/docs/stable/generated/torch.mv\n /// <summary>\n /// Performs a matrix-vector product of the matrix input and the vector vec.\n /// </summary>\n /// <returns></returns>\n public static Tensor mv(Tensor input, Tensor target) => input.mv(target);\n\n // https://pytorch.org/docs/stable/generated/torch.orgqr\n /// <summary>\n /// Computes the first n columns of a product of Householder matrices.\n /// </summary>\n /// <param name=\"input\">tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"tau\">tensor of shape (*, k) where * is zero or more batch dimensions.</param>\n public static Tensor orgqr(Tensor input, Tensor tau) => linalg.householder_product(input, tau);\n\n // https://pytorch.org/docs/stable/generated/torch.ormqr\n /// <summary>\n /// Computes the matrix-matrix multiplication of a product of Householder matrices with a general matrix.\n /// </summary>\n /// <param name=\"input\">Tensor of shape (*, mn, k) where * is zero or more batch dimensions and mn equals to m or n depending on the left.</param>\n /// <param name=\"tau\">Tensor of shape (*, min(mn, k)) where * is zero or more batch dimensions.</param>\n /// <param name=\"other\">Tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"left\">Controls the order of multiplication.</param>\n /// <param name=\"transpose\">Controls whether the matrix Q is conjugate transposed or not.</param>\n public static Tensor ormqr(Tensor input, Tensor tau, Tensor other, bool left=true, bool transpose=false) => input.ormqr(tau, other, left, transpose); \n\n // https://pytorch.org/docs/stable/generated/torch.outer\n /// <summary>\n /// Outer product of input and vec2.\n /// </summary>\n /// <param name=\"input\">1-D input vector.</param>\n /// <param name=\"vec2\">1-D input vector.</param>\n /// <remarks>If input is a vector of size n and vec2 is a vector of size m, then out must be a matrix of size n×m.</remarks>\n public static Tensor outer(Tensor input, Tensor vec2) => input.outer(vec2);\n\n // https://pytorch.org/docs/stable/generated/torch.pinverse\n /// <summary>\n /// Computes the pseudoinverse (Moore-Penrose inverse) of a matrix.\n /// </summary>\n /// <param name=\"input\">Tensor of shape (*, m, n) where * is zero or more batch dimensions.</param>\n /// <param name=\"rcond\">The tolerance value to determine when is a singular value zero </param>\n /// <param name=\"hermitian\">Indicates whether A is Hermitian if complex or symmetric if real. </param>\n /// <remarks>Input should be tensor of shape (*, m, n) where * is zero or more batch dimensions.</remarks>\n public static Tensor pinverse(Tensor input, double rcond = 1e-15, bool hermitian = false) => input.pinverse(rcond, hermitian);\n\n // https://pytorch.org/docs/stable/generated/torch.qr\n [Obsolete(\"torch.qr() is deprecated in favor of torch.linalg.qr() and will be removed in a future PyTorch release.\", true)]\n public static Tensor qr(Tensor input, bool some = true) => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.svd\n [Obsolete(\"torch.qr() is deprecated in favor of torch.linalg.svd() and will be removed in a future PyTorch release.\", true)]\n public static Tensor svd(Tensor input, bool some=true, bool compute_uv=true) => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.svd_lowrank\n // NOTE TO SELF: there's no native method for this. PyTorch implements it in Python.\n [Obsolete(\"not implemented\", true)]\n public static Tensor svd_lowrank(Tensor A, int q=6, int niter=2,Tensor? M=null) => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.pca_lowrank\n // NOTE TO SELF: there's no native method for this. PyTorch implements it in Python.\n [Obsolete(\"not implemented\", true)]\n public static Tensor pca_lowrank(Tensor A, int q=6, bool center=true, int niter=2) => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.symeig\n [Obsolete(\"torch.symeig() is deprecated in favor of torch.linalg.eigh() and will be removed in a future PyTorch release\", true)]\n public static Tensor symeig(Tensor input, bool eigenvectors = false, bool upper = true) => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.lobpcg\n [Obsolete(\"not implemented\", true)]\n static Tensor lobpcg(\n Tensor A,\n int k = 1,\n Tensor? B = null,\n Tensor? X = null,\n int? n = null,\n Tensor? iK = null,\n int? niter = null,\n float? tol=null,\n bool largest=true,\n LobpcgMethod method = LobpcgMethod.ortho,\n Action? tracker=null,\n IDictionary<string, string>? ortho_iparams=null,\n IDictionary<string, string>? ortho_fparams=null,\n IDictionary<string, string>? ortho_bparams=null)\n => throw new NotImplementedException();\n\n /// <summary>\n /// Computes the softmax function for the input tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">A dimension along which softmax will be computed.</param>\n /// <param name=\"dtype\">The desired data type of returned tensor.</param>\n public static Tensor softmax(Tensor input, int dim, ScalarType? dtype = null)\n => torch.special.softmax(input, dim, dtype);\n\n // https://pytorch.org/docs/stable/generated/torch.trapz\n /// <summary>\n /// Computes the trapezoidal rule along dim. By default the spacing between elements is assumed\n /// to be 1, but dx can be used to specify a different constant spacing, and x can be used to specify arbitrary spacing along dim.\n /// </summary>\n /// <param name=\"y\">Values to use when computing the trapezoidal rule.</param>\n /// <param name=\"x\">Defines spacing between values as specified above.</param>\n /// <param name=\"dim\">The dimension along which to compute the trapezoidal rule. The last (inner-most) dimension by default.</param>\n public static Tensor trapz(Tensor y, Tensor x, long dim = -1) => trapezoid(y, x, dim);\n\n /// <summary>\n /// Computes the trapezoidal rule along dim. By default the spacing between elements is assumed\n /// to be 1, but dx can be used to specify a different constant spacing, and x can be used to specify arbitrary spacing along dim.\n /// </summary>\n /// <param name=\"y\">Values to use when computing the trapezoidal rule.</param>\n /// <param name=\"dx\">Constant spacing between values.</param>\n /// <param name=\"dim\">The dimension along which to compute the trapezoidal rule. The last (inner-most) dimension by default.</param>\n public static Tensor trapz(Tensor y, double dx = 1, long dim = -1) => trapezoid(y, dx, dim);\n\n // https://pytorch.org/docs/stable/generated/torch.trapezoid\n /// <summary>\n /// Computes the trapezoidal rule along dim. By default the spacing between elements is assumed\n /// to be 1, but dx can be used to specify a different constant spacing, and x can be used to specify arbitrary spacing along dim.\n /// </summary>\n /// <param name=\"y\">Values to use when computing the trapezoidal rule.</param>\n /// <param name=\"x\">Defines spacing between values as specified above.</param>\n /// <param name=\"dim\">The dimension along which to compute the trapezoidal rule. The last (inner-most) dimension by default.</param>\n public static Tensor trapezoid(Tensor y, Tensor x, long dim = -1) => y.trapezoid(x, dim);\n\n /// <summary>\n /// Computes the trapezoidal rule along dim. By default the spacing between elements is assumed\n /// to be 1, but dx can be used to specify a different constant spacing, and x can be used to specify arbitrary spacing along dim.\n /// </summary>\n /// <param name=\"y\">Values to use when computing the trapezoidal rule.</param>\n /// <param name=\"dx\">Constant spacing between values.</param>\n /// <param name=\"dim\">The dimension along which to compute the trapezoidal rule. The last (inner-most) dimension by default.</param>\n public static Tensor trapezoid(Tensor y, double dx = 1, long dim = -1) => y.trapezoid(dx, dim);\n\n // https://pytorch.org/docs/stable/generated/torch.cumulative_trapezoid\n /// <summary>\n /// Cumulatively computes the trapezoidal rule along dim. By default the spacing between elements is assumed\n /// to be 1, but dx can be used to specify a different constant spacing, and x can be used to specify arbitrary spacing along dim.\n /// </summary>\n /// <param name=\"y\">Values to use when computing the trapezoidal rule.</param>\n /// <param name=\"x\">Defines spacing between values as specified above.</param>\n /// <param name=\"dim\">The dimension along which to compute the trapezoidal rule. The last (inner-most) dimension by default.</param>\n public static Tensor cumulative_trapezoid(Tensor y, Tensor x, long dim = -1) => y.cumulative_trapezoid(x, dim);\n\n /// <summary>\n /// Cumulatively computes the trapezoidal rule along dim. By default the spacing between elements is assumed\n /// to be 1, but dx can be used to specify a different constant spacing, and x can be used to specify arbitrary spacing along dim.\n /// </summary>\n /// <param name=\"y\">Values to use when computing the trapezoidal rule.</param>\n /// <param name=\"dx\">Constant spacing between values.</param>\n /// <param name=\"dim\">The dimension along which to compute the trapezoidal rule. The last (inner-most) dimension by default.</param>\n public static Tensor cumulative_trapezoid(Tensor y, double dx = 1, long dim = -1) => y.cumulative_trapezoid(dx, dim);\n\n // https://pytorch.org/docs/stable/generated/torch.triangular_solve\n [Obsolete(\"torch.triangular_solve() is deprecated in favor of torch.linalg.solve_triangular() and will be removed in a future PyTorch release.\", true)]\n static Tensor triangular_solve(\n Tensor b,\n Tensor A,\n bool upper = true,\n bool transpose = false,\n bool unitriangular = false)\n => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.vdot\n /// <summary>\n /// Computes the dot product of two 1D tensors.\n /// </summary>\n /// <param name=\"input\"></param>\n /// <param name=\"target\"></param>\n /// <returns></returns>\n /// <remarks>\n /// The vdot(a, b) function handles complex numbers differently than dot(a, b).\n /// If the first argument is complex, the complex conjugate of the first argument is used for the calculation of the dot product.\n /// </remarks>\n public static Tensor vdot(Tensor input, Tensor target) => input.vdot(target);\n }\n}" }, { "alpha_fraction": 0.4919374883174896, "alphanum_fraction": 0.4924336373806, "avg_line_length": 32.59166717529297, "blob_id": "0ea4f8bf2e92f0d83ce8f138d3e05291366d4925", "content_id": "3f9d27b8075e626bd97b322548a45b8fdf0e4e11", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4031, "license_type": "permissive", "max_line_length": 131, "num_lines": 120, "path": "/src/TorchSharp/Generator.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n /// <summary>\n /// Random Number Generator\n /// </summary>\n public class Generator : IDisposable\n {\n public IntPtr Handle { get; private set; }\n\n /// <summary>\n /// Gets the current device of the generator.\n /// </summary>\n public torch.Device device { get; private set; }\n\n /// <summary>\n /// Returns the Generator state as a torch.ByteTensor.\n /// </summary>\n /// <returns></returns>\n public Tensor get_state()\n {\n var res = THSGenerator_get_rng_state(Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Sets the Generator state.\n /// </summary>\n /// <param name=\"value\">The desired state.</param>\n public void set_state(Tensor value)\n {\n THSGenerator_set_rng_state(Handle, value is null ? IntPtr.Zero : value.Handle);\n torch.CheckForErrors();\n }\n\n public Generator manual_seed(long seed)\n {\n torch.TryInitializeDeviceType(DeviceType.CUDA);\n THSGenerator_gen_manual_seed(Handle, seed);\n return this;\n }\n\n /// <summary>\n /// Gets a non-deterministic random number from std::random_device or the current time and uses it to seed a Generator.\n /// </summary>\n /// <returns></returns>\n public long seed()\n {\n long seed = DateTime.UtcNow.Ticks;\n torch.TryInitializeDeviceType(DeviceType.CUDA);\n THSGenerator_gen_manual_seed(Handle, seed);\n return seed;\n }\n\n internal Generator(IntPtr nativeHandle)\n {\n Handle = nativeHandle;\n device = torch.CPU;\n }\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"seed\">An initial seed to use with the generator.</param>\n /// <param name=\"device\">The desired device.</param>\n public Generator(ulong seed = 0, torch.Device? device = null) :\n this(THSGenerator_new(seed, (long)(device?.type ?? DeviceType.CPU), device?.index ?? -1))\n {\n this.device = device ?? torch.CPU;\n }\n\n public static Generator Default {\n get {\n return new Generator(THSGenerator_default_generator());\n }\n }\n\n /// <summary>\n /// Returns the initial seed for generating random numbers.\n /// </summary>\n /// <returns></returns>\n public long initial_seed()\n {\n return THSGenerator_initial_seed(Handle);\n }\n\n #region Dispose() support\n protected virtual void Dispose(bool disposing)\n {\n if (Handle != IntPtr.Zero) {\n var h = Handle;\n Handle = IntPtr.Zero;\n THSGenerator_dispose(h);\n }\n }\n\n ~Generator()\n {\n // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method\n Dispose(disposing: false);\n }\n\n public void Dispose()\n {\n // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method\n Dispose(disposing: true);\n GC.SuppressFinalize(this);\n }\n #endregion\n }\n }\n}\n" }, { "alpha_fraction": 0.5701754093170166, "alphanum_fraction": 0.5742239952087402, "avg_line_length": 34.28571319580078, "blob_id": "888583bb24b5c312f323f7359b4badabe3fcfce1", "content_id": "cdf7f93bc10cab285c61c0b1a8b9376f0abcfdd0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1482, "license_type": "permissive", "max_line_length": 130, "num_lines": 42, "path": "/src/TorchVision/AdjustContrast.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class AdjustContrast : ITransform\n {\n internal AdjustContrast(double contrast_factor)\n {\n if (contrast_factor < 0.0)\n throw new ArgumentException($\"The sharpness factor ({contrast_factor}) must be non-negative.\");\n this.contrast_factor = contrast_factor;\n }\n\n public Tensor call(Tensor input)\n {\n return transforms.functional.adjust_contrast(input, contrast_factor);\n }\n\n private double contrast_factor;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Adjust the contrast of the image. \n /// </summary>\n /// <param name=\"contrast_factor\">\n /// How much to adjust the contrast. Can be any non-negative number.\n /// 0 gives a solid gray image, 1 gives the original image while 2 increases the contrast by a factor of 2.\n /// </param>\n /// <returns></returns>\n static public ITransform AdjustContrast(double contrast_factor)\n {\n return new AdjustContrast(contrast_factor);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.738095223903656, "alphanum_fraction": 0.7428571581840515, "avg_line_length": 31.30769157409668, "blob_id": "bda0a3cf34e22556c9ab1b2f7229c8afe1773533", "content_id": "f299c7b0e6fa2336c50f70420d1221eb65381048", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 420, "license_type": "permissive", "max_line_length": 130, "num_lines": 13, "path": "/src/TorchSharp/PInvoke/LibTorchSharp.crc32c.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp.PInvoke\n{\n internal static partial class NativeMethods\n {\n [DllImport(\"LibTorchSharp\")]\n internal static extern uint crc32c_append(uint crc, IntPtr value, ulong length);\n }\n}\n" }, { "alpha_fraction": 0.5171321034431458, "alphanum_fraction": 0.5222156047821045, "avg_line_length": 57.034481048583984, "blob_id": "8bd612088c2e48d10752d8fe514a557d09611e7b", "content_id": "5dd5fe6e2fd128b473d4d4ad55c8146dbf760522", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 15159, "license_type": "permissive", "max_line_length": 288, "num_lines": 261, "path": "/src/TorchSharp/NN/Vision.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public enum UpsampleMode\n {\n Nearest = 0,\n Linear = 1,\n Bilinear = 2,\n Bicubic = 3,\n Trilinear = 4\n }\n\n public enum InterpolationMode\n {\n Nearest = 0,\n Linear = 1,\n Bilinear = 2,\n Bicubic = 3,\n Trilinear = 4,\n Area = 5\n }\n\n public enum GridSampleMode\n {\n Nearest = 0,\n Bilinear = 2,\n // PyTorch docs say this should be available,\n // but the libtorch native code does not support it.\n //Bicubic = 3\n }\n\n public enum GridSamplePaddingMode\n {\n Zeros = 0,\n Reflection = 1,\n Border = 2,\n }\n\n public static partial class nn\n {\n\n public static partial class functional\n {\n\n /// <summary>\n /// Pads tensor.\n /// </summary>\n /// <param name=\"input\">N-dimensional tensor</param>\n /// <param name=\"pad\">m-elements tuple, where m/2 ≤ input dimensions and m is even</param>\n /// <param name=\"mode\">'constant', 'reflect', 'replicate' or 'circular'. Default: 'constant'</param>\n /// <param name=\"value\">Fill value for 'constant' padding. Default: 0</param>\n /// <returns></returns>\n public static Tensor pad(Tensor input, long[] pad, PaddingModes mode = PaddingModes.Constant, double value = 0)\n {\n unsafe {\n fixed (long* psize = pad) {\n var res = THSNN_pad(input.Handle, (IntPtr)psize, pad.Length, (byte)mode, value);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Pads tensor.\n /// </summary>\n /// <param name=\"input\">N-dimensional tensor</param>\n /// <param name=\"pad\">m-elements tuple, where m/2 ≤ input dimensions and m is even</param>\n /// <param name=\"mode\">'constant', 'reflect', 'replicate' or 'circular'. Default: 'constant'</param>\n /// <param name=\"value\">Fill value for 'constant' padding. Default: 0</param>\n /// <returns></returns>\n public static Tensor pad(Tensor input, ReadOnlySpan<long> pad, PaddingModes mode = PaddingModes.Constant, double value = 0)\n {\n unsafe {\n fixed (long* psize = pad) {\n var res = THSNN_pad(input.Handle, (IntPtr)psize, pad.Length, (byte)mode, value);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Pads tensor.\n /// </summary>\n /// <param name=\"input\">N-dimensional tensor</param>\n /// <param name=\"pad\">m-elements tuple, where m/2 ≤ input dimensions and m is even</param>\n /// <param name=\"mode\">'constant', 'reflect', 'replicate' or 'circular'. Default: 'constant'</param>\n /// <param name=\"value\">Fill value for 'constant' padding. Default: 0</param>\n /// <returns></returns>\n public static Tensor pad(Tensor input, (long, long) pad, PaddingModes mode = PaddingModes.Constant, double value = 0)\n {\n unsafe {\n var correctedPad = stackalloc long[] { pad.Item1, pad.Item2 };\n\n var res = THSNN_pad(input.Handle, (IntPtr)correctedPad, 2, (byte)mode, value);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n /// <summary>\n /// Pads tensor.\n /// </summary>\n /// <param name=\"input\">N-dimensional tensor</param>\n /// <param name=\"pad\">m-elements tuple, where m/2 ≤ input dimensions and m is even</param>\n /// <param name=\"mode\">'constant', 'reflect', 'replicate' or 'circular'. Default: 'constant'</param>\n /// <param name=\"value\">Fill value for 'constant' padding. Default: 0</param>\n /// <returns></returns>\n public static Tensor pad(Tensor input, (long, long, long, long) pad, PaddingModes mode = PaddingModes.Constant, double value = 0)\n {\n unsafe {\n var correctedPad = stackalloc long[] { pad.Item1, pad.Item2, pad.Item3, pad.Item4 };\n var res = THSNN_pad(input.Handle, (IntPtr)correctedPad, 4, (byte)mode, value);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n /// <summary>\n /// Pads tensor.\n /// </summary>\n /// <param name=\"input\">N-dimensional tensor</param>\n /// <param name=\"pad\">A single padding size, used for all edges.</param>\n /// <param name=\"mode\">'constant', 'reflect', 'replicate' or 'circular'. Default: 'constant'</param>\n /// <param name=\"value\">Fill value for 'constant' padding. Default: 0</param>\n /// <returns></returns>\n public static Tensor pad(Tensor input, long pad, PaddingModes mode = PaddingModes.Constant, double value = 0)\n {\n int length = (int)input.ndim * 2;\n\n unsafe {\n var correctedPad = stackalloc long[length];\n for (var i = 0; i < length; i++) correctedPad[i] = pad;\n\n var res = THSNN_pad(input.Handle, (IntPtr)correctedPad, length, (byte)mode, value);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n\n\n /// <summary>\n /// Given an input and a flow-field grid, computes the output using input values and pixel locations from grid.\n /// </summary>\n /// <param name=\"input\">Tensor of 4D or 5D</param>\n /// <param name=\"grid\">Flow-field tensor.</param>\n /// <param name=\"mode\">Interpolation mode to calculate output values 'bilinear' | 'nearest' | 'bicubic'.</param>\n /// <param name=\"padding_mode\">Padding mode for outside grid values 'zeros' | 'border' | 'reflection'. Default: 'zeros'</param>\n /// <param name=\"align_corners\">Geometrically, we consider the pixels of the input as squares rather than points.\n /// If set to true, the extrema (-1 and 1) are considered as referring to the center points of the input’s corner pixels.\n /// If set to false, they are instead considered as referring to the corner points of the input’s corner pixels, making the sampling more resolution agnostic.</param>\n /// <returns></returns>\n /// <remarks>\n /// Currently, only spatial (4-D) and volumetric (5-D) input are supported.\n /// Note: mode='bicubic' supports only 4-D input.\n /// </remarks>\n public static Tensor grid_sample(Tensor input, Tensor grid, GridSampleMode mode = GridSampleMode.Bilinear, GridSamplePaddingMode padding_mode = GridSamplePaddingMode.Zeros, bool? align_corners = null)\n {\n byte ac = (byte)((align_corners.HasValue) ? (align_corners.Value ? 1 : 2) : 0);\n var res = THSNN_grid_sample(input.Handle, grid.Handle, (byte)mode, (byte)padding_mode, ac);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Generates a 2D or 3D flow field (sampling grid), given a batch of affine matrices theta.\n /// </summary>\n /// <param name=\"theta\">Input batch of affine matrices with shape (N, 2, 3 ) for 2D or (N, 3, 4 ) for 3D</param>\n /// <param name=\"size\">The target output image size</param>\n /// <param name=\"align_corners\">if true, consider -1 and 1 to refer to the centers of the corner pixels rather than the image corners.\n /// Refer to grid_sample() for a more complete description.</param>\n /// <returns></returns>\n public static Tensor affine_grid(Tensor theta, long[]? size = null, bool align_corners = false)\n {\n unsafe {\n fixed (long* psize = size) {\n var res = THSNN_affine_grid(theta.Handle, (IntPtr)psize, size is null ? 0 : size.Length, align_corners);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n ///\n /// </summary>\n /// <param name=\"x\">The input tensor</param>\n /// <param name=\"size\">Output spatial size</param>\n /// <param name=\"scale_factor\">Multiplier for spatial size. Has to match input size if it is a tuple.</param>\n /// <param name=\"mode\">The algorithm used for upsampling: 'nearest' | 'linear' | 'bilinear' | 'bicubic' | 'trilinear' | 'area'</param>\n /// <param name=\"align_corners\">Geometrically, we consider the pixels of the input and output as squares rather than points.\n /// If set to true, the input and output tensors are aligned by the center points of their corner pixels, preserving the values at the corner pixels.\n /// If set to false, the input and output tensors are aligned by the corner points of their corner pixels, and the interpolation uses edge value padding for out-of-boundary values, making this operation independent of input size when scale_factor is kept the same.</param>\n /// <param name=\"recompute_scale_factor\">\n /// Recompute the scale_factor for use in the interpolation calculation.\n /// When scale_factor is passed as a parameter, it is used to compute the output_size.\n /// If recompute_scale_factor is False or not specified, the passed-in scale_factor will be used in the interpolation computation.\n /// Otherwise, a new scale_factor will be computed based on the output and input sizes for use in the interpolation computation\n /// (i.e. the computation will be identical to if the computed output_size were passed-in explicitly).\n /// </param>\n /// <returns></returns>\n public static Tensor interpolate(Tensor x, long[]? size = null, double[]? scale_factor = null, InterpolationMode mode = InterpolationMode.Nearest, bool? align_corners = null, bool recompute_scale_factor = false)\n {\n unsafe {\n fixed (long* psize = size) {\n fixed (double* pSF = scale_factor) {\n byte ac = (byte)((align_corners.HasValue) ? (align_corners.Value ? 1 : 2) : 0);\n var res = THSNN_interpolate(x.Handle, (IntPtr)psize, size is null ? 0 : size.Length, (IntPtr)pSF, scale_factor is null ? 0 : scale_factor.Length, (byte)mode, ac, recompute_scale_factor);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n\n /// <summary>\n /// Upsamples a given multi-channel 1D (temporal), 2D (spatial) or 3D (volumetric) data.\n /// The input data is assumed to be of the form minibatch x channels x[optional depth] x[optional height] x width.\n /// Hence, for spatial inputs, we expect a 4D Tensor and for volumetric inputs, we expect a 5D Tensor.\n /// </summary>\n /// <param name=\"x\">Input tensor</param>\n /// <param name=\"size\">Output spatial sizes</param>\n /// <param name=\"scale_factor\">Multiplier for spatial size. Has to match input size</param>\n /// <param name=\"align_corners\">If true, the corner pixels of the input and output tensors are aligned, and thus preserving the values at those pixels.\n /// This only has effect when mode is 'linear', 'bilinear', or 'trilinear'. Default: false</param>\n /// <returns></returns>\n public static Tensor upsample_bilinear(Tensor x, long[]? size = null, double[]? scale_factor = null, bool align_corners = false)\n {\n using (var d = torch.nn.Upsample(size, scale_factor, UpsampleMode.Bilinear, align_corners)) {\n return d.call(x);\n }\n }\n\n /// <summary>\n /// Upsamples a given multi-channel 1D (temporal), 2D (spatial) or 3D (volumetric) data.\n /// The input data is assumed to be of the form minibatch x channels x[optional depth] x[optional height] x width.\n /// Hence, for spatial inputs, we expect a 4D Tensor and for volumetric inputs, we expect a 5D Tensor.\n /// </summary>\n /// <param name=\"x\">Input tensor</param>\n /// <param name=\"size\">Output spatial sizes</param>\n /// <param name=\"scale_factor\">Multiplier for spatial size. Has to match input size</param>\n /// <param name=\"align_corners\">If true, the corner pixels of the input and output tensors are aligned, and thus preserving the values at those pixels.\n /// This only has effect when mode is 'linear', 'bilinear', or 'trilinear'. Default: false</param>\n /// <returns></returns>\n public static Tensor upsample_nearest(Tensor x, long[]? size = null, double[]? scale_factor = null, bool align_corners = false)\n {\n using (var d = torch.nn.Upsample(size, scale_factor, UpsampleMode.Nearest, align_corners)) {\n return d.call(x);\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6417730450630188, "alphanum_fraction": 0.6452260613441467, "avg_line_length": 76.83125305175781, "blob_id": "a24c9deda0e64edcddc858185877109356b6bc20", "content_id": "bb2df53f325dab07cb4fcd887d8f431b6ca1a461", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 12465, "license_type": "permissive", "max_line_length": 490, "num_lines": 160, "path": "/src/TorchSharp/NN/EmbeddingBag.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using Modules;\n\n public enum EmbeddingBagMode\n {\n Sum = 0,\n Mean = 1,\n Max = 2\n }\n\n namespace Modules\n {\n public sealed class EmbeddingBag : torch.nn.Module<Tensor, Tensor?, Tensor?, Tensor>, torch.nn.IModule<Tensor, Tensor, Tensor>, torch.nn.IModule<Tensor, Tensor?, Tensor?, Tensor>\n {\n internal EmbeddingBag(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n /// <summary>\n /// Forward pass of EmbeddingBag.\n /// </summary>\n /// <param name=\"input\">Tensor containing bags of indices into the embedding matrix.</param>\n /// <param name=\"offsets\">Only used when input is 1D. offsets determines the starting index position of each bag (sequence) in input.</param>\n /// <param name=\"perSampleWeights\">a tensor of float / double weights, or None to indicate all weights should be taken to be 1.\n /// If specified, per_sample_weights must have exactly the same shape as input and is treated as having the same offsets, if those are not None.\n /// Only supported for mode='sum'.</param>\n /// <returns></returns>\n public override Tensor forward(Tensor input, Tensor? offsets, Tensor? perSampleWeights)\n { \n var res = THSNN_EmbeddingBag_forward(handle, input.Handle, (offsets is null) ? IntPtr.Zero : offsets.Handle, (perSampleWeights is null) ? IntPtr.Zero : perSampleWeights.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public new Tensor call(Tensor input, Tensor? offsets, Tensor? perSampleWeights)\n {\n if (!input.IsIntegral()) throw new ArgumentException(\"Embedding input must be an integral tensor.\");\n if (!(offsets is null) && input.dtype != offsets.dtype) throw new ArgumentException(\"input and offsets must have the same element type.\");\n if (input.Dimensions == 1 && offsets is null) throw new ArgumentException(\"'offsets' must be non-null for a 1-D input.\");\n if (input.Dimensions == 2 && !(offsets is null)) throw new ArgumentException(\"'offsets' must be null for a 2-D input.\");\n\n if (input.Dimensions == 2 && input.dtype == ScalarType.Int32) throw new NotImplementedException(\"EmbeddingBag for 32-bit integers -- there's some issue in the native runtime that prevents this from working.\");\n\n return base.call(input, offsets, perSampleWeights);\n }\n\n /// <summary>\n /// Forward pass of EmbeddingBag.\n /// </summary>\n /// <param name=\"input\">Tensor containing bags of indices into the embedding matrix.</param>\n /// <param name=\"offsets\">Only used when input is 1D. offsets determines the starting index position of each bag (sequence) in input.</param>\n /// <returns></returns>\n public Tensor call(Tensor input, Tensor offsets)\n {\n if (!input.IsIntegral()) throw new ArgumentException(\"Embedding input must be an integral tensor.\");\n if (!(offsets is null) && input.dtype != offsets.dtype) throw new ArgumentException(\"input and offsets must have the same element type.\");\n if (input.Dimensions == 1 && offsets is null) throw new ArgumentException(\"'offsets' must be non-null for a 1-D input.\");\n if (input.Dimensions == 2 && !(offsets is null)) throw new ArgumentException(\"'offsets' must be null for a 2-D input.\");\n\n if (input.Dimensions == 2 && input.dtype == ScalarType.Int32) throw new NotImplementedException(\"EmbeddingBag for 32-bit integers -- there's some issue in the native runtime that prevents this from working.\");\n\n return base.call(input, offsets, null);\n }\n\n /// <summary>\n /// Forward pass of EmbeddingBag.\n /// </summary>\n /// <param name=\"input\">Tensor containing bags of indices into the embedding matrix.</param>\n /// <returns></returns>\n public Tensor call(Tensor input)\n {\n if (!input.IsIntegral()) throw new ArgumentException(\"Embedding input must be an integral tensor.\");\n if (input.Dimensions == 1) throw new ArgumentException(\"'offsets' must be non-null for a 1-D input.\");\n\n if (input.Dimensions == 2 && input.dtype == ScalarType.Int32) throw new NotImplementedException(\"EmbeddingBag for 32-bit integers -- there's some issue in the native runtime that prevents this from working.\");\n\n return base.call(input, null, null);\n }\n\n public Parameter? weight {\n get {\n var res = THSNN_EmbeddingBag_weight(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n set {\n THSNN_EmbeddingBag_set_weight(handle, value is null ? IntPtr.Zero : value.Handle);\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"weight\", value);\n }\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// A simple lookup table that stores embeddings of a fixed dictionary and size.\n /// This module is often used to store word embeddings and retrieve them using indices. The input to the module is a list of indices, and the output is the corresponding word embeddings.\n /// </summary>\n /// <param name=\"num_embeddings\">Size of the dictionary of embeddings, the vocabulary size.</param>\n /// <param name=\"embedding_dims\">The size of each embedding vector</param>\n /// <param name=\"max_norm\">If given, each embedding vector with norm larger than max_norm is renormalized to have norm max_norm.</param>\n /// <param name=\"norm_type\">The p of the p-norm to compute for the max_norm option. Default 2.</param>\n /// <param name=\"scale_grad_by_freq\">If given, this will scale gradients by the inverse of frequency of the words in the mini-batch. Default: false.</param>\n /// <param name=\"mode\">\"sum\", \"mean\" or \"max\". Specifies the way to reduce the bag.\n /// \"sum\" computes the weighted sum, taking per_sample_weights into consideration.\n /// \"mean\" computes the average of the values in the bag, \"max\" computes the max value over each bag. Default: \"mean\"</param>\n /// <param name=\"sparse\">If true, gradient w.r.t. weight matrix will be a sparse tensor. Default: false</param>\n /// <param name=\"include_last_offset\">If true, offsets has one additional element, where the last element is equivalent to the size of indices. This matches the CSR format.</param>\n /// <param name=\"padding_index\"> If specified, the entries at padding_idx do not contribute to the gradient; therefore, the embedding vector at padding_idx is not updated during training, i.e. it remains as a fixed “pad”. For a newly constructed EmbeddingBag, the embedding vector at padding_idx will default to all zeros, but can be updated to another value to be used as the padding vector. Note that the embedding vector at padding_idx is excluded from the reduction.</param>\n /// <param name=\"device\">The desired device of the parameters and buffers in this module</param>\n /// <param name=\"dtype\">The desired floating point or complex dtype of the parameters and buffers in this module</param>\n /// <returns></returns>\n /// <remarks>Keep in mind that only a limited number of optimizers support sparse gradients: currently it’s optim.SGD (CUDA and CPU), optim.SparseAdam (CUDA and CPU) and optim.Adagrad (CPU)</remarks>\n public static EmbeddingBag EmbeddingBag(long num_embeddings, long embedding_dims, double? max_norm = null, double norm_type = 2.0, bool scale_grad_by_freq = false, EmbeddingBagMode mode = EmbeddingBagMode.Mean, bool sparse = false, bool include_last_offset = false, long padding_index = -1, Device? device = null, ScalarType? dtype = null)\n {\n var res = THSNN_EmbeddingBag_ctor(num_embeddings, embedding_dims,\n max_norm.HasValue ? max_norm.Value : 0.0, max_norm.HasValue,\n norm_type, scale_grad_by_freq, (long)mode, sparse, include_last_offset, padding_index, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new EmbeddingBag(res, boxedHandle).MoveModule<EmbeddingBag>(device, dtype);\n }\n\n /// <summary>\n /// A simple lookup table that stores embeddings of a fixed dictionary and size.\n /// This module is often used to store word embeddings and retrieve them using indices. The input to the module is a list of indices, and the output is the corresponding word embeddings.\n /// </summary>\n /// <param name=\"embeddings\">FloatTensor containing weights for the EmbeddingBag in two dimensions. First dimension is being passed to EmbeddingBag as num_embeddings, second as embedding_dim.</param>\n /// <param name=\"freeze\">If true (the default), the tensor does not get updated in the learning</param>\n /// <param name=\"max_norm\">If given, each embedding vector with norm larger than max_norm is renormalized to have norm max_norm.</param>\n /// <param name=\"norm_type\">The p of the p-norm to compute for the max_norm option. Default 2.</param>\n /// <param name=\"scale_grad_by_freq\">If given, this will scale gradients by the inverse of frequency of the words in the mini-batch. Default: false.</param>\n /// <param name=\"mode\"></param>\n /// <param name=\"sparse\">If true, gradient w.r.t. weight matrix will be a sparse tensor. Default: false</param>\n /// <param name=\"include_last_offset\">If true, offsets has one additional element, where the last element is equivalent to the size of indices. This matches the CSR format.</param>\n /// <param name=\"padding_index\"> If specified, the entries at padding_idx do not contribute to the gradient; therefore, the embedding vector at padding_idx is not updated during training, i.e. it remains as a fixed “pad”. For a newly constructed EmbeddingBag, the embedding vector at padding_idx will default to all zeros, but can be updated to another value to be used as the padding vector. Note that the embedding vector at padding_idx is excluded from the reduction.</param>\n /// <param name=\"device\">The desired device of the parameters and buffers in this module</param>\n /// <param name=\"dtype\">The desired floating point or complex dtype of the parameters and buffers in this module</param>\n /// <returns></returns>\n /// <remarks>Keep in mind that only a limited number of optimizers support sparse gradients: currently it’s optim.SGD (CUDA and CPU), optim.SparseAdam (CUDA and CPU) and optim.Adagrad (CPU)</remarks>\n public static EmbeddingBag EmbeddingBag_from_pretrained(Tensor embeddings, bool freeze = true, double? max_norm = null, double norm_type = 2.0, bool scale_grad_by_freq = false, EmbeddingBagMode mode = EmbeddingBagMode.Mean, bool sparse = false, bool include_last_offset = false, long padding_index = -1, Device? device = null, ScalarType? dtype = null)\n {\n var res = THSNN_EmbeddingBag_from_pretrained(embeddings.Handle, freeze,\n max_norm.HasValue ? max_norm.Value : 0.0, max_norm.HasValue,\n norm_type, scale_grad_by_freq, (long)mode, sparse, include_last_offset, padding_index, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new EmbeddingBag(res, boxedHandle).MoveModule<EmbeddingBag>(device, dtype);\n\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5411838293075562, "alphanum_fraction": 0.5430629253387451, "avg_line_length": 38.41975402832031, "blob_id": "b401a64239981a2601ecfe56a567d19799a8c72e", "content_id": "35470b03f72a3c9246800aab224e8b3a16798a8c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3193, "license_type": "permissive", "max_line_length": 130, "num_lines": 81, "path": "/src/TorchAudio/Backend.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n /// <summary>\n /// Load audio data from a file.\n /// </summary>\n /// <param name=\"filepath\">The file path to load</param>\n /// <param name=\"frame_offset\">Number of frames to skip before reading data</param>\n /// <param name=\"num_frames\">Maximum number of frames to read.</param>\n /// <param name=\"normalize\">True to normalize the audio to [-1.0, 1.0]</param>\n /// <param name=\"channels_first\">The dimension of the returned tensor is [channel, time] when true</param>\n /// <param name=\"format\">The format of the audio file</param>\n /// <returns>A pair of waveform and sampling rate</returns>\n public static (torch.Tensor, int) load(\n string filepath,\n long frame_offset = 0,\n long num_frames = -1,\n bool normalize = true,\n bool channels_first = true,\n AudioFormat? format = null)\n {\n return backend.utils._backend.load(\n filepath,\n frame_offset,\n num_frames,\n normalize,\n channels_first,\n format);\n }\n\n /// <summary>\n /// Save audio data to a file.\n /// </summary>\n /// <param name=\"filepath\">The file path to save</param>\n /// <param name=\"src\">The waveform of audio</param>\n /// <param name=\"sample_rate\">The sampling rate of audio</param>\n /// <param name=\"channels_first\">The dimension of the returned tensor is [channel, time] when true</param>\n /// <param name=\"compression\">The compression factor</param>\n /// <param name=\"format\">The format of the audio file</param>\n /// <param name=\"encoding\">The audio encoding</param>\n /// <param name=\"bits_per_sample\">The number of bits per sample</param>\n public static void save(\n string filepath,\n torch.Tensor src,\n int sample_rate,\n bool channels_first = true,\n float? compression = null,\n AudioFormat? format = null,\n AudioEncoding? encoding = null,\n int? bits_per_sample = null)\n {\n backend.utils._backend.save(\n filepath,\n src,\n sample_rate,\n channels_first,\n compression,\n format,\n encoding,\n bits_per_sample);\n }\n\n /// <summary>\n /// Get the information of an audio file.\n /// </summary>\n /// <param name=\"filepath\">The file path of the audio file</param>\n /// <param name=\"format\">The format of the audio file</param>\n /// <returns>The information of the audio file</returns>\n public static AudioMetaData info(\n string filepath,\n AudioFormat? format = null)\n {\n return backend.utils._backend.info(\n filepath,\n format);\n }\n }\n}\n" }, { "alpha_fraction": 0.5016260147094727, "alphanum_fraction": 0.5040650367736816, "avg_line_length": 26.33333396911621, "blob_id": "5f658bfb6e1ecbbdad3cab413ed76b95377a5549", "content_id": "2dcce34a2d33e02f0680a530b17e35c205d98488", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4920, "license_type": "permissive", "max_line_length": 103, "num_lines": 180, "path": "/src/TorchSharp/Utils/OrderedDict.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System;\nusing System.Linq;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace TorchSharp.Utils\n{\n public class OrderedDict<TKey, TValue> : IDictionary<TKey, TValue>, IList<(TKey, TValue)>\n {\n /// <summary>\n /// Remove all items from the ParameterDict.\n /// </summary>\n public void clear()\n {\n _list.Clear();\n _dict.Clear();\n }\n\n /// <summary>\n /// Return an enumeration of the ParameterDict key/value pairs.\n /// </summary>\n /// <returns></returns>\n public IEnumerator<(TKey, TValue)> items() => _list.GetEnumerator();\n\n /// <summary>\n /// Return the ParameterDict keys.\n /// </summary>\n /// <returns></returns>\n public IEnumerable<TKey> keys() => _dict.Keys;\n\n /// <summary>\n /// Return the ParameterDict values.\n /// </summary>\n /// <returns></returns>\n public IEnumerable<TValue> values() => _dict.Values;\n\n public (TKey, TValue) this[int index] {\n get => _list[index];\n set {\n var key = value.Item1;\n _list[index] = value;\n _dict[key] = value.Item2;\n }\n }\n\n public bool IsReadOnly => false;\n\n public ICollection<TKey> Keys => _list.Select(kv => kv.Item1).ToList();\n\n public ICollection<TValue> Values => _list.Select(kv => kv.Item2).ToList();\n\n public int Count => _dict.Count;\n\n public TValue this[TKey key] {\n get => _dict[key];\n set {\n _dict[key] = value;\n var idx = _list.FindIndex(kv => kv.Item1.Equals(key));\n if (idx >= 0) {\n _list[idx] = (key, value);\n }\n else {\n _list.Add((key, value));\n }\n }\n }\n\n public void Add((TKey, TValue) item)\n {\n _dict.Add(item.Item1, item.Item2);\n _list.Add(item);\n }\n\n public void Add(TKey key, TValue value)\n {\n _dict.Add(key, value);\n _list.Add((key, value));\n }\n\n public void Add(KeyValuePair<TKey, TValue> item)\n {\n _dict.Add(item.Key, item.Value);\n _list.Add((item.Key, item.Value));\n }\n\n public bool Contains((TKey, TValue) item)\n {\n return _list.Contains(item);\n }\n\n public void CopyTo((TKey, TValue)[] array, int arrayIndex)\n {\n _list.CopyTo(array, arrayIndex);\n }\n\n public int IndexOf((TKey, TValue) item)\n {\n return _list.IndexOf(item);\n }\n\n public void Insert(int index, (TKey, TValue) item)\n {\n _dict.Add(item.Item1, item.Item2);\n _list.Insert(index, item);\n }\n\n public bool Remove((TKey, TValue) item)\n {\n _dict.Remove(item.Item1);\n return _list.Remove(item);\n }\n\n public void RemoveAt(int index)\n {\n if (index >= _list.Count) throw new IndexOutOfRangeException();\n var (n, p) = _list[index];\n _list.RemoveAt(index);\n _dict.Remove(n);\n }\n\n public bool ContainsKey(TKey key)\n {\n return _dict.ContainsKey(key);\n }\n\n public bool Remove(TKey key)\n {\n var value = _dict[key];\n var idx = _list.FindIndex(kv => kv.Item1.Equals(key));\n _list.RemoveAt(idx);\n return _dict.Remove(key);\n }\n\n public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)\n {\n return _dict.TryGetValue(key, out value);\n }\n\n public void Clear()\n {\n _dict.Clear();\n _list.Clear();\n }\n\n public bool Contains(KeyValuePair<TKey, TValue> item)\n {\n return _dict.ContainsKey(item.Key);\n }\n\n public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)\n {\n throw new NotImplementedException();\n }\n\n public bool Remove(KeyValuePair<TKey, TValue> item)\n {\n return _dict.Remove(item.Key);\n }\n\n public IEnumerator<(TKey, TValue)> GetEnumerator()\n {\n return _list.GetEnumerator();\n }\n\n IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()\n {\n throw new NotImplementedException();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return ((IEnumerable<KeyValuePair<TKey, TValue>>)this).GetEnumerator();\n }\n\n private List<(TKey, TValue)> _list = new List<(TKey, TValue)>();\n private Dictionary<TKey, TValue> _dict = new Dictionary<TKey, TValue>();\n }\n\n}\n" }, { "alpha_fraction": 0.5328227281570435, "alphanum_fraction": 0.5393872857093811, "avg_line_length": 25.882352828979492, "blob_id": "c89bd7df0a7c79fa3ba153c9a2839c0038cb76f6", "content_id": "1552dd0ff30fb7a65ed35f96daed0df9bebb9949", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 914, "license_type": "permissive", "max_line_length": 139, "num_lines": 34, "path": "/src/TorchVision/Invert.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class Invert : ITransform\n {\n internal Invert()\n {\n }\n\n public Tensor call(Tensor input)\n {\n return transforms.functional.invert(input);\n }\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Invert the image colors.\n /// </summary>\n /// <remarks>The code assumes that integer color values lie in the range [0,255], and floating point colors in [0,1[.</remarks>\n static public ITransform Invert()\n {\n return new Invert();\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5647902488708496, "alphanum_fraction": 0.5658523440361023, "avg_line_length": 44.37349319458008, "blob_id": "23e92a82c3dff027d7afcd2ac6b58afcd9498270", "content_id": "4d70a476467d52ebb6e0475b1cbd8bd0597abff5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3766, "license_type": "permissive", "max_line_length": 197, "num_lines": 83, "path": "/src/TorchSharp/NN/Normalization/GroupNorm.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n\n /// <summary>\n /// This class is used to represent a GroupNorm module.\n /// </summary>\n public sealed class GroupNorm : torch.nn.Module<Tensor, Tensor>\n {\n internal GroupNorm(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n if (tensor.Dimensions < 3) throw new ArgumentException($\"Invalid number of dimensions for GroupNorm argument: {tensor.Dimensions}\");\n var res = THSNN_GroupNorm_forward(handle.DangerousGetHandle(), tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public Parameter? bias {\n get {\n var res = THSNN_GroupNorm_bias(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n set {\n THSNN_GroupNorm_set_bias(handle, (value is null ? IntPtr.Zero : value.Handle));\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"bias\", value);\n }\n }\n\n public Parameter? weight {\n get {\n var res = THSNN_GroupNorm_weight(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n set {\n THSNN_GroupNorm_set_weight(handle, value is null ? IntPtr.Zero : value.Handle);\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"weight\", value);\n }\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies Group Normalization over a mini-batch of inputs as described in the paper Group Normalization\n /// </summary>\n /// <param name=\"num_groups\">Number of groups to separate the channels into</param>\n /// <param name=\"num_channels\">Number of channels expected in input</param>\n /// <param name=\"eps\">A value added to the denominator for numerical stability.</param>\n /// <param name=\"affine\">A boolean value that when set to true, this module has learnable per-channel affine parameters initialized to ones (for weights) and zeros (for biases).</param>\n /// <param name=\"device\">The desired device of the parameters and buffers in this module</param>\n /// <param name=\"dtype\">The desired floating point or complex dtype of the parameters and buffers in this module</param>\n /// <returns></returns>\n public static GroupNorm GroupNorm(long num_groups, long num_channels, double eps = 1e-05, bool affine = true, Device? device = null, ScalarType? dtype = null)\n {\n unsafe {\n var handle = THSNN_GroupNorm_ctor(num_groups, num_channels, eps, affine, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new GroupNorm(handle, boxedHandle).MoveModule<GroupNorm>(device, dtype);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.7562500238418579, "alphanum_fraction": 0.7604166865348816, "avg_line_length": 29, "blob_id": "b8432e578867293321999df53afcf2cf95228c71", "content_id": "e66492e11d57fa8ddbfa2a83c34692add348eb6d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 480, "license_type": "permissive", "max_line_length": 130, "num_lines": 16, "path": "/src/Native/LibTorchSharp/THSStorage.h", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#pragma once\n\n#include \"../Stdafx.h\"\n\n#include \"torch/torch.h\"\n\n#include \"Utils.h\"\n\nEXPORT_API(int64_t) THSTensor_storage_offset(const Tensor tensor);\n\nEXPORT_API(size_t) THSStorage_nbytes(const Tensor tensor);\n\nEXPORT_API(void) THSStorage_set_nbytes(const Tensor tensor, size_t nbytes);\n\nEXPORT_API(void*) THSStorage_data_ptr(const Tensor tensor);\n" }, { "alpha_fraction": 0.5736639499664307, "alphanum_fraction": 0.5775156617164612, "avg_line_length": 47.87058639526367, "blob_id": "1fc35aefb0dea60aeee88832873689c4f2df5020", "content_id": "364727dbdf396b7500c7840590c8e5da795593e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4158, "license_type": "permissive", "max_line_length": 206, "num_lines": 85, "path": "/src/TorchSharp/NN/TransformerEncoderLayer.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n public sealed class TransformerEncoderLayer : torch.nn.Module<Tensor, Tensor>, torch.nn.IModule<Tensor, Tensor, Tensor>, torch.nn.IModule<Tensor, Tensor, Tensor, Tensor>\n {\n internal TransformerEncoderLayer(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n /// <summary>\n /// Pass the input through the encoder layer.\n /// </summary>\n /// <param name=\"src\">The sequence to the encoder (required).</param>\n /// <param name=\"src_mask\">The additive mask for the src sequence (optional).</param>\n /// <param name=\"src_key_padding_mask\">The ByteTensor mask for src keys per batch (optional).</param>\n /// <returns></returns>\n public Tensor call(Tensor src, Tensor src_mask, Tensor src_key_padding_mask)\n {\n var res = THSNN_TransformerEncoderLayer_forward(handle,\n src.Handle,\n src_mask?.Handle ?? IntPtr.Zero,\n src_key_padding_mask?.Handle ?? IntPtr.Zero);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Pass the input through the encoder layer.\n /// </summary>\n /// <param name=\"src\">The sequence to the encoder (required).</param>\n /// <param name=\"src_mask\">The additive mask for the src sequence (optional).</param>\n public Tensor call(Tensor src, Tensor src_mask)\n {\n var res = THSNN_TransformerEncoderLayer_forward(handle,\n src.Handle,\n src_mask?.Handle ?? IntPtr.Zero,\n IntPtr.Zero);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Pass the input through the encoder layer.\n /// </summary>\n /// <param name=\"src\">The sequence to the encoder (required).</param>\n public override Tensor forward(Tensor src)\n {\n var res = THSNN_TransformerEncoderLayer_forward(handle,\n src.Handle,\n IntPtr.Zero,\n IntPtr.Zero);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// TransformerEncoderLayer is made up of self-attn and feedforward network. This standard encoder layer is based on the paper “Attention Is All You Need”.\n /// </summary>\n /// <param name=\"d_model\">The number of expected features in the input (required).</param>\n /// <param name=\"nhead\">The number of heads in the multiheadattention models (required).</param>\n /// <param name=\"dim_feedforward\">The dimension of the feedforward network model (default=2048).</param>\n /// <param name=\"dropout\">The dropout value (default=0.1).</param>\n /// <param name=\"activation\">The activation function of intermediate layer, relu or gelu (default=relu).</param>\n /// <returns></returns>\n public static TransformerEncoderLayer TransformerEncoderLayer(long d_model = 512, long nhead = 8, long dim_feedforward = 2048, double dropout = 0.1, Activations activation = nn.Activations.ReLU)\n {\n var res = THSNN_TransformerEncoderLayer_ctor(d_model, nhead, dim_feedforward, dropout, (long)activation, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new TransformerEncoderLayer(res, boxedHandle);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5447816252708435, "alphanum_fraction": 0.5481125116348267, "avg_line_length": 36.52777862548828, "blob_id": "23e2c9f7d2fcc7112170bb1b63178d78965b2887", "content_id": "de32e4dfb1d36409efb6d52a2fa27d5fbea94798", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2704, "license_type": "permissive", "max_line_length": 130, "num_lines": 72, "path": "/src/TorchSharp/NN/Activation/Softshrink.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a Softshrink module.\n /// </summary>\n public sealed class Softshrink : torch.nn.Module<Tensor, Tensor>\n {\n internal Softshrink(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_Softshrink_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public override string GetName()\n {\n return typeof(Softshrink).Name;\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Softshrink\n /// </summary>\n /// <param name=\"lambda\"> the λ value for the Softshrink formulation. Default: 0.5</param>\n /// <returns></returns>\n public static Softshrink Softshrink(double lambda = 0.5)\n {\n var handle = THSNN_Softshrink_ctor(lambda, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Softshrink(handle, boxedHandle);\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Softshrink\n /// </summary>\n /// <param name=\"x\">The input tensor</param>\n /// <param name=\"lambda\">The λ value for the Softshrink formulation. Default: 0.5</param>\n /// <returns></returns>\n public static Tensor Softshrink(Tensor x, double lambda = 0.5)\n {\n using (var m = nn.Softshrink(lambda)) {\n return m.call(x);\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5315040946006775, "alphanum_fraction": 0.5341463685035706, "avg_line_length": 59.74074172973633, "blob_id": "b1742b617d40d5500d58e118bf5211f862a7abc9", "content_id": "ab0b62cc5c3b9e1793a87c22b8feee0245871f8a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4920, "license_type": "permissive", "max_line_length": 188, "num_lines": 81, "path": "/src/TorchSharp/NN/Utils/RNNUtils.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static partial class nn\n {\n public static partial class utils\n {\n public static partial class rnn\n {\n /// <summary>\n /// Pack a padded sequences.\n /// </summary>\n /// <param name=\"input\">The padded input tensor</param>\n /// <param name=\"lengths\">The lengths of sequences</param>\n /// <param name=\"batch_first\">If true, the size of input tensor is (batch, seq, *), otherwise (seq, batch, *)</param>\n /// <param name=\"enforce_sorted\">if true, checks that the input contains sequences sorted by length in a decreasing order.</param>\n /// <returns></returns>\n public static PackedSequence pack_padded_sequence(torch.Tensor input, torch.Tensor lengths, bool batch_first = false, bool enforce_sorted = true)\n {\n var res = THSNN_pack_padded_sequence(input.Handle, lengths.Handle, batch_first, enforce_sorted);\n if (res.IsInvalid) { torch.CheckForErrors(); }\n return new PackedSequence(res);\n }\n\n /// <summary>\n /// Pad a packed batch of variable length sequences.\n /// </summary>\n /// <param name=\"sequence\">A packed batch</param>\n /// <param name=\"batch_first\">If true, the size of output tensor is (batch, seq, *), otherwise (seq, batch, *)</param>\n /// <param name=\"padding_value\">The values of padding.</param>\n /// <param name=\"total_length\">If not null, the output tensor is padded to the length of total_length.</param>\n /// <returns>The padded tensor</returns>\n public static (torch.Tensor, torch.Tensor) pad_packed_sequence(PackedSequence sequence, bool batch_first = false, double padding_value = 0.0, long? total_length = null)\n {\n IntPtr res1, res2;\n long total_length_arg = total_length.HasValue ? total_length.Value : -1;\n THSNN_pad_packed_sequence(sequence.Handle, batch_first, padding_value, total_length_arg, out res1, out res2);\n if (res1 == IntPtr.Zero || res2 == IntPtr.Zero) { torch.CheckForErrors(); }\n return (new torch.Tensor(res1), new torch.Tensor(res2));\n }\n\n /// <summary>\n /// Pad a list of variable length sequences.\n /// </summary>\n /// <param name=\"sequences\">A list of variable length sequences</param>\n /// <param name=\"batch_first\">If true, the size of output tensor is (batch, seq, *), otherwise (seq, batch, *)</param>\n /// <param name=\"padding_value\">The values of padding.</param>\n /// <returns>The padded tensor</returns>\n public static torch.Tensor pad_sequence(IEnumerable<torch.Tensor> sequences, bool batch_first = false, double padding_value = 0.0)\n {\n var sequences_arg = sequences.Select(p => p.Handle).ToArray();\n var res = THSNN_pad_sequence(sequences_arg, sequences_arg.Length, batch_first, padding_value);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new torch.Tensor(res);\n }\n\n /// <summary>\n /// Pack a list of variable length sequences.\n /// </summary>\n /// <param name=\"sequences\">A list of variable length sequences</param>\n /// <param name=\"enforce_sorted\">if true, checks that the input contains sequences sorted by length in a decreasing order.</param>\n /// <returns>The packed batch of variable length sequences</returns>\n public static PackedSequence pack_sequence(IEnumerable<torch.Tensor> sequences, bool enforce_sorted = true)\n {\n var sequences_arg = sequences.Select(p => p.Handle).ToArray();\n var res = THSNN_pack_sequence(sequences_arg, sequences_arg.Length, enforce_sorted);\n if (res.IsInvalid) { torch.CheckForErrors(); }\n return new PackedSequence(res);\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5518966913223267, "alphanum_fraction": 0.5646489262580872, "avg_line_length": 40.0264892578125, "blob_id": "a4eb103ad3b3af3002bd96b8b37b82e27c4e759b", "content_id": "c8b27c720c6e68d2110bc688f79f3674286a18fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6202, "license_type": "permissive", "max_line_length": 166, "num_lines": 151, "path": "/src/Examples/AdversarialExampleGeneration.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.IO;\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.utils.data;\n\nnamespace TorchSharp.Examples\n{\n /// <summary>\n /// FGSM Attack\n ///\n /// Based on : https://pytorch.org/tutorials/beginner/fgsm_tutorial.html\n /// </summary>\n /// <remarks>\n /// There are at least two interesting data sets to use with this example:\n ///\n /// 1. The classic MNIST set of 60000 images of handwritten digits.\n ///\n /// It is available at: http://yann.lecun.com/exdb/mnist/\n ///\n /// 2. The 'fashion-mnist' data set, which has the exact same file names and format as MNIST, but is a harder\n /// data set to train on. It's just as large as MNIST, and has the same 60/10 split of training and test\n /// data.\n /// It is available at: https://github.com/zalandoresearch/fashion-mnist/tree/master/data/fashion\n ///\n /// The example is based on the PyTorch tutorial, but the results from attacking the model are very different from\n /// what the tutorial article notes, at least on the machine where it was developed. There is an order-of-magnitude lower\n /// drop-off in accuracy in this version. That said, when running the PyTorch tutorial on the same machine, the\n /// accuracy trajectories are the same between .NET and Python. If the base convulutational model is trained\n /// using Python, and then used for the FGSM attack in both .NET and Python, the drop-off trajectories are extremenly\n /// close.\n /// </remarks>\n public class AdversarialExampleGeneration\n {\n#if NET472_OR_GREATER\n private readonly static string _dataLocation = NSPath.Join(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), \"..\", \"Downloads\", \"mnist\");\n#else\n private readonly static string _dataLocation = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), \"..\", \"Downloads\", \"mnist\");\n#endif // NET472_OR_GREATER\n\n private static int _epochs = 4;\n private static int _trainBatchSize = 64;\n private static int _testBatchSize = 128;\n\n internal static void Main(string[] args)\n {\n var cwd = Environment.CurrentDirectory;\n\n var dataset = args.Length > 0 ? args[0] : \"mnist\";\n var datasetPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n\n var _ = torch.random.manual_seed(1);\n\n //var device = torch.CPU;\n var device = torch.cuda.is_available() ? torch.CUDA : torch.CPU;\n Console.WriteLine($\"\\n Running AdversarialExampleGeneration on {device.type.ToString()}\\n\");\n Console.WriteLine($\"Dataset: {dataset}\");\n\n if (device.type == DeviceType.CUDA) {\n _trainBatchSize *= 4;\n _testBatchSize *= 4;\n _epochs *= 4;\n }\n\n MNIST.Model model = null;\n\n var normImage = torchvision.transforms.Normalize(new double[] {0.1307}, new double[] {0.3081});\n\n using (var test = torchvision.datasets.MNIST(datasetPath, false, true, normImage)) {\n\n var modelFile = dataset + \".model.bin\";\n\n if (!File.Exists(modelFile)) {\n // We need the model to be trained first, because we want to start with a trained model.\n Console.WriteLine(\n $\"\\n Running MNIST on {device.type.ToString()} in order to pre-train the model.\");\n\n model = new MNIST.Model(\"model\", device);\n\n using (var train = torchvision.datasets.MNIST(datasetPath, true, true, normImage)) {\n MNIST.TrainingLoop(dataset, (Device) device, model, train, test);\n }\n\n Console.WriteLine(\"Moving on to the Adversarial model.\\n\");\n\n } else {\n model = new MNIST.Model(\"model\", torch.CPU);\n model.load(modelFile);\n }\n\n model.to((Device) device);\n model.eval();\n }\n\n var epsilons = new double[] {0, 0.05, 0.1, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50};\n\n foreach (var ε in epsilons) {\n using (var test = torchvision.datasets.MNIST(datasetPath, false, true, normImage)) {\n var attacked = Test(model, torch.nn.NLLLoss(), ε, device, test, test.Count);\n Console.WriteLine($\"Epsilon: {ε:F2}, accuracy: {attacked:P2}\");\n }\n }\n }\n\n private static Tensor Attack(Tensor image, double ε, Tensor data_grad)\n {\n using (var sign = data_grad.sign()) {\n var perturbed = (image + ε * sign).clamp(0.0, 1.0);\n return perturbed;\n }\n }\n\n private static double Test(\n MNIST.Model model,\n Loss<Tensor, Tensor, Tensor> criterion,\n double ε,\n Device device,\n Dataset dataset,\n long size)\n {\n int correct = 0;\n\n using (var d = torch.NewDisposeScope()) {\n using var dataLoader = new DataLoader(dataset, _testBatchSize, device: device, shuffle: true);\n foreach (var dat in dataLoader) {\n var data = dat[\"data\"];\n var label = dat[\"label\"];\n data.requires_grad = true;\n\n using (var output = model.call(data))\n using (var loss = criterion.call(output, label)) {\n\n model.zero_grad();\n loss.backward();\n\n var perturbed = Attack(data, ε, data.grad());\n\n using (var final = model.call(perturbed)) {\n\n correct += final.argmax(1).eq(label).sum().ToInt32();\n }\n }\n\n d.DisposeEverything();\n }\n }\n\n return (double)correct / size;\n }\n }\n}\n" }, { "alpha_fraction": 0.5358197093009949, "alphanum_fraction": 0.5668997764587402, "avg_line_length": 34.26301193237305, "blob_id": "e6d663937a299ec49c8cb316187faab3b3e86c92", "content_id": "5cc6f832d31147c127b343056a1d48fd9a539ae6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12870, "license_type": "permissive", "max_line_length": 181, "num_lines": 365, "path": "/src/Native/LibTorchSharp/THSVision.cpp", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#include \"THSVision.h\"\n\n#include <torch/nn/init.h>\n\n// The image processing code was ported from the Python implmentation found in:\n//\n// https://github.com/pytorch/vision/blob/main/torchvision/transforms/functional_tensor.py\n\nvoid _rgb_to_hsv(at::Tensor& img, at::Tensor& h, at::Tensor& saturation, at::Tensor& value)\n{\n auto RGB = img.unbind(-3);\n auto r = RGB[0];\n auto g = RGB[1];\n auto b = RGB[2];\n\n auto maxc = std::get<0>(img.max(-3));\n auto minc = std::get<0>(img.min(-3));\n\n auto eqc = maxc == minc;\n auto cr = maxc - minc;\n\n auto options = at::TensorOptions()\n .dtype(maxc.dtype())\n .device(maxc.device())\n .requires_grad(maxc.requires_grad());\n\n auto ones = torch::ones_like(maxc, options);\n\n auto s = cr / torch::where(eqc, ones, maxc);\n auto cr_divisor = torch::where(eqc, ones, cr);\n\n auto rc = (maxc - r) / cr_divisor;\n auto gc = (maxc - g) / cr_divisor;\n auto bc = (maxc - b) / cr_divisor;\n\n auto hr = (maxc == r) * (bc - gc);\n auto hg = ((maxc == g) & (maxc != r)) * (2.0 + rc - bc);\n auto hb = ((maxc != g) & (maxc != r)) * (4.0 + gc - rc);\n\n h = (hr + hg + hb);\n h = torch::fmod((h / 6.0 + 1.0), 1.0);\n\n saturation = s;\n value = maxc;\n}\n\nvoid _hsv_to_rgb(at::Tensor& h, at::Tensor& s, at::Tensor& v, at::Tensor& img)\n{\n auto h6 = h * 6.0f;\n auto i = torch::floor(h6);\n auto f = h6 - i;\n i = i.to(at::ScalarType::Int) % 6;\n\n auto p = torch::clamp((v * (1.0f - s)), 0.0, 1.0);\n auto q = torch::clamp((v * (1.0 - s * f)), 0.0, 1.0);\n auto t = torch::clamp((v * (1.0 - s * (1.0 - f))), 0.0, 1.0);\n\n auto iunsq = i.unsqueeze(-3);\n\n auto mask = iunsq == torch::arange(6, at::TensorOptions(i.device())).view({ -1, 1, 1 });\n\n auto a1 = torch::stack({ v, q, p, p, t, v }, -3);\n auto a2 = torch::stack({ t, v, v, q, p, p }, -3);\n auto a3 = torch::stack({ p, p, t, v, v, q }, -3);\n auto a4 = torch::stack({ a1, a2, a3 }, -4);\n\n img = torch::einsum(\"...ijk,...xijk ->...xjk\", { mask.to(h.dtype()), a4 });\n}\n\nTensor THSVision_AdjustHue(const Tensor i, const double hue_factor)\n{\n try {\n torch_last_err = 0;\n\n auto img = *i;\n\n auto orig_dtype = img.scalar_type();\n\n if (!torch::isFloatingType(orig_dtype)) {\n img = img.to(c10::ScalarType::Float) / 255.0;\n }\n\n at::Tensor h;\n at::Tensor s;\n at::Tensor v;\n\n _rgb_to_hsv(img, h, s, v);\n\n h = (h + hue_factor) % 1.0;\n\n at::Tensor img_hue_adj;\n\n _hsv_to_rgb(h, s, v, img_hue_adj);\n\n if (!torch::isFloatingType(orig_dtype)) {\n img_hue_adj = (img_hue_adj * 255.0).to(orig_dtype);\n }\n\n return ResultTensor(img_hue_adj);\n }\n catch (const c10::Error e) {\n torch_last_err = strdup(e.what());\n }\n catch (const std::runtime_error e) {\n torch_last_err = strdup(e.what());\n }\n\n return nullptr;\n}\n\nTensor THSVision_GenerateAffineGrid(Tensor theta, const int64_t w, const int64_t h, const int64_t ow, const int64_t oh)\n{\n try {\n torch_last_err = 0;\n\n auto d = 0.5;\n\n auto thetaOptions = at::TensorOptions().dtype(theta->dtype()).device(theta->device());\n auto thetaDevice = at::TensorOptions().device(theta->device());\n\n auto base_grid = torch::empty({ 1, oh, ow, 3 }, thetaOptions);\n\n auto x_grid = torch::linspace(-ow * 0.5 + d, ow * 0.5 + d - 1, ow, thetaDevice);\n base_grid.index({ at::indexing::Ellipsis, 0 }).copy_(x_grid);\n\n auto y_grid = torch::linspace(-oh * 0.5 + d, oh * 0.5 + d - 1, oh, thetaDevice).unsqueeze_(-1);\n base_grid.index({ at::indexing::Ellipsis, 1 }).copy_(y_grid);\n base_grid.index({ at::indexing::Ellipsis, 2 }).fill_(1);\n\n auto rescaled_theta = theta->transpose(1, 2) / torch::tensor({ 0.5f * w, 0.5f * h }, thetaOptions);\n auto output_grid = base_grid.view({ 1, oh * ow, 3 }).bmm(rescaled_theta);\n\n return ResultTensor(output_grid.view({ 1, oh, ow, 2 }));\n }\n catch (const c10::Error e) {\n torch_last_err = strdup(e.what());\n }\n catch (const std::runtime_error e) {\n torch_last_err = strdup(e.what());\n }\n\n return nullptr;\n}\n\nTensor THSVision_ApplyGridTransform(Tensor i, Tensor g, const int8_t m, const float* fill, const int64_t fill_length)\n{\n try {\n torch_last_err = 0;\n\n auto img = *i;\n auto grid = *g;\n\n auto imgOptions = at::TensorOptions().dtype(img.dtype()).device(img.device());\n\n if (img.size(0) > 1) {\n grid = grid.expand({ img.size(0), grid.size(1), grid.size(2), grid.size(3) });\n }\n\n if (fill != nullptr) {\n auto dummy = torch::ones({ img.size(0), 1, img.size(2), img.size(3) }, imgOptions);\n img = torch::cat({ img, dummy }, 1);\n }\n\n const torch::nn::functional::GridSampleFuncOptions::mode_t mode =\n (m == 0)\n ? (torch::nn::functional::GridSampleFuncOptions::mode_t)torch::kNearest\n : (torch::nn::functional::GridSampleFuncOptions::mode_t)torch::kBilinear;\n auto sampleOpts = torch::nn::functional::GridSampleFuncOptions().padding_mode(torch::kZeros).mode(mode);\n sampleOpts.align_corners(false); // Supress warning. Default=false for grid_sample since libtorch 1.3.0\n\n img = torch::nn::functional::grid_sample(img, grid, sampleOpts);\n\n\n if (fill != nullptr) {\n\n auto COLON = at::indexing::Slice();\n\n auto mask = img.index({ COLON, at::indexing::Slice(-1, c10::nullopt), COLON, COLON });\n img = img.index({ COLON, at::indexing::Slice(c10::nullopt, -1), COLON, COLON });\n mask = mask.expand_as(img);\n\n auto fill_img = torch::tensor(at::ArrayRef<float>(fill, fill_length), imgOptions).view({ 1, fill_length, 1, 1 }).expand_as(img);\n\n if (m == 0) {\n mask = mask < 0.5;\n img[mask] = fill_img[mask];\n }\n else {\n img = img * mask + (-mask + 1.0) * fill_img;\n }\n }\n\n return ResultTensor(img);\n }\n catch (const c10::Error e) {\n torch_last_err = strdup(e.what());\n }\n catch (const std::runtime_error e) {\n torch_last_err = strdup(e.what());\n }\n\n return nullptr;\n}\n\nTensor THSVision_ScaleChannel(Tensor ic)\n{\n try {\n torch_last_err = 0;\n auto img_chan = *ic;\n\n auto hist = img_chan.is_cuda()\n ? torch::histc(img_chan.to(at::ScalarType::Float), 256, 0, 255)\n : torch::bincount(img_chan.view(-1), {}, 256);\n\n auto nonzero_hist = hist.index({ hist != 0 });\n\n auto step = torch::div(nonzero_hist.index({ at::indexing::Slice(c10::nullopt, -1) }).sum(), 255, \"floor\");\n auto count = step.count_nonzero();\n\n if (count.item<int>() == 0)\n {\n return ResultTensor(img_chan);\n }\n\n auto lut = torch::div(torch::cumsum(hist, 0) + torch::div(step, 2, \"floor\"), step, \"floor\");\n\n auto padOptions = torch::nn::functional::PadFuncOptions({ 1, 0 });\n lut = torch::nn::functional::pad(lut, padOptions).index({ at::indexing::Slice(c10::nullopt, -1) }).clamp(0, 255);\n\n return ResultTensor(lut.index({ img_chan.to(c10::ScalarType::Long) }).to(c10::ScalarType::Byte));\n }\n catch (const c10::Error e) {\n torch_last_err = strdup(e.what());\n }\n catch (const std::runtime_error e) {\n torch_last_err = strdup(e.what());\n }\n\n return nullptr;\n}\n\nvoid THSVision_ComputeOutputSize(const float* matrix, const int64_t matrix_length, const int64_t w, const int64_t h, int32_t* first, int32_t* second)\n{\n try {\n torch_last_err = 0;\n\n auto pts = torch::tensor({ -0.5f * w, -0.5f * h, 1.0f, -0.5f * w, 0.5f * h, 1.0f, 0.5f * w, 0.5f * h, 1.0f, 0.5f * w, -0.5f * h, 1.0f }).reshape({ 4,3 });\n auto theta = torch::tensor(c10::ArrayRef<float>(matrix, matrix_length), c10::TensorOptions().dtype(c10::ScalarType::Float)).view({ 2, 3 });\n auto new_pts = torch::matmul(pts, theta.t());\n\n auto min_vals = std::get<0>(new_pts.min(0));\n auto max_vals = std::get<0>(new_pts.max(0));\n\n min_vals += torch::tensor({ w * 0.5f, h * 0.5f });\n max_vals += torch::tensor({ w * 0.5f, h * 0.5f });\n\n float tol = 1e-4;\n auto cmax = torch::ceil((max_vals / tol).trunc_() * tol);\n auto cmin = torch::floor((min_vals / tol).trunc_() * tol);\n\n auto size = cmax - cmin;\n\n *first = size[0].item<int>();\n *second = size[1].item<int>();\n }\n catch (const c10::Error e) {\n torch_last_err = strdup(e.what());\n }\n catch (const std::runtime_error e) {\n torch_last_err = strdup(e.what());\n }\n}\n\nTensor THSVision_PerspectiveGrid(const float* c, const int64_t c_length, const int64_t ow, const int64_t oh, const int8_t scalar_type, const int device_type, const int device_index)\n{\n try {\n torch_last_err = 0;\n\n auto fullOptions = at::TensorOptions()\n .dtype(at::ScalarType(scalar_type))\n .device(c10::Device((c10::DeviceType)device_type, (c10::DeviceIndex)device_index));\n auto devOptions = at::TensorOptions()\n .device(c10::Device((c10::DeviceType)device_type, (c10::DeviceIndex)device_index));\n\n auto coeffs = c10::ArrayRef<float>(c, c_length);\n\n auto theta1 = torch::tensor({ coeffs[0], coeffs[1], coeffs[2], coeffs[3], coeffs[4], coeffs[5] }, fullOptions).view({ 1, 2, 3 });\n auto theta2 = torch::tensor({ coeffs[6], coeffs[7], 1.0f, coeffs[6], coeffs[7], 1.0f }, fullOptions).view({ 1, 2, 3 });\n\n auto d = 0.5f;\n auto base_grid = torch::empty({ 1, oh, ow, 3 }, fullOptions);\n auto x_grid = torch::linspace(d, ow * 1.0 + d - 1.0, ow, devOptions);\n base_grid.index({ at::indexing::Ellipsis, 0 }).copy_(x_grid);\n\n auto y_grid = torch::linspace(d, oh * 1.0 + d - 1.0, oh, devOptions).unsqueeze_(-1);\n base_grid.index({ at::indexing::Ellipsis, 1 }).copy_(y_grid);\n base_grid.index({ at::indexing::Ellipsis, 2 }).fill_(1);\n\n auto rescaled_theta1 = theta1.transpose(1, 2) / torch::tensor({ 0.5f * ow, 0.5f * oh }, fullOptions);\n\n auto output_grid1 = base_grid.view({ 1, oh * ow, 3 }).bmm(rescaled_theta1);\n auto output_grid2 = base_grid.view({ 1, oh * ow, 3 }).bmm(theta2.transpose(1, 2));\n auto output_grid = output_grid1 / output_grid2 - 1.0f;\n\n return ResultTensor(output_grid.view({ 1, oh, ow, 2 }));\n }\n catch (const c10::Error e) {\n torch_last_err = strdup(e.what());\n }\n catch (const std::runtime_error e) {\n torch_last_err = strdup(e.what());\n }\n\n return nullptr;\n}\n\n\nvoid THSVision_BRGA_RGB(const uint8_t* inputBytes, uint8_t* redBytes, uint8_t* greenBytes, uint8_t* blueBytes, int64_t inputChannelCount, int64_t imageSize)\n{\n const int inputBlue = 0, inputGreen = 1, inputRed = 2;\n\n for (int64_t i = 0, j = 0; i < imageSize; i += 1, j += inputChannelCount) {\n redBytes[i] = inputBytes[inputRed + j];\n greenBytes[i] = inputBytes[inputGreen + j];\n blueBytes[i] = inputBytes[inputBlue + j];\n }\n}\n\nvoid THSVision_BRGA_RGBA(const uint8_t* inputBytes, uint8_t* redBytes, uint8_t* greenBytes, uint8_t* blueBytes, uint8_t* alphaBytes, int64_t inputChannelCount, int64_t imageSize)\n{\n const int inputBlue = 0, inputGreen = 1, inputRed = 2, inputAlpha = 3;\n\n bool inputHasAlpha = inputChannelCount == 4;\n\n for (int64_t i = 0, j = 0; i < imageSize; i += 1, j += inputChannelCount) {\n redBytes[i] = inputBytes[inputRed + j];\n greenBytes[i] = inputBytes[inputGreen + j];\n blueBytes[i] = inputBytes[inputBlue + j];\n alphaBytes[i] = inputHasAlpha ? inputBytes[inputAlpha + j] : 255;\n }\n}\n\nvoid THSVision_RGB_BRGA(const uint8_t* inputBytes, uint8_t* outBytes, int64_t inputChannelCount, int64_t imageSize)\n{\n bool isgrey = inputChannelCount == 1;\n bool inputHasAlpha = inputChannelCount == 4;\n\n const int inputRed = 0, inputGreen = imageSize, inputBlue = imageSize * 2, inputAlpha = imageSize * 3;\n const int outputBlue = 0, outputGreen = 1, outputRed = 2, outputAlpha = 3;\n\n for (int64_t i = 0, j = 0; i < imageSize; i += 1, j += 4) {\n auto redPixel = inputBytes[inputRed + i];\n outBytes[outputRed + j] = redPixel;\n if (!isgrey) {\n outBytes[outputGreen + j] = inputBytes[inputGreen + i];\n outBytes[outputBlue + j] = inputBytes[inputBlue + i];\n }\n else {\n outBytes[outputGreen + j] = redPixel;\n outBytes[outputBlue + j] = redPixel;\n }\n outBytes[outputAlpha + j] = inputHasAlpha ? inputBytes[inputBlue + i] : 255;\n }\n}" }, { "alpha_fraction": 0.6443196535110474, "alphanum_fraction": 0.6474968194961548, "avg_line_length": 66.30237579345703, "blob_id": "d0c1b51618030e4f76406b624d88476cecde6a57", "content_id": "59afd1e9774c5a46a936ba5b99632ac6c6cd4b37", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 31168, "license_type": "permissive", "max_line_length": 269, "num_lines": 463, "path": "/src/TorchSharp/Tensor/torch.ComparisonOps.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Diagnostics.Contracts;\n\nnamespace TorchSharp\n{\n // https://pytorch.org/docs/stable/torch#comparison-ops\n public static partial class torch\n {\n // https://pytorch.org/docs/stable/generated/torch.allclose\n /// <summary>\n /// This function checks if all input and other lie within a certain distance from each other\n /// </summary>\n /// <param name=\"tensor\"></param>\n /// <param name=\"target\"></param>\n /// <param name=\"rtol\">Relative tolerance</param>\n /// <param name=\"atol\">Absolute tolerance</param>\n /// <param name=\"equal_nan\">If true, then two NaN s will be considered equal</param>\n [Pure]\n public static bool allclose(Tensor tensor, Tensor target, double rtol = 1e-05, double atol = 1e-08, bool equal_nan = false)\n => tensor.allclose(target, rtol, atol, equal_nan);\n\n // https://pytorch.org/docs/stable/generated/torch.argsort\n /// <summary>\n /// Returns the indices that sort a tensor along a given dimension in ascending order by value.\n /// </summary>\n [Pure]\n public static Tensor argsort(Tensor input, long dim = -1, bool descending = false)\n => input.argsort(dim, descending);\n\n // https://pytorch.org/docs/stable/generated/torch.eq\n /// <summary>\n /// Element-wise equal comparison\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]\n public static Tensor eq(Tensor left, Tensor right)\n => left.eq(right);\n\n // https://pytorch.org/docs/stable/generated/torch.equal\n [Pure]\n public static Tensor equal(Tensor tensor, Tensor target)\n => tensor.equal(target);\n\n // https://pytorch.org/docs/stable/generated/torch.ge\n /// <summary>\n /// Element-wise greater-than-or-equal comparison\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]\n public static Tensor ge(Tensor left, Tensor right)\n => left.ge(right);\n\n // https://pytorch.org/docs/stable/generated/torch.greater_equal\n [Pure]\n public static Tensor greater_equal(Tensor tensor, Tensor target)\n => tensor.greater_equal(target);\n\n // https://pytorch.org/docs/stable/generated/torch.gt\n /// <summary>\n /// Element-wise greater-than comparison\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]\n public static Tensor gt(Tensor left, Tensor right)\n => left.gt(right);\n\n // https://pytorch.org/docs/stable/generated/torch.greater\n [Pure]\n public static Tensor greater(Tensor tensor, Tensor target)\n => tensor.greater(target);\n\n // https://pytorch.org/docs/stable/generated/torch.isclose\n [Pure]\n public static Tensor isclose(Tensor tensor, Tensor other, double rtol = 1e-05, double atol = 1e-08, bool nanEqual = false)\n => tensor.isclose(other, rtol, atol, nanEqual);\n\n // https://pytorch.org/docs/stable/generated/torch.isfinite\n [Pure]\n public static Tensor isfinite(Tensor tensor)\n => tensor.isfinite();\n\n // https://pytorch.org/docs/stable/generated/torch.isin\n [Pure]\n public static Tensor isin(Tensor tensor, Tensor test_elements, bool assumeUnique = false, bool invert = false)\n => tensor.isin(test_elements, assumeUnique, invert);\n\n // https://pytorch.org/docs/stable/generated/torch.isinf\n [Pure]\n public static Tensor isinf(Tensor tensor)\n => tensor.isinf();\n\n // https://pytorch.org/docs/stable/generated/torch.isposinf\n [Pure]\n public static Tensor isposinf(Tensor tensor)\n => tensor.isposinf();\n\n // https://pytorch.org/docs/stable/generated/torch.isneginf\n [Pure]\n public static Tensor isneginf(Tensor tensor)\n => tensor.isneginf();\n\n // https://pytorch.org/docs/stable/generated/torch.isnan\n /// <summary>\n /// Returns a new tensor with boolean elements representing if each element of input is <value>NaN</value> or not.\n /// Complex values are considered <value>NaN</value> when either their real and/or imaginary part is <value>NaN</value>.\n /// </summary>\n /// <param name=\"input\">the input tensor</param>\n /// <returns>A boolean tensor that is <value>True</value> where input is <value>NaN</value> and <value>False</value> elsewhere</returns>\n [Pure]\n public static Tensor isnan(Tensor input)\n => input.isnan();\n\n // https://pytorch.org/docs/stable/generated/torch.isreal\n [Pure]\n public static Tensor isreal(Tensor tensor)\n => tensor.isreal();\n\n // https://pytorch.org/docs/stable/generated/torch.kthvalue\n /// <summary>\n /// Returns a named tuple (values, indices) where values is the k th smallest element of each row of the input tensor in the given dimension dim. And indices is the index location of each element found.\n /// If dim is not given, the last dimension of the input is chosen.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"k\">k for the k-th smallest element</param>\n /// <param name=\"dim\">The dimension to find the kth value along</param>\n /// <param name=\"keepdim\">Whether the output tensor has dim retained or not.</param>\n [Pure]\n public static (Tensor values, Tensor indices) kthvalue(Tensor input, long k, long? dim, bool keepdim = false)\n => input.kthvalue(k, dim, keepdim);\n\n // https://pytorch.org/docs/stable/generated/torch.le\n /// <summary>\n /// Element-wise less-than-or-equal comparison\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]\n public static Tensor le(Tensor left, Tensor right)\n => left.le(right);\n\n // https://pytorch.org/docs/stable/generated/torch.less_equal\n [Pure]\n public static Tensor less_equal(Tensor tensor, Tensor target)\n => tensor.less_equal(target);\n\n // https://pytorch.org/docs/stable/generated/torch.lt\n /// <summary>\n /// Element-wise less-than comparison\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]\n public static Tensor lt(Tensor left, Tensor right)\n => left.lt(right);\n\n // https://pytorch.org/docs/stable/generated/torch.less\n [Pure]\n public static Tensor less(Tensor tensor, Tensor target)\n => tensor.less(target);\n\n // https://pytorch.org/docs/stable/generated/torch.maximum\n /// <summary>\n /// Computes the element-wise maximum of input and other.\n /// </summary>\n /// <param name=\"input\">The first input tensor</param>\n /// <param name=\"other\">The second input tensor</param>\n [Pure]\n public static Tensor maximum(Tensor input, Tensor other)\n => input.maximum(other);\n\n // https://pytorch.org/docs/stable/generated/torch.minimum\n /// <summary>\n /// Computes the element-wise minimum of input and other.\n /// </summary>\n /// <param name=\"input\">The first input tensor</param>\n /// <param name=\"other\">The second input tensor</param>\n [Pure]\n public static Tensor minimum(Tensor input, Tensor other)\n => input.minimum(other);\n\n // https://pytorch.org/docs/stable/generated/torch.fmax\n /// <summary>\n /// Computes the element-wise maximum of input and other.\n ///\n /// This is like torch.maximum() except it handles NaNs differently: if exactly one of the two elements being compared is a NaN\n /// then the non-NaN element is taken as the maximum.\n /// Only if both elements are NaN is NaN propagated.\n /// </summary>\n /// <param name=\"input\">The first input tensor</param>\n /// <param name=\"other\">The second input tensor</param>\n [Pure]\n public static Tensor fmax(Tensor input, Tensor other)\n => input.fmax(other);\n\n // https://pytorch.org/docs/stable/generated/torch.fmin\n /// <summary>\n /// Computes the element-wise minimum of input and other.\n ///\n /// This is like torch.minimum() except it handles NaNs differently: if exactly one of the two elements being compared is a NaN\n /// then the non-NaN element is taken as the minimum.\n /// Only if both elements are NaN is NaN propagated.\n /// </summary>\n /// <param name=\"input\">The first input tensor</param>\n /// <param name=\"other\">The second input tensor</param>\n [Pure]\n public static Tensor fmin(Tensor input, Tensor other)\n => input.fmin(other);\n\n // https://pytorch.org/docs/stable/generated/torch.ne\n /// <summary>\n /// Element-wise not-equal comparison\n /// </summary>\n /// <param name=\"left\">The left-hand operand.</param>\n /// <param name=\"right\">The right-hand operand.</param>\n [Pure]\n public static Tensor ne(Tensor left, Tensor right)\n => left.ne(right);\n\n // https://pytorch.org/docs/stable/generated/torch.not_equal\n [Pure]\n public static Tensor not_equal(Tensor tensor, Tensor target)\n => tensor.not_equal(target);\n\n // https://pytorch.org/docs/stable/generated/torch.sort\n /// <summary>\n /// Sorts the elements of the input tensor along a given dimension in ascending order by value.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">The dimension to sort along. If dim is not given, the last dimension of the input is chosen.</param>\n /// <param name=\"descending\">Controls the sorting order (ascending or descending)</param>\n /// <param name=\"stable\">Makes the sorting routine stable, which guarantees that the order of equivalent elements is preserved.</param>\n /// <returns>A named tuple of (values, indices) is returned, where the values are the sorted values and indices are the indices of the elements in the original input tensor.</returns>\n [Pure]\n public static (Tensor values, Tensor indices) sort(Tensor input, long dim = -1, bool descending = false, bool stable = false)\n => input.sort(dim, descending, stable);\n\n // https://pytorch.org/docs/stable/generated/torch.searchsorted.html\n /// <summary>\n /// Find the indices from the innermost dimension of sorted_sequence such that, if the corresponding values in values were inserted before the indices,\n /// when sorted, the order of the corresponding innermost dimension within sorted_sequence would be preserved.\n /// Return a new tensor with the same size as values.\n /// If right is false, then the left boundary of sorted_sequence is closed. \n /// </summary>\n /// <param name=\"sorted_sequence\">N-D or 1-D tensor, containing monotonically increasing sequence on the innermost dimension unless sorter is provided, in which case the sequence does not need to be sorted</param>\n /// <param name=\"values\">N-D tensor or a Scalar containing the search value(s).</param>\n /// <param name=\"out_int32\">Indicates the output data type. torch.int32 if true, torch.int64 otherwise. Default value is false, i.e. default output data type is torch.int64.</param>\n /// <param name=\"right\">Indicates the output data type. torch.int32 if true, torch.int64 otherwise. Default value is false, i.e. default output data type is torch.int64.</param>\n /// <param name=\"sorter\">If provided, a tensor matching the shape of the unsorted sorted_sequence containing a sequence of indices that sort it in the ascending order on the innermost dimension</param>\n public static Tensor searchsorted(Tensor sorted_sequence, Tensor values, bool out_int32 = false, bool right = false, Tensor sorter = null)\n {\n var res = PInvoke.NativeMethods.THSTensor_searchsorted_t(sorted_sequence.Handle, values.Handle, out_int32, right, sorter is null ? IntPtr.Zero : sorter.Handle);\n if (res == IntPtr.Zero) CheckForErrors();\n return new Tensor(res);\n }\n\n // https://pytorch.org/docs/stable/generated/torch.searchsorted.html\n /// <summary>\n /// Find the indices from the innermost dimension of sorted_sequence such that, if the corresponding values in values were inserted before the indices,\n /// when sorted, the order of the corresponding innermost dimension within sorted_sequence would be preserved.\n /// Return a new tensor with the same size as values.\n /// If right is false, then the left boundary of sorted_sequence is closed. \n /// </summary>\n /// <param name=\"sorted_sequence\">N-D or 1-D tensor, containing monotonically increasing sequence on the innermost dimension unless sorter is provided, in which case the sequence does not need to be sorted</param>\n /// <param name=\"values\">A Scalar containing the search value.</param>\n /// <param name=\"out_int32\">Indicates the output data type. torch.int32 if true, torch.int64 otherwise. Default value is false, i.e. default output data type is torch.int64.</param>\n /// <param name=\"right\">Indicates the output data type. torch.int32 if true, torch.int64 otherwise. Default value is false, i.e. default output data type is torch.int64.</param>\n /// <param name=\"sorter\">If provided, a tensor matching the shape of the unsorted sorted_sequence containing a sequence of indices that sort it in the ascending order on the innermost dimension</param>\n public static Tensor searchsorted(Tensor sorted_sequence, Scalar values, bool out_int32, bool right, Tensor sorter)\n {\n var res = PInvoke.NativeMethods.THSTensor_searchsorted_s(sorted_sequence.Handle, values.Handle, out_int32, right, sorter is null ? IntPtr.Zero : sorter.Handle);\n if (res == IntPtr.Zero) CheckForErrors();\n return new Tensor(res);\n }\n\n /// https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/histograms.py#L679\n /// <summary>\n /// Computes a histogram of the values in a tensor.\n /// bins can be an integer or a 1D tensor.\n /// If bins is an int, it specifies the number of equal-width bins. By default, the lower and upper range of the bins is determined by the minimum and maximum elements of the input tensor. The range argument can be provided to specify a range for the bins.\n /// If bins is a 1D tensor, it specifies the sequence of bin edges including the rightmost edge. It should contain at least 2 elements and its elements should be increasing.\n /// </summary>\n /// <param name=\"input\"> the input tensor. </param>\n /// <param name=\"bins\"> int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, defines the sequence of bin edges including the rightmost edge. </param>\n /// <param name=\"range\"> Defines the range of the bins. </param>\n /// <param name=\"density\"> If False, the result will contain the count (or total weight) in each bin. If True, the result is the value of the probability density function over the bins, normalized such that the integral over the range of the bins is 1. </param>\n /// <returns></returns>\n public static (Tensor hist, Tensor bin_edges) histogram(Tensor input, HistogramBinSelector bins, (double min, double max)? range = null, bool density = false)\n => Utils.Histogram.histogram(input, bins, range, density);\n\n // https://pytorch.org/docs/stable/generated/torch.histogram.html\n /// <summary>\n /// Computes a histogram of the values in a tensor.\n /// bins can be an integer or a 1D tensor.\n /// If bins is an int, it specifies the number of equal-width bins. By default, the lower and upper range of the bins is determined by the minimum and maximum elements of the input tensor. The range argument can be provided to specify a range for the bins.\n /// If bins is a 1D tensor, it specifies the sequence of bin edges including the rightmost edge. It should contain at least 2 elements and its elements should be increasing.\n /// </summary>\n /// <param name=\"input\"> the input tensor. </param>\n /// <param name=\"bins\"> int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, defines the sequence of bin edges including the rightmost edge. </param>\n /// <param name=\"weight\"> If provided, weight should have the same shape as input. Each value in input contributes its associated weight towards its bin’s result. </param>\n /// <param name=\"density\"> If False, the result will contain the count (or total weight) in each bin. If True, the result is the value of the probability density function over the bins, normalized such that the integral over the range of the bins is 1. </param>\n /// <returns></returns>\n public static (Tensor hist, Tensor bin_edges) histogram(Tensor input, Tensor bins, Tensor weight = null, bool density = false)\n {\n var res = PInvoke.NativeMethods.THSTensor_histogram_t(input.Handle, bins.Handle, weight is null ? IntPtr.Zero : weight.Handle, density, out var r_bin_edges);\n if (res == IntPtr.Zero) CheckForErrors();\n if (r_bin_edges == IntPtr.Zero) CheckForErrors();\n return (new Tensor(res), new Tensor(r_bin_edges));\n }\n\n // https://pytorch.org/docs/stable/generated/torch.histogram.html\n /// <summary>\n /// Computes a histogram of the values in a tensor.\n /// bins can be an integer or a 1D tensor.\n /// If bins is an int, it specifies the number of equal-width bins. By default, the lower and upper range of the bins is determined by the minimum and maximum elements of the input tensor. The range argument can be provided to specify a range for the bins.\n /// If bins is a 1D tensor, it specifies the sequence of bin edges including the rightmost edge. It should contain at least 2 elements and its elements should be increasing.\n /// </summary>\n /// <param name=\"input\"> the input tensor. </param>\n /// <param name=\"bins\"> int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, defines the sequence of bin edges including the rightmost edge. </param>\n /// <param name=\"range\"> Defines the range of the bins. </param>\n /// <param name=\"weight\"> If provided, weight should have the same shape as input. Each value in input contributes its associated weight towards its bin’s result. </param>\n /// <param name=\"density\"> If False, the result will contain the count (or total weight) in each bin. If True, the result is the value of the probability density function over the bins, normalized such that the integral over the range of the bins is 1. </param>\n /// <returns></returns>\n public static (Tensor hist, Tensor bin_edges) histogram(Tensor input, long bins, (double min, double max)? range = null, Tensor weight = null, bool density = false)\n {\n double[] _range = Array.Empty<double>();\n if (range is not null)\n _range = new double[] { range.Value.min, range.Value.max };\n unsafe {\n fixed (double* prange = _range) {\n var res = _range == Array.Empty<double>()\n ? PInvoke.NativeMethods.THSTensor_histogram_i(input.Handle, bins, IntPtr.Zero, 0, weight is null ? IntPtr.Zero : weight.Handle, density, out var r_bin_edges)\n : PInvoke.NativeMethods.THSTensor_histogram_i(input.Handle, bins, (IntPtr)prange, _range.Length, weight is null ? IntPtr.Zero : weight.Handle, density, out r_bin_edges);\n if (res == IntPtr.Zero) CheckForErrors();\n if (r_bin_edges == IntPtr.Zero) CheckForErrors();\n return (new Tensor(res), new Tensor(r_bin_edges));\n }\n }\n }\n\n // https://pytorch.org/docs/stable/generated/torch.histogram.html\n /// <summary>\n /// Computes a histogram of the values in a tensor.\n /// bins can be an integer or a 1D tensor.\n /// If bins is an int, it specifies the number of equal-width bins. By default, the lower and upper range of the bins is determined by the minimum and maximum elements of the input tensor. The range argument can be provided to specify a range for the bins.\n /// If bins is a 1D tensor, it specifies the sequence of bin edges including the rightmost edge. It should contain at least 2 elements and its elements should be increasing.\n /// </summary>\n /// <param name=\"input\"> the input tensor. </param>\n /// <param name=\"bins\"> int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, defines the sequence of bin edges including the rightmost edge. </param>\n /// <param name=\"out_tensor\"> the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). </param>\n /// <returns></returns>\n public static (Tensor hist, Tensor bin_edges) histogram(Tensor input, Tensor bins, out (Tensor hist, Tensor bin_edges) out_tensor)\n => histogram(input, bins, null, false, out out_tensor);\n\n // https://pytorch.org/docs/stable/generated/torch.histogram.html\n /// <summary>\n /// Computes a histogram of the values in a tensor.\n /// bins can be an integer or a 1D tensor.\n /// If bins is an int, it specifies the number of equal-width bins. By default, the lower and upper range of the bins is determined by the minimum and maximum elements of the input tensor. The range argument can be provided to specify a range for the bins.\n /// If bins is a 1D tensor, it specifies the sequence of bin edges including the rightmost edge. It should contain at least 2 elements and its elements should be increasing.\n /// </summary>\n /// <param name=\"input\"> the input tensor. </param>\n /// <param name=\"bins\"> int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, defines the sequence of bin edges including the rightmost edge. </param>\n /// <param name=\"weight\"> If provided, weight should have the same shape as input. Each value in input contributes its associated weight towards its bin’s result. </param>\n /// <param name=\"density\"> If False, the result will contain the count (or total weight) in each bin. If True, the result is the value of the probability density function over the bins, normalized such that the integral over the range of the bins is 1. </param>\n /// <param name=\"out_tensor\"> the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). </param>\n /// <returns></returns>\n public static (Tensor hist, Tensor bin_edges) histogram(Tensor input, Tensor bins, Tensor weight, bool density, out (Tensor hist, Tensor bin_edges) out_tensor)\n {\n var res = PInvoke.NativeMethods.THSTensor_histogram_out_t(input.Handle, bins.Handle, weight is null ? IntPtr.Zero : weight.Handle, density, out var hist, out var bin_edges, out var r_bin_edges);\n if (res == IntPtr.Zero) CheckForErrors();\n if (hist == IntPtr.Zero) CheckForErrors();\n if (bin_edges == IntPtr.Zero) CheckForErrors();\n if (r_bin_edges == IntPtr.Zero) CheckForErrors();\n out_tensor = (new Tensor(hist), new Tensor(bin_edges));\n return (new Tensor(res), new Tensor(r_bin_edges));\n }\n\n // https://pytorch.org/docs/stable/generated/torch.histogram.html\n /// <summary>\n /// Computes a histogram of the values in a tensor.\n /// bins can be an integer or a 1D tensor.\n /// If bins is an int, it specifies the number of equal-width bins. By default, the lower and upper range of the bins is determined by the minimum and maximum elements of the input tensor. The range argument can be provided to specify a range for the bins.\n /// If bins is a 1D tensor, it specifies the sequence of bin edges including the rightmost edge. It should contain at least 2 elements and its elements should be increasing.\n /// </summary>\n /// <param name=\"input\"> the input tensor. </param>\n /// <param name=\"bins\"> int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, defines the sequence of bin edges including the rightmost edge. </param>\n /// <param name=\"out_tensor\"> the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). </param>\n /// <returns></returns>\n public static (Tensor hist, Tensor bin_edges) histogram(Tensor input, long bins, out (Tensor hist, Tensor bin_edges) out_tensor)\n => histogram(input, bins, null, null, false, out out_tensor);\n\n // https://pytorch.org/docs/stable/generated/torch.histogram.html\n /// <summary>\n /// Computes a histogram of the values in a tensor.\n /// bins can be an integer or a 1D tensor.\n /// If bins is an int, it specifies the number of equal-width bins. By default, the lower and upper range of the bins is determined by the minimum and maximum elements of the input tensor. The range argument can be provided to specify a range for the bins.\n /// If bins is a 1D tensor, it specifies the sequence of bin edges including the rightmost edge. It should contain at least 2 elements and its elements should be increasing.\n /// </summary>\n /// <param name=\"input\"> the input tensor. </param>\n /// <param name=\"bins\"> int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, defines the sequence of bin edges including the rightmost edge. </param>\n /// <param name=\"range\"> Defines the range of the bins. </param>\n /// <param name=\"out_tensor\"> the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). </param>\n /// <returns></returns>\n public static (Tensor hist, Tensor bin_edges) histogram(Tensor input, long bins, (double min, double max)? range, out (Tensor hist, Tensor bin_edges) out_tensor)\n => histogram(input, bins, range, null, false, out out_tensor);\n\n // https://pytorch.org/docs/stable/generated/torch.histogram.html\n /// <summary>\n /// Computes a histogram of the values in a tensor.\n /// bins can be an integer or a 1D tensor.\n /// If bins is an int, it specifies the number of equal-width bins. By default, the lower and upper range of the bins is determined by the minimum and maximum elements of the input tensor. The range argument can be provided to specify a range for the bins.\n /// If bins is a 1D tensor, it specifies the sequence of bin edges including the rightmost edge. It should contain at least 2 elements and its elements should be increasing.\n /// </summary>\n /// <param name=\"input\"> the input tensor. </param>\n /// <param name=\"bins\"> int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, defines the sequence of bin edges including the rightmost edge. </param>\n /// <param name=\"range\"> Defines the range of the bins. </param>\n /// <param name=\"weight\"> If provided, weight should have the same shape as input. Each value in input contributes its associated weight towards its bin’s result. </param>\n /// <param name=\"density\"> If False, the result will contain the count (or total weight) in each bin. If True, the result is the value of the probability density function over the bins, normalized such that the integral over the range of the bins is 1. </param>\n /// <param name=\"out_tensor\"> the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). </param>\n /// <returns></returns>\n public static (Tensor hist, Tensor bin_edges) histogram(Tensor input, long bins, (double min, double max)? range, Tensor weight, bool density, out (Tensor hist, Tensor bin_edges) out_tensor)\n {\n double[] _range = Array.Empty<double>();\n if (range is not null)\n _range = new double[] { range.Value.min, range.Value.max };\n unsafe {\n fixed (double* prange = _range) {\n var res = _range == Array.Empty<double>()\n ? PInvoke.NativeMethods.THSTensor_histogram_out_i(input.Handle, bins, IntPtr.Zero, 0, weight is null ? IntPtr.Zero : weight.Handle, density, out var hist, out var bin_edges, out var r_bin_edges)\n : PInvoke.NativeMethods.THSTensor_histogram_out_i(input.Handle, bins, (IntPtr)prange, _range.Length, weight is null ? IntPtr.Zero : weight.Handle, density, out hist, out bin_edges, out r_bin_edges);\n if (res == IntPtr.Zero) CheckForErrors();\n if (hist == IntPtr.Zero) CheckForErrors();\n if (bin_edges == IntPtr.Zero) CheckForErrors();\n if (r_bin_edges == IntPtr.Zero) CheckForErrors();\n out_tensor = (new Tensor(hist), new Tensor(bin_edges));\n return (new Tensor(res), new Tensor(r_bin_edges));\n }\n }\n }\n\n // https://pytorch.org/docs/stable/generated/torch.topk\n /// <summary>\n /// Returns the k largest elements of the given input tensor along a given dimension.\n /// </summary>\n /// <param name=\"tensor\">The input tensor</param>\n /// <param name=\"k\">The 'k' in 'top-k'.</param>\n /// <param name=\"dim\">The dimension to sort along. If dim is not given, the last dimension of the input is chosen.</param>\n /// <param name=\"largest\">Controls whether to return largest or smallest elements</param>\n /// <param name=\"sorted\">Controls whether to return the elements in sorted order</param>\n [Pure]\n public static (Tensor values, Tensor indices) topk(Tensor tensor, int k, int dim = -1, bool largest = true, bool sorted = true)\n => tensor.topk(k, dim, largest, sorted);\n\n // https://pytorch.org/docs/stable/generated/torch.msort\n [Pure]\n public static Tensor msort(Tensor tensor)\n => tensor.msort();\n }\n}" }, { "alpha_fraction": 0.5837081670761108, "alphanum_fraction": 0.5842078924179077, "avg_line_length": 34.73214340209961, "blob_id": "c728f54ec0fb3877f8269e9da8af53a74c46ad81", "content_id": "302627c388fb3bda0e1f24f42000811a79a76843", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2001, "license_type": "permissive", "max_line_length": 130, "num_lines": 56, "path": "/src/TorchSharp/NN/Activation/LogSoftMax.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a log softmax module.\n /// </summary>\n public sealed class LogSoftmax : torch.nn.Module<Tensor, Tensor>\n {\n internal LogSoftmax(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_LogSoftmax_forward(handle, tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n // Rather than spending cycles only to discover that this module has neither\n // parameters nor buffers, just shortcut the move completely.\n protected internal override nn.Module _to(Device device, ScalarType dtype) => this;\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1) => this;\n protected internal override nn.Module _to(ScalarType dtype) => this;\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n public static LogSoftmax LogSoftmax(long dim)\n {\n var handle = THSNN_LogSoftmax_ctor(dim, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new LogSoftmax(handle, boxedHandle);\n }\n\n public static partial class functional\n {\n public static Tensor log_softmax(Tensor x, long dim)\n {\n return torch.special.log_softmax(x, dim);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6044392585754395, "alphanum_fraction": 0.6081775426864624, "avg_line_length": 54.584415435791016, "blob_id": "4f9e7386da2dbe971c441f0bc68f11b548e2bad4", "content_id": "6b8cfd62e6b86a6738a3683f091c86bd0928064d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4284, "license_type": "permissive", "max_line_length": 206, "num_lines": 77, "path": "/src/TorchSharp/NN/TransformerDecoderLayer.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n public sealed class TransformerDecoderLayer : torch.nn.Module<Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor>, torch.nn.IModule<Tensor, Tensor, Tensor>\n {\n internal TransformerDecoderLayer(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { }\n\n /// <summary>\n /// Pass the inputs (and mask) through the decoder layer.\n /// </summary>\n /// <param name=\"tgt\">The sequence to the decoder layer (required).</param>\n /// <param name=\"memory\">The sequence from the last layer of the encoder (required).</param>\n /// <param name=\"tgt_mask\">The mask for the tgt sequence (optional).</param>\n /// <param name=\"memory_mask\">The mask for the memory sequence (optional).</param>\n /// <param name=\"tgt_key_padding_mask\">The mask for the tgt keys per batch (optional).</param>\n /// <param name=\"memory_key_padding_mask\">The mask for the memory keys per batch (optional).</param>\n /// <returns></returns>\n public override Tensor forward(Tensor tgt, Tensor memory, Tensor tgt_mask, Tensor memory_mask, Tensor tgt_key_padding_mask, Tensor memory_key_padding_mask)\n {\n var res = THSNN_TransformerDecoderLayer_forward(handle,\n tgt.Handle,\n memory.Handle,\n tgt_mask?.Handle ?? IntPtr.Zero,\n memory_mask?.Handle ?? IntPtr.Zero,\n tgt_key_padding_mask?.Handle ?? IntPtr.Zero,\n memory_key_padding_mask?.Handle ?? IntPtr.Zero);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public new Tensor call(Tensor tgt, Tensor memory, Tensor tgt_mask, Tensor memory_mask = null, Tensor tgt_key_padding_mask = null, Tensor memory_key_padding_mask = null)\n {\n return base.call(tgt, memory, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask);\n }\n\n /// <summary>\n /// Pass the inputs (and mask) through the decoder layer.\n /// </summary>\n /// <param name=\"tgt\">The sequence to the decoder layer (required).</param>\n /// <param name=\"memory\">The sequence from the last layer of the encoder (required).</param>\n public Tensor call(Tensor tgt, Tensor memory)\n {\n return base.call(tgt, memory, null, null, null, null);\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. This standard decoder layer is based on the paper “Attention Is All You Need”.\n /// </summary>\n /// <param name=\"d_model\">The number of expected features in the input (required).</param>\n /// <param name=\"nhead\">The number of heads in the multiheadattention models (required).</param>\n /// <param name=\"dim_feedforward\">The dimension of the feedforward network model (default=2048).</param>\n /// <param name=\"dropout\">The dropout value (default=0.1).</param>\n /// <param name=\"activation\">The activation function of intermediate layer, relu or gelu (default=relu).</param>\n /// <returns></returns>\n public static TransformerDecoderLayer TransformerDecoderLayer(long d_model = 512, long nhead = 8, long dim_feedforward = 2048, double dropout = 0.1, Activations activation = nn.Activations.ReLU)\n {\n var res = THSNN_TransformerDecoderLayer_ctor(d_model, nhead, dim_feedforward, dropout, (long)activation, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new TransformerDecoderLayer(res, boxedHandle);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5543248653411865, "alphanum_fraction": 0.5543248653411865, "avg_line_length": 36.939998626708984, "blob_id": "eaa31d5e10d4d83daea675f86f6e4f75e6f15f7e", "content_id": "7cd5acc25193dcf0c4050bc89f3743c87e786671", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1896, "license_type": "permissive", "max_line_length": 130, "num_lines": 50, "path": "/src/TorchVision/Erase.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\n\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class Erase : ITransform\n {\n internal Erase(int top, int left, int height, int width, Tensor value, bool inplace = false)\n {\n this.top = top;\n this.left = left;\n this.height = height;\n this.width = width;\n this.inplace = inplace;\n this.value = value;\n }\n\n public Tensor call(Tensor img)\n {\n return transforms.functional.erase(img, top, left, height, width, value, inplace);\n }\n\n private int top, left, height, width;\n private Tensor value;\n private bool inplace;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Erase a region of an image tensor with given value. \n /// </summary>\n /// <param name=\"top\">Vertical component of the top left corner of the erased region.</param>\n /// <param name=\"left\">Horizontal component of the top left corner of the erased region.</param>\n /// <param name=\"height\">The height of the erased region.</param>\n /// <param name=\"width\">The width of the erased region.</param>\n /// <param name=\"value\">Erasing value.</param>\n /// <param name=\"inplace\">For in-place operations.</param>\n /// <returns></returns>\n static public ITransform Erase(int top, int left, int height, int width, Tensor value, bool inplace = false)\n {\n return new Erase(top, left, height, width, value, inplace);\n }\n }\n }\n}" }, { "alpha_fraction": 0.4808405339717865, "alphanum_fraction": 0.48207664489746094, "avg_line_length": 34.9555549621582, "blob_id": "3913362de13983495366efb8c1050080ea023826", "content_id": "d99125ef8da7aa736c4f2826127a2d17fceab23a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1618, "license_type": "permissive", "max_line_length": 130, "num_lines": 45, "path": "/src/TorchAudio/NoBackend.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\n\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n public static partial class backend\n {\n public class NoBackend : AudioBackend\n {\n public override (torch.Tensor, int) load(\n string filepath,\n long frame_offset = 0,\n long num_frames = -1,\n bool normalize = true,\n bool channels_first = true,\n AudioFormat? format = null)\n {\n throw new InvalidOperationException(\"No audio I/O backend is available.\");\n }\n\n public override void save(\n string filepath,\n torch.Tensor src,\n int sample_rate,\n bool channels_first = true,\n float? compression = null,\n AudioFormat? format = null,\n AudioEncoding? encoding = null,\n int? bits_per_sample = null)\n {\n throw new InvalidOperationException(\"No audio I/O backend is available.\");\n }\n\n public override AudioMetaData info(\n string filepath,\n AudioFormat? format = null)\n {\n throw new InvalidOperationException(\"No audio I/O backend is available.\");\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.45195272564888, "alphanum_fraction": 0.46574169397354126, "avg_line_length": 42.40520477294922, "blob_id": "2fb4839b32ed57d6b88412a95742aa3a1749b0c6", "content_id": "1ae32898d1f0a52412218330ad8151bba7721a72", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 11676, "license_type": "permissive", "max_line_length": 181, "num_lines": 269, "path": "/src/TorchVision/models/MobileNetV2.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchvision,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/vision/blob/a4f53308b2d0f1aa9191686e326f45c26053f686/torchvision/models/mobilenetv2.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/vision/blob/main/LICENSE\n//\n\nusing System;\nusing System.Collections.Generic;\n\nusing static TorchSharp.torch;\nusing static TorchSharp.torchvision;\nusing static TorchSharp.torchvision.models._utils;\n\n#nullable enable\nnamespace TorchSharp\n{\n namespace Modules\n {\n /// <summary>\n /// MobileNet V2 main class\n /// </summary>\n public class MobileNetV2 : nn.Module<Tensor, Tensor>\n {\n private class InvertedResidual : nn.Module<Tensor, Tensor>\n {\n private readonly bool _is_cn;\n private readonly nn.Module<Tensor, Tensor> conv;\n private readonly long out_channels;\n private readonly long stride;\n private readonly bool use_res_connect;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n conv.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public InvertedResidual(\n string name,\n long inp,\n long oup,\n long stride,\n double expand_ratio,\n Func<long, nn.Module<Tensor, Tensor>>? norm_layer = null) : base(name)\n {\n this.stride = stride;\n if (stride != 1 && stride != 2) {\n throw new ArgumentOutOfRangeException($\"stride should be 1 or 2 insted of {stride}\");\n }\n\n if (norm_layer == null) {\n norm_layer = (features) => nn.BatchNorm2d(features);\n }\n\n var hidden_dim = (long)Math.Round(inp * expand_ratio);\n this.use_res_connect = this.stride == 1 && inp == oup;\n\n var layers = new List<nn.Module<Tensor, Tensor>>();\n if (expand_ratio != 1) {\n // pw\n layers.Add(\n ops.Conv2dNormActivation(\n inp,\n hidden_dim,\n kernel_size: 1,\n norm_layer: norm_layer,\n activation_layer: (inplace) => nn.ReLU6(inplace)));\n }\n layers.AddRange(new List<nn.Module<Tensor, Tensor>> {\n // dw\n ops.Conv2dNormActivation(\n hidden_dim,\n hidden_dim,\n stride: stride,\n groups: hidden_dim,\n norm_layer: norm_layer,\n activation_layer: (inplace) => nn.ReLU6(inplace)),\n // pw-linear\n nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias: false),\n norm_layer(oup)\n });\n this.conv = nn.Sequential(layers);\n this.out_channels = oup;\n this._is_cn = stride > 1;\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor x)\n {\n if (this.use_res_connect) {\n return x + this.conv.call(x);\n } else {\n return this.conv.call(x);\n }\n }\n }\n\n private readonly nn.Module<Tensor, Tensor> classifier;\n private readonly nn.Module<Tensor, Tensor> features;\n private readonly long last_channel;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n classifier.Dispose();\n features.Dispose();\n }\n base.Dispose(disposing);\n }\n\n internal MobileNetV2(\n string name,\n long num_classes = 1000,\n double width_mult = 1.0,\n long[][]? inverted_residual_setting = null,\n long round_nearest = 8,\n Func<long, long, long, long, Func<long, nn.Module<Tensor, Tensor>>, nn.Module<Tensor, Tensor>>? block = null,\n Func<long, nn.Module<Tensor, Tensor>>? norm_layer = null,\n double dropout = 0.2) : base(name)\n {\n if (block == null) {\n block = (input_channel, output_channel, stride, t, norm_layer) => new InvertedResidual(\"InvertedResidual\", input_channel, output_channel, stride, t, norm_layer);\n }\n\n if (norm_layer == null) {\n norm_layer = (features) => nn.BatchNorm2d(features);\n }\n\n long input_channel = 32;\n long last_channel = 1280;\n\n if (inverted_residual_setting == null) {\n inverted_residual_setting = new long[][] {\n // t, c, n, s\n new long[] { 1, 16, 1, 1 },\n new long[] { 6, 24, 2, 2 },\n new long[] { 6, 32, 3, 2 },\n new long[] { 6, 64, 4, 2 },\n new long[] { 6, 96, 3, 1 },\n new long[] { 6, 160, 3, 2 },\n new long[] { 6, 320, 1, 1 }\n };\n }\n\n // only check the first element, assuming user knows t,c,n,s are required\n if (inverted_residual_setting.Length == 0 || inverted_residual_setting[0].Length != 4) {\n throw new ArgumentException($\"inverted_residual_setting should be non-empty or a 4-element list, got {inverted_residual_setting}\");\n }\n\n // building first layer\n input_channel = _make_divisible(input_channel * width_mult, round_nearest);\n this.last_channel = _make_divisible(last_channel * Math.Max(1.0, width_mult), round_nearest);\n var features = new List<nn.Module<Tensor, Tensor>> {\n ops.Conv2dNormActivation(3, input_channel, stride: 2, norm_layer: norm_layer, activation_layer: (inplace) => nn.ReLU6(inplace))\n };\n // building inverted residual blocks\n foreach (var x in inverted_residual_setting) {\n long t = x[0];\n long c = x[1];\n long n = x[2];\n long s = x[3];\n var output_channel = _make_divisible(c * width_mult, round_nearest);\n for (var i = 0; i < n; i++) {\n var stride = i == 0 ? s : 1;\n features.Add(block(input_channel, output_channel, stride, t, norm_layer));\n input_channel = output_channel;\n }\n }\n // building last several layers\n features.Add(\n ops.Conv2dNormActivation(\n input_channel,\n this.last_channel,\n kernel_size: 1,\n norm_layer: norm_layer,\n activation_layer: (inplace) => nn.ReLU6(inplace)));\n // make it nn.Sequential\n this.features = nn.Sequential(features);\n\n // building classifier\n this.classifier = nn.Sequential(\n nn.Dropout(p: dropout),\n nn.Linear(this.last_channel, num_classes));\n\n RegisterComponents();\n\n // weight initialization\n foreach (var (_, m) in this.named_modules()) {\n if (m is Modules.Conv2d) {\n var conv = (Modules.Conv2d)m;\n nn.init.kaiming_normal_(conv.weight, mode: nn.init.FanInOut.FanOut);\n if (conv.bias is not null) {\n nn.init.zeros_(conv.bias);\n }\n } else if (m is Modules.BatchNorm2d) {\n var norm = (Modules.BatchNorm2d)m;\n nn.init.ones_(norm.weight);\n nn.init.zeros_(norm.bias);\n } else if (m is Modules.GroupNorm) {\n var norm = (Modules.GroupNorm)m;\n nn.init.ones_(norm.weight);\n nn.init.zeros_(norm.bias);\n } else if (m is Modules.Linear) {\n var linear = (Modules.Linear)m;\n nn.init.normal_(linear.weight, 0, 0.01);\n nn.init.zeros_(linear.bias);\n }\n }\n }\n\n public override Tensor forward(Tensor x)\n {\n x = this.features.call(x);\n // Cannot use \"squeeze\" as batch-size can be 1\n x = nn.functional.adaptive_avg_pool2d(x, (1, 1));\n x = torch.flatten(x, 1);\n x = this.classifier.call(x);\n return x;\n }\n }\n }\n\n public static partial class torchvision\n {\n public static partial class models\n {\n /// <summary>\n /// MobileNetV2 architecture from the `MobileNetV2: Inverted Residuals and Linear\n /// Bottlenecks https://arxiv.org/abs/1801.04381 paper.\n /// </summary>\n /// <param name=\"num_classes\">Number of classes</param>\n /// <param name=\"width_mult\">Width multiplier - adjusts number of channels in each layer by this amount</param>\n /// <param name=\"inverted_residual_setting\">Network structure</param>\n /// <param name=\"round_nearest\">Round the number of channels in each layer to be a multiple of this number\n /// Set to 1 to turn off rounding</param>\n /// <param name=\"block\">Module specifying inverted residual building block for mobilenet</param>\n /// <param name=\"norm_layer\">Module specifying the normalization layer to use</param>\n /// <param name=\"dropout\">The droupout probability</param>\n /// <returns></returns>\n public static Modules.MobileNetV2 mobilenet_v2(\n long num_classes = 1000,\n double width_mult = 1.0,\n long[][]? inverted_residual_setting = null,\n long round_nearest = 8,\n Func<long, long, long, long, Func<long, nn.Module<Tensor, Tensor>>, nn.Module<Tensor, Tensor>>? block = null,\n Func<long, nn.Module<Tensor, Tensor>>? norm_layer = null,\n double dropout = 0.2)\n {\n return new Modules.MobileNetV2(\n \"MobileNetV2\",\n num_classes,\n width_mult,\n inverted_residual_setting,\n round_nearest,\n block,\n norm_layer,\n dropout);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6534457206726074, "alphanum_fraction": 0.6534457206726074, "avg_line_length": 41.9361686706543, "blob_id": "e731a564d65bc7ce149081b7ac58d6e589b2509d", "content_id": "0b97fd47ada3d048797cdc7dd5508b37858df055", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2017, "license_type": "permissive", "max_line_length": 130, "num_lines": 47, "path": "/src/TorchSharp/Tensor/torch.LocallyDisablingGradientComputation.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Diagnostics.Contracts;\n\nnamespace TorchSharp\n{\n // https://pytorch.org/docs/stable/torch#locally-disabling-gradient-computation\n public static partial class torch\n {\n // https://pytorch.org/docs/stable/generated/torch.no_grad\n /// <summary>\n /// Context-manager that disables gradient calculation.\n /// </summary>\n /// <returns></returns>\n public static IDisposable no_grad() => new AutoGradMode(false);\n\n // https://pytorch.org/docs/stable/generated/torch.enable_grad\n /// <summary>\n /// Context-manager that enables gradient calculation.\n /// </summary>\n /// <returns></returns>\n public static IDisposable enable_grad(bool enabled = true) => new AutoGradMode(enabled);\n\n // https://pytorch.org/docs/stable/generated/torch.set_grad_enabled\n /// <summary>\n /// Context-manager that sets gradient calculation to on or off.\n /// </summary>\n /// <returns></returns>\n public static IDisposable set_grad_enabled(bool mode = true) => new AutoGradMode(mode);\n\n // https://pytorch.org/docs/stable/generated/torch.is_grad_enabled\n /// <summary>\n /// Returns true if grad mode is currently enabled.\n /// </summary>\n /// <returns></returns>\n [Pure]public static bool is_grad_enabled() => AutoGradMode.IsEnabled;\n\n // https://pytorch.org/docs/stable/generated/torch.inference_mode\n [Obsolete(\"not implemented\", true)]\n public static IDisposable inference_mode(bool mode = true) => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.is_inference_mode_enabled\n [Obsolete(\"not implemented\", true)]\n [Pure]public static bool is_inference_mode_enabled() => throw new NotImplementedException();\n }\n}" }, { "alpha_fraction": 0.6219512224197388, "alphanum_fraction": 0.6219512224197388, "avg_line_length": 21.454545974731445, "blob_id": "80bc65f1f2e4ec01a30f0fdd78bc63b448f88e04", "content_id": "f877827cb8faa19798a19dce0bf198099cf7f3d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 248, "license_type": "permissive", "max_line_length": 131, "num_lines": 11, "path": "/src/TorchSharp/Tensor/Enums/Reduce.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nnamespace TorchSharp\n{\n public enum Reduce\n {\n prod,\n mean,\n amax,\n amin\n }\n}" }, { "alpha_fraction": 0.5455530285835266, "alphanum_fraction": 0.5517278909683228, "avg_line_length": 51.15254211425781, "blob_id": "c2f67612ef6869c1a0d67fb84f5ff6725a2bf673", "content_id": "a6654ccc042cc19923f2a148fa4d09b4ffd1ec99", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9231, "license_type": "permissive", "max_line_length": 280, "num_lines": 177, "path": "/src/TorchSharp/NN/Convolution/Conv1D.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using Modules;\n\n public enum PaddingModes\n {\n Zeros = 0,\n Reflect = 1,\n Replicate = 2,\n Circular = 3,\n Constant = 4,\n }\n\n public enum Padding\n {\n Valid = 0,\n Same = 1\n }\n\n namespace Modules\n {\n public abstract class Convolution : torch.nn.Module<Tensor, Tensor>\n {\n protected Convolution(IntPtr handle, IntPtr boxedHandle, long input_channels) : base(handle, boxedHandle)\n {\n this.input_channels = input_channels;\n }\n\n protected bool ValidateShape(Tensor input, long dimensions)\n {\n var shape = input.shape;\n var ndim = shape.LongLength;\n\n return (ndim == dimensions+2) && (input.shape[1] == input_channels) || // Batched: N + C + dims\n (ndim == dimensions+1 && input.shape[0] == input_channels); // Unbathced: C + dims\n\n }\n\n protected long input_channels;\n }\n\n public sealed class Conv1d : Convolution\n {\n internal Conv1d(IntPtr handle, IntPtr boxedHandle, long input_channels) : base(handle, boxedHandle, input_channels) { }\n\n public override Tensor forward(Tensor input)\n {\n if (ValidateShape(input, 1)) {\n var res = THSNN_Conv1d_forward(handle, input.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n throw new ArgumentException($\"Expected 2D (unbatched) or 3D (batched) input with {input_channels} channels to Conv1d.\");\n }\n\n public Parameter? bias {\n get {\n var res = THSNN_Conv1d_bias(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return ((res == IntPtr.Zero) ? null : new Parameter(res));\n }\n set {\n THSNN_Conv1d_set_bias(handle, (value is null ? IntPtr.Zero : value.Handle));\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"bias\", value);\n }\n }\n public Parameter? weight {\n get {\n var res = THSNN_Conv1d_weight(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n set {\n THSNN_Conv1d_set_weight(handle, value is null ? IntPtr.Zero : value.Handle);\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"weight\", value);\n }\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies a 1D convolution over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"inputChannel\">Number of channels in the input image</param>\n /// <param name=\"outputChannel\">Number of channels produced by the convolution</param>\n /// <param name=\"kernelSize\">Size of the convolving kernel</param>\n /// <param name=\"stride\">Stride of the convolution. Default: 1</param>\n /// <param name=\"padding\">Zero-padding added to both sides of the input. Default: 0</param>\n /// <param name=\"dilation\">Spacing between kernel elements. Default: 1</param>\n /// <param name=\"paddingMode\">'zeros', 'reflect', 'replicate' or 'circular'. Default: 'zeros'</param>\n /// <param name=\"groups\">Number of blocked connections from input channels to output channels. Default: 1</param>\n /// <param name=\"bias\">If true, adds a learnable bias to the output. Default: true</param>\n /// <param name=\"device\">The desired device of the parameters and buffers in this module</param>\n /// <param name=\"dtype\">The desired floating point or complex dtype of the parameters and buffers in this module</param>\n /// <returns>Tensor of shape (N,C_out,L_out)</returns>\n public static Conv1d Conv1d(long inputChannel, long outputChannel, long kernelSize, long stride = 1, long padding = 0, long dilation = 1, PaddingModes paddingMode = PaddingModes.Zeros, long groups = 1, bool bias = true, Device? device = null, ScalarType? dtype = null)\n {\n var res = THSNN_Conv1d_ctor(inputChannel, outputChannel, kernelSize, stride, padding, dilation, (long)paddingMode, groups, bias, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Conv1d(res, boxedHandle, inputChannel).MoveModule<Conv1d>(device, dtype);\n }\n\n /// <summary>\n /// Applies a 1D convolution over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"inputChannel\">Number of channels in the input image</param>\n /// <param name=\"outputChannel\">Number of channels produced by the convolution</param>\n /// <param name=\"kernelSize\">Size of the convolving kernel</param>\n /// <param name=\"stride\">Stride of the convolution. Default: 1</param>\n /// <param name=\"padding\">Zero-padding added to both sides of the input. padding=Valid is the same as no padding. padding=Same pads the input so the output has the shape as the input. </param>\n /// <param name=\"dilation\">Spacing between kernel elements. Default: 1</param>\n /// <param name=\"paddingMode\">'zeros', 'reflect', 'replicate' or 'circular'. Default: 'zeros'</param>\n /// <param name=\"groups\">Number of blocked connections from input channels to output channels. Default: 1</param>\n /// <param name=\"bias\">If true, adds a learnable bias to the output. Default: true</param>\n /// <param name=\"device\">The desired device of the parameters and buffers in this module</param>\n /// <param name=\"dtype\">The desired floating point or complex dtype of the parameters and buffers in this module</param>\n /// <returns>Tensor of shape (N,C_out,L_out)</returns>\n public static Conv1d Conv1d(long inputChannel, long outputChannel, long kernelSize, Padding padding, long stride = 1, long dilation = 1, PaddingModes paddingMode = PaddingModes.Zeros, long groups = 1, bool bias = true, Device? device = null, ScalarType? dtype = null)\n {\n var res = THSNN_Conv1d_ctor(inputChannel, outputChannel, kernelSize, stride, padding == Padding.Valid ? 0 : -1, dilation, (long)paddingMode, groups, bias, out var boxedHandle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Conv1d(res, boxedHandle, inputChannel).MoveModule<Conv1d>(device, dtype);\n }\n\n public static partial class functional\n {\n /// <summary>\n /// Applies a 1D convolution over an input signal composed of several input planes.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"weight\"></param>\n /// <param name=\"bias\"></param>\n /// <param name=\"stride\"></param>\n /// <param name=\"padding\"></param>\n /// <param name=\"dilation\"></param>\n /// <param name=\"groups\"></param>\n /// <returns></returns>\n public static Tensor conv1d(Tensor input, Tensor weight, Tensor? bias = null,\n long? stride = null,\n long? padding = null,\n long? dilation = null,\n long groups = 1)\n {\n var strides = new long[] { stride ?? 1 };\n var paddingArray = new long[] { padding ?? 0 };\n var dilationArray = new long[] { dilation ?? 1 };\n var biasHandle = (bias is null ? IntPtr.Zero : bias.Handle);\n unsafe {\n fixed (long* pstrides = strides, ppadding = paddingArray, pdilation = dilationArray) {\n var res =\n THSTensor_conv1d(input.Handle, weight.Handle, biasHandle,\n (IntPtr)pstrides, strides.Length,\n (IntPtr)ppadding, paddingArray.Length,\n (IntPtr)pdilation, dilationArray.Length,\n groups);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5770045518875122, "alphanum_fraction": 0.5954614281654358, "avg_line_length": 52.30644989013672, "blob_id": "7fd5e7b256d5b553ee6fa3c2beca4c643a832206", "content_id": "803aec93c03a124d335b955ff1f0af0ca2a37978", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3305, "license_type": "permissive", "max_line_length": 117, "num_lines": 62, "path": "/pkg/FileRestitcher/FileRestitcher.Tests/UnitTest1.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "using System;\nusing System.IO;\nusing Xunit;\n\nnamespace FileRestitcherTests\n{\n public class Tests\n {\n //[Fact]\n public void TestRestitchingSmallFiles()\n {\n long size = 1024; // * 1024 * 1024; // enable this to test massive files, takes a long time\n var oneChunk = new byte[size];\n var rnd = new System.Random();\n for (int i = 0; i < 10; i++)\n oneChunk[i] = (byte)rnd.Next(0,255);\n var tmpDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @\"/tmp\";\n System.Console.WriteLine(\"tmpDir = {0}\", tmpDir);\n if (Directory.Exists(tmpDir))\n Directory.Delete(tmpDir, true);\n Directory.CreateDirectory(tmpDir);\n Directory.CreateDirectory(tmpDir + @\"/some-package-primary/runtimes\");\n Directory.CreateDirectory(tmpDir + @\"/some-package-fragment1/fragments\");\n Directory.CreateDirectory(tmpDir + @\"/some-package-fragment2/fragments\");\n Directory.CreateDirectory(tmpDir + @\"/some-package-fragment3/fragments\");\n File.WriteAllBytes(tmpDir + @\"/some-package-primary/runtimes/a.so\", oneChunk);\n File.WriteAllBytes(tmpDir + @\"/some-package-fragment1/fragments/a.so.fragment1\", oneChunk);\n File.WriteAllBytes(tmpDir + @\"/some-package-fragment2/fragments/a.so.fragment2\", oneChunk);\n File.WriteAllBytes(tmpDir + @\"/some-package-fragment3/fragments/a.so.fragment3\", oneChunk);\n System.Threading.Thread.Sleep(1000);\n using (var sha256Hash = System.Security.Cryptography.SHA256.Create()) {\n var expectedFile = tmpDir + @\"/a.so\";\n Console.WriteLine(\"Writing restored primary file at {0}\", expectedFile);\n var os = File.OpenWrite(expectedFile);\n os.Write(oneChunk, 0, oneChunk.Length);\n os.Write(oneChunk, 0, oneChunk.Length);\n os.Write(oneChunk, 0, oneChunk.Length);\n os.Write(oneChunk, 0, oneChunk.Length);\n os.Close();\n var os2 = File.OpenRead(expectedFile);\n byte[] bytes = sha256Hash.ComputeHash(os2);\n var builder = new System.Text.StringBuilder();\n for (int i = 0; i < bytes.Length; i++) {\n builder.Append(bytes[i].ToString(\"x2\"));\n }\n var sha = builder.ToString();\n File.WriteAllText(tmpDir + @\"/some-package-primary/runtimes/a.so.sha\", sha);\n os2.Close();\n }\n\n Assert.Equal(new FileInfo(tmpDir + @\"/some-package-primary/runtimes/a.so\").Length, 1* size);\n\n ConsoleApp2.Program.Restitch(tmpDir + @\"/some-package-primary\");\n Assert.True(File.Exists(tmpDir + @\"/some-package-primary/runtimes/a.so\"));\n Assert.Equal(new FileInfo(tmpDir + @\"/some-package-primary/runtimes/a.so\").Length, 4* size);\n Assert.False(File.Exists(tmpDir + @\"/some-package-fragment1/fragments/a.so.fragment1\"));\n Assert.False(File.Exists(tmpDir + @\"/some-package-fragment2/fragments/a.so.fragment2\"));\n Assert.False(File.Exists(tmpDir + @\"/some-package-fragment3/fragments/a.so.fragment3\"));\n }\n }\n\n}\n" }, { "alpha_fraction": 0.6319200992584229, "alphanum_fraction": 0.6329389810562134, "avg_line_length": 61.982173919677734, "blob_id": "77df93dca67f36d18fbc3b2036e9485d6820dad1", "content_id": "43e52c8e66771e0664c9950b8b17a3324a3d5e9c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 35431, "license_type": "permissive", "max_line_length": 214, "num_lines": 561, "path": "/src/TorchSharp/Tensor/torch.ReductionOps.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\n\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n // https://pytorch.org/docs/stable/torch#reduction-ops\n public static partial class torch\n {\n // https://pytorch.org/docs/stable/generated/torch.argmax\n /// <summary>\n /// Returns the indices of the maximum value of all elements in the input tensor.\n /// </summary>\n [Pure]public static Tensor argmax(Tensor input)\n => input.argmax();\n\n // https://pytorch.org/docs/stable/generated/torch.argmax\n /// <summary>\n /// Returns the indices of the maximum value of all elements in the input tensor.\n /// </summary>\n [Pure]public static Tensor argmax(Tensor input, long dim, bool keepdim = false)\n => input.argmax(dim, keepdim);\n\n // https://pytorch.org/docs/stable/generated/torch.argmin\n /// <summary>\n /// Returns the indices of the minimum value of all elements in the input tensor.\n /// </summary>\n [Pure]public static Tensor argmin(Tensor input)\n => input.argmin();\n\n // https://pytorch.org/docs/stable/generated/torch.argmin\n /// <summary>\n /// Returns the indices of the minimum value of all elements in the input tensor.\n /// </summary>\n [Pure]public static Tensor argmin(Tensor input, long dim, bool keepdim = false)\n => input.argmin(dim, keepdim);\n\n // https://pytorch.org/docs/stable/generated/torch.amax\n /// <summary>\n /// Returns the maximum value of each slice of the input tensor in the given dimension(s) dim.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dims\">The dimension or dimensions to reduce.</param>\n /// <param name=\"keepdim\">Whether the output tensor has dim retained or not.</param>\n /// <param name=\"out\">The output tensor -- optional.</param>\n [Pure]public static Tensor amax(Tensor input, long[] dims, bool keepdim = false, Tensor? @out = null)\n => input.amax(dims, keepdim, @out);\n\n [Pure]public static Tensor amax(Tensor input, ReadOnlySpan<long> dims, bool keepdim = false, Tensor? @out = null)\n => input.amax(dims, keepdim, @out);\n\n [Pure]public static Tensor amax(Tensor input, long[] dims)\n => input.amax(dims);\n\n // https://pytorch.org/docs/stable/generated/torch.amin\n /// <summary>\n /// Returns the minimum value of each slice of the input tensor in the given dimension(s) dim.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dims\">The dimension or dimensions to reduce.</param>\n /// <param name=\"keepdim\">Whether the output tensor has dim retained or not.</param>\n /// <param name=\"out\">The output tensor -- optional.</param>\n [Pure]public static Tensor amin(Tensor input, long[] dims, bool keepdim = false, Tensor? @out = null)\n => input.amin(dims, keepdim, @out);\n\n // https://pytorch.org/docs/stable/generated/torch.amin\n /// <summary>\n /// Returns the minimum value of each slice of the input tensor in the given dimension(s) dim.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dims\">The dimension or dimensions to reduce.</param>\n /// <param name=\"keepdim\">Whether the output tensor has dim retained or not.</param>\n /// <param name=\"out\">The output tensor -- optional.</param>\n [Pure]public static Tensor amin(Tensor input, ReadOnlySpan<long> dims, bool keepdim = false, Tensor? @out = null)\n => input.amin(dims, keepdim, @out);\n\n // https://pytorch.org/docs/stable/generated/torch.aminmax\n [Pure]public static (Tensor min, Tensor max) aminmax(Tensor input, long? dim = null, bool keepdim = false)\n => input.aminmax(dim, keepdim);\n\n // https://pytorch.org/docs/stable/generated/torch.all\n /// <summary>\n /// Tests if all elements in input evaluate to true.\n /// <param name=\"input\">The input tensor</param>\n /// </summary>\n [Pure]public static Tensor all(Tensor input) => input.all();\n\n // https://pytorch.org/docs/stable/generated/torch.all\n /// <summary>\n /// Tests if all elements in input evaluate to true.\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">The dimension to reduce</param>\n /// <param name=\"keepdim\">Keep the dimension to reduce</param>\n /// </summary>\n [Pure]public static Tensor all(Tensor input, long dim, bool keepdim = false) => input.all(dim, keepdim);\n\n // https://pytorch.org/docs/stable/generated/torch.any\n /// <summary>\n /// Tests if all elements in input evaluate to true.\n /// <param name=\"input\">The input tensor</param>\n /// </summary>\n [Pure]public static Tensor any(Tensor input) => input.any();\n\n // https://pytorch.org/docs/stable/generated/torch.any\n /// <summary>\n /// Tests if any element in input evaluate to true.\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">The dimension to reduce</param>\n /// <param name=\"keepdim\">Keep the dimension to reduce</param>\n /// </summary>\n [Pure]public static Tensor any(Tensor input, long dim, bool keepdim = false) => input.any(dim, keepdim);\n\n // https://pytorch.org/docs/stable/generated/torch.max\n /// <summary>\n /// Returns the maximum value of all elements in the input tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor max(Tensor input) => input.max();\n\n /// <summary>\n /// Computes the element-wise maximum of input and other.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"other\">The second tensor.</param>\n [Pure] public static Tensor max(Tensor input, Tensor other) => torch.maximum(input, other);\n\n // https://pytorch.org/docs/stable/generated/torch.max\n /// <summary>\n /// Returns a named tuple (values, indexes) where values is the maximum value of each row of the input tensor in the given dimension dim.\n /// And indices is the index location of each maximum value found (argmax).\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">the dimension to reduce.</param>\n /// <param name=\"keepdim\">whether the output tensor has dim retained or not. Default: false.</param>\n /// <remarks>If keepdim is true, the output tensors are of the same size as input except in the dimension dim where they are of size 1.\n /// Otherwise, dim is squeezed(see torch.squeeze()), resulting in the output tensors having 1 fewer dimension than input.</remarks>\n [Pure]public static (Tensor values, Tensor indexes) max(Tensor input, long dim, bool keepdim = false) => input.max(dim, keepdim);\n\n // https://pytorch.org/docs/stable/generated/torch.min\n /// <summary>\n /// Returns the minimum value of all elements in the input tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n [Pure]public static Tensor min(Tensor input) => input.min();\n\n /// <summary>\n /// Computes the element-wise minimum of input and other.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"other\">The second tensor.</param>\n [Pure] public static Tensor min(Tensor input, Tensor other) => torch.minimum(input, other);\n\n // https://pytorch.org/docs/stable/generated/torch.min\n /// <summary>\n /// Returns a named tuple (values, indexes) where values is the minimum value of each row of the input tensor in the given dimension dim.\n /// And indices is the index location of each minimum value found (argmin).\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">the dimension to reduce.</param>\n /// <param name=\"keepdim\">whether the output tensor has dim retained or not. Default: false.</param>\n /// <remarks>If keepdim is true, the output tensors are of the same size as input except in the dimension dim where they are of size 1.\n /// Otherwise, dim is squeezed(see torch.squeeze()), resulting in the output tensors having 1 fewer dimension than input.</remarks>\n [Pure]public static (Tensor values, Tensor indexes) min(Tensor input, long dim, bool keepdim = false) => input.min(dim, keepdim);\n\n // https://pytorch.org/docs/stable/generated/torch.dist\n /// <summary>\n /// Returns the p-norm of (input - other).\n /// The shapes of input and other must be broadcastable.\n /// </summary>\n /// <param name=\"input\">Left-hand side input tensor.</param>\n /// <param name=\"other\">Right-hand side input tensor</param>\n /// <param name=\"p\">The norm to be computed.</param>\n [Pure]public static Tensor dist(Tensor input, Tensor other, float p = 2.0f) => input.dist(other, p);\n\n // https://pytorch.org/docs/stable/generated/torch.logsumexp\n /// <summary>\n /// Returns the log of summed exponentials of each row of the input tensor in the given dimension dim.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dim\">The dimension to do the operation over</param>\n /// <param name=\"keepdim\">Thether the output tensor has dim retained or not.</param>\n [Pure]public static Tensor logsumexp(Tensor input, long dim, bool keepdim = false)\n => input.logsumexp(dim, keepdim);\n\n // https://pytorch.org/docs/stable/generated/torch.mean\n /// <summary>\n /// Returns the mean value of all elements in the input tensor.\n /// </summary>\n [Pure]public static Tensor mean(Tensor input) => input.mean();\n\n // https://pytorch.org/docs/stable/generated/torch.\n /// <summary>\n /// Returns the mean value of each row of the input tensor in the given dimension dim. If dim is a list of dimensions, reduce over all of them.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dimensions\">The dimension or dimensions to reduce.</param>\n /// <param name=\"keepdim\">Whether the output tensor has dim retained or not.</param>\n /// <param name=\"type\">The desired data type of returned tensor. If specified, the input tensor is cast to dtype before the operation is performed. This is useful for preventing data type overflows.</param>\n /// <remarks>\n /// If keepdim is True, the output tensor is of the same size as input except in the dimension(s) dim where it is of size 1.\n /// Otherwise, dim is squeezed(see torch.squeeze()), resulting in the output tensor having 1 (or len(dim)) fewer dimension(s).\n /// </remarks>\n [Pure]public static Tensor mean(Tensor input, long[] dimensions, bool keepdim = false, ScalarType? type = null) => input.mean(dimensions, keepdim, type);\n\n // https://pytorch.org/docs/stable/generated/torch.nanmean\n [Pure]public static Tensor nanmean(Tensor input, int? dim = null, bool keepdim = false, ScalarType? dtype = null)\n => input.nanmean(dim, keepdim, dtype);\n\n // https://pytorch.org/docs/stable/generated/torch.median\n [Pure]public static Tensor median(Tensor input) => input.median();\n\n // https://pytorch.org/docs/stable/generated/torch.nanmedian\n [Pure]public static Tensor nanmedian(Tensor input)\n => input.nanmedian();\n\n // https://pytorch.org/docs/stable/generated/torch.mode\n [Pure]public static (Tensor values, Tensor indices) mode(Tensor input, long dim = -1L, bool keepdim = false)\n => input.mode(dim, keepdim);\n\n // https://pytorch.org/docs/stable/generated/torch.norm\n [Pure]public static Tensor norm(Tensor input, float p = 2.0f)\n => input.norm(p);\n\n [Pure]public static Tensor norm(Tensor input, int dimension, bool keepdim = false, float p = 2.0f)\n => input.norm(dimension, keepdim, p);\n\n // https://pytorch.org/docs/stable/generated/torch.nansum\n [Pure]public static Tensor nansum(Tensor input) => input.nansum();\n\n // https://pytorch.org/docs/stable/generated/torch.prod\n // TODO: torch.prod\n // static Tensor prod(Tensor input, ScalarType dtype = null) => input.prod(dtype);\n\n // https://pytorch.org/docs/stable/generated/torch.quantile\n [Pure]public static Tensor quantile(Tensor input, Tensor q, long dim = -1, bool keepdim = false)\n => input.quantile(q, dim, keepdim);\n\n // https://pytorch.org/docs/stable/generated/torch.nanquantile\n [Pure]public static Tensor nanquantile(Tensor input, Tensor q, long dim = -1, bool keepdim = false)\n => input.nanquantile(q, dim, keepdim);\n\n // https://pytorch.org/docs/stable/generated/torch.std\n /// <summary>\n /// Calculates the standard deviation of all elements in the tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n [Pure]public static Tensor std(Tensor input, bool unbiased = true) => input.std(unbiased);\n\n /// <summary>Calculates the standard deviation of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample deviation is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>The <see cref=\"Tensor\">output tensor</see>.</returns>\n [Pure]public static Tensor std(Tensor input, long[] dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.std(dimensions, unbiased, keepdim, type);\n\n /// <summary>Calculates the standard deviation of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample deviation is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>The <see cref=\"Tensor\">output tensor</see>.</returns>\n [Pure]public static Tensor std(Tensor input, long dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.std(dimensions, unbiased, keepdim, type);\n\n /// <summary>Calculates the standard deviation of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample deviation is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>The <see cref=\"Tensor\">output tensor</see>.</returns>\n [Pure]public static Tensor std(Tensor input, (long, long) dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.std(dimensions, unbiased, keepdim, type);\n\n /// <summary>Calculates the standard deviation of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample deviation is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>The <see cref=\"Tensor\">output tensor</see>.</returns>\n [Pure]public static Tensor std(Tensor input, (long, long, long) dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.std(dimensions, unbiased, keepdim, type);\n\n // https://pytorch.org/docs/stable/generated/torch.std_mean\n /// <summary>Calculates the standard deviation and mean of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample deviation is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>A <see cref=\"Tensor\">tensor</see> tuple of the standard deviation and the mean.</returns>\n [Pure]public static (Tensor std, Tensor mean) std_mean(Tensor input, long[] dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.std_mean(dimensions, unbiased, keepdim, type);\n\n /// <summary>Calculates the standard deviation and mean of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample deviation is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>A <see cref=\"Tensor\">tensor</see> tuple of the standard deviation and the mean.</returns>\n [Pure]public static (Tensor std, Tensor mean) std_mean(Tensor input, ReadOnlySpan<long> dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.std_mean(dimensions, unbiased, keepdim, type);\n\n /// <summary>Calculates the standard deviation and mean of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample deviation is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>A <see cref=\"Tensor\">tensor</see> tuple of the standard deviation and the mean.</returns>\n [Pure]public static (Tensor std, Tensor mean) std_mean(Tensor input, long dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.std_mean(dimensions, unbiased, keepdim, type);\n\n /// <summary>Calculates the standard deviation and mean of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample deviation is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>A <see cref=\"Tensor\">tensor</see> tuple of the standard deviation and the mean.</returns>\n [Pure]public static (Tensor std, Tensor mean) std_mean(Tensor input, (long, long) dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.std_mean(dimensions, unbiased, keepdim, type);\n\n /// <summary>Calculates the standard deviation and mean of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample deviation is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>A <see cref=\"Tensor\">tensor</see> tuple of the standard deviation and the mean.</returns>\n [Pure]public static (Tensor std, Tensor mean) std_mean(Tensor input, (long, long, long) dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.std_mean(dimensions, unbiased, keepdim, type);\n\n // https://pytorch.org/docs/stable/generated/torch.sum\n /// <summary>\n /// Returns the sum of each row of the input tensor in the given dimensions.\n /// </summary>\n [Pure]public static Tensor sum(Tensor input, ScalarType? type = null) => input.sum(type);\n\n // https://pytorch.org/docs/stable/generated/torch.sum\n /// <summary>\n /// Returns the sum of each row of the input tensor in the given dimensions.\n /// </summary>\n [Pure]public static Tensor sum(Tensor input, ReadOnlySpan<long> dim, bool keepdim = false, ScalarType? type = null) => input.sum(dim, keepdim, type);\n\n // https://pytorch.org/docs/stable/generated/torch.sum\n /// <summary>\n /// Returns the sum of each row of the input tensor in the given dimension.\n /// </summary>\n [Pure]public static Tensor sum(Tensor input, long dim, bool keepdim = false, ScalarType? type = null) => input.sum(dim, keepdim, type);\n\n // https://pytorch.org/docs/stable/generated/torch.unique\n [Pure]static (Tensor output, Tensor? inverse_indices, Tensor? counts) unique(\n Tensor input, bool sorted = true, bool return_inverse = false, bool return_counts = false, int? dim = null)\n => input.unique(sorted, return_inverse, return_counts, dim);\n\n // https://pytorch.org/docs/stable/generated/torch.unique_consecutive\n [Pure]static (Tensor output, Tensor? inverse_indices, Tensor? counts) unique_consecutive(\n Tensor input, bool return_inverse = false, bool return_counts = false, int? dim = null)\n => input.unique_consecutive(return_inverse, return_counts, dim);\n\n // https://pytorch.org/docs/stable/generated/torch.var\n /// <summary>\n /// Calculates the variance of all elements in the tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n [Pure]public static Tensor var(Tensor input, bool unbiased = true) => input.var(unbiased);\n\n /// <summary>Calculates the variance of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample variance is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>The <see cref=\"Tensor\">output tensor</see>.</returns>\n [Pure]public static Tensor var(Tensor input, long[] dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.var(dimensions, unbiased, keepdim, type);\n\n /// <summary>Calculates the variance of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample variance is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>The <see cref=\"Tensor\">output tensor</see>.</returns>\n [Pure]public static Tensor var(Tensor input, long dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.var(dimensions, unbiased, keepdim, type);\n\n /// <summary>Calculates the variance of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample variance is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>The <see cref=\"Tensor\">output tensor</see>.</returns>\n [Pure]public static Tensor var(Tensor input, (long, long) dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.var(dimensions, unbiased, keepdim, type);\n\n /// <summary>Calculates the variance of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample variance is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>The <see cref=\"Tensor\">output tensor</see>.</returns>\n [Pure]public static Tensor var(Tensor input, (long, long, long) dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.var(dimensions, unbiased, keepdim, type);\n\n // https://pytorch.org/docs/stable/generated/torch.var_mean\n /// <summary>\n /// Calculates the variance and mean of all elements in the tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n [Pure]public static (Tensor @var, Tensor mean) var_mean(Tensor input, bool unbiased = true) => input.std_mean(unbiased);\n\n /// <summary>Calculates the variance and mean of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample variance is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>A <see cref=\"Tensor\">tensor</see> tuple of the variance and the mean.</returns>\n [Pure]public static (Tensor @var, Tensor mean) var_mean(Tensor input, long[] dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.var_mean(dimensions, unbiased, keepdim, type);\n\n /// <summary>Calculates the variance and mean of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample variance is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>A <see cref=\"Tensor\">tensor</see> tuple of the variance and the mean.</returns>\n [Pure]public static (Tensor @var, Tensor mean) var_mean(Tensor input, ReadOnlySpan<long> dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.var_mean(dimensions, unbiased, keepdim, type);\n\n /// <summary>Calculates the variance and mean of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample variance is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>A <see cref=\"Tensor\">tensor</see> tuple of the variance and the mean.</returns>\n [Pure]public static (Tensor @var, Tensor mean) var_mean(Tensor input, long dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.var_mean(dimensions, unbiased, keepdim, type);\n\n /// <summary>Calculates the variance and mean of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample variance is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>A <see cref=\"Tensor\">tensor</see> tuple of the variance and the mean.</returns>\n [Pure]public static (Tensor @var, Tensor mean) var_mean(Tensor input, (long, long) dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.var_mean(dimensions, unbiased, keepdim, type);\n\n /// <summary>Calculates the variance and mean of all elements in the tensor.</summary>\n /// <remarks>\n /// If <paramref name=\"unbiased\" /> is <value>true</value>, Bessel’s correction will be used.\n /// Otherwise, the sample variance is calculated, without any correction.\n /// </remarks>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dimensions\">The dimensions to reduce.</param>\n /// <param name=\"unbiased\">Whether to use Bessel’s correction (δN=1).</param>\n /// <param name=\"keepdim\">Whether the <see cref=\"Tensor\">output tensor</see> has dim retained or not.</param>\n /// <param name=\"type\"></param>\n /// <returns>A <see cref=\"Tensor\">tensor</see> tuple of the variance and the mean.</returns>\n [Pure]public static (Tensor @var, Tensor mean) var_mean(Tensor input, (long, long, long) dimensions, bool unbiased = true, bool keepdim = false, ScalarType? type = null)\n => input.var_mean(dimensions, unbiased, keepdim, type);\n\n // https://pytorch.org/docs/stable/generated/torch.count_nonzero\n /// <summary>\n /// Counts the number of non-zero values in the tensor input along the given dim. If no dim is specified then all non-zeros in the tensor are counted.\n /// </summary>\n /// <param name=\"input\">The input tensor.</param>\n /// <param name=\"dims\">List of dims along which to count non-zeros.</param>\n [Pure]public static Tensor count_nonzero(Tensor input, long[]? dims = null)\n => input.count_nonzero(dims);\n }\n}" }, { "alpha_fraction": 0.6863289475440979, "alphanum_fraction": 0.6969696879386902, "avg_line_length": 37.59821319580078, "blob_id": "69748fc248494996ea127fc2769ab1f85cfedcd7", "content_id": "3d3919ee3fe9da9ee4ae37d1980ab254339553ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4323, "license_type": "permissive", "max_line_length": 130, "num_lines": 112, "path": "/src/TorchSharp/PInvoke/LibTorchSharp.THSTorch.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp.PInvoke\n{\n internal static partial class NativeMethods\n {\n [DllImport(\"LibTorchSharp\")]\n [return: MarshalAs(UnmanagedType.U1)]\n internal static extern bool THSTorch_scalar_to_bool(IntPtr handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSTorch_dispose_scalar(IntPtr handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern byte THSTorch_scalar_type(IntPtr value);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern int THSTorch_can_cast(int type1, int type2);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern int THSTorch_promote_types(int type1, int type2);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSTorch_uint8_to_scalar(byte value);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSTorch_int8_to_scalar(sbyte value);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSTorch_int16_to_scalar(short value);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSTorch_int32_to_scalar(int value);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSTorch_int64_to_scalar(long value);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSTorch_float32_to_scalar(float value);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSTorch_float64_to_scalar(double value);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSTorch_complex32_to_scalar(float real, float imaginary);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSTorch_complex64_to_scalar(double real, double imaginary);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSTorch_bool_to_scalar([MarshalAs(UnmanagedType.U1)] bool value);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSTorch_float16_to_scalar(float value);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSTorch_bfloat16_to_scalar(float value);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern float THSTorch_scalar_to_float32(IntPtr handle);\n\n#if NET6_0_OR_GREATER\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSTorch_scalar_to_float16(IntPtr value, out Half res);\n#endif\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern double THSTorch_scalar_to_float64(IntPtr handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern sbyte THSTorch_scalar_to_int8(IntPtr handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern byte THSTorch_scalar_to_uint8(IntPtr handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern short THSTorch_scalar_to_int16(IntPtr handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern int THSTorch_scalar_to_int32(IntPtr handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern long THSTorch_scalar_to_int64(IntPtr handle);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSTorch_scalar_to_complex32(IntPtr handle, AllocatePinnedArray allocator);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSTorch_scalar_to_complex64(IntPtr handle, AllocatePinnedArray allocator);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSTorch_get_and_reset_last_err();\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern IntPtr THSTorch_lstsq(IntPtr handle, IntPtr b, out IntPtr qr);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern int THSTorch_get_num_threads();\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSTorch_set_num_threads(int threads);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern int THSTorch_get_num_interop_threads();\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSTorch_set_num_interop_threads(int threads);\n }\n}\n" }, { "alpha_fraction": 0.47560974955558777, "alphanum_fraction": 0.47560974955558777, "avg_line_length": 25.62162208557129, "blob_id": "72a8fb9266b87cce7305ecce5bc759a205c33b4a", "content_id": "43737a584f03ad472eee7db273bc1f9861c6ef9e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 984, "license_type": "permissive", "max_line_length": 130, "num_lines": 37, "path": "/src/TorchAudio/AudioMetaData.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nnamespace TorchSharp\n{\n public static partial class torchaudio\n {\n /// <summary>\n /// Meta-data of audio\n /// </summary>\n public struct AudioMetaData\n {\n /// <summary>\n /// Sample rate\n /// </summary>\n public int sample_rate;\n\n /// <summary>\n /// The number of frames\n /// </summary>\n public int num_frames;\n\n /// <summary>\n /// The number of channels\n /// </summary>\n public int num_channels;\n\n /// <summary>\n /// The number of bits per sample.\n /// </summary>\n public int bits_per_sample;\n\n /// <summary>\n /// Audio encoding\n /// </summary>\n public AudioEncoding encoding;\n }\n }\n}" }, { "alpha_fraction": 0.48172980546951294, "alphanum_fraction": 0.547435462474823, "avg_line_length": 38.77333450317383, "blob_id": "e4ca9d1cc963bab7f50db0c34c99cd85981d82cf", "content_id": "e22ed515f95e40973ce5b9ce3a682f947151958a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2983, "license_type": "permissive", "max_line_length": 131, "num_lines": 75, "path": "/src/Examples/VGG.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System.Collections.Generic;\n\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\n\nnamespace TorchSharp.Examples\n{\n /// <summary>\n /// Modified version of VGG to classify CIFAR10 32x32 images.\n /// </summary>\n /// <remarks>\n /// With an unaugmented CIFAR-10 data set, the author of this saw training converge\n /// at roughly 85% accuracy on the test set, after 50 epochs using VGG-16.\n /// </remarks>\n class VGG : Module<Tensor, Tensor>\n {\n // The code here is is loosely based on https://github.com/kuangliu/pytorch-cifar/blob/master/models/vgg.py\n // Licence and copypright notice at: https://github.com/kuangliu/pytorch-cifar/blob/master/LICENSE\n\n private readonly Dictionary<string, long[]> _channels = new Dictionary<string, long[]>() {\n { \"VGG11\", new long[] { 64, 0, 128, 0, 256, 256, 0, 512, 512, 0, 512, 512, 0 } },\n { \"VGG13\", new long[] { 64, 64, 0, 128, 128, 0, 256, 256, 0, 512, 512, 0, 512, 512, 0 } },\n { \"VGG16\", new long[] { 64, 64, 0, 128, 128, 0, 256, 256, 256, 0, 512, 512, 512, 0, 512, 512, 512, 0 } },\n { \"VGG19\", new long[] { 64, 64, 0, 128, 128, 0, 256, 256, 256, 256, 0, 512, 512, 512, 512, 0, 512, 512, 512, 512, 0 } }\n };\n\n private readonly Module<Tensor, Tensor> layers;\n\n public VGG(string name, int numClasses, Device device = null) : base(name)\n {\n var modules = new List<(string, Module<Tensor, Tensor>)>();\n\n var channels = _channels[name.ToUpper()];\n\n long in_channels = 3;\n\n for (var i = 0; i < channels.Length; i++) {\n\n if (channels[i] == 0) {\n modules.Add(($\"MaxPool2d-{i}a\", MaxPool2d(kernelSize: 2, stride: 2)));\n } else {\n modules.Add(($\"conv2d-{i}a\", Conv2d(in_channels, channels[i], kernelSize: 3, padding: 1)));\n modules.Add(($\"bnrm2d-{i}a\", BatchNorm2d(channels[i])));\n modules.Add(($\"relu-{i}b\", ReLU(inplace: true)));\n in_channels = channels[i];\n }\n }\n modules.Add((\"avgpool2d\", AvgPool2d(kernel_size: 1, stride: 1)));\n modules.Add((\"flatten\", Flatten()));\n modules.Add((\"linear\", Linear(512, numClasses)));\n\n layers = Sequential(modules);\n\n RegisterComponents();\n\n if (device != null && device.type == DeviceType.CUDA)\n this.to(device);\n }\n\n public override Tensor forward(Tensor input)\n {\n return layers.call(input);\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n layers.Dispose();\n ClearModules();\n }\n base.Dispose(disposing);\n }\n }\n}\n" }, { "alpha_fraction": 0.5376311540603638, "alphanum_fraction": 0.541280210018158, "avg_line_length": 42.8466682434082, "blob_id": "a6501ccc6a48a91f6d49caa26f9a2c8c9db0e5d4", "content_id": "2014f82bd8e38ed4e95909445226149e0ce2f470", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6577, "license_type": "permissive", "max_line_length": 149, "num_lines": 150, "path": "/src/TorchSharp/Distributions/Geometric.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// A Geometric distribution parameterized by probs,\n /// where probs is the probability of success of Bernoulli trials.\n ///\n /// It represents the probability that in k+1 Bernoulli trials, the\n /// first k trials failed, before seeing a success.\n /// </summary>\n public class Geometric : torch.distributions.Distribution\n {\n /// <summary>\n /// The mean of the distribution.\n /// </summary>\n public override Tensor mean => 1 / (probs - 1);\n\n /// <summary>\n /// The variance of the distribution\n /// </summary>\n public override Tensor variance => (1.0f / probs - 1.0f) / probs;\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"probs\">The probability of sampling '1'. Must be in range (0, 1]</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n public Geometric(Tensor probs = null, Tensor logits = null, torch.Generator generator = null) : base(generator) \n {\n this.batch_shape = probs is null ? logits.size() : probs.size();\n this._probs = probs?.alias().DetachFromDisposeScope();\n this._logits = logits?.alias().DetachFromDisposeScope();\n }\n\n /// <summary>\n /// Event probabilities\n /// </summary>\n public Tensor probs {\n get {\n return _probs ?? LogitsToProbs(_logits, true);\n }\n }\n\n /// <summary>\n /// Event log-odds\n /// </summary>\n public Tensor logits {\n get {\n return _logits ?? ProbsToLogits(_probs);\n }\n }\n\n private Tensor _probs;\n private Tensor _logits;\n\n /// <summary>\n /// Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples\n /// if the distribution parameters are batched.\n /// </summary>\n /// <param name=\"sample_shape\">The sample shape.</param>\n public override Tensor rsample(params long[] sample_shape)\n {\n using var _ = torch.NewDisposeScope();\n var shape = ExtendedShape(sample_shape);\n var tiny = torch.finfo(probs.dtype).tiny;\n using (torch.no_grad()) {\n var u = probs.new_empty(shape).uniform_(tiny, 1, generator: generator);\n return (u.log() / (-probs).log1p()).floor().MoveToOuterDisposeScope();\n }\n }\n\n /// <summary>\n /// Returns the log of the probability density/mass function evaluated at `value`.\n /// </summary>\n /// <param name=\"value\"></param>\n public override Tensor log_prob(Tensor value)\n {\n using var _ = torch.NewDisposeScope();\n var bcast = torch.broadcast_tensors(value, probs);\n value = bcast[0];\n var p = bcast[1].clone();\n p[(p == 1) & (value == 0)] = torch.tensor(0);\n return (value * (-p).log1p() + probs.log()).MoveToOuterDisposeScope();\n }\n\n /// <summary>\n /// Returns entropy of distribution, batched over batch_shape.\n /// </summary>\n /// <returns></returns>\n public override Tensor entropy()\n {\n return torch.nn.functional.binary_cross_entropy_with_logits(logits, probs, reduction: nn.Reduction.None);\n }\n\n /// <summary>\n /// Returns a new distribution instance (or populates an existing instance provided by a derived class) with batch dimensions expanded to\n /// `batch_shape`. This method calls `torch.Tensor.expand()` on the distribution's parameters. As such, this does not allocate new\n /// memory for the expanded distribution instance.\n /// </summary>\n /// <param name=\"batch_shape\">Tthe desired expanded size.</param>\n /// <param name=\"instance\">new instance provided by subclasses that need to override `.expand`.</param>\n public override distributions.Distribution expand(Size batch_shape, distributions.Distribution instance = null)\n {\n if (instance != null && !(instance is Geometric))\n throw new ArgumentException(\"expand(): 'instance' must be a Geometric distribution\");\n\n var newDistribution = ((instance == null) ?\n new Geometric(probs: _probs?.expand(batch_shape), logits: logits?.expand(batch_shape), generator) :\n instance) as Geometric;\n\n newDistribution.batch_shape = batch_shape;\n if (newDistribution == instance) {\n newDistribution._probs = _probs?.expand(batch_shape);\n newDistribution._logits = _logits?.expand(batch_shape);\n }\n return newDistribution;\n }\n }\n\n }\n public static partial class torch\n {\n public static partial class distributions\n {\n /// <summary>\n /// Creates a Geometric distribution parameterized by probs,\n /// where probs is the probability of success of Bernoulli trials.\n ///\n /// It represents the probability that in k+1 Bernoulli trials, the\n /// first k trials failed, before seeing a success.\n /// </summary>\n /// <param name=\"probs\">The probability of sampling '1'. Must be in range (0, 1]</param>\n /// <param name=\"logits\">The log-odds of sampling '1'</param>\n /// <param name=\"generator\">An optional random number generator object.</param>\n /// <returns></returns>\n public static Geometric Geometric(Tensor probs = null, Tensor logits = null, torch.Generator generator = null)\n {\n return new Geometric(probs, logits, generator);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.49470704793930054, "alphanum_fraction": 0.49643033742904663, "avg_line_length": 32.024391174316406, "blob_id": "1e2cc235bdc03ee0abfbfea8f86d44d8c8662373", "content_id": "64e4e3d560e15dde81dae4c2799768681b1ebd11", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8124, "license_type": "permissive", "max_line_length": 130, "num_lines": 246, "path": "/src/TorchSharp/NN/ParameterDict.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Linq;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing static TorchSharp.torch.nn;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// Holds parameters in a dictionary.\n /// \n /// ParameterDict can be indexed like a regular dictionary, but the parameters it\n /// contains are properly registered, and will be visible by all Module methods.\n ///\n /// ParameterDict is an ordered dictionary that respects the order of insertion, and\n /// in update(), the order of the merged OrderedDict or another ParameterDict (the argument to update()).\n /// </summary>\n public class ParameterDict : Module, IDictionary<string, Parameter>, IList<(string, Parameter)>\n {\n public ParameterDict() : base(nameof(ParameterDict))\n {\n }\n\n /// <summary>\n /// Remove all items from the ParameterDict.\n /// </summary>\n public void clear()\n {\n _list.Clear();\n _dict.Clear();\n }\n\n /// <summary>\n /// Return an enumeration of the ParameterDict key/value pairs.\n /// </summary>\n /// <returns></returns>\n public IEnumerator<(string, Parameter)> items() => _list.GetEnumerator();\n\n /// <summary>\n /// Return the ParameterDict keys.\n /// </summary>\n /// <returns></returns>\n public IEnumerable<string> keys() => _dict.Keys;\n\n protected override void RegisterComponents()\n {\n if (_registered) return;\n\n for (int i = 0; i < _list.Count; i++) {\n register_parameter($\"{_list[i].Item1}\", _list[i].Item2);\n }\n _registered = true;\n }\n\n private bool _registered = false;\n\n /// <summary>\n /// Return the ParameterDict values.\n /// </summary>\n /// <returns></returns>\n public IEnumerable<Parameter> values() => _dict.Values;\n\n public (string, Parameter) this[int index] {\n get => _list[index];\n set {\n var name = value.Item1;\n _list[index] = value;\n _dict[name] = value.Item2;\n }\n }\n\n public bool IsReadOnly => false;\n\n public ICollection<string> Keys => _list.Select(kv => kv.Item1).ToList();\n\n public ICollection<Parameter> Values => _list.Select(kv => kv.Item2).ToList();\n\n public int Count => _dict.Count;\n\n public Parameter this[string key] {\n get => _dict[key];\n set {\n _dict[key] = value;\n var idx = _list.FindIndex(kv => kv.Item1.Equals(key));\n _list[idx] = (key, value);\n }\n }\n\n public override bool has_parameter(string target)\n {\n return _dict.ContainsKey(target);\n }\n\n public override Parameter get_parameter(string target)\n {\n if (_dict.TryGetValue(target, out var result)) {\n return result;\n }\n return null;\n }\n\n public void Add((string, Parameter) item)\n {\n _dict.Add(item.Item1, item.Item2);\n _list.Add(item);\n }\n\n public void Add(string key, Parameter value)\n {\n _dict.Add(key, value);\n _list.Add((key, value));\n }\n\n public void Add(KeyValuePair<string, Parameter> item)\n {\n _dict.Add(item.Key, item.Value);\n _list.Add((item.Key, item.Value));\n }\n\n public bool Contains((string, Parameter) item)\n {\n return _list.Contains(item);\n }\n\n public void CopyTo((string, Parameter)[] array, int arrayIndex)\n {\n _list.CopyTo(array, arrayIndex);\n }\n\n public int IndexOf((string, Parameter) item)\n {\n return _list.IndexOf(item);\n }\n\n public void Insert(int index, (string, Parameter) item)\n {\n _dict.Add(item.Item1, item.Item2);\n _list.Insert(index, item);\n }\n\n public bool Remove((string, Parameter) item)\n {\n _dict.Remove(item.Item1);\n return _list.Remove(item);\n }\n\n public void RemoveAt(int index)\n {\n if (index >= _list.Count) throw new IndexOutOfRangeException();\n var (n,p) = _list[index];\n _list.RemoveAt(index);\n _dict.Remove(n);\n }\n\n public bool ContainsKey(string key)\n {\n return _dict.ContainsKey(key);\n }\n\n public bool Remove(string key)\n {\n var value = _dict[key];\n var idx = _list.FindIndex(kv => kv.Item1.Equals(key));\n _list.RemoveAt(idx);\n return _dict.Remove(key);\n }\n\n public bool TryGetValue(string key, [MaybeNullWhen(false)] out Parameter value)\n {\n return _dict.TryGetValue(key, out value);\n }\n\n public void Clear()\n {\n _dict.Clear();\n _list.Clear();\n }\n\n public bool Contains(KeyValuePair<string, Parameter> item)\n {\n return _dict.ContainsKey(item.Key);\n }\n\n public void CopyTo(KeyValuePair<string, Parameter>[] array, int arrayIndex)\n {\n throw new NotImplementedException();\n }\n\n public bool Remove(KeyValuePair<string, Parameter> item)\n {\n return _dict.Remove(item.Key);\n }\n\n public IEnumerator<(string, Parameter)> GetEnumerator()\n {\n return _list.GetEnumerator();\n }\n\n IEnumerator<KeyValuePair<string, Parameter>> IEnumerable<KeyValuePair<string, Parameter>>.GetEnumerator()\n {\n throw new NotImplementedException();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return ((IEnumerable<KeyValuePair<string, Parameter>>)this).GetEnumerator();\n }\n\n private List<(string, Parameter)> _list = new List<(string, Parameter)>();\n private Dictionary<string, Parameter> _dict = new Dictionary<string, Parameter>();\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n\n /// <summary>\n /// Create a ParameterList instance from an array of parameter tensors.\n /// </summary>\n /// <param name=\"parameters\">A tuple of (name,parameter).</param>\n /// <remarks>\n /// ParameterDict can be indexed like a regular dictionary, but the parameters it\n /// contains are properly registered, and will be visible by all Module methods.\n ///\n /// ParameterDict is an ordered dictionary that respects the order of insertion, and\n /// in update(), the order of the merged OrderedDict or another ParameterDict (the argument to update()).\n /// </remarks>\n public static ParameterDict ParameterDict(params (string, Parameter)[] parameters)\n {\n var result = new ParameterDict();\n foreach (var (n, p) in parameters) {\n result.Add(n, p);\n }\n return result;\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5330060124397278, "alphanum_fraction": 0.5351881980895996, "avg_line_length": 30.620689392089844, "blob_id": "3afb855fa919ed78c584c133ba543d8fa16212b2", "content_id": "472368314d627e59578360b268b42c2562506f29", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1833, "license_type": "permissive", "max_line_length": 130, "num_lines": 58, "path": "/src/TorchVision/CenterCrop.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System;\nusing static TorchSharp.torch;\n\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class CenterCrop : ITransform\n {\n internal CenterCrop(int height, int width)\n {\n if (height <= 0) \n throw new ArgumentOutOfRangeException(nameof(height), \"Height must be greater than 0.\");\n if (width <= 0) \n throw new ArgumentOutOfRangeException(nameof(width), \"Width must be greater than 0.\");\n\n this.height = height;\n this.width = width;\n }\n\n public Tensor call(Tensor input)\n {\n return transforms.functional.center_crop(input, height, width);\n }\n\n protected int height, width;\n\n public int Height => height;\n public int Width => width;\n\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Crop the center of the image.\n /// </summary>\n /// <param name=\"height\">Desired output height of the crop</param>\n /// <param name=\"width\">Desired output width of the crop</param>\n static public ITransform CenterCrop(int height, int width)\n {\n return new CenterCrop(height, width);\n }\n\n /// <summary>\n /// Crop the center of the image.\n /// </summary>\n /// <param name=\"size\">Desired output size of the crop</param>\n static public ITransform CenterCrop(int size)\n {\n return new CenterCrop(size, size);\n }\n }\n }\n}" }, { "alpha_fraction": 0.5069842338562012, "alphanum_fraction": 0.5288323760032654, "avg_line_length": 43.31745910644531, "blob_id": "9f8bef2aaee08a3c7eeeab404650c65c3cf2c48c", "content_id": "475420505d090c32ce7b6ecc6d8141651b8ce422", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5584, "license_type": "permissive", "max_line_length": 167, "num_lines": 126, "path": "/src/TorchVision/models/AlexNet.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing static TorchSharp.torch;\nusing static TorchSharp.torch.nn;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class models\n {\n /// <summary>\n /// AlexNet\n /// </summary>\n /// <param name=\"num_classes\">The number of output classes.</param>\n /// <param name=\"dropout\">The dropout ratio.</param>\n /// <param name=\"weights_file\">The location of a file containing pre-trained weights for the model.</param>\n /// <param name=\"skipfc\">If true, the last linear layer of the classifier will not be loaded from the weights file.</param>\n /// <param name=\"device\">The device to locate the model on.</param>\n /// <remarks>\n /// Pre-trained weights may be retrieved by using Pytorch and saving the model state-dict\n /// using the exportsd.py script, then loading into the .NET instance:\n ///\n /// from torchvision import models\n /// import exportsd\n /// \n /// model = models.alexnet(pretrained=True)\n /// f = open(\"model_weights.dat\", \"wb\")\n /// exportsd.save_state_dict(model.state_dict(), f)\n /// f.close()\n ///\n /// See also: https://github.com/dotnet/TorchSharp/blob/main/docfx/articles/saveload.md\n ///\n /// In order for the weights to be loaded, the number of classes has to be the same as\n /// in the pre-trained model, which is 1000.\n ///\n /// It is also possible to skip loading the last linear layer and use it for transfer-learning\n /// with a different number of output classes. To do so, pass skipfc=true.\n /// as the skip list when loading.\n ///\n /// All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB\n /// images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded\n /// in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].\n /// </remarks>\n public static Modules.AlexNet alexnet(int num_classes = 1000, float dropout = 0.5f, string? weights_file = null, bool skipfc = true, Device? device = null)\n {\n return new Modules.AlexNet(num_classes, dropout, weights_file, skipfc, device);\n }\n }\n }\n\n namespace Modules\n {\n // The code here is based on\n // https://github.com/pytorch/vision/blob/main/torchvision/models/alexnet.py\n // Licence and copypright notice at: https://github.com/pytorch/vision/blob/main/LICENSE\n\n public class AlexNet : Module<Tensor, Tensor>\n {\n private readonly Module<Tensor, Tensor> features;\n private readonly Module<Tensor, Tensor> avgpool;\n private readonly Module<Tensor, Tensor> classifier;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n features.Dispose(); avgpool.Dispose();\n classifier.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public AlexNet(int numClasses, float dropout = 0.5f, string? weights_file = null, bool skipfc = true, Device? device = null) : base(nameof(AlexNet))\n {\n features = Sequential(\n Conv2d(3, 64, kernelSize: 11, stride: 4, padding: 2),\n ReLU(inplace: true),\n MaxPool2d(kernelSize: 3, stride: 2),\n Conv2d(64, 192, kernelSize: 5, padding: 2),\n ReLU(inplace: true),\n MaxPool2d(kernelSize: 3, stride: 2),\n Conv2d(192, 384, kernelSize: 3, padding: 1),\n ReLU(inplace: true),\n Conv2d(384, 256, kernelSize: 3, padding: 1),\n ReLU(inplace: true),\n Conv2d(256, 256, kernelSize: 3, padding: 1),\n ReLU(inplace: true),\n MaxPool2d(kernelSize: 3, stride: 2)\n );\n\n avgpool = AdaptiveAvgPool2d(new long[] { 6, 6 });\n\n classifier = Sequential(\n Dropout(p: dropout),\n Linear(256 * 6 * 6, 4096),\n ReLU(inplace: true),\n Dropout(p: dropout),\n Linear(4096, 4096),\n ReLU(inplace: true),\n Linear(4096, numClasses)\n );\n\n RegisterComponents();\n\n if (!string.IsNullOrEmpty(weights_file)) {\n\n this.load(weights_file, skip: skipfc ? new[] { \"classifier.6.weight\", \"classifier.6.bias\" } : null);\n }\n\n if (device != null && device.type == DeviceType.CUDA)\n this.to(device);\n }\n\n public override Tensor forward(Tensor input)\n {\n using (var _ = NewDisposeScope()) {\n var f = features.call(input);\n var avg = avgpool.call(f);\n var x = avg.flatten(1);\n return classifier.call(x).MoveToOuterDisposeScope();\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.4583049416542053, "alphanum_fraction": 0.48074302077293396, "avg_line_length": 44.84635543823242, "blob_id": "6f2e1b423a0c2a869bdd0b406af734f9d6fb51d4", "content_id": "9531bea4ccb1949a7c3c0247ac5992d3780a4f07", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 17604, "license_type": "permissive", "max_line_length": 134, "num_lines": 384, "path": "/src/TorchVision/models/MobileNetV3.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchvision,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/vision/blob/3c9ae0ac5dda3d881a6ce5004ce5756ae7de7bc4/torchvision/models/mobilenetv3.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/vision/blob/main/LICENSE\n//\n\nusing System.Collections.Generic;\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.torchvision.models._utils;\nusing static TorchSharp.torchvision.ops;\nusing TorchSharp.Modules;\n\n#nullable enable\nnamespace TorchSharp\n{\n namespace Modules\n {\n public class MobileNetV3 : nn.Module<Tensor, Tensor>\n {\n /// <summary>\n /// Stores information listed at Tables 1 and 2 of the MobileNetV3 paper\n /// </summary>\n internal class InvertedResidualConfig\n {\n public readonly long dilation;\n public readonly long expanded_channels;\n public readonly long input_channels;\n public readonly long kernel;\n public readonly long out_channels;\n public readonly long stride;\n public readonly bool use_hs;\n public readonly bool use_se;\n\n public InvertedResidualConfig(\n long input_channels,\n long kernel,\n long expanded_channels,\n long out_channels,\n bool use_se,\n string activation,\n long stride,\n long dilation,\n double width_mult)\n {\n this.input_channels = adjust_channels(input_channels, width_mult);\n this.kernel = kernel;\n this.expanded_channels = adjust_channels(expanded_channels, width_mult);\n this.out_channels = adjust_channels(out_channels, width_mult);\n this.use_se = use_se;\n this.use_hs = activation == \"HS\";\n this.stride = stride;\n this.dilation = dilation;\n }\n\n internal static long adjust_channels(long channels, double width_mult)\n {\n return _make_divisible(channels * width_mult, 8);\n }\n }\n\n /// <summary>\n /// Implemented as described at section 5 of MobileNetV3 paper\n /// </summary>\n private class InvertedResidual : nn.Module<Tensor, Tensor>\n {\n private readonly bool _is_cn;\n private readonly nn.Module<Tensor, Tensor> block;\n private readonly long out_channels;\n private readonly bool use_res_connect;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n block.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public InvertedResidual(\n string name,\n InvertedResidualConfig cnf,\n Func<long, nn.Module<Tensor, Tensor>> norm_layer,\n Func<long, long, nn.Module<Tensor, Tensor>>? se_layer = null) : base(name)\n {\n if (!(1 <= cnf.stride && cnf.stride <= 2)) {\n throw new ArgumentException(\"illegal stride value\");\n }\n\n this.use_res_connect = cnf.stride == 1 && cnf.input_channels == cnf.out_channels;\n\n var layers = new List<nn.Module<Tensor, Tensor>>();\n Func<bool, nn.Module<Tensor, Tensor>> activation_layer = (\n cnf.use_hs ? (inplace) => nn.Hardswish(inplace) : (inplace) => nn.ReLU(inplace));\n\n // expand\n if (cnf.expanded_channels != cnf.input_channels) {\n layers.Add(Conv2dNormActivation(\n cnf.input_channels,\n cnf.expanded_channels,\n kernel_size: 1,\n norm_layer: norm_layer,\n activation_layer: activation_layer));\n }\n\n // depthwise\n var stride = cnf.dilation > 1 ? 1 : cnf.stride;\n layers.Add(Conv2dNormActivation(\n cnf.expanded_channels,\n cnf.expanded_channels,\n kernel_size: cnf.kernel,\n stride: stride,\n dilation: cnf.dilation,\n groups: cnf.expanded_channels,\n norm_layer: norm_layer,\n activation_layer: activation_layer));\n if (cnf.use_se) {\n var squeeze_channels = _make_divisible(cnf.expanded_channels / 4, 8);\n if (se_layer != null) {\n layers.Add(se_layer(cnf.expanded_channels, squeeze_channels));\n } else {\n layers.Add(\n torchvision.ops.SqueezeExcitation(\n cnf.expanded_channels,\n squeeze_channels,\n activation: () => nn.ReLU6(),\n scale_activation: () => nn.Hardsigmoid()));\n }\n }\n\n // project\n layers.Add(\n Conv2dNormActivation(\n cnf.expanded_channels, cnf.out_channels, kernel_size: 1, norm_layer: norm_layer, activation_layer: null));\n\n this.block = nn.Sequential(layers);\n this.out_channels = cnf.out_channels;\n this._is_cn = cnf.stride > 1;\n\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor input)\n {\n var result = this.block.call(input);\n if (this.use_res_connect) {\n result += input;\n }\n return result;\n }\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n avgpool.Dispose();\n classifier.Dispose();\n features.Dispose();\n }\n base.Dispose(disposing);\n }\n private readonly nn.Module<Tensor, Tensor> avgpool;\n private readonly nn.Module<Tensor, Tensor> classifier;\n private readonly nn.Module<Tensor, Tensor> features;\n\n /// <summary>\n /// MobileNet V3 main class\n /// </summary>\n /// <param name=\"name\"></param>\n /// <param name=\"inverted_residual_setting\">Network structure</param>\n /// <param name=\"last_channel\">The number of channels on the penultimate layer</param>\n /// <param name=\"num_classes\">Number of classes</param>\n /// <param name=\"block\">Module specifying inverted residual building block for mobilenet</param>\n /// <param name=\"norm_layer\">Module specifying the normalization layer to use</param>\n /// <param name=\"dropout\">The droupout probability</param>\n /// <exception cref=\"ArgumentException\"></exception>\n internal MobileNetV3(\n string name,\n InvertedResidualConfig[] inverted_residual_setting,\n long last_channel,\n long num_classes = 1000,\n Func<InvertedResidualConfig, Func<long, nn.Module<Tensor, Tensor>>, nn.Module<Tensor, Tensor>>? block = null,\n Func<long, nn.Module<Tensor, Tensor>>? norm_layer = null,\n double dropout = 0.2) : base(name)\n {\n if (inverted_residual_setting == null || inverted_residual_setting.Length == 0) {\n throw new ArgumentException(\"The inverted_residual_setting should not be empty\");\n }\n\n if (block == null) {\n block = (cnf, norm_layer) => new InvertedResidual(\"InvertedResidual\", cnf, norm_layer);\n }\n\n if (norm_layer == null) {\n norm_layer = (features) => nn.BatchNorm2d(features, eps: 0.001, momentum: 0.01);\n }\n\n var layers = new List<nn.Module<Tensor, Tensor>>();\n\n // building first layer\n var firstconv_output_channels = inverted_residual_setting[0].input_channels;\n layers.Add(\n Conv2dNormActivation(\n 3,\n firstconv_output_channels,\n kernel_size: 3,\n stride: 2,\n norm_layer: norm_layer,\n activation_layer: (inplace) => nn.Hardswish(inplace)));\n\n // building inverted residual blocks\n foreach (var cnf in inverted_residual_setting) {\n layers.Add(block(cnf, norm_layer));\n }\n\n // building last several layers\n var lastconv_input_channels = inverted_residual_setting[inverted_residual_setting.Length - 1].out_channels;\n var lastconv_output_channels = 6 * lastconv_input_channels;\n layers.Add(\n Conv2dNormActivation(\n lastconv_input_channels,\n lastconv_output_channels,\n kernel_size: 1,\n norm_layer: norm_layer,\n activation_layer: (inplace) => nn.Hardswish(inplace)));\n\n this.features = nn.Sequential(layers);\n this.avgpool = nn.AdaptiveAvgPool2d(1);\n this.classifier = nn.Sequential(\n nn.Linear(lastconv_output_channels, last_channel),\n nn.Hardswish(inplace: true),\n nn.Dropout(p: dropout, inplace: true),\n nn.Linear(last_channel, num_classes));\n\n RegisterComponents();\n\n foreach (var (_, m) in this.named_modules()) {\n if (m is Modules.Conv2d) {\n var conv = (Modules.Conv2d)m;\n nn.init.kaiming_normal_(conv.weight, mode: nn.init.FanInOut.FanOut);\n if (conv.bias is not null) {\n nn.init.zeros_(conv.bias);\n }\n } else if (m is Modules.BatchNorm2d) {\n var norm = (Modules.BatchNorm2d)m;\n nn.init.ones_(norm.weight);\n nn.init.zeros_(norm.bias);\n } else if (m is Modules.GroupNorm) {\n var norm = (Modules.GroupNorm)m;\n nn.init.ones_(norm.weight);\n nn.init.zeros_(norm.bias);\n } else if (m is Modules.Linear) {\n var linear = (Modules.Linear)m;\n nn.init.normal_(linear.weight, 0, 0.01);\n nn.init.zeros_(linear.bias);\n }\n }\n }\n\n public override Tensor forward(Tensor x)\n {\n x = this.features.call(x);\n x = this.avgpool.call(x);\n x = torch.flatten(x, 1);\n x = this.classifier.call(x);\n return x;\n }\n }\n }\n\n public static partial class torchvision\n {\n public static partial class models\n {\n private static (MobileNetV3.InvertedResidualConfig[], long) _mobilenet_v3_conf(\n string arch,\n double width_mult = 1.0,\n bool reduced_tail = false,\n bool dilated = false)\n {\n long last_channel;\n MobileNetV3.InvertedResidualConfig[] inverted_residual_setting;\n var reduce_divider = reduced_tail ? 2 : 1;\n var dilation = dilated ? 2 : 1;\n MobileNetV3.InvertedResidualConfig bneck_conf(\n long input_channels,\n long kernel,\n long expanded_channels,\n long out_channels,\n bool use_se,\n string activation,\n long stride,\n long dilation) => new MobileNetV3.InvertedResidualConfig(\n input_channels,\n kernel,\n expanded_channels,\n out_channels,\n use_se,\n activation,\n stride,\n dilation,\n width_mult: width_mult);\n long adjust_channels(long channels) =>\n MobileNetV3.InvertedResidualConfig.adjust_channels(\n channels,\n width_mult: width_mult);\n if (arch == \"mobilenet_v3_large\") {\n inverted_residual_setting = new MobileNetV3.InvertedResidualConfig[] {\n bneck_conf(16, 3, 16, 16, false, \"RE\", 1, 1),\n bneck_conf(16, 3, 64, 24, false, \"RE\", 2, 1),\n bneck_conf(24, 3, 72, 24, false, \"RE\", 1, 1),\n bneck_conf(24, 5, 72, 40, true, \"RE\", 2, 1),\n bneck_conf(40, 5, 120, 40, true, \"RE\", 1, 1),\n bneck_conf(40, 5, 120, 40, true, \"RE\", 1, 1),\n bneck_conf(40, 3, 240, 80, false, \"HS\", 2, 1),\n bneck_conf(80, 3, 200, 80, false, \"HS\", 1, 1),\n bneck_conf(80, 3, 184, 80, false, \"HS\", 1, 1),\n bneck_conf(80, 3, 184, 80, false, \"HS\", 1, 1),\n bneck_conf(80, 3, 480, 112, true, \"HS\", 1, 1),\n bneck_conf(112, 3, 672, 112, true, \"HS\", 1, 1),\n bneck_conf(112, 5, 672, 160 / reduce_divider, true, \"HS\", 2, dilation),\n bneck_conf(160 / reduce_divider, 5, 960 / reduce_divider, 160 / reduce_divider, true, \"HS\", 1, dilation),\n bneck_conf(160 / reduce_divider, 5, 960 / reduce_divider, 160 / reduce_divider, true, \"HS\", 1, dilation)\n };\n last_channel = adjust_channels(1280 / reduce_divider);\n } else if (arch == \"mobilenet_v3_small\") {\n inverted_residual_setting = new MobileNetV3.InvertedResidualConfig[] {\n bneck_conf(16, 3, 16, 16, true, \"RE\", 2, 1),\n bneck_conf(16, 3, 72, 24, false, \"RE\", 2, 1),\n bneck_conf(24, 3, 88, 24, false, \"RE\", 1, 1),\n bneck_conf(24, 5, 96, 40, true, \"HS\", 2, 1),\n bneck_conf(40, 5, 240, 40, true, \"HS\", 1, 1),\n bneck_conf(40, 5, 240, 40, true, \"HS\", 1, 1),\n bneck_conf(40, 5, 120, 48, true, \"HS\", 1, 1),\n bneck_conf(48, 5, 144, 48, true, \"HS\", 1, 1),\n bneck_conf(48, 5, 288, 96 / reduce_divider, true, \"HS\", 2, dilation),\n bneck_conf(96 / reduce_divider, 5, 576 / reduce_divider, 96 / reduce_divider, true, \"HS\", 1, dilation),\n bneck_conf(96 / reduce_divider, 5, 576 / reduce_divider, 96 / reduce_divider, true, \"HS\", 1, dilation)\n };\n last_channel = adjust_channels(1024 / reduce_divider);\n } else {\n throw new ArgumentException($\"Unsupported model type {arch}\");\n }\n return (inverted_residual_setting, last_channel);\n }\n\n private static Modules.MobileNetV3 _mobilenet_v3(\n MobileNetV3.InvertedResidualConfig[] inverted_residual_setting,\n long last_channel)\n {\n var model = new MobileNetV3(\"MobileNetV3\", inverted_residual_setting, last_channel);\n return model;\n }\n\n /// <summary>\n /// Constructs a large MobileNetV3 architecture from\n /// `Searching for MobileNetV3 https://arxiv.org/abs/1905.02244`.\n /// </summary>\n /// <returns></returns>\n public static MobileNetV3 mobilenet_v3_large()\n {\n var (inverted_residual_setting, last_channel) = _mobilenet_v3_conf(\"mobilenet_v3_large\");\n return _mobilenet_v3(inverted_residual_setting, last_channel);\n }\n\n /// <summary>\n /// Constructs a small MobileNetV3 architecture from\n /// `Searching for MobileNetV3 https://arxiv.org/abs/1905.02244`.\n /// </summary>\n /// <returns></returns>\n public static MobileNetV3 mobilenet_v3_small()\n {\n var (inverted_residual_setting, last_channel) = _mobilenet_v3_conf(\"mobilenet_v3_small\");\n return _mobilenet_v3(inverted_residual_setting, last_channel);\n }\n }\n }\n}" }, { "alpha_fraction": 0.6567100882530212, "alphanum_fraction": 0.6668975353240967, "avg_line_length": 33.40584182739258, "blob_id": "85f8467351161cae1d780e06bcf55040963b751e", "content_id": "6f9ca1742b0d924f4e3ecc8d6c65af862ca6ec8d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 44761, "license_type": "permissive", "max_line_length": 273, "num_lines": 1301, "path": "/src/Native/LibTorchSharp/THSNN.cpp", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#include \"THSNN.h\"\n\n#include <torch/nn/init.h>\n\n\nNNModule THSNN_Identity_ctor(NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n res = create_module<torch::nn::IdentityImpl>(outAsAnyModule);\n );\n}\n\nTensor THSNN_Identity_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Identity>()->forward(*tensor));\n}\n\nNNModule THSNN_Linear_ctor(const int64_t input_size, const int64_t output_size, const bool bias,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::LinearOptions(input_size, output_size).bias(bias);\n res = create_module<torch::nn::LinearImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Linear_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Linear>()->forward(*tensor));\n}\n\nTensor THSNN_Linear_bias(const NNModule module)\n{\n return get_bias<torch::nn::Linear>(module);\n}\n\nvoid THSNN_Linear_set_bias(const NNModule module, const Tensor bias)\n{\n set_bias<torch::nn::Linear>(module, bias);\n}\n\nTensor THSNN_Linear_weight(const NNModule module)\n{\n return get_weight<torch::nn::Linear>(module);\n}\n\nvoid THSNN_Linear_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::Linear>(module, weight);\n}\n\nTensor THSNN_functional_linear(const Tensor input, const Tensor weights, const Tensor bias)\n{\n CATCH_TENSOR(bias == nullptr ?\n torch::nn::functional::linear(*input, *weights) :\n torch::nn::functional::linear(*input, *weights, *bias));\n}\n\nTensor THSNN_functional_bilinear(const Tensor input1, const Tensor input2, const Tensor weights, const Tensor bias)\n{\n CATCH_TENSOR(bias == nullptr ?\n torch::nn::functional::bilinear(*input1, *input2, *weights) :\n torch::nn::functional::bilinear(*input1, *input2, *weights, *bias));\n}\n\nNNModule THSNN_Bilinear_ctor(const int64_t input_size_1, const int64_t input_size_2, const int64_t output_size, const bool bias,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::BilinearOptions(input_size_1, input_size_2, output_size).bias(bias);\n res = create_module<torch::nn::BilinearImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Bilinear_forward(const NNModule module, const Tensor x1, const Tensor x2)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Bilinear>()->forward(*x1, *x2));\n}\n\nTensor THSNN_Bilinear_bias(const NNModule module)\n{\n return get_bias<torch::nn::Bilinear>(module);\n}\n\nvoid THSNN_Bilinear_set_bias(const NNModule module, const Tensor bias)\n{\n set_bias<torch::nn::Bilinear>(module, bias);\n}\n\nTensor THSNN_Bilinear_weight(const NNModule module)\n{\n return get_weight<torch::nn::Bilinear>(module);\n}\n\nvoid THSNN_Bilinear_set_weight(const NNModule module, const Tensor weight)\n{\n set_weight<torch::nn::Bilinear>(module, weight);\n}\n\nTensor THSNN_dropout(const Tensor input, const double p, bool training, bool inplace)\n{\n auto opts = torch::nn::functional::DropoutFuncOptions()\n .inplace(inplace)\n .training(training)\n .p(p);\n\n CATCH_TENSOR(torch::nn::functional::dropout(*input, opts));\n}\n\nTensor THSNN_dropout2d(const Tensor input, const double p, bool training, bool inplace)\n{\n auto opts = torch::nn::functional::Dropout2dFuncOptions()\n .inplace(inplace)\n .training(training)\n .p(p);\n\n CATCH_TENSOR(torch::nn::functional::dropout2d(*input, opts));\n}\n\nTensor THSNN_dropout3d(const Tensor input, const double p, bool training, bool inplace)\n{\n auto opts = torch::nn::functional::Dropout3dFuncOptions()\n .inplace(inplace)\n .training(training)\n .p(p);\n\n CATCH_TENSOR(torch::nn::functional::dropout3d(*input, opts));\n}\n\nTensor THSNN_alpha_dropout(const Tensor input, const double p, bool training, bool inplace)\n{\n auto opts = torch::nn::functional::AlphaDropoutFuncOptions()\n .inplace(inplace)\n .training(training)\n .p(p);\n\n CATCH_TENSOR(torch::nn::functional::alpha_dropout(*input, opts));\n}\n\nTensor THSNN_feature_alpha_dropout(const Tensor input, const double p, bool training, bool inplace)\n{\n auto opts = torch::nn::functional::FeatureAlphaDropoutFuncOptions()\n .inplace(inplace)\n .training(training)\n .p(p);\n\n CATCH_TENSOR(torch::nn::functional::feature_alpha_dropout(*input, opts));\n}\n\nNNModule THSNN_Dropout_ctor(double probability, bool inplace, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::DropoutOptions(probability).inplace(inplace);\n res = create_module<torch::nn::DropoutImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Dropout_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Dropout>()->forward(*tensor));\n}\n\nNNModule THSNN_AlphaDropout_ctor(double probability, bool inplace, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::AlphaDropoutOptions(probability).inplace(inplace);\n res = create_module<torch::nn::AlphaDropoutImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_AlphaDropout_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::AlphaDropout>()->forward(*tensor));\n}\n\nNNModule THSNN_Dropout1d_ctor(double probability, bool inplace, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n // Creating a Dropout2d instance here is done on purpose. There's no torch::nn::Dropout1d\n auto opts = torch::nn::Dropout2dOptions(probability).inplace(inplace);\n res = create_module<torch::nn::Dropout2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Dropout1d_forward(const NNModule module, const Tensor tensor)\n{\n auto drop1d = (*module)->as<torch::nn::Dropout2d>();\n CATCH_TENSOR(drop1d->options.inplace()\n ? drop1d->forward((*tensor).unsqueeze_(-1)).squeeze_(-1)\n : drop1d->forward((*tensor).unsqueeze(-1)).squeeze(-1));\n}\n\n\nNNModule THSNN_Dropout2d_ctor(double probability, bool inplace, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::Dropout2dOptions(probability).inplace(inplace);\n res = create_module<torch::nn::Dropout2dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Dropout2d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Dropout2d>()->forward(*tensor));\n}\n\nNNModule THSNN_Dropout3d_ctor(double probability, bool inplace, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::Dropout3dOptions(probability).inplace(inplace);\n res = create_module<torch::nn::Dropout3dImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Dropout3d_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Dropout3d>()->forward(*tensor));\n}\n\nNNModule THSNN_FeatureAlphaDropout_ctor(double probability, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::FeatureAlphaDropoutOptions(probability);\n res = create_module<torch::nn::FeatureAlphaDropoutImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_FeatureAlphaDropout_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::FeatureAlphaDropout>()->forward(*tensor));\n}\n\nNNModule THSNN_PixelShuffle_ctor(const int64_t upscale_factor, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::PixelShuffleOptions(upscale_factor);\n res = create_module<torch::nn::PixelShuffleImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_PixelShuffle_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::PixelShuffle>()->forward(*tensor));\n}\n\nNNModule THSNN_PixelUnshuffle_ctor(const int64_t downscale_factor, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::PixelUnshuffleOptions(downscale_factor);\n res = create_module<torch::nn::PixelUnshuffleImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_PixelUnshuffle_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::PixelUnshuffle>()->forward(*tensor));\n}\n\ntemplate<typename T>\nvoid ApplyUpsampleMode(T& opts, const int8_t mode)\n{\n if (mode == 0)\n opts = opts.mode(torch::kNearest);\n if (mode == 1)\n opts = opts.mode(torch::kLinear);\n if (mode == 2)\n opts = opts.mode(torch::kBilinear);\n if (mode == 3)\n opts = opts.mode(torch::kBicubic);\n if (mode == 4)\n opts = opts.mode(torch::kTrilinear);\n}\n\ntemplate<typename T>\nvoid ApplyInterpolateMode(T& opts, const int8_t mode)\n{\n if (mode == 0)\n opts = opts.mode(torch::kNearest);\n if (mode == 1)\n opts = opts.mode(torch::kLinear);\n if (mode == 2)\n opts = opts.mode(torch::kBilinear);\n if (mode == 3)\n opts = opts.mode(torch::kBicubic);\n if (mode == 4)\n opts = opts.mode(torch::kTrilinear);\n if (mode == 5)\n opts = opts.mode(torch::kArea);\n}\n\nNNModule THSNN_Upsample_ctor(const int64_t* size, const int size_len, const double* scale_factor, const int scale_factor_len, const int8_t mode, const int8_t align_corners, NNAnyModule* outAsAnyModule)\n{\n auto opts = torch::nn::UpsampleOptions();\n // align_corners -- 0=None, 1=true, 2=false\n if (align_corners != 0)\n opts.align_corners(align_corners == 1);\n ApplyUpsampleMode(opts, mode);\n\n CATCH_RETURN_NNModule(\n if (size_len > 0) {\n std::vector<int64_t> sizes;\n for (int i = 0; i < size_len; ++i) {\n sizes.push_back(size[i]);\n }\n opts.size(sizes);\n }\n if (scale_factor_len > 0) {\n std::vector<double> scales;\n for (int i = 0; i < scale_factor_len; ++i) {\n scales.push_back(scale_factor[i]);\n }\n opts.scale_factor(scales);\n }\n res = create_module<torch::nn::UpsampleImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Upsample_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Upsample>()->forward(*tensor));\n}\n\ntemplate<typename T>\nvoid ApplyPadMode(T& opts, const int64_t padding)\n{\n if (padding == 1)\n opts = opts.mode(torch::kReflect);\n if (padding == 2)\n opts = opts.mode(torch::kReplicate);\n if (padding == 3)\n opts = opts.mode(torch::kCircular);\n if (padding == 4)\n opts = opts.mode(torch::kConstant);\n}\n\ntemplate<typename T>\nvoid ApplyGridMode(T& opts, const int8_t mode)\n{\n if (mode == 0)\n opts = opts.mode(torch::kNearest);\n if (mode == 2)\n opts = opts.mode(torch::kBilinear);\n // The PyTorch docs say that bicubic should be supported, but the C++\n // mode type does not allow for it. I'm leaving this in for future use.\n //if (mode == 3)\n // opts = opts.mode(torch::kBicubic);\n}\n\ntemplate<typename T>\nvoid ApplyGridPadMode(T& opts, const int64_t padding)\n{\n if (padding == 0)\n opts = opts.padding_mode(torch::kZeros);\n if (padding == 1)\n opts = opts.padding_mode(torch::kReflection);\n if (padding == 2)\n opts = opts.padding_mode(torch::kBorder);\n}\n\nTensor THSNN_pad(const Tensor input, const int64_t* pad, const int pad_length, const int8_t mode, const double value)\n{\n std::vector<int64_t> padding;\n for (int i = 0; i < pad_length; ++i) {\n padding.push_back(pad[i]);\n }\n auto opts = torch::nn::functional::PadFuncOptions(padding).value(value);\n ApplyPadMode(opts, mode);\n\n CATCH_TENSOR(torch::nn::functional::pad(*input, opts));\n}\n\nTensor THSNN_grid_sample(const Tensor input, const Tensor grid, const int8_t mode, const int8_t padding_mode, const int8_t align_corners)\n{\n auto opts = torch::nn::functional::GridSampleFuncOptions();\n if (align_corners != 0)\n opts.align_corners(align_corners == 1);\n ApplyGridMode(opts, mode);\n ApplyGridPadMode(opts, padding_mode);\n CATCH_TENSOR(torch::nn::functional::grid_sample(*input, *grid, opts));\n}\n\nTensor THSNN_affine_grid(const Tensor theta, const int64_t* size, const int size_len, const bool align_corners)\n{\n CATCH_TENSOR(torch::nn::functional::affine_grid(*theta, at::ArrayRef<int64_t>(size, size_len), align_corners));\n}\n\n\nEXPORT_API(Tensor) THSNN_interpolate(const Tensor input, const int64_t* size, const int size_len, const double* scale_factor, const int scale_factor_len, const int8_t mode, const int8_t align_corners, const bool recompute_scale_factor, NNAnyModule* outAsAnyModule)\n{\n auto opts = torch::nn::functional::InterpolateFuncOptions().recompute_scale_factor(recompute_scale_factor);\n // align_corners -- 0=None, 1=true, 2=false\n if (align_corners != 0)\n opts.align_corners(align_corners == 1);\n ApplyInterpolateMode(opts, mode);\n\n if (size_len > 0) {\n std::vector<int64_t> sizes;\n for (int i = 0; i < size_len; ++i) {\n sizes.push_back(size[i]);\n }\n opts.size(sizes);\n }\n if (scale_factor_len > 0) {\n std::vector<double> scales;\n for (int i = 0; i < scale_factor_len; ++i) {\n scales.push_back(scale_factor[i]);\n }\n opts.scale_factor(scales);\n }\n\n CATCH_TENSOR(torch::nn::functional::interpolate(*input, opts));\n}\n\nNNModule THSNN_Embedding_ctor(const int64_t num_embeddings, const int64_t embedding_dims,\n const int64_t padding_idx, bool has_pi, const double max_norm, const bool has_mn, const double norm_type,\n const bool scale_grad_by_freq, const bool sparse,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::EmbeddingOptions(num_embeddings, embedding_dims)\n .norm_type(norm_type)\n .scale_grad_by_freq(scale_grad_by_freq)\n .sparse(sparse);\n\n if (has_pi)\n opts.padding_idx(padding_idx);\n if (has_mn)\n opts.max_norm(max_norm);\n\n res = create_module<torch::nn::EmbeddingImpl>(opts, outAsAnyModule);\n );\n}\n\nNNModule THSNN_Embedding_from_pretrained(const Tensor embeddings, const bool freeze,\n const int64_t padding_idx, bool has_pi, const double max_norm, const bool has_mn, const double norm_type,\n const bool scale_grad_by_freq, const bool sparse,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto rows = embeddings->size(0);\n auto cols = embeddings->size(1);\n\n auto opts = torch::nn::EmbeddingOptions(rows, cols)\n .norm_type(norm_type)\n .scale_grad_by_freq(scale_grad_by_freq)\n .sparse(sparse);\n\n if (has_pi)\n opts.padding_idx(padding_idx);\n if (has_mn)\n opts.max_norm(max_norm);\n\n // Can't use the template function here -- custom logic.\n auto mod = std::make_shared<torch::nn::EmbeddingImpl>(opts);\n mod->weight = *embeddings;\n mod->weight.set_requires_grad(!freeze);\n\n // Keep a boxed version of the module in case we add it to a Sequential later (the C++ templating means\n // a Module can only be boxed to AnyModule at the point its static type is known).\n if (outAsAnyModule != nullptr)\n {\n auto wrapped = std::make_shared<torch::nn::AnyModule>(torch::nn::ModuleHolder<torch::nn::EmbeddingImpl>(*mod));\n *outAsAnyModule = new std::shared_ptr<torch::nn::AnyModule>(wrapped);\n }\n res = new std::shared_ptr<torch::nn::Module>(mod);\n );\n}\n\nTensor THSNN_Embedding_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Embedding>()->forward(*tensor));\n}\n\nTensor THSNN_Embedding_weight(const NNModule module)\n{\n return get_weight<torch::nn::Embedding>(module);\n}\n\nvoid THSNN_Embedding_set_weight(const NNModule module, const Tensor weights)\n{\n set_weight<torch::nn::Embedding>(module, weights);\n}\n\ntemplate<typename T>\nvoid ApplyEmbeddingBagMode(T& opts, const int64_t mode)\n{\n if (mode == 0)\n opts = opts.mode(torch::kSum);\n if (mode == 1)\n opts = opts.mode(torch::kMean);\n if (mode == 2)\n opts = opts.mode(torch::kMax);\n}\n\nNNModule THSNN_EmbeddingBag_ctor(const int64_t num_embeddings, const int64_t embedding_dims,\n const double max_norm, const bool has_mn, const double norm_type, const bool scale_grad_by_freq,\n const int64_t mode, const bool sparse, const bool include_last_offset, const int64_t padding_idx,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::EmbeddingBagOptions(num_embeddings, embedding_dims)\n .norm_type(norm_type)\n .scale_grad_by_freq(scale_grad_by_freq)\n .include_last_offset(include_last_offset)\n .sparse(sparse);\n\n ApplyEmbeddingBagMode(opts, mode);\n\n if (has_mn)\n opts = opts.max_norm(max_norm);\n if (padding_idx >= 0)\n opts = opts.padding_idx(padding_idx);\n\n res = create_module<torch::nn::EmbeddingBagImpl>(opts, outAsAnyModule);\n );\n}\n\nNNModule THSNN_EmbeddingBag_from_pretrained(const Tensor embeddings, const bool freeze,\n const double max_norm, const bool has_mn, const double norm_type, const bool scale_grad_by_freq,\n const int64_t mode, const bool sparse, const bool include_last_offset, const int64_t padding_idx,\n NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto rows = embeddings->size(0);\n auto cols = embeddings->size(1);\n\n auto opts = torch::nn::EmbeddingBagOptions(rows, cols)\n .norm_type(norm_type)\n .scale_grad_by_freq(scale_grad_by_freq)\n .include_last_offset(include_last_offset)\n .sparse(sparse);\n\n ApplyEmbeddingBagMode(opts, mode);\n\n if (has_mn)\n opts.max_norm(max_norm);\n if (padding_idx >= 0)\n opts = opts.padding_idx(padding_idx);\n\n // Can't use the template function here -- custom logic.\n auto mod = std::make_shared<torch::nn::EmbeddingBagImpl>(opts);\n mod->weight = *embeddings;\n mod->weight.set_requires_grad(!freeze);\n\n // Keep a boxed version of the module in case we add it to a Sequential later (the C++ templating means\n // a Module can only be boxed to AnyModule at the point its static type is known).\n if (outAsAnyModule != nullptr)\n {\n auto wrapped = std::make_shared<torch::nn::AnyModule>(torch::nn::ModuleHolder<torch::nn::EmbeddingBagImpl>(*mod));\n *outAsAnyModule = new std::shared_ptr<torch::nn::AnyModule>(wrapped);\n }\n res = new std::shared_ptr<torch::nn::Module>(mod);\n );\n}\n\nTensor THSNN_EmbeddingBag_forward(const NNModule module, const Tensor input, const Tensor offsets, const Tensor per_sample_weights)\n{\n if (offsets != nullptr && per_sample_weights != nullptr)\n {\n CATCH_TENSOR((*module)->as<torch::nn::EmbeddingBag>()->forward(*input, *offsets, *per_sample_weights));\n }\n else if (offsets == nullptr && per_sample_weights != nullptr)\n {\n CATCH_TENSOR((*module)->as<torch::nn::EmbeddingBag>()->forward(*input, {}, *per_sample_weights));\n }\n else if (offsets != nullptr && per_sample_weights == nullptr)\n {\n CATCH_TENSOR((*module)->as<torch::nn::EmbeddingBag>()->forward(*input, *offsets));\n }\n else\n {\n CATCH_TENSOR((*module)->as<torch::nn::EmbeddingBag>()->forward(*input));\n }\n}\n\nTensor THSNN_EmbeddingBag_weight(const NNModule module)\n{\n return get_weight<torch::nn::EmbeddingBag>(module);\n}\n\nvoid THSNN_EmbeddingBag_set_weight(const NNModule module, const Tensor weights)\n{\n set_weight<torch::nn::EmbeddingBag>(module, weights);\n}\n\ntemplate<typename T>\nvoid ApplyTransformerActivation(T& opts, const int64_t activation)\n{\n if (activation == 0)\n opts = opts.activation(torch::kReLU);\n if (activation == 1)\n opts = opts.activation(torch::kGELU);\n}\n\ntemplate<typename T>\nvoid ApplyRnnActivation(T& opts, const int64_t activation)\n{\n if (activation == 0)\n opts = opts.nonlinearity(torch::kReLU);\n if (activation == 1)\n opts = opts.nonlinearity(torch::kTanh);\n}\n\nNNModule THSNN_Transformer_ctor(const int64_t d_model, const int64_t nhead, const int64_t num_encoder_layers, const int64_t num_decoder_layers, const int64_t dim_feedforward, const double dropout, const int64_t activation, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::TransformerOptions(d_model, nhead)\n .num_encoder_layers(num_encoder_layers)\n .num_decoder_layers(num_decoder_layers)\n .dim_feedforward(dim_feedforward)\n .dropout(dropout);\n ApplyTransformerActivation(opts, activation);\n\n res = create_module<torch::nn::TransformerImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Transformer_forward(const NNModule module, const Tensor src, const Tensor tgt, const Tensor src_mask, const Tensor tgt_mask, const Tensor memory_mask, const Tensor src_key_padding_mask, const Tensor tgt_key_padding_mask, const Tensor memory_key_padding_mask)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Transformer>()->forward(\n *src,\n *tgt,\n (src_mask ? *src_mask : at::Tensor()),\n (tgt_mask ? *tgt_mask : at::Tensor()),\n (memory_mask ? *memory_mask : at::Tensor()),\n (src_key_padding_mask ? *src_key_padding_mask : at::Tensor()),\n (tgt_key_padding_mask ? *tgt_key_padding_mask : at::Tensor()),\n (memory_key_padding_mask ? *memory_key_padding_mask : at::Tensor()))\n );\n}\n\nNNModule THSNN_TransformerEncoderLayer_ctor(const int64_t d_model, const int64_t nhead, const int64_t dim_feedforward, const double dropout, const int64_t activation, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::TransformerEncoderLayerOptions(d_model, nhead)\n .dim_feedforward(dim_feedforward)\n .dropout(dropout);\n ApplyTransformerActivation(opts, activation);\n\n res = create_module<torch::nn::TransformerEncoderLayerImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_TransformerEncoderLayer_forward(const NNModule module, const Tensor src, const Tensor src_mask, const Tensor src_key_padding_mask)\n{\n CATCH_TENSOR((*module)->as<torch::nn::TransformerEncoderLayer>()->forward(\n *src,\n (src_mask ? *src_mask : at::Tensor()),\n (src_key_padding_mask ? *src_key_padding_mask : at::Tensor()))\n );\n}\n\nNNModule THSNN_TransformerDecoderLayer_ctor(const int64_t d_model, const int64_t nhead, const int64_t dim_feedforward, const double dropout, const int64_t activation, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::TransformerDecoderLayerOptions(d_model, nhead)\n .dim_feedforward(dim_feedforward)\n .dropout(dropout);\n ApplyTransformerActivation(opts, activation);\n\n res = create_module<torch::nn::TransformerDecoderLayerImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_TransformerDecoderLayer_forward(const NNModule module, const Tensor tgt, const Tensor memory, const Tensor tgt_mask, const Tensor memory_mask, const Tensor tgt_key_padding_mask, const Tensor memory_key_padding_mask)\n{\n CATCH_TENSOR((*module)->as<torch::nn::TransformerDecoderLayer>()->forward(\n *tgt,\n *memory,\n (tgt_mask ? *tgt_mask : at::Tensor()),\n (memory_mask ? *memory_mask : at::Tensor()),\n (tgt_key_padding_mask ? *tgt_key_padding_mask : at::Tensor()),\n (memory_key_padding_mask ? *memory_key_padding_mask : at::Tensor()))\n );\n}\n\nNNModule THSNN_MultiheadAttention_ctor(const int64_t embeded_dim, const int64_t num_heads, const double dropout, const bool bias, const bool add_bias_kv, const bool add_zero_attn, const int64_t kdim, const int64_t vdim, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::MultiheadAttentionOptions(embeded_dim, num_heads)\n .dropout(dropout)\n .bias(bias)\n .add_bias_kv(add_bias_kv)\n .add_zero_attn(add_zero_attn)\n .kdim(kdim)\n .vdim(vdim);\n\n res = create_module<torch::nn::MultiheadAttentionImpl>(opts, outAsAnyModule);\n );\n}\n\nvoid THSNN_MultiheadAttention_forward(const NNModule module, const Tensor query, const Tensor key, const Tensor value, const Tensor key_padding_mask, const bool need_weights, const Tensor attn_mask, Tensor& res1, Tensor& res2)\n{\n CATCH_TENSORS_2((*module)->as<torch::nn::MultiheadAttention>()->forward(\n *query,\n *key,\n *value,\n (key_padding_mask ? *key_padding_mask : at::Tensor()),\n need_weights,\n (attn_mask ? *attn_mask : at::Tensor()))\n );\n}\n\nNNModule THSNN_TransformerEncoder_ctor(const NNModule encoder_layer, const int64_t num_layers, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto enc = (*encoder_layer)->as<torch::nn::TransformerEncoderLayer>();\n auto opts = torch::nn::TransformerEncoderOptions(torch::nn::TransformerEncoderLayer(*enc), num_layers);\n\n res = create_module<torch::nn::TransformerEncoderImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_TransformerEncoder_forward(const NNModule module, const Tensor src, const Tensor src_mask, const Tensor src_key_padding_mask)\n{\n CATCH_TENSOR((*module)->as<torch::nn::TransformerEncoder>()->forward(\n *src,\n (src_mask ? *src_mask : at::Tensor()),\n (src_key_padding_mask ? *src_key_padding_mask : at::Tensor()))\n );\n}\n\nNNModule THSNN_TransformerDecoder_ctor(const NNModule decoder_layer, const int64_t num_layers, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto dec = (*decoder_layer)->as<torch::nn::TransformerDecoderLayer>();\n auto opts = torch::nn::TransformerDecoderOptions(torch::nn::TransformerDecoderLayer(*dec), num_layers);\n\n res = create_module<torch::nn::TransformerDecoderImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_TransformerDecoder_forward(const NNModule module, const Tensor tgt, const Tensor memory, const Tensor tgt_mask, const Tensor memory_mask, const Tensor tgt_key_padding_mask, const Tensor memory_key_padding_mask)\n{\n CATCH_TENSOR((*module)->as<torch::nn::TransformerDecoder>()->forward(\n *tgt,\n *memory,\n (tgt_mask ? *tgt_mask : at::Tensor()),\n (memory_mask ? *memory_mask : at::Tensor()),\n (tgt_key_padding_mask ? *tgt_key_padding_mask : at::Tensor()),\n (memory_key_padding_mask ? *memory_key_padding_mask : at::Tensor()))\n );\n}\n\nNNModule THSNN_Flatten_ctor(const int64_t start_dim, const int64_t end_dim, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::FlattenOptions()\n .start_dim(start_dim)\n .end_dim(end_dim);\n\n res = create_module<torch::nn::FlattenImpl>(opts, outAsAnyModule);\n );\n}\nTensor THSNN_Flatten_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Flatten>()->forward(*tensor));\n}\n\nNNModule THSNN_Unflatten_ctor(const int64_t dim, const int64_t* shape, const int64_t shape_len, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n std::vector<int64_t> sizes;\n for (int64_t i = 0; i < shape_len; ++i)\n {\n sizes.push_back(shape[i]);\n }\n auto opts = torch::nn::UnflattenOptions(dim, sizes);\n res = create_module<torch::nn::UnflattenImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_Unflatten_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Unflatten>()->forward(*tensor));\n}\n\nNNModule THSNN_CosineSimilarity_ctor(const int64_t dim, double eps, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::CosineSimilarityOptions()\n .dim(dim)\n .eps(eps);\n\n res = create_module<torch::nn::CosineSimilarityImpl>(opts, outAsAnyModule);\n );\n\n}\n\nTensor THSNN_CosineSimilarity_forward(const NNModule module, const Tensor input1, const Tensor input2)\n{\n CATCH_TENSOR((*module)->as<torch::nn::CosineSimilarity>()->forward(*input1, *input2));\n}\n\nNNModule THSNN_PairwiseDistance_ctor(double p, double eps, bool keep_dim, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::PairwiseDistanceOptions()\n .p(p)\n .eps(eps)\n .keepdim(keep_dim);\n\n res = create_module<torch::nn::PairwiseDistanceImpl>(opts, outAsAnyModule);\n );\n\n}\n\nTensor THSNN_PairwiseDistance_forward(const NNModule module, const Tensor input1, const Tensor input2)\n{\n CATCH_TENSOR((*module)->as<torch::nn::PairwiseDistance>()->forward(*input1, *input2));\n}\n\nNNModule THSNN_RNN_ctor(const int64_t input_size, const int64_t hidden_size, const int64_t num_layers, const int64_t nonlinearity, const bool bias, const bool batchFirst, const double dropout, const bool bidirectional, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::RNNOptions(input_size, hidden_size)\n .num_layers(num_layers)\n .bias(bias)\n .batch_first(batchFirst)\n .dropout(dropout)\n .bidirectional(bidirectional);\n\n ApplyRnnActivation(opts, nonlinearity);\n\n res = create_module<torch::nn::RNNImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_RNN_forward(const NNModule module, const Tensor input1, const Tensor input2, Tensor* h_n)\n{\n Tensor output = nullptr;\n *h_n = nullptr;\n CATCH(\n auto result = (*module)->as<torch::nn::RNN>()->forward(*input1, (input2 ? *input2 : at::Tensor()));\n output = new torch::Tensor(std::get<0>(result));\n *h_n = new torch::Tensor(std::get<1>(result));\n );\n return output;\n}\n\nPackedSequence THSNN_RNN_forward_with_packed_input(const NNModule module, const PackedSequence input1, const Tensor input2, Tensor* h_n)\n{\n PackedSequence output = nullptr;\n *h_n = nullptr;\n CATCH(\n auto result = (*module)->as<torch::nn::RNN>()->forward_with_packed_input(*input1, (input2 ? *input2 : at::Tensor()));\n output = new torch::nn::utils::rnn::PackedSequence(std::get<0>(result));\n *h_n = new torch::Tensor(std::get<1>(result));\n );\n return output;\n}\n\nvoid THSNN_RNN_flatten_parameters(const NNModule module)\n{\n CATCH(\n (*module)->as<torch::nn::RNN>()->flatten_parameters();\n );\n}\n\nTensor THSNN_RNN_bias_ih(const NNModule module, const int64_t idx)\n{\n return get_bias_ih<torch::nn::RNN>(module, idx);\n}\n\nvoid THSNN_RNN_set_bias_ih(const NNModule module, const Tensor bias, const int64_t idx)\n{\n set_bias_ih<torch::nn::RNN>(module, bias, idx);\n}\n\nTensor THSNN_RNN_weight_ih(const NNModule module, const int64_t idx)\n{\n return get_weight_ih<torch::nn::RNN>(module, idx);\n}\n\nvoid THSNN_RNN_set_weight_ih(const NNModule module, const Tensor weight, const int64_t idx)\n{\n set_weight_ih<torch::nn::RNN>(module, weight, idx);\n}\n\nTensor THSNN_RNN_bias_hh(const NNModule module, const int64_t idx)\n{\n return get_bias_hh<torch::nn::RNN>(module, idx);\n}\n\nvoid THSNN_RNN_set_bias_hh(const NNModule module, const Tensor bias, const int64_t idx)\n{\n set_bias_hh<torch::nn::RNN>(module, bias, idx);\n}\n\nTensor THSNN_RNN_weight_hh(const NNModule module, const int64_t idx)\n{\n return get_weight_hh<torch::nn::RNN>(module, idx);\n}\n\nvoid THSNN_RNN_set_weight_hh(const NNModule module, const Tensor weight, const int64_t idx)\n{\n set_weight_hh<torch::nn::RNN>(module, weight, idx);\n}\n\n\nNNModule THSNN_GRU_ctor(const int64_t input_size, const int64_t hidden_size, const int64_t num_layers, const bool bias, const bool batchFirst, const double dropout, const bool bidirectional, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::GRUOptions(input_size, hidden_size)\n .num_layers(num_layers)\n .bias(bias)\n .batch_first(batchFirst)\n .dropout(dropout)\n .bidirectional(bidirectional);\n\n res = create_module<torch::nn::GRUImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_GRU_forward(const NNModule module, const Tensor input1, const Tensor input2, Tensor* h_n)\n{\n Tensor output = nullptr;\n *h_n = nullptr;\n CATCH(\n auto result = (*module)->as<torch::nn::GRU>()->forward(*input1, (input2 ? *input2 : at::Tensor()));\n output = new torch::Tensor(std::get<0>(result));\n *h_n = new torch::Tensor(std::get<1>(result));\n );\n return output;\n}\n\nPackedSequence THSNN_GRU_forward_with_packed_input(const NNModule module, const PackedSequence input1, const Tensor input2, Tensor* h_n)\n{\n PackedSequence output = nullptr;\n *h_n = nullptr;\n CATCH(\n auto result = (*module)->as<torch::nn::GRU>()->forward_with_packed_input(*input1, (input2 ? *input2 : at::Tensor()));\n output = new torch::nn::utils::rnn::PackedSequence(std::get<0>(result));\n *h_n = new torch::Tensor(std::get<1>(result));\n );\n return output;\n}\n\nvoid THSNN_GRU_flatten_parameters(const NNModule module)\n{\n CATCH(\n (*module)->as<torch::nn::GRU>()->flatten_parameters();\n );\n}\n\nNNModule THSNN_LSTM_ctor(const int64_t input_size, const int64_t hidden_size, const int64_t num_layers, const bool bias, const bool batchFirst, const double dropout, const bool bidirectional, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::LSTMOptions(input_size, hidden_size)\n .num_layers(num_layers)\n .bias(bias)\n .batch_first(batchFirst)\n .dropout(dropout)\n .bidirectional(bidirectional);\n\n res = create_module<torch::nn::LSTMImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_LSTM_forward(const NNModule module, const Tensor input1, const Tensor h0, const Tensor c0, Tensor* h_n, Tensor* c_n)\n{\n const std::tuple<at::Tensor, at::Tensor>& second_arg = (h0 == nullptr || c0 == nullptr) ? std::make_tuple(at::Tensor(), at::Tensor()) : std::make_tuple(*h0, *c0);\n\n Tensor output = nullptr;\n *h_n = nullptr;\n *c_n = nullptr;\n CATCH(\n auto result = (*module)->as<torch::nn::LSTM>()->forward(*input1, second_arg);\n output = new torch::Tensor(std::get<0>(result));\n *h_n = new torch::Tensor(std::get<0>(std::get<1>(result)));\n *c_n = new torch::Tensor(std::get<1>(std::get<1>(result)));\n );\n return output;\n}\n\nPackedSequence THSNN_LSTM_forward_with_packed_input(const NNModule module, const PackedSequence input1, const Tensor h0, const Tensor c0, Tensor* h_n, Tensor* c_n)\n{\n const std::tuple<at::Tensor, at::Tensor>& second_arg = (h0 == nullptr || c0 == nullptr) ? std::make_tuple(at::Tensor(), at::Tensor()) : std::make_tuple(*h0, *c0);\n\n PackedSequence output = nullptr;\n *h_n = nullptr;\n *c_n = nullptr;\n CATCH(\n auto result = (*module)->as<torch::nn::LSTM>()->forward_with_packed_input(*input1, second_arg);\n output = new torch::nn::utils::rnn::PackedSequence(std::get<0>(result));\n *h_n = new torch::Tensor(std::get<0>(std::get<1>(result)));\n *c_n = new torch::Tensor(std::get<1>(std::get<1>(result)));\n );\n return output;\n}\n\nvoid THSNN_LSTM_flatten_parameters(const NNModule module)\n{\n CATCH(\n (*module)->as<torch::nn::LSTM>()->flatten_parameters();\n );\n}\n\nNNModule THSNN_RNNCell_ctor(const int64_t input_size, const int64_t hidden_size, const int64_t nonlinearity, const bool bias, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::RNNCellOptions(input_size, hidden_size)\n .bias(bias);\n\n ApplyRnnActivation(opts, nonlinearity);\n\n res = create_module<torch::nn::RNNCellImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_RNNCell_forward(const NNModule module, const Tensor input1, const Tensor h0)\n{\n CATCH_TENSOR((*module)->as<torch::nn::RNNCell>()->forward(*input1, (h0 ? *h0 : at::Tensor())));\n}\n\nTensor THSNN_RNNCell_bias_ih(const NNModule module)\n{\n return get_bias_ih<torch::nn::RNNCell>(module);\n}\n\nvoid THSNN_RNNCell_set_bias_ih(const NNModule module, const Tensor bias)\n{\n set_bias_ih<torch::nn::RNNCell>(module, bias);\n}\n\nTensor THSNN_RNNCell_weight_ih(const NNModule module)\n{\n return get_weight_ih<torch::nn::RNNCell>(module);\n}\n\nvoid THSNN_RNNCell_set_weight_ih(const NNModule module, const Tensor weight)\n{\n set_weight_ih<torch::nn::RNNCell>(module, weight);\n}\n\nTensor THSNN_RNNCell_bias_hh(const NNModule module)\n{\n return get_bias_hh<torch::nn::RNNCell>(module);\n}\n\nvoid THSNN_RNNCell_set_bias_hh(const NNModule module, const Tensor bias)\n{\n set_bias_hh<torch::nn::RNNCell>(module, bias);\n}\n\nTensor THSNN_RNNCell_weight_hh(const NNModule module)\n{\n return get_weight_hh<torch::nn::RNNCell>(module);\n}\n\nvoid THSNN_RNNCell_set_weight_hh(const NNModule module, const Tensor weight)\n{\n set_weight_hh<torch::nn::RNNCell>(module, weight);\n}\n\nNNModule THSNN_GRUCell_ctor(const int64_t input_size, const int64_t hidden_size, const bool bias, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::GRUCellOptions(input_size, hidden_size)\n .bias(bias);\n\n res = create_module<torch::nn::GRUCellImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_GRUCell_forward(const NNModule module, const Tensor input1, const Tensor h0)\n{\n CATCH_TENSOR((*module)->as<torch::nn::GRUCell>()->forward(*input1, (h0 ? *h0 : at::Tensor())));\n}\n\nTensor THSNN_GRUCell_bias_ih(const NNModule module)\n{\n return get_bias_ih<torch::nn::GRUCell>(module);\n}\n\nvoid THSNN_GRUCell_set_bias_ih(const NNModule module, const Tensor bias)\n{\n set_bias_ih<torch::nn::GRUCell>(module, bias);\n}\n\nTensor THSNN_GRUCell_weight_ih(const NNModule module)\n{\n return get_weight_ih<torch::nn::GRUCell>(module);\n}\n\nvoid THSNN_GRUCell_set_weight_ih(const NNModule module, const Tensor weight)\n{\n set_weight_ih<torch::nn::GRUCell>(module, weight);\n}\n\nTensor THSNN_GRUCell_bias_hh(const NNModule module)\n{\n return get_bias_hh<torch::nn::GRUCell>(module);\n}\n\nvoid THSNN_GRUCell_set_bias_hh(const NNModule module, const Tensor bias)\n{\n set_bias_hh<torch::nn::GRUCell>(module, bias);\n}\n\nTensor THSNN_GRUCell_weight_hh(const NNModule module)\n{\n return get_weight_hh<torch::nn::GRUCell>(module);\n}\n\nvoid THSNN_GRUCell_set_weight_hh(const NNModule module, const Tensor weight)\n{\n set_weight_hh<torch::nn::GRUCell>(module, weight);\n}\n\nNNModule THSNN_LSTMCell_ctor(const int64_t input_size, const int64_t hidden_size, const bool bias, NNAnyModule* outAsAnyModule)\n{\n CATCH_RETURN_NNModule(\n auto opts = torch::nn::LSTMCellOptions(input_size, hidden_size)\n .bias(bias);\n\n res = create_module<torch::nn::LSTMCellImpl>(opts, outAsAnyModule);\n );\n}\n\nTensor THSNN_LSTMCell_forward(const NNModule module, const Tensor input1, const Tensor h0, const Tensor c0, Tensor* c_n)\n{\n const std::tuple<at::Tensor, at::Tensor>& second_arg = (h0 == nullptr || c0 == nullptr) ? std::make_tuple(at::Tensor(), at::Tensor()) : std::make_tuple(*h0, *c0);\n\n Tensor output;\n CATCH(\n auto result = (*module)->as<torch::nn::LSTMCell>()->forward(*input1, second_arg);\n output = new torch::Tensor(std::get<0>(result));\n *c_n = new torch::Tensor(std::get<1>(result));\n );\n\n return output;\n}\n\nTensor THSNN_LSTMCell_bias_ih(const NNModule module)\n{\n return get_bias_ih<torch::nn::LSTMCell>(module);\n}\n\nvoid THSNN_LSTMCell_set_bias_ih(const NNModule module, const Tensor bias)\n{\n set_bias_ih<torch::nn::LSTMCell>(module, bias);\n}\n\nTensor THSNN_LSTMCell_weight_ih(const NNModule module)\n{\n return get_weight_ih<torch::nn::LSTMCell>(module);\n}\n\nvoid THSNN_LSTMCell_set_weight_ih(const NNModule module, const Tensor weight)\n{\n set_weight_ih<torch::nn::LSTMCell>(module, weight);\n}\n\nTensor THSNN_LSTMCell_bias_hh(const NNModule module)\n{\n return get_bias_hh<torch::nn::LSTMCell>(module);\n}\n\nvoid THSNN_LSTMCell_set_bias_hh(const NNModule module, const Tensor bias)\n{\n set_bias_hh<torch::nn::LSTMCell>(module, bias);\n}\n\nTensor THSNN_LSTMCell_weight_hh(const NNModule module)\n{\n return get_weight_hh<torch::nn::LSTMCell>(module);\n}\n\nvoid THSNN_LSTMCell_set_weight_hh(const NNModule module, const Tensor weight)\n{\n set_weight_hh<torch::nn::LSTMCell>(module, weight);\n}\n\n\nNNModule THSNN_Sequential_ctor( /* NNAnyModule *submodules, const int length */ )\n{\n //std::vector<torch::nn::NamedAnyModule> modules;\n //for (int i = 0; i < length; i++)\n //{\n //\tmodules.push_back(*(*submodules[i])->as<torch::nn::NamedAnyModule>());\n //}\n\n auto mod = std::make_shared<torch::nn::SequentialImpl>( /* std::begin(modules), std::end(modules) */ );\n return new std::shared_ptr<torch::nn::Module>(mod);\n}\n\nvoid THSNN_Sequential_push_back(const NNModule module, const char *name, const NNAnyModule submodule)\n{\n CATCH (\n (*module)->as<torch::nn::Sequential>()->push_back(name, *(*submodule));\n )\n}\n\nTensor THSNN_Sequential_forward(const NNModule module, const Tensor tensor)\n{\n CATCH_TENSOR((*module)->as<torch::nn::Sequential>()->forward(*tensor));\n}\n\nTensor THSNN_one_hot(const Tensor self, const int64_t num_classes)\n{\n CATCH_RETURN_Tensor(\n res = ResultTensor(torch::nn::functional::one_hot(*self, num_classes));\n )\n}\n\nTensor THSNN_PackedSequence_data(PackedSequence sequence)\n{\n CATCH_TENSOR(sequence->data());\n}\n\nTensor THSNN_PackedSequence_batch_sizes(PackedSequence sequence)\n{\n CATCH_TENSOR(sequence->batch_sizes());\n}\n\nTensor THSNN_PackedSequence_sorted_indices(PackedSequence sequence)\n{\n CATCH_TENSOR(sequence->sorted_indices());\n}\n\nTensor THSNN_PackedSequence_unsorted_indices(PackedSequence sequence)\n{\n CATCH_TENSOR(sequence->unsorted_indices());\n}\n\nvoid THSNN_PackedSequence_dispose(PackedSequence sequence)\n{\n delete sequence;\n}\n\nPackedSequence THSNN_pack_padded_sequence(Tensor input, Tensor lengths, bool batch_first, bool enforce_sorted)\n{\n CATCH_RETURN(\n torch::nn::utils::rnn::PackedSequence*,\n nullptr,\n new torch::nn::utils::rnn::PackedSequence(\n torch::nn::utils::rnn::pack_padded_sequence(\n *input, *lengths, batch_first, enforce_sorted)));\n}\n\nvoid THSNN_pad_packed_sequence(PackedSequence sequence, bool batch_first, double padding_value, int64_t total_length, Tensor* res1_, Tensor* res2_)\n{\n Tensor& res1 = *res1_;\n Tensor& res2 = *res2_;\n CATCH_TENSORS_2(\n torch::nn::utils::rnn::pad_packed_sequence(\n *sequence, batch_first, padding_value,\n total_length == -1 ? torch::nullopt : c10::optional<int64_t>(total_length)));\n}\n\nTensor THSNN_pad_sequence(const Tensor* sequences, const int sequences_len, bool batch_first, double padding_value)\n{\n CATCH_TENSOR(\n torch::nn::utils::rnn::pad_sequence(\n toTensors<at::Tensor>((torch::Tensor**)sequences, sequences_len),\n batch_first, padding_value));\n}\n\nPackedSequence THSNN_pack_sequence(const Tensor* sequences, int sequences_len, bool enforce_sorted)\n{\n CATCH_RETURN(\n torch::nn::utils::rnn::PackedSequence*,\n nullptr,\n new torch::nn::utils::rnn::PackedSequence(\n torch::nn::utils::rnn::pack_sequence(\n toTensors<at::Tensor>((torch::Tensor**)sequences, sequences_len),\n enforce_sorted)));\n}\n\nTensor THSNN_fold(const Tensor input, const int64_t out1, const int64_t out2, const int64_t kernel1, const int64_t kernel2, const int64_t stride1, const int64_t stride2, const int64_t pad1, const int64_t pad2, const int64_t dil1, const int64_t dil2)\n{\n auto opts =\n torch::nn::functional::FoldFuncOptions({ out1, out2 }, {kernel1, kernel2})\n .dilation({dil1, dil2})\n .padding({pad1, pad2})\n .stride({ stride1, stride2 });\n\n CATCH_TENSOR(torch::nn::functional::fold(*input, opts));\n}\n\n\n\nTensor THSNN_unfold(const Tensor input, const int64_t kernel1, const int64_t kernel2, const int64_t stride1, const int64_t stride2, const int64_t pad1, const int64_t pad2, const int64_t dil1, const int64_t dil2)\n{\n auto opts =\n torch::nn::functional::UnfoldFuncOptions({ kernel1, kernel2 })\n .dilation({ dil1, dil2 })\n .padding({ pad1, pad2 })\n .stride({ stride1, stride2 });\n\n CATCH_TENSOR(torch::nn::functional::unfold(*input, opts));\n}\n\nTensor THSNN_scaled_dot_product_attention(const Tensor query, const Tensor key, const Tensor value, const Tensor attention_mask, double p, bool casual)\n{\n auto mask = attention_mask == nullptr ? c10::nullopt : c10::optional<at::Tensor>(*attention_mask);\n\n CATCH_TENSOR(torch::scaled_dot_product_attention(*query, *key, *value, mask, p, casual));\n}" }, { "alpha_fraction": 0.5144138932228088, "alphanum_fraction": 0.5206185579299927, "avg_line_length": 47.957942962646484, "blob_id": "3e2a4ebee17073f79e61ecc403dfa0f8ce7379d6", "content_id": "7b9a8cd2a8344acc097dc7239bc8ccdd77ae19a0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 10476, "license_type": "permissive", "max_line_length": 218, "num_lines": 214, "path": "/src/TorchVision/Ops/Misc.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchvision,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/vision/blob/a4f53308b2d0f1aa9191686e326f45c26053f686/torchvision/ops/misc.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/vision/blob/main/LICENSE\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.Runtime.CompilerServices;\nusing static TorchSharp.torch;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class ops\n {\n private static nn.Module<Tensor, Tensor> ConvNormActivation(\n long in_channels,\n long out_channels,\n long kernel_size = 3,\n long stride = 1,\n long? padding = null,\n long groups = 1,\n Func<long, nn.Module<Tensor, Tensor>>? norm_layer = null,\n Func<bool, nn.Module<Tensor, Tensor>>? activation_layer = null,\n long dilation = 1,\n bool inplace = true,\n bool? bias = null,\n int rank = 2)\n {\n if (padding == null) {\n padding = (kernel_size - 1) / 2 * dilation;\n }\n\n if (bias == null) {\n bias = norm_layer == null;\n }\n\n var layers = new List<nn.Module<Tensor, Tensor>>();\n if (rank == 2) {\n layers.Add(\n nn.Conv2d(\n in_channels,\n out_channels,\n kernelSize: kernel_size,\n stride: stride,\n padding: padding.Value,\n dilation: dilation,\n groups: groups,\n bias: bias.Value));\n } else if (rank == 3) {\n layers.Add(\n nn.Conv3d(\n in_channels,\n out_channels,\n kernelSize: kernel_size,\n stride: stride,\n padding: padding.Value,\n dilation: dilation,\n groups: groups,\n bias: bias.Value));\n } else {\n throw new ArgumentOutOfRangeException(\"rank must be 2 or 3.\");\n }\n\n if (norm_layer != null) {\n layers.Add(norm_layer(out_channels));\n }\n\n if (activation_layer != null) {\n layers.Add(activation_layer(inplace));\n }\n return nn.Sequential(layers);\n }\n\n /// <summary>\n /// Configurable block used for Convolution2d-Normalization-Activation blocks.\n /// </summary>\n /// <param name=\"in_channels\">Number of channels in the input image</param>\n /// <param name=\"out_channels\">Number of channels produced by the Convolution-Normalization-Activation block</param>\n /// <param name=\"kernel_size\">Size of the convolving kernel.</param>\n /// <param name=\"stride\">Stride of the convolution.</param>\n /// <param name=\"padding\">Padding added to all four sides of the input. Default: null, in which case it will calculated as ``padding = (kernel_size - 1) // 2 * dilation``</param>\n /// <param name=\"groups\">Number of blocked connections from input channels to output channels.</param>\n /// <param name=\"norm_layer\">Norm layer that will be stacked on top of the convolution layer. If ``null`` this layer wont be used.</param>\n /// <param name=\"activation_layer\">Activation function which will be stacked on top of the normalization layer (if not null), otherwise on top of the conv layer. If ``null`` this layer wont be used.</param>\n /// <param name=\"dilation\">Spacing between kernel elements.</param>\n /// <param name=\"inplace\">Parameter for the activation layer, which can optionally do the operation in-place.</param>\n /// <param name=\"bias\">Whether to use bias in the convolution layer. By default, biases are included if ``norm_layer is null``.</param>\n public static nn.Module<Tensor, Tensor> Conv2dNormActivation(\n long in_channels,\n long out_channels,\n long kernel_size = 3,\n long stride = 1,\n long? padding = null,\n long groups = 1,\n Func<long, nn.Module<Tensor, Tensor>>? norm_layer = null,\n Func<bool, nn.Module<Tensor, Tensor>>? activation_layer = null,\n long dilation = 1,\n bool inplace = true,\n bool? bias = null)\n {\n return ConvNormActivation(\n in_channels,\n out_channels,\n kernel_size,\n stride,\n padding,\n groups,\n norm_layer,\n activation_layer,\n dilation,\n inplace,\n bias,\n rank: 2);\n }\n\n /// <summary>\n /// Configurable block used for Convolution3d-Normalization-Activation blocks.\n /// </summary>\n /// <param name=\"in_channels\">Number of channels in the input image</param>\n /// <param name=\"out_channels\">Number of channels produced by the Convolution-Normalization-Activation block</param>\n /// <param name=\"kernel_size\">Size of the convolving kernel.</param>\n /// <param name=\"stride\">Stride of the convolution.</param>\n /// <param name=\"padding\">Padding added to all four sides of the input. Default: null, in which case it will calculated as ``padding = (kernel_size - 1) // 2 * dilation``</param>\n /// <param name=\"groups\">Number of blocked connections from input channels to output channels.</param>\n /// <param name=\"norm_layer\">Norm layer that will be stacked on top of the convolution layer. If ``null`` this layer wont be used.</param>\n /// <param name=\"activation_layer\">Activation function which will be stacked on top of the normalization layer (if not null), otherwise on top of the conv layer. If ``null`` this layer wont be used.</param>\n /// <param name=\"dilation\">Spacing between kernel elements.</param>\n /// <param name=\"inplace\">Parameter for the activation layer, which can optionally do the operation in-place.</param>\n /// <param name=\"bias\">Whether to use bias in the convolution layer. By default, biases are included if ``norm_layer is null``.</param>\n public static nn.Module<Tensor, Tensor> Conv3dNormActivation(\n long in_channels,\n long out_channels,\n long kernel_size = 3,\n long stride = 1,\n long? padding = null,\n long groups = 1,\n Func<long, nn.Module<Tensor, Tensor>>? norm_layer = null,\n Func<bool, nn.Module<Tensor, Tensor>>? activation_layer = null,\n long dilation = 1,\n bool inplace = true,\n bool? bias = null)\n {\n return ConvNormActivation(\n in_channels,\n out_channels,\n kernel_size,\n stride,\n padding,\n groups,\n norm_layer,\n activation_layer,\n dilation,\n inplace,\n bias,\n rank: 3);\n }\n\n\n /// <summary>\n /// This block implements the multi-layer perceptron (MLP) module.\n /// </summary>\n /// <param name=\"in_channels\">Number of channels in the input image</param>\n /// <param name=\"hidden_channels\">List of the hidden channel dimensions</param>\n /// <param name=\"norm_layer\">Norm layer that will be stacked on top of the linear layer. If null, will be ignored</param>\n /// <param name=\"activation_layer\">Activation function which will be stacked on top of the normalization layer. Defaults to ReLU.</param>\n /// <param name=\"inplace\">Parameter for the activation layer, which can optionally do the operation in-place.</param>\n /// <param name=\"bias\">Whether to use bias in the linear and dropout layers.</param>\n /// <param name=\"dropout\">The probability for the dropout layer.</param>\n /// <returns></returns>\n public static Modules.Sequential MLP(\n long in_channels,\n IList<int> hidden_channels,\n Func<int, nn.Module<Tensor, Tensor>>? norm_layer = null,\n Func<nn.Module<Tensor, Tensor>>? activation_layer = null,\n bool inplace = false,\n bool bias = true,\n double dropout = 0.0\n )\n {\n if (activation_layer == null) {\n activation_layer = () => nn.ReLU(inplace);\n }\n\n var layers = new List<nn.Module<Tensor, Tensor>>();\n var in_dim = in_channels;\n for (int i = 0; i < hidden_channels.Count-1; i++) {\n var hidden_dim = hidden_channels[i];\n layers.Add(nn.Linear(in_dim, hidden_dim, hasBias: bias));\n if (norm_layer != null) {\n layers.Add(norm_layer(hidden_dim));\n }\n layers.Add(activation_layer());\n layers.Add(nn.Dropout(dropout, inplace));\n in_dim = hidden_dim;\n }\n\n layers.Add(nn.Linear(in_dim, hidden_channels[hidden_channels.Count-1], hasBias: bias));\n layers.Add(nn.Dropout(dropout, inplace));\n\n return nn.Sequential(layers);\n }\n }\n }\n}" }, { "alpha_fraction": 0.49920737743377686, "alphanum_fraction": 0.5010274648666382, "avg_line_length": 42.67179489135742, "blob_id": "a078e914274425b9efeaab77754b2f5737725b3f", "content_id": "59b98e91b1d01a95029e2e8072c63105b6d259c0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 34066, "license_type": "permissive", "max_line_length": 178, "num_lines": 780, "path": "/src/TorchSharp/Special.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n public static partial class torch\n {\n public static class special\n {\n /// <summary>\n /// Airy function.\n /// </summary>\n /// <param name=\"input\">Input tensor</param>\n /// <param name=\"out\">Optional output tensor, will be modified if present.</param>\n /// <returns></returns>\n public static Tensor airy_ai(Tensor input, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_airy_ai(input.Handle) :\n THSSpecial_airy_ai_out(input.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Bessel function of the first kind of order 0.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"out\">An optional output tensor, which will be modified if present.</param>\n public static Tensor bessel_j0(Tensor input, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_bessel_j0(input.Handle) :\n THSSpecial_bessel_j0_out(input.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Bessel function of the first kind of order 1.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"out\">An optional output tensor, which will be modified if present.</param>\n public static Tensor bessel_j1(Tensor input, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_bessel_j1(input.Handle) :\n THSSpecial_bessel_j1_out(input.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Bessel function of the second kind of order 1.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"out\">An optional output tensor, which will be modified if present.</param>\n public static Tensor bessel_y0(Tensor input, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_bessel_y0(input.Handle) :\n THSSpecial_bessel_y0_out(input.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Bessel function of the second kind of order 1.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"out\">An optional output tensor, which will be modified if present.</param>\n public static Tensor bessel_y1(Tensor input, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_bessel_y1(input.Handle) :\n THSSpecial_bessel_y1_out(input.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Modified Bessel function of the first kind of order 0.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"out\">An optional output tensor, which will be modified if present.</param>\n public static Tensor modified_bessel_i0(Tensor input, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_modified_bessel_i0(input.Handle) :\n THSSpecial_modified_bessel_i0_out(input.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Modified Bessel function of the first kind of order 1.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"out\">An optional output tensor, which will be modified if present.</param>\n public static Tensor modified_bessel_i1(Tensor input, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_modified_bessel_i1(input.Handle) :\n THSSpecial_modified_bessel_i1_out(input.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Modified Bessel function of the second kind of order 1.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"out\">An optional output tensor, which will be modified if present.</param>\n public static Tensor modified_bessel_k0(Tensor input, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_modified_bessel_k0(input.Handle) :\n THSSpecial_modified_bessel_k0_out(input.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Modified Bessel function of the second kind of order 1.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"out\">An optional output tensor, which will be modified if present.</param>\n public static Tensor modified_bessel_k1(Tensor input, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_modified_bessel_k1(input.Handle) :\n THSSpecial_modified_bessel_k1_out(input.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Scaled modified Bessel function of the second kind of order 0\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"out\">An optional output tensor, which will be modified if present.</param>\n public static Tensor scaled_modified_bessel_k0(Tensor input, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_scaled_modified_bessel_k0(input.Handle) :\n THSSpecial_scaled_modified_bessel_k0_out(input.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Scaled modified Bessel function of the second kind of order 1\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"out\">An optional output tensor, which will be modified if present.</param>\n public static Tensor scaled_modified_bessel_k1(Tensor input, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_scaled_modified_bessel_k1(input.Handle) :\n THSSpecial_scaled_modified_bessel_k1_out(input.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Bessel function of the first kind of order 0.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"out\">An optional output tensor, which will be modified if present.</param>\n public static Tensor spherical_bessel_j0(Tensor input, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_spherical_bessel_j0(input.Handle) :\n THSSpecial_spherical_bessel_j0_out(input.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the Chebyshev polynomial of the first kind.\n ///\n /// See: https://en.wikipedia.org/wiki/Chebyshev_polynomials\n /// </summary>\n /// <param name=\"x\">The input tensor.</param>\n /// <param name=\"n\">n</param>\n /// <param name=\"out\">An optional output tensor.</param>\n public static Tensor chebyshev_polynomial_t(Tensor x, Tensor n, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_chebyshev_polynomial_t(x.Handle, n.Handle) :\n THSSpecial_chebyshev_polynomial_t_out(x.Handle, n.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n\n /// <summary>\n /// Computes the Chebyshev polynomial of the second kind.\n ///\n /// See: https://en.wikipedia.org/wiki/Chebyshev_polynomials\n /// </summary>\n /// <param name=\"x\">The input tensor.</param>\n /// <param name=\"n\">n</param>\n /// <param name=\"out\">An optional output tensor.</param>\n public static Tensor chebyshev_polynomial_u(Tensor x, Tensor n, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_chebyshev_polynomial_u(x.Handle, n.Handle) :\n THSSpecial_chebyshev_polynomial_u_out(x.Handle, n.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the Chebyshev polynomial of the third kind.\n ///\n /// See: https://en.wikipedia.org/wiki/Chebyshev_polynomials\n /// </summary>\n /// <param name=\"x\">The input tensor.</param>\n /// <param name=\"n\">n</param>\n /// <param name=\"out\">An optional output tensor.</param>\n public static Tensor chebyshev_polynomial_v(Tensor x, Tensor n, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_chebyshev_polynomial_v(x.Handle, n.Handle) :\n THSSpecial_chebyshev_polynomial_v_out(x.Handle, n.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the Chebyshev polynomial of the fourth kind.\n ///\n /// See: https://en.wikipedia.org/wiki/Chebyshev_polynomials\n /// </summary>\n /// <param name=\"x\">The input tensor.</param>\n /// <param name=\"n\">n</param>\n /// <param name=\"out\">An optional output tensor.</param>\n public static Tensor chebyshev_polynomial_w(Tensor x, Tensor n, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_chebyshev_polynomial_w(x.Handle, n.Handle) :\n THSSpecial_chebyshev_polynomial_w_out(x.Handle, n.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the Chebyshev polynomial of the first kind.\n ///\n /// See: https://en.wikipedia.org/wiki/Chebyshev_polynomials\n /// </summary>\n /// <param name=\"x\">The input tensor.</param>\n /// <param name=\"n\">n</param>\n /// <param name=\"out\">An optional output tensor.</param>\n public static Tensor shifted_chebyshev_polynomial_t(Tensor x, Tensor n, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_shifted_chebyshev_polynomial_t(x.Handle, n.Handle) :\n THSSpecial_shifted_chebyshev_polynomial_t_out(x.Handle, n.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n\n /// <summary>\n /// Computes the Chebyshev polynomial of the second kind.\n ///\n /// See: https://en.wikipedia.org/wiki/Chebyshev_polynomials\n /// </summary>\n /// <param name=\"x\">The input tensor.</param>\n /// <param name=\"n\">n</param>\n /// <param name=\"out\">An optional output tensor.</param>\n public static Tensor shifted_chebyshev_polynomial_u(Tensor x, Tensor n, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_shifted_chebyshev_polynomial_u(x.Handle, n.Handle) :\n THSSpecial_shifted_chebyshev_polynomial_u_out(x.Handle, n.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the Chebyshev polynomial of the third kind.\n ///\n /// See: https://en.wikipedia.org/wiki/Chebyshev_polynomials\n /// </summary>\n /// <param name=\"x\">The input tensor.</param>\n /// <param name=\"n\">n</param>\n /// <param name=\"out\">An optional output tensor.</param>\n public static Tensor shifted_chebyshev_polynomial_v(Tensor x, Tensor n, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_shifted_chebyshev_polynomial_v(x.Handle, n.Handle) :\n THSSpecial_shifted_chebyshev_polynomial_v_out(x.Handle, n.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the Chebyshev polynomial of the fourth kind.\n ///\n /// See: https://en.wikipedia.org/wiki/Chebyshev_polynomials\n /// </summary>\n /// <param name=\"x\">The input tensor.</param>\n /// <param name=\"n\">n</param>\n /// <param name=\"out\">An optional output tensor.</param>\n public static Tensor shifted_chebyshev_polynomial_w(Tensor x, Tensor n, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_shifted_chebyshev_polynomial_w(x.Handle, n.Handle) :\n THSSpecial_shifted_chebyshev_polynomial_w_out(x.Handle, n.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Probabilist's Hermite polynomials.\n ///\n /// See: https://en.wikipedia.org/wiki/Hermite_polynomials\n /// </summary>\n /// <param name=\"x\">The input tensor.</param>\n /// <param name=\"n\">n</param>\n /// <param name=\"out\">An optional output tensor.</param>\n public static Tensor hermite_polynomial_h(Tensor x, Tensor n, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_hermite_polynomial_h(x.Handle, n.Handle) :\n THSSpecial_hermite_polynomial_h_out(x.Handle, n.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Physicists's Hermite polynomials.\n ///\n /// See: https://en.wikipedia.org/wiki/Hermite_polynomials\n /// </summary>\n /// <param name=\"x\">The input tensor.</param>\n /// <param name=\"n\">n</param>\n /// <param name=\"out\">An optional output tensor.</param>\n public static Tensor hermite_polynomial_he(Tensor x, Tensor n, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_hermite_polynomial_he(x.Handle, n.Handle) :\n THSSpecial_hermite_polynomial_he_out(x.Handle, n.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Laguerre polynomials\n /// \n /// See: https://en.wikipedia.org/wiki/Laguerre_polynomials\n /// </summary>\n /// <param name=\"x\">The input tensor.</param>\n /// <param name=\"n\">n</param>\n /// <param name=\"out\">An optional output tensor.</param>\n /// <returns></returns>\n public static Tensor laguerre_polynomial_l(Tensor x, Tensor n, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_laguerre_polynomial_l(x.Handle, n.Handle) :\n THSSpecial_laguerre_polynomial_l_out(x.Handle, n.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Legendre polynomials\n /// \n /// https://en.wikipedia.org/wiki/Legendre_polynomials\n /// </summary>\n /// <param name=\"x\">The input tensor.</param>\n /// <param name=\"n\">n</param>\n /// <param name=\"out\">An optional output tensor.</param>\n public static Tensor legendre_polynomial_p(Tensor x, Tensor n, Tensor @out = null)\n {\n var res = @out is null ?\n THSSpecial_legendre_polynomial_p(x.Handle, n.Handle) :\n THSSpecial_legendre_polynomial_p_out(x.Handle, n.Handle, @out.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the entropy on input, elementwise.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor entr(Tensor input)\n {\n var res = THSSpecial_entr(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the error function of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor erf(Tensor input)\n {\n var res = THSSpecial_erf(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the complementary error function of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor erfc(Tensor input)\n {\n var res = THSSpecial_erfc(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the scaled complementary error function of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor erfcx(Tensor input)\n {\n var res = THSSpecial_erfc(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the inverse error function of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor erfinv(Tensor input)\n {\n var res = THSSpecial_erfinv(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the expit (also known as the logistic sigmoid function) of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor expit(Tensor input)\n {\n var res = THSSpecial_expit(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the exponential of the elements minus 1 of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor expm1(Tensor input)\n {\n var res = THSSpecial_expm1(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the base two exponential function of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor exp2(Tensor input)\n {\n var res = THSSpecial_exp2(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the natural logarithm of the absolute value of the gamma function on input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor gammaln(Tensor input)\n {\n var res = THSSpecial_gammaln(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the regularized lower incomplete gamma function.\n /// </summary>\n /// <param name=\"input\">The first non-negative input tensor</param>\n /// <param name=\"other\">The second non-negative input tensor</param>\n /// <returns></returns>\n public static Tensor gammainc(Tensor input, Tensor other)\n {\n var res = THSSpecial_gammainc(input.Handle, other.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the regularized upper incomplete gamma function.\n /// </summary>\n /// <param name=\"input\">The first non-negative input tensor</param>\n /// <param name=\"other\">The second non-negative input tensor</param>\n /// <returns></returns>\n public static Tensor gammaincc(Tensor input, Tensor other)\n {\n var res = THSSpecial_gammaincc(input.Handle, other.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the n-th derivative of the digamma function on input.\n /// </summary>\n /// <param name=\"n\">The order of the polygamma function</param>\n /// <param name=\"input\">The second non-negative input tensor</param>\n /// <returns></returns>\n public static Tensor polygamma(long n, Tensor input)\n {\n var res = THSSpecial_polygamma(n, input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the multivariate log-gamma function with dimension pp element-wise.\n /// </summary>\n /// <param name=\"input\">The tensor to compute the multivariate log-gamma function</param>\n /// <param name=\"p\">The number of dimensions</param>\n /// <returns></returns>\n public static Tensor multigammaln(Tensor input, long p)\n {\n var res = THSSpecial_multigammaln(input.Handle, p);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the logarithmic derivative of the gamma function on input.\n /// </summary>\n /// <param name=\"input\">The second non-negative input tensor</param>\n /// <returns></returns>\n public static Tensor digamma(Tensor input)\n {\n var res = THSSpecial_digamma(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the logarithmic derivative of the gamma function on input.\n /// </summary>\n /// <param name=\"input\">The second non-negative input tensor</param>\n public static Tensor psi(Tensor input) => digamma(input);\n\n /// <summary>\n /// Computes the zeroth order modified Bessel function of the first kind for each element of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor i0(Tensor input)\n {\n var res = THSSpecial_i0(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the exponentially scaled zeroth order modified Bessel function of the first kind (as defined below) for each element of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor i0e(Tensor input)\n {\n var res = THSSpecial_i0e(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the first order modified Bessel function of the first kind for each element of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor i1(Tensor input)\n {\n var res = THSSpecial_i1(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the exponentially scaled first order modified Bessel function of the first kind (as defined below) for each element of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor i1e(Tensor input)\n {\n var res = THSSpecial_i1e(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Returns a new tensor with the logit of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor logit(Tensor input)\n {\n var res = THSSpecial_logit(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Returns a new tensor with the logit of the elements of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">A dimension along which log_softmax will be computed.</param>\n /// <param name=\"dtype\">The desired data type of returned tensor.</param>\n /// <returns></returns>\n public static Tensor log_softmax(Tensor input, long dim, ScalarType? dtype = null)\n {\n var dt = dtype.HasValue ? dtype.Value : input.dtype;\n var res = THSSpecial_log_softmax(input.Handle, dim, (sbyte)dt);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the area under the standard Gaussian probability density function, integrated from minus infinity to input, elementwise.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor ndtr(Tensor input)\n {\n var res = THSSpecial_ndtr(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the argument, x, for which the area under the Gaussian probability density function (integrated from minus infinity to x) is equal to input, elementwise.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor ndtri(Tensor input)\n {\n var res = THSSpecial_ndtri(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the normalized sinc of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <returns></returns>\n public static Tensor sinc(Tensor input)\n {\n var res = THSSpecial_sinc(input.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Alias for torch.special.expit()\n /// </summary>\n /// <returns></returns>\n public static Tensor sigmoid(Tensor input) => input.sigmoid();\n\n /// <summary>\n /// Alias for torch.special.expit()\n /// </summary>\n /// <returns></returns>\n public static Tensor sigmoid_(Tensor input) => input.sigmoid_();\n\n /// <summary>\n /// Computes the softmax function for the input tensor.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"dim\">A dimension along which softmax will be computed.</param>\n /// <param name=\"dtype\">The desired data type of returned tensor.</param>\n /// <returns></returns>\n public static Tensor softmax(Tensor input, long dim, ScalarType? dtype = null)\n {\n var dt = dtype.HasValue ? dtype.Value : input.dtype;\n var res = THSSpecial_softmax(input.Handle, dim, (sbyte)dt);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes input * log1p(other). Similar to SciPy’s scipy.special.xlog1py.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"other\"></param>\n /// <returns></returns>\n public static Tensor xlog1py(Tensor input, Tensor other)\n {\n var res = THSSpecial_xlog1py(input.Handle, other.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the Hurwitz zeta function, elementwise.\n /// </summary>\n /// <param name=\"x\">The input tensor corresponding to x</param>\n /// <param name=\"q\">The input tensor corresponding to q</param>\n /// <remarks>The Riemann zeta function corresponds to the case when q = 1.</remarks>\n public static Tensor zeta(Tensor x, Tensor q)\n {\n var res = THSSpecial_zeta(x.Handle, q.Handle);\n if (res == IntPtr.Zero)\n torch.CheckForErrors();\n return new Tensor(res);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5192856192588806, "alphanum_fraction": 0.5412377715110779, "avg_line_length": 40.78238296508789, "blob_id": "2109429199f404fab762abf1343a6286414df5ea", "content_id": "821b521c2f99c9bc3862dac13c50f42ba722d558", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8063, "license_type": "permissive", "max_line_length": 213, "num_lines": 193, "path": "/test/TorchSharpTest/TestDataLoader.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System.Collections.Generic;\nusing Xunit;\n\n\nnamespace TorchSharp\n{\n [Collection(\"Sequential\")]\n public class TestDataLoader\n {\n private class TestDataset : torch.utils.data.Dataset\n {\n public override long Count { get; } = 10;\n public override Dictionary<string, torch.Tensor> GetTensor(long index)\n {\n return new() {{\"data\", torch.tensor(1)}, {\"label\", torch.tensor(13)}, {\"index\", torch.tensor(index)}};\n }\n }\n\n [Fact]\n public void DatasetTest()\n {\n using var dataset = new TestDataset();\n var d = dataset.GetTensor(0);\n Assert.True(d.ContainsKey(\"data\"));\n Assert.True(d.ContainsKey(\"index\"));\n Assert.True(d.ContainsKey(\"label\"));\n\n Assert.Equal(d[\"data\"], torch.tensor(1));\n Assert.Equal(d[\"label\"], torch.tensor(13));\n Assert.Equal(d[\"index\"], torch.tensor(0L));\n }\n\n [Fact]\n public void TensorDatasetTest()\n {\n var x = torch.randn(4, 12);\n var y = torch.randn(4, 16);\n using var dataset = torch.utils.data.TensorDataset(x, y);\n Assert.Equal(2, dataset.Count);\n\n var d = dataset.GetTensor(0);\n\n Assert.Equal(2, d.Count);\n Assert.Equal(x[0], d[0]);\n Assert.Equal(y[0], d[1]);\n }\n\n // Cannot assert index because ConcurrentBag append tensors randomly\n [Fact]\n public void DataLoaderTest1()\n {\n using var dataset = new TestDataset();\n using var dataloader = new torch.utils.data.DataLoader(dataset, 2, false, torch.CPU);\n var iterator = dataloader.GetEnumerator();\n Assert.True(iterator.MoveNext());\n Assert.Equal(iterator.Current[\"data\"], torch.tensor(rawArray: new[]{1L, 1L}, dimensions: new[]{2L}, dtype: torch.ScalarType.Int32));\n Assert.Equal(iterator.Current[\"label\"], torch.tensor(rawArray: new[]{13L, 13L}, dimensions: new[]{2L}, dtype: torch.ScalarType.Int32));\n Assert.Equal(iterator.Current[\"index\"].ToString(TensorStringStyle.Julia), torch.tensor(rawArray: new[]{0L, 1L}, dimensions: new[]{2L}, dtype: torch.ScalarType.Int64).ToString(TensorStringStyle.Julia));\n iterator.Dispose();\n }\n\n [Fact]\n public void DataLoaderTest2()\n {\n using var dataset = new TestDataset();\n using var dataloader = new torch.utils.data.DataLoader(dataset, 2, false, torch.CPU);\n long idx = 0;\n foreach (var x in dataloader) {\n Assert.Equal(x[\"data\"], torch.tensor(new[]{1, 1}, new[]{2L}));\n Assert.Equal(x[\"index\"], torch.tensor(new[]{idx++, idx++}, new[]{2L}));\n }\n }\n\n [Fact]\n public void DataLoaderTest3()\n {\n using var dataset = new TestDataset();\n {\n using var dataloader = new torch.utils.data.DataLoader(dataset, 3, false, torch.CPU);\n Assert.Equal(4, dataloader.Count);\n }\n {\n using var dataloader = new torch.utils.data.DataLoader(dataset, 3, false, torch.CPU, drop_last: true);\n Assert.Equal(3, dataloader.Count);\n }\n {\n using var dataloader = new torch.utils.data.DataLoader(dataset, 2, false, torch.CPU, drop_last: true);\n Assert.Equal(5, dataloader.Count);\n }\n }\n\n private const int stressBatchSize = 32;\n\n private class LargeTestDataset : torch.utils.data.Dataset\n {\n public override long Count { get; } = 2*stressBatchSize;\n public override Dictionary<string, torch.Tensor> GetTensor(long index)\n {\n return new() { { \"data\", torch.rand(3, 512, 512) }, { \"label\", torch.tensor(16) }, { \"index\", torch.tensor(index) } };\n }\n }\n\n [Fact]\n public void BigDataLoaderTest3()\n {\n using var dataset = new LargeTestDataset();\n using var dataloader = new torch.utils.data.DataLoader(dataset, stressBatchSize, false, torch.CPU);\n var iter = dataloader.GetEnumerator();\n iter.MoveNext();\n var x = iter.Current;\n Assert.Equal(new long[] { stressBatchSize, 3, 512, 512 }, x[\"data\"].shape);\n iter.MoveNext();\n x = iter.Current;\n Assert.Equal(new long[] { stressBatchSize, 3, 512, 512 }, x[\"data\"].shape);\n Assert.False(iter.MoveNext());\n iter.Dispose();\n }\n\n [Fact]\n public void MultiThreadDataLoaderTest1()\n {\n using var dataset = new TestDataset();\n using var dataloader = new torch.utils.data.DataLoader(dataset, 4, false, torch.CPU, num_worker: 2);\n var iter = dataloader.GetEnumerator();\n iter.MoveNext();\n var x = iter.Current;\n Assert.Equal(x[\"data\"], torch.tensor(new[]{1, 1, 1, 1}, new[]{4L}));\n Assert.Equal(x[\"index\"], torch.tensor(new[]{0L, 1, 2, 3}, new[]{4L}));\n iter.MoveNext();\n x = iter.Current;\n Assert.Equal(x[\"data\"], torch.tensor(new[]{1, 1, 1, 1}, new[]{4L}));\n Assert.Equal(x[\"index\"], torch.tensor(new[]{4L, 5, 6, 7}, new[]{4L}));\n iter.MoveNext();\n x = iter.Current;\n Assert.Equal(x[\"data\"], torch.tensor(new[]{1, 1}, new[]{2L}));\n Assert.Equal(x[\"index\"], torch.tensor(new[]{8L, 9}, new[]{2L}));\n iter.Dispose();\n }\n\n [Fact]\n public void MultiThreadDataLoaderTest2()\n {\n using var dataset = new TestDataset();\n using var dataloader = new torch.utils.data.DataLoader(dataset, 5, false, torch.CPU, num_worker: 2);\n var iter = dataloader.GetEnumerator();\n iter.MoveNext();\n var x = iter.Current;\n Assert.Equal(x[\"data\"], torch.tensor(new[]{1, 1, 1, 1, 1}, new[]{5L}));\n Assert.Equal(x[\"index\"], torch.tensor(new[]{0L, 1, 2, 3, 4}, new[]{5L}));\n iter.MoveNext();\n x = iter.Current;\n Assert.Equal(x[\"data\"], torch.tensor(new[]{1, 1, 1, 1, 1}, new[]{5L}));\n Assert.Equal(x[\"index\"], torch.tensor(new[]{5L, 6, 7, 8, 9}, new[]{5L}));\n Assert.False(iter.MoveNext());\n iter.Dispose();\n }\n\n [Fact]\n public void MultiThreadDataLoaderTest3()\n {\n using var dataset = new TestDataset();\n using var dataloader = new torch.utils.data.DataLoader(dataset, 5, false, torch.CPU, num_worker: 11);\n var iter = dataloader.GetEnumerator();\n iter.MoveNext();\n var x = iter.Current;\n Assert.Equal(x[\"data\"], torch.tensor(new[]{1, 1, 1, 1, 1}, new[]{5L}));\n Assert.Equal(x[\"index\"], torch.tensor(new[]{0L, 1, 2, 3, 4}, new[]{5L}));\n iter.MoveNext();\n x = iter.Current;\n Assert.Equal(x[\"data\"], torch.tensor(new[]{1, 1, 1, 1, 1}, new[]{5L}));\n Assert.Equal(x[\"index\"], torch.tensor(new[]{5L, 6, 7, 8, 9}, new[]{5L}));\n Assert.False(iter.MoveNext());\n iter.Dispose();\n }\n\n [Fact]\n public void CustomSeedTest()\n {\n using var dataset = new TestDataset();\n using var dataloader = new torch.utils.data.DataLoader(dataset, 2, true, seed: 1);\n using var dataloader2 = new torch.utils.data.DataLoader(dataset, 2, true, seed: 1);\n var iterator = dataloader.GetEnumerator();\n var iterator2 = dataloader2.GetEnumerator();\n iterator.MoveNext();\n iterator2.MoveNext();\n Assert.Equal(iterator.Current, iterator2.Current);\n iterator.Dispose();\n iterator2.Dispose();\n }\n }\n}" }, { "alpha_fraction": 0.5452775359153748, "alphanum_fraction": 0.5530672073364258, "avg_line_length": 34.41379165649414, "blob_id": "e99e77e99bf1d20ce47d658288da2bcb2f12f8c1", "content_id": "8837d1ce2f1c8b05fee686c02b56ade6f2ffa528", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1027, "license_type": "permissive", "max_line_length": 130, "num_lines": 29, "path": "/test/TorchSharpTest/TestTorchHub.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System.Reflection;\nusing Xunit;\n\n#nullable enable\nnamespace TorchSharp\n{\n public class TestTorchHub\n {\n [Fact]\n public void TestProgressBar()\n {\n var type = typeof(torch.hub);\n foreach (var method in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Static)) {\n if (method.Name == \"_create_progress_bar\") {\n var result = (IProgressBar?)method.Invoke(null, new object[] { false });\n Assert.NotNull(result);\n Assert.Equal(\"TorchSharp.ConsoleProgressBar\", result.GetType().FullName);\n Assert.Equal(0, result.Value);\n Assert.Null(result.Maximum);\n result.Value = 100;\n result.Maximum = 50;\n Assert.Equal(50, result.Value);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5553908944129944, "alphanum_fraction": 0.5569749474525452, "avg_line_length": 46.73170852661133, "blob_id": "42411a79c6e947feaf3d27d062f3225fb9fa9b1d", "content_id": "7ae4007cd043ceb54e26361084293fdb9a35f4d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 19594, "license_type": "permissive", "max_line_length": 211, "num_lines": 410, "path": "/src/TorchSharp/NN/Sequential.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using System.Runtime.CompilerServices;\n using Modules;\n using TorchSharp.PInvoke;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a Sequential module.\n /// </summary>\n public class Sequential : torch.nn.Module<Tensor, Tensor>\n {\n public Sequential append(string name, torch.nn.IModule<Tensor, Tensor> module)\n {\n Add(name, module);\n return this;\n }\n\n internal void Add(string name, torch.nn.IModule<Tensor, Tensor> sm)\n {\n var submodule = (torch.nn.Module)sm;\n\n Debug.Assert(!handle.IsInvalid);\n Debug.Assert(!submodule.handle.IsInvalid);\n\n // Keep the sub-module alive for at least as long as the Sequential object is alive.\n _modules.Add(sm);\n _names.Add(name);\n }\n\n public Sequential append(torch.nn.IModule<Tensor, Tensor> module)\n {\n var name = _modules.Count.ToString();\n Add(name, module);\n return this;\n }\n\n internal void Add(torch.nn.IModule<Tensor, Tensor> module)\n {\n var name = _modules.Count.ToString();\n Add(name, module);\n }\n\n public override IEnumerable<(string name, Parameter parameter)> named_parameters(bool recurse = true)\n {\n if (!recurse) yield break;\n\n var seen = new HashSet<IntPtr>();\n seen.Add(IntPtr.Zero); // Ignore invalid parameters\n\n for (var i = 0; i < _names.Count; i++) {\n foreach (var (n, p) in ((torch.nn.Module)_modules[i]).named_parameters(true)) {\n if (seen.Contains(p.handle)) continue;\n seen.Add(p.handle);\n yield return ($\"{_names[i]}.{n}\", p);\n }\n }\n }\n\n public override IEnumerable<(string name, Tensor buffer)> named_buffers(bool recurse = true)\n {\n if (!recurse) yield break;\n\n var seen = new HashSet<IntPtr>();\n seen.Add(IntPtr.Zero); // Ignore invalid buffers\n\n for (var i = 0; i < _names.Count; i++) {\n foreach (var (n, p) in ((torch.nn.Module)_modules[i]).named_buffers(true)) {\n if (seen.Contains(p.handle)) continue;\n seen.Add(p.handle);\n yield return ($\"{_names[i]}.{n}\", p);\n }\n }\n }\n\n public override IEnumerable<(string name, torch.nn.Module module)> named_children()\n {\n for (var i = 0; i < _names.Count; i++) {\n yield return ($\"{_names[i]}\", ((torch.nn.Module)_modules[i]));\n }\n }\n\n public override IEnumerable<(string name, torch.nn.Module module)> named_modules()\n {\n for (var i = 0; i < _names.Count; i++) {\n yield return ($\"{_names[i]}\", ((torch.nn.Module)_modules[i]));\n }\n\n for (var i = 0; i < _names.Count; i++) {\n var sm = (torch.nn.Module)_modules[i];\n var name = _names[i];\n foreach (var (n, p) in sm.named_modules()) {\n yield return ($\"{name}.{n}\", p);\n }\n }\n\n }\n internal Sequential(IntPtr handle) : base(handle, IntPtr.Zero)\n {\n }\n\n /// <summary>\n /// Constructor, intended for derived modules.\n /// </summary>\n /// <param name=\"modules\">An ordered list of the contained modules.</param>\n protected Sequential(params (string name, torch.nn.Module<Tensor, Tensor> submodule)[] modules) : base(IntPtr.Zero, IntPtr.Zero)\n {\n var handle = THSNN_Sequential_ctor();\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n\n this.handle = new HType(handle, true);\n\n foreach (var module in modules) Add(module.name, module.submodule);\n }\n\n /// <summary>\n /// Constructor, intended for derived modules.\n /// </summary>\n /// <param name=\"modules\">An ordered list of the contained modules.</param>\n protected Sequential(params torch.nn.Module<Tensor, Tensor>[] modules) : base(IntPtr.Zero, IntPtr.Zero)\n {\n var handle = THSNN_Sequential_ctor();\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n\n this.handle = new HType(handle, true);\n\n foreach (var m in modules) Add(m);\n }\n\n public override Tensor forward(Tensor tensor)\n {\n // If there are no modules, just return a fresh handle to the input.\n if (_modules.Count == 0) return tensor.alias();\n\n // The loop-based logic below only works for n > 1, so here's another special case.\n if (_modules.Count == 1) return _modules[0].call(tensor);\n\n // Note: we have not been able to detect any significant performance difference between\n // implementing forward() in native or managed code.\n\n // Using an for loop helps debugging, since we can know the ordinal of the submodule.\n\n var t0 = _modules[0].call(tensor);\n\n for (var idx = 1; idx < _modules.Count - 1; idx++) {\n var t1 = _modules[idx].call(t0);\n t0.Dispose();\n t0 = t1;\n }\n\n var result = _modules[_modules.Count - 1].call(t0);\n t0.Dispose();\n\n return result;\n }\n\n public override nn.Module apply(Action<nn.Module> fn)\n {\n // More efficient than asking C++ for the children. We already have the list, after all.\n foreach (var m in _modules) ((torch.nn.Module)m).apply(fn);\n fn(this);\n return this;\n\n }\n\n /// <summary>\n /// The number of modules in the Sequential collection.\n /// </summary>\n public int Count => _modules.Count;\n\n /// <summary>\n /// Module indexer.\n /// </summary>\n [IndexerName(\"SequentialItems\")]\n public nn.IModule<Tensor,Tensor> this[int index] {\n get {\n return _modules[index];\n }\n }\n\n /// <summary>\n /// Module indexer.\n /// </summary>\n [IndexerName(\"SequentialItems\")]\n public Sequential this[(int? start, int? end) index] {\n get {\n var start = index.start.HasValue ? index.start.Value : 0;\n var end = index.end.HasValue ? index.end.Value : _modules.Count;\n\n return Slice(start, end);\n }\n }\n\n private Sequential Slice(int start, int end)\n {\n if (start < 0 || start > _modules.Count) throw new IndexOutOfRangeException($\"{start} is not a valid index.\");\n if (end < 0 || end > _modules.Count) throw new IndexOutOfRangeException($\"{end} is not a valid index.\");\n\n var stop = Math.Min(_modules.Count, end);\n\n var result = new Sequential(Array.Empty<torch.nn.Module<Tensor, Tensor>>());\n\n for (var i = start; i < stop; i++) {\n result.Add(_names[i], _modules[i]);\n }\n return result;\n }\n\n#if !NETSTANDARD2_0_OR_GREATER\n /// <summary>\n /// Module indexer.\n /// </summary>\n [IndexerName(\"SequentialItems\")]\n public Sequential this[System.Range index] {\n get {\n var start = index.Start.IsFromEnd ? _modules.Count - index.Start.Value : index.Start.Value;\n var end = index.End.IsFromEnd ? _modules.Count - index.End.Value : index.End.Value;\n\n return this[(start, end)];\n }\n }\n#endif\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n foreach (var m in _modules) { ((torch.nn.Module)m).Dispose(); }\n }\n base.Dispose(disposing);\n }\n\n /// <summary>\n /// Sets the module in training mode.\n /// </summary>\n /// <remarks>\n /// This has any effect only on certain modules.See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.Dropout, BatchNorm, etc.\n /// </remarks>\n public override void train(bool on = true)\n {\n foreach (var m in _modules) { ((torch.nn.Module)m).train(on); }\n }\n\n /// <summary>\n /// Sets the module in evaluation mode.\n /// </summary>\n /// <remarks>\n /// This has any effect only on certain modules.See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.Dropout, BatchNorm, etc.\n /// </remarks>\n public override void eval()\n {\n foreach (var m in _modules) { ((torch.nn.Module)m).eval(); }\n }\n\n protected internal override nn.Module _to(ScalarType dtype)\n {\n foreach (var m in _modules) { ((torch.nn.Module)m)._to(dtype); }\n return this;\n }\n\n protected internal override nn.Module _to(Device device, ScalarType dtype)\n {\n foreach (var m in _modules) { ((torch.nn.Module)m)._to(device, dtype); }\n return this;\n }\n\n protected internal override nn.Module _to(DeviceType deviceType, int deviceIndex = -1)\n {\n foreach (var m in _modules) { ((torch.nn.Module)m)._to(deviceType, deviceIndex); }\n return this;\n }\n\n // Currently, Sequential is implemented entirely in managed code, but if we go back to\n // using the native forward() implementation, this collection is still necessary.\n // The module handles are held in the native runtime, which calls back into managed code,\n // the .NET module instances need to stay alive, and keeping a list of them will do that.\n\n private List<torch.nn.IModule<Tensor, Tensor>> _modules = new List<nn.IModule<Tensor, Tensor>>();\n private List<string> _names = new List<string>();\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Get empty sequential\n /// </summary>\n /// <returns></returns>\n public static Sequential Sequential()\n {\n var handle = THSNN_Sequential_ctor();\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n\n return new Sequential(handle);\n }\n\n /// <summary>\n /// A sequential container. Modules will be added to it in the order they are passed in the constructor.\n /// Alternatively, an OrderedDict of modules can be passed in. The forward() method of Sequential accepts any input and forwards it to the first module it contains.\n /// It then “chains” outputs to inputs sequentially for each subsequent module, finally returning the output of the last module.\n /// The value a Sequential provides over manually calling a sequence of modules is that it allows treating the whole container as a single module,\n /// such that performing a transformation on the Sequential applies to each of the modules it stores (which are each a registered submodule of the Sequential).\n /// </summary>\n /// <param name=\"modules\">An ordered list of the contained modules.</param>\n /// <returns></returns>\n /// <remarks>Sequential will take ownership of the modules and dispose of them when disposed.</remarks>\n public static Sequential Sequential(params (string name, torch.nn.Module<Tensor, Tensor> submodule)[] modules)\n {\n var res = Sequential();\n foreach (var module in modules)\n res.Add(module.name, module.submodule);\n return res;\n }\n\n /// <summary>\n /// A sequential container. Modules will be added to it in the order they are passed in the constructor.\n /// It then “chains” outputs to inputs sequentially for each subsequent module, finally returning the output of the last module.\n /// The value a Sequential provides over manually calling a sequence of modules is that it allows treating the whole container as a single module,\n /// such that performing a transformation on the Sequential applies to each of the modules it stores (which are each a registered submodule of the Sequential).\n /// </summary>\n /// <param name=\"modules\">An ordered list of the contained modules.</param>\n /// <returns></returns>\n /// <remarks>Sequential will take ownership of the modules and dispose of them when disposed.</remarks>\n public static Sequential Sequential(params torch.nn.Module<Tensor, Tensor>[] modules)\n {\n var res = Sequential();\n foreach (var m in modules)\n res.Add(m);\n return res;\n }\n\n /// <summary>\n /// A sequential container. Modules will be added to it in the order they are passed in the constructor.\n /// Alternatively, an OrderedDict of modules can be passed in. The forward() method of Sequential accepts any input and forwards it to the first module it contains.\n /// It then “chains” outputs to inputs sequentially for each subsequent module, finally returning the output of the last module.\n /// The value a Sequential provides over manually calling a sequence of modules is that it allows treating the whole container as a single module,\n /// such that performing a transformation on the Sequential applies to each of the modules it stores (which are each a registered submodule of the Sequential).\n /// </summary>\n /// <param name=\"modules\">An ordered list of the contained modules.</param>\n /// <remarks>Sequential will take ownership of the modules and dispose of them when disposed.</remarks>\n public static Sequential Sequential(params System.Tuple<string, torch.nn.Module<Tensor, Tensor>>[] modules)\n {\n var res = Sequential();\n foreach (var module in modules)\n res.Add(module.Item1, module.Item2);\n return res;\n }\n\n /// <summary>\n /// A sequential container. Modules will be added to it in the order they are passed in the constructor.\n /// Alternatively, an OrderedDict of modules can be passed in. The forward() method of Sequential accepts any input and forwards it to the first module it contains.\n /// It then “chains” outputs to inputs sequentially for each subsequent module, finally returning the output of the last module.\n /// The value a Sequential provides over manually calling a sequence of modules is that it allows treating the whole container as a single module,\n /// such that performing a transformation on the Sequential applies to each of the modules it stores (which are each a registered submodule of the Sequential).\n /// </summary>\n /// <param name=\"modules\">An ordered list of the contained modules.</param>\n /// <remarks>Sequential will take ownership of the modules and dispose of them when disposed.</remarks>\n public static Sequential Sequential(IEnumerable<(string name, torch.nn.Module<Tensor, Tensor> submodule)> modules)\n {\n var res = Sequential();\n foreach (var module in modules)\n res.Add(module.name, module.submodule);\n return res;\n }\n\n /// <summary>\n /// A sequential container. Modules will be added to it in the order they are passed in the constructor.\n /// Alternatively, an OrderedDict of modules can be passed in. The forward() method of Sequential accepts any input and forwards it to the first module it contains.\n /// It then “chains” outputs to inputs sequentially for each subsequent module, finally returning the output of the last module.\n /// The value a Sequential provides over manually calling a sequence of modules is that it allows treating the whole container as a single module,\n /// such that performing a transformation on the Sequential applies to each of the modules it stores (which are each a registered submodule of the Sequential).\n /// </summary>\n /// <param name=\"modules\">An ordered list of the contained modules.</param>\n /// <remarks>Sequential will take ownership of the modules and dispose of them when disposed.</remarks>\n public static Sequential Sequential(IEnumerable<System.Tuple<string, torch.nn.Module<Tensor, Tensor>>> modules)\n {\n var res = Sequential();\n foreach (var module in modules)\n res.Add(module.Item1, module.Item2);\n return res;\n }\n\n /// <summary>\n /// A sequential container. Modules will be added to it in the order they are passed in the constructor.\n /// It then “chains” outputs to inputs sequentially for each subsequent module, finally returning the output of the last module.\n /// The value a Sequential provides over manually calling a sequence of modules is that it allows treating the whole container as a single module,\n /// such that performing a transformation on the Sequential applies to each of the modules it stores (which are each a registered submodule of the Sequential).\n /// </summary>\n /// <param name=\"modules\">An ordered list of the contained modules.</param>\n /// <returns></returns>\n /// <remarks>Sequential will take ownership of the modules and dispose of them when disposed.</remarks>\n public static Sequential Sequential(IEnumerable<torch.nn.Module<Tensor, Tensor>> modules)\n {\n var res = Sequential();\n foreach (var module in modules)\n res.Add(module);\n return res;\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5300552248954773, "alphanum_fraction": 0.5334318280220032, "avg_line_length": 54.96653366088867, "blob_id": "3ade0ce040dae85a22bc86a23884a84178453193", "content_id": "06df3cb78167fb8a19f24752d7c0ebef0ed3b88f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 28431, "license_type": "permissive", "max_line_length": 214, "num_lines": 508, "path": "/src/TorchSharp/FFT.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n // This file contains the mathematical operators on Tensor\n public enum FFTNormType\n {\n Backward = 0,\n Forward = 1,\n Ortho = 2\n }\n\n public static partial class torch\n {\n public static partial class fft\n {\n /// <summary>\n /// Computes the one dimensional discrete Fourier transform of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"n\">Signal length. If given, the input will either be zero-padded or trimmed to this length before computing the FFT.</param>\n /// <param name=\"dim\">The dimension along which to take the one dimensional FFT.</param>\n /// <param name=\"norm\">Normalization mode.</param>\n /// <returns></returns>\n /// <remarks>The name was changed because it would conflict with its surrounding scope. That's not legal in .NET.</remarks>\n public static Tensor fft_(Tensor input, long n = -1, long dim = -1, FFTNormType norm = FFTNormType.Backward)\n {\n var res = THSTensor_fft(input.Handle, n, dim, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the one dimensional inverse discrete Fourier transform of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"n\">Signal length. If given, the input will either be zero-padded or trimmed to this length before computing the IFFT.</param>\n /// <param name=\"dim\">The dimension along which to take the one dimensional IFFT.</param>\n /// <param name=\"norm\">Normalization mode.</param>\n /// <returns></returns>\n public static Tensor ifft(Tensor input, long n = -1, long dim = -1, FFTNormType norm = FFTNormType.Backward)\n {\n var res = THSTensor_ifft(input.Handle, n, dim, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the two-dimensional discrete Fourier transform of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"s\">\n /// Signal size in the transformed dimensions.\n /// If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the FFT.\n /// If a length -1 is specified, no padding is done in that dimension.\n /// </param>\n /// <param name=\"dim\">Dimensions to be transformed</param>\n /// <param name=\"norm\">Normalization mode.</param>\n /// <returns></returns>\n public static Tensor fft2(Tensor input, long[] s = null, long[] dim = null, FFTNormType norm = FFTNormType.Backward)\n {\n if (input.Dimensions < 2) throw new ArgumentException(\"fft2() input should be at least 2D\");\n if (dim == null) dim = new long[] { -2, -1 };\n unsafe {\n fixed (long* ps = s, pDim = dim) {\n var res = THSTensor_fft2(input.Handle, (IntPtr)ps, (IntPtr)pDim, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes the two-dimensional inverse discrete Fourier transform of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"s\">\n /// Signal size in the transformed dimensions.\n /// If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the IFFT.\n /// If a length -1 is specified, no padding is done in that dimension.\n /// </param>\n /// <param name=\"dim\">Dimensions to be transformed</param>\n /// <param name=\"norm\">Normalization mode.</param>\n public static Tensor ifft2(Tensor input, long[] s = null, long[] dim = null, FFTNormType norm = FFTNormType.Backward)\n {\n if (input.Dimensions < 2) throw new ArgumentException(\"ifft2() input should be at least 2D\");\n if (dim == null) dim = new long[] { -2, -1 };\n unsafe {\n fixed (long* ps = s, pDim = dim) {\n var res = THSTensor_ifft2(input.Handle, (IntPtr)ps, (IntPtr)pDim, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes the N-dimensional discrete Fourier transform of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"s\">\n /// Signal size in the transformed dimensions.\n /// If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the IFFT.\n /// If a length -1 is specified, no padding is done in that dimension.\n /// </param>\n /// <param name=\"dim\">Dimensions to be transformed</param>\n /// <param name=\"norm\">Normalization mode.</param>\n /// <returns></returns>\n public static Tensor fftn(Tensor input, long[] s = null, long[] dim = null, FFTNormType norm = FFTNormType.Backward)\n {\n var slen = (s == null) ? 0 : s.Length;\n var dlen = (dim == null) ? 0 : dim.Length;\n unsafe {\n fixed (long* ps = s, pDim = dim) {\n var res = THSTensor_fftn(input.Handle, (IntPtr)ps, slen, (IntPtr)pDim, dlen, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes the N-dimensional inverse discrete Fourier transform of input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"s\">\n /// Signal size in the transformed dimensions.\n /// If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the IFFT.\n /// If a length -1 is specified, no padding is done in that dimension.\n /// </param>\n /// <param name=\"dim\">Dimensions to be transformed</param>\n /// <param name=\"norm\">Normalization mode.</param>\n /// <returns></returns>\n public static Tensor ifftn(Tensor input, long[] s = null, long[] dim = null, FFTNormType norm = FFTNormType.Backward)\n {\n var slen = (s == null) ? 0 : s.Length;\n var dlen = (dim == null) ? 0 : dim.Length;\n unsafe {\n fixed (long* ps = s, pDim = dim) {\n var res = THSTensor_ifftn(input.Handle, (IntPtr)ps, slen, (IntPtr)pDim, dlen, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes the one dimensional inverse Fourier transform of real-valued input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"n\">Signal length. If given, the input will either be zero-padded or trimmed to this length before computing the FFT.</param>\n /// <param name=\"dim\">The dimension along which to take the one dimensional FFT.</param>\n /// <param name=\"norm\">Normalization mode.</param>\n public static Tensor irfft(Tensor input, long n = -1, long dim = -1, FFTNormType norm = FFTNormType.Backward)\n {\n var res = THSTensor_irfft(input.Handle, n, dim, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the one dimensional Fourier transform of real-valued input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"n\">Signal length. If given, the input will either be zero-padded or trimmed to this length before computing the FFT.</param>\n /// <param name=\"dim\">The dimension along which to take the one dimensional FFT.</param>\n /// <param name=\"norm\">Normalization mode.</param>\n /// <returns></returns>\n public static Tensor rfft(Tensor input, long n = -1, long dim = -1, FFTNormType norm = FFTNormType.Backward)\n {\n var res = THSTensor_rfft(input.Handle, n, dim, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the two-dimensional discrete Fourier transform of real-vaued input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"s\">\n /// Signal size in the transformed dimensions.\n /// If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the FFT.\n /// If a length -1 is specified, no padding is done in that dimension.\n /// </param>\n /// <param name=\"dim\">Dimensions to be transformed</param>\n /// <param name=\"norm\">Normalization mode.</param>\n public static Tensor rfft2(Tensor input, long[] s = null, long[] dim = null, FFTNormType norm = FFTNormType.Backward)\n {\n if (input.Dimensions < 2) throw new ArgumentException(\"rfft2() input should be at least 2D\");\n if (dim == null) dim = new long[] { -2, -1 };\n unsafe {\n fixed (long* ps = s, pDim = dim) {\n var res = THSTensor_rfft2(input.Handle, (IntPtr)ps, (IntPtr)pDim, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes the two-dimensional inverse discrete Fourier transform of real-valued input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"s\">\n /// Signal size in the transformed dimensions.\n /// If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the IFFT.\n /// If a length -1 is specified, no padding is done in that dimension.\n /// </param>\n /// <param name=\"dim\">Dimensions to be transformed</param>\n /// <param name=\"norm\">Normalization mode.</param>\n public static Tensor irfft2(Tensor input, long[] s = null, long[] dim = null, FFTNormType norm = FFTNormType.Backward)\n {\n if (input.Dimensions < 2) throw new ArgumentException(\"irfft2() input should be at least 2D\");\n if (dim == null) dim = new long[] { -2, -1 };\n unsafe {\n fixed (long* ps = s, pDim = dim) {\n var res = THSTensor_irfft2(input.Handle, (IntPtr)ps, (IntPtr)pDim, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes the N-dimensional discrete Fourier transform of real-valued input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"s\">\n /// Signal size in the transformed dimensions.\n /// If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the IFFT.\n /// If a length -1 is specified, no padding is done in that dimension.\n /// </param>\n /// <param name=\"dim\">Dimensions to be transformed</param>\n /// <param name=\"norm\">Normalization mode.</param>\n public static Tensor rfftn(Tensor input, long[] s = null, long[] dim = null, FFTNormType norm = FFTNormType.Backward)\n {\n var slen = (s == null) ? 0 : s.Length;\n var dlen = (dim == null) ? 0 : dim.Length;\n unsafe {\n fixed (long* ps = s, pDim = dim) {\n var res = THSTensor_rfftn(input.Handle, (IntPtr)ps, slen, (IntPtr)pDim, dlen, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes the N-dimensional inverse discrete Fourier transform of real-valued input.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"s\">\n /// Signal size in the transformed dimensions.\n /// If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the IFFT.\n /// If a length -1 is specified, no padding is done in that dimension.\n /// </param>\n /// <param name=\"dim\">Dimensions to be transformed</param>\n /// <param name=\"norm\">Normalization mode.</param>\n public static Tensor irfftn(Tensor input, long[] s = null, long[] dim = null, FFTNormType norm = FFTNormType.Backward)\n {\n var slen = (s == null) ? 0 : s.Length;\n var dlen = (dim == null) ? 0 : dim.Length;\n unsafe {\n fixed (long* ps = s, pDim = dim) {\n var res = THSTensor_irfftn(input.Handle, (IntPtr)ps, slen, (IntPtr)pDim, dlen, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes the one dimensional discrete Fourier transform of a Hermitian symmetric input signal.\n /// </summary>\n /// <param name=\"input\">The input tensor representing a half-Hermitian signal</param>\n /// <param name=\"n\">\n /// Output signal length. This determines the length of the real output.\n /// If given, the input will either be zero-padded or trimmed to this length before computing the Hermitian FFT.</param>\n /// <param name=\"dim\">The dimension along which to take the one dimensional Hermitian FFT.</param>\n /// <param name=\"norm\">Normalization mode.</param>\n /// <returns></returns>\n public static Tensor hfft(Tensor input, long n = -1, long dim = -1, FFTNormType norm = FFTNormType.Backward)\n {\n var res = THSTensor_hfft(input.Handle, n, dim, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Computes the inverse of hfft().\n /// </summary>\n /// <param name=\"input\">The input tensor representing a half-Hermitian signal</param>\n /// <param name=\"n\">\n /// Output signal length. This determines the length of the real output.\n /// If given, the input will either be zero-padded or trimmed to this length before computing the Hermitian FFT.</param>\n /// <param name=\"dim\">The dimension along which to take the one dimensional Hermitian FFT.</param>\n /// <param name=\"norm\">Normalization mode.</param>\n public static Tensor ihfft(Tensor input, long n = -1, long dim = -1, FFTNormType norm = FFTNormType.Backward)\n {\n var res = THSTensor_ihfft(input.Handle, n, dim, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n /// <summary>\n /// Reorders n-dimensional FFT data, as provided by fftn(), to have negative frequency terms first.\n /// This performs a periodic shift of n-dimensional data such that the origin(0, ..., 0) is moved to the center of the tensor.Specifically, to input.shape[dim] // 2 in each selected dimension.\n /// </summary>\n /// <param name=\"input\">The tensor in FFT order</param>\n /// <param name=\"dim\">The dimensions to rearrange. Only dimensions specified here will be rearranged, any other dimensions will be left in their original order. Default: All dimensions of input.</param>\n /// <returns></returns>\n public static Tensor fftshift(Tensor input, long[] dim = null)\n {\n var dlen = (dim == null) ? 0 : dim.Length;\n unsafe {\n fixed (long* pDim = dim) {\n var res = THSTensor_fftshift(input.Handle, (IntPtr)pDim, dlen);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Inverse of fftshift().\n /// </summary>\n /// <param name=\"input\">The tensor in FFT order</param>\n /// <param name=\"dim\">The dimensions to rearrange. Only dimensions specified here will be rearranged, any other dimensions will be left in their original order. Default: All dimensions of input.</param>\n public static Tensor ifftshift(Tensor input, long[] dim = null)\n {\n var dlen = (dim == null) ? 0 : dim.Length;\n unsafe {\n fixed (long* pDim = dim) {\n var res = THSTensor_ifftshift(input.Handle, (IntPtr)pDim, dlen);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes the discrete Fourier Transform sample frequencies for a signal of size n.\n /// </summary>\n /// <param name=\"n\">The FFT length</param>\n /// <param name=\"d\">The sampling length scale. </param>\n /// <param name=\"dtype\">The desired data type of the returned tensor</param>\n /// <param name=\"device\">the desired device of the returned tensor</param>\n /// <param name=\"requires_grad\">If autograd should record operations on the returned tensor.</param>\n public static Tensor fftfreq(long n, double d = 1.0, torch.ScalarType? dtype = null, torch.Device device = null, bool requires_grad = false)\n {\n device = torch.InitializeDevice(device);\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n dtype = get_default_dtype();\n }\n\n var handle = THSTensor_fftfreq(n, d, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_fftfreq(n, d, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(handle);\n }\n\n /// <summary>\n /// Computes the sample frequencies for rfft() with a signal of size n.\n /// </summary>\n /// <param name=\"n\">The FFT length</param>\n /// <param name=\"d\">The sampling length scale. </param>\n /// <param name=\"dtype\">The desired data type of the returned tensor</param>\n /// <param name=\"device\">the desired device of the returned tensor</param>\n /// <param name=\"requires_grad\">If autograd should record operations on the returned tensor.</param>\n public static Tensor rfftfreq(long n, double d = 1.0, torch.ScalarType? dtype = null, torch.Device device = null, bool requires_grad = false)\n {\n device = torch.InitializeDevice(device);\n if (!dtype.HasValue) {\n // Determine the element type dynamically.\n dtype = get_default_dtype();\n }\n\n var handle = THSTensor_rfftfreq(n, d, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n if (handle == IntPtr.Zero) {\n GC.Collect();\n GC.WaitForPendingFinalizers();\n handle = THSTensor_rfftfreq(n, d, (sbyte)dtype, (int)device.type, device.index, requires_grad);\n }\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(handle);\n }\n\n /// <summary>\n /// Computes the 2-dimensional discrete Fourier transform of a Hermitian symmetric input signal.\n ///\n /// Equivalent to hfftn() but only transforms the last two dimensions by default.\n /// input is interpreted as a one-sided Hermitian signal in the time domain.\n /// By the Hermitian property, the Fourier transform will be real-valued.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"s\">\n /// Signal size in the transformed dimensions.\n /// If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the IFFT.\n /// If a length -1 is specified, no padding is done in that dimension.\n /// </param>\n /// <param name=\"dim\">Dimensions to be transformed</param>\n /// <param name=\"norm\">Normalization mode.</param>\n public static Tensor hfft2(Tensor input, long[] s = null, long[] dim = null, FFTNormType norm = FFTNormType.Backward)\n {\n if (input.Dimensions < 2) throw new ArgumentException(\"hfft2() input should be at least 2D\");\n if (dim == null) dim = new long[] { -2, -1 };\n unsafe {\n fixed (long* ps = s, pDim = dim) {\n var res = THSTensor_hfft2(input.Handle, (IntPtr)ps, (IntPtr)pDim, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes the 2-dimensional inverse discrete Fourier transform of a Hermitian symmetric input signal.\n ///\n /// Equivalent to hfftn() but only transforms the last two dimensions by default.\n /// input is interpreted as a one-sided Hermitian signal in the time domain.\n /// By the Hermitian property, the Fourier transform will be real-valued.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"s\">\n /// Signal size in the transformed dimensions.\n /// If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the IFFT.\n /// If a length -1 is specified, no padding is done in that dimension.\n /// </param>\n /// <param name=\"dim\">Dimensions to be transformed</param>\n /// <param name=\"norm\">Normalization mode.</param>\n public static Tensor ihfft2(Tensor input, long[] s = null, long[] dim = null, FFTNormType norm = FFTNormType.Backward)\n {\n if (input.Dimensions < 2) throw new ArgumentException(\"ihfft2() input should be at least 2D\");\n if (dim == null) dim = new long[] { -2, -1 };\n unsafe {\n fixed (long* ps = s, pDim = dim) {\n var res = THSTensor_ihfft2(input.Handle, (IntPtr)ps, (IntPtr)pDim, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes the n-dimensional discrete Fourier transform of a Herimitian symmetric input signal.\n ///\n /// input is interpreted as a one-sided Hermitian signal in the time domain.\n /// By the Hermitian property, the Fourier transform will be real-valued.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"s\">\n /// Signal size in the transformed dimensions.\n /// If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the IFFT.\n /// If a length -1 is specified, no padding is done in that dimension.\n /// </param>\n /// <param name=\"dim\">Dimensions to be transformed</param>\n /// <param name=\"norm\">Normalization mode.</param>\n public static Tensor hfftn(Tensor input, long[] s = null, long[] dim = null, FFTNormType norm = FFTNormType.Backward)\n {\n if (input.Dimensions < 2) throw new ArgumentException(\"hfftn() input should be at least 2D\");\n var slen = (s == null) ? 0 : s.Length;\n var dlen = (dim == null) ? 0 : dim.Length;\n unsafe {\n fixed (long* ps = s, pDim = dim) {\n var res = THSTensor_hfftn(input.Handle, (IntPtr)ps, slen, (IntPtr)pDim, dlen, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n /// <summary>\n /// Computes the n-dimensional inverse discrete Fourier transform of a Herimitian symmetric input signal.\n ///\n /// input is interpreted as a one-sided Hermitian signal in the time domain.\n /// By the Hermitian property, the Fourier transform will be real-valued.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"s\">\n /// Signal size in the transformed dimensions.\n /// If given, each dimension dim[i] will either be zero-padded or trimmed to the length s[i] before computing the IFFT.\n /// If a length -1 is specified, no padding is done in that dimension.\n /// </param>\n /// <param name=\"dim\">Dimensions to be transformed</param>\n /// <param name=\"norm\">Normalization mode.</param>\n public static Tensor ihfftn(Tensor input, long[] s = null, long[] dim = null, FFTNormType norm = FFTNormType.Backward)\n {\n if (input.Dimensions < 2) throw new ArgumentException(\"ihfftn() input should be at least 2D\");\n var slen = (s == null) ? 0 : s.Length;\n var dlen = (dim == null) ? 0 : dim.Length;\n unsafe {\n fixed (long* ps = s, pDim = dim) {\n var res = THSTensor_ihfftn(input.Handle, (IntPtr)ps, slen, (IntPtr)pDim, dlen, (sbyte)norm);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6702355742454529, "alphanum_fraction": 0.6761242151260376, "avg_line_length": 38.74468231201172, "blob_id": "df97e2c877d61ee2e0d34fbf4747b4506e8ec7a7", "content_id": "07b3e5f52d9a5fac6e3c5d1f55bce2067b1f518b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1868, "license_type": "permissive", "max_line_length": 149, "num_lines": 47, "path": "/src/TorchSharp/PInvoke/LibTorchSharp.THSAutograd.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace TorchSharp.PInvoke\n{\n internal static partial class NativeMethods\n {\n [DllImport(\"LibTorchSharp\")]\n [return: MarshalAs(UnmanagedType.U1)]\n internal static extern bool THSAutograd_isGradEnabled();\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSAutograd_setGrad([MarshalAs(UnmanagedType.U1)] bool enabled);\n\n [DllImport(\"LibTorchSharp\")]\n [return: MarshalAs(UnmanagedType.U1)]\n internal static extern bool THSAutograd_isAnomalyEnabled();\n\n [DllImport(\"LibTorchSharp\")]\n [return: MarshalAs(UnmanagedType.U1)]\n internal static extern bool THSAutograd_shouldCheckNaN();\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSAutograd_setAnomaly([MarshalAs(UnmanagedType.U1)] bool enabled, [MarshalAs(UnmanagedType.U1)] bool check_nan);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSAutograd_grad(\n IntPtr outputs, long oLength,\n IntPtr inputs, long iLength,\n IntPtr grad_outs, long gLength,\n [MarshalAs(UnmanagedType.U1)] bool retain_graph,\n [MarshalAs(UnmanagedType.U1)] bool create_graph,\n [MarshalAs(UnmanagedType.U1)] bool allow_unused,\n AllocatePinnedArray allocator);\n\n [DllImport(\"LibTorchSharp\")]\n internal static extern void THSAutograd_backward(\n IntPtr tensors, long tLength,\n IntPtr grad_tensors, long gtLength,\n [MarshalAs(UnmanagedType.U1)] bool retain_graph,\n [MarshalAs(UnmanagedType.U1)] bool create_graph,\n IntPtr inputs, long iLength);\n\n }\n}\n" }, { "alpha_fraction": 0.5888888835906982, "alphanum_fraction": 0.5888888835906982, "avg_line_length": 25.52941131591797, "blob_id": "f6e08bcdaea1d2a53fb46a7fcb82c8051d9e5d75", "content_id": "b40c2060b32b7c454e9663ddb5c62baaecef3de8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 452, "license_type": "permissive", "max_line_length": 131, "num_lines": 17, "path": "/src/TorchSharp/Tensor/Enums/layout.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nnamespace TorchSharp\n{\n // https://pytorch.org/docs/stable/tensor_attributes.html#torch.layout\n public enum layout\n {\n /// <summary>\n /// dense Tensors\n /// </summary>\n strided,\n\n /// <summary>\n /// sparse COO Tensors\n /// </summary>\n sparse_coo\n }\n}" }, { "alpha_fraction": 0.6787330508232117, "alphanum_fraction": 0.6854012608528137, "avg_line_length": 49.60240936279297, "blob_id": "a2b316f3ffc736cfddc5c80b03967f2d718421b5", "content_id": "42745a786e9aa4a8a519e12c229a41bf66ffd78e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4199, "license_type": "permissive", "max_line_length": 144, "num_lines": 83, "path": "/src/TorchSharp/Tensor/torch.Utilities.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n#nullable enable\nusing System;\nusing System.Diagnostics.Contracts;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n // https://pytorch.org/docs/stable/torch#utilities\n public static partial class torch\n {\n // https://pytorch.org/docs/stable/generated/torch.compiled_with_cxx11_abi\n [Pure, Obsolete(\"not implemented\", true)]\n public static bool compiled_with_cxx11_abi() => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.result_type\n public static ScalarType result_type(Tensor tensor1, Tensor tensor2)\n {\n var res = THSTensor_result_type(tensor1.Handle, tensor2.Handle);\n if (res == -1) CheckForErrors();\n return (ScalarType)res;\n }\n\n // https://pytorch.org/docs/stable/generated/torch.can_cast\n public static bool can_cast(ScalarType from, ScalarType to)\n {\n var res = THSTorch_can_cast((int)from, (int)to);\n if (res == -1) CheckForErrors();\n return res != 0;\n }\n\n // https://pytorch.org/docs/stable/generated/torch.promote_types\n public static ScalarType promote_types(ScalarType type1, ScalarType type2)\n {\n var res = THSTorch_promote_types((int)type1, (int)type2);\n if (res == -1) CheckForErrors();\n return (ScalarType)res;\n }\n\n // https://pytorch.org/docs/stable/generated/torch.use_deterministic_algorithms\n [Obsolete(\"not implemented\", true)]\n public static IDisposable use_deterministic_algorithms(bool mode = true, bool warn_only = false) => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.are_deterministic_algorithms_enabled\n [Pure, Obsolete(\"not implemented\", true)]\n public static bool are_deterministic_algorithms_enabled() => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.is_deterministic_algorithms_warn_only_enabled\n [Pure, Obsolete(\"not implemented\", true)]\n public static bool is_deterministic_algorithms_warn_only_enabled() => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.set_deterministic_debug_mode\n [Obsolete(\"not implemented\", true)]\n public static IDisposable set_deterministic_debug_mode(DebugMode mode) => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.get_deterministic_debug_mode\n [Pure, Obsolete(\"not implemented\", true)]\n public static DebugMode get_deterministic_debug_mode() => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.set_float32_matmul_precision\n [Obsolete(\"not implemented\", true)]\n public static IDisposable set_float32_matmul_precision(Float32MatmulPrecision precision) => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.get_float32_matmul_precision\n [Pure, Obsolete(\"not implemented\", true)]\n public static Float32MatmulPrecision get_float32_matmul_precision() => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.set_warn_always\n [Obsolete(\"not implemented\", true)]\n public static IDisposable set_warn_always(bool mode = true) => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch.is_warn_always_enabled\n [Pure, Obsolete(\"not implemented\", true)]\n public static bool is_warn_always_enabled() => throw new NotImplementedException();\n\n // https://pytorch.org/docs/stable/generated/torch._assert\n [Obsolete(\"not implemented\", true)]\n public static void _assert(bool condition, string message) => throw new NotImplementedException();\n\n [Obsolete(\"not implemented\", true)]\n public static void _assert(Func<bool> condition, string message) => throw new NotImplementedException();\n }\n}" }, { "alpha_fraction": 0.45644113421440125, "alphanum_fraction": 0.4817243814468384, "avg_line_length": 36.910335540771484, "blob_id": "fbc4c51d0749eed58be5e937508ccc7d38825fdd", "content_id": "3ece4ce4af0a5b8d288c075b145522f194d1a6d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 96823, "license_type": "permissive", "max_line_length": 130, "num_lines": 2554, "path": "/test/TorchSharpTest/TestLoadSave.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.IO;\nusing System.Linq;\nusing TorchSharp.Modules;\nusing static TorchSharp.torch.nn;\nusing Xunit;\nusing System.Collections.Generic;\n\n#nullable enable\n\nnamespace TorchSharp\n{\n [Collection(\"Sequential\")]\n public class TestLoadSave\n {\n private static Random rand = new Random();\n\n static string RandomFileName(string extension)\n {\n return $\"_STR{rand.Next()}.{extension}\";\n }\n\n [Fact]\n public void TestSaveLoadLinear1()\n {\n var location = RandomFileName(\"ts\");\n\n if (File.Exists(location)) File.Delete(location);\n\n try {\n var linear = Linear(100, 10, true);\n var params0 = linear.parameters();\n linear.save(location);\n\n var loadedLinear = Linear(100, 10, true);\n loadedLinear.load(location);\n\n var params1 = loadedLinear.parameters();\n Assert.Equal(params0, params1);\n\n loadedLinear = Linear(100, 10, true);\n loadedLinear.load(location, skip: new[] { \"weight\" });\n var params2 = loadedLinear.parameters();\n\n Assert.NotEqual(params0.First(), params2.First());\n Assert.Equal(params0.Skip(1).First(), params2.Skip(1).First());\n } finally {\n if (File.Exists(location)) File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveLoadLinear2()\n {\n var location = RandomFileName(\"ts\");\n\n if (File.Exists(location)) File.Delete(location);\n try {\n var linear = Linear(100, 10, true);\n var params0 = linear.parameters();\n linear.save(location, skip: new[] { \"weight\" });\n\n var loadedLinear = Linear(100, 10, true);\n Assert.Throws<ArgumentException>(() => loadedLinear.load(location, strict: true));\n loadedLinear.load(location, strict: false);\n var params2 = loadedLinear.parameters();\n\n Assert.NotEqual(params0.First(), params2.First());\n Assert.Equal(params0.Skip(1).First(), params2.Skip(1).First());\n } finally {\n if (File.Exists(location)) File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveLoadLinear3()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n try {\n using var linear = Linear(100, 10, true);\n var params0 = linear.parameters();\n linear.save(location);\n\n var loadedLinear = Linear(10, 10, true); // Mismatched shape, shouldn't matter when skipped.\n Assert.Throws<ArgumentException>(() => loadedLinear.load(location));\n\n loadedLinear.load(location, skip: new[] { \"weight\" });\n var params2 = loadedLinear.parameters();\n\n Assert.NotEqual(params0.First(), params2.First());\n Assert.Equal(params0.Skip(1).First(), params2.Skip(1).First());\n } finally {\n if (File.Exists(location)) File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveLoadConv2D()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n try {\n using var conv = Conv2d(100, 10, 5);\n var params0 = conv.parameters();\n conv.save(location);\n using var loaded = Conv2d(100, 10, 5);\n loaded.load(location);\n var params1 = loaded.parameters();\n\n Assert.Equal(params0, params1);\n } finally {\n if (File.Exists(location)) File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveLoadConv2D_sd()\n {\n using var conv = Conv2d(100, 10, 5);\n var params0 = conv.parameters();\n\n var sd = conv.state_dict();\n\n using var loaded = Conv2d(100, 10, 5);\n Assert.NotEqual(params0, loaded.parameters());\n\n loaded.load_state_dict(sd);\n Assert.Equal(params0, loaded.parameters());\n }\n\n [Fact]\n public void TestSaveLoadConv2DStream()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n try {\n using var conv = Conv2d(100, 10, 5);\n var params0 = conv.parameters();\n\n using (var stream = System.IO.File.OpenWrite(location)) {\n conv.save(stream);\n }\n\n using var loaded = Conv2d(100, 10, 5);\n\n using (var stream = System.IO.File.OpenRead(location)) {\n loaded.load(stream);\n }\n var params1 = loaded.parameters();\n\n Assert.Equal(params0, params1);\n\n } finally {\n if (File.Exists(location)) File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveLoadSequential()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n try {\n using var conv = Sequential(Conv2d(100, 10, 5), Linear(100, 10, true));\n var params0 = conv.parameters();\n conv.save(location);\n using var loaded = Sequential(Conv2d(100, 10, 5), Linear(100, 10, true));\n loaded.load(location);\n var params1 = loaded.parameters();\n\n Assert.Equal(params0, params1);\n } finally {\n if (File.Exists(location)) File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveLoadSequentialStream()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n try {\n using var conv = Sequential(Conv2d(100, 10, 5), Linear(100, 10, true));\n var params0 = conv.parameters();\n using (var stream = System.IO.File.OpenWrite(location)) {\n conv.save(stream);\n }\n using var loaded = Sequential(Conv2d(100, 10, 5), Linear(100, 10, true));\n using (var stream = System.IO.File.OpenRead(location)) {\n loaded.load(stream);\n }\n var params1 = loaded.parameters();\n\n Assert.Equal(params0, params1);\n } finally {\n if (File.Exists(location)) File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveLoadSequential_sd()\n {\n using var conv = Sequential(Conv2d(100, 10, 5), Linear(100, 10, true));\n var params0 = conv.parameters();\n\n var sd = conv.state_dict();\n\n using var loaded = Sequential(Conv2d(100, 10, 5), Linear(100, 10, true));\n Assert.NotEqual(params0, loaded.parameters());\n\n loaded.load_state_dict(sd);\n Assert.Equal(params0, loaded.parameters());\n }\n\n [Fact]\n public void TestSaveLoadSequential_error1()\n {\n using var conv = Sequential(Conv2d(100, 10, 5), Linear(100, 10, true));\n var params0 = conv.parameters();\n\n var sd = conv.state_dict();\n sd.Remove(\"0.bias\");\n\n using var loaded = Sequential(Conv2d(100, 10, 5), Linear(100, 10, true));\n Assert.NotEqual(params0, loaded.parameters());\n\n Assert.Throws<InvalidOperationException>(() => loaded.load_state_dict(sd));\n }\n\n [Fact]\n public void TestSaveLoadSequential_error2()\n {\n using var conv = Sequential(Conv2d(100, 10, 5), Linear(100, 10, true));\n var params0 = conv.parameters();\n\n var sd = conv.state_dict();\n var t = sd[\"0.bias\"];\n\n sd.Add(\"2.bias\", t);\n\n using var loaded = Sequential(Conv2d(100, 10, 5), Linear(100, 10, true));\n Assert.NotEqual(params0, loaded.parameters());\n\n Assert.Throws<InvalidOperationException>(() => loaded.load_state_dict(sd));\n }\n\n [Fact]\n public void TestSaveLoadSequential_lax()\n {\n using var conv = Sequential(Conv2d(100, 10, 5), Linear(100, 10, true));\n var params0 = conv.parameters();\n\n var sd = conv.state_dict();\n var t = sd[\"0.bias\"];\n sd.Remove(\"0.bias\");\n\n sd.Add(\"2.bias\", t);\n\n using var loaded = Sequential(Conv2d(100, 10, 5), Linear(100, 10, true));\n Assert.NotEqual(params0, loaded.parameters());\n\n var (m, u) = loaded.load_state_dict(sd, false);\n Assert.NotEqual(params0, loaded.parameters());\n\n Assert.NotEmpty(m);\n Assert.NotEmpty(u);\n }\n\n [Fact]\n public void TestSaveLoadCustomWithParameters()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n try {\n using var original = new TestModule1();\n Assert.True(original.has_parameter(\"test\"));\n\n var params0 = original.parameters();\n Assert.True(params0.ToArray().ToArray()[0].requires_grad);\n original.save(location);\n\n using var loaded = new TestModule1();\n Assert.True(loaded.has_parameter(\"test\"));\n\n var params1 = loaded.parameters();\n Assert.True(params1.ToArray()[0].requires_grad);\n Assert.NotEqual(params0.ToArray(), params1);\n\n loaded.load(location);\n var params2 = loaded.parameters();\n Assert.True(params2.ToArray()[0].requires_grad);\n Assert.Equal(params0, params2);\n } finally {\n if (File.Exists(location)) File.Delete(location);\n }\n }\n\n private class TestModule1 : Module<torch.Tensor, torch.Tensor>\n {\n public TestModule1() : base(\"TestModule1\")\n {\n RegisterComponents();\n }\n\n public override torch.Tensor forward(torch.Tensor input)\n {\n throw new NotImplementedException();\n }\n\n private Parameter test = Parameter(torch.randn(new long[] { 2, 2 }));\n }\n\n\n [Fact]\n public void TestSaveLoadError_1()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n try {\n var linear = Linear(100, 10, true);\n var params0 = linear.parameters();\n linear.save(location);\n var loaded = Conv2d(100, 10, 5);\n Assert.Throws<ArgumentException>(() => loaded.load(location));\n } finally {\n if (File.Exists(location)) File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveLoadError_2()\n {\n var location = \"TestSaveLoadError_2.ts\";\n\n // Submodule count mismatch\n if (File.Exists(location)) File.Delete(location);\n try {\n var linear = Sequential((\"linear1\", Linear(100, 10, true)));\n var params0 = linear.parameters();\n linear.save(location);\n var loaded = Sequential((\"linear1\", Linear(100, 10, true)), (\"conv1\", Conv2d(100, 10, 5)));\n Assert.Throws<ArgumentException>(() => loaded.load(location));\n // Shouldn't get an error for this:\n loaded.load(location, strict: false);\n } finally {\n if (File.Exists(location)) File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveLoadError_3()\n {\n var location = RandomFileName(\"ts\");\n // Submodule name mismatch\n if (File.Exists(location)) File.Delete(location);\n try {\n var linear = Sequential((\"linear1\", Linear(100, 10, true)));\n var params0 = linear.parameters();\n linear.save(location);\n var loaded = Sequential((\"linear2\", Linear(100, 10, true)));\n Assert.Throws<ArgumentException>(() => loaded.load(location));\n File.Delete(location);\n } finally {\n if (File.Exists(location)) File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveLoadSequence()\n {\n if (File.Exists(\".model-list.txt\")) File.Delete(\".model-list.txt\");\n\n var lin1 = Linear(100, 10, true);\n var lin2 = Linear(10, 5, true);\n var seq = Sequential((\"lin1\", lin1), (\"lin2\", lin2));\n var params0 = seq.parameters();\n seq.save(\".model-list.txt\");\n\n var lin3 = Linear(100, 10, true);\n var lin4 = Linear(10, 5, true);\n var seq1 = Sequential((\"lin1\", lin3), (\"lin2\", lin4));\n seq1.load(\".model-list.txt\");\n File.Delete(\"model-list.txt\");\n\n var params1 = seq1.parameters();\n Assert.Equal(params0, params1);\n }\n\n [Fact]\n public void TestSaveLoadGruOnCPU()\n {\n var location = RandomFileName(\"ts\");\n // Works on CPU\n if (File.Exists(location)) File.Delete(location);\n try {\n var gru = GRU(2, 2, 2);\n var params0 = gru.parameters();\n gru.save(location);\n\n var loadedGru = GRU(2, 2, 2);\n loadedGru.load(location);\n var params1 = loadedGru.parameters();\n File.Delete(location);\n Assert.Equal(params0, params1);\n } finally {\n if (File.Exists(location)) File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveLoadGruOnCUDA()\n {\n var location = RandomFileName(\"ts\");\n if (torch.cuda.is_available()) {\n\n // Fails on CUDA\n if (File.Exists(location)) File.Delete(location);\n try {\n var gru = GRU(2, 2, 2);\n gru.to(DeviceType.CUDA);\n var params0 = gru.parameters().ToArray();\n Assert.Equal(DeviceType.CUDA, params0[0].device_type);\n\n gru.save(location);\n\n // Make sure the model is still on the GPU when we come back.\n\n params0 = gru.parameters().ToArray();\n Assert.Equal(DeviceType.CUDA, params0[0].device_type);\n\n var loadedGru = GRU(2, 2, 2);\n loadedGru.to(DeviceType.CUDA);\n loadedGru.load(location);\n var params1 = loadedGru.parameters().ToArray();\n\n Assert.Equal(DeviceType.CUDA, params1[0].device_type);\n\n File.Delete(location);\n Assert.Equal(params0, params1);\n } finally {\n if (File.Exists(location)) File.Delete(location);\n }\n\n }\n }\n\n [Fact]\n public void TestSummaryWriterLogDir()\n {\n var w1 = torch.utils.tensorboard.SummaryWriter(\"runs/123\");\n Assert.Equal(\"runs/123\", w1.LogDir);\n if (Directory.Exists(w1.LogDir)) {\n Directory.Delete(w1.LogDir, recursive: true);\n }\n\n var w2 = torch.utils.tensorboard.SummaryWriter(\"garbage\", createRunName: true);\n Assert.NotEqual(\"garbage\", w2.LogDir);\n Assert.StartsWith(\"garbage\", w2.LogDir);\n if (Directory.Exists(w2.LogDir)) {\n Directory.Delete(w2.LogDir, recursive: true);\n }\n }\n\n [Fact]\n public void TestTensorBoardScalar()\n {\n var writer = torch.utils.tensorboard.SummaryWriter();\n Assert.StartsWith(\"runs\", writer.LogDir);\n\n for (var i = 0; i < 100; i++) {\n writer.add_scalar(\"a/b\", MathF.Sin(i * MathF.PI / 8), i);\n }\n\n // Comment this out to look at the output data in tensorboard\n if (Directory.Exists(writer.LogDir)) {\n Directory.Delete(writer.LogDir, recursive: true);\n }\n }\n\n [Fact]\n public void TestTensorBoardScalars1()\n {\n var writer = torch.utils.tensorboard.SummaryWriter();\n for (var i = 0; i < 100; i++) {\n float f = i;\n writer.add_scalars(\"run_14h\", new Dictionary<string, float> {\n { \"sin\",i* MathF.Sin(f / 5) },\n { \"cos\", i* MathF.Cos(f / 5) },\n { \"tan\", MathF.Tan(f / 5) }\n }, i);\n }\n\n // Comment this out to look at the output data in tensorboard\n if (Directory.Exists(writer.LogDir)) {\n Directory.Delete(writer.LogDir, recursive: true);\n }\n }\n\n [Fact]\n public void TestTensorBoardScalars2()\n {\n var writer = torch.utils.tensorboard.SummaryWriter();\n for (var i = 0; i < 100; i++) {\n float f = i;\n writer.add_scalars(\"run_14h\", new[] {\n (\"sin\",i* MathF.Sin(f / 5)),\n (\"cos\", i* MathF.Cos(f / 5)),\n (\"tan\", MathF.Tan(f / 5))\n }, i);\n }\n\n // Comment this out to look at the output data in tensorboard\n if (Directory.Exists(writer.LogDir)) {\n Directory.Delete(writer.LogDir, recursive: true);\n }\n }\n\n [Fact]\n public void TestSaveRprop()\n {\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.Rprop(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.Rprop(seq.parameters(), 0.5, 0.01, 1.25, 1e-8, 35);\n optim2.load_state_dict(sd);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.Rprop.Options;\n var opt2 = sd2.Options[i] as Modules.Rprop.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.etaminus, opt2!.etaminus),\n () => Assert.Equal(opt!.etaplus, opt2!.etaplus),\n () => Assert.Equal(opt!.min_step, opt2!.min_step),\n () => Assert.Equal(opt!.max_step, opt2!.max_step)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.Rprop.State;\n var opt2 = sd2.State[i] as Modules.Rprop.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n }\n\n [Fact]\n public void TestSaveRpropFile()\n {\n var location = RandomFileName(\"ts\");\n\n if (File.Exists(location)) File.Delete(location);\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.Rprop(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.Rprop(seq.parameters(), 0.5, 0.01, 1.25, 1e-8, 35);\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.Rprop.Options;\n var opt2 = sd2.Options[i] as Modules.Rprop.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.etaminus, opt2!.etaminus),\n () => Assert.Equal(opt!.etaplus, opt2!.etaplus),\n () => Assert.Equal(opt!.min_step, opt2!.min_step),\n () => Assert.Equal(opt!.max_step, opt2!.max_step)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.Rprop.State;\n var opt2 = sd2.State[i] as Modules.Rprop.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveSGD()\n {\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.SGD(seq.parameters(), 0.01);\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.SGD(seq.parameters(), 0.5, 0.01, 1.25, 1e-8);\n optim2.load_state_dict(sd);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.SGD.Options;\n var opt2 = sd2.Options[i] as Modules.SGD.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.momentum, opt2!.momentum),\n () => Assert.Equal(opt!.dampening, opt2!.dampening),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.SGD.State;\n var opt2 = sd2.State[i] as Modules.SGD.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n }\n\n [Fact]\n public void TestSaveSGDFile()\n {\n var location = RandomFileName(\"ts\");\n\n if (File.Exists(location)) File.Delete(location);\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.SGD(seq.parameters(), 0.01);\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.SGD(seq.parameters(), 0.5, 0.01, 1.25, 1e-8);\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.SGD.Options;\n var opt2 = sd2.Options[i] as Modules.SGD.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.momentum, opt2!.momentum),\n () => Assert.Equal(opt!.dampening, opt2!.dampening),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.SGD.State;\n var opt2 = sd2.State[i] as Modules.SGD.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveSGDFile2()\n {\n var location = RandomFileName(\"ts\");\n\n if (File.Exists(location)) File.Delete(location);\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.SGD(seq.parameters(), 0.01);\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.SGD(seq.parameters(), 0.5, 0.01, 1.25, 1e-8);\n\n // Force the SGD momentum_buffer to be created.\n\n using var x = torch.randn(new long[] { 64, 10 });\n using var y = torch.randn(new long[] { 64, 10 });\n\n var loss = torch.nn.MSELoss(Reduction.Sum);\n\n using var eval = seq.call(x);\n var output = loss.call(eval, y);\n\n var l = output.ToSingle();\n\n optim2.zero_grad();\n\n output.backward();\n\n optim2.step();\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.SGD.Options;\n var opt2 = sd2.Options[i] as Modules.SGD.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.momentum, opt2!.momentum),\n () => Assert.Equal(opt!.dampening, opt2!.dampening),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.SGD.State;\n var opt2 = sd2.State[i] as Modules.SGD.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveSGDFile3()\n {\n var location = RandomFileName(\"ts\");\n\n if (File.Exists(location)) File.Delete(location);\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.SGD(seq.parameters(), 0.01, 0.025);\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.SGD(seq.parameters(), 0.5, 0.01, 1.25, 1e-8);\n\n // Force the SGD momentum_buffer to be created.\n\n using var x = torch.randn(new long[] { 64, 10 });\n using var y = torch.randn(new long[] { 64, 10 });\n\n var loss = torch.nn.MSELoss(Reduction.Sum);\n\n using var eval = seq.call(x);\n var output = loss.call(eval, y);\n\n var l = output.ToSingle();\n\n optim.zero_grad();\n\n output.backward();\n\n optim.step();\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.SGD.Options;\n var opt2 = sd2.Options[i] as Modules.SGD.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.momentum, opt2!.momentum),\n () => Assert.Equal(opt!.dampening, opt2!.dampening),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.SGD.State;\n var opt2 = sd2.State[i] as Modules.SGD.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveASGD()\n {\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.ASGD(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.ASGD(seq.parameters(), 0.5, 0.01, 1.25, 1e-8, 0.25);\n optim2.load_state_dict(sd);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.ASGD.Options;\n var opt2 = sd2.Options[i] as Modules.ASGD.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.lambd, opt2!.lambd),\n () => Assert.Equal(opt!.alpha, opt2!.alpha),\n () => Assert.Equal(opt!.t0, opt2!.t0),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.ASGD.State;\n var opt2 = sd2.State[i] as Modules.ASGD.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n }\n\n [Fact]\n public void TestSaveASGDFile()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.ASGD(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.ASGD(seq.parameters(), 0.5, 0.01, 1.25, 1e-8, 0.25);\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.ASGD.Options;\n var opt2 = sd2.Options[i] as Modules.ASGD.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.lambd, opt2!.lambd),\n () => Assert.Equal(opt!.alpha, opt2!.alpha),\n () => Assert.Equal(opt!.t0, opt2!.t0),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.ASGD.State;\n var opt2 = sd2.State[i] as Modules.ASGD.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveRMSProp()\n {\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.RMSProp(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.RMSProp(seq.parameters(), 0.5, 0.01, 1.25, 1e-8, 0.25);\n optim2.load_state_dict(sd);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.RMSProp.Options;\n var opt2 = sd2.Options[i] as Modules.RMSProp.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.momentum, opt2!.momentum),\n () => Assert.Equal(opt!.alpha, opt2!.alpha),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.RMSProp.State;\n var opt2 = sd2.State[i] as Modules.RMSProp.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n }\n\n [Fact]\n public void TestSaveRMSPropFile()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.RMSProp(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.RMSProp(seq.parameters(), 0.5, 0.01, 1.25, 1e-8, 0.25);\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.RMSProp.Options;\n var opt2 = sd2.Options[i] as Modules.RMSProp.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.momentum, opt2!.momentum),\n () => Assert.Equal(opt!.alpha, opt2!.alpha),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.RMSProp.State;\n var opt2 = sd2.State[i] as Modules.RMSProp.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveRAdam()\n {\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.RAdam(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.RAdam(seq.parameters(), 0.5, 0.01, 0.75, 1e-8, 0.25);\n optim2.load_state_dict(sd);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.RAdam.Options;\n var opt2 = sd2.Options[i] as Modules.RAdam.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.beta1, opt2!.beta1),\n () => Assert.Equal(opt!.beta2, opt2!.beta2),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.RAdam.State;\n var opt2 = sd2.State[i] as Modules.RAdam.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n }\n\n [Fact]\n public void TestSaveRAdamFile()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.RAdam(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.RAdam(seq.parameters(), 0.5, 0.01, 0.75, 1e-8, 0.25);\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.RAdam.Options;\n var opt2 = sd2.Options[i] as Modules.RAdam.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.beta1, opt2!.beta1),\n () => Assert.Equal(opt!.beta2, opt2!.beta2),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.RAdam.State;\n var opt2 = sd2.State[i] as Modules.RAdam.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveNAdam()\n {\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.NAdam(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.NAdam(seq.parameters(), 0.5, 0.01, 0.75, 1e-8, 0.25);\n optim2.load_state_dict(sd);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.NAdam.Options;\n var opt2 = sd2.Options[i] as Modules.NAdam.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.beta1, opt2!.beta1),\n () => Assert.Equal(opt!.beta2, opt2!.beta2),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay),\n () => Assert.Equal(opt!.momentum_decay, opt2!.momentum_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.NAdam.State;\n var opt2 = sd2.State[i] as Modules.NAdam.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n }\n\n [Fact]\n public void TestSaveNAdamFile()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.NAdam(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.NAdam(seq.parameters(), 0.5, 0.01, 0.75, 1e-8, 0.25);\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.NAdam.Options;\n var opt2 = sd2.Options[i] as Modules.NAdam.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.beta1, opt2!.beta1),\n () => Assert.Equal(opt!.beta2, opt2!.beta2),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay),\n () => Assert.Equal(opt!.momentum_decay, opt2!.momentum_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.NAdam.State;\n var opt2 = sd2.State[i] as Modules.NAdam.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveAdam()\n {\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.Adam(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.Adam(seq.parameters(), 0.5, 0.01, 0.75, 1e-8, 0.25);\n optim2.load_state_dict(sd);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.Adam.Options;\n var opt2 = sd2.Options[i] as Modules.Adam.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.beta1, opt2!.beta1),\n () => Assert.Equal(opt!.beta2, opt2!.beta2),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay),\n () => Assert.Equal(opt!.amsgrad, opt2!.amsgrad),\n () => Assert.Equal(opt!.maximize, opt2!.maximize)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.Adam.State;\n var opt2 = sd2.State[i] as Modules.Adam.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n }\n\n [Fact]\n public void TestSaveAdamFile()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.Adam(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.Adam(seq.parameters(), 0.5, 0.01, 0.75, 1e-8, 0.25);\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.Adam.Options;\n var opt2 = sd2.Options[i] as Modules.Adam.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.beta1, opt2!.beta1),\n () => Assert.Equal(opt!.beta2, opt2!.beta2),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay),\n () => Assert.Equal(opt!.amsgrad, opt2!.amsgrad),\n () => Assert.Equal(opt!.maximize, opt2!.maximize)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.Adam.State;\n var opt2 = sd2.State[i] as Modules.Adam.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveAdamFile2()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.Adam(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.Adam(seq.parameters(), 0.5, 0.01, 0.75, 1e-8, 0.25, true);\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.Adam.Options;\n var opt2 = sd2.Options[i] as Modules.Adam.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.beta1, opt2!.beta1),\n () => Assert.Equal(opt!.beta2, opt2!.beta2),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay),\n () => Assert.Equal(opt!.amsgrad, opt2!.amsgrad),\n () => Assert.Equal(opt!.maximize, opt2!.maximize)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.Adam.State;\n var opt2 = sd2.State[i] as Modules.Adam.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveAdamFile3()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.Adam(seq.parameters(), amsgrad: true);\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.Adam(seq.parameters(), 0.5, 0.01, 0.75, 1e-8, 0.25);\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.Adam.Options;\n var opt2 = sd2.Options[i] as Modules.Adam.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.beta1, opt2!.beta1),\n () => Assert.Equal(opt!.beta2, opt2!.beta2),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay),\n () => Assert.Equal(opt!.amsgrad, opt2!.amsgrad),\n () => Assert.Equal(opt!.maximize, opt2!.maximize)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.Adam.State;\n var opt2 = sd2.State[i] as Modules.Adam.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveAdamW()\n {\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.AdamW(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.AdamW(seq.parameters(), 0.5, 0.01, 0.75, 1e-8, 0.25);\n optim2.load_state_dict(sd);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.AdamW.Options;\n var opt2 = sd2.Options[i] as Modules.AdamW.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.beta1, opt2!.beta1),\n () => Assert.Equal(opt!.beta2, opt2!.beta2),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay),\n () => Assert.Equal(opt!.amsgrad, opt2!.amsgrad),\n () => Assert.Equal(opt!.maximize, opt2!.maximize)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.AdamW.State;\n var opt2 = sd2.State[i] as Modules.AdamW.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n }\n\n [Fact]\n public void TestSaveAdamWFile()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.AdamW(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.AdamW(seq.parameters(), 0.5, 0.01, 0.75, 1e-8, 0.25);\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.AdamW.Options;\n var opt2 = sd2.Options[i] as Modules.AdamW.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.beta1, opt2!.beta1),\n () => Assert.Equal(opt!.beta2, opt2!.beta2),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay),\n () => Assert.Equal(opt!.amsgrad, opt2!.amsgrad),\n () => Assert.Equal(opt!.maximize, opt2!.maximize)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.AdamW.State;\n var opt2 = sd2.State[i] as Modules.AdamW.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveAdamWFile2()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.AdamW(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.AdamW(seq.parameters(), 0.5, 0.01, 0.75, 1e-8, 0.25, true);\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.AdamW.Options;\n var opt2 = sd2.Options[i] as Modules.AdamW.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.beta1, opt2!.beta1),\n () => Assert.Equal(opt!.beta2, opt2!.beta2),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay),\n () => Assert.Equal(opt!.amsgrad, opt2!.amsgrad),\n () => Assert.Equal(opt!.maximize, opt2!.maximize)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.AdamW.State;\n var opt2 = sd2.State[i] as Modules.AdamW.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveAdamWFile3()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.AdamW(seq.parameters(), amsgrad: true);\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.AdamW(seq.parameters(), 0.5, 0.01, 0.75, 1e-8, 0.25);\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.AdamW.Options;\n var opt2 = sd2.Options[i] as Modules.AdamW.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.beta1, opt2!.beta1),\n () => Assert.Equal(opt!.beta2, opt2!.beta2),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay),\n () => Assert.Equal(opt!.amsgrad, opt2!.amsgrad),\n () => Assert.Equal(opt!.maximize, opt2!.maximize)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.AdamW.State;\n var opt2 = sd2.State[i] as Modules.AdamW.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveAdamax()\n {\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.Adamax(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.Adamax(seq.parameters(), 0.5, 0.01, 0.75, 1e-8, 0.25);\n optim2.load_state_dict(sd);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.Adamax.Options;\n var opt2 = sd2.Options[i] as Modules.Adamax.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.beta1, opt2!.beta1),\n () => Assert.Equal(opt!.beta2, opt2!.beta2),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.Adamax.State;\n var opt2 = sd2.State[i] as Modules.Adamax.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n }\n\n [Fact]\n public void TestSaveAdamaxFile()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.Adamax(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.Adamax(seq.parameters(), 0.5, 0.01, 0.75, 1e-8, 0.25);\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.Adamax.Options;\n var opt2 = sd2.Options[i] as Modules.Adamax.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.beta1, opt2!.beta1),\n () => Assert.Equal(opt!.beta2, opt2!.beta2),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.Adamax.State;\n var opt2 = sd2.State[i] as Modules.Adamax.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveAdagrad()\n {\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.Adagrad(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.Adagrad(seq.parameters(), 0.5, 0.01, 0.75, 1e-8, 0.25);\n optim2.load_state_dict(sd);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.Adagrad.Options;\n var opt2 = sd2.Options[i] as Modules.Adagrad.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.lr_decay, opt2!.lr_decay),\n () => Assert.Equal(opt!.initial_accumulator_value, opt2!.initial_accumulator_value),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.Adagrad.State;\n var opt2 = sd2.State[i] as Modules.Adagrad.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n }\n\n [Fact(Skip = \"Often takes a very long time. No idea why.\")]\n public void TestSaveAdagradFile()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.Adagrad(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.Adagrad(seq.parameters(), 0.5, 0.01, 0.75, 1e-8, 0.25);\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.Adagrad.Options;\n var opt2 = sd2.Options[i] as Modules.Adagrad.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.lr_decay, opt2!.lr_decay),\n () => Assert.Equal(opt!.initial_accumulator_value, opt2!.initial_accumulator_value),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.Adagrad.State;\n var opt2 = sd2.State[i] as Modules.Adagrad.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestSaveAdadelta()\n {\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.Adadelta(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.Adadelta(seq.parameters(), 0.5, 0.01, 1e-8, 0.25);\n optim2.load_state_dict(sd);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.Adadelta.Options;\n var opt2 = sd2.Options[i] as Modules.Adadelta.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.rho, opt2!.rho),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.Adadelta.State;\n var opt2 = sd2.State[i] as Modules.Adadelta.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n }\n\n [Fact]\n public void TestSaveAdadeltaFile()\n {\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim = torch.optim.Adadelta(seq.parameters());\n\n var sd = optim.state_dict();\n Assert.Multiple(\n () => Assert.Equal(4, sd.State.Count),\n () => Assert.Single(sd.Options)\n );\n\n var optim2 = torch.optim.Adadelta(seq.parameters(), 0.5, 0.01, 1e-8, 0.25);\n\n try {\n optim.save_state_dict(location);\n optim2.load_state_dict(location);\n\n var sd2 = optim2.state_dict();\n\n Assert.Multiple(\n () => Assert.Equal(4, sd2.State.Count),\n () => Assert.Single(sd2.Options)\n );\n\n for (int i = 0; i < sd.Options.Count; i++) {\n var opt = sd.Options[i] as Modules.Adadelta.Options;\n var opt2 = sd2.Options[i] as Modules.Adadelta.Options;\n Assert.Multiple(\n () => Assert.Equal(opt!.InitialLearningRate, opt2!.InitialLearningRate),\n () => Assert.Equal(opt!.LearningRate, opt2!.LearningRate),\n () => Assert.Equal(opt!.rho, opt2!.rho),\n () => Assert.Equal(opt!.eps, opt2!.eps),\n () => Assert.Equal(opt!.weight_decay, opt2!.weight_decay)\n );\n }\n for (int i = 0; i < sd.State.Count; i++) {\n var opt = sd.State[i] as Modules.Adadelta.State;\n var opt2 = sd2.State[i] as Modules.Adadelta.State;\n Assert.True(opt!.ApproximatelyEquals(opt2));\n }\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestMisMatchedFile()\n {\n\n var location = RandomFileName(\"ts\");\n if (File.Exists(location)) File.Delete(location);\n\n var l1 = Linear(10, 10, true);\n var l2 = Linear(10, 10, true);\n var seq = Sequential(l1, l2);\n\n var optim1 = torch.optim.SGD(seq.parameters(), 0.05);\n\n try {\n optim1.save_state_dict(location);\n Assert.Throws<InvalidDataException>(() => torch.optim.ASGD(seq.parameters()).load_state_dict(location));\n Assert.Throws<InvalidDataException>(() => torch.optim.Rprop(seq.parameters()).load_state_dict(location));\n Assert.Throws<InvalidDataException>(() => torch.optim.RMSProp(seq.parameters()).load_state_dict(location));\n Assert.Throws<InvalidDataException>(() => torch.optim.RAdam(seq.parameters()).load_state_dict(location));\n Assert.Throws<InvalidDataException>(() => torch.optim.NAdam(seq.parameters()).load_state_dict(location));\n Assert.Throws<InvalidDataException>(() => torch.optim.Adam(seq.parameters()).load_state_dict(location));\n Assert.Throws<InvalidDataException>(() => torch.optim.AdamW(seq.parameters()).load_state_dict(location));\n Assert.Throws<InvalidDataException>(() => torch.optim.Adamax(seq.parameters()).load_state_dict(location));\n Assert.Throws<InvalidDataException>(() => torch.optim.Adagrad(seq.parameters()).load_state_dict(location));\n Assert.Throws<InvalidDataException>(() => torch.optim.Adadelta(seq.parameters()).load_state_dict(location));\n } finally {\n File.Delete(location);\n }\n }\n\n [Fact]\n public void TestLoadingSGDStateFromPython()\n {\n var lin = torch.nn.Linear(10, 10);\n\n double learning_rate = 0.00004f;\n var optimizer = torch.optim.SGD(lin.parameters(), learning_rate);\n\n optimizer.load_state_dict(\"sgd1.dat\");\n\n var sd = optimizer.state_dict();\n\n Assert.Single(sd.Options);\n Assert.Equal(2, sd.State.Count);\n\n foreach (var opts in sd.Options) {\n var options = opts as Modules.SGD.Options;\n Assert.Equal(0.1, options!.momentum);\n Assert.NotEqual(learning_rate, options!.LearningRate);\n }\n\n foreach (var st in sd.State) {\n var state = st as Modules.SGD.State;\n Assert.NotNull(state!.momentum_buffer);\n }\n }\n\n [Fact]\n public void TestLoadingASGDStateFromPython()\n {\n var lin = torch.nn.Linear(10, 10);\n\n double learning_rate = 0.004f;\n var optimizer = torch.optim.ASGD(lin.parameters(), learning_rate);\n\n optimizer.load_state_dict(\"asgd1.dat\");\n\n var sd = optimizer.state_dict();\n\n Assert.Single(sd.Options);\n Assert.Equal(2, sd.State.Count);\n\n foreach (var opts in sd.Options) {\n var options = opts as Modules.ASGD.Options;\n Assert.Equal(0.65, options!.alpha);\n Assert.Equal(1e-3, options!.lambd);\n Assert.Equal(1e5, options!.t0);\n Assert.NotEqual(learning_rate, options!.LearningRate);\n }\n\n foreach (var st in sd.State) {\n var state = st as Modules.ASGD.State;\n Assert.Equal(1, state!.step);\n Assert.NotNull(state!.ax);\n }\n }\n\n [Fact]\n public void TestLoadingRMSpropStateFromPython()\n {\n var lin1 = torch.nn.Linear(10, 10);\n var lin2 = torch.nn.Linear(10, 10);\n\n var seq = Sequential((\"lin1\", lin1), (\"lin2\", lin2));\n\n var pgs = new RMSProp.ParamGroup[] {\n new () { Parameters = lin1.parameters(), Options = new() { LearningRate = 0.00005 } },\n new (lin2.parameters(), lr: 0.00003, centered: false, momentum: 0.25)\n };\n\n double learning_rate = 0.00004f;\n var optimizer = torch.optim.RMSProp(pgs, learning_rate);\n\n optimizer.load_state_dict(\"rmsprop1.dat\");\n\n var sd = optimizer.state_dict();\n\n Assert.Equal(2, sd.Options.Count);\n Assert.Equal(4, sd.State.Count);\n\n var options = sd.Options[0] as Modules.RMSProp.Options;\n Assert.Multiple(\n () => Assert.Equal(0.1, options!.momentum),\n () => Assert.Equal(0.001, options!.LearningRate),\n () => Assert.False(options!.centered)\n );\n\n options = sd.Options[1] as Modules.RMSProp.Options;\n Assert.Multiple(\n () => Assert.Equal(0, options!.momentum),\n () => Assert.Equal(0.01, options!.LearningRate),\n () => Assert.True(options!.centered)\n );\n\n var state = sd.State[0] as Modules.RMSProp.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.square_avg),\n () => Assert.NotNull(state!.momentum_buffer),\n () => Assert.Null(state!.grad_avg)\n );\n\n state = sd.State[1] as Modules.RMSProp.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.square_avg),\n () => Assert.NotNull(state!.momentum_buffer),\n () => Assert.Null(state!.grad_avg)\n );\n\n state = sd.State[2] as Modules.RMSProp.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.square_avg),\n () => Assert.Null(state!.momentum_buffer),\n () => Assert.NotNull(state!.grad_avg)\n );\n\n state = sd.State[3] as Modules.RMSProp.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.square_avg),\n () => Assert.Null(state!.momentum_buffer),\n () => Assert.NotNull(state!.grad_avg)\n );\n }\n\n [Fact]\n public void TestLoadingRpropStateFromPython()\n {\n var lin1 = torch.nn.Linear(10, 10);\n var lin2 = torch.nn.Linear(10, 10);\n\n var seq = Sequential((\"lin1\", lin1), (\"lin2\", lin2));\n\n var pgs = new Rprop.ParamGroup[] {\n new () { Parameters = lin1.parameters(), Options = new() { LearningRate = 0.00005 } },\n new (lin2.parameters(), lr: 0.00003, maximize: false)\n };\n\n double learning_rate = 0.00004f;\n var optimizer = torch.optim.Rprop(pgs, learning_rate);\n\n optimizer.load_state_dict(\"rprop1.dat\");\n\n var sd = optimizer.state_dict();\n\n Assert.Equal(2, sd.Options.Count);\n Assert.Equal(4, sd.State.Count);\n\n var options = sd.Options[0] as Modules.Rprop.Options;\n Assert.Multiple(\n () => Assert.Equal(0.35, options!.etaminus),\n () => Assert.Equal(1.5, options!.etaplus),\n () => Assert.Equal(1e-5, options!.min_step),\n () => Assert.Equal(5, options!.max_step),\n () => Assert.Equal(0.001, options!.LearningRate),\n () => Assert.False(options!.maximize)\n );\n\n options = sd.Options[1] as Modules.Rprop.Options;\n Assert.Multiple(\n () => Assert.Equal(0.45, options!.etaminus),\n () => Assert.Equal(1.5, options!.etaplus),\n () => Assert.Equal(1e-5, options!.min_step),\n () => Assert.Equal(5, options!.max_step),\n () => Assert.Equal(0.01, options!.LearningRate),\n () => Assert.True(options!.maximize)\n );\n\n foreach (var st in sd.State) {\n var state = sd.State[0] as Modules.Rprop.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.prev),\n () => Assert.NotNull(state!.step_size)\n );\n }\n }\n\n [Fact]\n public void TestLoadingAdamStateFromPython()\n {\n var lin1 = torch.nn.Linear(10, 10);\n var lin2 = torch.nn.Linear(10, 10);\n\n var seq = Sequential((\"lin1\", lin1), (\"lin2\", lin2));\n\n var pgs = new Adam.ParamGroup[] {\n new () { Parameters = lin1.parameters(), Options = new() { LearningRate = 0.00005 } },\n new (lin2.parameters(), lr: 0.00003, amsgrad: false, beta1: 0.25)\n };\n\n double learning_rate = 0.00004f;\n var optimizer = torch.optim.Adam(pgs, learning_rate);\n\n optimizer.load_state_dict(\"adam1.dat\");\n\n var sd = optimizer.state_dict();\n\n Assert.Equal(2, sd.Options.Count);\n Assert.Equal(4, sd.State.Count);\n\n var options = sd.Options[0] as Modules.Adam.Options;\n Assert.Multiple(\n () => Assert.Equal(0.8, options!.beta1),\n () => Assert.Equal(0.9, options!.beta2),\n () => Assert.Equal(0.001, options!.LearningRate),\n () => Assert.False(options!.amsgrad)\n );\n\n options = sd.Options[1] as Modules.Adam.Options;\n Assert.Multiple(\n () => Assert.Equal(0.7, options!.beta1),\n () => Assert.Equal(0.79, options!.beta2),\n () => Assert.Equal(0.01, options!.LearningRate),\n () => Assert.True(options!.amsgrad)\n );\n\n var state = sd.State[0] as Modules.Adam.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_avg_sq),\n () => Assert.Null(state!.max_exp_avg_sq)\n );\n\n state = sd.State[1] as Modules.Adam.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_avg_sq),\n () => Assert.Null(state!.max_exp_avg_sq)\n );\n\n state = sd.State[2] as Modules.Adam.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_avg_sq),\n () => Assert.NotNull(state!.max_exp_avg_sq)\n );\n\n state = sd.State[3] as Modules.Adam.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_avg_sq),\n () => Assert.NotNull(state!.max_exp_avg_sq)\n );\n }\n\n [Fact]\n public void TestLoadingAdamWStateFromPython()\n {\n var lin1 = torch.nn.Linear(10, 10);\n var lin2 = torch.nn.Linear(10, 10);\n\n var seq = Sequential((\"lin1\", lin1), (\"lin2\", lin2));\n\n var pgs = new AdamW.ParamGroup[] {\n new () { Parameters = lin1.parameters(), Options = new() { LearningRate = 0.00005 } },\n new (lin2.parameters(), lr: 0.00003, amsgrad: false, beta1: 0.25)\n };\n\n double learning_rate = 0.00004f;\n var optimizer = torch.optim.AdamW(pgs, learning_rate);\n\n optimizer.load_state_dict(\"adamw1.dat\");\n\n var sd = optimizer.state_dict();\n\n Assert.Equal(2, sd.Options.Count);\n Assert.Equal(4, sd.State.Count);\n\n var options = sd.Options[0] as Modules.AdamW.Options;\n Assert.Multiple(\n () => Assert.Equal(0.8, options!.beta1),\n () => Assert.Equal(0.9, options!.beta2),\n () => Assert.Equal(0.001, options!.LearningRate),\n () => Assert.False(options!.amsgrad)\n );\n\n options = sd.Options[1] as Modules.AdamW.Options;\n Assert.Multiple(\n () => Assert.Equal(0.7, options!.beta1),\n () => Assert.Equal(0.79, options!.beta2),\n () => Assert.Equal(0.01, options!.LearningRate),\n () => Assert.True(options!.amsgrad)\n );\n\n var state = sd.State[0] as Modules.AdamW.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_avg_sq),\n () => Assert.Null(state!.max_exp_avg_sq)\n );\n\n state = sd.State[1] as Modules.AdamW.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_avg_sq),\n () => Assert.Null(state!.max_exp_avg_sq)\n );\n\n state = sd.State[2] as Modules.AdamW.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_avg_sq),\n () => Assert.NotNull(state!.max_exp_avg_sq)\n );\n\n state = sd.State[3] as Modules.AdamW.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_avg_sq),\n () => Assert.NotNull(state!.max_exp_avg_sq)\n );\n }\n\n [Fact]\n public void TestLoadingNAdamStateFromPython()\n {\n var lin1 = torch.nn.Linear(10, 10);\n var lin2 = torch.nn.Linear(10, 10);\n\n var seq = Sequential((\"lin1\", lin1), (\"lin2\", lin2));\n\n var pgs = new NAdam.ParamGroup[] {\n new () { Parameters = lin1.parameters(), Options = new() { LearningRate = 0.00005 } },\n new (lin2.parameters(), lr: 0.00003, beta1: 0.25, weight_decay: 0.1)\n };\n\n double learning_rate = 0.00004f;\n var optimizer = torch.optim.NAdam(pgs, learning_rate);\n\n optimizer.load_state_dict(\"nadam1.dat\");\n\n var sd = optimizer.state_dict();\n\n Assert.Equal(2, sd.Options.Count);\n Assert.Equal(4, sd.State.Count);\n\n var options = sd.Options[0] as Modules.NAdam.Options;\n Assert.Multiple(\n () => Assert.Equal(0.8, options!.beta1),\n () => Assert.Equal(0.9, options!.beta2),\n () => Assert.Equal(0.001, options!.LearningRate),\n () => Assert.Equal(0, options!.weight_decay)\n );\n\n options = sd.Options[1] as Modules.NAdam.Options;\n Assert.Multiple(\n () => Assert.Equal(0.7, options!.beta1),\n () => Assert.Equal(0.79, options!.beta2),\n () => Assert.Equal(0.01, options!.LearningRate),\n () => Assert.Equal(0.3, options!.weight_decay)\n );\n\n foreach (var st in sd.State) {\n var state = st as Modules.NAdam.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_avg_sq)\n );\n }\n }\n\n [Fact]\n public void TestLoadingRAdamStateFromPython()\n {\n var lin1 = torch.nn.Linear(10, 10);\n var lin2 = torch.nn.Linear(10, 10);\n\n var seq = Sequential((\"lin1\", lin1), (\"lin2\", lin2));\n\n var pgs = new RAdam.ParamGroup[] {\n new () { Parameters = lin1.parameters(), Options = new() { LearningRate = 0.00005 } },\n new (lin2.parameters(), lr: 0.00003, beta1: 0.25)\n };\n\n double learning_rate = 0.00004f;\n var optimizer = torch.optim.RAdam(pgs, learning_rate);\n\n optimizer.load_state_dict(\"radam1.dat\");\n\n var sd = optimizer.state_dict();\n\n var options = sd.Options[0] as Modules.RAdam.Options;\n Assert.Multiple(\n () => Assert.Equal(0.8, options!.beta1),\n () => Assert.Equal(0.9, options!.beta2),\n () => Assert.Equal(0.001, options!.LearningRate),\n () => Assert.Equal(0, options!.weight_decay)\n );\n\n options = sd.Options[1] as Modules.RAdam.Options;\n Assert.Multiple(\n () => Assert.Equal(0.7, options!.beta1),\n () => Assert.Equal(0.79, options!.beta2),\n () => Assert.Equal(0.01, options!.LearningRate),\n () => Assert.Equal(0.3, options!.weight_decay)\n );\n\n foreach (var st in sd.State) {\n var state = st as Modules.RAdam.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_avg_sq)\n );\n }\n }\n\n [Fact]\n public void TestLoadingAdadeltaStateFromPython()\n {\n var lin1 = torch.nn.Linear(10, 10);\n var lin2 = torch.nn.Linear(10, 10);\n\n var seq = Sequential((\"lin1\", lin1), (\"lin2\", lin2));\n\n var pgs = new Adadelta.ParamGroup[] {\n new () { Parameters = lin1.parameters(), Options = new() { LearningRate = 0.00005 } },\n new (lin2.parameters(), lr: 0.00003, maximize: false, rho: 0.25)\n };\n\n double learning_rate = 0.00004f;\n var optimizer = torch.optim.Adadelta(pgs, learning_rate);\n\n optimizer.load_state_dict(\"adadelta1.dat\");\n\n var sd = optimizer.state_dict();\n\n Assert.Equal(2, sd.Options.Count);\n Assert.Equal(4, sd.State.Count);\n\n var options = sd.Options[0] as Modules.Adadelta.Options;\n Assert.Multiple(\n () => Assert.Equal(0.85, options!.rho),\n () => Assert.Equal(0.3, options!.weight_decay),\n () => Assert.Equal(0.001, options!.LearningRate),\n () => Assert.False(options!.maximize)\n );\n\n options = sd.Options[1] as Modules.Adadelta.Options;\n Assert.Multiple(\n () => Assert.Equal(0.79, options!.rho),\n () => Assert.Equal(0.3, options!.weight_decay),\n () => Assert.Equal(0.01, options!.LearningRate),\n () => Assert.True(options!.maximize)\n );\n\n foreach (var st in sd.State) {\n var state = st as Modules.Adadelta.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.square_avg),\n () => Assert.NotNull(state!.acc_delta)\n );\n }\n }\n\n [Fact]\n public void TestLoadingAdagradStateFromPython()\n {\n var lin = torch.nn.Linear(10, 10);\n\n double learning_rate = 0.00004f;\n var optimizer = torch.optim.Adagrad(lin.parameters(), learning_rate);\n\n optimizer.load_state_dict(\"adagrad1.dat\");\n\n var sd = optimizer.state_dict();\n\n Assert.Single(sd.Options);\n Assert.Equal(2, sd.State.Count);\n\n foreach (var opts in sd.Options) {\n var options = opts as Modules.Adagrad.Options;\n Assert.Equal(0.85, options!.lr_decay);\n Assert.Equal(0.3, options!.weight_decay);\n Assert.NotEqual(learning_rate, options!.LearningRate);\n }\n\n foreach (var st in sd.State) {\n var state = st as Modules.Adagrad.State;\n Assert.Equal(1, state!.step);\n Assert.NotNull(state!.sum);\n }\n }\n\n [Fact]\n public void TestLoadingAdamaxStateFromPython()\n {\n var lin1 = torch.nn.Linear(10, 10);\n var lin2 = torch.nn.Linear(10, 10);\n\n var seq = Sequential((\"lin1\", lin1), (\"lin2\", lin2));\n\n var pgs = new Adamax.ParamGroup[] {\n new () { Parameters = lin1.parameters(), Options = new() { LearningRate = 0.00005 } },\n new (lin2.parameters(), lr: 0.00003, weight_decay: 0.25, beta1: 0.25)\n };\n\n double learning_rate = 0.00004f;\n var optimizer = torch.optim.Adamax(pgs, learning_rate);\n\n optimizer.load_state_dict(\"adamax1.dat\");\n\n var sd = optimizer.state_dict();\n\n Assert.Equal(2, sd.Options.Count);\n Assert.Equal(4, sd.State.Count);\n\n var options = sd.Options[0] as Modules.Adamax.Options;\n Assert.Multiple(\n () => Assert.Equal(0.8, options!.beta1),\n () => Assert.Equal(0.9, options!.beta2),\n () => Assert.Equal(0.001, options!.LearningRate),\n () => Assert.Equal(0, options!.weight_decay)\n );\n\n options = sd.Options[1] as Modules.Adamax.Options;\n Assert.Multiple(\n () => Assert.Equal(0.7, options!.beta1),\n () => Assert.Equal(0.79, options!.beta2),\n () => Assert.Equal(0.01, options!.LearningRate),\n () => Assert.Equal(0.3, options!.weight_decay)\n );\n\n var state = sd.State[0] as Modules.Adamax.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_inf)\n );\n\n state = sd.State[1] as Modules.Adamax.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_inf)\n );\n\n state = sd.State[2] as Modules.Adamax.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_inf)\n );\n\n state = sd.State[3] as Modules.Adamax.State;\n Assert.Multiple(\n () => Assert.Equal(1, state!.step),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_avg),\n () => Assert.NotNull(state!.exp_inf)\n );\n }\n }\n}\n" }, { "alpha_fraction": 0.5175543427467346, "alphanum_fraction": 0.5232505798339844, "avg_line_length": 42.73690414428711, "blob_id": "6d2895a61f8f3431c5674d3f44ef5a1981061133", "content_id": "0846ff4a3e4ee130a597d55fa8fa944e891ee370", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 37569, "license_type": "permissive", "max_line_length": 175, "num_lines": 859, "path": "/src/TorchAudio/Modules/Tacotron2.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchaudio,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/audio/blob/e502df0106403f7666f89fee09715256ea2e0df3/torchaudio/models/tacotron2.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/audio/blob/main/LICENSE\n//\n\n// *****************************************************************************\n// Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// * Neither the name of the NVIDIA CORPORATION nor the\n// names of its contributors may be used to endorse or promote products\n// derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY\n// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// *****************************************************************************\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing static TorchSharp.torch;\n\nusing static TorchSharp.torch.nn;\nusing F = TorchSharp.torch.nn.functional;\n\n#nullable enable\nnamespace TorchSharp.Modules\n{\n /// <summary>\n /// Tacotron2 model based on the implementation from\n /// Nvidia https://github.com/NVIDIA/DeepLearningExamples/.\n /// </summary>\n public class Tacotron2 : nn.Module<Tensor,Tensor,Tensor,Tensor, (Tensor, Tensor, Tensor, Tensor)>\n {\n public readonly bool mask_padding;\n public readonly int n_mels;\n public readonly int n_frames_per_step;\n\n private readonly Modules.Embedding embedding;\n private readonly Encoder encoder;\n private readonly Decoder decoder;\n private readonly Postnet postnet;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n embedding.Dispose();\n encoder.Dispose();\n decoder.Dispose();\n postnet.Dispose();\n }\n base.Dispose(disposing);\n }\n\n internal Tacotron2(\n string name,\n bool mask_padding = false,\n int n_mels = 80,\n int n_symbol = 148,\n int n_frames_per_step = 1,\n int symbol_embedding_dim = 512,\n int encoder_embedding_dim = 512,\n int encoder_n_convolution = 3,\n int encoder_kernel_size = 5,\n int decoder_rnn_dim = 1024,\n int decoder_max_step = 2000,\n double decoder_dropout = 0.1,\n bool decoder_early_stopping = true,\n int attention_rnn_dim = 1024,\n int attention_hidden_dim = 128,\n int attention_location_n_filter = 32,\n int attention_location_kernel_size = 31,\n double attention_dropout = 0.1,\n int prenet_dim = 256,\n int postnet_n_convolution = 5,\n int postnet_kernel_size = 5,\n int postnet_embedding_dim = 512,\n double gate_threshold = 0.5) : base(name)\n {\n this.mask_padding = mask_padding;\n this.n_mels = n_mels;\n this.n_frames_per_step = n_frames_per_step;\n this.embedding = nn.Embedding(n_symbol, symbol_embedding_dim);\n torch.nn.init.xavier_uniform_(this.embedding.weight);\n this.encoder = new Encoder(\"encoder\", encoder_embedding_dim, encoder_n_convolution, encoder_kernel_size);\n this.decoder = new Decoder(\n \"decoder\",\n n_mels,\n n_frames_per_step,\n encoder_embedding_dim,\n decoder_rnn_dim,\n decoder_max_step,\n decoder_dropout,\n decoder_early_stopping,\n attention_rnn_dim,\n attention_hidden_dim,\n attention_location_n_filter,\n attention_location_kernel_size,\n attention_dropout,\n prenet_dim,\n gate_threshold);\n this.postnet = new Postnet(\"postnet\", n_mels, postnet_embedding_dim, postnet_kernel_size, postnet_n_convolution);\n RegisterComponents();\n }\n\n public override (Tensor, Tensor, Tensor, Tensor) forward(\n Tensor tokens,\n Tensor token_lengths,\n Tensor mel_specgram,\n Tensor mel_specgram_lengths)\n {\n var embedded_inputs = this.embedding.call(tokens).transpose(1, 2);\n\n var encoder_outputs = this.encoder.call(embedded_inputs, token_lengths);\n var (x, gate_outputs, alignments) = this.decoder.call(\n encoder_outputs, mel_specgram, memory_lengths: token_lengths\n );\n mel_specgram = x;\n\n var mel_specgram_postnet = this.postnet.call(mel_specgram);\n mel_specgram_postnet = mel_specgram + mel_specgram_postnet;\n\n if (this.mask_padding) {\n var mask = _get_mask_from_lengths(mel_specgram_lengths);\n mask = mask.expand(this.n_mels, mask.size(0), mask.size(1));\n mask = mask.permute(1, 0, 2);\n\n mel_specgram = mel_specgram.masked_fill(mask, 0.0);\n mel_specgram_postnet = mel_specgram_postnet.masked_fill(mask, 0.0);\n gate_outputs = gate_outputs.masked_fill(mask[TensorIndex.Colon, 0, TensorIndex.Colon], 1e3);\n }\n\n return (mel_specgram, mel_specgram_postnet, gate_outputs, alignments);\n }\n\n public (Tensor, Tensor, Tensor) infer(\n Tensor tokens, Tensor? lengths = null)\n {\n var n_batch = tokens.shape[0];\n var max_length = tokens.shape[1];\n if (lengths is null) {\n lengths = torch.tensor(new long[] { max_length }).expand(n_batch).to(tokens.device).to(tokens.dtype);\n }\n\n if (lengths is null) {\n throw new ArgumentNullException();\n }\n\n var embedded_inputs = this.embedding.call(tokens).transpose(1, 2);\n var encoder_outputs = this.encoder.call(embedded_inputs, lengths);\n var (mel_specgram, mel_specgram_lengths, _, alignments) = this.decoder.infer(encoder_outputs, lengths);\n\n var mel_outputs_postnet = this.postnet.call(mel_specgram);\n mel_outputs_postnet = mel_specgram + mel_outputs_postnet;\n\n alignments = alignments.unfold(1, n_batch, n_batch).transpose(0, 2);\n\n return (mel_outputs_postnet, mel_specgram_lengths, alignments);\n }\n\n private static Modules.Linear _get_linear_layer(long in_dim, long out_dim, bool bias = true, init.NonlinearityType w_init_gain = init.NonlinearityType.Linear)\n {\n var linear = torch.nn.Linear(in_dim, out_dim, hasBias: bias);\n torch.nn.init.xavier_uniform_(linear.weight, gain: torch.nn.init.calculate_gain(w_init_gain));\n return linear;\n }\n\n private static Modules.Conv1d _get_conv1d_layer(\n int in_channels,\n int out_channels,\n int kernel_size = 1,\n int stride = 1,\n long? padding = null,\n int dilation = 1,\n bool bias = true,\n init.NonlinearityType w_init_gain = init.NonlinearityType.Linear)\n {\n if (padding is null) {\n if (kernel_size % 2 != 1) {\n throw new ArgumentException(\"kernel_size must be odd\");\n }\n padding = dilation * (kernel_size - 1) / 2;\n }\n\n var conv1d = torch.nn.Conv1d(\n in_channels,\n out_channels,\n kernelSize: kernel_size,\n stride: stride,\n padding: padding.Value,\n dilation: dilation,\n bias: bias);\n\n torch.nn.init.xavier_uniform_(conv1d.weight, gain: torch.nn.init.calculate_gain(w_init_gain));\n\n return conv1d;\n }\n\n private static Tensor _get_mask_from_lengths(Tensor lengths)\n {\n var max_len = torch.max(lengths).item<int>();\n var ids = torch.arange(0, max_len, device: lengths.device, dtype: lengths.dtype);\n var mask = (ids < lengths.unsqueeze(1)).to(torch.uint8);\n mask = torch.le(mask, 0);\n return mask;\n }\n\n private class LocationLayer : nn.Module<Tensor, Tensor>\n {\n private readonly Modules.Conv1d location_conv;\n private readonly Modules.Linear location_dense;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n location_conv.Dispose();\n location_dense.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public LocationLayer(\n string name,\n int attention_n_filter,\n int attention_kernel_size,\n int attention_hidden_dim) : base(name)\n {\n var padding = (attention_kernel_size - 1) / 2;\n this.location_conv = _get_conv1d_layer(\n 2,\n attention_n_filter,\n kernel_size: attention_kernel_size,\n padding: padding,\n bias: false,\n stride: 1,\n dilation: 1);\n this.location_dense = _get_linear_layer(\n attention_n_filter,\n attention_hidden_dim,\n bias: false,\n w_init_gain: init.NonlinearityType.Tanh);\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor attention_weights_cat)\n {\n // (n_batch, attention_n_filter, text_lengths.max())\n var processed_attention = this.location_conv.call(attention_weights_cat);\n processed_attention = processed_attention.transpose(1, 2);\n // (n_batch, text_lengths.max(), attention_hidden_dim)\n processed_attention = this.location_dense.call(processed_attention);\n return processed_attention;\n }\n }\n\n private class Attention : nn.Module<Tensor,Tensor,Tensor,Tensor,Tensor, (Tensor, Tensor)>\n {\n private readonly LocationLayer location_layer;\n public readonly Modules.Linear memory_layer;\n private readonly Modules.Linear query_layer;\n public readonly float score_mask_value;\n private readonly Modules.Linear v;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n location_layer.Dispose();\n memory_layer.Dispose();\n query_layer.Dispose();\n v.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public Attention(\n string name,\n int attention_rnn_dim,\n int encoder_embedding_dim,\n int attention_hidden_dim,\n int attention_location_n_filter,\n int attention_location_kernel_size) : base(name)\n {\n this.query_layer = _get_linear_layer(attention_rnn_dim, attention_hidden_dim, bias: false, w_init_gain: init.NonlinearityType.Tanh);\n this.memory_layer = _get_linear_layer(\n encoder_embedding_dim, attention_hidden_dim, bias: false, w_init_gain: init.NonlinearityType.Tanh);\n this.v = _get_linear_layer(attention_hidden_dim, 1, bias: false);\n this.location_layer = new LocationLayer(\n \"location_layer\",\n attention_location_n_filter,\n attention_location_kernel_size,\n attention_hidden_dim);\n this.score_mask_value = float.NegativeInfinity;\n RegisterComponents();\n }\n\n private Tensor _get_alignment_energies(Tensor query, Tensor processed_memory, Tensor attention_weights_cat)\n {\n var processed_query = this.query_layer.call(query.unsqueeze(1));\n var processed_attention_weights = this.location_layer.call(attention_weights_cat);\n var energies = this.v.call(torch.tanh(processed_query + processed_attention_weights + processed_memory));\n\n var alignment = energies.squeeze(2);\n return alignment;\n }\n\n public override (Tensor, Tensor) forward(\n Tensor attention_hidden_state,\n Tensor memory,\n Tensor processed_memory,\n Tensor attention_weights_cat,\n Tensor mask)\n {\n var alignment = this._get_alignment_energies(attention_hidden_state, processed_memory, attention_weights_cat);\n\n alignment = alignment.masked_fill(mask, this.score_mask_value);\n\n var attention_weights = F.softmax(alignment, dim: 1);\n var attention_context = torch.bmm(attention_weights.unsqueeze(1), memory);\n attention_context = attention_context.squeeze(1);\n\n return (attention_context, attention_weights);\n }\n }\n\n public class Prenet : nn.Module<Tensor, Tensor>\n {\n private readonly Modules.ModuleList<Module<Tensor, Tensor>> layers;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n layers.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public Prenet(string name, int in_dim, long[] out_sizes) : base(name)\n {\n this.layers = nn.ModuleList<Module<Tensor, Tensor>>();\n long prev_size = in_dim;\n for (int i = 0; i < out_sizes.Length; i++) {\n long in_size = prev_size;\n long out_size = out_sizes[i];\n this.layers.Add(\n _get_linear_layer(in_size, out_size, bias: false));\n prev_size = out_size;\n }\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor x)\n {\n foreach (var linear in this.layers) {\n x = F.dropout(F.relu(linear.call(x)), p: 0.5, training: true);\n }\n return x;\n }\n }\n\n private class Postnet : nn.Module<Tensor, Tensor>\n {\n private readonly Modules.ModuleList<Module<Tensor, Tensor>> convolutions;\n public readonly int n_convs;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n convolutions.Dispose();\n }\n\n base.Dispose(disposing);\n }\n\n public Postnet(\n string name,\n int n_mels,\n int postnet_embedding_dim,\n int postnet_kernel_size,\n int postnet_n_convolution) : base(name)\n {\n this.convolutions = nn.ModuleList<Module<Tensor, Tensor>>();\n\n for (int i = 0; i < postnet_n_convolution; i++) {\n var in_channels = i == 0 ? n_mels : postnet_embedding_dim;\n var out_channels = i == postnet_n_convolution - 1 ? n_mels : postnet_embedding_dim;\n var init_gain = i == postnet_n_convolution - 1 ? init.NonlinearityType.Linear : init.NonlinearityType.Tanh;\n var num_features = i == postnet_n_convolution - 1 ? n_mels : postnet_embedding_dim;\n this.convolutions.append(\n nn.Sequential(\n _get_conv1d_layer(\n in_channels,\n out_channels,\n kernel_size: postnet_kernel_size,\n stride: 1,\n padding: (postnet_kernel_size - 1) / 2,\n dilation: 1,\n w_init_gain: init_gain),\n nn.BatchNorm1d(num_features)));\n }\n\n this.n_convs = this.convolutions.Count;\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor x)\n {\n for (int i = 0; i < this.convolutions.Count; i++) {\n var conv = this.convolutions[i];\n if (i < this.n_convs - 1) {\n x = F.dropout(torch.tanh(conv.call(x)), 0.5, training: this.training);\n } else {\n x = F.dropout(conv.call(x), 0.5, training: this.training);\n }\n }\n return x;\n }\n }\n\n private class Encoder : nn.Module<Tensor, Tensor, Tensor>\n {\n private readonly Modules.ModuleList<Module<Tensor, Tensor>> convolutions;\n private readonly Modules.LSTM lstm;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n convolutions.Dispose();\n lstm.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public Encoder(\n string name,\n int encoder_embedding_dim,\n int encoder_n_convolution,\n int encoder_kernel_size) : base(name)\n {\n this.convolutions = nn.ModuleList<Module<Tensor, Tensor>>();\n for (int i = 0; i < encoder_n_convolution; i++) {\n var conv_layer = nn.Sequential(\n _get_conv1d_layer(\n encoder_embedding_dim,\n encoder_embedding_dim,\n kernel_size: encoder_kernel_size,\n stride: 1,\n padding: (encoder_kernel_size - 1) / 2,\n dilation: 1,\n w_init_gain: init.NonlinearityType.ReLU\n ),\n nn.BatchNorm1d(encoder_embedding_dim)\n );\n this.convolutions.append(conv_layer);\n }\n\n this.lstm = nn.LSTM(\n encoder_embedding_dim,\n encoder_embedding_dim / 2,\n 1,\n batchFirst: true,\n bidirectional: true\n );\n this.lstm.flatten_parameters();\n RegisterComponents();\n }\n\n public override Tensor forward(Tensor x, Tensor input_lengths)\n {\n foreach (var conv in this.convolutions) {\n x = F.dropout(F.relu(conv.call(x)), 0.5, training: this.training);\n }\n\n x = x.transpose(1, 2);\n\n input_lengths = input_lengths.cpu();\n var packed_x = nn.utils.rnn.pack_padded_sequence(x, input_lengths, batch_first: true);\n\n var (packed_outputs, _, _) = this.lstm.call(packed_x);\n var (outputs, _) = nn.utils.rnn.pad_packed_sequence(packed_outputs, batch_first: true);\n\n return outputs;\n }\n }\n\n private class Decoder : nn.Module<Tensor, Tensor, Tensor, (Tensor, Tensor, Tensor)>\n {\n public readonly double attention_dropout;\n private readonly Attention attention_layer;\n private readonly Modules.LSTMCell attention_rnn;\n public readonly long attention_rnn_dim;\n public readonly double decoder_dropout;\n public readonly bool decoder_early_stopping;\n public readonly long decoder_max_step;\n private readonly Modules.LSTMCell decoder_rnn;\n public readonly long decoder_rnn_dim;\n public readonly long encoder_embedding_dim;\n private readonly Modules.Linear gate_layer;\n public readonly double gate_threshold;\n private readonly Modules.Linear linear_projection;\n public readonly int n_frames_per_step;\n public readonly int n_mels;\n public readonly Prenet prenet;\n public readonly long prenet_dim;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n attention_layer.Dispose(); attention_rnn.Dispose();\n decoder_rnn.Dispose();\n gate_layer.Dispose();\n linear_projection.Dispose();\n prenet.Dispose();\n }\n base.Dispose(disposing);\n }\n\n public Decoder(\n string name,\n int n_mels,\n int n_frames_per_step,\n int encoder_embedding_dim,\n int decoder_rnn_dim,\n int decoder_max_step,\n double decoder_dropout,\n bool decoder_early_stopping,\n int attention_rnn_dim,\n int attention_hidden_dim,\n int attention_location_n_filter,\n int attention_location_kernel_size,\n double attention_dropout,\n long prenet_dim,\n double gate_threshold) : base(name)\n {\n this.n_mels = n_mels;\n this.n_frames_per_step = n_frames_per_step;\n this.encoder_embedding_dim = encoder_embedding_dim;\n this.attention_rnn_dim = attention_rnn_dim;\n this.decoder_rnn_dim = decoder_rnn_dim;\n this.prenet_dim = prenet_dim;\n this.decoder_max_step = decoder_max_step;\n this.gate_threshold = gate_threshold;\n this.attention_dropout = attention_dropout;\n this.decoder_dropout = decoder_dropout;\n this.decoder_early_stopping = decoder_early_stopping;\n\n this.prenet = new Prenet(\"prenet\", n_mels * n_frames_per_step, new[] {\n prenet_dim,\n prenet_dim\n });\n\n this.attention_rnn = nn.LSTMCell(prenet_dim + encoder_embedding_dim, attention_rnn_dim);\n\n this.attention_layer = new Attention(\n \"attention\",\n attention_rnn_dim,\n encoder_embedding_dim,\n attention_hidden_dim,\n attention_location_n_filter,\n attention_location_kernel_size);\n\n this.decoder_rnn = nn.LSTMCell(attention_rnn_dim + encoder_embedding_dim, decoder_rnn_dim, true);\n\n this.linear_projection = _get_linear_layer(decoder_rnn_dim + encoder_embedding_dim, n_mels * n_frames_per_step);\n\n this.gate_layer = _get_linear_layer(\n decoder_rnn_dim + encoder_embedding_dim, 1, bias: true, w_init_gain: init.NonlinearityType.Sigmoid);\n RegisterComponents();\n }\n\n private Tensor _get_initial_frame(Tensor memory)\n {\n var n_batch = memory.size(0);\n var dtype = memory.dtype;\n var device = memory.device;\n var decoder_input = torch.zeros(n_batch, this.n_mels * this.n_frames_per_step, dtype: dtype, device: device);\n return decoder_input;\n }\n\n private (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor) _initialize_decoder_states(Tensor memory)\n {\n var n_batch = memory.size(0);\n var max_time = memory.size(1);\n var dtype = memory.dtype;\n var device = memory.device;\n\n var attention_hidden = torch.zeros(n_batch, this.attention_rnn_dim, dtype: dtype, device: device);\n var attention_cell = torch.zeros(n_batch, this.attention_rnn_dim, dtype: dtype, device: device);\n\n var decoder_hidden = torch.zeros(n_batch, this.decoder_rnn_dim, dtype: dtype, device: device);\n var decoder_cell = torch.zeros(n_batch, this.decoder_rnn_dim, dtype: dtype, device: device);\n\n var attention_weights = torch.zeros(n_batch, max_time, dtype: dtype, device: device);\n var attention_weights_cum = torch.zeros(n_batch, max_time, dtype: dtype, device: device);\n var attention_context = torch.zeros(n_batch, this.encoder_embedding_dim, dtype: dtype, device: device);\n\n var processed_memory = this.attention_layer.memory_layer.call(memory);\n\n return (\n attention_hidden,\n attention_cell,\n decoder_hidden,\n decoder_cell,\n attention_weights,\n attention_weights_cum,\n attention_context,\n processed_memory);\n }\n\n private Tensor _parse_decoder_inputs(Tensor decoder_inputs)\n {\n // (n_batch, n_mels, mel_specgram_lengths.max()) -> (n_batch, mel_specgram_lengths.max(), n_mels)\n decoder_inputs = decoder_inputs.transpose(1, 2);\n decoder_inputs = decoder_inputs.view(\n decoder_inputs.size(0),\n decoder_inputs.size(1) / this.n_frames_per_step,\n -1);\n // (n_batch, mel_specgram_lengths.max(), n_mels) -> (mel_specgram_lengths.max(), n_batch, n_mels)\n decoder_inputs = decoder_inputs.transpose(0, 1);\n return decoder_inputs;\n }\n\n private (Tensor, Tensor, Tensor) _parse_decoder_outputs(Tensor mel_specgram, Tensor gate_outputs, Tensor alignments)\n {\n // (mel_specgram_lengths.max(), n_batch, text_lengths.max())\n // -> (n_batch, mel_specgram_lengths.max(), text_lengths.max())\n alignments = alignments.transpose(0, 1).contiguous();\n // (mel_specgram_lengths.max(), n_batch) -> (n_batch, mel_specgram_lengths.max())\n gate_outputs = gate_outputs.transpose(0, 1).contiguous();\n // (mel_specgram_lengths.max(), n_batch, n_mels) -> (n_batch, mel_specgram_lengths.max(), n_mels)\n mel_specgram = mel_specgram.transpose(0, 1).contiguous();\n // decouple frames per step\n var shape = new long[] { mel_specgram.shape[0], -1, this.n_mels };\n mel_specgram = mel_specgram.view(shape);\n // (n_batch, mel_specgram_lengths.max(), n_mels) -> (n_batch, n_mels, T_out)\n mel_specgram = mel_specgram.transpose(1, 2);\n\n return (mel_specgram, gate_outputs, alignments);\n }\n\n public (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor) decode(\n Tensor decoder_input,\n Tensor attention_hidden,\n Tensor attention_cell,\n Tensor decoder_hidden,\n Tensor decoder_cell,\n Tensor attention_weights,\n Tensor attention_weights_cum,\n Tensor attention_context,\n Tensor memory,\n Tensor processed_memory,\n Tensor mask)\n {\n var cell_input = torch.cat(new[] { decoder_input, attention_context }, -1);\n\n (attention_hidden, attention_cell) = this.attention_rnn.call(cell_input, (attention_hidden, attention_cell));\n attention_hidden = F.dropout(attention_hidden, this.attention_dropout, training: this.training);\n\n var attention_weights_cat = torch.cat(new[] { attention_weights.unsqueeze(1), attention_weights_cum.unsqueeze(1) }, dim: 1);\n (attention_context, attention_weights) = this.attention_layer.call(\n attention_hidden, memory, processed_memory, attention_weights_cat, mask);\n\n attention_weights_cum += attention_weights;\n decoder_input = torch.cat(new[] { attention_hidden, attention_context }, -1);\n\n (decoder_hidden, decoder_cell) = this.decoder_rnn.call(decoder_input, (decoder_hidden, decoder_cell));\n decoder_hidden = F.dropout(decoder_hidden, this.decoder_dropout, training: this.training);\n\n var decoder_hidden_attention_context = torch.cat(new[] { decoder_hidden, attention_context }, dim: 1);\n var decoder_output = this.linear_projection.call(decoder_hidden_attention_context);\n\n var gate_prediction = this.gate_layer.call(decoder_hidden_attention_context);\n\n return (\n decoder_output,\n gate_prediction,\n attention_hidden,\n attention_cell,\n decoder_hidden,\n decoder_cell,\n attention_weights,\n attention_weights_cum,\n attention_context);\n }\n\n // Decoder forward pass for training.\n public override (Tensor, Tensor, Tensor) forward(Tensor memory, Tensor mel_specgram_truth, Tensor memory_lengths)\n {\n var decoder_input = this._get_initial_frame(memory).unsqueeze(0);\n var decoder_inputs = this._parse_decoder_inputs(mel_specgram_truth);\n decoder_inputs = torch.cat(new[] { decoder_input, decoder_inputs }, dim: 0);\n decoder_inputs = this.prenet.call(decoder_inputs);\n\n var mask = _get_mask_from_lengths(memory_lengths);\n var (\n attention_hidden,\n attention_cell,\n decoder_hidden,\n decoder_cell,\n attention_weights,\n attention_weights_cum,\n attention_context,\n processed_memory\n ) = this._initialize_decoder_states(memory);\n\n var mel_output_list = new List<Tensor>();\n var gate_output_list = new List<Tensor>();\n var alignment_list = new List<Tensor>();\n while (mel_output_list.Count < decoder_inputs.size(0) - 1) {\n decoder_input = decoder_inputs[mel_output_list.Count];\n Tensor mel_output, gate_output;\n (\n mel_output,\n gate_output,\n attention_hidden,\n attention_cell,\n decoder_hidden,\n decoder_cell,\n attention_weights,\n attention_weights_cum,\n attention_context\n ) = this.decode(\n decoder_input,\n attention_hidden,\n attention_cell,\n decoder_hidden,\n decoder_cell,\n attention_weights,\n attention_weights_cum,\n attention_context,\n memory,\n processed_memory,\n mask);\n\n mel_output_list.Add(mel_output.squeeze(1));\n gate_output_list.Add(gate_output.squeeze(1));\n alignment_list.Add(attention_weights);\n }\n\n var (mel_specgram, gate_outputs, alignments) = this._parse_decoder_outputs(\n torch.stack(mel_output_list), torch.stack(gate_output_list), torch.stack(alignment_list));\n\n return (mel_specgram, gate_outputs, alignments);\n }\n\n public new (Tensor, Tensor, Tensor) call(Tensor memory, Tensor mel_specgram_truth, Tensor memory_lengths) => base.call(memory, mel_specgram_truth, memory_lengths);\n\n private Tensor _get_go_frame(Tensor memory)\n {\n var n_batch = memory.size(0);\n var dtype = memory.dtype;\n var device = memory.device;\n var decoder_input = torch.zeros(n_batch, this.n_mels * this.n_frames_per_step, dtype: dtype, device: device);\n return decoder_input;\n }\n\n public (Tensor, Tensor, Tensor, Tensor) infer(Tensor memory, Tensor memory_lengths)\n {\n var batch_size = memory.size(0);\n var device = memory.device;\n\n var decoder_input = this._get_go_frame(memory);\n\n var mask = _get_mask_from_lengths(memory_lengths);\n var (\n attention_hidden,\n attention_cell,\n decoder_hidden,\n decoder_cell,\n attention_weights,\n attention_weights_cum,\n attention_context,\n processed_memory\n ) = this._initialize_decoder_states(memory);\n\n var mel_specgram_lengths = torch.zeros(new[] {\n batch_size\n }, dtype: torch.int32, device: device);\n var finished = torch.zeros(new[] {\n batch_size\n }, dtype: torch.@bool, device: device);\n var mel_specgram_list = new List<Tensor>();\n var gate_output_list = new List<Tensor>();\n var alignment_list = new List<Tensor>();\n for (long i = 0; i < this.decoder_max_step; i++) {\n decoder_input = this.prenet.call(decoder_input);\n Tensor mel_specgram, gate_output;\n (\n mel_specgram,\n gate_output,\n attention_hidden,\n attention_cell,\n decoder_hidden,\n decoder_cell,\n attention_weights,\n attention_weights_cum,\n attention_context\n ) = this.decode(\n decoder_input,\n attention_hidden,\n attention_cell,\n decoder_hidden,\n decoder_cell,\n attention_weights,\n attention_weights_cum,\n attention_context,\n memory,\n processed_memory,\n mask);\n\n mel_specgram_list.Add(mel_specgram.unsqueeze(0));\n gate_output_list.Add(gate_output.transpose(0, 1));\n alignment_list.Add(attention_weights);\n mel_specgram_lengths[~finished] += 1;\n\n finished |= torch.sigmoid(gate_output.squeeze(1)) > this.gate_threshold;\n if (this.decoder_early_stopping && torch.all(finished).item<bool>()) {\n break;\n }\n\n decoder_input = mel_specgram;\n }\n\n if (mel_specgram_list.Count == this.decoder_max_step) {\n Debug.WriteLine(\"Reached max decoder steps. The generated spectrogram might not cover the whole transcript.\");\n }\n\n var mel_specgrams = torch.cat(mel_specgram_list, dim: 0);\n var gate_outputs = torch.cat(gate_output_list, dim: 0);\n var alignments = torch.cat(alignment_list, dim: 0);\n\n (mel_specgrams, gate_outputs, alignments) = this._parse_decoder_outputs(mel_specgrams, gate_outputs, alignments);\n\n return (mel_specgrams, mel_specgram_lengths, gate_outputs, alignments);\n }\n }\n }\n}" }, { "alpha_fraction": 0.579365074634552, "alphanum_fraction": 0.5833333134651184, "avg_line_length": 35, "blob_id": "11a9d48ac1f5fb8f3a83c4a3f934f208a7e39eb8", "content_id": "e5a5fd1861a598f17dfc79a2886f102c839249a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1512, "license_type": "permissive", "max_line_length": 130, "num_lines": 42, "path": "/src/TorchVision/AdjustBrightness.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class AdjustBrightness : ITransform\n {\n internal AdjustBrightness(double brightness_factor)\n {\n if (brightness_factor < 0.0)\n throw new ArgumentException($\"The sharpness factor ({brightness_factor}) must be non-negative.\");\n this.brightness_factor = brightness_factor;\n }\n\n public Tensor call(Tensor input)\n {\n return transforms.functional.adjust_brightness(input, brightness_factor);\n }\n\n private double brightness_factor;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Adjust the sharpness of the image. \n /// </summary>\n /// <param name=\"brightness_factor\">\n /// How much to adjust the brightness. Can be any non negative number.\n /// 0 gives a black image, 1 gives the original image while 2 increases the brightness by a factor of 2.\n /// </param>\n /// <returns></returns>\n static public ITransform AdjustBrightness(double brightness_factor)\n {\n return new AdjustBrightness(brightness_factor);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5237137675285339, "alphanum_fraction": 0.530632734298706, "avg_line_length": 47.039772033691406, "blob_id": "4f0c2c66c872fe6be47a04d8211558d1127104ca", "content_id": "8ca7dae45dba7040fa26059a1c73b4ef4696277e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 16911, "license_type": "permissive", "max_line_length": 223, "num_lines": 352, "path": "/src/TorchSharp/Optimizers/Adagrad.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using System.IO;\n using Modules;\n\n public static partial class torch\n {\n public static partial class optim\n {\n\n /// <summary>\n /// Implements the Adagrad algorithm.\n ///\n /// It has been proposed in Adaptive Subgradient Methods for Online Learning and Stochastic Optimization.\n /// http://jmlr.org/papers/v12/duchi11a.html\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize</param>\n /// <param name=\"lr\">learning rate (default: 1e-2)</param>\n /// <param name=\"lr_decay\">learning rate decay (default: 0)</param>\n /// <param name=\"weight_decay\">weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"initial_accumulator_value\"></param>\n /// <param name=\"eps\">Term added to the denominator to improve numerical stability (default: 1e-10)</param>\n /// <returns></returns>\n public static Adagrad Adagrad(IEnumerable<Parameter> parameters, double lr = 1e-2, double lr_decay = 0, double weight_decay = 0, double initial_accumulator_value = 0, double eps = 1e-10)\n {\n return new Adagrad(parameters, lr, lr_decay, weight_decay, initial_accumulator_value, eps);\n }\n\n /// <summary>\n /// Implements the Adagrad algorithm.\n ///\n /// It has been proposed in Adaptive Subgradient Methods for Online Learning and Stochastic Optimization.\n /// http://jmlr.org/papers/v12/duchi11a.html\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize</param>\n /// <param name=\"lr\">learning rate (default: 1e-2)</param>\n /// <param name=\"lr_decay\">learning rate decay (default: 0)</param>\n /// <param name=\"weight_decay\">weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"initial_accumulator_value\"></param>\n /// <param name=\"eps\">Term added to the denominator to improve numerical stability (default: 1e-10)</param>\n /// <returns></returns>\n public static Adagrad Adagrad(IEnumerable<(string name, Parameter parameter)> parameters, double lr = 1e-2, double lr_decay = 0, double weight_decay = 0, double initial_accumulator_value = 0, double eps = 1e-10)\n {\n return new Adagrad(parameters.Select(np => np.parameter), lr, lr_decay, weight_decay, initial_accumulator_value, eps);\n }\n\n /// <summary>\n /// Implements the Adagrad algorithm.\n ///\n /// It has been proposed in Adaptive Subgradient Methods for Online Learning and Stochastic Optimization.\n /// http://jmlr.org/papers/v12/duchi11a.html\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize</param>\n /// <param name=\"lr\">learning rate (default: 1e-2)</param>\n /// <param name=\"lr_decay\">learning rate decay (default: 0)</param>\n /// <param name=\"weight_decay\">weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"initial_accumulator_value\"></param>\n /// <param name=\"eps\">Term added to the denominator to improve numerical stability (default: 1e-10)</param>\n /// <returns></returns>\n public static Adagrad Adagrad(IEnumerable<Adagrad.ParamGroup> parameters, double lr = 1e-2, double lr_decay = 0, double weight_decay = 0, double initial_accumulator_value = 0, double eps = 1e-10)\n {\n return new Adagrad(parameters, lr, lr_decay, weight_decay, initial_accumulator_value, eps);\n }\n }\n }\n\n namespace Modules\n {\n public class Adagrad : OptimizerHelper\n {\n /// <summary>\n /// Implements Adagrad algorithm.\n ///\n /// It has been proposed in Adaptive Subgradient Methods for Online Learning and Stochastic Optimization.\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize</param>\n /// <param name=\"lr\">learning rate (default: 1e-2)</param>\n /// <param name=\"lr_decay\">learning rate decay (default: 0)</param>\n /// <param name=\"weight_decay\">weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"initial_accumulator_value\"></param>\n /// <param name=\"eps\">Term added to the denominator to improve numerical stability (default: 1e-10)</param>\n /// <returns></returns>\n public Adagrad(IEnumerable<Parameter> parameters, double lr = 1e-2, double lr_decay = 0, double weight_decay = 0, double initial_accumulator_value = 0, double eps = 1e-10)\n : this(new ParamGroup[] { new() { Parameters = parameters } }, lr, lr_decay, weight_decay, initial_accumulator_value, eps)\n {\n }\n /// <summary>\n /// Implements Adagrad algorithm.\n ///\n /// It has been proposed in Adaptive Subgradient Methods for Online Learning and Stochastic Optimization.\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize</param>\n /// <param name=\"lr\">learning rate (default: 1e-2)</param>\n /// <param name=\"lr_decay\">learning rate decay (default: 0)</param>\n /// <param name=\"weight_decay\">weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"initial_accumulator_value\"></param>\n /// <param name=\"eps\">Term added to the denominator to improve numerical stability (default: 1e-10)</param>\n /// <returns></returns>\n public Adagrad(IEnumerable<ParamGroup> parameters, double lr = 1e-2, double lr_decay = 0, double weight_decay = 0, double initial_accumulator_value = 0, double eps = 1e-10)\n {\n if (lr < 0) throw new ArgumentException($\"Invalid learning rate: {lr}\");\n if (eps < 0) throw new ArgumentException($\"Invalid ε: {eps}\");\n if (lr_decay < 0.0) throw new ArgumentException($\"Invalid lr_decay value: {lr_decay}\");\n if (weight_decay < 0.0) throw new ArgumentException($\"Invalid weight_decay value: {weight_decay}\");\n if (initial_accumulator_value < 0) throw new ArgumentException($\"Invalid initial_accumulator_value: {initial_accumulator_value}\");\n\n var options = new Options {\n LearningRate = lr,\n InitialLearningRate = lr,\n lr_decay = lr_decay,\n eps = eps,\n initial_accumulator_value = initial_accumulator_value,\n weight_decay = weight_decay\n };\n\n _defaults = options;\n _parameter_groups = new List<Modules.ParamGroup>();\n\n foreach (var g in parameters) {\n add_param_group(g);\n }\n }\n\n /// <summary>\n /// Performs a single optimization step (parameter update).\n /// </summary>\n /// <param name=\"closure\">A closure that reevaluates the model and returns the loss. Optional for most optimizers.</param>\n /// <returns></returns>\n public override Tensor step(Func<Tensor> closure = null)\n {\n return _step<ParamGroup>(group => {\n\n var options = group.Options as Options;\n var lr_decay = options.lr_decay.Value;\n var weight_decay = options.weight_decay.Value;\n var eps = options.eps.Value;\n var initial_accumulator_value = options.initial_accumulator_value.Value;\n var lr = options.LearningRate.Value;\n\n foreach (var param in group.Parameters) {\n\n var state = (State)_state[param.handle];\n\n var grad = param.grad();\n\n if (grad is null) continue;\n\n state.step += 1;\n\n if (weight_decay != 0) {\n grad = grad.add(param, alpha: weight_decay);\n }\n\n var clr = lr / (1 + (state.step - 1) * lr_decay);\n\n if (grad.is_sparse)\n throw new NotImplementedException(\"Adagrad optimization over sparse parameters\");\n if (torch.is_complex(grad))\n throw new NotImplementedException(\"Adagrad optimization over complex parameters\");\n\n state.sum.addcmul_(grad, grad, value: 1);\n var std = state.sum.sqrt().add_(eps);\n param.addcdiv_(grad, std, value: -clr);\n }\n\n\n }, closure);\n }\n\n protected override void Dispose(bool disposing)\n {\n base.Dispose(disposing);\n foreach (var kvp in _state) {\n ((State)kvp.Item2).Dispose();\n }\n }\n\n public sealed class State : OptimizerState, IDisposable\n {\n public long step;\n public Tensor sum;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n private void Dispose(bool disposing)\n {\n if (disposing) {\n sum.Dispose();\n }\n }\n\n /// <summary>\n /// Move all the state to the indicated device.\n /// </summary>\n /// <param name=\"device\">The device to move all state to.</param>\n public override void to(Device device)\n {\n sum = sum.to(device);\n }\n\n /// <summary>\n /// Load the optimizer parameter state from a stream.\n /// </summary>\n /// <param name=\"reader\">A binary reader connected to a stream open for reading.</param>\n public override void LoadStateDict(BinaryReader reader)\n {\n step = reader.ReadInt64();\n sum.Load(reader);\n }\n\n /// <summary>\n /// Load optimizer parameter state from another optimizer.\n /// </summary>\n /// <param name=\"source\">An optimizer state record.</param>\n public override void LoadStateDict(OptimizerState source)\n {\n var st_state = source as State;\n sum.Dispose();\n step = st_state.step;\n sum = st_state.sum;\n }\n\n /// <summary>\n /// Save the optimizer parameter state to a stream.\n /// </summary>\n /// <param name=\"writer\">A binary writer connected to a stream open for writing.</param>\n public override void SaveStateDict(BinaryWriter writer)\n {\n writer.Write(step);\n sum.Save(writer);\n }\n\n /// <summary>\n /// Useful for tests, allows comparison of one state with another.\n /// </summary>\n /// <param name=\"other\">The other optimizer state</param>\n /// <returns></returns>\n public override bool ApproximatelyEquals(OptimizerState other)\n {\n var rhs = other as State;\n return (rhs is not null) && step == rhs.step && sum.allclose(rhs.sum);\n }\n }\n\n /// <summary>\n /// Add a param group to the Optimizer s param_groups.\n /// </summary>\n /// <param name=\"param_group\"></param>\n /// <remarks>This can be useful when fine tuning a pre-trained network as frozen layers can be made trainable and added to the Optimizer as training progresses.</remarks>\n public override void add_param_group(Modules.ParamGroup param_group)\n {\n var def = _defaults as Options;\n if (param_group.Options is null) {\n param_group.Options = new Options();\n }\n\n var opt = param_group.Options as Options;\n\n // Make sure all the options are set.\n if (!opt.LearningRate.HasValue) opt.LearningRate = def.LearningRate;\n if (!opt.lr_decay.HasValue) opt.lr_decay = def.lr_decay;\n if (!opt.eps.HasValue) opt.eps = def.eps;\n if (!opt.weight_decay.HasValue) opt.weight_decay = def.weight_decay;\n if (!opt.initial_accumulator_value.HasValue) opt.initial_accumulator_value = def.initial_accumulator_value;\n\n opt.InitialLearningRate = opt.LearningRate.Value;\n\n _parameter_groups.Add(param_group);\n\n foreach (var p in param_group.Parameters) {\n var state = new State();\n _state[p.Handle] = state;\n state.step = 0;\n var init_value = torch.is_complex(p.dtype)\n ? (Scalar)new System.Numerics.Complex((param_group.Options as Options).initial_accumulator_value.Value, (param_group.Options as Options).initial_accumulator_value.Value)\n : (Scalar)(param_group.Options as Options).initial_accumulator_value.Value;\n state.sum = torch.full_like(p, init_value).DetachFromDisposeScope();\n }\n }\n\n public class Options : OptimizerOptions\n {\n public double? lr_decay;\n public double? initial_accumulator_value;\n public double? eps;\n public double? weight_decay;\n\n /// <summary>\n /// Load optimizer options (param-group hyperparameters) from another optimizer.\n /// </summary>\n /// <param name=\"source\">An optimizer options record.</param>\n public override void LoadStateDict(OptimizerOptions source)\n {\n base.LoadStateDict(source);\n var opts = source as Options;\n lr_decay = opts.lr_decay;\n initial_accumulator_value = opts.initial_accumulator_value;\n eps = opts.eps;\n weight_decay = opts.weight_decay;\n }\n\n /// <summary>\n /// Load the optimizer options (param-group hyperparameters) from a stream.\n /// </summary>\n /// <param name=\"reader\">A binary reader connected to a stream open for reading.</param>\n public override void LoadStateDict(BinaryReader reader)\n {\n base.LoadStateDict(reader);\n lr_decay = reader.ReadDouble();\n initial_accumulator_value = reader.ReadDouble();\n eps = reader.ReadDouble();\n weight_decay = reader.ReadDouble();\n }\n\n /// <summary>\n /// Save the optimizer options (param-group hyperparameters) to a stream.\n /// </summary>\n /// <param name=\"writer\">A binary writer connected to a stream open for writing.</param>\n public override void SaveStateDict(BinaryWriter writer)\n {\n base.SaveStateDict(writer);\n writer.Write(lr_decay.Value);\n writer.Write(initial_accumulator_value.Value);\n writer.Write(eps.Value);\n writer.Write(weight_decay.Value);\n }\n }\n\n public class ParamGroup : ParamGroup<Options>\n {\n public ParamGroup() { }\n\n public ParamGroup(IEnumerable<Parameter> parameters, Options options) : base(parameters, options) { }\n\n public ParamGroup(IEnumerable<Parameter> parameters, double lr = 0.01, double lr_decay = 0, double weight_decay = 0, double initial_accumulator_value = 0, double eps = 1e-10)\n : base(parameters, new Adagrad.Options { LearningRate = lr, lr_decay = lr_decay, initial_accumulator_value = initial_accumulator_value, weight_decay = weight_decay, eps = eps })\n {\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5762327313423157, "alphanum_fraction": 0.5782958269119263, "avg_line_length": 48.96907043457031, "blob_id": "b0cbb8c9cc2b7315394332c0df7b6a68de0ac4a8", "content_id": "004be40ba6ad7b53bc9a3a985b6981790b454455", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4847, "license_type": "permissive", "max_line_length": 209, "num_lines": 97, "path": "/src/TorchSharp/NN/Normalization/LayerNorm.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\n#nullable enable\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n\n /// <summary>\n /// This class is used to represent a LayerNorm module.\n /// </summary>\n public sealed class LayerNorm : torch.nn.Module<Tensor, Tensor>\n {\n internal LayerNorm(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n var res = THSNN_LayerNorm_forward(handle.DangerousGetHandle(), tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n\n public Parameter? bias {\n get {\n var res = THSNN_LayerNorm_bias(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n set {\n THSNN_LayerNorm_set_bias(handle, (value is null ? IntPtr.Zero : value.Handle));\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"bias\", value);\n }\n }\n\n public Parameter? weight {\n get {\n var res = THSNN_LayerNorm_weight(handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return (res == IntPtr.Zero) ? null : new Parameter(res);\n }\n set {\n THSNN_LayerNorm_set_weight(handle, value is null ? IntPtr.Zero : value.Handle);\n torch.CheckForErrors();\n ConditionallyRegisterParameter(\"weight\", value);\n }\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies Layer Normalization over a mini-batch of inputs as described in the paper Layer Normalization\n /// </summary>\n /// <param name=\"normalized_shape\">Input shape from an expected input.</param>\n /// <param name=\"eps\">A value added to the denominator for numerical stability. Default: 1e-5</param>\n /// <param name=\"elementwise_affine\">a boolean value that when set to true, this module has learnable per-element affine parameters initialized to ones (for weights) and zeros (for biases).</param>\n /// <param name=\"device\">The desired device of the parameters and buffers in this module</param>\n /// <param name=\"dtype\">The desired floating point or complex dtype of the parameters and buffers in this module</param>\n /// <returns></returns>\n public static LayerNorm LayerNorm(long[] normalized_shape, double eps = 1e-05, bool elementwise_affine = true, Device? device = null, ScalarType? dtype = null)\n {\n unsafe {\n fixed (long* pNormShape = normalized_shape) {\n var handle = THSNN_LayerNorm_ctor((IntPtr)pNormShape, normalized_shape.Length, eps, elementwise_affine, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new LayerNorm(handle, boxedHandle).MoveModule<LayerNorm>(device, dtype);\n }\n }\n }\n\n /// <summary>\n /// Applies Layer Normalization over a mini-batch of inputs as described in the paper Layer Normalization\n /// </summary>\n /// <param name=\"normalized_shape\">Input shape from an expected input.</param>\n /// <param name=\"eps\">A value added to the denominator for numerical stability. Default: 1e-5</param>\n /// <param name=\"elementwise_affine\">a boolean value that when set to true, this module has learnable per-element affine parameters initialized to ones (for weights) and zeros (for biases).</param>\n /// <param name=\"device\">The desired device of the parameters and buffers in this module</param>\n /// <param name=\"dtype\">The desired floating point or complex dtype of the parameters and buffers in this module</param>\n /// <returns></returns>\n public static LayerNorm LayerNorm(long normalized_shape, double eps = 1e-05, bool elementwise_affine = true, Device? device = null, ScalarType? dtype = null)\n {\n return LayerNorm(new[] { normalized_shape }, eps, elementwise_affine, device, dtype);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5151121616363525, "alphanum_fraction": 0.5373632311820984, "avg_line_length": 38.36496353149414, "blob_id": "7d640ab4d770079a8ea2a56fc241555559cbefb9", "content_id": "64c4053d7332262504fdcc6514a71bcfd59c90e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5393, "license_type": "permissive", "max_line_length": 130, "num_lines": 137, "path": "/test/TorchSharpTest/TestNNUtils.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\nusing System.Linq;\nusing Xunit;\n\nnamespace TorchSharp\n{\n public class TestNNUtils\n {\n (torch.Tensor[], torch.Tensor) make_test()\n {\n var sequences = new torch.Tensor[]\n {\n torch.tensor(new long[] { 1, 2, 3, 4 }),\n torch.tensor(new long[] { 5, 6 }),\n torch.tensor(new long[] { 7, 8 }),\n };\n var sequences_len = torch.tensor(sequences.Select(x => x.shape[0]).ToArray());\n return (sequences, sequences_len);\n }\n\n [Fact]\n public void TestPadSequence()\n {\n var (sequences, sequences_len) = make_test();\n var padded_sequences = torch.nn.utils.rnn.pad_sequence(sequences);\n Assert.Equal(2, padded_sequences.ndim);\n Assert.Equal(new long[] { 4, 3 }, padded_sequences.shape);\n Assert.True(padded_sequences.sum().item<long>() == 36);\n\n var packed_sequence = torch.nn.utils.rnn.pack_padded_sequence(padded_sequences, sequences_len);\n var (inverted_sequences, inverted_sequences_len) = torch.nn.utils.rnn.pad_packed_sequence(packed_sequence);\n packed_sequence.Dispose();\n Assert.True(torch.max(torch.square(inverted_sequences - padded_sequences)).item<long>() == 0);\n }\n\n [Fact]\n public void TestPackSequence()\n {\n var (sequences, sequences_len) = make_test();\n var padded_sequences = torch.nn.utils.rnn.pad_sequence(sequences);\n Assert.Equal(2, padded_sequences.ndim);\n Assert.Equal(new long[] { 4, 3 }, padded_sequences.shape);\n Assert.True(padded_sequences.sum().item<long>() == 36);\n\n var packed_sequence = torch.nn.utils.rnn.pack_sequence(sequences);\n var (inverted_sequences, inverted_sequences_len) = torch.nn.utils.rnn.pad_packed_sequence(packed_sequence);\n packed_sequence.Dispose();\n Assert.True(torch.max(torch.square(inverted_sequences - padded_sequences)).item<long>() == 0);\n }\n\n [Fact]\n public void TestAutoGradGrad()\n {\n using var _ = torch.NewDisposeScope();\n var x1 = torch.rand(1, requires_grad: true);\n var x2 = torch.rand(1, requires_grad: true);\n\n var y = x1.pow(2) + 5 * x2;\n\n var grad = torch.autograd.grad(new[] { y }, new[] { x1, x2 }, new[] { torch.ones_like(y) });\n Assert.Equal(x1.shape, grad[0].shape);\n Assert.Equal(x2.shape, grad[1].shape);\n Assert.Equal(2.0f * x1.item<float>(), grad[0].item<float>());\n Assert.Equal(5.0f, grad[1].item<float>());\n }\n\n [Fact]\n public void TestAutoGradBackward1()\n {\n using var _ = torch.NewDisposeScope();\n var x1 = torch.rand(1, requires_grad: true);\n var x2 = torch.rand(1, requires_grad: true);\n\n var y = x1.pow(2) + 5 * x2;\n\n torch.autograd.backward(new[] { y }, new[] { torch.ones_like(y) });\n Assert.Equal(x1.shape, x1.grad().shape);\n Assert.Equal(x2.shape, x2.grad().shape);\n Assert.Equal(2.0f*x1.item<float>(), x1.grad().item<float>());\n Assert.Equal(5.0f, x2.grad().item<float>());\n }\n\n [Fact]\n public void TestAutoGradBackward2()\n {\n using var _ = torch.NewDisposeScope();\n var x1 = torch.rand(1, requires_grad: true);\n var x2 = torch.rand(1, requires_grad: true);\n\n var y = x1.pow(2) + 5 * x2;\n\n y.backward(new[] { torch.ones_like(y) });\n Assert.Equal(x1.shape, x1.grad().shape);\n Assert.Equal(x2.shape, x2.grad().shape);\n Assert.Equal(2.0f * x1.item<float>(), x1.grad().item<float>());\n Assert.Equal(5.0f, x2.grad().item<float>());\n }\n\n [Fact]\n public void TestAutoGradAnomaly()\n {\n Assert.False(AnomalyMode.IsEnabled);\n\n using (var ad = torch.autograd.detect_anomaly(false)) {\n Assert.True(AnomalyMode.IsEnabled);\n Assert.False(AnomalyMode.ShouldCheckNaN);\n }\n\n Assert.False(AnomalyMode.IsEnabled);\n\n using (var ad = torch.autograd.set_detect_anomaly(false)) {\n Assert.False(AnomalyMode.IsEnabled);\n Assert.True(AnomalyMode.ShouldCheckNaN);\n }\n\n Assert.False(AnomalyMode.IsEnabled);\n }\n\n [Fact]\n public void TestSizeSlice()\n {\n var shape = Enumerable.Range(0, 10).Select(i => (long)i).ToArray();\n var sz = new torch.Size(shape);\n Assert.Multiple(\n () => Assert.Equal(new long[] { 0, 1, 2, 3, 4, 5 }, sz.Slice(0, 6).Shape),\n () => Assert.Equal(new long[] { 2, 3, 4, 5 }, sz.Slice(2, 6).Shape),\n () => Assert.Equal(new long[] { 0, 1, 2, 3, 4, 5 }, sz.Slice(0, -4).Shape),\n () => Assert.Equal(new long[] { 2, 3, 4, 5 }, sz.Slice(2, -4).Shape),\n () => Assert.Equal(new long[] { 8, 9 }, sz.Slice(-2, sz.Length).Shape),\n () => Assert.True(sz.Slice(0, 0).IsEmpty),\n () => Assert.True(sz.Slice(-2, 0).IsEmpty)\n );\n\n }\n }\n}\n" }, { "alpha_fraction": 0.5609756112098694, "alphanum_fraction": 0.5711751580238342, "avg_line_length": 50.2613639831543, "blob_id": "002ccb71dd275858ec6733dfaeda39fe13dc0ca2", "content_id": "c3ad686e871b310689fec0d07a65661ca199dc37", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4518, "license_type": "permissive", "max_line_length": 147, "num_lines": 88, "path": "/src/TorchVision/ColorJitter.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\n\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class ColorJitter : ITransform\n {\n internal ColorJitter((float, float) brightness, (float, float) contrast, (float, float) saturation, (float, float) hue)\n {\n this.brightness = brightness;\n this.contrast = contrast;\n this.saturation = saturation;\n this.hue = hue;\n }\n\n public Tensor call(Tensor image)\n {\n var randoms = torch.rand(4, ScalarType.Float32).data<float>().ToArray();\n var b = Adjust(randoms[0], brightness.Item1, brightness.Item2);\n var c = Adjust(randoms[1], contrast.Item1, contrast.Item2);\n var s = Adjust(randoms[2], saturation.Item1, saturation.Item2);\n var h = Adjust(randoms[3], hue.Item1, hue.Item2);\n\n var transform = torchvision.transforms.Compose(\n transforms.AdjustBrightness(b),\n transforms.AdjustContrast(c),\n transforms.AdjustSaturation(s),\n transforms.AdjustHue(h)\n );\n return transform.call(image);\n }\n\n internal static float Adjust(float input, float min, float max)\n {\n return input * (max - min) + min;\n }\n\n private (float, float) brightness;\n private (float, float) contrast;\n private (float, float) saturation;\n private (float, float) hue;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Randomly change the brightness, contrast, saturation and hue of an image.\n /// The image is expected to have […, 3, H, W] shape, where … means an arbitrary number of leading dimensions.\n /// </summary>\n /// <param name=\"brightness\">How much to jitter brightness, [min,max]. Should be non-negative.</param>\n /// <param name=\"contrast\">How much to jitter contrast, [min,max]. Should be non-negative.</param>\n /// <param name=\"saturation\">How much to jitter saturation, [min,max]. Should be non-negative. </param>\n /// <param name=\"hue\">How much to jitter hue. Should lie between -0.5 and 0.5, with min less than max.</param>\n /// <returns></returns>\n /// <remarks>The image will not be cropped outside its boundaries.</remarks>\n static public ITransform ColorJitter((float, float) brightness, (float, float) contrast, (float, float) saturation, (float, float) hue)\n {\n return new ColorJitter(brightness, contrast, saturation, hue);\n }\n\n /// <summary>\n /// Randomly change the brightness, contrast, saturation and hue of an image.\n /// The image is expected to have […, 3, H, W] shape, where … means an arbitrary number of leading dimensions.\n /// </summary>\n /// <param name=\"brightness\">How much to jitter brightness. Should be non-negative.\n /// The brightness_factor used is chosen uniformly from [max(0, 1 - brightness), 1 + brightness]</param>\n /// <param name=\"contrast\">How much to jitter contrast. Should be non-negative.\n /// The contrast_factor used is chosen uniformly from [max(0, 1 - contrast), 1 + contrast]</param>\n /// <param name=\"saturation\">How much to jitter saturation. Should be non-negative.\n /// The saturation_factor used is chosen uniformly from [max(0, 1 - saturation), 1 + saturation] </param>\n /// <param name=\"hue\">How much to jitter hue. Should be between 0 and 0.5.</param>\n /// <returns></returns>\n /// <remarks>The image will not be cropped outside its boundaries.</remarks>\n static public ITransform ColorJitter(float brightness = 0, float contrast = 0, float saturation = 0, float hue = 0)\n {\n return new ColorJitter(\n (MathF.Max(0, 1 - brightness), 1 + brightness),\n (MathF.Max(0, 1 - contrast), 1 + contrast),\n (MathF.Max(0, 1 - saturation), 1 + saturation),\n (-hue, hue));\n }\n }\n }\n}" }, { "alpha_fraction": 0.5708770155906677, "alphanum_fraction": 0.5821841955184937, "avg_line_length": 39.741573333740234, "blob_id": "d2dc199c046010d734648cf22145691ef218629a", "content_id": "cb615bc2baf82e38575c4adf76cdb00027e00743", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3634, "license_type": "permissive", "max_line_length": 162, "num_lines": 89, "path": "/src/TorchVision/Ops/StochasticDepth.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\n\n// A number of implementation details in this file have been translated from the Python version of torchvision,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/vision/blob/a4f53308b2d0f1aa9191686e326f45c26053f686/torchvision/ops/stochastic_depth.py\n//\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/vision/blob/main/LICENSE\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.Runtime.CompilerServices;\nusing static TorchSharp.torch;\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n\n public static partial class ops\n {\n public static StochasticDepth StochasticDepth(double p, StochasticDepth.Mode mode) => new StochasticDepth(p, mode);\n\n /// <summary>\n /// Implements the Stochastic Depth from “Deep Networks with Stochastic Depth” used for randomly dropping residual branches of residual architectures.\n /// </summary>\n /// <param name=\"input\">The input tensor</param>\n /// <param name=\"p\">Probability of the input to be zeroed.</param>\n /// <param name=\"mode\">\"batch\" or \"row\". \"batch\" randomly zeroes the entire input, \"row\" zeroes randomly selected rows from the batch.</param>\n /// <param name=\"training\">Apply stochastic depth if is True</param>\n public static Tensor stochastic_depth(Tensor input, double p, StochasticDepth.Mode mode, bool training = true)\n {\n if (p < 0 || p > 1) throw new ArgumentOutOfRangeException(nameof(p));\n if (!training || p == 0.0) return input.alias();\n\n var survival_rate = 1 - p;\n var size = new List<long>();\n\n if (mode == torchvision.StochasticDepth.Mode.Row) {\n size.Add(input.shape[0]);\n for (var i = 0; i < input.ndim-1; i++)\n size.Add(1);\n } else {\n for (var i = 0; i < input.ndim; i++)\n size.Add(1);\n }\n\n var noise = torch.empty(size.ToArray(), dtype: input.dtype, device: input.device);\n noise.bernoulli_(survival_rate);\n\n if (survival_rate > 0) {\n noise.div_(survival_rate);\n }\n return input * noise;\n }\n }\n\n /// <summary>\n /// Implements the Stochastic Depth from “Deep Networks with Stochastic Depth” used for randomly dropping residual branches of residual architectures.\n /// </summary>\n public class StochasticDepth : nn.Module<Tensor, Tensor>\n {\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"p\">Probability of the input to be zeroed.</param>\n /// <param name=\"mode\">\"batch\" or \"row\". \"batch\" randomly zeroes the entire input, \"row\" zeroes randomly selected rows from the batch.</param>\n public StochasticDepth(double p, Mode mode) : base(nameof(StochasticDepth))\n {\n this.p = p;\n this.mode = mode;\n }\n\n public override Tensor forward(Tensor input)\n {\n return ops.stochastic_depth(input, p, mode, training);\n }\n\n public enum Mode { Batch, Row }\n\n private double p;\n private Mode mode;\n }\n }\n}\n" }, { "alpha_fraction": 0.6013584136962891, "alphanum_fraction": 0.607105553150177, "avg_line_length": 38.875, "blob_id": "720dcaf68f2dd5bec595d0e6dc03cfb5cc21a407", "content_id": "5fc5f07b7f0a6ee8841f1ef8e2b36e397977d9f3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1914, "license_type": "permissive", "max_line_length": 190, "num_lines": 48, "path": "/src/TorchSharp/NN/Normalization/LocalResponseNorm.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing static TorchSharp.torch;\nusing static TorchSharp.PInvoke.NativeMethods;\n\nnamespace TorchSharp\n{\n using Modules;\n\n namespace Modules\n {\n /// <summary>\n /// This class is used to represent a LocalResponseNorm module.\n /// </summary>\n public sealed class LocalResponseNorm : torch.nn.Module<Tensor, Tensor>\n {\n internal LocalResponseNorm(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle)\n {\n }\n\n public override Tensor forward(Tensor tensor)\n {\n if (tensor.Dimensions < 3) throw new ArgumentException($\"Invalid number of dimensions for LocalResponseNorm argument: {tensor.Dimensions}\");\n var res = THSNN_LocalResponseNorm_forward(handle.DangerousGetHandle(), tensor.Handle);\n if (res == IntPtr.Zero) { torch.CheckForErrors(); }\n return new Tensor(res);\n }\n }\n }\n\n public static partial class torch\n {\n public static partial class nn\n {\n /// <summary>\n /// Applies local response normalization over an input signal composed of several input planes, where channels occupy the second dimension. Applies normalization across channels.\n /// </summary>\n public static LocalResponseNorm LocalResponseNorm(long size, double alpha = 0.0001, double beta = 0.75, double k = 1.0)\n {\n unsafe {\n var handle = THSNN_LocalResponseNorm_ctor(size, alpha, beta, k, out var boxedHandle);\n if (handle == IntPtr.Zero) { torch.CheckForErrors(); }\n return new LocalResponseNorm(handle, boxedHandle);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.46465590596199036, "alphanum_fraction": 0.4722936749458313, "avg_line_length": 49.71936798095703, "blob_id": "9b41dd1801824c2ea66a632dca5ebaf98db50a06", "content_id": "c988ec3c00dd027f11d698bce25b17caaf3c659c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 12831, "license_type": "permissive", "max_line_length": 147, "num_lines": 253, "path": "/src/TorchVision/IO/GDriveDownload.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Security.Cryptography;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web;\n\n// A number of implementation details in this file have been translated from the Python version of torchvision,\n// largely located in the files found in this folder:\n//\n// https://github.com/pytorch/vision/blob/b78d98bb152ffb9c0c0f5365f59f475c70b1784e/torchvision/datasets/utils.py\n// The origin has the following copyright notice and license:\n//\n// https://github.com/pytorch/vision/blob/main/LICENSE\n//\n\n#nullable enable\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n public static partial class io\n {\n public class GDriveDownload\n {\n private static async Task SaveResponseContentAsync(\n byte[] head,\n Stream content,\n string destination,\n long? length = null,\n CancellationToken cancellationToken = default)\n {\n using (var progress_bar = torch.hub.CreateProgressBar(false))\n using (var fh = File.OpenWrite(destination)) {\n progress_bar.Maximum = length;\n await fh.WriteAsync(head, 0, head.Length, cancellationToken);\n progress_bar.Value = head.Length;\n byte[] buffer = new byte[64 * 1024];\n while (true) {\n int ret = await content.ReadAsync(buffer, 0, buffer.Length, cancellationToken);\n if (ret == 0) break;\n await fh.WriteAsync(buffer, 0, ret, cancellationToken);\n progress_bar.Value += ret;\n }\n }\n }\n\n private static string CalculateMD5(string fpath)\n {\n MD5 md5 = MD5.Create();\n byte[] hash;\n using (var stream = File.OpenRead(fpath)) {\n hash = md5.ComputeHash(stream);\n }\n return BitConverter.ToString(hash).Replace(\"-\", \"\").ToLowerInvariant();\n }\n\n private static bool CheckMD5(string fpath, string md5)\n {\n return md5 == CalculateMD5(fpath);\n }\n\n /// <summary>\n /// Check if the file exists and verify its content with MD5.\n /// </summary>\n /// <param name=\"fpath\">A path to the file</param>\n /// <param name=\"md5\">MD5 checksum</param>\n /// <returns>True if the file exists and MD5 of its content matches</returns>\n public static bool CheckIntegrity(string fpath, string? md5 = null)\n {\n if (!File.Exists(fpath)) {\n return false;\n }\n if (md5 is null) {\n return true;\n }\n return CheckMD5(fpath, md5);\n }\n\n private static async Task<(string, byte[], Stream)> ExtractGdriveApiResponseAsync(\n HttpResponseMessage response,\n int chunk_size = 32 * 1024,\n CancellationToken cancellationToken = default)\n {\n var stream = await response.Content.ReadAsStreamAsync();\n var buf = new byte[chunk_size];\n int pos = 0;\n while (pos < chunk_size) {\n int readLen = await stream.ReadAsync(buf, pos, chunk_size - pos, cancellationToken);\n if (readLen == 0) break;\n pos += readLen;\n }\n buf = buf.AsSpan(0, pos).ToArray();\n\n string api_response = string.Empty;\n string first_chunk = Encoding.ASCII.GetString(buf);\n string pattern = \"<title>Google Drive - (?<api_response>.+?)</title>\";\n var match = Regex.Match(first_chunk, pattern);\n if (match.Success) {\n api_response = match.Groups[\"api_response\"].Value;\n }\n return (api_response, buf, stream);\n }\n\n /// <summary>\n /// Download a Google Drive file and place it in root.\n /// </summary>\n /// <param name=\"file_id\">id of file to be downloaded</param>\n /// <param name=\"root\">Directory to place downloaded file in</param>\n /// <param name=\"filename\">Name to save the file under. If null, use the id of the file.</param>\n /// <param name=\"md5\">MD5 checksum of the download. If null, do not check</param>\n public static void DownloadFileFromGoogleDrive(\n string file_id, string root, string? filename = null, string? md5 = null)\n {\n try {\n Task.Run(async () => {\n await DownloadFileFromGoogleDriveAsync(file_id, root, filename, md5);\n }).Wait();\n } catch (AggregateException ex) {\n throw ex.InnerException ?? ex;\n }\n }\n\n /// <summary>\n /// Download a Google Drive file and place it in root.\n /// </summary>\n /// <param name=\"file_id\">id of file to be downloaded</param>\n /// <param name=\"root\">Directory to place downloaded file in</param>\n /// <param name=\"filename\">Name to save the file under. If null, use the id of the file.</param>\n /// <param name=\"md5\">MD5 checksum of the download. If null, do not check</param>\n /// <param name=\"cancellationToken\">A cancellation token</param>\n public static async Task DownloadFileFromGoogleDriveAsync(\n string file_id, string root, string? filename = null, string? md5 = null,\n CancellationToken cancellationToken = default)\n {\n // Based on https://stackoverflow.com/questions/38511444/python-download-files-from-google-drive-using-url\n if (filename is null) {\n filename = file_id;\n }\n var fpath = Path.Combine(root, filename);\n\n Directory.CreateDirectory(root);\n\n if (CheckIntegrity(fpath, md5)) {\n if (md5 is null) {\n Console.WriteLine($\"Using downloaded file: {fpath}\");\n } else {\n Console.WriteLine($\"Using downloaded and verified file: {fpath}\");\n }\n return;\n }\n\n CookieContainer cookies = new CookieContainer();\n HttpClientHandler handler = new HttpClientHandler();\n handler.CookieContainer = cookies;\n\n using (var httpClient = new HttpClient(handler)) {\n string url = \"https://drive.google.com/uc\";\n\n var queryString = HttpUtility.ParseQueryString(string.Empty);\n queryString.Add(\"id\", file_id);\n queryString.Add(\"export\", \"download\");\n string query_url = url + \"?\" + queryString.ToString();\n HttpResponseMessage? response = null;\n\n try {\n response = await httpClient.GetAsync(query_url, HttpCompletionOption.ResponseHeadersRead, cancellationToken);\n response.EnsureSuccessStatusCode();\n var responseCookies = cookies.GetCookies(new Uri(url));\n string token = string.Empty;\n foreach (var obj in responseCookies) {\n Cookie? kv = obj as Cookie;\n if (kv != null && kv.Name.StartsWith(\"download_warning\")) {\n token = kv.Value;\n }\n }\n string api_response = string.Empty;\n byte[]? head = null;\n Stream? stream = null;\n if (string.IsNullOrEmpty(token)) {\n (api_response, head, stream) = await ExtractGdriveApiResponseAsync(response, cancellationToken: cancellationToken);\n token = api_response == \"Virus scan warning\" ? \"t\" : string.Empty;\n }\n\n if (!string.IsNullOrEmpty(token)) {\n queryString.Add(\"confirm\", token);\n query_url = url + \"?\" + queryString.ToString();\n response.Dispose();\n response = null;\n response = await httpClient.GetAsync(query_url, HttpCompletionOption.ResponseHeadersRead, cancellationToken);\n (api_response, head, stream) = await ExtractGdriveApiResponseAsync(response);\n }\n\n if (head == null || stream == null) {\n // unreachable\n throw new InvalidDataException();\n }\n\n if (api_response == \"Quota exceeded\") {\n throw new InvalidDataException(\n $\"The daily quota of the file {filename} is exceeded and it \" +\n \"can't be downloaded. This is a limitation of Google Drive \" +\n \"and can only be overcome by trying again later.\");\n }\n\n await SaveResponseContentAsync(head, stream, fpath, cancellationToken: cancellationToken);\n } finally {\n if (response != null) {\n response.Dispose();\n }\n }\n\n // In case we deal with an unhandled GDrive API response, the file should be smaller than 10kB and contain only text\n if (new FileInfo(fpath).Length < 10 * 1024) {\n string text = ReadAllTextAsync(fpath);\n // Regular expression to detect HTML. Copied from https://stackoverflow.com/a/70585604\n if (Regex.Match(text, @\"</?\\s*[a-z-][^>]*\\s*>|(&(?:[\\w\\d]+|#\\d+|#x[a-f\\d]+);)\").Success) {\n Console.WriteLine(\n $\"We detected some HTML elements in the downloaded file. \" +\n $\"This most likely means that the download triggered an unhandled API response by GDrive. \" +\n $\"Please report this to torchvision at https://github.com/pytorch/vision/issues including \" +\n $\"the response:\\n\\n{text}\"\n );\n }\n }\n\n if (md5 is not null && !CheckMD5(fpath, md5)) {\n throw new InvalidDataException(\n $\"The MD5 checksum of the download file {fpath} does not match the one on record.\" +\n $\"Please delete the file and try again. \" +\n $\"If the issue persists, please report this to torchvision at https://github.com/pytorch/vision/issues.\");\n }\n }\n }\n\n private static string ReadAllTextAsync(string path, CancellationToken cancellationToken = default)\n {\n var memory = new MemoryStream();\n using (var stream = File.OpenRead(path)) {\n stream.CopyTo(memory);\n }\n return Encoding.ASCII.GetString(memory.GetBuffer());\n }\n }\n }\n }\n}" }, { "alpha_fraction": 0.5197963118553162, "alphanum_fraction": 0.5339757204055786, "avg_line_length": 49.45088195800781, "blob_id": "d799ee0c7d732ad819dec3b25bd95d810ae842d2", "content_id": "541684bf997745f2121bf8be5e44161dcb8d380d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 20029, "license_type": "permissive", "max_line_length": 238, "num_lines": 397, "path": "/src/TorchSharp/Optimizers/NAdam.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n using System.IO;\n using Modules;\n\n public static partial class torch\n {\n public static partial class optim\n {\n\n /// <summary>\n /// Implements the NAdam algorithm.\n ///\n /// For further details regarding the algorithm we refer to Incorporating Nesterov Momentum into Adam.\n /// https://openreview.net/forum?id=OM0jvwB8jIp57ZJjtNEZ\n /// </summary>\n /// <param name=\"named_parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"lr \">Learning rate</param>\n /// <param name=\"beta1\">Coefficient used for computing running averages of gradient and its square (default: 0.9)</param>\n /// <param name=\"beta2\">Coefficient used for computing running averages of gradient and its square (default: 0.999)</param>\n /// <param name=\"eps\">Term added to the denominator to improve numerical stability, i.e. avoid division-by-zero (default: 1e-8)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"momentum_decay\">Momentum decay</param>\n public static NAdam NAdam(IEnumerable<Parameter> named_parameters, double lr = 0.002, double beta1 = 0.9, double beta2 = 0.999, double eps = 1e-8, double weight_decay = 0, double momentum_decay = 4e-3)\n {\n return new NAdam(named_parameters, lr, beta1, beta2, eps, weight_decay, momentum_decay);\n }\n\n /// <summary>\n /// Implements the NAdam algorithm.\n ///\n /// For further details regarding the algorithm we refer to Incorporating Nesterov Momentum into Adam.\n /// https://openreview.net/forum?id=OM0jvwB8jIp57ZJjtNEZ\n /// </summary>\n /// <param name=\"named_parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"lr \">Learning rate</param>\n /// <param name=\"beta1\">Coefficient used for computing running averages of gradient and its square (default: 0.9)</param>\n /// <param name=\"beta2\">Coefficient used for computing running averages of gradient and its square (default: 0.999)</param>\n /// <param name=\"eps\">Term added to the denominator to improve numerical stability, i.e. avoid division-by-zero (default: 1e-8)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"momentum_decay\">Momentum decay</param>\n public static NAdam NAdam(IEnumerable<(string name, Parameter parameter)> named_parameters, double lr = 0.002, double beta1 = 0.9, double beta2 = 0.999, double eps = 1e-8, double weight_decay = 0, double momentum_decay = 4e-3)\n {\n return new NAdam(named_parameters.Select(np => np.parameter), lr, beta1, beta2, eps, weight_decay, momentum_decay);\n }\n\n /// <summary>\n /// Implements the NAdam algorithm.\n ///\n /// For further details regarding the algorithm we refer to Incorporating Nesterov Momentum into Adam.\n /// https://openreview.net/forum?id=OM0jvwB8jIp57ZJjtNEZ\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"lr \">Learning rate</param>\n /// <param name=\"beta1\">Coefficient used for computing running averages of gradient and its square (default: 0.9)</param>\n /// <param name=\"beta2\">Coefficient used for computing running averages of gradient and its square (default: 0.999)</param>\n /// <param name=\"eps\">Term added to the denominator to improve numerical stability, i.e. avoid division-by-zero (default: 1e-8)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"momentum_decay\">Momentum decay</param>\n public static NAdam NAdam(IEnumerable<NAdam.ParamGroup> parameters, double lr = 0.002, double beta1 = 0.9, double beta2 = 0.999, double eps = 1e-8, double weight_decay = 0, double momentum_decay = 4e-3)\n {\n return new NAdam(parameters, lr, beta1, beta2, eps, weight_decay, momentum_decay);\n }\n }\n }\n\n namespace Modules\n {\n using static torch.optim;\n\n public class NAdam : OptimizerHelper, IBetas\n {\n /// <summary>\n /// Implements NAdam algorithm.\n ///\n /// For further details regarding the algorithm we refer to Incorporating Nesterov Momentum into Adam.\n /// https://openreview.net/forum?id=OM0jvwB8jIp57ZJjtNEZ\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"lr \">Learning rate</param>\n /// <param name=\"beta1\">Coefficient used for computing running averages of gradient and its square (default: 0.9)</param>\n /// <param name=\"beta2\">Coefficient used for computing running averages of gradient and its square (default: 0.999)</param>\n /// <param name=\"eps\">Term added to the denominator to improve numerical stability, i.e. avoid division-by-zero (default: 1e-8)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"momentum_decay\">Momentum decay</param>\n public NAdam(IEnumerable<Parameter> parameters, double lr, double beta1 = 0.9, double beta2 = 0.999, double eps = 1e-8, double weight_decay = 0, double momentum_decay = 4e-3)\n : this(new ParamGroup[] { new ParamGroup { Parameters = parameters } }, lr, beta1, beta2, eps, weight_decay, momentum_decay)\n {\n }\n\n /// <summary>\n /// Implements NAdam algorithm.\n ///\n /// For further details regarding the algorithm we refer to Incorporating Nesterov Momentum into Adam.\n /// https://openreview.net/forum?id=OM0jvwB8jIp57ZJjtNEZ\n /// </summary>\n /// <param name=\"parameters\">Parameters to optimize. This optimizer requires the <b>named</b> parameters collection.</param>\n /// <param name=\"lr \">Learning rate</param>\n /// <param name=\"beta1\">Coefficient used for computing running averages of gradient and its square (default: 0.9)</param>\n /// <param name=\"beta2\">Coefficient used for computing running averages of gradient and its square (default: 0.999)</param>\n /// <param name=\"eps\">Term added to the denominator to improve numerical stability, i.e. avoid division-by-zero (default: 1e-8)</param>\n /// <param name=\"weight_decay\">Weight decay (L2 penalty) (default: 0)</param>\n /// <param name=\"momentum_decay\">Momentum decay</param>\n /// <returns></returns>\n public NAdam(IEnumerable<ParamGroup> parameters, double lr = 0.002, double beta1 = 0.9, double beta2 = 0.999, double eps = 1e-8, double weight_decay = 0, double momentum_decay = 4e-3)\n {\n if (lr < 0.0) throw new ArgumentException($\"Invalid learning rate: {lr}\");\n if (beta1 < 0.0 || beta1 > 1.0) throw new ArgumentException($\"Invalid beta1 value: {beta1}\");\n if (beta2 < 0.0 || beta2 > 1.0) throw new ArgumentException($\"Invalid beta2 value: {beta2}\");\n if (eps < 0.0) throw new ArgumentException($\"Invalid eps value: {eps}\");\n if (weight_decay < 0.0) throw new ArgumentException($\"Invalid weight_decay value: {weight_decay}\");\n if (momentum_decay < 0.0) throw new ArgumentException($\"Invalid momentum_decay value: {momentum_decay}\");\n\n var options = new Options {\n LearningRate = lr,\n InitialLearningRate = lr,\n beta1 = beta1,\n beta2 = beta2,\n eps = eps,\n weight_decay = weight_decay,\n momentum_decay = momentum_decay\n };\n\n _defaults = options;\n _parameter_groups = new List<Modules.ParamGroup>();\n\n foreach (var g in parameters) {\n add_param_group(g);\n }\n }\n\n /// <summary>\n /// Performs a single optimization step (parameter update).\n /// </summary>\n /// <param name=\"closure\">A closure that reevaluates the model and returns the loss. Optional for most optimizers.</param>\n /// <returns></returns>\n public override Tensor step(Func<Tensor> closure = null)\n {\n return _step<ParamGroup>(group => {\n\n var options = group.Options as Options;\n var beta1 = options.beta1.Value;\n var beta2 = options.beta2.Value;\n var eps = options.eps.Value;\n var weight_decay = options.weight_decay.Value;\n var momentum_decay = options.momentum_decay.Value;\n var lr = options.LearningRate.Value;\n\n foreach (var param in group.Parameters) {\n\n var grad = param.grad();\n\n if (grad is null) continue;\n\n var state = (State)_state[param.handle];\n\n state.step += 1;\n\n var exp_avg = state.exp_avg;\n var exp_avg_sq = state.exp_avg_sq;\n\n var bias_correction2 = 1 - Math.Pow(beta2, state.step);\n\n grad = (weight_decay != 0)\n ? grad.add(param, alpha: weight_decay)\n : grad.alias();\n\n var mu = beta1 * (1.0 - 0.5 * Math.Pow(0.96, state.step * momentum_decay));\n var mu_next = beta1 * (1.0 - 0.5 * Math.Pow(0.96, (state.step + 1) * momentum_decay));\n\n var mu_product = state.mu_product * mu;\n var mu_product_next = mu_product * mu * mu_next;\n\n exp_avg.mul_(beta1).add_(grad, alpha: 1 - beta1);\n exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value: 1 - beta2);\n\n var denom = exp_avg_sq.div(bias_correction2).sqrt_().add_(eps);\n\n param.addcdiv_(grad, denom, value: -lr * (1 - mu) / (1 - mu_product));\n param.addcdiv_(exp_avg, denom, value: -lr * mu_next / (1 - mu_product_next));\n\n state.mu_product = mu_product;\n }\n }, closure);\n }\n\n protected override void Dispose(bool disposing)\n {\n base.Dispose(disposing);\n foreach (var kvp in _state) {\n ((State)kvp.Item2).Dispose();\n }\n }\n\n public sealed class State : OptimizerState, IDisposable\n {\n public long step;\n public double mu_product;\n public Tensor exp_avg;\n public Tensor exp_avg_sq;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n private void Dispose(bool disposing)\n {\n if (disposing) {\n exp_avg.Dispose();\n exp_avg_sq.Dispose();\n }\n }\n\n /// <summary>\n /// Move all the state to the indicated device.\n /// </summary>\n /// <param name=\"device\">The device to move all state to.</param>\n public override void to(Device device)\n {\n exp_avg = exp_avg.to(device);\n exp_avg_sq = exp_avg_sq.to(device);\n }\n\n /// <summary>\n /// Load the optimizer parameter state from a stream.\n /// </summary>\n /// <param name=\"reader\">A binary reader connected to a stream open for reading.</param>\n public override void LoadStateDict(BinaryReader reader)\n {\n step = reader.ReadInt64();\n mu_product = reader.ReadDouble();\n exp_avg.Load(reader);\n exp_avg_sq.Load(reader);\n }\n\n /// <summary>\n /// Save the optimizer parameter state to a stream.\n /// </summary>\n /// <param name=\"writer\">A binary writer connected to a stream open for writing.</param>\n public override void SaveStateDict(BinaryWriter writer)\n {\n writer.Write(step);\n writer.Write(mu_product);\n exp_avg.Save(writer);\n exp_avg_sq.Save(writer);\n }\n\n /// <summary>\n /// Load optimizer parameter state from another optimizer.\n /// </summary>\n /// <param name=\"source\">An optimizer state record.</param>\n public override void LoadStateDict(OptimizerState source)\n {\n var st_state = source as State;\n exp_avg.Dispose();\n exp_avg_sq.Dispose();\n\n step = st_state.step;\n mu_product = st_state.mu_product;\n exp_avg = st_state.exp_avg;\n exp_avg_sq = st_state.exp_avg_sq;\n }\n\n /// <summary>\n /// Useful for tests, allows comparison of one state with another.\n /// </summary>\n /// <param name=\"other\">The other optimizer state</param>\n /// <returns></returns>\n public override bool ApproximatelyEquals(OptimizerState other)\n {\n var rhs = other as State;\n return (rhs is not null) && step == rhs.step &&\n mu_product == rhs.mu_product &&\n exp_avg.allclose(rhs.exp_avg) &&\n exp_avg_sq.allclose(rhs.exp_avg_sq);\n }\n }\n\n /// <summary>\n /// Add a param group to the Optimizer s param_groups.\n /// </summary>\n /// <param name=\"param_group\"></param>\n /// <remarks>This can be useful when fine tuning a pre-trained network as frozen layers can be made trainable and added to the Optimizer as training progresses.</remarks>\n public override void add_param_group(Modules.ParamGroup param_group)\n {\n var def = _defaults as Options;\n if (param_group.Options is null) {\n param_group.Options = new Options();\n }\n\n var opt = param_group.Options as Options;\n\n // Make sure all the options are set.\n if (!opt.LearningRate.HasValue) opt.LearningRate = def.LearningRate;\n if (!opt.beta1.HasValue) opt.beta1 = def.beta1;\n if (!opt.beta2.HasValue) opt.beta2 = def.beta2;\n if (!opt.eps.HasValue) opt.eps = def.eps;\n if (!opt.weight_decay.HasValue) opt.weight_decay = def.weight_decay;\n if (!opt.momentum_decay.HasValue) opt.momentum_decay = def.momentum_decay;\n\n opt.InitialLearningRate = opt.LearningRate.Value;\n\n _parameter_groups.Add(param_group);\n\n foreach (var p in param_group.Parameters) {\n var state = new State();\n _state[p.Handle] = state;\n state.step = 0;\n state.exp_avg = torch.zeros_like(p).DetachFromDisposeScope();\n state.exp_avg_sq = torch.zeros_like(p).DetachFromDisposeScope();\n }\n }\n\n public class Options : OptimizerOptions\n {\n public double? beta1;\n public double? beta2;\n public double? eps;\n public double? weight_decay;\n public double? momentum_decay;\n\n /// <summary>\n /// Load optimizer options (param-group hyperparameters) from another optimizer.\n /// </summary>\n /// <param name=\"source\">An optimizer options record.</param>\n public override void LoadStateDict(OptimizerOptions source)\n {\n base.LoadStateDict(source);\n var opts = source as Options;\n beta1 = opts.beta1;\n beta2 = opts.beta2;\n eps = opts.eps;\n weight_decay = opts.weight_decay;\n momentum_decay = opts.momentum_decay;\n }\n\n /// <summary>\n /// Load the optimizer options (param-group hyperparameters) from a stream.\n /// </summary>\n /// <param name=\"reader\">A binary reader connected to a stream open for reading.</param>\n public override void LoadStateDict(BinaryReader reader)\n {\n base.LoadStateDict(reader);\n beta1 = reader.ReadDouble();\n beta2 = reader.ReadDouble();\n eps = reader.ReadDouble();\n weight_decay = reader.ReadDouble();\n momentum_decay = reader.ReadDouble();\n }\n\n /// <summary>\n /// Save the optimizer options (param-group hyperparameters) to a stream.\n /// </summary>\n /// <param name=\"writer\">A binary writer connected to a stream open for writing.</param>\n public override void SaveStateDict(BinaryWriter writer)\n {\n base.SaveStateDict(writer);\n writer.Write(beta1.Value);\n writer.Write(beta2.Value);\n writer.Write(eps.Value);\n writer.Write(weight_decay.Value);\n writer.Write(momentum_decay.Value);\n }\n }\n\n public class ParamGroup : ParamGroup<Options>, IBetas\n {\n public ParamGroup() { }\n\n public ParamGroup(IEnumerable<Parameter> parameters, Options options) : base(parameters, options) { }\n\n public ParamGroup(IEnumerable<Parameter> parameters, double lr = 1.0, double beta1 = 0.9, double beta2 = 0.999, double eps = 1e-8, double weight_decay = 0, double momentum_decay = 4e-3)\n : base(parameters, new NAdam.Options { LearningRate = lr, beta1 = beta1, beta2 = beta2, eps = eps, weight_decay = weight_decay, momentum_decay = momentum_decay })\n {\n }\n\n public (double, double) Betas {\n get => (Options.beta1.Value, Options.beta2.Value);\n set { Options.beta1 = value.Item1; Options.beta2 = value.Item2; }\n }\n }\n\n public (double, double) Betas {\n get => ((_defaults as Options).beta1.Value, (_defaults as Options).beta2.Value);\n set { (_defaults as Options).beta1 = value.Item1; (_defaults as Options).beta2 = value.Item2; }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6769911646842957, "alphanum_fraction": 0.6769911646842957, "avg_line_length": 24.22222137451172, "blob_id": "7f2afcfc3435ec6731a16bbdcfd92c00bcc5ed1f", "content_id": "98c0714e78779e6aea9452903ce9301eea460dbe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 228, "license_type": "permissive", "max_line_length": 131, "num_lines": 9, "path": "/src/TorchSharp/Tensor/Enums/LobpcgMethod.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nnamespace TorchSharp\n{\n public enum LobpcgMethod\n {\n basic,\n ortho\n }\n}" }, { "alpha_fraction": 0.5157126784324646, "alphanum_fraction": 0.5157126784324646, "avg_line_length": 30.839284896850586, "blob_id": "2fb046f455d1def83b4608595d48b6d8403ddfb6", "content_id": "19bd3b84be81d74db9486c0a32e72f6aa1ad36a9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1782, "license_type": "permissive", "max_line_length": 130, "num_lines": 56, "path": "/src/TorchVision/RandomOrder.cs", "repo_name": "NiklasGustafsson/TorchSharp", "src_encoding": "UTF-8", "text": "// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static TorchSharp.torch;\n\nnamespace TorchSharp\n{\n public static partial class torchvision\n {\n internal class RandomOrder : IDisposable, ITransform\n {\n public RandomOrder(ITransform[] transforms)\n {\n this.transforms = transforms;\n }\n\n public void Dispose()\n {\n foreach (var t in transforms) {\n if (t is IDisposable) {\n ((IDisposable)t).Dispose();\n }\n }\n }\n\n public Tensor call(Tensor input)\n {\n var rng = new Random();\n foreach (var t in transforms.OrderBy(t => rng.NextDouble())) {\n input = t.call(input);\n }\n return input;\n }\n\n private IList<ITransform> transforms;\n }\n\n public static partial class transforms\n {\n /// <summary>\n /// Apply a list of transformations in a random order.\n /// </summary>\n /// <param name=\"transforms\">A list of transforms to apply.</param>\n /// <remarks>\n /// This transform uses the .NET Random API, not the Torch RNG.\n /// Each invocation of 'forward()' will randomize the order in which transforms\n /// are applied.\n /// </remarks>\n static public ITransform RandomOrder(params ITransform[] transforms)\n {\n return new RandomOrder(transforms);\n }\n }\n }\n}" } ]
361
luanacamm/Python-Hand-on-Solve-200-Problems
https://github.com/luanacamm/Python-Hand-on-Solve-200-Problems
62a4c81d4ad6422690c103348dfeeb90161831cf
3901b97772de6fa6eec476e4179c8d95207fce94
39391e21b64c66e73192fc3e6df7729ed390ce04
refs/heads/master
2020-03-25T01:27:02.355154
2018-08-02T04:18:26
2018-08-02T04:18:26
143,238,590
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6339285969734192, "alphanum_fraction": 0.6547619104385376, "avg_line_length": 23, "blob_id": "f0b811a4bc2faa3c7551785eca6d7a1bb41750f7", "content_id": "e2adf54ddf1b3a8f419ca870f719704e273321ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 336, "license_type": "no_license", "max_line_length": 105, "num_lines": 14, "path": "/LuanaSiqueiraSection03Lecture10.py", "repo_name": "luanacamm/Python-Hand-on-Solve-200-Problems", "src_encoding": "UTF-8", "text": "'''\ncalculate with input\nSection 3, Lecture 10\n# Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn. Go to the editor\n# Sample value of n is 5 \n# Expected Result : 615\n'''\n\n\nn = int(input(\"Input a number: \"))\na = str(n)\naa = str(n)+str(n)\naaa = str(n)+str(n)+str(n)\ntotal=(int (a)+int(aa)+ int (aaa))\n" }, { "alpha_fraction": 0.6441176533699036, "alphanum_fraction": 0.6882352828979492, "avg_line_length": 29.909090042114258, "blob_id": "1727e835325688a0418edf84a4d35f110dafad80", "content_id": "f5ca77873f0d6b011d7f11c28f96e90890121316", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 340, "license_type": "no_license", "max_line_length": 99, "num_lines": 11, "path": "/LuanaSiqueiraSection03Lecture08.py", "repo_name": "luanacamm/Python-Hand-on-Solve-200-Problems", "src_encoding": "UTF-8", "text": "'''\ninput age\nSection 3, Lecture 8\n# Create a program that asks the user to enter their name and their age.\n# Print out a message addressed to them that tells them the year that they will turn 100 years old.\n'''\n\nname = str(input(\"Name: \"))\nage = int(input(\"Age: \"))\nyear = (100-age)+2018\nprint(\"In \", year, name, \"will be 100 years old.\")\n" } ]
2
gyash03081997/coursera
https://github.com/gyash03081997/coursera
5e8001ab85b6a65b1cd8d070bcef4c4f6ea1da19
1f2dafb2eab45f561f039c260cca82c6a19b813f
df3b09d028513787d126c7813db2f399c273167c
refs/heads/master
2020-04-01T04:15:59.916647
2019-04-05T17:30:11
2019-04-05T17:30:11
152,856,337
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7211776971817017, "alphanum_fraction": 0.7287567257881165, "avg_line_length": 18.37005615234375, "blob_id": "1039524ca4bf3f451482256950e89ac357b8c069", "content_id": "a45876c486b61c96433dc58934dbb472e464bb3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6861, "license_type": "no_license", "max_line_length": 39, "num_lines": 354, "path": "/NLP Classwork/Stemmer.py", "repo_name": "gyash03081997/coursera", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport nltk\nnltk.download()\n\n\n# In[2]:\n\n\nfrom nltk.stem import PorterStemmer\nfrom nltk.stem import LancasterStemmer\n\n\n# In[3]:\n\n\nporter=PorterStemmer()\nlancaster=LancasterStemmer()\nprint(\"Porter Stemmer\")\nprint(porter.stem(\"cats\"))\nprint(porter.stem(\"trouble\"))\nprint(porter.stem(\"troubling\"))\nprint(porter.stem(\"troubled\"))\nprint(\"Lancaster Stemmer\")\nprint(lancaster.stem(\"cats\"))\nprint(lancaster.stem(\"trouble\"))\nprint(lancaster.stem(\"troubling\"))\nprint(lancaster.stem(\"troubled\"))\n\n\n# In[4]:\n\n\nprint(lancaster.stem(\"apple\"))\nprint(porter.stem(\"apple\"))\n\n\n# In[5]:\n\n\nprint(lancaster.stem(\"happiness\"))\nprint(porter.stem(\"happiness\"))\n\n\n# In[6]:\n\n\nprint(lancaster.stem(\"Dying\"))\nprint(porter.stem(\"Dying\"))\n\n\n# In[7]:\n\n\nprint(lancaster.stem(\"dying\"))\nprint(porter.stem(\"dying\"))\n\n\n# In[8]:\n\n\nprint(lancaster.stem(\"impossible\"))\nprint(porter.stem(\"impossible\"))\n\n\n# In[9]:\n\n\nprint(lancaster.stem(\"Impossible\"))\nprint(porter.stem(\"Impossible\"))\n\n\n# In[10]:\n\n\nprint(lancaster.stem(\"prenuptial\"))\nprint(porter.stem(\"prenuptial\"))\n\n\n# In[11]:\n\n\nprint(lancaster.stem(\"Prenuptial\"))\nprint(porter.stem(\"Prenuptial\"))\n\n\n# In[12]:\n\n\nprint(lancaster.stem(\"Collage\"))\nprint(porter.stem(\"Collage\"))\n\n\n# In[13]:\n\n\nprint(lancaster.stem(\"collage\"))\nprint(porter.stem(\"collage\"))\n\n\n# In[14]:\n\n\nprint(lancaster.stem(\"distrustful\"))\nprint(porter.stem(\"distrustful\"))\n\n\n# In[ ]:\n\n\n\n\n\n# In[15]:\n\n\nprint(lancaster.stem(\"receive\"))\nprint(porter.stem(\"receive\"))\nprint(lancaster.stem(\"proctee\"))\nprint(porter.stem(\"proctee\"))\n\n\n# In[16]:\n\n\nprint(lancaster.stem(\"Receive\"))\nprint(porter.stem(\"Receive\"))\nprint(lancaster.stem(\"Proctee\"))\nprint(porter.stem(\"Proctee\"))\n\n\n# In[36]:\n\n\nprint(lancaster.stem(\"brownie\"))\nprint(porter.stem(\"brownie\"))\n\n\n# In[18]:\n\n\nprint(lancaster.stem(\"employer\"))\nprint(porter.stem(\"employer\"))\nprint(lancaster.stem(\"employee\"))\nprint(porter.stem(\"employee\"))\n\n\n# In[21]:\n\n\nprint(lancaster.stem(\"unhappy\"))\nprint(porter.stem(\"unhappy\"))\nprint(lancaster.stem(\"trilogy\"))\nprint(porter.stem(\"trilogy\"))\n\n\n# In[22]:\n\n\nprint(lancaster.stem(\"collaborate\"))\nprint(porter.stem(\"collaborate\"))\nprint(lancaster.stem(\"corporate\"))\nprint(porter.stem(\"corporate\"))\n\n\n# In[23]:\n\n\nprint(lancaster.stem(\"obliterate\"))\nprint(porter.stem(\"obliterate\"))\nprint(lancaster.stem(\"crate\"))\nprint(porter.stem(\"crate\"))\n\n\n# In[24]:\n\n\nprint(lancaster.stem(\"obliterate\"))\nprint(porter.stem(\"obliterate\"))\n\n\n# In[25]:\n\n\nprint(lancaster.stem(\"salutation\"))\nprint(porter.stem(\"salutation\"))\nprint(lancaster.stem(\"information\"))\nprint(porter.stem(\"information\"))\nprint(lancaster.stem(\"generation\"))\nprint(porter.stem(\"generation\"))\nprint(lancaster.stem(\"exclaimation\"))\nprint(porter.stem(\"exclaimation\"))\nprint(lancaster.stem(\"speculation\"))\nprint(porter.stem(\"speculation\"))\nprint(lancaster.stem(\"hibernation\"))\nprint(porter.stem(\"hibernation\"))\nprint(lancaster.stem(\"manipulation\"))\nprint(porter.stem(\"manipulation\"))\nprint(lancaster.stem(\"application\"))\nprint(porter.stem(\"application\"))\nprint(lancaster.stem(\"termination\"))\nprint(porter.stem(\"termination\"))\nprint(lancaster.stem(\"retribution\"))\nprint(porter.stem(\"retribution\"))\nprint(lancaster.stem(\"distribution\"))\nprint(porter.stem(\"distribution\"))\nprint(lancaster.stem(\"execution\"))\nprint(porter.stem(\"execution\"))\nprint(lancaster.stem(\"substitution\"))\nprint(porter.stem(\"substitution\"))\nprint(lancaster.stem(\"movement\"))\nprint(porter.stem(\"movement\"))\nprint(lancaster.stem(\"predicament\"))\nprint(porter.stem(\"predicament\"))\nprint(lancaster.stem(\"abolishment\"))\nprint(porter.stem(\"abolishment\"))\nprint(lancaster.stem(\"infringement\"))\nprint(porter.stem(\"infringement\"))\nprint(lancaster.stem(\"attainment\"))\nprint(porter.stem(\"attainment\"))\nprint(lancaster.stem(\"accomplishment\"))\nprint(porter.stem(\"accomplishment\"))\n\n\n# In[26]:\n\n\nprint(lancaster.stem(\"incredible\"))\nprint(porter.stem(\"incredible\"))\nprint(lancaster.stem(\"invincible\"))\nprint(porter.stem(\"invincible\"))\nprint(lancaster.stem(\"forcible\"))\nprint(porter.stem(\"forcible\"))\nprint(lancaster.stem(\"visible\"))\nprint(porter.stem(\"visible\"))\n\n\n# In[27]:\n\n\nprint(lancaster.stem(\"gillible\"))\nprint(porter.stem(\"gullible\"))\nprint(lancaster.stem(\"tangible\"))\nprint(porter.stem(\"tangible\"))\nprint(lancaster.stem(\"possible\"))\nprint(porter.stem(\"possible\"))\nprint(lancaster.stem(\"collapsible\"))\nprint(porter.stem(\"collapsible\"))\nprint(lancaster.stem(\"accessible\"))\nprint(porter.stem(\"accessible\"))\nprint(lancaster.stem(\"convertible\"))\nprint(porter.stem(\"convertible\"))\nprint(lancaster.stem(\"permissible\"))\nprint(porter.stem(\"permissible\"))\n\n\n# In[31]:\n\n\nprint(lancaster.stem(\"abider\"))\nprint(porter.stem(\"abider\"))\nprint(lancaster.stem(\"abetter\"))\nprint(porter.stem(\"abetter\"))\nprint(lancaster.stem(\"abater\"))\nprint(porter.stem(\"abater\"))\nprint(lancaster.stem(\"adopter\"))\nprint(porter.stem(\"adopter\"))\nprint(lancaster.stem(\"adorner\"))\nprint(porter.stem(\"adorner\"))\n\n\n# In[32]:\n\n\nprint(lancaster.stem(\"ionization\"))\nprint(porter.stem(\"ionization\"))\nprint(lancaster.stem(\"activization\"))\nprint(porter.stem(\"activization\"))\nprint(lancaster.stem(\"realization\"))\nprint(porter.stem(\"realization\"))\n\n\n# In[33]:\n\n\nprint(lancaster.stem(\"acidified\"))\nprint(porter.stem(\"acidified\"))\nprint(lancaster.stem(\"allied\"))\nprint(porter.stem(\"allied\"))\nprint(lancaster.stem(\"amplified\"))\nprint(porter.stem(\"amplified\"))\nprint(lancaster.stem(\"beautified\"))\nprint(porter.stem(\"beautified\"))\nprint(lancaster.stem(\"identified\"))\nprint(porter.stem(\"identified\"))\nprint(lancaster.stem(\"buried\"))\nprint(porter.stem(\"buried\"))\nprint(lancaster.stem(\"humidified\"))\nprint(porter.stem(\"humidified\"))\nprint(lancaster.stem(\"abducted\"))\nprint(porter.stem(\"abducted\"))\nprint(lancaster.stem(\"aborted\"))\nprint(porter.stem(\"aborted\"))\nprint(lancaster.stem(\"abandoned\"))\nprint(porter.stem(\"abandoned\"))\nprint(lancaster.stem(\"accorded\"))\nprint(porter.stem(\"accorded\"))\nprint(lancaster.stem(\"aligned\"))\nprint(porter.stem(\"aligned\"))\nprint(lancaster.stem(\"alleged\"))\nprint(porter.stem(\"alleged\"))\nprint(lancaster.stem(\"curated\"))\nprint(porter.stem(\"curated\"))\n\n\n# In[35]:\n\n\nprint(lancaster.stem(\"abhor\"))\nprint(porter.stem(\"abhor\"))\nprint(lancaster.stem(\"abjudicator\"))\nprint(porter.stem(\"abjudicator\"))\nprint(lancaster.stem(\"acceptor\"))\nprint(porter.stem(\"acceptor\"))\nprint(lancaster.stem(\"frown\"))\nprint(porter.stem(\"circulator\"))\nprint(lancaster.stem(\"circulator\"))\nprint(porter.stem(\"commentor\"))\nprint(lancaster.stem(\"commentor\"))\nprint(porter.stem(\"corridor\"))\nprint(lancaster.stem(\"corridor\"))\nprint(porter.stem(\"corridor\"))\nprint(lancaster.stem(\"decorator\"))\nprint(porter.stem(\"decorator\"))\nprint(lancaster.stem(\"exclaimator\"))\nprint(porter.stem(\"exclaimator\"))\n\n\n# In[39]:\n\n\nprint(lancaster.stem(\"crying\"))\nprint(porter.stem(\"crying\"))\nprint(lancaster.stem(\"Dying\"))\nprint(porter.stem(\"Dying\"))\nprint(lancaster.stem(\"dying\"))\nprint(porter.stem(\"dying\"))\n\n\n# In[ ]:\n\n\n\n\n" }, { "alpha_fraction": 0.7063218355178833, "alphanum_fraction": 0.7183908224105835, "avg_line_length": 15.224299430847168, "blob_id": "46fca356b991430a59a4aa64a6c0d1cd83e97de6", "content_id": "f755181d79e3cc074b45dba4b70a5b370c8383a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1740, "license_type": "no_license", "max_line_length": 112, "num_lines": 107, "path": "/NLP Classwork/Vectorizer.py", "repo_name": "gyash03081997/coursera", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport nltk\nfrom nltk.stem import PorterStemmer\nstemmer=PorterStemmer()\n\nexample=\"The cat was chasing a mouse\"\nexample=[stemmer.stem(token) for token in example.split(\" \")]\n\n\n# In[3]:\n\n\nprint(\" \".join(example))\n\n\n# In[12]:\n\n\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\nlemmatizer=WordNetLemmatizer()\n\nexample=\"The cat was chasing the mice\"\nexample=[lemmatizer.lemmatize(token) for token in example.split(\" \")]\n\n\n# In[13]:\n\n\nprint(\" \".join(example))\n\n\n# In[11]:\n\n\nprint(lemmatizer.lemmatize('better',pos='a'))\n\n\n# In[14]:\n\n\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\nlemmatizer=WordNetLemmatizer()\n\nexample=\"The cat was chasing the mice. there were cacti round the corner\"\nexample=[lemmatizer.lemmatize(token) for token in example.split(\" \")]\n\n\n# In[18]:\n\n\nprint(\" \".join(example))\n\n\n# In[19]:\n\n\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n\n# In[24]:\n\n\nvect=CountVectorizer(binary=True)#can explore other parameters like other than binary\ncorpus=[\"Tessaract is a good good optical recognition technique\",\"optical character recognition is significant\"]\nvect.fit(corpus)\n#print(vect.transform([\"This is a good optical\"]).toarray())\nprint(vect.transform(corpus).toarray())\n\n\n# In[25]:\n\n\nvect=CountVectorizer(binary=True)#can explore other parameters like other than binary\ncorpus=[\"Tessaract is a good good optical recognition technique\",\"Tessaract is significant\"]\nvect.fit(corpus)\n#print(vect.transform([\"This is a good optical\"]).toarray())\nprint(vect.transform(corpus).toarray())\n\n\n# In[30]:\n\n\nvocab=vect.vocabulary_ #vocabulary built in\nfor key in sorted(vocab.keys()):\n print(\"{}:{}\".format(key,vocab[key]))\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n" } ]
2
bayerj/Jaeger
https://github.com/bayerj/Jaeger
221f12b3326892a4859d1f9ee46ee990d0481230
d4730f3f920c7d6c0aa8430a9c39732e3ef07eca
fce770f0181cbc5e5b3be4a9edc1b8f832942dbb
refs/heads/master
2021-01-10T20:33:04.100122
2012-04-17T12:45:02
2012-04-17T12:45:02
3,866,877
2
1
null
null
null
null
null
[ { "alpha_fraction": 0.5528150200843811, "alphanum_fraction": 0.5560321807861328, "avg_line_length": 22.3125, "blob_id": "3e57d77f589b368cf7f176f772a7cbc799adf6ff", "content_id": "d9a8f04766005fa2a217a7c6b38be1e1ed917ee6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1865, "license_type": "no_license", "max_line_length": 60, "num_lines": 80, "path": "/jaeger/searchspace.py", "repo_name": "bayerj/Jaeger", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\nimport numpy as np\n\n\nclass Numeric(object):\n\n def __init__(self, intify=False):\n self.intify = intify\n\n def draw(self, seed):\n res = self._draw(seed)\n if self.intify:\n res = int(round(res))\n return res\n\n\nclass Uniform(Numeric):\n\n def __init__(self, lower, upper, intify=False):\n self.size = 1\n self.lower = lower\n self.upper = upper\n super(Uniform, self).__init__(intify)\n\n def _draw(self, seed):\n # Pick only the first entry.\n seed = seed[0]\n scale = self.upper - self.lower\n return seed * scale + self.lower\n\n\nclass LogUniform(Numeric):\n\n def __init__(self, lower, upper, intify=False):\n self.size = 1\n self.lower = lower\n self.upper = upper\n self.uniform = Uniform(np.log(lower), np.log(upper))\n super(LogUniform, self).__init__(intify)\n\n def _draw(self, seed):\n drawn = self.uniform.draw(seed)\n return np.exp(drawn)\n\n\nclass OneOf(object):\n\n def __init__(self, choices):\n self.size = len(choices)\n self.choices = choices\n\n def draw(self, seed):\n return self.choices[seed.argmax()]\n\n\nclass SearchSpace(object):\n\n def __init__(self):\n self.variables = []\n\n def add(self, handle, var):\n self.variables.append((handle, var))\n\n def draw(self, seeds=None):\n n_seeds = sum(i.size for _, i in self.variables)\n if seeds is None:\n seeds = np.random.random(n_seeds)\n seeds = np.asarray(seeds)\n if seeds.shape[0] != n_seeds:\n raise ValueError('wrong dimension of seed')\n\n start = 0\n sample = {}\n for handle, v in self.variables:\n stop = start + v.size\n sample[handle] = v.draw(seeds[start:stop])\n start = stop\n return sample\n" }, { "alpha_fraction": 0.8075539469718933, "alphanum_fraction": 0.8075539469718933, "avg_line_length": 41.769229888916016, "blob_id": "32f2e5327d62e3b1d9672c1e389c16d09bfdf89d", "content_id": "6d9f0aa067260646f6ede4b7365c43f49af25841", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 556, "license_type": "no_license", "max_line_length": 80, "num_lines": 13, "path": "/README.md", "repo_name": "bayerj/Jaeger", "src_encoding": "UTF-8", "text": "Jaeger\n------\n\nJaeger is a small package for performing random search on parameter spaces for\nfunctions with a nice interface. I hope to extend it with Bayesian optimization\nand distributed evaluation techniques.\n\nThe approach is that the user defines a function which all the parameters that\nshould vary as inputs. In the next step, he defines a search space consisting\nof several random variables. She can then sample from that search space in order\nto pass those parameters into the function of interest.\n\nFor an example, see examples/neuralnetwork.py.\n" }, { "alpha_fraction": 0.6254545450210571, "alphanum_fraction": 0.6618182063102722, "avg_line_length": 31.352941513061523, "blob_id": "adfdfc2724b4342cc2a28e0e44ce861962be4e9e", "content_id": "59e070e8f016387338167c1ef0b84f36609a533c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 550, "license_type": "no_license", "max_line_length": 61, "num_lines": 17, "path": "/examples/neuralnetwork.py", "repo_name": "bayerj/Jaeger", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport jaeger.searchspace as S\n\nsearch = S.SearchSpace()\nsearch.add('n_hidden', S.Uniform(10, 200, intify=True))\nsearch.add('momentum', S.Uniform(0.0, 0.99))\nsearch.add('step_rate', S.LogUniform(0.00001, 1))\nsearch.add('transfer_function', S.OneOf(['tanh', 'sigmoid']))\n\nfor i in range(10):\n sample = search.draw()\n print 'number of hiddens:', sample['n_hidden']\n print 'transfer function:', sample['transfer_function']\n print 'momentum:', sample['momentum']\n print 'step rate:', sample['step_rate']\n print\n" }, { "alpha_fraction": 0.5624270439147949, "alphanum_fraction": 0.604434072971344, "avg_line_length": 23.485713958740234, "blob_id": "8d8a40effd1e6e5aacdd82c56910eca867429ac4", "content_id": "50e7e8e10d450fddc953ef11a373f910c7099ce1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 857, "license_type": "no_license", "max_line_length": 70, "num_lines": 35, "path": "/test/test_searchspace.py", "repo_name": "bayerj/Jaeger", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nfrom jaeger.searchspace import Uniform, LogUniform, OneOf, SearchSpace\n\n\ndef test_uniform():\n x = Uniform(0, 1)\n seeds = np.random.random((1000, 1))\n draws = [x.draw(s) for s in seeds]\n assert all(0 <= i < 1 for i in draws)\n\n\ndef test_uniform_int():\n x = Uniform(0, 2, intify=True)\n seeds = np.random.random((1000, 1))\n draws = [x.draw(s) for s in seeds]\n assert all(i in (0, 1, 2) for i in draws)\n\n\ndef test_loguniform():\n x = LogUniform(1, 2)\n seeds = np.random.random((10, 1))\n draws = [x.draw(s) for s in seeds]\n print draws\n assert all(1 <= i < 2 for i in draws)\n\n\ndef test_loguniform_int():\n x = LogUniform(1, 2, intify=True)\n seeds = np.random.random((1000, 1))\n draws = [x.draw(s) for s in seeds]\n print draws\n assert all(i in (1, 2) for i in draws)\n" } ]
4
lindo-zy/TBspider
https://github.com/lindo-zy/TBspider
5f1a6df29977d08be83852ee6141100d15ba4a8f
ea640770c0c7473ffe498c4ee065b14850795af7
1f0c7bf2558cb9481993420fa723a152418b273f
refs/heads/master
2020-08-01T20:07:48.995353
2019-10-16T15:04:10
2019-10-16T15:04:10
211,101,359
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.659375011920929, "alphanum_fraction": 0.6625000238418579, "avg_line_length": 15.8421049118042, "blob_id": "c9bc22c1d67fe192182e84361133e70c85aa231a", "content_id": "ae11284cb23599d1287cc7ddd68ffbced220eb0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 320, "license_type": "no_license", "max_line_length": 52, "num_lines": 19, "path": "/DataItem/DataItem/items.py", "repo_name": "lindo-zy/TBspider", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Define here the models for your scraped items\n#\n# See documentation in:\n# https://doc.scrapy.org/en/latest/topics/items.html\n\n\nfrom scrapy import Item, Field\n\n\nclass TBdetailItem(Item):\n result = Field()\n callback = Field()\n headers = Field()\n\n\nclass TestItem(Item):\n ip = Field()\n" }, { "alpha_fraction": 0.4871891438961029, "alphanum_fraction": 0.4941597580909729, "avg_line_length": 28.16483497619629, "blob_id": "9bf4ab3cb7a9f557732f75e7b9be6d5982b13f41", "content_id": "d0c391bae23d7c40c8c66e82e7f561020994dbab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5550, "license_type": "no_license", "max_line_length": 112, "num_lines": 182, "path": "/DataItem/redis_pool.py", "repo_name": "lindo-zy/TBspider", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport redis\nfrom config import *\nimport re\nimport json\nimport random\n\n\nclass RedisPool(object):\n\n def __init__(self, host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWORD, db=DB_NUM):\n\n pool = redis.ConnectionPool(host='127.0.0.1', port=6379, decode_responses=True, db=db,\n password=REDIS_PASSWORD)\n\n if password:\n self._db = redis.Redis(connection_pool=pool)\n else:\n self._db = redis.Redis(host=host, port=port, db=db, decode_responses=True)\n\n # 插入集合\n def set(self, name, value):\n '''\n redis.set('key', 'value')\n :param name:\n :param value:\n :return:\n '''\n self._db.set(name, value)\n\n # 批量插入\n def mset(self, mapping):\n '''\n redis.mset({\"key1\": 'value1', \"key2\": 'value2'})\n :param mapping:\n :return:\n '''\n self._db.mset(json.dumps(mapping))\n\n # 取某个key的值\n def get(self, name):\n '''\n red.get('key1')\n :param name:\n :return:\n '''\n return self._db.get(name=name)\n\n def hset(self, name, key, mapping):\n '''\n\n :param name:\n :param key:\n :param mapping:\n :return:\n '''\n status = self._db.hset(name, key, json.dumps(mapping))\n if int(status) == 0:\n print(f'{key}:更新数据成功!')\n else:\n print(f'{key}:插入数据成功!')\n\n def hget(self, name, key):\n '''\n :param name:\n :param key:\n :return:\n '''\n return self._db.hget(name, key)\n\n def hmget(self, name, keys_list):\n\n return self._db.hmget(name=name, keys=keys_list)\n\n def hgetall(self, name):\n '''\n :param name:\n :return:\n '''\n return self._db.hgetall(name)\n\n def zadd(self, name, value, score):\n mapping = {json.dumps(value): int(score)}\n self._db.zadd(name, mapping)\n\n def zrangebyscore(self, name, min, max, withscores=True):\n '''\n 按分数范围,从小到大排列\n :param name:\n :param min:\n :param max:\n :return:\n '''\n return self._db.zrangebyscore(name, min, max, withscores=withscores)\n\n def zrem(self, name, values):\n '''\n 删除有序集合中的值\n :param name:\n :param values:\n :return:\n '''\n self._db.zrem(name, json.dumps(values))\n\n def save_cookie(self, value, score=3):\n self.zadd(\"cookies_pool\", value, score)\n\n def save_account(self, account_list):\n # 录入账号\n try:\n if len(account_list) > 0:\n for account in account_list:\n username = account['username']\n password = account['password']\n print('账号', username, '密码', password)\n self._db.hset('accounts', username, password)\n else:\n print('请检查账号录入配置!')\n except Exception as e:\n print(f'请检查账号录入配置,错误信息{e}')\n\n def get_accounts(self):\n accounts_dict = self._db.hgetall('accounts')\n result = {}\n for user, password in accounts_dict.items():\n result[user] = password\n return result\n\n def update_pool(self, username, counter=1):\n # 先取出,再更新score\n # 返回列表\n result = self.zrangebyscore('cookies_pool', 0, 3)\n if result:\n for item in result:\n score = int(item[1]) - counter\n value = json.loads(item[0])\n if score >= 0 and value.get('username') == username:\n # 更新cookies\n self.zadd('cookies_pool', value=value, score=score)\n print('score更新成功!')\n elif score < 0 and value.get('username') == username:\n self.zrem('cookies_pool', value)\n else:\n print('cookies_pool为空!')\n\n def cookies_pool(self, account=''):\n result = self.zrangebyscore('cookies_pool', 0, 3)\n self.update_pool(account)\n cookie_list = []\n if result:\n for item in result:\n item_dict = json.loads(item[0])\n score = int(item[1])\n cookie_account = item_dict['username']\n # 返回其他有效cookies\n if cookie_account != account:\n cookie = item_dict['cookie']\n # # 做一步预处理,增加cookie可用度\n unb_random = ''.join(str(random.choice(range(9))) for _ in range(13))\n\n pattern = r'unb=(\\d+)'\n cookie_unb = re.sub(pattern=pattern, repl='unb=' + unb_random, string=cookie)\n\n cookie_token = ''.join(re.findall(r'_m_h5_tk=([^;]+);', cookie_unb)).split('_')[0]\n\n cookie_dict = dict([tuple(x.split('=', 1)) for x in cookie_unb.split(';')])\n\n cookie_list.append({'account': cookie_account, 'score': score, 'cookie_token': cookie_token,\n 'cookie_dict': cookie_dict, 'cookie_str': cookie_unb})\n else:\n return None\n return cookie_list[-1]\n else:\n print('cookies池为空!')\n return None\n\n\nif __name__ == '__main__':\n con = RedisPool()\n print(con.cookies_pool())\n" }, { "alpha_fraction": 0.4503311216831207, "alphanum_fraction": 0.47965940833091736, "avg_line_length": 14.731343269348145, "blob_id": "b0cf57e117dcb88786f6de33294319fbd3c70b7e", "content_id": "d857afed3b836af56f9f7e629f6ab91a8e96578e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1457, "license_type": "no_license", "max_line_length": 94, "num_lines": 67, "path": "/项目结构文档.md", "repo_name": "lindo-zy/TBspider", "src_encoding": "UTF-8", "text": "## ShopSpider\n\n#### api\n\n此项目是Flask框架的web工程,运行起来是接受post数据,进行对指定店铺采集\n\n\n\ngunicorn -w 4 -b 0.0.0.0:8888 wsgi:app 部署flask工程\n\n测试的时候直接运行wisgi.py即可\n\n------\n\n#### DataItem\n\ndata_utils:爬虫工具目录\n\nspdiers:爬虫编写目录\n\n进入到TBspider/DataItem部署爬虫工程\n1.执行scrapyd命令\n2.新建一个命令行窗口,执行scrapyd-deploy TB -p DataItem\n3.控制台出现status:ok 表明部署成功\n\n详细参考:https://blog.csdn.net/web_9705/article/details/80417219\n\n------\n\n数据库配置\n\nredis配置:api/config.py和DataItem/spiderConfig.py\n\n\n------\n\n需要的相关账号\n\n| 新浪微博 | 密码 | 淘宝 | 密码 |\n| :---------- | ----------- | ----------- | ----------- |\n\n\n| 代理商 | 账号 | 密码 | 备注 |\n| ------------------------------------------------------- | ----------- | ----------- | ---- |\n\n| 打码平台 | 账号 | 密码 | 备注 |\n| ----------------------- | ------------ | ----------- | ---- |\n\n\n\n------\n\n完整运行流程\n\n1.运行/DataItem/data_utils/gen_login_cookie.py文件,生成至少一个登陆后的cookie\n2.使用scrapyd和scrapyd-deplpoy部署爬虫\n3.将所需采集的店铺信息发送至启动的服务\n\n------\n\n项目优化\n\n1.redis数据库使用db2和db3\n\n2.cookies过期太快\n\n------\n\n\n\n" }, { "alpha_fraction": 0.6597796082496643, "alphanum_fraction": 0.6625344157218933, "avg_line_length": 25.88888931274414, "blob_id": "3d15ae4a434fe234a9e650ece335e977cbc80e03", "content_id": "34fdad9eeb7d543432f7c7b6cf1c741b87d46a4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 760, "license_type": "no_license", "max_line_length": 83, "num_lines": 27, "path": "/DataItem/DataItem/pipelines.py", "repo_name": "lindo-zy/TBspider", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\nimport requests\nimport json\nfrom DataItem.myLog import Log\n\nlogger = Log(log_name='pipeline')\n\n\nclass TestPipeline:\n def process_item(self, item, spider):\n data = item\n logger.info(f'开始回调给产品库:{data[\"callback\"]}')\n\n callback = data['callback']\n result = data['result']\n headers = data['headers']\n\n requests.packages.urllib3.disable_warnings()\n r = requests.post(url=callback, headers=headers, json=result, verify=False)\n\n logger.info(f'产品库响应内容:{r.text}')\n return item\n" }, { "alpha_fraction": 0.5195195078849792, "alphanum_fraction": 0.6042513251304626, "avg_line_length": 50.9357795715332, "blob_id": "bc7e9dd0ab199f4492bb885bd52ad21b73cd8f7f", "content_id": "7275774b8c0cd58e859ed275cd71ff2dbd738f66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17843, "license_type": "no_license", "max_line_length": 259, "num_lines": 327, "path": "/DataItem/DataItem/spiders/NewTbShopSpider.py", "repo_name": "lindo-zy/TBspider", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport re\nimport time\nimport hashlib\nimport json\nfrom html import unescape\nimport requests\nimport scrapy\nfrom scrapy import signals\nfrom scrapy.selector import Selector\nfrom DataItem.redis_pool import RedisPool\nfrom DataItem.myLog import Log\nfrom datetime import datetime\nimport random\nfrom urllib.parse import urlparse\nimport math\n\nlogger = Log(log_name='TBSpider')\n\n\nclass TbshopspiderSpider(scrapy.Spider):\n name = 'NewTbShopSpider'\n allowed_domains = ['taobao.com', 'tmall.com']\n\n custom_settings = {\n 'CONCURRENT_REQUESTS': 1,\n 'CONCURRENT_REQUESTS_PER_DOMAIN': 1,\n 'DOWNLOAD_DELAY': 1,\n 'REDIRECT_ENABLED': False,\n 'DOWNLOADER_MIDDLEWARES': {\n # 'DataItem.middlewares.ProxyDownloaderMiddleware': 610,\n 'DataItem.middlewares.CookiesPoolMiddleware': 610, # cookie池\n # 'scrapy_crawlera.CrawleraMiddleware': 610\n }\n }\n\n def __init__(self, **kwargs):\n\n logger.info(f'----------------开始采集,{datetime.now()}----------------')\n\n # 初始化redis\n self.rdb = RedisPool()\n self.reds_conn = self.rdb.redis_con()\n\n # 获取店铺所有商品id,价格,名称\n self.product_list_api = '/i/asynSearch.htm?mid=w-{0}-0&wid={0}&pageNo='\n\n self.shop_info_api = 'http://shop.m.taobao.com/shop/shopsearch/search_page_json.do?sort=default&type=all&q='\n\n self.shop_detail_api = ('http://h5api.m.taobao.com/h5/mtop.taobao.geb.shopinfo.queryshopinfo/2.0/?jsv=2.4.2'\n '&appKey={appkey}&t={t}&sign={sign}&api=mtop.taobao.geb.shopinfo.queryshopinfo&v=2.0'\n '&type=originaljson&timeout=3000&AntiCreep=true&dataType=json&H5Request=true&data={data}')\n\n # 计算淘宝sign的appkeys\n self.appkeys = '12574478'\n self.cookie_pool = self.con.cookies_pool()\n self.account = self.cookie_pool['account']\n self.token = self.cookie_pool['cookie_token']\n self.cookies = self.cookie_pool['cookie_dict']\n logger.info(f'当前使用的cookies的账号为:{self.account}')\n\n # 存储全部商品id\n self.all_products_list = []\n\n # todo 正式 接受的参数\n self.shopName = kwargs.get('shop_name')\n self.sellerName = kwargs.get('seller_name')\n self.shopId = kwargs.get('shop_id')\n self.shopLink = kwargs.get('shop_link')\n\n self.chrome_agents = [\n \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.4; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2224.3 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 4.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36\",\n \"Mozilla/5.0 (X11; OpenBSD i386) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1944.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.3319.102 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.2309.372 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.2117.157 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1866.237 Safari/537.36\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/4E423F\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36 Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.517 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1664.3 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1664.3 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1623.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.17 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.62 Safari/537.36\",\n \"Mozilla/5.0 (X11; CrOS i686 4319.74.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.2 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1468.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1467.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1500.55 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.90 Safari/537.36\",\n \"Mozilla/5.0 (X11; NetBSD) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36\",\n \"Mozilla/5.0 (X11; CrOS i686 3912.101.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.60 Safari/537.17\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.15 (KHTML, like Gecko) Chrome/24.0.1295.0 Safari/537.15\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.14 (KHTML, like Gecko) Chrome/24.0.1292.0 Safari/537.14\"\n ]\n\n super().__init__(**kwargs)\n\n def start_requests(self):\n\n shop_search_url = 'https://' + urlparse(self.shopLink).netloc\n\n # todo 请求店铺所有商品,直接请求?\n r = requests.get(shop_search_url + '/search.htm')\n\n select = Selector(text=r.text)\n\n if 'tmall.com' in shop_search_url:\n # wid = select.css('#hd > div::attr(data-widgetid)').get()\n wid = int(select.css('#bd > div::attr(data-widgetid)').get()) + 1 # 天猫 10月更新\n self.product_list = shop_search_url + self.product_list_api.format(wid)\n\n elif 'taobao.com' in self.shopLink:\n # 权值id\n wid = select.css('[data-title=宝贝列表]::attr(data-widgetid)').get()\n\n self.product_list = shop_search_url + self.product_list_api.format(wid)\n\n json_url = self.shop_info_api + self.shopName\n\n yield scrapy.Request(url=json_url, callback=self.parse_search)\n\n # 搜索店铺信息并匹配\n def parse_search(self, response):\n\n self.result = {}\n doc = unescape(response.text)\n # json接口内容 参考文件:接口内容.json\n json_data = json.loads(doc)\n\n if json_data.get('listItem'):\n shop_info = json_data['listItem'][0]['shop']\n # 店铺地区\n self.result['shop_link'] = self.shopLink\n self.result['shop_area'] = json_data['listItem'][0]['area']\n self.result['shop_logo'] = shop_info.get('logo')\n self.result['shop_name'] = self.shopName\n self.result['seller_name'] = self.sellerName\n self.result['shop_id'] = self.shopId\n\n if shop_info.get('isMall'):\n self.result['shop_type'] = '天猫'\n else:\n self.result['shop_type'] = '淘宝'\n shop_medal = json_data['listItem'][0].get('medal')\n # 动态评价接口\n self.result['shop_ajax'] = shop_medal.get('ajaxurl')\n # 卖家id 使用正则匹配出来\n self.result['seller_id'] = re.findall(r'userid=(\\d+)', shop_medal.get('ajaxurl'))[0]\n # 好评率\n self.result['shop_favRate'] = json_data['listItem'][0].get('favRate')\n else:\n logger.warning('店铺信息解析失败!请查看scrapyd日志获取详情!')\n\n # 随机轮换 User-Agent,因为是h5接口,要用手机浏览器带cookies访问\n iphone_headers = [\n 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Mobile/15A372 MicroMessenger/6.5.16 NetType/WIFI Language/zh_CN',\n 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Mobile/15A372 wxwork/2.1.5 MicroMessenger/6.3.22',\n 'Mozilla/5.0 (iPhone 6s; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 MQQBrowser/7.7.2 Mobile/15A372 Safari/8536.25 MttCustomUA/2 QBWebViewType/1',\n 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0_1 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Mobile/15A402 MicroMessenger/6.5.16 NetType/WIFI Language/zh_CN'\n ]\n\n headers = {'user-agent': random.choice(iphone_headers)}\n\n data = '{\"sellerId\": %s}' % self.re_dt.get('sellerid')\n cookies = self.cookies\n token = self.token\n account = self.account\n # 这部分只需要更换cookies,一般能访问成功,因为只访问一次接口\n if response.meta.get('change_cookie'):\n logger.info('-----------------更换cookies-----------------')\n cookie_pool = self.con.cookies_pool(account)\n\n account = cookie_pool['account']\n token = cookie_pool['cookie_token']\n cookies = cookie_pool['cookie_dict']\n cookie_str = cookie_pool['cookie_str']\n logger.info(f'更换后的cookies的账号为:{account}')\n\n data = '{\"sellerId\": %s}' % self.result.get('seller_id')\n\n decrypt = self.sign(token=token, appkey=self.appkeys, t=str(int(time.time() * 1000)),\n data=data)\n\n url = self.shop_detail_api.format(**decrypt)\n\n yield scrapy.Request(url=url, headers=headers,\n cookies=cookies, callback=self.parse_store_item, meta={'account': account})\n\n # 进一步抓取店铺信息\n def parse_store_item(self, response):\n\n # 参考:接口2.json\n doc = json.loads(response.text)\n\n # 判断是否拿到了接口数据\n status = doc.get('ret')\n logger.info(f'json接口响应状态{status}')\n if 'SUCCESS' not in status[0]:\n yield scrapy.Request(url=self.json_url, callback=self.parse_search, dont_filter=True,\n meta={'change_cookie': True})\n\n json_data = doc.get('data')\n self.count = json_data.get('itemCount') # 商品总数\n self.result['fans_num'] = str(json_data.get('fansNum')) # 粉丝数\n self.result['item_count'] = str(self.count) # 产品数量\n self.result['new_item'] = str(json_data.get('newItem')) # 新品数\n if json_data.get('goldenSeller'):\n self.result['golden_seller'] = '金牌卖家'\n else:\n self.result['golden_seller'] = ''\n\n logger.info(f'店铺信息:{self.result}')\n\n self.reds_conn.hset('shop_info', self.shopName, json.dumps(self.result))\n if 'tmall.com' in self.product_list:\n totalPages = math.ceil(int(self.count) / 90) + 1 # 向上取整\n elif 'taobao.com' in self.product_list:\n totalPages = math.ceil(int(self.count) / 24) + 1 # 向上取整\n logger.info(f'总共需要采集的页面有:{totalPages}页')\n\n for page in range(1, totalPages + 1):\n url = self.product_list + str(page)\n # 预处理cookies\n headers = {\n 'User-Agent': random.choice(self.chrome_agents)\n }\n time.sleep(1)\n yield scrapy.Request(url=url, headers=headers, callback=self.parse_productId,\n meta={'with_cookie': True})\n\n def parse_productId(self, response):\n '''\n 解析当前商品详情页中的所有商品id\n :param response:\n :return:\n '''\n headers = {\n 'User-Agent': random.choice(self.chrome_agents)\n }\n if 'rgv587_flag' in response.text:\n yield scrapy.Request(url=response.request.url, headers=headers, callback=self.parse_productId,\n meta={'with_cookie': True, 'block': True})\n\n text = response.text.replace('\\\\\"', '')\n s = Selector(text=text)\n\n products_id_list = s.css('.J_TItems div .item::attr(data-id)').getall()\n\n if len(products_id_list) == 0:\n products_id_list = s.css('.shop-hesper-bd .item::attr(data-id)').getall()\n\n logger.info(f'当前页商品id:{products_id_list}')\n\n # 存储全部商品\n self.all_products_list.extend(products_id_list)\n\n # 根据所需元素计算sign\n def sign(self, token, appkey, t, data):\n '''\n :param token:\n :param appkey:\n :param t: str(int(time.time() * 1000))\n :param data:\n :return:\n '''\n pp = '&'.join([token, t, appkey, data]).encode()\n sign = hashlib.md5(pp).hexdigest()\n return {'sign': sign, 't': t, 'appkey': appkey, 'data': data}\n\n # 店铺爬虫结束后,数据存入redis并调用商品详情爬虫\n def close(self, spider, reason):\n try:\n # 去重存储所有商品id\n all_products_id = list(set(self.all_pids))\n logger.info(all_products_id)\n\n logger.info(f'采集到了{len(all_products_id)}条商品数据')\n lose_count = int(self.count) - len(all_products_id)\n if lose_count > 0:\n logger.warning(f'采集缺失:{lose_count},缺失百分比:{lose_count / int(self.count) * 100}%')\n\n data = json.dumps({'product_counts': len(all_products_id), 'product_id': all_products_id})\n\n # redis 存储抓取的全部商品id\n self.reds_conn.hset('products_id', self.shopName, data)\n\n # 启动详情爬虫的参数\n post_data = {'project': 'DataItem', 'spider': 'TbDetailSpiderNew', 'shop_name': self.shopName,\n 'shop_id': self.shopId}\n\n # 调用淘宝详情爬虫\n r = requests.post('http://localhost:6800/schedule.json', data=post_data, timeout=50)\n if r.status_code == 200:\n logger.info(f'传递给详情采集爬虫的参数为:{post_data}')\n logger.info(f'详情采集爬虫调用状态码:{r.status_code},响应内容:{json.loads(r.text)}')\n else:\n logger.warning(f'启用详情爬虫失败!状态码:{r.status_code}')\n except Exception as e:\n logger.warning(f'启用详情爬虫失败!错误信息{e}')\n" }, { "alpha_fraction": 0.5698432326316833, "alphanum_fraction": 0.5819115042686462, "avg_line_length": 36.546875, "blob_id": "de7aa386206f04cb21f540d371d98bb818f7dfdb", "content_id": "b2047e40469e076e33b37d1fb01948a087f98711", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8021, "license_type": "no_license", "max_line_length": 126, "num_lines": 192, "path": "/DataItem/CookiesPool/generator.py", "repo_name": "lindo-zy/TBspider", "src_encoding": "UTF-8", "text": "import json\nimport time\nimport requests\nimport random\nfrom urllib import parse\nfrom selenium.webdriver.chrome import options\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium import webdriver\nfrom scrapy.selector import Selector\nfrom CookiesPool.apiLog import Log\nfrom CookiesPool.config import *\nfrom redis_pool import RedisPool\nfrom CookiesPool.verify import Yundama\n\nlogger = Log()\n\n'''\nchromedriver 根据自己的chrome版本下载配置\n\n\n本地使用,生成cookies\n1.登陆频繁微博会出现414,无法访问,一般封禁半小时内\n2.切换海外代理登陆,新浪微博需要打码,淘宝需要验证手机号 #不推荐使用\n3.手动获取cookies,添加到redis #todo\n\n\n1.尝试登陆移动端新浪\nhttps://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=https://m.weibo.cn/\n2.移动端登陆成功->淘宝关联登陆\n\n'''\n\n\nclass CookiesGenerator:\n\n def get_cookie(self, username, password):\n\n \"\"\"\n 使用微博关联登陆淘宝,进而从m端淘宝页面获取cookie\n \"\"\"\n\n option = options.Options()\n\n option.add_argument(\"disable-infobars\") # # 去除info框\n option.add_experimental_option('excludeSwitches', ['enable-automation']) # 开发者模式,防止被识别\n option.add_argument('log-level=3')\n # option.add_argument(\"--proxy-server=http://114.239.254.76:4236\") #添加代理\n # option.add_argument('--headless') # headless模式\n # option.add_argument(\"window-size=2436, 1125\")\n # option.add_argument(\"--no-sandbox\")\n\n # executable_path = os.path.join(os.getcwd(), 'chromedriver.exe') # chromedriver路径\n\n # browser = webdriver.Chrome(executable_path=executable_path, options=option)\n browser = webdriver.Chrome(options=option)\n\n browser.implicitly_wait(20) # 隐式加载\n try:\n browser.get('https://weibo.com/')\n browser.maximize_window()\n # 等待微博登录框加载完成后输入账号密码登陆\n wb_locator = '.login_innerwrap .W_login_form[node-type=normal_form] input[name=username]'\n WebDriverWait(browser, 300, 0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR, wb_locator)))\n logger.info('当前步骤:输入账号密码!')\n browser.find_element_by_css_selector(\n '.login_innerwrap [node-type=normal_form] input[name=username]').send_keys(\n username)\n browser.find_element_by_css_selector(\n '.login_innerwrap [node-type=normal_form] input[name=password]').send_keys(\n password)\n # 增加延时\n time.sleep(3)\n\n yundama = Yundama()\n\n sel = Selector(text=browser.page_source)\n verify_img = sel.css('[action-type=btn_change_verifycode]::attr(src)').get()\n\n if not verify_img:\n browser.find_element_by_css_selector(\n '.login_innerwrap [node-type=normal_form] .W_btn_a').click()\n else:\n print('出现验证码,开始识别验证码')\n\n # 截图大法\n pic = browser.find_element_by_xpath('//*[@id=\"pl_login_form\"]/div/div[3]/div[3]/a/img')\n pic.screenshot('yzm.png') # 元素截图\n time.sleep(1)\n result = yundama.identify(file='yzm.png')\n if not result:\n print('验证码识别失败, 跳过识别')\n return\n else:\n browser.find_element_by_xpath('//*[@id=\"pl_login_form\"]/div/div[3]/div[3]/div/input').send_keys(result)\n time.sleep(1)\n browser.find_element_by_css_selector('.login_innerwrap [node-type=normal_form] .W_btn_a').click()\n\n logger.info('当前步骤:登陆淘宝!')\n # 等待微博登陆完成后转到淘宝登陆页面并点击使用微博登陆\n wb_login_locator = '.WB_feed_detail'\n WebDriverWait(browser, 300, 0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR, wb_login_locator)))\n browser.get('https://login.taobao.com')\n try:\n browser.find_element_by_css_selector('#J_Quick2Static').click()\n except Exception as e:\n # 添加错误日志\n logger.warning(f'错误信息{e}')\n\n browser.find_element_by_css_selector('.weibo-login').click()\n time.sleep(1)\n # 判断是否有微博快速登录框出现,有则点击,无则输入微博密码登陆\n if browser.find_element_by_css_selector('.logged_info .W_btn_g'):\n # tb_submit_locator = '.logged_info .W_btn_g'\n # WebDriverWait(browser, 300, 0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR, tb_submit_locator)))\n browser.find_element_by_css_selector('.logged_info .W_btn_g').click()\n elif browser.find_elements_by_css_selector('[node-type=submitStates]'):\n browser.find_element_by_css_selector('.enter_psw').send_keys(password)\n browser.find_element_by_css_selector('[node-type=submitStates]').click()\n return\n\n time.sleep(2)\n # 等待淘宝登陆完成后转入淘宝m端首页\n tb_locator = '.logo-bd'\n WebDriverWait(browser, 300, 0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR, tb_locator)))\n browser.get('https://h5.m.taobao.com')\n\n # 等待淘宝m端首页加载完成,获取cookie并存入redis\n m_tb_locator = '.header-bd'\n WebDriverWait(browser, 300, 0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR, m_tb_locator)))\n cookies = browser.get_cookies()\n\n result = self.cookie_handler(cookies)\n\n cookie_str = result[0]\n\n logger.info('成功获取到cookies!')\n\n # 存储到redis->cookies_pool\n con = RedisPool()\n con.save_cookie({\"username\": username, \"cookie\": cookie_str})\n\n browser.quit()\n\n # 传输cookies,当前工程在本地,则传输cookies到线上\n # if LOCAL:\n # url = 'http://47.56.68.237:8888/recieve_cookie'\n # headers = {\"Content-Type\": \"application/json\"}\n # data = {\n # 'data': {'cookie': cookie_str, 'username': username, \"token\": \"ce934bc118beedabd789ed5cf6a20dc7\"}}\n # try:\n # r = requests.post(url=url, headers=headers, json=data)\n #\n # logger.info(f'状态码:{r.status_code},响应内容:{json.loads(r.text)}')\n # except Exception as e:\n # logger.warning(f'cookies传输出错,{e}')\n\n except Exception as e:\n logger.warning(f'cookie获取失败: {e}')\n\n finally:\n browser.quit()\n # 下次获取cookies\n # 加入随机等待时间减少被反爬识别概率\n # todo 登录多了,会封Ip\n time.sleep(random.randint(1, 4))\n\n def cookie_handler(self, cookie_list):\n cookie_dict = {}\n cookie_ls = []\n for item in cookie_list:\n cookie_dict[item['name']] = item['value']\n temp = item['name'] + \"=\" + item['value']\n cookie_ls.append(temp)\n\n cookie_str = ';'.join(item for item in cookie_ls)\n return cookie_str, cookie_dict\n\n def run(self):\n # 从redis中取出账号和密码\n con = RedisPool()\n accounts_dict = con.get_accounts()\n\n for username, password in accounts_dict.items():\n logger.info(f'当前生成cookies账号为:{username},密码:{password}')\n self.get_cookie(username, password)\n\n\nif __name__ == '__main__':\n generator = CookiesGenerator()\n generator.run()\n" }, { "alpha_fraction": 0.5117599368095398, "alphanum_fraction": 0.5660989284515381, "avg_line_length": 25.80434799194336, "blob_id": "534af19577e504cf9200261ba6e3fe522de3ceed", "content_id": "68e46df33bc0c2527360cb83592991617d9d261c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1307, "license_type": "no_license", "max_line_length": 111, "num_lines": 46, "path": "/DataItem/DataItem/spiderConfig.py", "repo_name": "lindo-zy/TBspider", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n'''\n相关配置文件\n'''\n\n# php接口回调设置\n\n# 本地测试\n# php_api = {\n# \"http://127.0.0.1/api/screen/shop\": {\n# \"url\": \"http://127.0.0.1/api/screen/product\",\n# \"result\": \"http://127.0.0.1/api/screen/result\",\n# \"headers\": {\n# \"api-key\": \"[email protected]\",\n# \"api-token\": \"g/l+OjehOxCdfKnaC+WeHuZ4fo7rODXTIOH3ftUZtaY=\",\n# \"Content-Type\": \"application/json\"\n# }\n# }\n# }\n\n# 测试服\nSHOP_CALLBACK = r'http://127.0.0.1/api/screen/shop'\nPRODUCT_CALLBACK = r\"https://pr.test.puget.work/api/screen/product\"\nRESULT_CALLBACK = r'https://pr.test.puget.work/api/screen/result'\nAPI_KEY = '[email protected]'\nAPI_TOKEN = 'g/l+OjehOxCdfKnaC+WeHuZ4fo7rODXTIOH3ftUZtaY='\nHEADERS_CALLBACK = {\"api-key\": API_KEY,\n \"api-token\": API_TOKEN,\n \"Content-Type\": \"application/json\",\n 'user-agent': \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.14 (KHTML, like Gecko) \"\n \"Chrome/24.0.1292.0 Safari/537.14 \"}\n\n# 测试服\n# REDIS_PASSWORD = 'WpRWHOb9rinQXbwa'\n# 本地\nREDIS_PASSWORD = ''\n# Redis数据库地址\nREDIS_HOST = '127.0.0.1'\n\n# Redis端口\nREDIS_PORT = 6379\n\n# Redis密码,如无填None\nREDIS_PASSWORD = ''\nDB_NUM = 0\n" }, { "alpha_fraction": 0.6492537260055542, "alphanum_fraction": 0.6567164063453674, "avg_line_length": 6.388888835906982, "blob_id": "b794f2de2d8715a0d6631e7b11b194a837e8efce", "content_id": "6eb9f5256be111001d4dcc10b2c5c73501cf4f16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 178, "license_type": "no_license", "max_line_length": 27, "num_lines": 18, "path": "/DataItem/CookiesPool/README.md", "repo_name": "lindo-zy/TBspider", "src_encoding": "UTF-8", "text": "# CookiesPool / Cookies池\n\n\n## 基础配置 \n\n修改cookiespool/config.py\n\n\n\n### 进程开关\n\n配置信息到cookiespool/config文件修改\n\n## 运行\n\n```\npython3 run.py\n```\n\n" }, { "alpha_fraction": 0.5256490111351013, "alphanum_fraction": 0.5344677567481995, "avg_line_length": 34.62389373779297, "blob_id": "c6e18f81cbaa79f8c0625eaf45824e130645c06b", "content_id": "f3c829346c7db57a3bf60a5154986de05dc7d2c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8657, "license_type": "no_license", "max_line_length": 139, "num_lines": 226, "path": "/DataItem/DataItem/spiders/ProductSpider.py", "repo_name": "lindo-zy/TBspider", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport re\nimport datetime\nimport json\nimport scrapy\nfrom DataItem.redis_pool import RedisPool\nfrom bs4 import BeautifulSoup\nfrom DataItem.myLog import Log\nfrom scrapy.selector import Selector\nimport random\n\nlogger = Log(log_name='DetailSpider')\n\n\nclass ProductSpider(scrapy.Spider):\n name = 'ProductSpider'\n\n allowed_domains = ['*']\n # 开启scrapyhub代理 备用\n crawlera_enabled = True\n crawlera_apikey = ''\n\n # todo 自定义设置,调优\n custom_settings = {\n 'CONCURRENT_REQUESTS': 5,\n 'CONCURRENT_REQUESTS_PER_DOMAIN': 5, # 单个ip最大并发量\n 'AUTOTHROTTLE_ENABLED': False, # 限流器\n 'DOWNLOADER_MIDDLEWARES': {\n # 'DataItem.middlewares.ProxyDownloaderMiddleware': 610, #开启阿布云\n 'scrapy_crawlera.CrawleraMiddleware': 610\n }\n }\n\n def __init__(self, **kwargs):\n logger.info(f'----------------开始采集,{datetime.datetime.now()}----------------')\n\n self.reds_conn = RedisPool().redis_con()\n\n self.product_detail_api = r'https://h5api.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?data=%7B%22itemNumId%22%3A%22{0}%22%7D'\n\n # 初始化详情正则对象\n self.img_cpl = re.compile(r'.*?\"img\":\"(https://.*?\\.jpg)', re.DOTALL) # 匹配详情图\n self.img_cpl2 = re.compile(r'.*?image\":{\"itemImages\":\\[(.*?)\\].*', re.DOTALL) # 匹配详情图\n self.desc_cpl = re.compile(r'.*?descUrl\".*?\"(.*?)\"', re.DOTALL) # 匹配详情图入口url\n self.all_imgs = [] # 所有图片的详情\n\n self.job_id = kwargs.get('_job', '1') # 此爬虫的job_id\n\n # 店铺名称\n # self.shopName = kwargs.get('shop_name')\n # self.shopid = kwargs.get('shop_id')\n\n self.productIdList = kwargs.get('productId_list')\n\n self.result = {}\n\n super().__init__(**kwargs)\n\n # 开始解析\n def start_requests(self):\n\n product_list = self.productIdList\n\n n = 0\n for product_id in product_list:\n n += 1\n logger.info(f'开始采集第{n}个商品,id为:{product_id}')\n\n product_detail_api = r'https://h5api.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?data=%7B%22itemNumId%22%3A%22{}%22%7D'\n\n # 构建商品详情接口\n url = product_detail_api.format(product_id)\n # 增加cookies\n cookies_dict = self.reds_conn.hgetall('queue_cookie')\n cookies_list = list(cookies_dict.values())\n\n cookie = cookies_list[-1]\n\n unb_random = ''.join(str(random.choice(range(9))) for _ in range(13))\n\n pattern = r'unb=(\\d+)'\n temp = re.sub(pattern=pattern, repl='unb=' + unb_random, string=cookie)\n ls = temp.split(';')\n cookies = {}\n for i in ls:\n key, value = i.split('=', 1)\n cookies[key] = value\n\n yield scrapy.Request(url=url, callback=self.parse_tb, dont_filter=True, cookies=cookies,\n meta={'url': url, 'slug': product_id, 'request_tp': 'store'})\n\n # 解析淘宝网页\n def parse_tb(self, response):\n try:\n # 参考:商品详情json\n product_detail_json = json.loads(response.text)\n\n data = product_detail_json['data']\n\n slug = response.meta.get('slug') # 淘宝的商品ID\n\n # 响应失败标志\n\n status = product_detail_json['ret'][0]\n if '成功' not in status:\n logger.warning(f'{response.request.url},商品列表采集失败!响应内容:{product_detail_json.get(\"ret\")}')\n return\n\n # 商品信息\n product_info = {}\n\n # 商品名称\n product_info['product_name'] = data['item'].get('title')\n # 商品id\n product_info['product_id'] = data['item'].get('itemId')\n # 商品类别id\n product_info['product_categoryId'] = data['item'].get('categoryId')\n\n site_type = data['params']['trackParams']['BC_type'] # B为天猫C为淘宝\n # 商品源url,区分B-淘宝,C-天猫\n if site_type == 'B':\n source_url = \"https://detail.tmall.com/item.htm?id={0}\".format(slug)\n else:\n source_url = \"https://item.taobao.com/item.htm?id={0}\".format(slug)\n\n product_info['product_url'] = source_url\n\n price_info = json.loads(data['apiStack'][0]['value']) # 价格信息\n\n purchase_price = price_info['price']['price']['priceText'].split('-')[-1] # 实际价格\n\n # 销量\n sell_count = price_info.get('item').get('sellCount') if price_info.get('item', dict()).get(\n 'sellCount') else 0\n\n purchase_list_price = price_info['price'].get('extraPrices')\n\n purchase_list_price = purchase_list_price[0]['priceText'].split('-')[\n -1] if purchase_list_price else purchase_price # 市场价\n\n item = data['item'] # 商品信息\n\n skuBase = data['skuBase']\n option_values = skuBase.get('props', {})\n\n tmall_descurl = f\"https:{item['tmallDescUrl']}\" # 商品图片详情页 origin\n\n images = item['images'] # 缩略图信息\n feature_image_list = [f'https:{u}' for u in images]\n\n props = data.get('props').get('groupProps')[0].get('基本信息')\n\n # todo 重写\n opt = [{'name': i['name'], 'values': [{'name': j['name'],\n 'thumb': (f\"http:{j.get('image')}\" if not j.get('image').startswith(\n 'http') else j.get('image')) if j.get('image') else ''} for j in\n i['values']]} for i in option_values][::-1] if option_values else {}\n\n product_info['product_price'] = purchase_price # 淘宝价\n product_info['product_sale_price'] = purchase_list_price # 定价\n\n product_info['product_props'] = props # 商品属性集合\n\n product_info['product_options'] = opt # 商品选项集合\n product_info['product_sell_count'] = sell_count # 商品销量\n\n product_info['product_images'] = feature_image_list # 图片集合\n\n sku_price_info = price_info['skuCore']['sku2info'] # sku价格\n\n product_info['product_sku_prices'] = sku_price_info\n\n # 抓取页面图片详情\n yield scrapy.Request(tmall_descurl,\n callback=self.parse_detail,\n meta={'product_info': product_info, 'slug': slug},\n dont_filter=True)\n except Exception as e:\n logger.warning(f'错误信息{e}')\n\n # 解析详情接口,判断是否有图片接口存在,如果存在则进一步抓取图片\n def parse_detail(self, response):\n\n product_info = response.meta.get('product_info')\n\n product_id = response.meta.get('slug')\n # 详情html\n product_describe = response.text\n\n product_info['product_describe'] = product_describe\n\n # 详情接口\n descurl = 'https://h5api.m.taobao.com/h5/mtop.taobao.detail.getdesc/6.0/?jsv=2.4.11&data={\"id\":\"%s\",\"type\":\"1\"}' % (\n product_id)\n\n yield scrapy.Request(url=descurl, callback=self.parse_img_new,\n meta={'product_info': product_info},\n dont_filter=True)\n\n # 获取图片\n def parse_img_new(self, response):\n product_info = response.meta.get('product_info')\n text = json.loads(response.text).get('data').get('pcDescContent')\n selector = Selector(text=text)\n image_urls = selector.css('img::attr(src)').getall()\n\n if not image_urls:\n soup = BeautifulSoup(text, 'lxml')\n if soup.find_all('img'):\n for link in soup.find_all('img'):\n image_urls.append(link.get(\"src\"))\n else:\n logger.warning(f'{response.request.url}:没有图片!')\n\n image_urls = [f'https:{img}' for img in image_urls]\n\n product_info['product_images_urls'] = image_urls\n\n # 参考:商品详情2.json\n data = json.dumps(product_info)\n\n # 存储到数据库\n self.reds_conn.hset('product_info', product_info['product_id'], data)\n\n def close(self, spider, reason):\n logger.info(f'----------------全部商品采集完成,{datetime.datetime.now()}----------------')\n" }, { "alpha_fraction": 0.4673663377761841, "alphanum_fraction": 0.47950148582458496, "avg_line_length": 38.089744567871094, "blob_id": "582c121554880debb246f0d644598a50dc416a03", "content_id": "defb21df619ca765863e41664d3f37de9ae325ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6614, "license_type": "no_license", "max_line_length": 113, "num_lines": 156, "path": "/DataItem/CookiesPool/api.py", "repo_name": "lindo-zy/TBspider", "src_encoding": "UTF-8", "text": "import json\nimport requests\nfrom flask import Flask, request\nfrom scrapy import Selector\nfrom CookiesPool.apiLog import Log\nfrom redis_pool import RedisPool\n\n__all__ = ['app']\n\napp = Flask(__name__)\n\nlogger = Log()\n\n# 测试服\nTOKEN = 'ce934bc118beedabd789ed5cf6a20dc7'\n\n\[email protected]('/request_crawler', methods=[\"POST\"])\ndef request_crawler():\n if request.method == 'POST':\n params = request.json\n logger.info(f'接收到参数:{params}')\n data = params['data']\n con = RedisPool()\n # 执行请求scrapy爬虫\n if 'shop_link' in data.keys():\n try:\n url = data['shop_link']\n print('需要采集的店铺:', url)\n post_data = {}\n\n s_id = data['id']\n # todo 这个是什么排序?\n sort_type = data.get('sort_type', '_sale')\n\n post_data['project'] = 'DataItem'\n # 需要启动的爬虫\n post_data['spider'] = 'NewTbShopSpider'\n\n # 店铺在shop_fetch_tasks中的表\n post_data['s_id'] = s_id\n post_data['sort_type'] = sort_type\n r = requests.post('http://localhost:6800/schedule.json', data=post_data, timeout=50)\n logger.info('scrapyd状态:', r.text)\n # 爬虫的jobid\n jobid = r.json()['jobid']\n logger.info('当前任务ID:', jobid)\n con.hset('all_shop', s_id, json.dumps(data, ensure_ascii=False))\n\n con.hset('store', jobid, json.dumps(data, ensure_ascii=False))\n\n logger.info(f'采集爬虫启动成功!详情:{r.text}')\n logger.info({'code': 200, 'msg': '成功接收任务!'})\n return json.dumps({'code': 200, 'msg': '成功接收任务!'})\n except Exception as e:\n logger.info({'code': 500, 'msg': f'错误信息:{e}'})\n return json.dumps({'code': 500, 'msg': f'错误信息:{e}'})\n\n # 获取店铺信息\n elif 'url' in data.keys():\n try:\n url = data['url']\n print('需要采集的店铺:', url)\n r = requests.get(url)\n s = Selector(text=r.text)\n # 店铺id\n shopId = s.css('#LineZing::attr(shopid)').get()\n\n shopName = ''\n sellerName = ''\n\n # 获取淘宝店铺基本信息\n if 'taobao.com' in url:\n if s.css('.hd-shop-name a::text').get():\n shopName = s.css('.hd-shop-name a::text').get()\n elif s.css('.first-block .shop-name span::text').get():\n shopName = s.css('.first-block .shop-name span::text').get()\n else:\n shopName = ''\n if s.css('.tb-box-half.tb-seller-info label::text').get():\n sellerName = s.css('.tb-box-half.tb-seller-info label::text').get().strip()\n elif s.css('.seller-name::text').get():\n sellerName = s.css('.seller-name::text').get().strip('掌柜:')\n elif s.css('.shop-more-info p.info-item:nth-child(2)::text').get():\n sellerName = s.css('.shop-more-info p.info-item:nth-child(2)::text').get().strip()\n else:\n sellerName = ''\n\n # 获取天猫店铺信息\n elif 'tmall.com' in url:\n if s.css('.hd-shop-name a::text').get():\n shopName = s.css('.hd-shop-name a::text').get()\n else:\n shopName = s.css('.slogo-shopname strong::text').get()\n # 天猫默认 卖家和商铺同名\n sellerName = shopName\n\n # if s.css('.tb-box-half.tb-seller-info label::text').get():\n # sellerName = s.css('.tb-box-half.tb-seller-info label::text').get().strip()\n # else:\n # sellerName = s.css('.shopkeeper div a::text').get()\n\n # 商铺基本信息\n shopInfo = {'shopname': shopName, 'shopid': shopId, 'sellername': sellerName}\n print(f'采集店铺基本信息:{shopInfo}')\n\n con.hset('ShopInfoQuery', json.dumps(shopInfo, ensure_ascii=False), url)\n\n logger.info({'code': 200, 'msg': '店铺基本信息获取成功!', 'shop_info': shopInfo})\n return json.dumps({'code': 200, 'msg': '店铺基本信息获取成功!', 'shop_info': shopInfo}, ensure_ascii=False)\n except Exception as e:\n logger.info({'code': 500, 'msg': f'错误信息:{e}'})\n return json.dumps({'code': 500, 'msg': f'错误信息:{e}'})\n else:\n logger.info({'code': 500, 'msg': '任务接收失败,请检查参数!'})\n return json.dumps({'code': 500, 'msg': '任务接收失败,请检查参数!'})\n\n\[email protected]('/recieve_cookie', methods=[\"POST\"])\ndef recieve_cookie():\n if request.method == 'POST':\n try:\n params = json.loads(request.data)\n logger.info({'code': 200, 'msg': 'cookies接收成功!'})\n data = params['data']\n cookie = data['cookie']\n username = data['username']\n con = RedisPool()\n con.save_cookie(username, json.dumps({'cookie': cookie, 'counter': 3}))\n\n return json.dumps({'code': 200, 'msg': 'cookies接收成功!'})\n except Exception as e:\n logger.info({'code': 500, 'msg': f'错误信息{e}'})\n return json.dumps({'code': 500, 'msg': f'错误信息{e}'})\n\n\[email protected]_request\ndef before_request():\n if request.method == 'POST':\n try:\n jdata = json.loads(request.data)['data']\n if jdata.get('token') and TOKEN == jdata.get('token'):\n logger.info({'code': 200, 'msg': 'token 校验成功!'})\n else:\n logger.info({'code': 500, 'msg': 'token校验失败!'})\n return json.dumps({'code': 500, 'msg': 'token校验失败!'})\n except Exception as e:\n logger.info({'code': 500, 'msg': f'错误信息{e}'})\n return json.dumps({'code': 500, 'msg': f'错误信息{e}'})\n elif request.method == 'GET':\n logger.info('Flask工程开启成功!')\n return 'Flask工程开启成功!'\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=8888)\n" }, { "alpha_fraction": 0.566919207572937, "alphanum_fraction": 0.6439393758773804, "avg_line_length": 15.5, "blob_id": "033cd7e6affd980c19a26955a3a29d1a39aaef57", "content_id": "fe3878b7f58dadeb7032be297f11d696e3f4ce46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 966, "license_type": "no_license", "max_line_length": 66, "num_lines": 48, "path": "/DataItem/CookiesPool/config.py", "repo_name": "lindo-zy/TBspider", "src_encoding": "UTF-8", "text": "# Redis数据库地址\nREDIS_HOST = '127.0.0.1'\n\n# Redis端口\nREDIS_PORT = 6379\n\n# Redis密码,如无填None\nREDIS_PASSWORD = ''\n\nDB_NUM = 0\n\n# 配置信息,无需修改\n# REDIS_DOMAIN = '*'\n# REDIS_NAME = '*'\n\n\n# 产生器和验证器循环周期\nCYCLE = 2400 # 秒\n\n# API地址和端口\nAPI_HOST = '127.0.0.1'\nAPI_PORT = 8888\n\n# 进程开关\n# 产生器,模拟登录添加Cookies\nGENERATOR_PROCESS = True\n\n# API接口服务\nAPI_PROCESS = True\n\n# 账号\nACCOUNTS = [{\"username\": '15625006690', \"password\": \"tmp11235\"},\n {\"username\": '18922373490', \"password\": \"tmp11235\"},\n {\"username\": '18922412249', \"password\": \"tmp11235\"}]\n\n# 区别本地和线上\nLOCAL = False\n\n# 云打码相关配置到yundama.com申请注册\nYUNDAMA_USERNAME = 'jianbai'\nYUNDAMA_PASSWORD = 'tmp11235'\nYUNDAMA_APP_ID = 1\nYUNDAMA_APP_KEY = '22cc5376925e9387a23cf797cb9ba745'\n\nYUNDAMA_API_URL = 'http://api.yundama.com/api.php'\n\n# 云打码最大尝试次数\nYUNDAMA_MAX_RETRY = 20\n" }, { "alpha_fraction": 0.5791420340538025, "alphanum_fraction": 0.5791420340538025, "avg_line_length": 26.59183692932129, "blob_id": "b9256543cda3f5d316a2c6f87490689a8abf110b", "content_id": "e52f1a4dfdd0564f47b996ee9fc966dc32f02558", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1480, "license_type": "no_license", "max_line_length": 72, "num_lines": 49, "path": "/DataItem/CookiesPool/scheduler.py", "repo_name": "lindo-zy/TBspider", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom multiprocessing import Process\nfrom CookiesPool.api import app\nfrom CookiesPool.generator import *\nfrom redis_pool import RedisPool\nfrom CookiesPool.config import *\n\n\n# 调度器\nclass Scheduler(object):\n @staticmethod\n def generate_cookie(cycle=CYCLE):\n while True:\n\n try:\n generator = CookiesGenerator()\n generator.run()\n print(f'cookies生成结束!时间:{datetime.now()}')\n # 每一个cycle生成一轮cookies\n time.sleep(cycle)\n except Exception as e:\n print(f'cookies生成器发生错误,错误信息:{e}')\n\n @staticmethod\n def api():\n app.run(host=API_HOST, port=API_PORT)\n\n def run(self):\n # 导入账号\n con = RedisPool()\n con.save_account(ACCOUNTS)\n\n # 开启生成器\n if GENERATOR_PROCESS:\n print(f'开启cookies生成器!')\n generate_process = Process(target=Scheduler.generate_cookie)\n generate_process.start()\n\n # # 开启验证\n # if VALID_PROCESS:\n # logger.info(f'开启cookies验证!')\n # valid_process = Process(target=Scheduler.valid_cookie)\n # valid_process.start()\n\n # 开启flask工程\n if API_PROCESS:\n print(f'开启flask工程成功!')\n api_process = Process(target=Scheduler.api)\n api_process.start()\n" }, { "alpha_fraction": 0.5165562629699707, "alphanum_fraction": 0.7086092829704285, "avg_line_length": 14.100000381469727, "blob_id": "8b3d9457a31a3f82dde0227499e896f7cceaf2d8", "content_id": "707d5b4a6de8a4e3a26075d22291e1e789f180bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 151, "license_type": "no_license", "max_line_length": 22, "num_lines": 10, "path": "/requirements.txt", "repo_name": "lindo-zy/TBspider", "src_encoding": "UTF-8", "text": "setuptools==40.8.0\nscrapy_crawlera==1.6.0\nrequests==2.21.0\nScrapy==1.6.0\nFlask==1.0.2\nredis==3.3.4\nselenium==3.141.0\nbs4==4.8.0\nscrapyd\nscrapyd-client\n" }, { "alpha_fraction": 0.7077363729476929, "alphanum_fraction": 0.7077363729476929, "avg_line_length": 22.066667556762695, "blob_id": "56a3780f2fe59e84c9b3b4c78d4422441d037720", "content_id": "30426cd3b35d6efb413ec085f71ccfe9af64f975", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 425, "license_type": "no_license", "max_line_length": 73, "num_lines": 15, "path": "/DataItem/main.py", "repo_name": "lindo-zy/TBspider", "src_encoding": "UTF-8", "text": "\nfrom scrapy.cmdline import execute\nimport os\nimport sys\n\nsys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__))))\n\n\"\"\"\n此文件为主调试入口,flask接口文件是 /api/wsgi.py\n不建议使用此文件进行调试,需要手动在爬虫中配参数\n\n\"\"\"\n\n# execute(['scrapy', 'crawl', 'NewTbShopSpider'])\n# execute(['scrapy', 'crawl', 'TbDetailSpiderNew'])\nexecute(['scrapy', 'crawl', 'TestSpider'])\n\n\n" }, { "alpha_fraction": 0.4993671476840973, "alphanum_fraction": 0.5853285789489746, "avg_line_length": 48.63874435424805, "blob_id": "f843272c07e25a239d06f8baf39050ed6de828aa", "content_id": "2672ce3a3f1ccc3dcce9420cc873ec66391d2eb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20090, "license_type": "no_license", "max_line_length": 259, "num_lines": 382, "path": "/DataItem/DataItem/spiders/TestSpider.py", "repo_name": "lindo-zy/TBspider", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport re\nimport time\nimport hashlib\nimport json\nfrom html import unescape\nimport requests\nimport scrapy\nfrom scrapy import signals\nfrom scrapy.selector import Selector\nfrom DataItem.myLog import Log\nfrom datetime import datetime\nimport random\nfrom urllib.parse import urlparse\nimport math\nfrom redis_pool import RedisPool\n\nlogger = Log(log_name='TBSpider')\n\n\nclass TestSpider(scrapy.Spider):\n name = 'TestSpider'\n allowed_domains = ['taobao.com', 'tmall.com']\n\n custom_settings = {\n # 'CRAWLERA_ENABLED': False\n 'CONCURRENT_REQUESTS': 1,\n 'CONCURRENT_REQUESTS_PER_DOMAIN': 1,\n 'DOWNLOAD_DELAY': 1,\n 'REDIRECT_ENABLED': False,\n 'DOWNLOADER_MIDDLEWARES': {\n # 'DataItem.middlewares.ProxyDownloaderMiddleware': 610,\n 'DataItem.middlewares.CookiesPoolMiddleware': 610,\n # 'scrapy_crawlera.CrawleraMiddleware': 610\n }\n\n }\n\n def __init__(self, **kwargs):\n\n logger.info(f'----------------开始采集,{datetime.now()}----------------')\n\n # 初始化redis\n self.con = RedisPool()\n\n # 初始化请求类别, 用于区别代理\n self.request_tp = ('store', 'detail')\n\n # 获取店铺所有商品id,价格,名称\n self.store_list = '/i/asynSearch.htm?mid=w-{0}-0&wid={0}&pageNo='\n\n self.baseurl = 'http://shop.m.taobao.com/shop/shopsearch/search_page_json.do?sort=default&type=all&q='\n\n self.store_detail = ('http://h5api.m.taobao.com/h5/mtop.taobao.geb.shopinfo.queryshopinfo/2.0/?jsv=2.4.2'\n '&appKey={appkey}&t={t}&sign={sign}&api=mtop.taobao.geb.shopinfo.queryshopinfo&v=2.0'\n '&type=originaljson&timeout=3000&AntiCreep=true&dataType=json&H5Request=true&data={data}')\n\n self.chrome_agents = [\n \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.4; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2224.3 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 4.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36\",\n \"Mozilla/5.0 (X11; OpenBSD i386) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1944.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.3319.102 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.2309.372 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.2117.157 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1866.237 Safari/537.36\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/4E423F\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36 Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.517 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1664.3 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1664.3 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1623.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.17 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.62 Safari/537.36\",\n \"Mozilla/5.0 (X11; CrOS i686 4319.74.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.2 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1468.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1467.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1500.55 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.90 Safari/537.36\",\n \"Mozilla/5.0 (X11; NetBSD) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36\",\n \"Mozilla/5.0 (X11; CrOS i686 3912.101.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.60 Safari/537.17\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.15 (KHTML, like Gecko) Chrome/24.0.1295.0 Safari/537.15\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.14 (KHTML, like Gecko) Chrome/24.0.1292.0 Safari/537.14\"\n ]\n\n # 计算淘宝sign的appkeys\n self.appkeys = '12574478'\n\n # 存储全部商品id\n self.all_pids = []\n\n # scrapyd爬虫的jobid\n self.job_id = kwargs.get('_job', '1')\n\n # 设置all_shop 的key,s_id是店铺在数据库中的id\n self.s_id = kwargs.get('s_id', '1')\n\n # 备忘录,记录被封禁url的处理\n self.block_record = []\n\n self.title = ''\n self.seller_name = ''\n self.shop_id = 0\n logger.info(f'接收到的参数:{kwargs}')\n\n # cookie池\n self.cookie_pool = self.con.cookies_pool()\n self.count = 0\n self.account = self.cookie_pool['account']\n self.token = self.cookie_pool['cookie_token']\n self.cookies = self.cookie_pool['cookie_dict']\n logger.info(f'当前使用的cookies的账号为:{self.account}')\n\n # 失败url链接\n self.fail_urls = []\n super().__init__(**kwargs)\n\n\n\n def start_requests(self):\n\n # resp = self.con.hget('all_shop', self.s_id)\n #\n # if resp:\n # # 从redis取出的数据\n # data = json.loads(resp)\n # else:\n # logger.warning(f'redis数据库表:_all_shop出现异常,参数为:{self.s_id}')\n # return\n\n # 测试数据\n\n data = {\n \"id\": 1,\n \"shop_id\": \"59002150\", # 店铺id\n \"title\": \"哈果超人 haco实用轻\", # 店铺名称\n \"name\": \"behsu网购\", # 掌柜名称\n \"platform_id\": 1, # 产品库定义的平台ID,淘宝为3,天猫为4\n \"shop_link\": \"https://haco.taobao.com/index.htm?spm=a1z10.3-c-s.w5002-14453794708.2.5ae258eaRYkhrS\",\n\n # 'url': 'https://haco.taobao.com/index.htm?spm=a1z10.3-c-s.w5002-14453794708.2.5ae258eaRYkhrS',\n # \"callback\": \"https://pr.test.puget.work/api/screen/shop\", # 发送采集结果的回调地址\n \"token\": \"ce934bc118beedabd789ed5cf6a20dc7\" # 接口请求认证\n }\n\n self.title = data.get('title')\n self.seller_name = data.get('name')\n self.shop_id = data.get('shop_id')\n\n shop_link = data.get('shop_link')\n\n shop_search_url = 'https://' + urlparse(shop_link).netloc\n\n # 请求店铺所有商品\n r = requests.get(shop_search_url + '/search.htm')\n sel = Selector(text=r.text)\n\n # 获取权值id\n if 'tmall.com' in shop_search_url:\n # wid = sel.css('[data-title=搜索列表]::attr(data-widgetid)').get()\n wid = int(sel.css('#bd > div::attr(data-widgetid)').get()) + 1 # 天猫 10月更新\n # wid = sel.css('#hd > div::attr(data-widgetid)').get()\n # '//*[@id=\"bd\"]//*[@class=\"J_TModule\"]/@data-widgetid'\n self.shop_search_list = shop_search_url + self.store_list.format(str(wid))\n\n elif 'taobao.com' in shop_link:\n # 权值id\n wid = sel.css('[data-title=宝贝列表]::attr(data-widgetid)').get()\n # 获取全部商品id的接口\n # 'https://guchun.tmall.com/i/asynSearch.htm?mid=w-18297719823-0&wid=18297719823&pageNo='\n self.shop_search_list = shop_search_url + self.store_list.format(wid)\n else:\n logger.warning('店铺信息解析失败!请查看scrapyd日志获取详情!')\n return\n\n self.con.hset('widget_id', self.title, wid)\n\n # json接口 免登陆\n # http://shop.m.taobao.com/shop/shopsearch/search_page_json.do?sort=default&type=all&q=Simple%E9%9F%A9%E5%9B%BD%E5%A5%B3%E8%A3%85\n self.json_url = self.baseurl + self.title\n\n yield scrapy.Request(url=self.json_url, callback=self.parse_search)\n\n # 搜索店铺信息并匹配\n def parse_search(self, response):\n\n self.re_dt = {}\n shopid = self.shop_id\n sid = self.s_id\n\n doc = unescape(response.text)\n # json接口内容 参考文件:接口1.json\n jd_data = json.loads(doc)\n\n if jd_data.get('listItem'):\n for s in jd_data.get('listItem'):\n try:\n if str(shopid) in str(s):\n self.re_dt['sign'] = str(sid) # sign 产品库id\n self.re_dt['shopid'] = str(s.get('shop').get('id')) # 淘宝shopid\n self.re_dt['is_mall'] = s.get('shop').get('isMall') # 是否天猫\n self.re_dt['total_sold'] = str(s.get('shop').get('totalSold')) # 销量\n self.re_dt['level'] = ''.join(re.findall('\\d-\\d', str(s.get('icon')))) # 店铺等级\n self.re_dt['sellerid'] = ''.join(re.findall('userid=(\\d+)', str(s.get('medal')))) # 卖家id\n self.re_dt['goods'] = s.get('favRate') # 好评率\n break\n except Exception as e:\n logger.warning(f'发生错误的函数:parse_search(),错误信息:{e}')\n continue\n\n # 随机轮换 User-Agent,因为是h5接口,要用手机浏览器带cookies访问\n iphone_headers = [\n 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Mobile/15A372 MicroMessenger/6.5.16 NetType/WIFI Language/zh_CN',\n 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Mobile/15A372 wxwork/2.1.5 MicroMessenger/6.3.22',\n 'Mozilla/5.0 (iPhone 6s; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 MQQBrowser/7.7.2 Mobile/15A372 Safari/8536.25 MttCustomUA/2 QBWebViewType/1',\n 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0_1 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Mobile/15A402 MicroMessenger/6.5.16 NetType/WIFI Language/zh_CN'\n ]\n\n headers = {'user-agent': random.choice(iphone_headers)}\n\n data = '{\"sellerId\": %s}' % self.re_dt.get('sellerid')\n cookies = self.cookies\n token = self.token\n account = self.account\n\n # 这部分只需要更换cookies,一般能访问成功,因为只访问一次接口\n if response.meta.get('change_cookie'):\n logger.info('-----------------更换cookies-----------------')\n cookie_pool = self.con.cookies_pool(account)\n if cookie_pool is None:\n return self.close(TestSpider, 'cookie池为空!')\n account = cookie_pool['account']\n token = cookie_pool['cookie_token']\n cookies = cookie_pool['cookie_dict']\n cookie_str = cookie_pool['cookie_str']\n logger.info(f'更换后的cookies的账号为:{account}')\n\n # 解码\n st = self.sign(token=token, appkey=self.appkeys, t=str(int(time.time() * 1000)), data=data)\n\n # 实时接口\n '''\n http://h5api.m.taobao.com/h5/mtop.taobao.geb.shopinfo.queryshopinfo/2.0/?jsv=2.4.2\n &appKey=12574478&t=1569315579952&sign=88d9947b4728cc649bc50f3cb66ef2c6&\n api=mtop.taobao.geb.shopinfo.queryshopinfo&v=2.0&type=originaljson&timeout=3000&\n AntiCreep=true&dataType=json&H5Request=true&data={\"sellerId\": 3790578263}\n '''\n url = self.store_detail.format(**st)\n\n yield scrapy.Request(url=url, headers=headers, cookies=cookies,\n callback=self.parse_store_item,\n meta={'account': account})\n\n # 进一步抓取店铺信息\n def parse_store_item(self, response):\n re_data = self.re_dt\n\n # 参考:接口2.json\n doc = json.loads(response.text)\n # 接口访问状态\n status = doc.get('ret')\n\n logger.info(f'json接口响应状态{status}')\n if 'SUCCESS' not in status[0]:\n logger.info('处理淘宝封禁!')\n yield scrapy.Request(url=self.json_url, callback=self.parse_search, dont_filter=True,\n meta={'change_cookie': True})\n else:\n # 存储动态json接口内容\n self.con.hset('item_json', self.title, response.text)\n tdt = doc.get('data')\n self.count = tdt.get('itemCount') # 商品总数\n re_data['shopname'] = tdt.get('shopName') # 店铺名\n re_data['fans_num'] = str(tdt.get('fansNum')) # 粉丝数\n re_data['item_count'] = str(self.count) # 产品数量\n re_data['new_item'] = str(tdt.get('newItem')) # 新品数\n re_data['golden_seller'] = tdt.get('goldenSeller') # 金牌卖家\n logger.info(f'店铺信息:{re_data}')\n\n # url = r'https://shop142840423.taobao.com/i/asynSearch.htm?mid=w-13377183093-0&wid=13377183093&pageNo=1'\n\n # 商品详情的第一页\n # 天猫用不上这个详情页,直接计算出页数\n # 淘宝暂时直接计算出页数\n\n if 'tmall.com' in self.shop_search_list:\n # 通过计算得出页数\n totalPages = math.ceil(int(self.count) / 90) + 1 # 向上取整\n elif 'taobao.com' in self.shop_search_list:\n # s = Selector(text=html)\n # # count = int(s.xpath('//*[@id=\"shop-search-list\"]/div/div[2]/span/text()').extract_first())\n # # if count is not None and count > item_count:\n # # item_count = count\n # 通过计算得出页数\n totalPages = math.ceil(int(self.count) / 24) + 1 # 向上取整\n\n logger.info(f'总共需要采集的页面有:{totalPages}页')\n\n for page in range(1, totalPages + 1):\n url = self.shop_search_list + str(page)\n # 预处理cookies\n headers = {\n 'User-Agent': random.choice(self.chrome_agents)\n }\n time.sleep(1)\n yield scrapy.Request(url=url, headers=headers, callback=self.parse_productId,\n meta={'with_cookie': True})\n\n\n def parse_productId(self, response):\n '''\n 解析当前商品详情页中的所有商品id\n :param response:\n :return:\n '''\n headers = {\n 'User-Agent': random.choice(self.chrome_agents)\n }\n if 'rgv587_flag' in response.text:\n yield scrapy.Request(url=response.request.url, headers=headers, callback=self.parse_productId,\n meta={'with_cookie': True, 'block': True})\n\n text = response.text.replace('\\\\\"', '')\n s = Selector(text=text)\n firstPagePids = s.css('.J_TItems div .item::attr(data-id)').getall()\n if len(firstPagePids) == 0:\n firstPagePids = s.css('.shop-hesper-bd .item::attr(data-id)').getall()\n logger.info(f'{response.request.url},商品id:{firstPagePids}')\n pids = firstPagePids\n\n # 存储全部商品\n # todo 增加持续化存储\n self.all_pids.extend(pids)\n\n # 根据所需元素计算sign\n def sign(self, token, appkey, t, data):\n '''\n :param token:\n :param appkey:\n :param t: str(int(time.time() * 1000))\n :param data:\n :return:\n '''\n pp = '&'.join([token, t, appkey, data]).encode()\n sign = hashlib.md5(pp).hexdigest()\n return {'sign': sign, 't': t, 'appkey': appkey, 'data': data}\n\n # 店铺爬虫结束后,数据存入redis并调用商品详情爬虫\n def close(self, spider, reason):\n # 去重存储所有商品id\n all_products_id = list(set(self.all_pids))\n logger.info(all_products_id)\n\n logger.info(f'采集到了{len(all_products_id)}条商品数据')\n lose_count = int(self.count) - len(all_products_id)\n if lose_count > 0:\n logger.warning(f'采集缺失:{lose_count},缺失百分比:{lose_count / int(self.count) * 100}%')\n" }, { "alpha_fraction": 0.6181393265724182, "alphanum_fraction": 0.6243674755096436, "avg_line_length": 32.80263137817383, "blob_id": "8ef18760e2c1ab122966393e209969a1bb63f18c", "content_id": "c6396a51ee64d2f44baf06ec5857b5087d660ef8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2703, "license_type": "no_license", "max_line_length": 115, "num_lines": 76, "path": "/DataItem/DataItem/middlewares.py", "repo_name": "lindo-zy/TBspider", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Define here the models for your spider middleware\n#\n# See documentation in:\n# https://doc.scrapy.org/en/latest/topics/spider-middleware.html\n\nimport base64\nimport random\nimport re\nimport requests\nfrom .settings import PROXY_USER, PROXY_PASS\nfrom scrapy_crawlera import CrawleraMiddleware\nfrom redis_pool import RedisPool\n\n\n# 阿布云代理\nclass ProxyDownloaderMiddleware(CrawleraMiddleware):\n # 代理服务器\n proxyServer = \"http://http-dyn.abuyun.com:9020\"\n\n # 生成加密后的代理密码\n proxyAuth = \"Basic \" + base64.urlsafe_b64encode(bytes((PROXY_USER + \":\" + PROXY_PASS), \"ascii\")).decode(\"utf8\")\n\n def process_request(self, request, spider):\n if request.meta.get('request_tp') == 'store':\n request.meta['proxy'] = self.proxyServer\n request.headers['Proxy-Authorization'] = self.proxyAuth\n elif request.meta.get('request_tp') == 'detail':\n super().process_request(request, spider)\n\n def process_response(self, request, response, spider):\n if response.headers.__contains__('cache-control') and request.meta.get('request_tp') == 'store':\n return request\n return response\n\n\nclass CookiesPoolMiddleware(CrawleraMiddleware):\n\n def get_cookies(self, account=''):\n con = RedisPool()\n cookies_pool = con.cookies_pool(account)\n if cookies_pool is None:\n print('cookies池为空!')\n return None\n self.account = cookies_pool['account']\n token = cookies_pool['cookie_token']\n # cookie_dict = cookies_pool['cookie_dict']\n cookie_str = cookies_pool['cookie_str']\n\n # 预处理增加cookie可用度\n unb_random = ''.join(str(random.choice(range(9))) for _ in range(13))\n\n pattern = r'unb=(\\d+)'\n cookie_unb = re.sub(pattern=pattern, repl='unb=' + unb_random, string=cookie_str)\n cookie_dict = dict([tuple(x.split('=', 1)) for x in cookie_unb.split(';')])\n print(f'当前账号:{self.account}')\n\n return cookie_dict\n\n # 处理request请求\n def process_request(self, request, spider):\n if request.meta.get('with_cookie'):\n if request.meta.get('block'):\n print('中间件处理淘宝封禁!')\n request.cookies = self.get_cookies(self.account)\n else:\n request.cookies = self.get_cookies()\n return None\n\n # 处理响应\n # def process_response(self, request, response, spider):\n # if request.meta.get('with_cookie') and request.meta.get('block'):\n # print('使用中间件,处理淘宝封禁!')\n # return request\n # return response\n" } ]
16
jasondzy/Python
https://github.com/jasondzy/Python
d0a0ffad8aaac1f75d9e7c5ecd5cc9c33bd712ea
9fe9cf23f7defa3581e7bcfe4cf8ec6a830b6cd7
2de1aaa4d9bde03e21601bfeddf7e85863b0d54a
refs/heads/master
2021-01-01T18:46:00.739387
2018-02-11T14:59:26
2018-02-11T14:59:26
98,430,631
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5054945349693298, "alphanum_fraction": 0.5164835453033447, "avg_line_length": 5.92307710647583, "blob_id": "512262367cd150e6a2aa7c9bfdcd24968e4bedba", "content_id": "7cd4e9a63bee409606ec0c104b041f6d5ebc738d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 91, "license_type": "no_license", "max_line_length": 37, "num_lines": 13, "path": "/Python/plus/C_lib/test.c", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\n#include <stdio.h>\n\nint Loop()\n{\n\tprintf(\"---This is a C library---\");\n\n\twhile(1);\n\n\n\n\n\n}\n" }, { "alpha_fraction": 0.7186400890350342, "alphanum_fraction": 0.7291910648345947, "avg_line_length": 38.71428680419922, "blob_id": "a33c7625b7b9630fed6b7475d12967365ff8b914", "content_id": "96868b870dd22b2202da7c85977bd89e9f1dd57f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1391, "license_type": "no_license", "max_line_length": 103, "num_lines": 21, "path": "/Python/plus/Process/pool.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "from multiprocessing import Pool\r\nimport time, os, random\r\n\r\n\r\ndef long_time_task(name): #这里创建了子进程需要运行的函数\r\n\tprint('Run task %s (%s)..'%(name,os.getpid()))\r\n\tstart = time.time()\r\n\ttime.sleep(random.random()*3)\r\n\tend = time.time()\r\n\tprint('task %s runs %0.2f seconds'%(name, (end-start)))\r\n\r\nif __name__ == '__main__':\r\n\tprint('Parent Process %s'%os.getpid())\r\n\tp = Pool(4) #使用进程池创建了4个进程,也就是该进程池中只有4个进程在运行\r\n\tfor i in range(5):#这里调用for循环,往Pool中存放5次的任务,如下的apply_async函数中的args是向函数传递的参数,这是元组类型,当只有一个参数的时候需要在最后添加一个,\r\n\t\tp.apply_async(long_time_task, args=(i,)) #往进程池中放入需要运行的函数,由于进程池中只有四个进程,而这里放入了5个任务,所以必会有一个任务无法立刻得到运行\r\n\tprint('waiting for all subprocess done...') #此处是主进程运行的打印\r\n\r\n\tp.close() # 在join前边需要调用close函数,表明不会再有任务往进程池中存放了\r\n\tp.join() #调用了join函数,表明主进程会在此处block,等待所有的子进程运行结束后才会往下运行,这里用来作为主进程和子进程的同步\r\n\tprint('all subprocess done...')#运行到这里表明所有的子进程和主进程都运行完毕了" }, { "alpha_fraction": 0.5430916547775269, "alphanum_fraction": 0.5718194246292114, "avg_line_length": 19.22222137451172, "blob_id": "797de78479865e12a6d800be515b6798524c9776", "content_id": "9fdd032e1f1b8d5f527849160ade7fa75a9fa80b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 731, "license_type": "no_license", "max_line_length": 65, "num_lines": 36, "path": "/Python/plus/net/web/web_dynamic/web_framework.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\n\n# define a functon , this function is standard for wsgi interface\ndef application(environ, start_response):\n\n header= ''''''\n\n urls = [\n ('./index.html', handle_index),\n ('./index11.html', handle_index11)\n\n ]\n \n start_response('HTTP/1.1 200 ok',header)\n\n path = environ.get('PATH', '/')\n\n for name, handler in urls:\n if name == path:\n return handler()\n\n start_response('HTTP/1.1 404 not found',header)\n return '404 not found'\n\ndef handle_index():\n\n fp = open('./index.html', 'r')\n file_data = fp.read()\n fp.close()\n\n return file_data\n\ndef handle_index11():\n fp = open('./index11.html', 'r')\n file_data = fp.read()\n fp.close()\n\n return file_data\n\n" }, { "alpha_fraction": 0.6740442514419556, "alphanum_fraction": 0.6740442514419556, "avg_line_length": 36.38461685180664, "blob_id": "5ce43ed48fa81658501c03e56bea98a04ab8c95a", "content_id": "e4981eff12456c9989f80886c08654945480a40c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 497, "license_type": "no_license", "max_line_length": 65, "num_lines": 13, "path": "/django/jason_test/booktest/urls.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n\turl(r'^$',views.index,name=\"index\"),\r\n\turl(r'^upload/',views.upload,name=\"upload\"),\r\n\turl(r'^pages/',views.pages,name=\"pages\"),\r\n\turl(r'^book_index/',views.book_index, name=\"book_index\"),\r\n\turl(r'^ajax_get/',views.ajax_get,name=\"ajax_get\"),\r\n\turl(r'^get_bookinfo/',views.get_bookinfo,name=\"get_bookinfo\"),\r\n\turl(r'^editor/',views.editor,name=\"editor\"),\r\n\turl(r'^editor_handle',views.editor_handle,name=\"editor_handle\"),\r\n]" }, { "alpha_fraction": 0.5050128102302551, "alphanum_fraction": 0.5206341743469238, "avg_line_length": 27.771812438964844, "blob_id": "39c39fa75b7d82facc065ec5d1ecc5d449fda2db", "content_id": "4c33f77ec4f14b03ab2e5e680f87324d3f77464b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4463, "license_type": "no_license", "max_line_length": 145, "num_lines": 149, "path": "/Python/mysql/connect.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\n\nfrom pymysql import *\n\nclass py_mysql(object):\n\n def __init__(self, host, port, user, passwd, db, charset):\n self.host = host\n self.port = port\n self.user = user\n self.passwd = passwd\n self.db = db\n self.charset = charset\n try:\n print(self.host, self.port, self.user, self.passwd, self.db, self.charset)\n self.conn = connect(host = self.host, port = self.port, user = self.user, passwd = self.passwd, db = self.db, charset = self.charset)\n except Exception as e:\n print(e)\n print('fail!!!')\n else:\n print('connect ok')\n self.curssor = self.conn.cursor()\n\n\n def add(self, params=[]):\n sql = 'insert into login values(%s,%s,%s,%s,%s,%s)'\n res = self.curssor.execute(sql, params)\n\n if res:\n self.conn.commit()\n else:\n self.conn.rollback()\n print (res)\n\n# self.curssor.close()\n# self.conn.close()\n\n def delete(self, params):\n sql = 'delete from login where id = %s'\n res = self.curssor.execute(sql, params)\n\n if res:\n self.conn.commit()\n else:\n self.conn.rollback()\n print(res)\n\n def update(self, params):\n sql = 'update login set %s = %s where id = %s'\n res = self.curssor.execute(sql, params)\n\n if res:\n self.conn.commit()\n else:\n self.conn.rollback()\n print(res)\n\n def select(self, params):\n sql = 'select * from login'\n\n# print('------%s-----'%params)\n\n if params[0] == 'one':\n self.curssor.execute(sql)\n result = self.curssor.fetchone()\n print('select one ok')\n elif params[0] == 'all':\n self.curssor.execute(sql)\n result = self.curssor.fetchall()\n print('select all ok')\n else:\n print('command wrong!')\n result = NULL\n\n return result\n\n def close(self):\n self.curssor.close()\n self.conn.close()\n\nclass Userlogin(py_mysql):\n# def __init__(self, host, port, user, passwd, db, charset):#此处若不定义__init__函数则默认使用父类的__init__函数\n# super(Userlogin,self).__init__(host, port, user, passwd, db, charset)#此处若定义__init__函数可通过此方式调用父类的__init__函数\n# 以上调用父类中的__init__函数的作用是使用父类中创建的一些局部变量,该类添加的局部变量可在此处及以下继续添加\n def login(self, user, passwd):\n sql = 'select passwd from login where name = %s'\n params = [user]\n res = self.curssor.execute(sql, params)\n\n if res:\n result = self.curssor.fetchone()\n# print('----result:%s-----'%result)\n print('select ok....')\n else:\n result = NULL\n print('username wrong!!!')\n\n# print('---result:%s---passwd:%s---'%(result,passwd))\n if result[0] == passwd:\n print(' login sucess....')\n else:\n print('passwd wrong!!!!')\n\n def join(self, user, passwd):\n sql = 'select passwd from login where name = %s'\n params = [user]\n res = self.curssor.execute(sql, params)\n if res:\n print('username exists, change it!!')\n return 0\n else:\n print('username can join...')\n\n sql = 'insert into login(name,passwd) values(%s,%s)'\n params = [user, passwd]\n\n res = self.curssor.execute(sql, params)\n if res:\n self.conn.commit()\n print('insert ok...')\n else:\n self.conn.rollback()\n print('insert fail!!!')\n\n return 1\n \n\nif __name__ == '__main__':\n\n# database = input('please input the database: ')\n# mysql = py_mysql(host = '192.168.31.216', port = 3306, user = 'root', passwd = 'dzy', db = 'python3', charset = 'utf8')\n\n# params = [0, 'll', '123456', '34567890', 'pudong', 0]\n# mysql.add(params)\n\n# params = ['all']\n# data = mysql.select(params)\n# print(data)\n\n login = Userlogin(host = '192.168.31.216', port = 3306, user = 'root', passwd = 'dzy', db = 'python3', charset = 'utf8')\n# login.login('ll', '123456')\n \n result = login.join('ggg','333333')\n if result:\n print('join sucess...')\n else:\n print('join fail !!')\n\n login.close()\n\n print('OK!!')\n" }, { "alpha_fraction": 0.6905055642127991, "alphanum_fraction": 0.6905055642127991, "avg_line_length": 52.06666564941406, "blob_id": "8e6dc5c02c5fac921a1994bbd4b0e4c402396509", "content_id": "657e72a59787eb375a6d69584539751350107bc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 811, "license_type": "no_license", "max_line_length": 106, "num_lines": 15, "path": "/django/tiantian/tiantian_project/urls.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n url(r'^register/$',views.register,name=\"register\"),\r\n url(r'^register_handle/$',views.register_handle,name=\"register_handle\"),\r\n url(r'^check_username/$',views.check_username,name=\"check_username\"),\r\n url(r'^login/$',views.login,name=\"login\"),\r\n url(r'^login_handle/$',views.login_handle,name=\"login_handle\"),\r\n url(r'^user_center_info/$',views.user_center_info,name=\"user_center_info\"),\r\n url(r'^user_center_info_register/$',views.user_center_info_register,name=\"user_center_info_register\"),\r\n url(r'^user_center_info_register_handle$',views.user_center_info_register_handle,name\r\n \t=\"user_center_info_register_handle\"),\r\n url(r'^user_center_order$',views.user_center_order,name=\"user_center_order\"),\r\n]\r\n" }, { "alpha_fraction": 0.6104129552841187, "alphanum_fraction": 0.6122082471847534, "avg_line_length": 12.925000190734863, "blob_id": "c517c9b5b450b206be6ab370ef0e20a5ea512ec3", "content_id": "c408b0609442d8fecc940d436977de220b39c975", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 557, "license_type": "no_license", "max_line_length": 38, "num_lines": 40, "path": "/Python/plus/copy_test.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\nfrom multiprocessing import Pool\nimport os\nimport shutil\n\ndef copy_files(name):\n\t\n\tprint('-----%s--------'%name)\n\tfr = open('test/'+name)\n\tfw = open('test_bak/'+name,'w')\n\n\tcontent = fr.read()\n\tfw.write(content)\n\n\tfr.close()\n\tfw.close()\n\n\n\n\n\ndef main():\n\n\tif not os.path.exists('test_bak/'):\n\t\tos.mkdir('test_bak')\n\telse:\n\t\tshutil.rmtree('test_bak')\n\t\tos.mkdir('test_bak')\n\tsource_files = os.listdir('test')\n\n\tpool = Pool(5)\n\n\tfor name in source_files:\n\t\tpool.apply_async(copy_files,(name,))\n\n\tpool.close()\n\tpool.join()\n\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.5282837748527527, "alphanum_fraction": 0.5349951982498169, "avg_line_length": 23.162790298461914, "blob_id": "ac25b924f5ce05009801f41ee03b5273d2701c1b", "content_id": "cbec2fb6541b4bf2d605680d8070f3ce36567a90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2086, "license_type": "no_license", "max_line_length": 99, "num_lines": 86, "path": "/Python/plus/net/web/web_framework/web_service.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\nfrom socket import *\nfrom multiprocessing import Process\nimport re\nimport sys\nfrom web_framework import app\n\nclass Http_service(object):\n ''' For Http_service '''\n def __init__(self):\n self.send_data = ''\n\n self.Web_service = socket(AF_INET, SOCK_STREAM)\n print('--create a socket--')\n \n self.Web_service.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\n\n self.Web_service.bind(('', 7788))\n print('--bind port --')\n\n def Http_start(self):\n self.Web_service.listen(5)\n print('--listenning--')\n\n while True:\n Client, ip_info = self.Web_service.accept()\n print('--accept--')\n\n # create a Process to receive data and handle it \n p = Process(target=self.Receive_data, args=(Client,))\n p.start()\n\n # when create the Process and transfer the Client. the main process client should be closed\n Client.close()\n\n self.Web_service.close()\n\n def Receive_data(self, Client):\n # Receive data \n print('--receive data--')\n data = Client.recv(1024)\n\n # data is right?\n if data:\n print(data)\n\n self.Handle_data(data)\n\n Client.send(bytes(self.send_data, 'utf-8'))\n else:\n print('--data error--')\n \n # close client, only connect one time\n Client.close() \n\n def start_response(self, status, headers):\n\n self.response_body = status + '\\r\\n' + str(headers) + '\\r\\n'\n\n def Handle_data(self, data):\n # split the html name\n html = '.'+(re.match(r'\\w+ +(/[^ ]*)', (data.decode('utf-8')).splitlines()[0])).group(1)\n\n print('---html:%s-----'%html)\n # create a environ \n environ = {\n 'PATH': html\n }\n\n html_data = app(environ, self.start_response)\n\n print(html_data)\n\n # http send data\n self.send_data = self.response_body + '\\r\\n'+ html_data\n\n\n\n\ndef main():\n http = Http_service()\n\n http.Http_start()\n\n\nif __name__ == '__main__':\n main()\n\n\n \n" }, { "alpha_fraction": 0.6530105471611023, "alphanum_fraction": 0.6554934978485107, "avg_line_length": 23.140625, "blob_id": "b3d2c787f9a09d1daf44da2423dc7dc345909766", "content_id": "6256effbd5cab451f6451a7dd57a3f927feb3e02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1639, "license_type": "no_license", "max_line_length": 105, "num_lines": 64, "path": "/tornado/test/04_chat.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "import tornado.web\r\nimport tornado.httpserver\r\nimport tornado.ioloop\r\nimport tornado.options\r\nfrom tornado.web import url\r\nfrom tornado.websocket import WebSocketHandler\r\n\r\nimport os\r\n\r\ntornado.options.define('port', default=8000, type=int, help='runserver on given port')\r\n\r\nclass IndexHandler(tornado.web.RequestHandler):\r\n\tdef get(self):\r\n\t\tself.render('chat.html')\r\n\r\nclass ChatHander(WebSocketHandler):\r\n\tusers = set()\r\n\r\n\tdef open(self):\r\n\t\tself.users.add(self)\r\n\r\n\t\tfor u in self.users:\r\n\t\t\tu.write_message(\"%s 进入聊天室\" % self.request.remote_ip)\r\n\r\n\tdef on_message(self,message):\r\n\t\tfor u in self.users:\r\n\t\t\tu.write_message(\" %s发送消息:%s\" %(self.request.remote_ip, message))\r\n\r\n\tdef on_close(self):\r\n\t\tusers.remove(self)\r\n\t\tfor u in self.users:\r\n\t\t\tu.write_message(\"%s退出聊天室\"% self.request.remote_ip)\r\n\r\n\tdef check_origin(self, origin):\r\n\t\treturn True\r\n\r\n\r\nclass Application(tornado.web.Application):\r\n\tdef __init__(self):\r\n\t\thandler = [\r\n\t\t\turl(r'^/$', IndexHandler, name=\"IndexHandler\"),\r\n\t\t\turl(r'^/chat$', ChatHander, name=\"ChatHander\"),\r\n\t\t]\r\n\r\n\t\tsettings = dict(\r\n\t\t\tdebug= True,\r\n\t\t\tstatic_path = os.path.join(current_path, 'static'),\r\n\t\t\ttemplate_path = os.path.join(current_path, 'templates'),\r\n\t\t\t)\r\n\r\n\t\tsuper(Application, self).__init__(handler, **settings) \r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n\ttornado.options.parse_command_line()\r\n\tcurrent_path = os.path.dirname(__file__)\r\n\r\n\tapp = Application()\r\n\r\n\thttp_server = tornado.httpserver.HTTPServer(app)\r\n\thttp_server.listen(tornado.options.options.port)\r\n\r\n\ttornado.ioloop.IOLoop.current().start()\r\n\r\n" }, { "alpha_fraction": 0.4642857015132904, "alphanum_fraction": 0.5200892686843872, "avg_line_length": 23.94444465637207, "blob_id": "f989783c2aad0aae97a6f92ff84e5d79e172376a", "content_id": "c3533ad71215ad4cf6e512c07ea928d2e8c778b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 526, "license_type": "no_license", "max_line_length": 83, "num_lines": 18, "path": "/Python/algorithm/select.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "def select_seq(seq_data):\n \"\"\"插入排序的核心思想是找到后边无序序列中的最小值,并将最小值一次的放入序列的开头\"\"\"\n n = len(seq_data)\n\n for j in range(n-1):\n i = j\n min_value = i\n for i in range(i, n):\n if seq_data[i] < seq_data[min_value]:\n seq_data[min_value], seq_data[i] = seq_data[i], seq_data[min_value]\n\n\nif __name__ == '__main__':\n seq = [54, 226, 93, 17, 77, 31, 44, 55, 20, 6, 23, 54]\n\n select_seq(seq)\n\n print(seq)" }, { "alpha_fraction": 0.5100577473640442, "alphanum_fraction": 0.5399684906005859, "avg_line_length": 30.059782028198242, "blob_id": "658491938b473c95fd0b59d1cc33c2fe8419b6ef", "content_id": "bb60dae28b24a552a623b303c42eaf8ebd83f7f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5729, "license_type": "no_license", "max_line_length": 163, "num_lines": 184, "path": "/Python/basic/plane_war/plane_war.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n#! -*- coding:utf-8 -*-\n\nimport pygame\nimport time \n\nfrom pygame.locals import *\n\nclass Window(object):\n def __init__(self,temp1,temp2,temp3):\n self.size = temp1\n self.pos = temp2\n self.color = temp3 \n self.window = pygame.display.set_mode(self.size,self.pos,self.color)\n self.image = pygame.image.load('./feiji/background.png')\n\n\n def __str__(self):\n return \"create a window size:%s pos:%d color_size:%d\"%(str(self.size),self.pos,self.color)\n\n\nclass Base_plane(object):\n def __init__(self,name0,name1,name2,name3,name4,x,y):\n self.image0 = pygame.image.load(name0)\n self.image1 = pygame.image.load(name1)\n self.image2 = pygame.image.load(name2)\n self.image3 = pygame.image.load(name3)\n self.image4 = pygame.image.load(name4)\n self.x = x\n self.y = y\n\n\n\n\nclass My_hero(Base_plane):\n def __init__(self,name0,name1,name2,name3,name4,x,y):\n Base_plane.__init__(self,name0,name1,name2,name3,name4,x,y)\n self.bullet_list = []\n self.mouse_flag = 0\n\n def display(self,temp):\n temp.window.blit(self.image0,(self.x,self.y))\n\n for i in self.bullet_list:\n i.display(temp)\n if i.y < 0 :\n self.bullet_list.remove(i)\n\n def shoot(self,temp):\n bullet = Bullet(self.x,self.y)\n self.bullet_list.append(bullet)\n bullet.enemy.add(temp)\n\n def mouse_move(self):\n self.x,self.y = pygame.mouse.get_pos()\n self.x -= 50\n self.y -= 62\n\n\nclass Enemy1(Base_plane):\n def __init__(self,name0,name1,name2,name3,name4,x,y):\n Base_plane.__init__(self,name0,name1,name2,name3,name4,x,y)\n self.disappear_flag = 0 \n self.disappear = 0\n self.recreate = 0\n self.direction = 'right'\n\n def display(self,temp):\n if self.disappear_flag==0 and self.disappear==0:\n temp.window.blit(self.image0,(self.x,self.y))\n if self.disappear_flag == 4 and self.disappear ==0:\n temp.window.blit(self.image1,(self.x,self.y))\n self.disappear_flag -=1\n elif self.disappear_flag == 3 and self.disappear ==0:\n temp.window.blit(self.image2,(self.x,self.y))\n self.disappear_flag -=1\n elif self.disappear_flag == 2 and self.disappear ==0:\n temp.window.blit(self.image3,(self.x,self.y))\n self.disappear_flag -=1\n elif self.disappear_flag == 1 and self.disappear ==0:\n temp.window.blit(self.image4,(self.x,self.y))\n self.disappear_flag -=1\n self.disappear = 1\n\n def mov(self):\n if self.x >420-10 :\n self.direction = 'left'\n elif self.x <10 :\n self.direction = 'right'\n if self.direction == 'left':\n self.x -=5\n elif self.direction == 'right':\n self.x += 5\n print('direction:%s x:%d'%(self.direction,self.x))\n \n\nclass Bullet(object):\n\n def __init__(self,temp_x,temp_y):\n self.image = pygame.image.load('./feiji/bullet.png')\n self.x = temp_x\n self.y = temp_y\n self.enemy = set()\n\n def display(self,temp):\n temp.window.blit(self.image,(self.x,self.y))\n self.y -=20\n\n for temp in self.enemy:\n print('x:%d y:%d'%(self.x,self.y))\n if self.x-55 <temp.x and self.x+15 > temp.x and self.y-45 <temp.y and self.y+45 >temp.y and temp.disappear_flag==0:\n temp.disappear_flag = 4\n break\n \n\n\n\ndef move(temp1,temp2):\n\n for event in pygame.event.get():\n\n if event.type == QUIT:\n print('exit')\n exit() #use to quit frome a programe\n elif event.type == KEYDOWN:\n if event.key == K_a or event.key == K_LEFT:\n print('left')\n temp1.x -=10\n\n elif event.key == K_d or event.key == K_RIGHT:\n print('right')\n temp1.x +=10\n\n elif event.key == K_c:\n print('exit')\n exit()\n elif event.key == K_m:\n print('use mouse for moving')\n temp1.mouse_flag = 1\n \n elif event.key == K_SPACE:\n print('space')\n temp1.shoot(temp2)\n\n elif event.key == K_n:\n print('create a new game')\n temp2.recreate = 1\n\n\ndef main():\n pygame.init() # pygame init\n screen = Window((480,852),0,32)\n pygame.display.set_caption('Plane War') #创建窗口标签\n#---------above create a whole background class-----------------\n hero = My_hero('./feiji/hero1.png','./feiji/hero_blowup_n1.png','./feiji/hero_blowup_n2.png','./feiji/hero_blowup_n3.png','./feiji/hero_blowup_n4.png',210,700)\n enemy1 = Enemy1('./feiji/enemy1.png','./feiji/enemy1_down1.png','./feiji/enemy1_down2.png','./feiji/enemy1_down3.png','./feiji/enemy1_down4.png',210,0)\n#--------above create a hero plane class---------------------- \n\n while True:\n screen.window.blit(screen.image,(0,0))\n#---------above create a background----------------------------\n hero.display(screen)\n if hero.mouse_flag == 1 :\n hero.mouse_move()\n enemy1.display(screen)\n enemy1.mov()\n#---------above create plane--------------------------\n if enemy1.recreate ==1 :\n enemy1 = Enemy1('./feiji/enemy1.png','./feiji/enemy1_down1.png','./feiji/enemy1_down2.png','./feiji/enemy1_down3.png','./feiji/enemy1_down4.png',210,0)\n enemy1.recreate = 0\n move(hero,enemy1)\n\n \n pygame.display.update()\n\n time.sleep(0.01)\n\n\n\n\n\nif __name__ == '__main__':\n\n main()\n\n\n" }, { "alpha_fraction": 0.4166666567325592, "alphanum_fraction": 0.44583332538604736, "avg_line_length": 18.83333396911621, "blob_id": "55cc3576e42122a1f87e2c495653e939f48e66fa", "content_id": "fe7d7809fc044437d5c00caf9ed6184ff43f8c53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 240, "license_type": "no_license", "max_line_length": 45, "num_lines": 12, "path": "/Python/readme.txt", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "/*******************************************\n\n\tAuthor: Jason(dongzhenyu)\n\tDate: 2017-7-26\n\tGoal: proficient in using python\n\tGithub account: jasondzy\n********************************************/\n\n\n\n\nThis dir is used for python study\n\n\n" }, { "alpha_fraction": 0.7085714340209961, "alphanum_fraction": 0.7657142877578735, "avg_line_length": 17.66666603088379, "blob_id": "8ffd40afad2c9c2d99f0bd0982c26b1de3bb9477", "content_id": "79c88ecf1b993ff39fd439b5e00954e9b7f7cd94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 175, "license_type": "no_license", "max_line_length": 49, "num_lines": 9, "path": "/django/jason_test/uwsgi.ini", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "[uwsgi]\r\nhttp=0.0.0.0:8000\r\nchdir=/home/ubuntu/user_jason/git/django/tiantian\r\nwsgi-file=tiantian/\r\nprocesses=4\r\nthreads=2\r\nmaster=True\r\npidfile=uwsgi.pid\r\ndaemonize=uswgi.log" }, { "alpha_fraction": 0.420265793800354, "alphanum_fraction": 0.460132896900177, "avg_line_length": 17.272727966308594, "blob_id": "061e8d3ae0c13a0a8abee75d506eeb3b94e8b9ab", "content_id": "b41fc478fabba0c958876b540065aca97f64ae56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 602, "license_type": "no_license", "max_line_length": 45, "num_lines": 33, "path": "/Python/algorithm/merge.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "def sort(left, right):\n lst = []\n j = 0\n i = 0\n while i < len(left) and j < len(right):\n if left[i] < right[j]:\n lst.append(left[i])\n i = i+1\n else:\n lst.append(right[j])\n j += 1\n lst += left[i:]\n lst += right[j:]\n\n return lst\n\n\ndef merge(lst):\n\n if len(lst) <= 1:\n return lst\n\n middle = len(lst) // 2\n left = merge(lst[:middle])\n right = merge(lst[middle:])\n\n return sort(left, right)\n\n\nif __name__ == '__main__':\n ll = [54, 26, 93, 17, 77, 31, 44, 55, 20]\n result = merge(ll)\n print(result)" }, { "alpha_fraction": 0.5576496720314026, "alphanum_fraction": 0.5620842576026917, "avg_line_length": 19.409090042114258, "blob_id": "281e7b1cd34b4e2504cf9d1eb89b3ea5dcce1760", "content_id": "7e9e6d58624504bf618b688aba5e5b6f6dcf234c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 902, "license_type": "no_license", "max_line_length": 122, "num_lines": 44, "path": "/Python/basic/furniture/furniture_test.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\n\nclass room():\n \n def __init__(self,area,addr,info):\n \n self.area = area\n self.addr = addr\n self.info = info\n self.useful = self.area\n\n def __str__(self):\n\n msg = \"romm:size is :%d area useful is:%d addr is:%s info is:%s \"%(self.area,self.useful,self.addr,self.info)\n return msg\n def add_item(self,item):\n self.useful -= item.get_size()\n\n\n\n\nclass bed():\n \n def __init__(self,size,name):\n self.size = size\n self.name = name\n\n def __str__(self):\n msg = \"bed : size is:%d name is:%s\"%(self.size,self.name)\n return msg\n\n def get_size(self): #define a func to get the private data;\n return self.size\n\nroom_dzy = room(200,\"hangzhou,xihu area\",\"four rooms\")\n\nprint(room_dzy)\n\n\nbed_one = bed(8,\"yijia\")\n\nprint(bed_one)\n\nroom_dzy.add_item(bed_one)# arg is a class type\n\nprint(room_dzy)\n\n\n" }, { "alpha_fraction": 0.5067567825317383, "alphanum_fraction": 0.5164092779159546, "avg_line_length": 23.654762268066406, "blob_id": "dd0ca9768e958e9f35cff2d0fde65c259b687953", "content_id": "2730a9f0f4c149e9fac2eb144a2b78eac7369bdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2072, "license_type": "no_license", "max_line_length": 111, "num_lines": 84, "path": "/Python/plus/net/web/web_service/web_service.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\nfrom socket import *\nfrom multiprocessing import Process\nimport re\n\n\nclass Http_service(object):\n ''' For Http_service '''\n def __init__(self):\n self.send_data = ''\n\n self.Web_service = socket(AF_INET, SOCK_STREAM)\n print('--create a socket--')\n \n self.Web_service.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\n\n self.Web_service.bind(('', 7788))\n print('--bind port --')\n\n def Http_start(self):\n self.Web_service.listen(5)\n print('--listenning--')\n\n while True:\n Client, ip_info = self.Web_service.accept()\n print('--accept--')\n\n # create a Process to receive data and handle it \n p = Process(target=self.Receive_data, args=(Client,))\n p.start()\n\n # when create the Process and transfer the Client. the main process client should be closed\n Client.close()\n\n self.Web_service.close()\n\n def Receive_data(self, Client):\n # Receive data \n print('--receive data--')\n data = Client.recv(1024)\n\n # data is right?\n if data:\n print(data)\n\n self.Handle_data(data)\n\n Client.send(bytes(self.send_data, 'utf-8'))\n else:\n print('--data error--')\n \n # close client, only connect one time\n Client.close() \n\n def Handle_data(self, data):\n # split the html name\n html = '.'+(re.match(r'\\w+ +(/[^ ]*)', (data.decode('utf-8')).splitlines()[0])).group(1)\n\n # try to read the local html data\n try:\n file = open(html, 'rb')\n html_data = file.read()\n except:\n print('open file error')\n while True:\n print('-----------')\n finally:\n file.close()\n\n print(html_data)\n\n # http send data\n self.send_data = \"HTTP/1.1 200 ok\\r\\n\" + \"Server: my server\" \"\\r\\n\" + '\\r\\n'+ html_data.decode('utf-8')\n\n\n\n\ndef main():\n http = Http_service()\n\n http.Http_start()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.7104166746139526, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 21.904762268066406, "blob_id": "110025018fb77cd4b330bf83966e3f5d67216243", "content_id": "d3a4bde258c84702fc6ff1dbe2d66298d320eeae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 480, "license_type": "no_license", "max_line_length": 46, "num_lines": 21, "path": "/django/tiantian/tiantian_project/models.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "from django.db import models\n\n# Create your models here.\n\nclass UserInfo(models.Model):\n\tuser_name = models.CharField(max_length=20)\n\tuser_passwd = models.CharField(max_length=40)\n\tuser_mail = models.CharField(max_length=30)\n\n\tdef __str__(self):\n\t\treturn self.user_name\n\n\n\nclass User_address_info(models.Model):\n\taddress = models.CharField(max_length=100)\n\ttel_num = models.CharField(max_length=12)\n\tuser = models.ForeignKey(UserInfo)\n\t\n\tdef __str__(self):\n\t\treturn str(self.user)" }, { "alpha_fraction": 0.6076555252075195, "alphanum_fraction": 0.619617223739624, "avg_line_length": 18.465116500854492, "blob_id": "a912e5d36c291925ce16249605b8e7eab0c0e60c", "content_id": "989ed944a3f88a424c655c9b28ecdfde9d2a06f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1022, "license_type": "no_license", "max_line_length": 77, "num_lines": 43, "path": "/Python/plus/net/tcp/tcp_service.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\"\"\"\n# note: 这里是通过gevent模块还实现单线程多任务的功能,其中的socket函数来自gevent模块中\n#\n#\n\n\"\"\"\nfrom gevent import socket, monkey\nimport gevent\n\nmonkey.patch_all()#使用gevent中的monkey来对接一下的函数进行封装成非阻塞的功能,此处必须\n\ndef handle_data(client):\n while True:\n data = client.recv(1024)\n if data:\n print(data)\n else:\n client.close()\n break\n\n\ndef main():\n service = socket.socket()\n print('create a socket')\n\n# service.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\n\n service.bind(('', 7788))\n print('bind a port')\n\n service.listen(5)\n print('listenning.....')\n\n while True:\n client,ip = service.accept()\n print('accept..')\n\n gevent.spawn(handle_data,client)#添加需要进行调度的函数,只要遇到阻塞类型的函数就会进行切换从而实现多任务\n\n service.close()#never to run here for service\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.7872763276100159, "alphanum_fraction": 0.7952286005020142, "avg_line_length": 22.952381134033203, "blob_id": "e8732bca37879640621e73fd518ce564b166637d", "content_id": "121a84f73966768d32d214f90f24816a09542ec6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 875, "license_type": "no_license", "max_line_length": 97, "num_lines": 21, "path": "/Python/plus/Process/multi_processing.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\nfrom multiprocessing import Process\nimport time \n\ndef test():#这里表示的是子进程中所要运行的程序\n\tfor i in range(5):\n\t\tprint('---son Process---')\n\t\ttime.sleep(1)\n\nson = Process(target=test)#这里使用Process类创建了一个进程son,里边的参数是一个函数表明son这个进程需要处理的事情,参数中的test运行结束后子进程自动消亡\n\nson.start()#start方法表示的是开始运行子进程\n\ntime.sleep(1)\n\n#son.terminate() #Process中的terminate方法的作用是立刻停止所创建的子进程并返回,到这里子进程就结束了了,整个程序就只剩下主进程了\n\nson.join()#这里表示的是主进程在这里等待子进程运行完毕后才会往下执行,这里起到进程的同步作用\n\nwhile True:#这里表示的是主进程中所要运行的程序\n\tprint('---parent process--')\n\ttime.sleep(1)" }, { "alpha_fraction": 0.5941176414489746, "alphanum_fraction": 0.6058823466300964, "avg_line_length": 14.090909004211426, "blob_id": "035debb3e9d1a61b951a6d3f8fd7dccc013b2c29", "content_id": "75b37126fffb4079075f33f03d4afbab96c6c2ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 170, "license_type": "no_license", "max_line_length": 37, "num_lines": 11, "path": "/Python/basic/exception/exception.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\n\ntry:\n 5/0\n\n\nexcept Exception as ret :\n print(\"%s wrong has happend\"%ret)\n\nelse :\n print(\"No wrong happened\")\nfinally :\n print(\"programme run sucess....\")\n\n\n" }, { "alpha_fraction": 0.6164383292198181, "alphanum_fraction": 0.6164383292198181, "avg_line_length": 25.375, "blob_id": "79b8b2e6974d691000dabc9921a3d3beaa81f019", "content_id": "d1d56854345ba5a31901016f47ea23b59ae3e9e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 219, "license_type": "no_license", "max_line_length": 58, "num_lines": 8, "path": "/tornado/project/Ihome/Settings.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\r\n# import os\r\n\r\n# current_path = os.path.dirname(__file__)\r\n# settings = dict(\r\n# \tdebug = True,\r\n# \tstatic_path = os.path.join(current_path, 'static'),\r\n# \ttemplate_path = os.path.join(current_path, 'template'),\r\n# \t)" }, { "alpha_fraction": 0.7600364685058594, "alphanum_fraction": 0.7700729966163635, "avg_line_length": 33.28125, "blob_id": "4438b97876880b03a2cd5e123ccd768d1395f338", "content_id": "abe9f99af4ce762491c63e52e5a73583a7d8c498", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1946, "license_type": "no_license", "max_line_length": 115, "num_lines": 32, "path": "/Python/plus/decorator/decorator.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "def func(function): #这里的func定义的是一个闭包,这里的参数是function\n\tprint('Tis is a decorate1---')\n\tdef func_inner(*args,**kwargs):#这里的func_inner是闭包中的内嵌函数,最终闭包的返回值就是这个内嵌函数的地址\n\t\tprint('----func_inner----')\n\t\tfunction(*args,**kwargs)#这里的function()的作用是执行函数function,从这里可以验证闭包的参数是一个函数的地址\n\n\treturn func_inner#这里是闭包的返回值,该返回值是函数的地址\n\n\ndef func2(function):\n\tprint('This is a decorate2')\n\tdef func_inner(*args,**kwargs):#这里对内嵌函数定义了不定参数,注意这里的内嵌函数就是将来调用的函数test(),所以要实现test(x,y...)带入参数,那么这里的内嵌函数必须定义成带参数的形式\n\t\tprint('-----func_inner2---')\n\t\tfunction(*args,**kwargs)#这里的函数调用的是定义的test函数,所以这里的参数要使用内嵌函数中的参数,可以不一致。因为最终所有的参数都是通过装饰后的test传递进来的。\n\treturn func_inner\n\n\n\n@func #这里的作用是试用装饰器func,传入的参数就是下一行中的函数地址,即test\n@func2 #通过执行这个py脚本,注意管着两个连续的装饰器的执行顺序是如何的\ndef test(a):\n\tprint('----test---a=%d---'%a)\n@func#通过对改脚本的输出log可知,装饰器的执行是在所有函数之前的,即这三个装饰器的最先打印处This is a decoratex,其中decorate2最先打印出来\ndef test1(a):\n\tprint('----test1-- a=%d--'%a)\n\ntest(0)#调用test函数,注意这里的test函数已经不再是上边定义了的test函数,而是经过装饰器装饰了的函数\ntest1(1)\n\n#@func的作用就是对函数进行装饰,流程原理如下:\n#@func => test = func(test) => func_inner()\n#即最后的test的地址为func_inner的地址,而在func_inner中有调用test所以实现了对test的封装" }, { "alpha_fraction": 0.45676276087760925, "alphanum_fraction": 0.521064281463623, "avg_line_length": 25.58823585510254, "blob_id": "c5cb3e3b7ba9e7722ed7350c41bd7b3a7e77d6dd", "content_id": "0166bfe371f1f62922a7c3d51e13a1bc0b894ef3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 601, "license_type": "no_license", "max_line_length": 85, "num_lines": 17, "path": "/Python/algorithm/insert.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "def insert_seq(seq_data):\n \"\"\"这里是采用插入排序的方式,具体实现原理是通过将序列分成两列来对待,即前边的有序序列和后边的无序序列,每次从无序序列中提取一个数插入到前边的有序序列中去\"\"\"\n n = len(seq_data)\n for j in range(n):\n i = j\n while i > 0:\n if seq_data[i] < seq_data[i-1]:\n seq_data[i-1], seq_data[i] = seq_data[i], seq_data[i-1]\n i -= 1\n\n\nif __name__ == '__main__':\n seq = [54, 226, 93, 17, 77, 31, 44, 55, 20, 6, 23, 54]\n\n insert_seq(seq)\n\n print(seq)" }, { "alpha_fraction": 0.7934272289276123, "alphanum_fraction": 0.7981220483779907, "avg_line_length": 30.950000762939453, "blob_id": "f79e101889ab19e2f579de301543f22f9a29a160", "content_id": "4e8bb9548a4a90ef8566c47da963f2aaa21837db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1111, "license_type": "no_license", "max_line_length": 127, "num_lines": 20, "path": "/Python/plus/Process/process_class.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\nfrom multiprocessing import Process\nimport time\n\n\nclass New_process(Process):#这里定义了一个新的Newprocess类,这个类继承了Process这个父类,即可通过这个新建的类来创建一个自定义的进程\n\tdef __init__(self,value):\n\t\tProcess.__init__(self)#初始化调用了父类中的init函数,同时也加入了自定义的value的变量\n\t\tself.value = value\n\n\tdef run(self):#定义了一个run方法,切记:此处定义的run方法是对父类Process中的run方法的一种重写,接下来的父类中的start方法启用的是这里重写了的run方法,这里也实现了一个不用通过tartget=xxx的方法传入一个方法\n\t\twhile True:\n\t\t\tprint('----son-----')\n\t\t\ttime.sleep(1)\n\nson = New_process(1)#用新创建的类来创建一个子进程,里边传入的参数并没有实际的作用\nson.start()#调用start方法,这个start方法是在父类中定义的,但是这个start的方法实际调用的是run方法,由于在新建的类中重写了run方法所以最终调用的是新创建的类中的run方法\n\nwhile True:\n\tprint('---parent----')\n\ttime.sleep(1)" }, { "alpha_fraction": 0.5438596606254578, "alphanum_fraction": 0.5470494627952576, "avg_line_length": 16.742856979370117, "blob_id": "9d56e5a0172057ca9c764517ac55db8accdbfe30", "content_id": "40e2cbdfd5c45ccfa1e62558cc8c25dfd0926a34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 627, "license_type": "no_license", "max_line_length": 62, "num_lines": 35, "path": "/Python/basic/class_func/class_func.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\n\nclass Game(object):\n\n num = 0\n\n def __init__(self):\n self.name = \"croos fire\"\n\n\n #define a class func , use classmethod to define\n\n @classmethod\n def class_num(cls):\n cls.num +=1\n\n #staticmethod can no args . so no self or cls and so on...\n @staticmethod\n def print_info():\n print(\"---------------------\")\n print(\" cross fire \")\n print (\"___________________\")\n\n\ngame = Game()\n\n# call the object func\nprint(game.name)\n\n#call the class func\n#Game.class_num() or\ngame.class_num()\nprint(Game.num)\n\n#call the static func\n#Game.print_info() or\ngame.print_info()\n\n\n\n\n" }, { "alpha_fraction": 0.6838235259056091, "alphanum_fraction": 0.6911764740943909, "avg_line_length": 23.81818199157715, "blob_id": "7569d55132e9b7a0db34f3bc869dfdb2aefe38bf", "content_id": "d5d5b05da588419816efa24cb35895f78086d7d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 272, "license_type": "no_license", "max_line_length": 50, "num_lines": 11, "path": "/django/tiantian/goods_app/views.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\n# Create your views here.\n\ndef index(request):\n\tname = request.session.get('user',None)\n\tif name != None:\n\t\tcontext = {'user':name,'status':1}\n\telse:\n\t\tcontext = {'user':\"\",'status':0}\n\treturn render(request,'goods/index.html',context)" }, { "alpha_fraction": 0.7200000286102295, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 11.5, "blob_id": "cde0b7317bb476798c98164133b143337f321adf", "content_id": "add78c5a1b6ab6186bc8378891ccb9cd248ca0d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 25, "license_type": "no_license", "max_line_length": 12, "num_lines": 2, "path": "/Python/basic/README.md", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "# class_func\n# furniture\n" }, { "alpha_fraction": 0.5659287571907043, "alphanum_fraction": 0.586140513420105, "avg_line_length": 20.14285659790039, "blob_id": "2d7188fe13aed35b1f092e68222048af850c0c80", "content_id": "8cfe31961c370943ce4be7b08be83c0cf27a295b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1039, "license_type": "no_license", "max_line_length": 69, "num_lines": 49, "path": "/Python/plus/net/web/web_framework/web_framework.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\n\nclass Application(object):\n\n def __init__(self,urls):\n self.urls = urls\n\n # define a callable function, so the class can be called\n def __call__(self, environ, start_response):\n return self.application(environ, start_response)\n\n\n # define a functon , this function is standard for wsgi interface\n def application(self,environ, start_response):\n\n header= ''''''\n\n start_response('HTTP/1.1 200 ok',header)\n\n path = environ.get('PATH', '/')\n\n for name, handler in self.urls:\n if name == path:\n return handler()\n\n start_response('HTTP/1.1 404 not found',header)\n return '404 not found'\n\ndef handle_index():\n\n fp = open('./index.html', 'r')\n file_data = fp.read()\n fp.close()\n\n return file_data\n\ndef handle_index11():\n fp = open('./index11.html', 'r')\n file_data = fp.read()\n fp.close()\n\n return file_data\n\n\nurls = [\n ('./index.html', handle_index),\n ('./index11.html', handle_index11)\n\n]\n\napp = Application(urls)\n\n" }, { "alpha_fraction": 0.610837459564209, "alphanum_fraction": 0.7192118167877197, "avg_line_length": 19.200000762939453, "blob_id": "a4fa24eae73bab0e1a5c16763830a4eebf7c1eb3", "content_id": "751b71ce01f6c9c740b4c778e27cd8a86967e58f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 203, "license_type": "no_license", "max_line_length": 60, "num_lines": 10, "path": "/Python/plus/net/send_data.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\nimport socket\n\n\nudp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n\nudp_socket.bind(('',7766))\n\ndata = udp_socket.recvfrom(1024)\nprint(data)\nudp_socket.sendto(b'hello',('192.168.0.107',8080))\n" }, { "alpha_fraction": 0.5933236479759216, "alphanum_fraction": 0.5997097492218018, "avg_line_length": 23.062936782836914, "blob_id": "a706b783183dbe6a0af6077233c08aa6ed8eefee", "content_id": "999857b258b7c1e0fae773124b82108e87be6ac6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4193, "license_type": "no_license", "max_line_length": 197, "num_lines": 143, "path": "/Python/basic/Project/laowang_shut.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\n\n\nclass Person():\n\n def __init__(self,name):\n self.name = name\n self.gun = None\n self.hp = 100\n\n def __str__(self):\n return \"The person name is %s hp is:%s the gun is: %s\"%(self.name,self.hp,self.gun)\n def load_bullet(self,temp1,temp2):\n temp1.add_bullet(temp2)\n\n def load_bullet_package(self,temp1,temp2):\n temp1.bullet_package = temp2\n\n def load_gun(self,temp):\n self.gun = temp\n\n def shoot(self,enemy):\n self.gun.shoot(enemy)\n\n def hp_down(self,temp):\n self.hp -= temp\n if self.hp < 0 :\n print(\"enemy has died!!!\")\n\n\nclass Gun():\n\n def __init__(self,name):\n self.name = name\n self.bullet_package = None\n self.bullet = None\n def __str__(self):\n return \"The name of gun is %s the bullet_package is:%s\"%(self.name,self.bullet_package)#这里的self.bullet_package变量,其实就是调用bullet_package中的__str__方法,因为__str__方法中用的就是return,所以对象名称中保存的值就是__str__\n\n def add_bullet_package(self,temp):\n self.bullet_package = temp\n \n def shoot(self,temp):\n self.bullet = self.bullet_package.pop_bullet()\n if self.bullet :\n self.bullet.hurt(temp)\n else :\n print(\"Do not have bullet\")\n\n\nclass Bullet_package():\n def __init__(self,max_num):\n self.max_num = max_num\n self.bullet_num=[]\n\n\n def __str__(self):\n return \"The max num of bullets is %d load bullet is %d\"%(self.max_num,len(self.bullet_num))\n\n\n def add_bullet(self,temp):\n self.bullet_num.append(temp)\n \n\n def pop_bullet(self):\n return self.bullet_num.pop()\n\n\nclass Bullet():\n def __init__(self,ability):\n self.ability = ability\n\n def __str__(self):\n return \"the ability is %d\"%self.ability\n \n def hurt(self,temp):\n temp.hp_down(self.ability)\n\n\n\ndef main():\n\n bullet = Bullet(10) #创建一个bullet实体,每一个实体都有一个独立的存储空间,即使是由同一个类创造出来的,他们中的属性值(即__init__下的变量值)是不一样的,这也是self的作用,若不用self.xx那么xx表示的就是类的属性,对由其创建的对象是一样的\n print(bullet)\n\n bullet_package = Bullet_package(30)\n print(bullet_package)\n\n\n gun = Gun(\"AK47\")\n print(gun)\n\n\n laowang = Person(\"laowang\")\n print(laowang)\n\n#---------above create three classes-----------------------\n\n for i in range(30):\n bullet = Bullet(10)#创建一个bullet实体\n laowang.load_bullet(bullet_package,bullet) # 这里的参数传递的是对象,不要传递类,因为对象才是实体,类只是一个模具\n print(bullet_package)\n#---------above add some bullets--------------------------\n\n laowang.load_bullet_package(gun,bullet_package)#从这些对象之间的调用可知,python是一种解释性语言,其按照顺序的方式对程序进行解释执行,所以这里的参数对象,必定是前边已经赋值了的\n print(gun)\n\n#---------above add a bullet_package into gun------------\n\n laowang.load_gun(gun)#在这里的各个函数调用过程中,时刻都会改变main一开始创建的四个对象中的值,因为这四个对象是一个在内存空间中的实体,对象中的属性值通过引用的方式改变其自身的值\n print(laowang)\n\n#--------above add a gun -------------------------------\n\n laosong = Person(\"laosong\")#这里再次创建一个Person对象,注意这里并不是和laowang是同一个对象,他们分别是独立的一块内存空间,其属性值是不一定相同的\n\n#--------above create a enemy------------------- -------\n\n laowang.shoot(laosong)\n print(laosong)\n\n laowang.shoot(laosong)\n print(laosong)\n laowang.shoot(laosong)\n print(laosong)\n\n laowang.shoot(laosong)\n print(laosong)\n\n laowang.shoot(laosong)\n print(laosong)\n\n\n laowang.shoot(laosong)\n print(laosong)\n\n\n\n#---------above shoot enemy-----------------------------\n\n\n\n\n\nif __name__ == \"__main__\" :#python中用来区别import和执行运行的方式\n main()\n\n" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 41, "blob_id": "f80b29a195b5af49d37927a3a1531d934a562230", "content_id": "9fe535c164c4cab3799d0bb03672c31124e9e4b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 45, "license_type": "no_license", "max_line_length": 41, "num_lines": 1, "path": "/Python/basic/readme.txt", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\n\n\tthis is a basic python study test record\n" }, { "alpha_fraction": 0.6577181220054626, "alphanum_fraction": 0.6711409687995911, "avg_line_length": 29.589040756225586, "blob_id": "114f6f289b8b00dd666b7596c03578f00c5d5210", "content_id": "ce5e6dc76a1e4c403cfb657a3935c23f8095df3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5397, "license_type": "no_license", "max_line_length": 142, "num_lines": 146, "path": "/tornado/test/03_template.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "import tornado.web\r\nimport tornado.httpserver\r\nimport tornado.options\r\nimport tornado.ioloop\r\nimport tornado.httpclient\r\nimport tornado.gen\r\nimport os\r\nimport pymysql\r\nimport base64, uuid, json\r\nfrom tornado.web import url, StaticFileHandler\r\n\r\ntornado.options.define(\"port\", default=8000, type=int, help=\"runserver on given port\")\r\n\r\n\r\nclass IndexHander(tornado.web.RequestHandler):\r\n\tdef get(self):\r\n\t\tcontext = {\r\n\t\t\t'price':398,\r\n\t\t\t'title':'宽窄巷子+160平大空间+文化保护区双地铁',\r\n\t\t\t'address':'北京市丰台区六里桥地铁',\r\n\r\n\t\t}\r\n\t\tself.render(\"index.html\",context=context) #注意,render的第二个参数是一个关键字参数,需要传入xx=xxx类型的参数,或者**xx这里的xx是一个字典,**表示的是对字典进行解引用,解引用就是一个关键字参数\r\n #render的第一个参数是可变参数类型\r\n\r\nclass NewHander(tornado.web.RequestHandler):\r\n\tdef get(self):\r\n\t\tself.render('newindex.html',text=\"\")\r\n\r\n\tdef post(self):\r\n\t\ttext = self.get_argument('text')\r\n\t\tself.render('newindex.html', text=text)\r\n\r\nclass SetCookie(tornado.web.RequestHandler):\r\n\tdef get(self):\r\n\r\n\t\tcookie = self.get_secure_cookie('count')\r\n\t\tcount = int(cookie) +1 if cookie else 1\r\n\t\tself.set_secure_cookie('count', str(count))\r\n\r\n\t\treturn self.write(str(count))\r\n\r\nclass csrf_test(tornado.web.RequestHandler):\r\n\tdef get(self):\r\n\t\t# self.xsrf_token #这里是用来设置_xsrf这个cookie的值得,若采用模板的{% module xxX%}格式则不需要在这里进行手动测试\r\n\t\tself.render('csrf_test.html')\r\n\tdef post(self):\r\n\t\tself.write(\"ok\")\r\n\r\nclass AsyncHandler(tornado.web.RequestHandler):\r\n\[email protected] #这里的作用相当于python3中最近加入的async模块,此模块对Python的异步操作功能紧进行了封装,用协程的方式实现,当遇到IO阻塞的时候系统能够自动切换到其他未阻塞的协程中去执行\r\n\tdef get(self):\r\n\t\thttp = tornado.httpclient.AsyncHTTPClient()\r\n\t\tresponse = yield http.fetch(\"http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=14.130.112.24\")\r\n\t\t\t\t#如上的作用是当http.fetch阻塞的时候,系统自动的切换到其他协程中去执行,\r\n\t\tif response.error:\r\n\t\t\tself.send_error(500)\r\n\t\telse:\r\n\t\t\tprint('type of data:',type(response.body))\r\n\t\t\tprint(str(response.body))\r\n\t\t\tdata = json.loads(response.body.decode('utf-8'))\r\n\t\t\tself.write('country:%s, provice:%s, city:%s'% (data['country'], data['province'],data['city']))\r\n\r\n\r\nclass Application(tornado.web.Application):\r\n\tdef __init__(self):\r\n\t\thandlers = [\r\n\t\t\turl(r'^/$', IndexHander, name=\"index\"),\r\n\t\t\turl(r'^/cookie$', SetCookie, name=\"cookie\"),\r\n\t\t\turl(r'^/new$', NewHander, name=\"newhander\"),\r\n\t\t\turl(r'/csrf', csrf_test, name=\"csrf_test\"),\r\n\t\t\turl(r'^/async$', AsyncHandler, name=\"AsyncHandler\"),\r\n\t\t]\r\n\r\n\t\tsettings = dict(\r\n\t\t\tstatic_path = os.path.join(current_path,\"static\"), #这里加入静态文件所在的位置\r\n\t\t\ttemplate_path = os.path.join(current_path, \"templates\"), #这里加入模板文件的路劲\r\n\t\t\tdebug = True,\r\n\t\t\tcookie_secret = str(base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes)), #这里使用uuid和base64共同合成了一个随机的字符串,添加到cookie从而形成secure_cookie的机制\r\n\t\t\txsrf_cookies = True,\r\n\t\t\t)\r\n\t\tsuper(Application, self).__init__(handlers,**settings)\r\n\t\ttry:\r\n\t\t\tself.db = pymysql.connect(\r\n\t\t\t\thost = '115.159.62.43',\r\n\t\t\t\tport = 3306,\r\n\t\t\t\tdb = 'LoveHome',\r\n\t\t\t\tuser = 'root',\r\n\t\t\t\tpasswd = 'dzy',\r\n\t\t\t\tcharset = 'utf8'\r\n\t\t\t\t)\r\n\t\texcept Exception as e:\r\n\t\t\tprint(e)\r\n\t\t\tprint('connect to mysql fail!!')\r\n\t\telse:\r\n\t\t\tprint('connect sucess')\r\n\t\t\tself.cursor = self.db.cursor()\r\n\r\n\tdef create_table(self):\r\n\t\tsql = '''\r\n\t\t\tcreate table houses (\r\n \t\t\tid bigint(20) unsigned not null auto_increment comment '房屋编号',\r\n \t\t\ttitle varchar(64) not null default '' comment '标题',\r\n \t\t\tposition varchar(32) not null default '' comment '位置',\r\n \t\t\tprice int not null default 0,\r\n \t\t\tscore int not null default 5,\r\n \t\t\tcomments int not null default 0,\r\n \t\t\tprimary key(id)\r\n\t\t\t)ENGINE=InnoDB default charset=utf8 comment='房屋信息表'\r\n\t\t'''\r\n\t\tself.cursor.execute(sql)\r\n\t\tself.db.commit()\r\n\r\n\t\tself.cursor.close()\r\n\t\tself.db.close()\r\n\r\nif __name__ == '__main__':\r\n\r\n\tcurrent_path = os.path.dirname(__file__)\r\n\r\n\ttornado.options.parse_command_line()\r\n\r\n\t# app = tornado.web.Application([\r\n\t# \turl(r'^/$', IndexHander, name=\"index\"),\r\n\t# \turl(r'^/new$', NewHander, name=\"newhander\"),\r\n\t# \t# url(r'/()',StaticFileHandler, {\"path\":os.path.join(current_path,\"static/html\"), \"default_filename\":\"index.html\"}, name=\"index\"),\r\n\t# \t#注意如上的/后必须加上正则匹配的(),因为StaticFileHandler中的get方法需要参数,不加会报错,这里实现了任意url地址访问静态文件的方式\r\n\r\n\t# \t],\r\n\r\n\t# \tstatic_path = os.path.join(current_path,\"static\"), #这里加入静态文件所在的位置\r\n\t# \ttemplate_path = os.path.join(current_path, \"templates\"), #这里加入模板文件的路劲\r\n\r\n\t# \t debug=True)\r\n\r\n\r\n\tapp = Application()\r\n\t# app.create_table() #这里创建一个表\r\n\t# app.cursor.execute('select * from test_tbl')\r\n\t# result = app.cursor.fetchone()\r\n\t# print(result) \r\n\r\n\thttp_server = tornado.httpserver.HTTPServer(app)\r\n\thttp_server.listen(tornado.options.options.port)\r\n\r\n\ttornado.ioloop.IOLoop.current().start()\r\n\r\n\t\r\n\r\n" }, { "alpha_fraction": 0.7135134935379028, "alphanum_fraction": 0.7675675749778748, "avg_line_length": 18.77777862548828, "blob_id": "69bcec2a549a031dbbc431b32f9194edc59d99d6", "content_id": "3cfdaaecf148ad9acd6d2210e1c1fdeb6358b26d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 185, "license_type": "no_license", "max_line_length": 50, "num_lines": 9, "path": "/django/tiantian/uwsgi.ini", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "[uwsgi]\r\nsocket=0.0.0.0:8000\r\nchdir=/home/ubuntu/user_jason/git/django/tiantian/\r\nwsgi-file=tiantian/wsgi.py\r\nprocesses=1\r\nthreads=1\r\nmaster=True\r\npidfile=uwsgi.pid\r\ndaemonize=uswgi.log" }, { "alpha_fraction": 0.7387518286705017, "alphanum_fraction": 0.7532656192779541, "avg_line_length": 22, "blob_id": "19700a2f3f9c48525a7f5d6574b81f51f7a918f1", "content_id": "81d63f8e24725f69e6284afd3b849170c87aee72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 689, "license_type": "no_license", "max_line_length": 46, "num_lines": 30, "path": "/django/jason_test/booktest/models.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom tinymce.models import HTMLField\n\n# Create your models here.\n\nclass BookInfo(models.Model):\n\tbtitle = models.CharField(max_length=20)\n\tbpub_date = models.DateTimeField()\n\tbread = models.IntegerField(default=0)\n\tbcommet = models.IntegerField(default=0)\n\tisDelete = models.BooleanField(default=False)\n\tbcontent = HTMLField()\n\n\n\n\n\tdef __str__(self):\n\t\treturn self.btitle\n\n\nclass HeroInfo(models.Model):\n\thname = models.CharField(max_length=20)\n\thgender = models.BooleanField(default=1)\n\thBook = models.ForeignKey('BookInfo')\n\thcontent = models.CharField(max_length=100)\n\tisDelete = models.BooleanField(default=False)\n\t\n\n\tdef __str__(self):\n\t\treturn self.hname" }, { "alpha_fraction": 0.5109395384788513, "alphanum_fraction": 0.5186614990234375, "avg_line_length": 23.96666717529297, "blob_id": "8ef7925bdad54a053ca14f2f2318c6736cd978a9", "content_id": "8858b4dab4b03a4fd195a6888f3ca70e8575f9ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 795, "license_type": "no_license", "max_line_length": 86, "num_lines": 30, "path": "/django/jason_test/templates/booktest/editor.html", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\r\n<html>\r\n<head>\r\n <title>editro</title>\r\n {% load static from staticfiles %}\r\n <script type=\"text/javascript\" src=\"{% static 'tiny_mce/tiny_mce.js' %}\"></script>\r\n <script type=\"text/javascript\">\r\n tinyMCE.init({\r\n 'mode':'textareas',\r\n 'theme':'advanced',\r\n 'width':400,\r\n 'height':100\r\n });\r\n </script>\r\n</head>\r\n<body>\r\n<form method=\"post\" action=\"{% url 'booktest:editor_handle' %}\">\r\n\t{% csrf_token %}\r\n <select name=\"select\">\r\n \t{% for index,item in data %}\r\n \t<option value=\"{{index}}\">{{item}}</option>\r\n \t{% endfor %}\r\n </select>\r\n <br>\r\n <textarea name='hcontent'>哈哈,这是啥呀</textarea>\r\n <br>\r\n <input type=\"submit\" value=\"提交\">\r\n</form>\r\n</body>\r\n</html>" }, { "alpha_fraction": 0.6939066052436829, "alphanum_fraction": 0.7050113677978516, "avg_line_length": 25, "blob_id": "18d19f968aa52314f60accc2b8ace72d7e4422c4", "content_id": "6742574c83380bf985e6383ac9cdc181dbdb3b8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3692, "license_type": "no_license", "max_line_length": 89, "num_lines": 135, "path": "/django/tiantian/tiantian_project/views.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse, JsonResponse\nfrom .models import *\nfrom hashlib import sha1\nimport re\n\n# Create your views here.\ndef register(request):\n\treturn render(request,'user/register.html')\n\ndef register_handle(request):\n\t#获取用户提交的信息\n\tname = request.POST['user_name']\n\tpwd = request.POST['pwd']\n\tcpwd = request.POST['cpwd']\n\temail = request.POST['email']\n\n\t#判断密码是否相同\n\tif pwd != cpwd:\n\t\treturn redirect(reverse('tiantian:register'))\n\n\t#判断邮箱是否正确\n\tif re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\\.[com,cn,net]{1,3}$',email) == None:\n\t\treturn redirect(reverse('tiantian:register'))\n\n\t# 密码加密:\n\ts1 = sha1()\n\ts1.update(pwd.encode(\"utf-8\"))\n\tpasswd = s1.hexdigest()\n\t# 加密 end\n\n\tuser = UserInfo()\n\tuser.user_name = name\n\tuser.user_passwd = passwd\n\tuser.user_mail = email\n\tuser.save()\n\n\treturn redirect(reverse('tiantian:login'))\n\n\t# return render(request,)\n\ndef check_username(request):\n\tprint('test')\n\tname = request.GET['name']\n\tprint(name)\n\tcount = UserInfo.objects.filter(user_name=name).count() #这里使用的是count的方式来计算过滤出来的值有多少个\n\tprint(count) #能使用count的原因是过滤出来的是一个数组\n\tif count:\n\t\tprint('1')\n\t\treturn JsonResponse({'status':1})\n\telse:\n\t\tprint('0')\n\t\treturn JsonResponse({'status':0})\n\ndef login(request):\n\treturn render(request,'user/login.html')\n\ndef login_handle(request):\n\tname = request.POST['username']\n\tpwd = request.POST['pwd']\n\t#获取密码的加密格式字符串\n\ts1 = sha1()\n\ts1.update(pwd.encode(\"utf-8\"))\n\tpasswd = s1.hexdigest()\t\n\t# 加密 end\n\n\t#比较用户名\n\tcount = UserInfo.objects.filter(user_name=name).count()\n\tif count == 0:\n\t\treturn redirect(reverse('tiantian:login'))\n\telse:\n\t\tuser = UserInfo.objects.get(user_name=name)\n\t\tif user.user_passwd != passwd:\n\t\t\tstatus = 0\n\t\t\treturn redirect(reverse('tiantian:login'))\n\t\telse:\n\t\t\tstatus = 1\n\t\t\trequest.session['user']=name\n\t\t\trequest.session.set_expiry(300)\n\t\t\treturn redirect(reverse('goods:index'))\n\n\ndef user_center_info(request):\n\tname = request.session.get('user',None)\n\n\tif name == None:\n\t\treturn redirect(reverse('tiantian:login'))\n\n\tuser = UserInfo.objects.get(user_name=name)\n\taddr = user.user_address_info_set.all()\n\tif addr.count() == 0:\n\t\treturn redirect(reverse('tiantian:user_center_info_register'))\n\taddress = []\n\tfor i in addr:\n\t\taddress.append(i)\n\tcontext = {'name':name,'address':address}\n\treturn render(request,'user/user_center_info.html',context)\n\ndef user_center_info_register(request):\n\tname = request.session.get('user',None)\n\tif name == None:\n\t\treturn redirect(reverse('tiantian:login'))\n\telse:\n\t\tuser = UserInfo.objects.get(user_name=name)\n\t\taddr = user.user_address_info_set.all()\n\t\tif addr.count() == 0:\n\t\t\tstatus=0\n\t\telse:\n\t\t\tstatus=1\n\n\t\taddress = []\n\t\tfor i in addr:\n\t\t\taddress.append(i)\n\t\tcontext = {'name':name,'address':address,'status':status}\n\t\tprint(context)\n\treturn render(request,'user/user_center_site.html',context)\n\ndef user_center_info_register_handle(request):\n\ttel_num = request.POST['tel_num']\n\taddress = request.POST['address']\n\n\tif len(tel_num)<5 or len(address)<5:\n\t\treturn redirect(reverse('tiantian:user_center_info_register'))\n\n\tusername = request.session.get('user',None)\n\tif username == None:\n\t\treturn redirect(reverse('tiantian:register'))\n\tuser = UserInfo.objects.get(user_name=username)\n\tuser.user_address_info_set.create(address=address,tel_num=tel_num)\n\treturn redirect(reverse('tiantian:user_center_info'))\n\n\ndef user_center_order(request):\n\treturn render(request,'user/user_center_order.html')\n\n\n" }, { "alpha_fraction": 0.5834854245185852, "alphanum_fraction": 0.5894160866737366, "avg_line_length": 21.52688217163086, "blob_id": "4acbed1b9ad00b00892109b74b83a5f3f2047d29", "content_id": "f3e20646c8ecc72dc9e7f7598cd48f4853e898f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2264, "license_type": "no_license", "max_line_length": 136, "num_lines": 93, "path": "/tornado/project/Ihome/models.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\r\nimport pymysql\r\nimport redis\r\nimport mysql_settings\r\n\r\n############################ mysql 处理类######################################################\r\nclass HandleMysql(object):\r\n\tdef __init__(self):\r\n\r\n\t\ttry:\r\n\t\t\tself.db = pymysql.connect(**mysql_settings.setting)\r\n\t\texcept Exception as e:\r\n\t\t\traise e\r\n\t\telse:\r\n\t\t\tprint('connect mysql sucess')\r\n\t\t\tself.cursor = self.db.cursor()\r\n\r\n\tdef create_table(self):\r\n\r\n\t\tfor sql in mysql_settings.table1:\r\n\t\t\ttry:\r\n\t\t\t\tself.cursor.execute(sql)\r\n\t\t\texcept Exception as e:\r\n\t\t\t\tprint(' %s alerady exist, do not create it again'% (sql.split(\"\\n\")[1].split(\" \")[2]))\r\n\t\t\telse:\r\n\t\t\t\tself.db.commit()\r\n\r\n\tdef get_values_from_mysql(self, sql):\r\n\t\ttry:\r\n\t\t\tself.cursor.execute(sql)\r\n\t\texcept Exception as e:\r\n\t\t\tprint('data did not exist')\r\n\t\t\tresult = None\r\n\t\telse:\t\r\n\t\t\tresult = self.cursor.fetchall()\r\n\r\n\t\treturn result\r\n\r\n\tdef insert_into_tbl(self, sql):\r\n\t\ttry:\r\n\t\t\tself.cursor.execute(sql)\r\n\t\texcept Exception as e:\r\n\t\t\traise(e)\r\n\t\telse:\r\n\t\t\tself.db.commit()\r\n\t\treturn True\r\n\r\n\tdef update_tbl(self, sql):\r\n\t\ttry:\r\n\t\t\tself.cursor.execute(sql)\r\n\t\texcept Exception as e:\r\n\t\t\traise(e)\r\n\t\telse:\r\n\t\t\tself.db.commit()\r\n\t\treturn True\r\n\r\n\tdef close_mysql():\r\n\t\tself.cursor.close()\r\n\t\tself.db.close()\r\n\r\n\r\n\r\n\r\n\r\n##################################### Redis 处理类####################################################\r\n\r\nclass HandRedis(object):\r\n\t######## connect to redis#########\r\n\tdef __init__(self):\r\n\t\ttry:\r\n\t\t\tself.redisInstance = redis.StrictRedis(host=\"localhost\", port=\"6379\") #这里的host只能使用localhost来进行连接,因为redis没有设置密码,且redis绑定了127.0.0.1这个地址\r\n\t\texcept Exception as e:\r\n\t\t\tprint(\" connect to redis failed \")\r\n\t\t\traise(e)\r\n\t\telse:\r\n\t\t\tprint(\" connect redis sucess\")\r\n\r\n\tdef set_value(self, key, value):\r\n\t\tresult = self.redisInstance.set(key, value)\r\n\t\tprint('set key,value',key,value)\r\n\r\n\tdef get_value(self, key):\r\n\t\tresult = self.redisInstance.get(key)\r\n\t\t# print('key ,value:',key,result)\r\n\t\treturn result\r\n\r\n\tdef set_expire(self, key, date):\r\n\t\tresult = self.redisInstance.expire(key, date)\r\n\t\tprint('set expire time key,date:',key,date)\r\n\r\n\tdef del_value(self, key):\r\n\t\tresult = self.redisInstance.delete(key)\r\n\t\tprint('delete',key)\r\n\t\treturn result\r\n\r\n" }, { "alpha_fraction": 0.5188916921615601, "alphanum_fraction": 0.5843828916549683, "avg_line_length": 18.799999237060547, "blob_id": "71f4e84e554755384c0cd031d02cb94b15a339ba", "content_id": "6a3b6f9a549de13f105266748844eaa02691318b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 397, "license_type": "no_license", "max_line_length": 61, "num_lines": 20, "path": "/Python/plus/net/receive_data.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "import socket\n\ndef main():\n receive = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n\n receive.bind( ('',7788) )\n\n receive.sendto(b'test',('192.168.0.107', 8081) )\n\n while True:\n re_data = receive.recvfrom(1024)\n data,ipinfo = re_data\n receive.sendto(data,ipinfo)\n print(data.decode('gb2312'))\n\n receive.close()\n\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.6591100096702576, "alphanum_fraction": 0.6612090468406677, "avg_line_length": 28.060976028442383, "blob_id": "a2d97895a54972443c74c32f10d1ee5f07775db6", "content_id": "1592057bc085ff5a7c9206432df946588d5f918e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2706, "license_type": "no_license", "max_line_length": 83, "num_lines": 82, "path": "/django/jason_test/booktest/views.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nfrom django.conf import settings\nfrom .models import *\nfrom django.core.paginator import Paginator\nimport json\n# Create your views here.\n\ndef index(request):\n return render(request,'booktest/index.html')\n # return HttpResponse('ok')\n\n\ndef upload(request):\n\n if request.method == 'POST':\n picture = request.FILES['picture']\n fname = '%s/cars/%s'%(settings.MEDIA_ROOT, picture.name)\n # return HttpResponse(settings.MEDIA_ROOT)\n with open(fname,'wb') as pic:\n for c in picture.chunks():\n pic.write(c)\n return HttpResponse('ok')\n else:\n return HttpResponse('error')\ndef my_custom_page_not_found_view(request):\n return HttpResponse('fail 404 fail')\n\ndef pages(request,id):\n if id == '':\n id = '1'\n list = HeroInfo.objects.all()\n paginator = Paginator(list,5)\n page = paginator.page(int(id))\n context = {'page':page}\n\n return render(request,'booktest/pages.html',context)\n\ndef book_index(request):\n return render(request,'booktest/book_index.html')\n\ndef ajax_get(request):\n # print('hello')\n book_list = BookInfo.objects.all()\n # print(book_list)\n # return JsonResponse({'data':book_list}) #这样返回数据会报错\n l = []\n for list in book_list:\n l.append((list.id,list.btitle)) #这里必须要将获得的book_list进行遍历,取出元素放在一个数组中才行,否则会报错\n return JsonResponse({'data':l}) #具体为什么这样的原因还有待解析\n\ndef get_bookinfo(request):\n print('test')\n id = request.GET['id'] #这里使用的是ajax的方式进行数据的传递\n print(id)\n list=HeroInfo.objects.filter(hBook_id=id)#这里的filter返回的是一个查询集,并不是一个对象,而是一个对象集合\n print(list)\n hero_list = []\n for i in list:\n hero_list.append((i.id,i.hname))\n return JsonResponse({'data':hero_list})\n\n#富文本编辑器\ndef editor(request):\n data = BookInfo.objects.all()\n list = []\n for l in data:\n list.append([l.id,l.btitle])\n print(list)\n context = {'data':list}\n return render(request,'booktest/editor.html',context)\n\ndef editor_handle(request):\n html = request.POST['hcontent'] #此处获取的是大文本提交的内容\n id = request.POST['select'] #此处获取的是要提交的id号\n print('id:',id)\n print(html)\n book = BookInfo.objects.get(pk=id) #注意filter方法返回的是一个查询集合,是一个集合,get返回的是一个对象\n print(book.btitle)\n book.bcontent = html\n book.save()\n return HttpResponse('ok')" }, { "alpha_fraction": 0.7318037748336792, "alphanum_fraction": 0.7436708807945251, "avg_line_length": 31.210525512695312, "blob_id": "f10f0c426ab7d6bab2d161fb8e49d5a09accad59", "content_id": "49b8cc75b7eaf62390f3a17b0e3e2dacf7765818", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1646, "license_type": "no_license", "max_line_length": 125, "num_lines": 38, "path": "/tornado/test/01_hello.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "import tornado.web\r\nimport tornado.ioloop\r\nimport tornado.httpserver\r\nimport tornado.options\r\nfrom tornado.web import url\r\n\r\ntornado.options.define(\"port\",default=8000,type=int, help=\"run server on the given port.\") #这里定义了port参数,这样就可以在命令行启动的时候将改参数传入了\r\ntornado.options.define(\"itcast\",default=[],type=str, multiple=True, help=\"itcast subjects.\")#这里定义了一个多参数变量,命令行传参的时候需要用,号隔开\r\nclass IndexHander(tornado.web.RequestHandler):\r\n\r\n\tdef get(self):\r\n\t\tself.write(\"hello world\")\r\n\r\nclass SecondHander(tornado.web.RequestHandler):\r\n\tdef initialize(self,subject):\r\n\t\tself.subject = subject\r\n\r\n\tdef get(self):\r\n\t\tself.write(self.subject)\r\n\r\n\r\nif __name__ == '__main__':\r\n\ttornado.options.parse_config_file(\"./config\") #这里定义了解析命令行参数的函数,命令行中的参数通过这个函数进行解析\r\n\tprint (tornado.options.options.itcast)#这里打印出itcase参数,注意解析后的参数有两个options\r\n\r\n\tapp = tornado.web.Application(\r\n\t\t[url(r'/',IndexHander,name=\"index\"),\r\n\r\n\t\t url(r'/cpp',SecondHander,{\"subject\":\"c++\"},name=\"cpp\"),\r\n\r\n\t\t], debug=True) #这里的作用是添加路由,这里创建了一个应用app\r\n\t# app.listen(8000) #这里监听8000端口\r\n\r\n\thttp_server = tornado.httpserver.HTTPServer(app)\r\n\thttp_server.bind(tornado.options.options.port)\r\n\thttp_server.start(1)#0表示的是开启的进程数目和所使用的的服务器的核心数有关,当大于0的时候就是所设置的进程数目\r\n\r\n\ttornado.ioloop.IOLoop.current().start() #此处的函数才是真正运行服务器\r\n\r\n" }, { "alpha_fraction": 0.47216036915779114, "alphanum_fraction": 0.4922049045562744, "avg_line_length": 16.30769157409668, "blob_id": "a017161c8c7d0b7d951873d0c6bf136b21dd5923", "content_id": "7c78d70fccab489632e259f25a404f25fc4f5e0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 449, "license_type": "no_license", "max_line_length": 39, "num_lines": 26, "path": "/Python/plus/Process/green.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "from greenlet import greenlet\nfrom time import sleep\ndef funca():\n while True:\n print('-----A-------')\n gr2.switch()\n print('---switch to funca---')\n sleep(0.5)\n\ndef funcb():\n while True:\n print('----B---------')\n gr1.switch()\n print('---switch to funcb----')\n sleep(0.5)\n\n\n\ngr1 = greenlet(funca)\ngr2 = greenlet(funcb)\n\ndef main():\n gr1.switch()\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.7162004709243774, "alphanum_fraction": 0.7255244851112366, "avg_line_length": 29.814815521240234, "blob_id": "1d1d112af929e810ce54d05efcd177d7f37405e3", "content_id": "804eb7bb57f73fbb11ed98f67edd732a3a0ad709", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2086, "license_type": "no_license", "max_line_length": 90, "num_lines": 54, "path": "/tornado/test/02_input.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "import tornado.web\r\nimport tornado.ioloop\r\nimport tornado.httpserver\r\nimport tornado.options\r\nfrom tornado.web import url\r\n\r\n\r\ntornado.options.define(\"port\", default=8000, type=int, help=\"runserver on given port\")\r\n\r\nclass IndexHander(tornado.web.RequestHandler):\r\n\r\n\tdef post(self):\r\n\r\n\t\tpara_query = self.get_query_arguments('a') #这里的作用是在url中获取a的参数值,获取的是一个列表,存放的是a的所有值\r\n\t\tpara_body = self.get_body_arguments('b')\r\n\t\tprint('body',para_body)\r\n\t\tprint('query',para_query)\r\n\t\tself.write(\"ok\")\r\n\r\nclass SecondHander(tornado.web.RequestHandler):\r\n\tdef post(self):\r\n\t\tprint(self.request.method)\r\n\t\tprint(self.request.uri)\r\n\t\tprint(self.request.host)\r\n\t\tprint(self.request.headers)\r\n\r\nclass ThirdHander(tornado.web.RequestHandler):\r\n\tdef post(self):\r\n\t\tfiles = self.request.files #获取request中所有的files类型的文件,这些文件是用字典的形式组织的\r\n\t\timg = files.get('image1') #从这些字典类型数据中获取指定image图片信息\r\n\t\tprint(img[0]['filename']) #获取的img信息也是一个列表信息,即相同名字image1可以传入多张file文件,列表中的值又是字典类型的数据\r\n\r\n\t\twith open('/home/ubuntu/user_jason/temp/image.jpg','wb') as f: #将从request中获取的图片信息写入到文件中去\r\n\t\t\tf.write(img[0]['body']) #body中存放的就是image1的信息,这里将image1中的信息写入到新创建的文件中\r\n\t\tself.write('ok')\r\n\r\nclass FiveHander(tornado.web.RequestHandler):\r\n\tdef initialize(self,arg1): #这里的参数接收的是路由中传递过来的字典类型参数\r\n\t\tprint(arg1)\r\n\r\nif __name__ == '__main__':\r\n\ttornado.options.parse_command_line()\r\n\r\n\tapp = tornado.web.Application([\r\n\t\turl(r'/',IndexHander,name=\"index\"),\r\n\t\turl(r'/second',SecondHander,name=\"second\"),\r\n\t\turl(r'/third',ThirdHander,name=\"third\"),\r\n\t\turl(r'/five',FiveHander,{'arg1':'111'},name=\"five\"),\r\n\t\t], debug=True)\r\n\r\n\thttp_server = tornado.httpserver.HTTPServer(app)\r\n\thttp_server.listen(tornado.options.options.port)\r\n\r\n\ttornado.ioloop.IOLoop.current().start()" }, { "alpha_fraction": 0.6877323389053345, "alphanum_fraction": 0.6877323389053345, "avg_line_length": 28.88888931274414, "blob_id": "02944e9f081228c6a7f67ea2059fdc691f0c7050", "content_id": "3393a72a01b15caa7bf20a7d19657b77e73df918", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 429, "license_type": "no_license", "max_line_length": 95, "num_lines": 9, "path": "/Python/plus/net/web/web_framework/readme.txt", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\n#########################\n\n# Note:这里是把web_service这个python程序当做了主体,通过在web_service程序中\n 来调用web框架\n#这里使用的是wsgi的网关接口协议,主要的就是在服务器函数中调用application(\n environ,start_repose)函数,在framework脚本中实现这个application函数。而start_respose正好反过来,service中实现,frame中调用\n\n\n#########################" }, { "alpha_fraction": 0.6656105518341064, "alphanum_fraction": 0.6702412962913513, "avg_line_length": 57.49275207519531, "blob_id": "fa872202afa6f2df8e908d5f2063ae7a70e92b7d", "content_id": "b82c71c4172e9158fe064dcdda1af7c972af00e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4329, "license_type": "no_license", "max_line_length": 190, "num_lines": 69, "path": "/tornado/project/Ihome/Server.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "import tornado.web\r\nimport tornado.options\r\nimport tornado.httpserver\r\nimport tornado.ioloop\r\nimport os\r\nimport models\r\nimport Handlers\r\nimport base64, uuid\r\nfrom tornado.web import url, StaticFileHandler\r\n\r\ntornado.options.define('port', default=8000, type=int, help=' runserver on given port')\r\n\r\n\r\nclass Application(tornado.web.Application):\r\n\tdef __init__(self):\r\n\t\t################# create mysql object #######\r\n\t\tself.mysql = models.HandleMysql()\r\n\t\tself.mysql.create_table()\r\n\t\t################# end #######################\r\n\t\t################# create redis object #######\r\n\t\tself.redis = models.HandRedis()\r\n\t\t################# end #######################\r\n\r\n\t\t################# 进行域名地址的映射 ##########\r\n\t\tsuper(Application, self).__init__(\r\n\t\t[\r\n\t\t# url(r'^/$', Handlers.IndexHandler, name=\"IndexHandler\"), #这里不采用get中的render返回index的原因是因为,index.html中使用了index.js脚本中的$.get等方式来和后台通讯从而获得数据,而render方式处理模板的时候会对模板进行解析处理会报错,只能通过直接加载index.html的方式\r\n\t\turl(r'/api/house/index', Handlers.House_index, dict(database = self.mysql, database_redis = self.redis), name=\"House_index\"),\r\n\t\turl(r'^/register$', Handlers.House_register, dict(database = self.mysql, database_redis = self.redis), name=\"House_register\"),\r\n\t\turl(r'^/api/piccode$', Handlers.PicCodeHandler, dict(database = self.mysql, database_redis = self.redis), name=\"PicCodeHandler\"),\r\n\t\turl(r'^/api/smscode$', Handlers.Smscode, dict(database = self.mysql, database_redis = self.redis), name=\"Smscode\"),\r\n\t\turl(r'^/api/register$', Handlers.Register_verity, dict(database = self.mysql, database_redis = self.redis), name=\"Register_verity\"),\r\n\t\turl(r'^/api/login$', Handlers.Login_verity, dict(database = self.mysql, database_redis = self.redis), name=\"database = self.mysql\"),\r\n\t\turl(r'^/api/check_login$', Handlers.Check_login, dict(database = self.mysql, database_redis = self.redis), name=\"Check_login\"),\r\n\t\turl(r'^/api/profile$', Handlers.Personal_info, dict(database = self.mysql, database_redis = self.redis), name=\"Personal_info\"),\r\n\t\turl(r'^/api/profile/name$', Handlers.Personal_name, dict(database = self.mysql, database_redis = self.redis), name=\"Personal_name\"),\r\n\t\turl(r'^/api/profile/avatar$', Handlers.Personal_img, dict(database = self.mysql, database_redis = self.redis), name=\"Personal_img\"),\r\n\t\turl(r'^/api/house/info$', Handlers.House_info, dict(database = self.mysql, database_redis = self.redis), name=\"House_info\"),\r\n\t\turl(r'^/api/order$', Handlers.House_reserve, dict(database = self.mysql, database_redis = self.redis), name=\"House_reserve\"),\r\n\t\turl(r'^/api/order/my$', Handlers.Show_order, dict(database = self.mysql, database_redis = self.redis), name=\"Show_order\"),\r\n\t\turl(r'^/api/profile/auth$', Handlers.Real_name_verity, dict(database = self.mysql, database_redis = self.redis), name=\"Real_name_verity\"),\r\n\t\turl(r'^/api/house/my$', Handlers.Myhouse_show, dict(database = self.mysql, database_redis = self.redis), name=\"Myhouse_show\"),\r\n\t\turl(r'^/api/house/list2$', Handlers.House_list_handler, dict(database = self.mysql, database_redis = self.redis), name = \"House_list_handler\"),\r\n\t\turl(r'^/api/house/area$', Handlers.Area_info_handler, dict(database = self.mysql, database_redis = self.redis), name=\"Area_info_handler\"),\r\n\t\turl(r'^/api/logout$', Handlers.Login_out, dict(database = self.mysql, database_redis = self.redis), name = \"Login_out\"),\r\n\t\turl(r'/(.*)',StaticFileHandler, {\"path\":os.path.join(os.path.dirname(__file__),\"template\"), \"default_filename\":\"index.html\"}, name=\"index\"),\r\n\t\t],\r\n\t\t################# end ########################\r\n\t\tdebug = True, \r\n\t\tstatic_path = os.path.join(os.path.dirname(__file__), 'static'),\r\n\t\ttemplate_path = os.path.join(os.path.dirname(__file__), 'template'),\r\n\t\tcookie_secret = str(base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes)), #这里使用uuid和base64共同合成了一个随机的字符串,添加到cookie从而形成secure_cookie的机制\r\n\t\txsrf_cookies = True,\r\n\t\t)\r\n\r\n\r\ndef main():\r\n\ttornado.options.parse_command_line()\r\n\r\n\tapp = Application()\r\n\r\n\thttp_server = tornado.httpserver.HTTPServer(app)\r\n\thttp_server.listen(8000) \r\n\r\n\ttornado.ioloop.IOLoop.current().start()\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()" }, { "alpha_fraction": 0.6610939502716064, "alphanum_fraction": 0.6767218112945557, "avg_line_length": 46.68141555786133, "blob_id": "63e902ce95656bace89d9ed71e2ff69b53322596", "content_id": "61296bb14e57d20be9f9ce6f31dd2f0bda2c837d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6109, "license_type": "no_license", "max_line_length": 103, "num_lines": 113, "path": "/tornado/project/Ihome/mysql_settings.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\r\n\r\nsetting = dict(\r\n\thost = '115.159.62.43',\r\n\tport = 3306,\r\n\tdb = 'Ihome',\r\n\tuser = 'root',\r\n\tpasswd = 'dzy',\r\n\tcharset = 'utf8',\r\n\t)\r\n\r\ntable1 = [\r\n\t'''\r\n\tCREATE TABLE ih_user_profile (\r\n \tup_user_id bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',\r\n \tup_name varchar(32) NOT NULL COMMENT '昵称',\r\n \tup_mobile char(11) NOT NULL COMMENT '手机号',\r\n \tup_passwd varchar(64) NOT NULL COMMENT '密码',\r\n \tup_real_name varchar(32) NULL COMMENT '真实姓名',\r\n \tup_id_card varchar(20) NULL COMMENT '身份证号',\r\n \tup_avatar varchar(128) NULL COMMENT '用户头像',\r\n \tup_admin tinyint NOT NULL DEFAULT '0' COMMENT '是否是管理员,0-不是,1-是',\r\n \tup_utime datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后更新时间',\r\n \tup_ctime datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',\r\n \tPRIMARY KEY (up_user_id),\r\n \tUNIQUE (up_name),\r\n \tUNIQUE (up_mobile)\r\n\t) ENGINE=InnoDB AUTO_INCREMENT=10000 DEFAULT CHARSET=utf8 COMMENT='用户信息表';\r\n\t''',\r\n\t'''\r\n\tCREATE TABLE ih_area_info (\r\n \tai_area_id bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '区域id',\r\n \tai_name varchar(32) NOT NULL COMMENT '区域名称',\r\n \tai_ctime datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',\r\n \tPRIMARY KEY (ai_area_id)\r\n\t) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='房源区域表';\r\n\t''',\r\n\t'''\r\n\tCREATE TABLE ih_house_info (\r\n \thi_house_id bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '房屋id',\r\n \thi_user_id bigint unsigned NOT NULL COMMENT '用户ID',\r\n \thi_title varchar(64) NOT NULL COMMENT '房屋名称',\r\n \thi_price int unsigned NOT NULL DEFAULT '0' COMMENT '房屋价格,单位分',\r\n \thi_area_id bigint unsigned NOT NULL COMMENT '房屋区域ID',\r\n \thi_address varchar(512) NOT NULL DEFAULT '' COMMENT '地址',\r\n \thi_room_count tinyint unsigned NOT NULL DEFAULT '1' COMMENT '房间数',\r\n \thi_acreage int unsigned unsigned NOT NULL DEFAULT '0' COMMENT '房屋面积',\r\n \thi_house_unit varchar(32) NOT NULL DEFAULT '' COMMENT '房屋户型',\r\n \thi_capacity int unsigned NOT NULL DEFAULT '1' COMMENT '容纳人数',\r\n \thi_beds varchar(64) NOT NULL DEFAULT '' COMMENT '床的配置',\r\n \thi_deposit int unsigned NOT NULL DEFAULT '0' COMMENT '押金,单位分',\r\n \thi_min_days int unsigned NOT NULL DEFAULT '1' COMMENT '最短入住时间',\r\n \thi_max_days int unsigned NOT NULL DEFAULT '0' COMMENT '最长入住时间,0-不限制',\r\n \thi_order_count int unsigned NOT NULL DEFAULT '0' COMMENT '下单数量',\r\n \thi_verify_status tinyint NOT NULL DEFAULT '0' COMMENT '审核状态,0-待审核,1-审核未通过,2-审核通过',\r\n \thi_online_status tinyint NOT NULL DEFAULT '1' COMMENT '0-下线,1-上线',\r\n \thi_index_image_url varchar(256) NULL COMMENT '房屋主图片url',\r\n \thi_utime datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后更新时间',\r\n \thi_ctime datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',\r\n \tPRIMARY KEY (hi_house_id),\r\n \tKEY `hi_status` (hi_verify_status, hi_online_status),\r\n \tCONSTRAINT FOREIGN KEY (`hi_user_id`) REFERENCES `ih_user_profile` (`up_user_id`),\r\n \tCONSTRAINT FOREIGN KEY (`hi_area_id`) REFERENCES `ih_area_info` (`ai_area_id`)\r\n\t) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='房屋信息表';\r\n\t''',\r\n\t'''\r\n\tCREATE TABLE ih_house_facility (\r\n \thf_id bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '自增id',\r\n \thf_house_id bigint unsigned NOT NULL COMMENT '房屋id',\r\n \thf_facility_id int unsigned NOT NULL COMMENT '房屋设施',\r\n \thf_ctime datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',\r\n \tPRIMARY KEY (hf_id),\r\n \tCONSTRAINT FOREIGN KEY (`hf_house_id`) REFERENCES `ih_house_info` (`hi_house_id`)\r\n\t) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='房屋设施表';\r\n\t''',\r\n\t'''\r\n\tCREATE TABLE ih_facility_catelog (\r\n \tfc_id int unsigned NOT NULL AUTO_INCREMENT COMMENT '自增id',\r\n \tfc_name varchar(32) NOT NULL COMMENT '设施名称',\r\n \tfc_ctime datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',\r\n \tPRIMARY KEY (fc_id)\r\n\t) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='设施型录表';\r\n\t''',\r\n\t'''\r\n\tCREATE TABLE ih_order_info (\r\n \toi_order_id bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '订单id',\r\n \toi_user_id bigint unsigned NOT NULL COMMENT '用户id',\r\n \toi_house_id bigint unsigned NOT NULL COMMENT '房屋id',\r\n \toi_begin_date date NOT NULL COMMENT '入住时间',\r\n \toi_end_date date NOT NULL COMMENT '离开时间',\r\n \toi_days int unsigned NOT NULL COMMENT '入住天数',\r\n \toi_house_price int unsigned NOT NULL COMMENT '房屋单价,单位分',\r\n \toi_amount int unsigned NOT NULL COMMENT '订单金额,单位分',\r\n \toi_status tinyint NOT NULL DEFAULT '0' COMMENT '订单状态,0-待接单,1-待支付,2-已支付,3-待评价,4-已完成,5-已取消,6-拒接单',\r\n \toi_comment text NULL COMMENT '订单评论',\r\n \toi_utime datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后更新时间',\r\n \toi_ctime datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',\r\n \tPRIMARY KEY (oi_order_id),\r\n \tKEY `oi_status` (oi_status),\r\n \tCONSTRAINT FOREIGN KEY (`oi_user_id`) REFERENCES `ih_user_profile` (`up_user_id`),\r\n \tCONSTRAINT FOREIGN KEY (`oi_house_id`) REFERENCES `ih_house_info` (`hi_house_id`)\r\n\t) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='订单表';\r\n\t''',\r\n\t'''\r\n\tCREATE TABLE ih_house_image (\r\n \thi_image_id bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '图片id',\r\n \thi_house_id bigint unsigned NOT NULL COMMENT '房屋id',\r\n \thi_url varchar(256) NOT NULL COMMENT '图片url',\r\n \thi_ctime datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',\r\n \tPRIMARY KEY (hi_image_id),\r\n \tCONSTRAINT FOREIGN KEY (hi_house_id) REFERENCES ih_house_info (hi_house_id)\r\n\t) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='房屋图片表';\r\n\t''',\r\n\r\n]" }, { "alpha_fraction": 0.5652173757553101, "alphanum_fraction": 0.5652173757553101, "avg_line_length": 23.33333396911621, "blob_id": "afa41c9a66ec089cd1d4437004bbfc040f6d3660", "content_id": "85503c18b5bf8bb551bdadb6badb39ce53549f23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 368, "license_type": "no_license", "max_line_length": 108, "num_lines": 15, "path": "/Python/basic/class_func/class_new.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\n\nclass Dog(object):\n\n def __init__(self):\n print(\"init the var\")\n\n def __new__(cls): # the func is used to create a new class , \n print(\"create a class\")\n return object.__new__(cls) # use the parent __new__ func to create a class,the arg need transfer cls\n \n def __str__(self):\n return \"Hello world\"\n\n\ndog = Dog()\nprint(dog)\n\n" }, { "alpha_fraction": 0.5769230723381042, "alphanum_fraction": 0.6009615659713745, "avg_line_length": 14.923076629638672, "blob_id": "e5bd0ac5d4ab2a7615b0282230308e42c12d67b9", "content_id": "1b12735a821c4b3b0bca1e978128654fba17636a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "no_license", "max_line_length": 45, "num_lines": 13, "path": "/Python/plus/Process/fork.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "import os\nimport time\n\npid=os.fork()\n\nif pid == 0:\n\twhile True:\n\t\tprint('1-----This is a son process-------')\n\t\ttime.sleep(1)\nelse:\n\twhile True:\n\t\tprint('2-----This is a parrent process---')\n\t\ttime.sleep(1)\n\n" }, { "alpha_fraction": 0.6041666865348816, "alphanum_fraction": 0.6348039507865906, "avg_line_length": 28.125, "blob_id": "7a74eeb8392060be412cfc67675b3db159c0c517", "content_id": "134b8a8244dc87301334226103851dbf2ca8adeb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2380, "license_type": "no_license", "max_line_length": 147, "num_lines": 56, "path": "/Python/plus/net/tftp/tftp_load.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\nimport struct \n\nimport socket\n\ndef download_file(name,data):\n\tf = open(name,'ab') #注意这里一定要以字节追加的形式打开,因为tftp发送过来的就是字节型的数据,所以将字节型的数据直接写入到文件中即可。其他形式不可以\n\tf.write(data)\n\n\tf.close()\n\n\n\ndef main():\n name = input('---please input which file you want to load----')\n struct_info = '!H' + str(len(name)) + 'sb5sb'\n print(struct_info)\n\n udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #创建UDP对象\n\n send_data = struct.pack(struct_info, 1, name.encode('utf-8'), 0, b\"octet\", 0)#此处的作用是使用struct模块对要发送的数据按照tftp的信息格式进行封装,具体的信息见课件中tftp的信息格式\n\n udp_socket.sendto(send_data, ('192.168.0.107', 69))#这里对上面封装好了的数据发往69号端口,此端口是tftp默认的首次通信端口,接下来的数据通信端口就不在是69号端口了,而是采用的动态端口的方式,所以再往69端口发数据就不会有任何响应\n\n while True:\n receive_data = udp_socket.recvfrom(1024)#再发送完数据后,tftp就会返回进行封装了的512字节的数据,这里接收的时候并不需要绑定端口,因为tftp会根据所接收到的数据解析出所用的端口\n\n data,ip_info = receive_data #对接收到的信息进行解析,因为网络通信中接收到的信息是一个tuple类型的数据,tuple的首个元素是封装的数据,第二个元素是ip地址信息\n\n cmd_info = data[:4]#获取数据中前四个字节的信息,根据tftp协议,前四个字节有特殊作用,4个字节后的512个字节才是真正的数据\n\n cmd_info = struct.unpack('!HH',cmd_info)#这里是将接收到的数据进行解析,这里解析到的cmd_info是一个tuple,(3,1)\n \n\n print(cmd_info)\n print(data[4:])\n\n if cmd_info[0] == 3:\n download_file(name,data[4:])\n if len(data[4:])<512:\n print('---receive data end-------')\n break\n \n print('------------receive next 512 bytes data---------')\n ACK = struct.pack('!HH',4,cmd_info[1])\n udp_socket.sendto(ACK,ip_info)\n else:\n break\n\n\n\n udp_socket.close()\n\n\n\nif __name__ == '__main__':\n\tmain()\n" }, { "alpha_fraction": 0.7108433842658997, "alphanum_fraction": 0.7108433842658997, "avg_line_length": 15.300000190734863, "blob_id": "7752696717fdee3dff79e68b0f3eaad2d2ab4fca", "content_id": "fa525c89a487deea39257d01d8d75e523249532f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 166, "license_type": "no_license", "max_line_length": 37, "num_lines": 10, "path": "/Python/plus/C_lib/readme.md", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\n\n# As show,we can include a c Librarya\n\n follow bellow steps\n\nfirst: gcc test.c -shared -o test.so\nfinally: python c_lib.py\n\n\n\nSo we can use C programme in python \n" }, { "alpha_fraction": 0.5724366903305054, "alphanum_fraction": 0.5824571251869202, "avg_line_length": 29.80695915222168, "blob_id": "222c5c618c19700aee32bc2c12e35e52f58515a9", "content_id": "4faeec2cf69d0103abeab6ab59b2e29be2114ebd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31602, "license_type": "no_license", "max_line_length": 254, "num_lines": 891, "path": "/tornado/project/Ihome/Handlers.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "import tornado.web\r\nimport json\r\nimport models\r\nimport logging\r\nimport random\r\nfrom hashlib import sha1\r\nimport base64, uuid\r\nfrom utils.captcha.captcha import captcha\r\nfrom utils.commons import required_login\r\nfrom libs.yuntongxun.SendTemplateSMS import ccp\r\n\r\nImage_id = \"1111\"\r\nclass BaseHandler(tornado.web.RequestHandler):\r\n\tdef initialize(self, database, database_redis):\r\n\t\tself.database = database\r\n\t\tself.redis = database_redis\r\n\r\n\tdef prepare(self):\r\n\t\t\"\"\"预解析json数据\"\"\" #这里判断请求的类型是否是json类型\r\n\t\tself.xsrf_token\r\n\t\t# print(self.request.body)\r\n\t\tif self.request.headers.get(\"Content-Type\", \"\").startswith(\"application/json\"):\r\n\t\t\tself.json_args = json.loads(self.request.body.decode(\"utf-8\")) #对body中的json数据进行解析成字典的类型,lods是解析,dumps是翻译成json类\r\n\t\telse:\r\n\t\t\tself.json_args = {}\r\n\r\n\tdef get_current_user(self):\r\n\t\tsession_id = self.get_secure_cookie('session_id')\r\n\t\tif session_id == None:\r\n\t\t\tprint(\" not login!!!\")\r\n\t\t\treturn None\r\n\t\tvalue = self.redis.get_value(session_id)\r\n\t\tif value == None or len(value) == 0:\r\n\t\t\tprint(\"not login!!!\")\r\n\t\t\treturn None\r\n\r\n\t\treturn value\r\n\r\n###################这里实现一个主页处理函数#########################################\r\nclass House_index(BaseHandler):\r\n\tdef get(self):\r\n\t\tprint('================================')\r\n\t\tsql = \"select hi_house_id,hi_title,hi_index_image_url from ih_house_info order by hi_order_count desc limit 3;\"\r\n\t\tresult = self.database.get_values_from_mysql(sql)\r\n\t\tprint(result)\r\n\r\n\t\thouses = []\r\n\t\tfor value in result:\r\n\t\t\thouses.append({'house_id':value[0], 'img_url':value[2], 'title':value[1]})\r\n\r\n\r\n\t\tsql = \" select * from ih_area_info\"\r\n\t\tresult = self.database.get_values_from_mysql(sql)\r\n\t\t# print(result)\r\n\r\n\t\tarea = []\r\n\t\tfor value in result:\r\n\t\t\tarea.append({'area_id':value[0], 'name':value[1]})\r\n\t\t# print(area)\r\n\r\n\t\tjson_houses = json.dumps(houses) #注意在tornado中self.write(xx)中的xx要是字典型的数据,这样tornado就会自动将xx转换为json数据传输\r\n\t\tjson_areas = json.dumps(area) #注意,字典型数据xx中的子元素的值若是个字典或数组等组合类型的值。需要将子元素的值转换为json型数据包裹在外层自动类型变量中进行传输\r\n\t\tresp = '{\"errcode\":\"0\", \"errmsg\":\"OK\", \"houses\":%s, \"areas\":%s}' % (json_houses, json_areas)\r\n\t\tself.write(resp) #这里就是返回数据,自动将字典类型变量转换为json数据类型\r\n\t\tself.set_header(\"Content-Type\", \"application/json; charset=UTF-8\") #设置传输类型的头部为 json类型,若是不设置可能会出错\r\n\t\t# self.write('ok') #以上的这么多设置主要是针对$ajax类型的数据请求,因为javascript擅长解析的是json类型数据\r\n\r\n#############这里实现的是一个检查用户是否登录的功能 ########\r\nclass Check_login(BaseHandler):\r\n\tdef get(self):\r\n\t\tsession_id = self.get_secure_cookie('session_id')\r\n\t\t# print(\"session_id======\",session_id)\r\n\t\tuser_data = {}\r\n\t\tif session_id == None:\r\n\t\t\tprint(\"session_id cookie do not exist\")\r\n\t\t\tdata = {\r\n\t\t\t\t\"errcode\":1,\r\n\t\t\t\t\"data\":None,\r\n\t\t\t}\r\n\t\telse:\r\n\t\t\tvalue = self.redis.get_value(session_id)\r\n\t\t\tif value == None:\r\n\t\t\t\tdata = {\r\n\t\t\t\t\"errcode\":1,\r\n\t\t\t\t\"data\":None,\r\n\t\t\t\t}\r\n\t\t\telse:\r\n\t\t\t\tsql = 'select up_name from ih_user_profile where up_mobile=\"%s\" '%value.decode(\"utf-8\")\r\n\t\t\t\tresult = self.database.get_values_from_mysql(sql)\r\n\t\t\t\tif result == None or len(result)==0:\r\n\t\t\t\t\tprint(\"session_id do not exist in redis\")\r\n\t\t\t\t\tdata = {\r\n\t\t\t\t\t\"errcode\":1,\r\n\t\t\t\t\t\"data\":None,\r\n\t\t\t\t\t}\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint(\" login user:\", value)\r\n\t\t\t\t\tuser_data['name'] = result\r\n\t\t\t\t\t# user_data = json.dumps(user_data)\r\n\t\t\t\t\tdata = {\r\n\t\t\t\t\t\t\"errcode\":0,\r\n\t\t\t\t\t\t\"data\":user_data,\r\n\t\t\t\t\t}\r\n\r\n\t\tself.write(data)\r\n\t\tself.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\r\n\r\n############# 这里实现的是注册的主页面显示功能 ############\r\n\r\nclass House_register(BaseHandler):\r\n\tdef get(self):\r\n\t\tprint(\"register============\")\r\n\t\tself.render('register.html')\r\n\r\n##############验证码功能#################################\r\n\r\nclass PicCodeHandler(BaseHandler): #前端的img中的src是一个GET方式的请求\r\n\t\"\"\"图片验证码\"\"\"\r\n\tdef get(self):\r\n\t\tglobal Image_id #这里使用的是Image_id这个全局变量来传递图片验证码数据\r\n\t\t\"\"\"获取图片验证码\"\"\"\r\n\t\tpre_code_id = self.get_argument(\"pre\", \"\")\r\n\t\tcur_code_id = self.get_argument(\"cur\")\r\n\t\t# 生成图片验证码\r\n\t\tname, text, pic = captcha.generate_captcha() #这里使用了外接包,导入的captcha是对象,生成了图片信息\r\n\t\t# print(text) #这里的text是真正的数据,是用来判断用户传入过来的验证是否是正确的\r\n\t\tImage_id = text\r\n\t\t#这里的pic是直接生成的图片二进制码,所以接下来可以直接通过self.write往html写入数据\r\n\t\tself.set_header(\"Content-Type\", \"image/jpg\")\r\n\t\tself.write(pic) #这里的作用是将图片的二进制数据写入到前端系统\r\n\r\n\r\n###############手机验证码功能#################################\r\nclass Smscode(BaseHandler):\r\n\tdef post(self):\r\n\t\tglobal Image_id\r\n\t\tmobile = self.json_args.get('mobile') #这里的json_args是个字典类型,存放的是json类型的数据,ajax中的json数据的获取是通过self.request.body()中获取的\r\n\t\timageCode = self.json_args.get('piccode') #这里的字典中的值是在BaseHandler中进行预解析的\r\n\t\timageCodeId = self.json_args.get('piccode_id')\r\n\t\t# print(\"image_id===============\")\r\n\t\t# print(Image_id)\r\n\t\tif imageCode.upper() != Image_id:\r\n\t\t\tdata = {\r\n\t\t\t\t\"errcode\":'1',\r\n\t\t\t\t\"errmsg\":\"imagecode wrong\"\r\n\t\t\t}\r\n\t\telse:\r\n\t\t\tprint(\"iamge code true\",imageCode)\r\n\t\t\tdata = {\r\n\t\t\t\t\"errcode\":'0',\r\n\t\t\t\t\"errmsg\":'ok',\r\n\t\t\t}\r\n\t\t\t# 产生随机短信验证码\r\n\t\t\tsms_code = \"%06d\" % random.randint(1, 1000000)\r\n\t\t\ttry:\r\n\t\t\t\tself.redis.set_value(\"sms_code_%s\" % mobile, sms_code)\r\n\t\t\t\tself.redis.set_expire(\"sms_code_%s\" % mobile, 360)\r\n\t\t\texcept Exception as e:\r\n\t\t\t\tlogging.error(e)\r\n\t\t\t\tdata = {\r\n\t\t\t\t\t\"errcode\":'1',\r\n\t\t\t\t\t\"errmsg\":\"create Smscode fail\"\r\n\t\t\t\t}\r\n\r\n\t\t\tprint('sms_code========',sms_code)\r\n\r\n\t\t\t# 发送短信验证码\r\n\t\t\ttry:\r\n\t\t\t\tresult = ccp.sendTemplateSMS(mobile, [sms_code, 1], 1)\r\n\t\t\texcept Exception as e:\r\n\t\t\t\tlogging.error(e)\r\n\t\t\t\tdata = {\r\n\t\t\t\t\t\"errcode\":'1',\r\n\t\t\t\t\t\"errmsg\":\"send Smscode fail\"\r\n\t\t\t\t}\r\n\t\t\tif result:\r\n\t\t\t\tdata = {\r\n\t\t\t\t\t\"errcode\":'0',\r\n\t\t\t\t\t\"errmsg\":\"ok\"\r\n\t\t\t\t}\r\n\t\t\telse:\r\n\t\t\t\tdata = {\r\n\t\t\t\t\t\"errcode\":'1',\r\n\t\t\t\t\t\"errmsg\":\"目前该短信注册功能由于采用的是云通讯的测试功能,只支持绑定的手机号发送验证码,此处其他手机可输入任意值即可\"\r\n\t\t\t\t}\r\n\r\n\t\tself.write(data)\r\n\t\tself.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\r\n\r\n################注册验证功能################################\r\nclass Register_verity(BaseHandler):\r\n\tdef post(self):\r\n\t\tmobile = self.json_args.get('mobile')\r\n\t\tphoneCode = self.json_args.get('phonecode')\r\n\t\tpasswd = self.json_args.get('password')\r\n\t\tpasswd2 = self.json_args.get('password2')\r\n\t\t# print(mobile,phoneCode,passwd,passwd2)\r\n\r\n\t\t################这里用来判断手机号是否已经注册了###########\r\n\t\tsql = \"select up_name from ih_user_profile where up_mobile='%s'\"%mobile\r\n\t\tresult = self.database.get_values_from_mysql(sql)\r\n\t\tprint(\"#############\",result)\r\n\t\tif len(result) != 0:\r\n\t\t\tprint(\"mobile number existed\")\r\n\t\t\tdata = {\r\n\t\t\t'errcode':'1',\r\n\t\t\t'errmsg':'mobile number existed'\r\n\t\t\t}\r\n\t\t\tself.write(data)\r\n\t\t\tself.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\r\n\t\t################这里判断两次输入的密码是否一致###########\r\n\t\telif passwd != passwd2:\r\n\t\t\tdata = { \r\n\t\t\t'errcode':'1',\r\n\t\t\t'errmsg':'password mismatch'\r\n\t\t\t}\r\n\t\t\tself.write(data)\r\n\t\t\tself.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\r\n\t\telse:\r\n\t\t#############这里对密码进行加密处理#####################\r\n\t\t\ts1 = sha1()\r\n\t\t\ts1.update(passwd.encode(\"utf-8\"))\r\n\t\t\tpassword = s1.hexdigest()\r\n\t\t\r\n\t\t#############验证手机的验证码是否正确###################\r\n\t\t\tcode = self.redis.get_value(\"sms_code_%s\" % mobile)\r\n\t\t\t# print(' redis code value',code.decode(\"utf-8\"))\r\n\t\t\t# print('phonecode=======',phoneCode)\r\n\t\t\tif phoneCode == code.decode(\"utf-8\"):\r\n\t\t\t\tprint('Smscode=======ok')\r\n\r\n\t\t#######将手机号和密码存入数据库中去####################\r\n\t\t\tdefault_image_path = '/static/images/landlord01.jpg'\r\n\t\t\tsql = \"insert into ih_user_profile(up_name,up_mobile,up_passwd,up_avatar) values('%s','%s','%s','%s')\"%(mobile, mobile, password, default_image_path)\r\n\t\t\tprint(sql)\r\n\t\t\tself.database.insert_into_tbl(sql)\r\n\r\n\t\t####### 将注册成功后的用户写入session 机制 ############\r\n\t\t#这里生成一个独一无二的session_id号\r\n\t\t\tsession_id = str(base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes))\r\n\t\t\tself.set_secure_cookie(\"session_id\", session_id, expires_days=1)\r\n\t\t#这里将存在cookie中的session_id存放到redis中,这样就可以通过cookie来在redis中进行数据查询\t\r\n\t\t\tself.redis.set_value(session_id, str(mobile))\r\n\t\t\tself.redis.set_expire(session_id, 360)\r\n\t\t###########返回状态码给到js端##########################\r\n\t\t\tdata = {\r\n\t\t\t\t'errcode':'0',\r\n\t\t\t\t'errmsg':'ok'\r\n\t\t\t}\r\n\r\n\t\t\tself.write(data)\r\n\t\t\tself.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\r\n\r\n\r\n###############################登陆处理功能###################################\r\nclass Login_verity(BaseHandler):\r\n\tdef post(self):\r\n\t\tmobile = self.json_args.get('mobile')\r\n\t\tpasswd = self.json_args.get('password')\r\n\r\n\t\t################# 从mysql数据库中查询是否存在该手机号 ###########\r\n\t\tsql = \"select up_passwd from ih_user_profile where up_mobile=%s\"%mobile\r\n\t\tresult = self.database.get_values_from_mysql(sql)\r\n\t\t# print(\"result=====\",result)\r\n\t\tif result == None or len(result) == 0:\r\n\t\t\tprint(\" mobile dot exist please register\")\r\n\t\t\tdata = {\r\n\t\t\t\t'errcode':'1',\r\n\t\t\t\t'errmsg':'do not exist'\r\n\t\t\t}\r\n\t\t\tself.write(data)\r\n\t\t\tself.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\r\n\t\telse:\r\n\t\t\t############ 对输入的密码进行加密后和数据库中的密码进行比较 ####\r\n\t\t\ts1 = sha1()\r\n\t\t\ts1.update(passwd.encode(\"utf-8\"))\r\n\t\t\tpassword = s1.hexdigest()\r\n\t\t\tprint('password=====',password)\r\n\t\t\t############# end #########################################\r\n\t\t\t# print(\"password===== result======\",password,result[0])\r\n\r\n\t\t\tif password != result[0][0]:\r\n\t\t\t\tprint(\"password wrong\")\r\n\t\t\t\tdata = {\r\n\t\t\t\t'errcode':'1',\r\n\t\t\t\t'errmsg':'password wrong'\r\n\t\t\t\t}\r\n\t\t\t\tself.write(data)\r\n\t\t\t\tself.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\r\n\t\t\telse:\r\n\t\t\t\tprint(\" login sucess\")\r\n\t\t\t\t#############这里设置 session 功能######################\r\n\t\t\t\tsession_id = str(base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes))\r\n\t\t\t\tself.set_secure_cookie(\"session_id\", session_id, expires_days=1)\r\n\t\t\t\tself.redis.set_value(session_id, str(mobile))\r\n\t\t\t\tself.redis.set_expire(session_id, 3600)\r\n\t\t\t\t############# end #####################################\r\n\t\t\t\tdata = {\r\n\t\t\t\t'errcode':'0',\r\n\t\t\t\t'errmsg':'login sucess'\r\n\t\t\t\t}\r\n\t\t\t\tself.write(data)\r\n\t\t\t\tself.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\r\n\r\n#############################个人信息处理################################\r\n\r\nclass Personal_info(BaseHandler):\r\n\t@required_login\r\n\tdef get(self):\r\n\t\tsession_id = self.get_secure_cookie(\"session_id\")\r\n\t\t# print(\"session_id===\",session_id)\r\n\t\tmobile = self.redis.get_value(session_id).decode(\"utf-8\")\r\n\t\t# print(\"mobile=====\",mobile)\r\n\t\tsql = \"select up_name,up_avatar from ih_user_profile where up_mobile=%s\"%mobile\r\n\t\tresult = self.database.get_values_from_mysql(sql)\r\n\t\t# print(\"name====\",result)\r\n\t\tif result == None or len(result) == 0: \r\n\t\t\tprint(\"can not search name\")\r\n\t\t\tself.write(dict(errcode=\"4101\", errmsg=\"用户未登录\"))\r\n\r\n\t\t# print(\"result[0][1]======\", result[0][1])\r\n\t\tif result[0][1] == None:\r\n\t\t\timage_path = \"/static/images/landlord01.jpg\"\r\n\t\telse:\r\n\t\t\timage_path = result[0][1]\r\n\r\n\t\tuser_data = {\r\n\t\t\t\"name\":result[0][0],\r\n\t\t\t\"mobile\":mobile,\r\n\t\t\t\"avatar\":image_path\r\n\t\t}\r\n\r\n\t\tdata = {\r\n\t\t\t\"errcode\":\"0\",\r\n\t\t\t\"data\":user_data,\r\n\t\t}\r\n\r\n\t\tself.write(data)\r\n\t\tself.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\r\n\r\n##########################处理用户修改用户名#########################\r\nclass Personal_name(BaseHandler):\r\n\t@required_login\r\n\tdef post(self):\r\n\t\tuser_name = self.json_args.get('name')\r\n\t\t# print('user_name====',user_name)\r\n\t\t################# 获取当前登录的用户id ######################\r\n\t\tsession_id = self.get_secure_cookie(\"session_id\")\r\n\t\t# print(\"session_id===\",session_id)\r\n\t\tmobile = self.redis.get_value(session_id).decode(\"utf-8\")\r\n\t\tsql = 'update ih_user_profile set up_name=\"%s\" where up_mobile=\"%s\" '%(user_name, mobile)\r\n\t\t# print(sql)\r\n\t\tresult = self.database.update_tbl(sql)\r\n\t\tif result != True:\r\n\t\t\tprint(\" update sql failed \")\r\n\t\t\treturn 0\r\n\t\telse:\r\n\t\t\tprint(\" update sql sucess \")\r\n\r\n\t\t\tdata = {\r\n\t\t\t\t\"errcode\":\"0\",\r\n\t\t\t}\r\n\r\n\t\t\tself.write(data)\r\n\t\t\tself.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\r\n\r\n######################### 这里用来处理用户上传的头像信息 #############\r\n#####---这里使用的技术栈是直接保存在了服务器/static/images/personal_images中\r\n#####---这里可使用七牛技术存储到远程服务器上(由于账号实名问题,七牛账号暂时不可用)\r\nclass Personal_img(BaseHandler):\r\n\t@required_login\r\n\tdef post(self):\r\n\t\t################# 获取当前登录的用户id ######################\r\n\t\tsession_id = self.get_secure_cookie(\"session_id\")\r\n\t\t# print(\"session_id===\",session_id)\r\n\t\tmobile = self.redis.get_value(session_id).decode(\"utf-8\")\r\n\t\tprint(\"test_test======\")\r\n\t\tfiles = self.request.files\r\n\t\timage_file = files.get(\"avatar\")\r\n\t\tif image_file:\r\n\t\t\tfile_name = image_file[0][\"filename\"]\r\n\t\t\t# print(\"filename=====\", file_name)\r\n\t\t\timage = image_file[0][\"body\"]\r\n\r\n\t\t\tfile_path = './static/images/personal_images/' + mobile# + \".\" + \".\".join(file_name.split(\".\")[1:])\r\n\t\t\tfile = open(file_path, 'wb')\r\n\t\t\tfile.write(image)\r\n\r\n\t\t\tfile.close()\r\n\r\n\t\t\tdata = {\r\n\t\t\t\t'errcode':'0',\r\n\t\t\t\t'data':file_path,\r\n\t\t\t}\r\n\r\n\t\t\t############## 这里需要添加将图片路径保存在mysql的功能#####\r\n\t\t\tsql = 'update ih_user_profile set up_avatar=\"%s\" where up_mobile=\"%s\" '%(file_path, mobile)\r\n\t\t\tresult = self.database.update_tbl(sql)\r\n\t\t\tif result != True:\r\n\t\t\t\tprint(\" update sql failed \")\r\n\t\t\t\treturn 0\r\n\r\n\t\telse:\r\n\t\t\tdata = {\r\n\t\t\t\t'errcode':'4001',\r\n\t\t\t\t'data':\"/static/images/landlord01.jpg\",\r\n\t\t\t}\r\n\r\n\t\tself.write(data)\r\n\t\tself.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\r\n\r\n######################## 房屋信息显示 #######################\r\nclass House_info(BaseHandler):\r\n\t######### POST 处理的是房屋提交信息 ######################\r\n\t@required_login\r\n\tdef post(self):\r\n\t\t\"\"\"保存\"\"\"\r\n\t\t# 获取参数\r\n\t\t\"\"\"{\r\n\t\t\t\"title\":\"\",\r\n\t\t\t\"price\":\"\",\r\n\t\t\t\"area_id\":\"1\",\r\n\t\t\t\"address\":\"\",\r\n\t\t\t\"room_count\":\"\",\r\n\t\t\t\"acreage\":\"\",\r\n\t\t\t\"unit\":\"\",\r\n\t\t\t\"capacity\":\"\",\r\n\t\t\t\"beds\":\"\",\r\n\t\t\t\"deposit\":\"\",\r\n\t\t\t\"min_days\":\"\",\r\n\t\t\t\"max_days\":\"\",\r\n\t\t\t\"facility\":[\"7\",\"8\"]\r\n\t\t}\"\"\"\r\n\t\t################# 获取当前登录的用户id ######################\r\n\t\tsession_id = self.get_secure_cookie(\"session_id\")\r\n\t\t# print(\"session_id===\",session_id)\r\n\t\tmobile = self.redis.get_value(session_id).decode(\"utf-8\")\r\n\t\tsql = 'select up_user_id from ih_user_profile where up_mobile=\"%s\"'%mobile\r\n\t\tret = self.database.get_values_from_mysql(sql)\r\n\r\n\t\tuser_id = ret[0][0]\r\n\t\ttitle = self.json_args.get(\"title\")\r\n\t\tprice = self.json_args.get(\"price\")\r\n\t\tarea_id = self.json_args.get(\"area_id\")\r\n\t\taddress = self.json_args.get(\"address\")\r\n\t\troom_count = self.json_args.get(\"room_count\")\r\n\t\tacreage = self.json_args.get(\"acreage\")\r\n\t\tunit = self.json_args.get(\"unit\")\r\n\t\tcapacity = self.json_args.get(\"capacity\")\r\n\t\tbeds = self.json_args.get(\"beds\")\r\n\t\tdeposit = self.json_args.get(\"deposit\")\r\n\t\tmin_days = self.json_args.get(\"min_days\")\r\n\t\tmax_days = self.json_args.get(\"max_days\")\r\n\t\tfacility = self.json_args.get(\"facility\") # 对一个房屋的设施,是列表类型\r\n\t\t# 校验\r\n\t\tif not all((title, price, area_id, address, room_count, acreage, unit, capacity, beds, deposit, min_days,\r\n\t\t\t\t\tmax_days)):\r\n\t\t\treturn self.write(dict(errcode='3', errmsg=\"缺少参数\"))\r\n\r\n\t\ttry:\r\n\t\t\tprice = int(price) * 100\r\n\t\t\tdeposit = int(deposit) * 100\r\n\t\texcept Exception as e:\r\n\t\t\treturn self.write(dict(errcode='2', errmsg=\"参数错误\"))\r\n\r\n\t\t# 数据\r\n\t\ttry:\r\n\t\t\tsql = \"insert into ih_house_info(hi_user_id,hi_title,hi_price,hi_area_id,hi_address,hi_room_count,\" \\\r\n\t\t\t\t \"hi_acreage,hi_house_unit,hi_capacity,hi_beds,hi_deposit,hi_min_days,hi_max_days) \" \\\r\n\t\t\t\t \"values(%s,%s,%s,%s,%s,%s,%s,\" \\\r\n\t\t\t\t \"%s,%s,%s,%s,%s,%s)\"%(user_id, title, price, area_id, address, room_count, acreage, unit, capacity, beds, deposit, min_days, max_days)\r\n\t\t\t# 对于insert语句,execute方法会返回最后一个自增id\r\n\t\t\tself.database.insert_into_tbl(sql)\r\n\t\texcept Exception as e:\r\n\t\t\tlogging.error(e)\r\n\t\t\treturn self.write(dict(errcode='4', errmsg=\"save data error\"))\r\n\r\n\t\tsql = 'select hi_house_id from ih_house_info where hi_user_id=%s'%user_id\r\n\t\tret = self.database.get_values_from_mysql(sql)\r\n\t\thouse_id = ret[0][-1]\r\n\t\t# print('house_id================',house_id)\r\n\r\n\t\ttry:\r\n\t\t\tsql = \"insert into ih_house_facility(hf_house_id,hf_facility_id) values\"\r\n\t\t\tsql_val = [] # 用来保存条目的(%s, %s)部分 最终的形式 [\"(%s, %s)\", \"(%s, %s)\"]\r\n\t\t\tvals = [] # 用来保存的具体的绑定变量值\r\n\t\t\tfor facility_id in facility:\r\n\t\t\t\t# sql += \"(%s, %s),\" 采用此种方式,sql语句末尾会多出一个逗号\r\n\t\t\t\t# sql_val.append(\"(%d, %s)\")\r\n\t\t\t\tvals.append(str((house_id,facility_id)))\r\n\t\t\t\t# vals.append(facility_id)\r\n\r\n\t\t\t# sql += \",\".join(sql_val)\r\n\t\t\tsql += \",\".join(vals)\r\n\t\t\t# print('sql=============',sql)\r\n\t\t\tlogging.debug(sql)\r\n\t\t\tlogging.debug(vals)\r\n\t\t\tself.database.insert_into_tbl(sql)\r\n\t\texcept Exception as e:\r\n\t\t\tlogging.error(e)\r\n\t\t\ttry:\r\n\t\t\t\tsql = \"delete from ih_house_info where hi_house_id=%s\"%house_id\r\n\t\t\t\tself.database.insert_into_tbl(sql)\r\n\t\t\texcept Exception as e:\r\n\t\t\t\tlogging.error(e)\r\n\t\t\t\treturn self.write(dict(errcode='4', errmsg=\"delete fail\"))\r\n\t\t\telse:\r\n\t\t\t\treturn self.write(dict(errcode='4', errmsg=\"no data save\"))\r\n\t\t# 返回\r\n\t\tself.write(dict(errcode='0', errmsg=\"OK\", house_id=house_id))\r\n\r\n\r\n\t######### GET处理 的是获取房屋信息 ######################\r\n\t@required_login\r\n\tdef get(self):\r\n\t\thouse_id = self.get_query_argument('house_id')\r\n\t\tprint(house_id)\r\n\t\t########### 获取房屋信息 #########################\r\n\t\tsession_id = self.get_secure_cookie(\"session_id\")\r\n\t\tmobile = self.redis.get_value(session_id).decode(\"utf-8\")\r\n\r\n\t\t# 校验参数,判断传入的house_id是否正确\r\n\t\tif not house_id:\r\n\t\t\treturn self.write(dict(errcode='3', errmsg=\"缺少参数\"))\r\n\r\n\t\t# 这里可以添加从redis缓存中获取这些房屋信息,这样就避免了进行多次查询数据的操作\r\n\t\t# 这里以待加入功能\r\n\t\t# TODO\r\n\r\n\t\t# 查询数据库\r\n\r\n\t\t# 查询房屋基本信息\r\n\t\tsql = \"select hi_title,hi_price,hi_address,hi_room_count,hi_acreage,hi_house_unit,hi_capacity,hi_beds,\" \\\r\n\t\t\t \"hi_deposit,hi_min_days,hi_max_days,up_name,up_avatar,hi_user_id \" \\\r\n\t\t\t \"from ih_house_info inner join ih_user_profile on hi_user_id=up_user_id where hi_house_id=%s\"%house_id\r\n\r\n\t\tret = self.database.get_values_from_mysql(sql)\r\n\t\t# print(\"result=======\", ret)\r\n\t\t# 用户查询的可能是不存在的房屋id, 此时ret为None\r\n\t\tif not ret:\r\n\t\t\treturn self.write(dict(errcode='2', errmsg=\"查无此房\"))\r\n\r\n\t\tdata = {\r\n\t\t\t\"hid\":house_id,\r\n\t\t\t\"user_id\":ret[0][13],\r\n\t\t\t\"title\":ret[0][0],\r\n\t\t\t\"price\":ret[0][1],\r\n\t\t\t\"address\":ret[0][2],\r\n\t\t\t\"room_count\":ret[0][3],\r\n\t\t\t\"acreage\":ret[0][4],\r\n\t\t\t\"unit\":ret[0][5],\r\n\t\t\t\"capacity\":ret[0][6],\r\n\t\t\t\"beds\":ret[0][7],\r\n\t\t\t\"deposit\":ret[0][8],\r\n\t\t\t\"min_days\":ret[0][9],\r\n\t\t\t\"max_days\":ret[0][10],\r\n\t\t\t\"user_name\":ret[0][11],\r\n\t\t\t\"user_avatar\":ret[0][12]\r\n\t\t}\r\n\r\n\t\t# print(\"data===========\",data)\r\n\r\n\t\t# 查询房屋的图片信息\r\n\t\tsql = \"select hi_url from ih_house_image where hi_house_id=%s\"%house_id\r\n\t\tret = self.database.get_values_from_mysql(sql)\r\n\t\t# print(\"image=============\",ret)\r\n\r\n\t\t# 如果查询到的图片\r\n\t\timages = []\r\n\t\tif ret:\r\n\t\t\tfor image in ret:\r\n\t\t\t\timages.append(image[0])\r\n\t\tdata[\"images\"] = images\r\n\r\n\t\t# 查询房屋的基本设施\r\n\t\tsql = \"select hf_facility_id from ih_house_facility where hf_house_id=%s\"%house_id\r\n\t\tret = self.database.get_values_from_mysql(sql)\r\n\r\n\t\t# 如果查询到设施\r\n\t\tfacilities = []\r\n\t\tif ret:\r\n\t\t\tfor facility in ret:\r\n\t\t\t\tfacilities.append(facility[0])\r\n\t\tdata[\"facilities\"] = facilities\r\n\r\n\t\t# 查询评论信息\r\n\t\tsql = \"select oi_comment,up_name,oi_utime,up_mobile from ih_order_info inner join ih_user_profile \" \\\r\n\t\t\t \"on oi_user_id=up_user_id where oi_house_id=%s and oi_status=4 and oi_comment is not null\"%house_id\r\n\r\n\t\tret = self.database.get_values_from_mysql(sql)\r\n\t\tcomments = []\r\n\t\tif ret:\r\n\t\t\tfor comment in ret:\r\n\t\t\t\tcomments.append(dict(\r\n\t\t\t\t\tuser_name = comment[1] if comment[1] != comment[3] else \"匿名用户\",\r\n\t\t\t\t\tcontent = comment[0],\r\n\t\t\t\t\tctime = comment[2].strftime(\"%Y-%m-%d %H:%M:%S\")\r\n\t\t\t\t))\r\n\t\tdata[\"comments\"] = comments\r\n\r\n\t\t# 存入到redis中\r\n\t\tjson_data = json.dumps(data)\r\n\r\n\t\t## 可以在此处将上边查询到的这么多数据存储到redis中,这样下次查询的时候就能加快查询步骤\r\n\t\t#TODO\r\n\r\n\t\tresp = '{\"errcode\":\"0\", \"errmsg\":\"OK\", \"data\":%s, \"user_id\":%s}' % (json_data, mobile)\r\n\t\t# self.write(dict(errcode=RET.OK, errmsg=\"OK\", data=data))\r\n\t\tself.write(resp)\r\n\t\tself.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\r\n\r\n\r\n############## 获取预定信息 /api/house/info ########################################\r\nclass House_reserve(BaseHandler):\r\n\tdef post(self):\r\n\t\thouse_id = self.json_args.get('house_id')\r\n\t\tstart_date = self.json_args.get('start_date')\r\n\t\tend_date = self.json_args.get('end_date')\r\n\t\tprint('====',house_id,start_date,end_date)\r\n\r\n\t\tsql = ' select oi_begin_date,oi_end_date from ih_order_info where oi_house_id=%s'%house_id\r\n\t\tret = self.database.get_values_from_mysql(sql)\r\n\t\tif not ret:\r\n\t\t\tprint(' query order info error')\r\n\t\t\tdata = {\r\n\t\t\t\t'errcode':'4101',\r\n\t\t\t}\r\n\t\t############ 这里添加对 html中传来的事件信息,和该house在order数据库中存在的时间内信息进行比较来判断所选择的时间段是否可预定\r\n\r\n\t\tdata = {\r\n\t\t\t'errcode':'0'\r\n\t\t}\r\n\t\tself.write(data)\r\n\t\tself.set_header('Content-Type', 'application/json; charset=UTF-8')\r\n\r\n############### 处理显示订单信息 ##########################################\r\nclass Show_order(BaseHandler):\r\n\t@required_login\r\n\tdef get(self):\r\n\t\tsession_id = self.get_secure_cookie(\"session_id\")\r\n\t\t# print(\"session_id===\",session_id)\r\n\t\tmobile = self.redis.get_value(session_id).decode(\"utf-8\")\r\n\r\n\t\tsql = ' select up_user_id from ih_user_profile where up_mobile=%s'%mobile\r\n\t\tret = self.database.get_values_from_mysql(sql)\r\n\t\tif not ret:\r\n\t\t\tprint('user_id doesr not exist')\r\n\t\t\tdata = {\r\n\t\t\t\t'errcode':'1',\r\n\t\t\t}\r\n\t\tuser_id = ret[0][0]\r\n\t\t# print('user_id======',user_id)\r\n\r\n\t\t# 用户的身份,用户想要查询作为房客下的单,还是想要查询作为房东 被人下的单\r\n\t\trole = self.get_query_argument(\"role\", \"\")\r\n\t\ttry:\r\n\t\t\t# 查询房东订单\r\n\t\t\tif \"landlord\" == role:\r\n\t\t\t\tsql = 'select oi_order_id,hi_title,hi_index_image_url,oi_begin_date,oi_end_date,oi_ctime,oi_days,oi_amount,oi_status,oi_comment from ih_order_info inner join ih_house_info on oi_house_id=hi_house_id where hi_user_id=%s order by oi_ctime desc'%user_id\r\n\t\t\t\tret = self.database.get_values_from_mysql(sql)\r\n\t\t\t\tif not ret:\r\n\t\t\t\t\tprint(' query order info fail')\r\n\t\t\t\t\tdata = {\r\n\t\t\t\t\t\t'errcode':'1',\r\n\t\t\t\t\t}\r\n\r\n\t\t\telse:\r\n\t\t\t\tsql = 'select oi_order_id,hi_title,hi_index_image_url,oi_begin_date,oi_end_date,oi_ctime,oi_days,oi_amount,oi_status,oi_comment from ih_order_info inner join ih_house_info on oi_house_id=hi_house_id where oi_user_id=%s order by oi_ctime desc'%user_id\r\n\t\t\t\tret = self.database.get_values_from_mysql(sql)\r\n\t\t\t\tif not ret:\r\n\t\t\t\t\tprint(' query order info fail')\r\n\t\t\t\t\tdata = {\r\n\t\t\t\t\t\t'errcode':'1',\r\n\t\t\t\t\t}\r\n\r\n\t\texcept Exception as e:\r\n\t\t\tlogging.error(e)\r\n\t\t\treturn self.write({\"errcode\":'1', \"errmsg\":\"get data error\"})\r\n\t\torders = []\r\n\t\t# print('ret========',ret[0][0])\r\n\t\tif ret:\r\n\t\t\tfor l in ret:\r\n\t\t\t\t# print('l[0]======',l)\r\n\t\t\t\torder = {\r\n\t\t\t\t\t\"order_id\":l[0],\r\n\t\t\t\t\t\"title\":l[1],\r\n\t\t\t\t\t\"img_url\":l[2],\r\n\t\t\t\t\t\"start_date\":l[3].strftime(\"%Y-%m-%d\"),\r\n\t\t\t\t\t\"end_date\":l[4].strftime(\"%Y-%m-%d\"),\r\n\t\t\t\t\t\"ctime\":l[5].strftime(\"%Y-%m-%d\"),\r\n\t\t\t\t\t\"days\":l[6],\r\n\t\t\t\t\t\"amount\":l[7],\r\n\t\t\t\t\t\"status\":l[8],\r\n\t\t\t\t\t\"comment\":l[9] if l[9] else \"\"\r\n\t\t\t\t}\r\n\t\t\t\torders.append(order)\r\n\t\tself.write({\"errcode\":'0', \"errmsg\":\"OK\", \"orders\":orders})\r\n\r\n#################### 此处进行的是实名认证的功能 ############################\r\nclass Real_name_verity(BaseHandler):\r\n\t@required_login\r\n\tdef get(self):\r\n\t\tsession_id = self.get_secure_cookie(\"session_id\")\r\n\t\t# print(\"session_id===\",session_id)\r\n\t\tmobile = self.redis.get_value(session_id).decode(\"utf-8\")\r\n\t\t# print('mobile=======',mobile)\r\n\r\n\t\tsql = ' select up_real_name,up_id_card from ih_user_profile where up_mobile=\"%s\"'%mobile\r\n\t\tret = self.database.get_values_from_mysql(sql)\r\n\r\n\t\t# print('ret=====',ret)\r\n\t\tuser_data = {\r\n\t\t\t'real_name':ret[0][0],\r\n\t\t\t'id_card':ret[0][1],\r\n\t\t}\r\n\t\tdata = {\r\n\t\t\t'errcode':'0',\r\n\t\t\t'data':user_data,\r\n\t\t}\r\n\r\n\t\tprint('data========',data)\r\n\r\n\t\tself.write(data)\r\n\t\tself.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\r\n\r\n################# 修改当前用户的实名认证情况 #############################\r\n\t@required_login\r\n\tdef post(self):\r\n\t\t########### 获取当前用户的情况###################################\r\n\t\tsession_id = self.get_secure_cookie(\"session_id\")\r\n\t\t# print(\"session_id===\",session_id)\r\n\t\tmobile = self.redis.get_value(session_id).decode(\"utf-8\")\r\n\t\t# print('mobile=======',mobile)\r\n\r\n\t\treal_name = self.json_args.get('real_name')\r\n\t\tid_card = self.json_args.get('id_card')\r\n\t\t# print('id_card=====',real_name, id_card)\r\n\r\n\t\tsql = 'update ih_user_profile set up_real_name=\"%s\", up_id_card=\"%s\" where up_mobile=\"%s\"'%(real_name, id_card, mobile)\r\n\t\tret = self.database.update_tbl(sql)\r\n\t\tif not ret:\r\n\t\t\tprint('update real name fial')\r\n\r\n\t\tdata = {\r\n\t\t\t'errcode':'0',\r\n\t\t}\r\n\r\n\t\tself.write(data)\r\n\t\tself.set_header('Content-Type', 'application/json; charset=UTF-8')\r\n\r\nclass Myhouse_show(BaseHandler):\r\n\t@required_login\r\n\tdef get(self):\r\n\t\t########### 获取当前用户的情况###################################\r\n\t\tsession_id = self.get_secure_cookie(\"session_id\")\r\n\t\t# print(\"session_id===\",session_id)\r\n\t\tmobile = self.redis.get_value(session_id).decode(\"utf-8\")\r\n\t\t# print('mobile=======',mobile)\r\n\r\n\t\tsql = 'select up_user_id from ih_user_profile where up_mobile=\"%s\"'%mobile\r\n\t\tret = self.database.get_values_from_mysql(sql)\r\n\t\tuser_id = ret[0][0]\r\n\r\n\t\ttry:\r\n\t\t\tsql = \"select a.hi_house_id,a.hi_title,a.hi_price,a.hi_ctime,b.ai_name,a.hi_index_image_url \" \\\r\n\t\t\t\t \"from ih_house_info a inner join ih_area_info b on a.hi_area_id=b.ai_area_id where a.hi_user_id=%s\"%user_id\r\n\t\t\tret = self.database.get_values_from_mysql(sql)\r\n\t\texcept Exception as e:\r\n\t\t\tlogging.error(e)\r\n\t\t\treturn self.write({\"errcode\":'1', \"errmsg\":\"get data erro\"})\r\n\t\thouses = []\r\n\t\tif ret:\r\n\t\t\tfor l in ret:\r\n\t\t\t\thouse = {\r\n\t\t\t\t\t\"house_id\":l[0],\r\n\t\t\t\t\t\"title\":l[1],\r\n\t\t\t\t\t\"price\":l[2],\r\n\t\t\t\t\t\"ctime\":l[3].strftime(\"%Y-%m-%d\"), # 将返回的Datatime类型格式化为字符串\r\n\t\t\t\t\t\"area_name\":l[4],\r\n\t\t\t\t\t\"img_url\":l[5] if l[5] else \"\"\r\n\t\t\t\t}\r\n\t\t\t\thouses.append(house)\r\n\t\tself.write({\"errcode\":'0', \"errmsg\":\"OK\", \"houses\":houses})\r\n\t\tself.set_header('Content-Type', 'application/json; charset=UTF-8')\r\n\r\n#################### 此处的作用是提供房源提交的时候的地区选择功能 #####################\r\nclass Area_info_handler(BaseHandler):\r\n\t\"\"\"提供城区信息\"\"\"\r\n\t@required_login\r\n\tdef get(self):\r\n\r\n\t\t# 查询Mysql数据库,获取城区信息\r\n\t\tsql = \"select ai_area_id,ai_name from ih_area_info\"\r\n\r\n\t\ttry:\r\n\t\t\tret = self.database.get_values_from_mysql(sql)\r\n\t\texcept Exception as e:\r\n\t\t\tlogging.error(e)\r\n\t\t\treturn self.write(dict(errcode='1', errmsg=\"数据库查询出错\"))\r\n\t\tif not ret:\r\n\t\t\treturn self.write(dict(errcode='2', errmsg=\"没有数据\"))\r\n\t\t# 保存转换好的区域信息\r\n\t\tdata = []\r\n\t\tfor row in ret:\r\n\t\t\td = {\r\n\t\t\t\t\"area_id\": row[0],\r\n\t\t\t\t\"name\": row[1]\r\n\t\t\t}\r\n\t\t\tdata.append(d)\r\n\r\n\t\tself.write(dict(errcode='0', errmsg=\"OK\", data=data))\r\n\r\n################ 此处的作用 是退出当前用户的登录#################\r\n\r\nclass Login_out(BaseHandler):\r\n\t@required_login\r\n\tdef get(self):\r\n\t\t########### 获取当前用户的情况###################################\r\n\t\tsession_id = self.get_secure_cookie(\"session_id\")\r\n\t\t# print(\"session_id===\",session_id)\r\n\t\t#将当前用户在redis中存储的信息删除掉\r\n\t\tret = self.redis.del_value(session_id)\r\n\t\t# print('ret=========',ret)\r\n\t\tif not ret:\r\n\t\t\tlogging.error('delete value fial')\r\n\t\t\tdata = {\r\n\t\t\t\t'errcode':'1',\r\n\t\t\t}\r\n\t\telse:\r\n\t\t\tdata = {\r\n\t\t\t\t'errcode':'0',\r\n\t\t\t}\r\n\r\n\t\tself.write(data)\r\n\t\tself.set_header('Content-Type', 'application/json; charset=UTF-8')\r\n\r\n\r\n##################### 此处的作用是按照所选择的条件查询房屋资源################\r\n################# 此函数目前的状态是:待补充功能 ############################\r\nclass House_list_handler(BaseHandler):\r\n\t\"\"\"房源列表页面\"\"\"\r\n\tdef get(self):\r\n\t\t\"\"\"get方式用来获取数据库数据,本身的逻辑不会对数据库数据产生影响\"\"\"\r\n\t\t\"\"\"\r\n\t\t传入参数说明\r\n\t\tstart_date 用户查询的起始时间 sd 非必传 \"\" \"2017-02-28\"\r\n\t\tend_date 用户查询的终止时间 ed 非必传 \"\"\r\n\t\tarea_id 用户查询的区域条件 aid 非必传 \"\"\r\n\t\tsort_key 排序的关键词 sk 非必传 \"new\" \"new\" \"booking\" \"price-inc\" \"price-des\"\r\n\t\tpage 返回的数据页数 p 非必传 1\r\n\t\t\"\"\"\r\n\t\t# 获取参数\r\n\t\tstart_date = self.get_argument(\"sd\", \"\")\r\n\t\tend_date = self.get_argument(\"ed\", \"\")\r\n\t\tarea_id = self.get_argument(\"aid\", \"\")\r\n\t\tsort_key = self.get_argument(\"sk\", \"new\")\r\n\t\tpage = self.get_argument(\"p\", \"1\")\r\n\r\n\t\t# 检查参数\r\n\t\t# 判断日期格式、sort_Key 字段的值、page的整数\r\n\r\n\t\t# 数据查询\r\n\t\t# 涉及到表: ih_house_info 房屋的基本信息 ih_user_profile 房东的用户信息 ih_order_info 房屋订单数据\r\n\r\n\t\tsql = \"select hi_title,hi_house_id,hi_price,hi_room_count,hi_address,hi_order_count,up_avatar,hi_index_image_url,hi_ctime\" \\\r\n\t\t\t \" from ih_house_info inner join ih_user_profile on hi_user_id=up_user_id left join ih_order_info\" \\\r\n\t\t\t \" on hi_house_id=oi_house_id where hi_area_id=%s\"%area_id\r\n\r\n\t\tlogging.debug(sql)\r\n\t\ttry:\r\n\t\t\tret = self.database.get_values_from_mysql(sql)\r\n\t\texcept Exception as e:\r\n\t\t\tlogging.error(e)\r\n\t\t\treturn self.write(dict(errcode='4', errmsg=\"查询出错\"))\r\n\t\tdata = []\r\n\t\tif ret:\r\n\t\t\tfor l in ret:\r\n\t\t\t\thouse = dict(\r\n\t\t\t\t\thouse_id=l[1],\r\n\t\t\t\t\ttitle=l[0],\r\n\t\t\t\t\tprice=l[2],\r\n\t\t\t\t\troom_count=l[3],\r\n\t\t\t\t\taddress=l[4],\r\n\t\t\t\t\torder_count=l[5],\r\n\t\t\t\t\tavatar=l[6] if l[6] else \"\",\r\n\t\t\t\t\timage_url=l[7] if l[7] else \"\"\r\n\t\t\t\t)\r\n\t\t\t\tdata.append(house)\r\n\t\ttotal_page = len(data)\r\n\t\tself.write(dict(errcode='0', errmsg=\"OK\", data=data, total_page=total_page))\r\n\t\tself.set_header('Content-Type', 'application/json; charset=UTF-8')\r\n\r\n" }, { "alpha_fraction": 0.6858638525009155, "alphanum_fraction": 0.6858638525009155, "avg_line_length": 30.66666603088379, "blob_id": "5b22bc6160b7584f804557bad7f0b0c82238dd9b", "content_id": "d9614792008a24652ace82267731efe381d47389", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 191, "license_type": "no_license", "max_line_length": 85, "num_lines": 6, "path": "/Python/basic/package/__init__.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\n# this __ini__.py is must for a python package. \n\n\n__all__ = [\"Sendmesg\"] #define which module import \n\nfrom . import Sendmesg# this is must , only run this ,and can use the Semdmesg moudle\n" }, { "alpha_fraction": 0.6761133670806885, "alphanum_fraction": 0.6801619529724121, "avg_line_length": 16.5, "blob_id": "e430a2c30ea854d903d3ce6bcfd50b7975821c3d", "content_id": "7a272330731e902e59b07d09927624b71d3a1e5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 247, "license_type": "no_license", "max_line_length": 61, "num_lines": 14, "path": "/Python/plus/C_lib/c_lib.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\n\nfrom ctypes import *#must include , use to load c library\nimport threading\n\nLIB = cdll.LoadLibrary('./test.so')# loadding \n\n\nfor i in range(4):\n th = threading.Thread(target=LIB.Loop)#use the c function\n th.start()\n\n\n\nwhile True:\n pass\n" }, { "alpha_fraction": 0.4888888895511627, "alphanum_fraction": 0.5333333611488342, "avg_line_length": 19.5, "blob_id": "1773cca450986220b2d225cebbf2d69d8bd60419", "content_id": "b489a631fe382e82d2253dbf7bf62b6d00c835fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 45, "license_type": "no_license", "max_line_length": 27, "num_lines": 2, "path": "/Python/basic/package/Sendmesg.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\n\ndef test1():\n print(\"This is test1 \")\n\n\n" }, { "alpha_fraction": 0.3283582031726837, "alphanum_fraction": 0.35820895433425903, "avg_line_length": 31.5, "blob_id": "76029461ad9b70e211d48ada7eac892686369a90", "content_id": "6ed334f6fa64eeb398f8bc664cefb60e45ab17e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 67, "license_type": "no_license", "max_line_length": 51, "num_lines": 2, "path": "/Python/basic/package/receivemsg.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "\n\ndef test2():\n print(\"-------------This is test2------------\")\n" }, { "alpha_fraction": 0.5122615694999695, "alphanum_fraction": 0.553133487701416, "avg_line_length": 22.70967674255371, "blob_id": "73d1325badeba6b77b541074167a25248632611c", "content_id": "7ad947746f1417607fc9682b81c8e4a3eafd6a90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 830, "license_type": "no_license", "max_line_length": 65, "num_lines": 31, "path": "/Python/algorithm/fast.py", "repo_name": "jasondzy/Python", "src_encoding": "UTF-8", "text": "def fast_seq(seq_data, start, end):\n \"\"\"如下是快速排序的代码,快速排序代码采用的是low和high两个位置坐标来对数列进行迭代的寻找首元素的位置的操作\"\"\"\n mid_value = seq_data[start]\n low = start\n high = end\n\n if start >= end:\n return\n\n while low < high:\n while low < high and seq_data[high] >= mid_value:\n high -= 1\n seq_data[low] = seq_data[high]\n\n while low < high and seq_data[low] < mid_value:\n low += 1\n seq_data[high] = seq_data[low]\n\n seq_data[low] = mid_value\n fast_seq(seq_data,start, low-1)\n fast_seq(seq_data, low+1, end)\n\n# return left_seq + right_seq\n\n\nif __name__ == '__main__':\n seq = [54, 226, 93, 17, 77, 31, 44, 55, 20, 6, 23, 54]\n\n fast_seq(seq, 0, len(seq)-1)\n\n print(seq)" } ]
55
kirik200088/Crypro_Algorithm
https://github.com/kirik200088/Crypro_Algorithm
23c8adae46d2705e443f11b40e9eb3fb1c3700ec
d6499bdfd4f0fbab77ff5c8f35504d6fbcd3c707
3dbaf7fe1db3a84afc527c070bbff90708e85c4e
refs/heads/master
2020-08-21T14:10:32.949185
2019-10-19T09:00:52
2019-10-19T09:00:52
216,177,119
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.4555778205394745, "alphanum_fraction": 0.48964595794677734, "avg_line_length": 19.2297306060791, "blob_id": "57be91d61cc7adcdb912c17c900ddf8f9ef37d47", "content_id": "1b0309dc26787386089ec9f1d3c3bde9db87b500", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1513, "license_type": "no_license", "max_line_length": 57, "num_lines": 74, "path": "/hamming.cpp", "repo_name": "kirik200088/Crypro_Algorithm", "src_encoding": "UTF-8", "text": "//Вы не слишком добры...\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <string>\n#include <clocale>\n\n#define int long long\n\nusing namespace std;\n\nvector<char> fix_code(vector<char>& arr, int n = -1) {\n\tint ans_wr = 0;\n\tif (n == -1)\n\t\tn = arr.size();\n\tfor (int i = 1; i < n + 1; i *= 2) {\n\t\tbool ans = 0;\n\t\tfor (int j = i; j < n + 1; j += 2 * i) {\n\t\t\tfor (int k = j; k < j + i; k++) {\n\t\t\t\tans xor_eq (arr[k - 1] == '1' ? true : false);\n\t\t\t}\n\t\t}\n\t\tif (ans)\n\t\t\tans_wr += i;\n\t}\n\t//cout << ans_wr;\n\tif (ans_wr)\n\t\tarr[ans_wr - 1] = (arr[ans_wr - 1] == '1' ? '0' : '1');\n\tvector<char> ret;\n\tint notPrint = 1;\n\tint it2 = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (i + 1 == notPrint)\n\t\t\tnotPrint *= 2;\n\t\telse\n\t\t\tret.push_back(arr[i]);\n\t}\n\treturn ret;\n}\n\nsigned main() {\n\tint n = 0, k, bas = 15;\n\tsetlocale(LC_ALL, \"ru\");\n\tstring s2;\n\tgetline(cin, s2);\n\tvector<char> ans_bit;\n\tvector<char> arr(10000);\n\tint it = 0;\n\tfor (auto el : s2) {\n\t\tif (el == '0' || el == '1')\n\t\t\tarr[it++] = el;\n\t}\n\tfor (int i = 0; i < it; i += 15) {\n\t\tvector<char> send;\n\t\tfor (int j = i; j < i + 15; j++)\n\t\t\tsend.push_back(arr[j]);\n\t\tvector<char> ans = fix_code(send, 15);\n\t\tfor (auto el : ans) {\n\t\t\tans_bit.push_back(el);\n\t\t\tcout << el;\n\t\t}\n\t\tcout << ' ';\n\t}\n\tcout << endl;\n\tfor (int i = 0; i < ans_bit.size(); i += 8) {\n\t\tint symb_ans = 0;\n\t\tfor (int j = i; j < i + 8 && j < ans_bit.size(); j++) {\n\t\t\tif (ans_bit[j] == '1') {\n\t\t\t\tsymb_ans += (pow(2, abs(-1*(j - i - 7))));\n\t\t\t}\n\t\t}\n\t\tcout << (char)(symb_ans);\n\t}\n}\n" }, { "alpha_fraction": 0.34151729941368103, "alphanum_fraction": 0.3594402074813843, "avg_line_length": 15.295999526977539, "blob_id": "52e9862154d6befce2032abbb9eadec374da6bde", "content_id": "db65a4f61132b49f21ab8a67b9285d670d4ce4f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4124, "license_type": "no_license", "max_line_length": 87, "num_lines": 250, "path": "/Siberian_Hard_Decode.cpp", "repo_name": "kirik200088/Crypro_Algorithm", "src_encoding": "WINDOWS-1251", "text": "//Пример: Ктосук отько-елр лувбь ю\n//Гаие дн а - Гадание\n#include <iostream>\n#include <string>\n#include <Windows.h>\n\nusing namespace std;\n\nint main()\n{\n\tstring s;\n\tint a, d, n = 0;\n\tint flag = 0;\n\tSetConsoleCP(1251);\n\tSetConsoleOutputCP(1251);\n\n\tgetline(cin, s);\n\t//s = \"Чтопсь отоо -мл ея н\";\n\t//cout << s;\n\n\tfor (int i = 0; i < s.length(); i++)\n\t{\n\t\tif (s[i] == ' ')\n\t\t{\n\t\t\ts.erase(i, 1);\n\t\t\ti--;\n\t\t}\n\t}\n\twhile (true)\n\t{\n\t\tn++;\n\t\tif ((n * n + n) / 2 == s.length())\n\t\t{\n\t\t\tflag = 1;\n\t\t\tbreak;\n\t\t}\n\t\telse if ((n * n + n) / 2 + (n * n + n) % 2 > s.length())\n\t\t{\n\t\t\tflag = 2;\n\t\t\tbreak;\n\t\t}\n\t}\n\tcout << endl;\n\tint tmp = n;\n\tint tmpfor = 0;\n\tint count = 0;\n\tchar ch[100][100];\n\tint x = 0, y = 0;\n\tfor (int i = 0; i < 100; i++)\n\t{\n\t\tfor (int j = 0; j < 100; j++)\n\t\t{\n\t\t\tch[j][i] = ' ';\n\t\t}\n\t}\n\tif (flag == 1)\n\t{\n\n\t\tfor (int i = 0; i < s.length(); i++)\n\t\t{\n\t\t\tif (tmpfor == n)\n\t\t\t{\n\t\t\t\tn--;\n\t\t\t\ttmpfor = 0;\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tif (tmpfor < n)\n\t\t\t{\n\t\t\t\tch[tmp - n + tmpfor][count] = s[i];\n\t\t\t}\n\t\t\ttmpfor++;\n\t\t}\n\t\tcout << ch[x][y];\n\t\twhile (true)\n\t\t{\n\t\t\tif (ch[x + 1][y] != ' ')\n\t\t\t{\n\t\t\t\tx++;\n\t\t\t\twhile (ch[x][y] != ' ')\n\t\t\t\t{\n\t\t\t\t\tcout << ch[x][y];\n\t\t\t\t\ty++;\n\t\t\t\t}\n\t\t\t\tx++;\n\t\t\t\twhile (ch[x][y] != ' ')\n\t\t\t\t{\n\t\t\t\t\tcout << ch[x][y];\n\t\t\t\t\ty--;\n\t\t\t\t}\n\t\t\t\ty++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tcout << endl << endl;\n\t\tfor (int i = 0; i < tmp; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < tmp; j++)\n\t\t\t{\n\t\t\t\tcout << ch[j][i];\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n\t}\n\telse\n\t{\n\t\tn--;\n\t\ttmp = n; //tmpfor=0;n=3;s.lenght()=7;x=1;count=0\n\t\tx = s.length() - ((n * n + n) / 2 + (n * n + n) % 2); // 7 - 6 + 0 = 1\t\t //Гаие дн а\n\t\tif ((n + 1) % 2 == 0)\n\t\t{\n\t\t\tfor (int i = 0; i < s.length(); i++)\n\t\t\t{\n\t\t\t\t//cout << ch[1][1];\n\t\t\t\tif (tmpfor > n && x > 0)\n\t\t\t\t{\n\t\t\t\t\tch[tmp - n + tmpfor][count] = s[i];\n\t\t\t\t\tx--;\n\t\t\t\t\tn--;\n\t\t\t\t\tcount++;\n\t\t\t\t\tcout << endl;\n\t\t\t\t\ttmpfor = 0;\n\t\t\t\t}\n\t\t\t\tif (tmpfor < n && x == 0)\n\t\t\t\t{\n\t\t\t\t\tch[tmp - n + tmpfor][count] = s[i];\n\t\t\t\t\tcout << \" \" << ch[tmp - n + tmpfor][count];\n\t\t\t\t\t//cout << \" x: \" << tmp - n + tmpfor << \" y: \" << count;\n\t\t\t\t}\n\t\t\t\telse if (tmpfor == n && x == 0)\n\t\t\t\t{\n\t\t\t\t\ttmpfor = 0;\n\t\t\t\t\tcount++;\n\t\t\t\t\tn--;\n\t\t\t\t\tcout << endl;\n\n\t\t\t\t\t//ch[tmp - n + tmpfor][count] = s[i];\n\t\t\t\t\t//cout << \" \" << ch[tmp - n + tmpfor][count];\n\t\t\t\t\t//cout << \" x: \" << tmp - n + tmpfor << \" y: \" << count;\n\t\t\t\t\ttmpfor = 0;\n\t\t\t\t\tch[tmp - n + tmpfor][count] = s[i];\n\t\t\t\t\tcout << \" \" << ch[tmp - n + tmpfor][count];\n\t\t\t\t}\n\t\t\t\telse if (tmpfor <= n && x > 0)\n\t\t\t\t{\n\t\t\t\t\tch[tmp - n + tmpfor][count] = s[i];\n\t\t\t\t\tcout << \" \" << ch[tmp - n + tmpfor][count];\n\t\t\t\t\t//cout << \" x: \" << tmp - n + tmpfor << \" y: \" << count;\n\t\t\t\t}\n\t\t\t\ttmpfor++;\n\t\t\t}\n\t\t\tcout << endl;\n\t\t\tcout << endl;\n\t\t\tcout << ch[x][y];\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (ch[x + 1][y] != ' ')\n\t\t\t\t{\n\t\t\t\t\tx++;\n\t\t\t\t\twhile (ch[x][y] != ' ')\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << ch[x][y];\n\t\t\t\t\t\ty++;\n\t\t\t\t\t}\n\t\t\t\t\tx++;\n\t\t\t\t\twhile (ch[x][y] != ' ')\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << ch[x][y];\n\t\t\t\t\t\ty--;\n\t\t\t\t\t}\n\t\t\t\t\ty++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tn++;\n\t\t\ttmp = n;\n\t\t\tfor (int i = 0; i < s.length(); i++)\n\t\t\t{\n\t\t\t\tif (tmpfor == n - 1 && n > x)\n\t\t\t\t{\n\t\t\t\t\tcount++;\n\t\t\t\t\ttmpfor = 0;\n\t\t\t\t\tn--;\n\t\t\t\t\tcout << endl;\n\t\t\t\t}\n\t\t\t\tif (tmpfor < n - 1 && n > x)\n\t\t\t\t{\n\t\t\t\t\tch[tmp - n + tmpfor][count] = s[i];\n\t\t\t\t\tcout << \" \" << ch[tmp - n + tmpfor][count];\n\t\t\t\t\t//cout << \" x: \" << tmp - n + tmpfor << \" y: \" << count;\n\t\t\t\t}\n\t\t\t\tif (tmpfor == n && n <= x)\n\t\t\t\t{\n\t\t\t\t\ttmpfor = 0;\n\t\t\t\t\tn--;\n\t\t\t\t\tcount++;\n\t\t\t\t\tcout << endl;\n\t\t\t\t}\n\t\t\t\tif (tmpfor < n && n <= x)\n\t\t\t\t{\n\t\t\t\t\tch[tmp - n + tmpfor][count] = s[i];\n\t\t\t\t\tcout << \" \" << ch[tmp - n + tmpfor][count];\n\t\t\t\t\t//cout << \" x: \" << tmp - n + tmpfor << \" y: \" << count;\n\t\t\t\t}\n\n\t\t\t\ttmpfor++;\n\t\t\t}\n\t\t\tx = 0;\n\t\t\tcout << endl;\n\t\t\tcout << endl;\n\t\t\tcout << ch[x][y];\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tif (ch[x + 1][y] != ' ')\n\t\t\t\t{\n\n\t\t\t\t\tx++;\n\t\t\t\t\twhile (ch[x][y] != ' ')\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << ch[x][y];\n\t\t\t\t\t\ty++;\n\t\t\t\t\t}\n\t\t\t\t\tx++;\n\t\t\t\t\twhile (ch[x][y] != ' ')\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << ch[x][y];\n\t\t\t\t\t\ty--;\n\t\t\t\t\t}\n\t\t\t\t\ty++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n\n\t}\n\tsystem(\"pause\");\n}" }, { "alpha_fraction": 0.5284403562545776, "alphanum_fraction": 0.5302752256393433, "avg_line_length": 18.5, "blob_id": "05aea91ddf9418d0d758865344af23037d2e9076", "content_id": "4b05f87ead2718afd3c79b5efd83341ad0cf1198", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 545, "license_type": "no_license", "max_line_length": 43, "num_lines": 28, "path": "/aes.py", "repo_name": "kirik200088/Crypro_Algorithm", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\ndef __main__():\n password = input()\n string = input()\n\n sorted_password = sorted(password)\n\n digits = []\n\n for char in password:\n i = sorted_password.index(char)\n digits.append(i)\n sorted_password[i] = \"-\"\n\n height = len(string) // len(password)\n\n decoded_string = \"\"\n\n for i in range(height):\n for digit in digits:\n index = digit * height + i\n decoded_string += string[index]\n\n print(decoded_string)\n\n\nif __name__ == \"__main__\":\n __main__()" }, { "alpha_fraction": 0.4605166018009186, "alphanum_fraction": 0.47822877764701843, "avg_line_length": 18.35714340209961, "blob_id": "ace8b60894ae3ec306784a0f28a882404a84d6a1", "content_id": "3b44c3679a7ac2b28180de0cd110f219fb4c5a89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1355, "license_type": "no_license", "max_line_length": 105, "num_lines": 70, "path": "/elias.py", "repo_name": "kirik200088/Crypro_Algorithm", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport binascii\n\n\ndef main():\n string = input()\n\n start_symbol = string[:1]\n string = string[1:].replace(\" \", \"\")\n\n nulls_count = 0\n next_offset = -1\n new_string = \"\"\n\n for i in range(len(string)):\n char = string[i]\n\n if i > next_offset:\n if char == '0':\n nulls_count += 1\n\n if char == '1':\n next_offset = i + nulls_count\n nulls_count = 0\n\n new_string += char\n\n if i == next_offset:\n new_string += ' '\n\n segments = new_string[:-1].split()\n counters = []\n\n for segment in segments:\n counters.append(int(segment, base=2))\n\n is_nulls = start_symbol == '0'\n\n string = \"\"\n\n for counter in counters:\n for i in range(counter):\n if is_nulls:\n string += \"0\"\n else:\n string += \"1\"\n\n is_nulls = not is_nulls\n\n binary_string = \"\"\n\n for i in range(len(string)):\n binary_string += string[i]\n\n if (i + 1) % 8 == 0:\n binary_string += \" \"\n\n i += 1\n\n final_string = \"\"\n\n for binary_number in binary_string.split():\n final_string += binascii.unhexlify(hex(int(binary_number, 2)).replace(\"0x\", \"\")).decode('cp1251')\n\n print(final_string)\n\n\nif __name__ == \"__main__\":\n main()\n" } ]
4
mitngan/e2openplugin-AutoBackup
https://github.com/mitngan/e2openplugin-AutoBackup
c83830ac62097d2cdd8020a43e6c5135dcf98310
393967b29c1ed6c4f662ac37dfafc2687ebdeb0e
05df9d6433937a1898b5c633186a6d6469060e9b
refs/heads/master
2020-06-23T18:44:37.781223
2019-07-24T20:32:17
2019-07-24T20:32:17
198,720,369
0
0
null
2019-07-24T23:00:06
2019-07-24T20:32:20
2019-07-24T20:32:18
null
[ { "alpha_fraction": 0.6153846383094788, "alphanum_fraction": 0.6219780445098877, "avg_line_length": 34, "blob_id": "fe014bdf5ccfb763ec906025659e44a6d78b2f8c", "content_id": "20466327d71d3abd553d20857938d73a41d52981", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 455, "license_type": "no_license", "max_line_length": 92, "num_lines": 13, "path": "/setup.py", "repo_name": "mitngan/e2openplugin-AutoBackup", "src_encoding": "UTF-8", "text": "from distutils.core import setup\nimport setup_translate\n\npkg = 'Extensions.AutoBackup'\nsetup (name = 'enigma2-plugin-extensions-autobackup',\n version = '0.1',\n description = 'AutoBackup',\n package_dir = {pkg: 'plugin'},\n packages = [pkg],\n package_data = {pkg: \n ['plugin.png', 'backup.cfg', 'settings-backup.sh', 'locale/*/LC_MESSAGES/*.mo']},\n cmdclass = setup_translate.cmdclass, # for translation\n )\n" }, { "alpha_fraction": 0.7005506157875061, "alphanum_fraction": 0.7043625712394714, "avg_line_length": 47.14285659790039, "blob_id": "d8fdc6b373d9bc99377af94a8211554edfdf4a35", "content_id": "dcd4377cf0c59b9af6a2a77f9b04e2e705febbf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2361, "license_type": "no_license", "max_line_length": 169, "num_lines": 49, "path": "/updateallpo.sh", "repo_name": "mitngan/e2openplugin-AutoBackup", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Script to generate pot and po files outside of the normal build process\n#\n# To add create a new language file simply create the folder replace MyLanguageCode by the language code:\n# mkdir ./plugin/locale/MyLanguageCode\n# \n# Exemple: mkdir ./plugin/locale/fr\n#\n# Then run the script\n#\n# Pre-requisite:\n# The following tools must be installed on your system and accessible from path\n# gawk, find, xgettext, gsed, python, msguniq, msgmerge, msgattrib, msgfmt, msginit\n##\n# Author: Pr2 for OpenPLi Team\n# Version: 1.0\n#\nextension=$(gawk -F \".\" '/'\"'\"'Extensions.*'\"'\"'/ { gsub(/'\"'\"'$/,\"\",$2); print $2 }' setup.py )\nprintf \"Retrieve extension name: %s\\n\" $extension\nprintf \"Po files update/creation from script starting.\\n\"\nlanguages=($(ls ./plugin/locale | tr \"\\n\" \" \"))\n#\n# Arguments to generate the pot and po files are not retrieved from the Makefile.\n# So if parameters are changed in Makefile please report the same changes in this script.\n#\ncd plugin\nprintf \"Creating file $extension.pot\\n\"\nfind -s -X .. -name \"*.py\" -exec xgettext --no-wrap -L Python --from-code=UTF-8 -kpgettext:1c,2 --add-comments=\"TRANSLATORS:\" -d $extension -s -o $extension-py.pot {} \\+\ngsed --in-place $extension-py.pot --expression=s/CHARSET/UTF-8/\ncat $extension-py.pot | msguniq --no-wrap --no-location -o $extension.pot -\nrm $extension-py.pot\nOLDIFS=$IFS\nIFS=\" \"\nfor lang in \"${languages[@]}\" ; do\n\tif [ -f ./locale/$lang/LC_MESSAGES/$extension.po ]; then \\\n\t\tprintf \"Updating existing translation file for language %s\\n\" $lang\n\t\tmsgmerge --backup=none --no-wrap --no-location -s -U ./locale/$lang/LC_MESSAGES/$extension.po $extension.pot && touch ./locale/$lang/LC_MESSAGES/$extension.po; \\\n\t\tmsgattrib --no-wrap --no-obsolete ./locale/$lang/LC_MESSAGES/$extension.po -o ./locale/$lang/LC_MESSAGES/$extension.po; \\\n\t\tmsgfmt -o ./locale/$lang/LC_MESSAGES/$extension.mo ./locale/$lang/LC_MESSAGES/$extension.po; \\\n\telse \\\n\t\tprintf \"New file created for %s, please add it to github before commit\\n\" $lang; \\\n\t\tmkdir ./locale/$lang/LC_MESSAGES/; \\\n\t\tmsginit -l ./locale/$lang/LC_MESSAGES/$extension.po -o ./locale/$lang/LC_MESSAGES/$extension.po -i $extension.pot --no-translator; \\\n\t\tmsgfmt -o ./locale/$lang/LC_MESSAGES/$extension.mo ./locale/$lang/LC_MESSAGES/$extension.po; \\\n\tfi\ndone\nIFS=$OLDIFS\ncd ..\nprintf \"Po files update/creation from script finished!\\n\"\n\n\n" } ]
2
h-yes-oo/database
https://github.com/h-yes-oo/database
c0da5313d553d9ed761921bbb399a5f50c875209
2da88323482a2f8b7605e10e9bdfb7913518fcfd
24566b7d764303b040e31e76e121930dc645c125
refs/heads/master
2023-05-28T19:16:43.821113
2021-06-14T10:28:09
2021-06-14T10:28:09
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6276443600654602, "alphanum_fraction": 0.6393251419067383, "avg_line_length": 28.521072387695312, "blob_id": "38bc73a58a274df76c4d28bb55656cdfc62a18cd", "content_id": "2a3f1b5495eb00970d0173d14c7036dd5358670a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7705, "license_type": "no_license", "max_line_length": 94, "num_lines": 261, "path": "/PRJ2_2015-16227/executions.py", "repo_name": "h-yes-oo/database", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport mysql.connector\nfrom mysql.connector import errorcode\n\n#create table with tables schema\ndef create_tables(cursor, tables):\n for table_name in tables:\n table_description = tables[table_name]\n try:\n cursor.execute(table_description)\n except mysql.connector.Error as err:\n if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:\n print(\"already exists.\")\n else:\n print(err.msg)\n\n#insert building, performance, audience function with their schema\ndef insert_building(cursor, name, location, capacity):\n add_building = (\"INSERT INTO building \"\n \"(name, location, capacity) \"\n \"VALUES (%s, %s, %s)\" )\n data_building = (name, location, capacity)\n cursor.execute(add_building, data_building)\n\ndef insert_performance(cursor, name, ptype, price):\n add_performance = (\"INSERT INTO performance \"\n \"(name, type, price) \"\n \"VALUES (%s, %s, %s)\" )\n data_performance = (name, ptype, price)\n cursor.execute(add_performance, data_performance)\n\ndef insert_audience(cursor, name, gender, age):\n add_audience = (\"INSERT INTO audience \"\n \"(name, gender, age) \"\n \"VALUES (%s, %s, %s)\" )\n data_audience = (name, gender, age)\n cursor.execute(add_audience, data_audience)\n\n#return if the performance is already assigned to building\ndef check_building_assigned(cursor, pid):\n check = (\n \"SELECT building FROM performance WHERE id = %s\"\n )\n cursor.execute(check, (pid,))\n for data in cursor:\n #if not assigned, return false\n if data['building'] is None:\n return False\n else:\n return True\n\n#return if assigning performance to building succeed\ndef assign_p_to_b(cursor, pid, bid):\n #check if the performance is already assigned to building\n check = check_building_assigned(cursor,pid)\n if(check):\n print(\"Performance %d is already assigned\" % (pid))\n return False\n #if function not returned, assign performance to building\n update = (\n \"UPDATE performance SET building = %s \"\n \"WHERE id = %s\"\n )\n cursor.execute(update, (bid, pid))\n return True\n\n#return if id exists in table\ndef check_by_id(cursor, table, bid):\n check = (\n \"SELECT 1 FROM {} WHERE id = %s\".format(table)\n )\n cursor.execute(check,(bid, ))\n result = cursor.fetchall()\n if len(result) > 0:\n return True\n else:\n return False\n\n#return if the seat of pid already taken\ndef seat_taken(cursor, pid, seat):\n check = (\n \"SELECT 1 FROM reservation WHERE performance = %s AND seat = %s\"\n )\n cursor.execute(check,(pid, seat))\n result = cursor.fetchall()\n if len(result) > 0:\n print(\"The seat is already taken\")\n return True\n else:\n return False\n\n#insert new data to reservation table\ndef reserve(cursor, pid, aid, seat):\n add_performance = (\"INSERT INTO reservation \"\n \"(audience, performance, seat) \"\n \"VALUES (%s, %s, %s)\" )\n data_performance = (aid, pid, seat)\n cursor.execute(add_performance, data_performance)\n\n#print a line\ndef print_line():\n print(\"-----------------------------------------------------------------------------------\")\n\n#print all building\ndef print_building(curA, curB):\n print_line()\n print(\"%-8s %-30s %-16s %-16s %-16s\" %('id','name','location','capacity','assigned'))\n print_line()\n curA.execute(\"SELECT * FROM building ORDER BY id\")\n result = curA.fetchall()\n for data in result:\n count_query = (\"SELECT COUNT(id) FROM performance WHERE building = %s\")\n curB.execute(count_query, (data['id'], ))\n for x in curB:\n print(\"%-8s %-30s %-16s %-16s %-16s\" %(\n data['id'], data['name'], data['location'], data['capacity'], x[0]\n ))\n print_line()\n\n#basic audience printing format\ndef print_audience(result):\n print_line()\n print(\"%-8s %-36s %-22s %-20s\" %('id','name','gender','age'))\n print_line()\n for data in result:\n print(\"%-8s %-36s %-22s %-20s\" %(\n data['id'], data['name'], data['gender'], data['age']\n ))\n print_line()\n\n#print all audiences\ndef print_audience_all(cursor):\n cursor.execute(\"SELECT * FROM audience ORDER BY id\")\n result = cursor.fetchall()\n print_audience(result)\n\n#print audience of specific performance\ndef print_audience_of_performance(cursor, pid):\n select_query = (\n \"SELECT * FROM audience \"\n \"WHERE id IN (\"\n \"SELECT DISTINCT audience FROM reservation \"\n \"WHERE performance = %s) \"\n \"ORDER BY id\"\n )\n cursor.execute(select_query, (pid,))\n result = cursor.fetchall()\n print_audience(result)\n\n#basic performance printing format\ndef print_performance(curB, result):\n print_line()\n print(\"%-8s %-30s %-16s %-16s %-16s\" %('id','name','type','price','booked'))\n print_line()\n for data in result:\n count_query = (\"SELECT COUNT(id) FROM reservation WHERE performance = %s\")\n curB.execute(count_query, (data['id'], ))\n for x in curB:\n print(\"%-8s %-30s %-16s %-16s %-16s\" %(\n data['id'], data['name'], data['type'], data['price'], x[0]\n ))\n print_line()\n\n#print all performances \ndef print_performance_all(curA, curB):\n curA.execute(\"SELECT * FROM performance ORDER BY id\")\n result = curA.fetchall()\n print_performance(curB, result)\n\n#print performance of specific building\ndef print_performance_of_building(curA, curB, bid):\n select_query = (\n \"SELECT * FROM performance \"\n \"WHERE building = %s ORDER BY id\"\n )\n curA.execute(select_query, (bid,))\n result = curA.fetchall()\n print_performance(curB, result)\n\n#return capacity of the performance\ndef get_capacity(curB, pid):\n select_query = (\n \"SELECT capacity FROM building \"\n \"WHERE id = (\"\n \"SELECT building FROM performance \"\n \"WHERE id = %s)\"\n )\n curB.execute(select_query, (pid, ))\n result = curB.fetchall()\n capacity = result[0][0]\n return capacity\n\n#using for loop, print seat of performance\ndef print_seat_of_performance(curB, pid):\n capacity = get_capacity(curB, pid)\n print_line()\n print(\"%-40s %-40s\" %('seat_number', 'audience_id'))\n print_line()\n for seat in range(1,capacity+1):\n find_query = (\n \"SELECT audience FROM reservation \"\n \"WHERE performance = %s and seat = %s\"\n )\n curB.execute(find_query, (pid, seat))\n result = curB.fetchall()\n if(len(result) == 0):\n print(\"%-40d\" %(seat))\n else:\n print(\"%-40d %-40d\" %(seat, result[0][0]))\n print_line()\n\n#delete existing table and create new tables\ndef refresh(cursor, tables):\n for table_name in ['reservation', 'audience', 'performance','building']:\n sql = \"DROP TABLE IF EXISTS %s\" % table_name\n cursor.execute(sql)\n create_tables(cursor,tables)\n\n#delete from table instance with did\ndef delete(cursor, table, did):\n delete_query = (\n \"DELETE FROM {} WHERE id = %s\".format(table)\n )\n cursor.execute(delete_query,(did,))\n\n#return if all the seat in seat list can be reserved\ndef can_reserve(curB, seat_list, pid):\n capacity = get_capacity(curB, pid)\n for seat in seat_list:\n if seat > capacity:\n print(\"Seat number out of range\")\n return False\n for seat in seat_list:\n if seat_taken(curB, pid, seat):\n return False\n return True\n\n#return one ticket price with respect to the audience's age\ndef get_ticket_price(curB, pid, aid):\n age_query = (\n \"SELECT age FROM audience \"\n \"WHERE id = %s\"\n )\n curB.execute(age_query, (aid,))\n age_result = curB.fetchall()\n age = age_result[0][0]\n if age <= 7:\n return 0\n price_query = (\n \"SELECT price FROM performance \"\n \"WHERE id = %s\"\n )\n curB.execute(price_query, (pid,))\n price_result = curB.fetchall()\n price = price_result[0][0]\n if 8 <= age and age <= 12:\n return price * 0.5\n elif 13 <= age and age <= 18:\n return price * 0.8\n else:\n return price\n" }, { "alpha_fraction": 0.5964173674583435, "alphanum_fraction": 0.6046722531318665, "avg_line_length": 36.15644073486328, "blob_id": "0becb2b0ee595ea443278cba16c30ec1600130f6", "content_id": "7b3a1c9ee86b2784fb275e8be0f99023e32ed2c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12114, "license_type": "no_license", "max_line_length": 102, "num_lines": 326, "path": "/PRJ1-2_2015-16227/run.py", "repo_name": "h-yes-oo/database", "src_encoding": "UTF-8", "text": "import sys\nimport lark\nfrom lark import Lark, Transformer\nfrom berkeleydb import db\nimport os\nimport json\n\n# to reuse prompt message\nprompt = \"DB_2015-16227> \"\n\n#messages\ndef CreateTableSuccess(tableName):\n return f\"'{tableName}' table is created\"\nCharLengthError = \"Char length should be over 0\"\nDuplicatePrimaryKeyDefError = \"Create table has failed: primary key definition is duplicated\"\nDuplicateColumnDefError = \"Create table has failed: column definition is duplicated\"\ndef NonExistingColumnDefError(colName):\n return f\"Create table has failed: '{colName}' does not exists in column definition\"\nTableExistenceError = \"Create table has failed: table with the same name already exists\"\n\nReferenceTypeError = \"Create table has failed: foreign key references wrong type\"\nReferenceNonPrimaryKeyError = \"Create table has failed: foreign key references non primary key column\"\nReferenceColumnExistenceError = \"Create table has failed: foreign key references non existing column\"\nReferenceTableExistenceError = \"Create table has failed: foreign key references non existing table\"\n\ndef DropSuccess(tableName):\n return f\"'{tableName}' table is dropped\"\ndef DropReferencedTableError(tableName):\n return f\"Drop table has failed: '{tableName}' is referenced by other table\"\n\nNoSuchTable = \"No such table\"\n\n# make transformer to print appropriate message for each query\nclass MyTransformer(Transformer):\n def command(self, items):\n if not isinstance(items[0], list):\n exit()\n return items[0]\n\n def query_list(self, items):\n return items\n\n def create_table_query(self, items):\n try:\n info_list = items[2:] #get rid of CREATE TABLE\n table_name = info_list[0]\n file_name = f\"db/{table_name}.db\"\n #check if the file already exists\n if os.path.isfile(file_name):\n raise Exception(TableExistenceError)\n elem_list = info_list[1]\n #initialize variables\n find_primary_key = False\n primary_key = []\n foreign_key = []\n referencing = []\n referenced = []\n col_dict = {}\n #processing table_element_list\n for elem in elem_list:\n if elem[0] == 'primary key':\n #if already find primary key, raise error\n if find_primary_key:\n raise Exception(DuplicatePrimaryKeyDefError)\n else:\n find_primary_key = True\n primary_key = elem[1]\n #process foreign key after get all column information\n elif elem[0] == 'foreign key':\n continue\n #store all column names and infos into a dict\n else:\n #if already have the same column, raise error\n if elem[0] in col_dict:\n raise Exception(DuplicateColumnDefError)\n else:\n #if char length smaller than 1, raise error\n if elem[1]['type'] == 'error':\n raise Exception(CharLengthError)\n else:\n col_dict[elem[0]] = elem[1]\n #process all foreign keys\n for elem in elem_list:\n if elem[0] == 'foreign key':\n fk_list = elem[1]\n referenced_table = elem[2]\n referenced_col_list = elem[3]\n # check if foreign key is one of columns\n for f in fk_list:\n if f not in col_dict:\n raise Exception(NonExistingColumnDefError(f))\n # check if num of foreign keys and num of referenced cols is the same\n if (len(fk_list) != len(referenced_col_list)):\n Exception(ReferenceTypeError)\n ref_file_name = f\"db/{referenced_table}.db\"\n # check if the referenced_table exists\n if not os.path.isfile(ref_file_name):\n raise Exception(ReferenceTableExistenceError)\n else:\n refDB = db.DB()\n refDB.open(ref_file_name, dbtype=db.DB_HASH)\n ref_pk_list = json.loads(refDB.get(b\"primary_key\"))\n ref_col_list = json.loads(refDB.get(b\"columns\"))\n # check if referenced table has foreign key\n for rf_col in referenced_col_list:\n if rf_col not in ref_col_list:\n raise Exception(ReferenceColumnExistenceError)\n # check if foreign key is primary key of referenced table\n for rf_col in referenced_col_list:\n if rf_col not in ref_pk_list:\n raise Exception(ReferenceNonPrimaryKeyError)\n # check if foreign key contains all primary keys of referenced table\n if len(referenced_col_list) != len(ref_pk_list):\n raise Exception(ReferenceNonPrimaryKeyError)\n else:\n for i in range(len(fk_list)):\n # check if fk_list[i] and referenced_col_list[i] has the same type\n ori_type = json.loads(refDB.get(referenced_col_list[i].encode('utf-8')))['type']\n fk_type = col_dict[fk_list[i]]['type']\n if ori_type != fk_type:\n raise Exception(ReferenceTypeError)\n #ready to reference\n #add referenced_table to referencing list of this new table\n referencing.append(referenced_table)\n #add this new table to referenced list of the referenced_table\n rf_by = json.loads(refDB.get(b\"referenced\"))\n rf_by.append(table_name)\n refDB.put(b\"referenced\", json.dumps(rf_by).encode('utf-8'))\n #add all foreign keys to foreign_key\n for fk in fk_list:\n foreign_key.append(fk)\n refDB.close()\n #check if primary_key and foreign_key is in column list and change their properties\n for p in primary_key:\n if p in col_dict:\n col_dict[p]['null'] = 'N'\n col_dict[p]['key'] = 'PRI'\n else:\n raise Exception(NonExistingColumnDefError(p))\n\n for f in foreign_key:\n if f in col_dict:\n if col_dict[f]['key'] == '':\n col_dict[f]['key'] = 'FOR'\n else:\n col_dict[f]['key'] += '/FOR'\n else:\n raise Exception(NonExistingColumnDefError(f))\n #encode variables and put to database\n encoded_p = json.dumps(primary_key).encode('utf-8')\n encoded_f = json.dumps(foreign_key).encode('utf-8')\n\n myDB = db.DB()\n myDB.open(file_name, dbtype=db.DB_HASH, flags=db.DB_CREATE)\n for key in col_dict.keys():\n myDB.put(key.encode('utf-8'), json.dumps(col_dict[key]).encode('utf-8'))\n myDB.put(b\"primary_key\",encoded_p)\n myDB.put(b\"foreign_key\",encoded_f)\n myDB.put(b\"referenced\", json.dumps(referenced).encode('utf-8'))\n myDB.put(b\"referencing\", json.dumps(referencing).encode('utf-8'))\n myDB.put(b\"columns\", json.dumps(list(col_dict.keys())).encode('utf-8'))\n myDB.close()\n print(prompt, CreateTableSuccess(table_name), sep=\"\")\n except Exception as e:\n print(prompt,e,sep='')\n\n\n def drop_table_query(self, items):\n try:\n table_name = items[2]\n file_name = f\"db/{table_name}.db\"\n #check if the table exists\n if not os.path.isfile(file_name):\n raise Exception(NoSuchTable)\n else:\n #get the table's referenced and referencing\n myDB = db.DB()\n myDB.open(file_name, dbtype=db.DB_HASH)\n referenced_by = json.loads(myDB.get(b\"referenced\"))\n referencing = json.loads(myDB.get(b\"referencing\"))\n myDB.close()\n #if no table is referencing it, can drop\n if len(referenced_by) == 0:\n #for all table which this table is referencing,\n #remove this table's name from their referenced list\n for rf in referencing:\n rf_file = f\"db/{rf}.db\"\n rfDB = db.DB()\n rfDB.open(rf_file, dbtype=db.DB_HASH)\n referenced = json.loads(rfDB.get(b\"referenced\"))\n referenced.remove(table_name)\n rfDB.put(b\"referenced\", json.dumps(referenced).encode('utf-8'))\n rfDB.close()\n #delete the database file\n os.remove(file_name)\n print(prompt, DropSuccess(table_name), sep=\"\")\n #if the table is referenced by more than one table, cannot drop\n else:\n raise Exception(DropReferencedTableError(table_name))\n except Exception as e:\n print(prompt, e, sep='')\n\n #show all tables by their file name\n def show_tables_query(self, items):\n print('----------------')\n tables = os.listdir('../PRJ1-3_2015-16227/db')\n for t in tables:\n print(t[:-3])\n print('----------------')\n\n def desc_query(self, items):\n try:\n table_name = items[1]\n file_name = f\"db/{table_name}.db\"\n #check if the table exists\n if not os.path.isfile(file_name):\n raise Exception(NoSuchTable)\n else:\n myDB = db.DB()\n myDB.open(file_name, dbtype=db.DB_HASH)\n print(\"------------------------------------------------------------\")\n print(f\"table_name {table_name}\")\n print('%-20s%-20s%-20s%-20s' % ('column_name', 'type', 'null', 'key'))\n #get column list and iterate\n col_names = json.loads(myDB.get(b'columns'))\n for key in col_names:\n val = json.loads(myDB.get(key.encode('utf-8')))\n print('%-20s%-20s%-20s%-20s' % (key,val['type'], val['null'], val['key']))\n myDB.close()\n print(\"-----------------------------------------------------------\")\n except Exception as e:\n print(prompt,e,sep='')\n\n def select_query(self, items):\n print(prompt,\"'SELECT' requested\",sep='')\n def insert_query(self, items):\n print(prompt,\"'INSERT' requested\",sep='')\n def delete_query(self, items):\n print(prompt,\"'DELETE' requested\",sep='')\n\n def table_element_list(self, items):\n elem_list = items[1:-1] # get rid of LP and RP\n return elem_list\n\n def table_element(self, items):\n return items[0]\n\n def column_definition(self, items):\n dict = {}\n dict['type'] = items[1]\n #if not null constraint, set null to N\n if len(items) > 2:\n dict['null'] = 'N'\n else:\n dict['null'] = 'Y'\n dict['key'] = ''\n return (items[0], dict)\n\n def data_type(self, items):\n length = len(items)\n if (length == 4):\n #if char length smaller than 1, set type to 'error'\n if int(items[2]) <= 0:\n return 'error'\n result = ''\n for i in range(length):\n result += str(items[i])\n return result.lower()\n\n def table_constraint_definition(self, items):\n return items[0]\n\n def primary_key_constraint(self, items):\n return ['primary key', items[2]]\n\n def referential_constraint(self, items):\n col_list = items[2]\n referenced_table = items[4]\n referenced_col_list = items[5]\n return ['foreign key', col_list, referenced_table, referenced_col_list ]\n\n def column_name_list(self, items):\n return list(items[1:-1])\n #table name to lower case\n def table_name(self, t):\n (t,) = t\n return t.lower()\n #column name to lower case\n def column_name(self, c):\n (c,) = c\n return c.lower()\n def IDENTIFIER(self, s):\n return str(s)\n\n\nif __name__ == '__main__':\n\n # make sql_parser with grammar.lark file\n with open('../PRJ1-3_2015-16227/grammar.lark') as file:\n sql_parser = Lark(file.read(), start=\"command\", lexer=\"standard\")\n\n #get input until the program ended\n while(True):\n #get input with prompt message\n data_input = input(prompt)\n #if command 'exit' is given, end the program\n if(data_input == 'exit'):\n sys.exit()\n #get additional input until it ends with semicolon\n while len(data_input) == 0 or data_input[-1] != ';':\n #to prevent error, add white space to data_input\n data_input += ' '\n data_input += input()\n #split the input by semicolon\n input_list = list(data_input.split(';'))\n #exclude the last element of input_list since it is empty string\n for i in range(len(input_list) - 1):\n #restore semicolon in the end of the command\n command = input_list[i] + ';'\n #using try ... except, process the syntax error\n try:\n result = sql_parser.parse(command)\n MyTransformer().transform(result)\n except Exception as e:\n print(prompt,\"Syntax error\",sep='')\n break\n\n" }, { "alpha_fraction": 0.6248062252998352, "alphanum_fraction": 0.6930232644081116, "avg_line_length": 22.454545974731445, "blob_id": "03b1fd6ed89dc9a6cb919d08d9dd80836acd375d", "content_id": "0f05b4d741b7544c09252549e78d1bf9240c441a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1290, "license_type": "no_license", "max_line_length": 44, "num_lines": 55, "path": "/sample2.sql", "repo_name": "h-yes-oo/database", "src_encoding": "UTF-8", "text": "create table students (\n id int,\n birthday date,\n primary key(id)\n);\n\ncreate table class (\n num int,\n start_date date,\n primary key(num)\n);\n\ncreate table enrolls (\n id int,\n lecture_name char(50),\n num int,\n primary key(lecture_name),\n foreign key(id) references students(id),\n foreign key(num) references class(num)\n);\n\ninsert into students values(1, null);\ninsert into students values(2, 2020-02-16);\ninsert into students values(3, 2020-03-16);\ninsert into students values(4, 2020-04-16);\ninsert into students values(5, 2020-05-16);\ninsert into students values(6, 2020-06-16);\n\ninsert into class values(5, null);\ninsert into class values(6, null);\ninsert into class values(3, 2020-03-16);\ninsert into class values(4, 2020-03-17);\n\ninsert into enrolls values(1,'hihi',6);\ninsert into enrolls values(1,'hihello',5);\ninsert into enrolls values(2,'lec6',5);\ninsert into enrolls values(3,'hihi3',6);\ninsert into enrolls values(4,'hi44',3);\ninsert into enrolls values(5,'leadfa',4);\n\nselect * from account;\n\ncreate table account (\n ACCOUNT_NUMBER date,\n branch_name char(20),\n BALANCE int,\n primary key(account_number)\n);\n\ncreate table loan (\n ACCOUNT_NUMBER date,\n branch_name char(20),\n BALANCE int,\n primary key(account_number)\n);\n" }, { "alpha_fraction": 0.5569864511489868, "alphanum_fraction": 0.583387017250061, "avg_line_length": 34.318180084228516, "blob_id": "8548f90a5c3151fbba66325b37ae4fbb315aad62", "content_id": "a1043f5d72f02b199645d5d1ee46cedbf1bd9b47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1553, "license_type": "no_license", "max_line_length": 69, "num_lines": 44, "path": "/PRJ2_2015-16227/table.py", "repo_name": "h-yes-oo/database", "src_encoding": "UTF-8", "text": "#store table schemas for building, performance, audience, reservation\nTABLES = {}\nTABLES['building'] = (\n \"CREATE TABLE `building` (\"\n \" `id` int(11) NOT NULL AUTO_INCREMENT,\"\n \" `name` varchar(200) NOT NULL,\"\n \" `location` varchar(200) NOT NULL,\"\n \" `capacity` int(11) NOT NULL,\"\n \" PRIMARY KEY (`id`)\"\n \") ENGINE=InnoDB\")\n\nTABLES['performance'] = (\n \"CREATE TABLE `performance` (\"\n \" `id` int(11) NOT NULL AUTO_INCREMENT,\"\n \" `name` varchar(200) NOT NULL,\"\n \" `type` varchar(200) NOT NULL,\"\n \" `price` int(11) NOT NULL,\"\n \" `building` int(11),\"\n \" PRIMARY KEY (`id`),\"\n \" CONSTRAINT `performance_ibfk_1` FOREIGN KEY (`building`) \"\n \" REFERENCES `building` (`id`) ON DELETE CASCADE\"\n \") ENGINE=InnoDB\")\n\nTABLES['audience'] = (\n \"CREATE TABLE `audience` (\"\n \" `id` int(11) NOT NULL AUTO_INCREMENT,\"\n \" `name` varchar(200) NOT NULL,\"\n \" `gender` char(1) NOT NULL,\"\n \" `age` int(11) NOT NULL,\"\n \" PRIMARY KEY (`id`)\"\n \") ENGINE=InnoDB\")\n\nTABLES['reservation'] = (\n \" CREATE TABLE `reservation` (\"\n \" `id` int(11) NOT NULL AUTO_INCREMENT,\"\n \" `audience` int(11) NOT NULL,\"\n \" `performance` int(11) NOT NULL,\"\n \" `seat` int(11) NOT NULL,\"\n \" PRIMARY KEY (`id`),\"\n \" CONSTRAINT `reservation_ibfk_1` FOREIGN KEY (`audience`) \"\n \" REFERENCES `audience` (`id`) ON DELETE CASCADE,\"\n \" CONSTRAINT `reservation_ibfk_2` FOREIGN KEY (`performance`) \"\n \" REFERENCES `performance` (`id`) ON DELETE CASCADE\"\n \") ENGINE=InnoDB\")" }, { "alpha_fraction": 0.6503198146820068, "alphanum_fraction": 0.6567164063453674, "avg_line_length": 36.540000915527344, "blob_id": "c3da2e56bab43bab23036e836de8134f82f22662", "content_id": "b194fd4662cee4814a9b58b4cb555d86f4b91399", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1876, "license_type": "no_license", "max_line_length": 68, "num_lines": 50, "path": "/PRJ1-1_2015-16227/hw1/run.py", "repo_name": "h-yes-oo/database", "src_encoding": "UTF-8", "text": "import sys\nfrom lark import Lark, Transformer\n#to reuse prompt message\nprompt = \"DB_2015-16227> \"\n#make transformer to print appropriate message for each query\nclass MyTransformer(Transformer):\n def create_table_query(self, items):\n print(prompt,\"'CREATE TABLE' requested\",sep='')\n def drop_table_query(self, items):\n print(prompt,\"'DROP TABLE' requested\",sep='')\n def select_query(self, items):\n print(prompt,\"'SELECT' requested\",sep='')\n def insert_query(self, items):\n print(prompt,\"'INSERT' requested\",sep='')\n def desc_query(self, items):\n print(prompt,\"'DESC' requested\",sep='')\n def delete_query(self, items):\n print(prompt,\"'DELETE' requested\",sep='')\n def show_tables_query(self, items):\n print(prompt,\"'SHOW TABLES' requested\",sep='')\n#make sql_parser with grammar.lark file\nwith open('grammar.lark') as file:\n sql_parser = Lark(file.read(), start=\"command\", lexer=\"standard\")\n\nif __name__ == '__main__':\n #get input until the program ended\n while(True):\n #get input with prompt message\n data_input = input(prompt)\n #if command 'exit' is given, end the program\n if(data_input == 'exit'):\n sys.exit()\n #get additional input until it ends with semicolon\n while len(data_input) == 0 or data_input[-1] != ';':\n #to prevent error, add white space to data_input\n data_input += ' '\n data_input += input()\n #split the input by semicolon\n input_list = list(data_input.split(';'))\n #exclude the last element of input_list since it is empty string\n for i in range(len(input_list) - 1):\n #restore semicolon in the end of the command\n command = input_list[i] + ';'\n #using try ... except, process the syntax error\n try:\n result = sql_parser.parse(command)\n MyTransformer().transform(result)\n except:\n print(prompt,\"Syntax error\",sep='')\n break" }, { "alpha_fraction": 0.4639105498790741, "alphanum_fraction": 0.47336888313293457, "avg_line_length": 36.12033462524414, "blob_id": "324ef9a92e68851c9471edcb6d6da2f78e2fe6e5", "content_id": "2588cb1c2119965b5ac5d8b3f3bec1611d62cfd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 48740, "license_type": "no_license", "max_line_length": 102, "num_lines": 1313, "path": "/PRJ1-3_2015-16227/run.py", "repo_name": "h-yes-oo/database", "src_encoding": "UTF-8", "text": "import sys\nimport lark\nfrom lark import Lark, Transformer\nfrom berkeleydb import db\nimport os\nimport json\nfrom exceptions import *\nimport datetime\nfrom prettytable import PrettyTable\nimport copy\n\n# to reuse prompt message\nprompt = \"DB_2015-16227> \"\n\n#messages\ndef CreateTableSuccess(tableName):\n return f\"'{tableName}' table is created\"\n\ndef DropSuccess(tableName):\n return f\"'{tableName}' table is dropped\"\n\n\n\n# make transformer to print appropriate message for each query\nclass MyTransformer(Transformer):\n def command(self, items):\n if not isinstance(items[0], list):\n exit()\n return items[0]\n\n def query_list(self, items):\n return items\n\n def create_table_query(self, items):\n try:\n info_list = items[2:] #get rid of CREATE TABLE\n table_name = info_list[0]\n file_name = f\"db/{table_name}.db\"\n #check if the file already exists\n if os.path.isfile(file_name):\n raise TableExistenceError()\n elem_list = info_list[1]\n #initialize variables\n find_primary_key = False\n primary_key = []\n foreign_key = []\n referencing = []\n referenced = []\n col_dict = {}\n #processing table_element_list\n for elem in elem_list:\n if elem[0] == 'primary key':\n #if already find primary key, raise error\n if find_primary_key:\n raise DuplicatePrimaryKeyDefError()\n else:\n find_primary_key = True\n primary_key = elem[1]\n #process foreign key after get all column information\n elif elem[0] == 'foreign key':\n continue\n #store all column names and infos into a dict\n else:\n #if already have the same column, raise error\n if elem[0] in col_dict:\n raise DuplicateColumnDefError()\n else:\n col_dict[elem[0]] = elem[1]\n #process all foreign keys\n for elem in elem_list:\n if elem[0] == 'foreign key':\n fk_list = elem[1]\n referenced_table = elem[2]\n referenced_col_list = elem[3]\n # check if foreign key is one of columns\n for f in fk_list:\n if f not in col_dict:\n raise NonExistingColumnDefError(f)\n # check if num of foreign keys and num of referenced cols is the same\n if (len(fk_list) != len(referenced_col_list)):\n raise ReferenceTypeError()\n ref_file_name = f\"db/{referenced_table}.db\"\n # check if the referenced_table exists\n if not os.path.isfile(ref_file_name):\n raise ReferenceTableExistenceError()\n else:\n refDB = db.DB()\n refDB.open(ref_file_name, dbtype=db.DB_HASH)\n ref_pk_list = json.loads(refDB.get(b\"primary_key\"))\n ref_col_list = json.loads(refDB.get(b\"columns\"))\n # check if referenced table has foreign key\n for rf_col in referenced_col_list:\n if rf_col not in ref_col_list:\n raise ReferenceColumnExistenceError()\n # check if foreign key is primary key of referenced table\n for rf_col in referenced_col_list:\n if rf_col not in ref_pk_list:\n raise ReferenceNonPrimaryKeyError()\n # check if foreign key contains all primary keys of referenced table\n if len(referenced_col_list) != len(ref_pk_list):\n raise ReferenceNonPrimaryKeyError()\n else:\n for i in range(len(fk_list)):\n # check if fk_list[i] and referenced_col_list[i] has the same type\n ori_type = json.loads(refDB.get(referenced_col_list[i].encode('utf-8')))['type']\n fk_type = col_dict[fk_list[i]]['type']\n if ori_type != fk_type:\n raise ReferenceTypeError()\n #ready to reference\n #add referenced_table to referencing list of this new table\n referencing.append(referenced_table)\n #add this new table to referenced list of the referenced_table\n rf_by = json.loads(refDB.get(b\"referenced\"))\n rf_by.append(table_name)\n refDB.put(b\"referenced\", json.dumps(rf_by).encode('utf-8'))\n #add all foreign key information to foreign_key\n ordered_fk_list = ['' for _ in range(len(fk_list))]\n for idx in range(len(fk_list)):\n pk = referenced_col_list[idx]\n ori_idx = ref_pk_list.index(pk)\n ordered_fk_list[ori_idx] = fk_list[idx]\n\n foreign_key.append([ordered_fk_list, referenced_table, ref_pk_list])\n refDB.close()\n #check if primary_key and foreign_key is in column list and change their properties\n for p in primary_key:\n if p in col_dict:\n col_dict[p]['null'] = 'N'\n col_dict[p]['key'] = 'PRI'\n else:\n raise NonExistingColumnDefError(p)\n\n for fk_info in foreign_key:\n for f in fk_info[0]:\n if f in col_dict:\n if col_dict[f]['key'] == '':\n col_dict[f]['key'] = 'FOR'\n else:\n col_dict[f]['key'] += '/FOR'\n else:\n raise NonExistingColumnDefError(f)\n '''\n for f in foreign_key:\n if f in col_dict:\n if col_dict[f]['key'] == '':\n col_dict[f]['key'] = 'FOR'\n else:\n col_dict[f]['key'] += '/FOR'\n else:\n raise NonExistingColumnDefError(f)\n '''\n #encode variables and put to database\n encoded_p = json.dumps(primary_key).encode('utf-8')\n encoded_f = json.dumps(foreign_key).encode('utf-8')\n\n myDB = db.DB()\n myDB.open(file_name, dbtype=db.DB_HASH, flags=db.DB_CREATE)\n for key in col_dict.keys():\n myDB.put(key.encode('utf-8'), json.dumps(col_dict[key]).encode('utf-8'))\n myDB.put(b\"primary_key\",encoded_p)\n myDB.put(b\"foreign_key\",encoded_f)\n myDB.put(b\"referenced\", json.dumps(referenced).encode('utf-8'))\n myDB.put(b\"referencing\", json.dumps(referencing).encode('utf-8'))\n myDB.put(b\"columns\", json.dumps(list(col_dict.keys())).encode('utf-8'))\n myDB.close()\n print(prompt, CreateTableSuccess(table_name), sep=\"\")\n except Exception as e:\n print(prompt,e,sep='')\n\n\n def drop_table_query(self, items):\n try:\n table_name = items[2]\n file_name = f\"db/{table_name}.db\"\n #check if the table exists\n if not os.path.isfile(file_name):\n raise NoSuchTable()\n else:\n #get the table's referenced and referencing\n myDB = db.DB()\n myDB.open(file_name, dbtype=db.DB_HASH)\n referenced_by = json.loads(myDB.get(b\"referenced\"))\n referencing = json.loads(myDB.get(b\"referencing\"))\n myDB.close()\n #if no table is referencing it, can drop\n if len(referenced_by) == 0:\n #for all table which this table is referencing,\n #remove this table's name from their referenced list\n for rf in referencing:\n rf_file = f\"db/{rf}.db\"\n rfDB = db.DB()\n rfDB.open(rf_file, dbtype=db.DB_HASH)\n referenced = json.loads(rfDB.get(b\"referenced\"))\n referenced.remove(table_name)\n rfDB.put(b\"referenced\", json.dumps(referenced).encode('utf-8'))\n rfDB.close()\n #delete the database file\n os.remove(file_name)\n print(prompt, DropSuccess(table_name), sep=\"\")\n #if the table is referenced by more than one table, cannot drop\n else:\n raise DropReferencedTableError(table_name)\n except Exception as e:\n print(prompt, e, sep='')\n\n #show all tables by their file name\n def show_tables_query(self, items):\n print('----------------')\n tables = os.listdir('../PRJ1-3_2015-16227/db')\n for t in tables:\n print(t[:-3])\n print('----------------')\n\n def desc_query(self, items):\n try:\n table_name = items[1]\n file_name = f\"db/{table_name}.db\"\n #check if the table exists\n if not os.path.isfile(file_name):\n raise NoSuchTable()\n else:\n myDB = db.DB()\n myDB.open(file_name, dbtype=db.DB_HASH)\n print(\"------------------------------------------------------------\")\n print(f\"table_name {table_name}\")\n print('%-20s%-20s%-20s%-20s' % ('column_name', 'type', 'null', 'key'))\n #get column list and iterate\n col_names = json.loads(myDB.get(b'columns'))\n for key in col_names:\n val = json.loads(myDB.get(key.encode('utf-8')))\n print('%-20s%-20s%-20s%-20s' % (key,val['type'], val['null'], val['key']))\n myDB.close()\n print(\"-----------------------------------------------------------\")\n except Exception as e:\n print(prompt,e,sep='')\n\n def select_query(self, items):\n cols, col_nick = items[1]\n table_expression = items[2]\n where = table_expression[0]\n tables, nickname = table_expression[1][0]\n #check if all tables exists\n existing_tables = os.listdir('../PRJ1-3_2015-16227/db')\n existing_tables = list(map(lambda x : x[:-3], existing_tables))\n for table in tables:\n if table not in existing_tables:\n raise SelectTableExistenceError(table)\n columns = []\n all_cols = []\n for table in tables:\n myDB = db.DB()\n myDB.open(f\"db/{table}.db\", dbtype=db.DB_HASH)\n col_names = json.loads(myDB.get(b'columns'))\n for col in col_names:\n all_cols.append(f\"{table}.{col}\")\n myDB.close()\n # if col list is *, add all columns of tables\n if len(cols) == 0:\n columns = all_cols\n else:\n #if col list is given, check if the cols are all right and sort by tables\n cols_copy = [ c for c in cols ]\n for table in tables:\n myDB = db.DB()\n myDB.open(f\"db/{table}.db\", dbtype=db.DB_HASH)\n col_names = json.loads(myDB.get(b'columns'))\n for col in cols:\n col_info = col.split('.')\n if len(col_info) > 1:\n if col_info[0] == table or (col_info[0] in nickname and nickname[col_info[0]] == table):\n if col_info[1] in col_names:\n columns.append(f\"{table}.{col_info[1]}\")\n try:\n cols_copy.remove(col)\n except:\n #if duplicate column name exist, ambiguous\n raise SelectColumnResolveError(col)\n else:\n raise SelectColumnResolveError(col)\n else:\n if col in col_names:\n columns.append(f\"{table}.{col}\")\n try:\n cols_copy.remove(col)\n except:\n #if duplicate column name exist, ambiguous\n raise SelectColumnResolveError(col)\n myDB.close()\n #if not existing column\n if len(cols_copy) > 0:\n raise SelectColumnResolveError(cols_copy[0])\n\n #get all possible result from specified tables\n rows = []\n for table in tables:\n infos = []\n myDB = db.DB()\n myDB.open(f\"db/{table}.db\", dbtype=db.DB_HASH)\n col_names = json.loads(myDB.get(b'columns'))\n info_list = list(map(lambda col: bytes(col, encoding=\"utf-8\"), col_names))\n info_list += [b'primary_key', b'foreign_key', b'referencing', b'referenced', b'columns']\n cursor = myDB.cursor()\n data = cursor.first()\n while data:\n key, value = data\n val_dict = json.loads(value)\n if key not in info_list:\n info = []\n for col in all_cols:\n if len(col.split('.')) > 1:\n t_name, col_name = col.split('.')\n if t_name == table or (t_name in nickname and nickname[t_name] == table):\n if val_dict[col_name] is None:\n info.append('null')\n else:\n info.append(val_dict[col_name])\n else:\n info.append(None)\n else:\n if col in val_dict:\n if val_dict[col] is None:\n info.append('null')\n else:\n info.append(val_dict[col])\n else:\n info.append(None)\n infos.append(info)\n data = cursor.next()\n myDB.close()\n rows.append(infos)\n #get cartesian join of the result\n for i in range(1,len(rows)):\n new_row = []\n for j in range(len(rows[i])):\n for row in rows[i-1]:\n r = [x if y is None else y for x,y in zip(rows[i][j], row)]\n new_row.append(r)\n rows[i] = new_row\n \n final_row = [r for r in rows[-1]]\n\n if where:\n #with where clause\n condition = table_expression[1][1]\n predicates = []\n p_col = {}\n def flatten(l):\n for i in l:\n if type(i) == list or (type(i) == tuple and len(i) == 2):\n flatten(i)\n else:\n if type(i) == tuple and len(i) == 3:\n predicates.append(i)\n flatten(condition)\n #check if comparable\n for idx in range(len(predicates)):\n p = predicates[idx]\n oper = p[1]\n if oper in ['is','is not']:\n #null predicate\n #find if the col name is valid\n col_name = p[0]\n if col_name in col_nick:\n col_name = col_nick[col_name]\n if len(col_name.split('.')) > 1:\n t_n , c_n = col_name.split('.')\n #check if specified table\n if t_n not in tables:\n if t_n not in nickname:\n raise WhereTableNotSpecified()\n else:\n t_n = nickname[t_n]\n #check if the col exist\n myDB = db.DB()\n myDB.open(f\"db/{t_n}.db\", dbtype=db.DB_HASH)\n c_list = json.loads(myDB.get(b'columns'))\n if c_n not in c_list:\n raise WhereColumnNotExist()\n else:\n predicates[idx] = (f\"{t_n}.{c_n}\",p[1],p[2])\n p_col[col_name] = f\"{t_n}.{c_n}\"\n myDB.close()\n else:\n Find = False\n for t_n in tables:\n myDB = db.DB()\n myDB.open(f\"db/{t_n}.db\", dbtype=db.DB_HASH)\n c_list = json.loads(myDB.get(b'columns'))\n if col_name in c_list:\n if Find:\n #if same col name found in two different tables, ambiguous\n raise WhereAmbiguousReference()\n else:\n Find = True\n predicates[idx] = (f\"{t_n}.{col_name}\",p[1],p[2])\n p_col[col_name] = f\"{t_n}.{col_name}\"\n myDB.close()\n if not Find:\n raise WhereColumnNotExist()\n else:\n #comparison predicate\n two_type = []\n stripped_tuple = [p[0],p[1],p[2]]\n for op_idx in (0,2):\n if p[op_idx][0] in ['str','int','date']:\n two_type.append(p[op_idx][0])\n stripped_tuple[op_idx] = p[op_idx][1]\n else:\n #if col name, check if valid col name\n col_name = p[op_idx][1]\n if col_name in col_nick:\n col_name = col_nick[col_name]\n if len(col_name.split('.')) > 1:\n t_n , c_n = col_name.split('.')\n #check if specified table\n if t_n not in tables:\n if t_n not in nickname:\n raise WhereTableNotSpecified()\n else:\n t_n = nickname[t_n]\n #check if the col exist\n myDB = db.DB()\n myDB.open(f\"db/{t_n}.db\", dbtype=db.DB_HASH)\n c_list = json.loads(myDB.get(b'columns'))\n if c_n in c_list:\n #find it\n stripped_tuple[op_idx] = f\"{t_n}.{c_n}\"\n p_col[col_name] = f\"{t_n}.{c_n}\"\n type_s = json.loads(myDB.get(c_n.encode('utf-8')))['type']\n if type_s in ['int','date']:\n two_type.append(type_s)\n else:\n two_type.append('str')\n else:\n raise WhereColumnNotExist()\n myDB.close()\n else:\n Find = False\n find_type = ''\n for t_n in tables:\n myDB = db.DB()\n myDB.open(f\"db/{t_n}.db\", dbtype=db.DB_HASH)\n c_list = json.loads(myDB.get(b'columns'))\n if col_name in c_list:\n if Find:\n #if same col name found in two different tables, ambiguous\n raise WhereAmbiguousReference()\n else:\n Find = True\n stripped_tuple[op_idx] = f\"{t_n}.{col_name}\"\n p_col[col_name] = f\"{t_n}.{col_name}\"\n type_s = json.loads(myDB.get(col_name.encode('utf-8')))['type']\n if type_s in ['int','date']:\n find_type = type_s\n else:\n find_type = 'str'\n myDB.close()\n if Find:\n two_type.append(find_type)\n else:\n raise WhereColumnNotExist()\n if len(two_type) == 2:\n if two_type[0] != two_type[1]:\n raise WhereIncomparableError()\n predicates[idx] = tuple(stripped_tuple)\n\n final = []\n\n for row in final_row:\n cond = copy.deepcopy(condition)\n def evaluate(l,row):\n for idx in range(len(l)):\n i=l[idx]\n if type(i) == list or (type(i) == tuple and len(i) == 2):\n evaluate(i,row)\n else:\n if type(i) == tuple and len(i) == 3:\n oper = i[1]\n if oper in ['is','is not']:\n #null predicate\n col_name = i[0]\n if col_name in col_nick:\n col_name = col_nick[col_name]\n if col_name in p_col:\n col_name = p_col[col_name]\n ridx = all_cols.index(col_name)\n if oper == 'is':\n if row[ridx] == 'null':\n l[idx] = True\n else:\n l[idx] = False\n elif oper == 'is not':\n if row[ridx] == 'null':\n l[idx] = False\n else:\n l[idx] = True\n else:\n #comparison predicate\n two_type = []\n eval = [i[0],i[1],i[2]]\n #if val op col\n if i[0][0] in ['str','int','date'] and i[2][0] == 'col':\n eval[0] = i[0][1]\n col_name = i[2][1]\n if col_name in col_nick:\n col_name = col_nick[col_name]\n if col_name in p_col:\n col_name = p_col[col_name]\n ridx = all_cols.index(col_name)\n eval[2] = row[ridx]\n #elif col op val\n elif i[2][0] in ['str','int','date'] and i[0][0] == 'col':\n eval[2] = i[2][1]\n col_name = i[0][1]\n if col_name in col_nick:\n col_name = col_nick[col_name]\n if col_name in p_col:\n col_name = p_col[col_name]\n ridx = all_cols.index(col_name)\n eval[0] = row[ridx]\n #elif col op col\n elif i[2][0] == 'col' and i[0][0] == 'col':\n col_name = i[0][1]\n if col_name in col_nick:\n col_name = col_nick[col_name]\n if col_name in p_col:\n col_name = p_col[col_name]\n ridx = all_cols.index(col_name)\n eval[0] = row[ridx]\n col_name = i[2][1]\n if col_name in col_nick:\n col_name = col_nick[col_name]\n if col_name in p_col:\n col_name = p_col[col_name]\n ridx = all_cols.index(col_name)\n eval[2] = row[ridx]\n #elif val op val\n else:\n eval[0] = i[0][1]\n eval[2] = i[2][1]\n #evaluate\n if eval[1] == \"<\":\n if eval[0] < eval[2]:\n l[idx] = True\n else: \n l[idx] = False\n if eval[1] == \">\":\n if eval[0] > eval[2]:\n l[idx] = True\n else: \n l[idx] = False\n if eval[1] == \"=\":\n if eval[0] == eval[2]:\n l[idx] = True\n else: \n l[idx] = False\n if eval[1] == \">=\":\n if eval[0] >= eval[2]:\n l[idx] = True\n else: \n l[idx] = False\n if eval[1] == \"<=\":\n if eval[0] <= eval[2]:\n l[idx] = True\n else: \n l[idx] = False\n if eval[1] == \"!=\":\n if eval[0] != eval[2]:\n l[idx] = True\n else: \n l[idx] = False\n \n def combine(l):\n for idx in range(len(l)):\n i=l[idx]\n if type(i) == list:\n if len(i) == 1 and type(i[0]) == bool:\n l[idx] = i[0]\n if len(i) > 1 and i[0] == 'not' and type(i[1]) == bool:\n l[idx] = not i[1]\n if len(i) > 1 and i[0] == 'and' and all(type(x) == bool for x in i[1]):\n if all(x for x in i[1]):\n l[idx] = True\n else:\n l[idx] = False\n elif len(i) > 1 and i[0] == 'or' and all(type(x) == bool for x in i[1]):\n if any(x for x in i[1]):\n l[idx] = True\n else:\n l[idx] = False\n else:\n combine(i)\n\n evaluate(cond,row)\n while not all(type(x) == bool for x in cond[1]):\n combine(cond)\n\n if any(x for x in cond[1]):\n final.append(row)\n \n result = PrettyTable(list(map(lambda x: x.upper(),columns)))\n col_index = list(map(lambda x: all_cols.index(x),columns))\n for r in final:\n rr = list(map(lambda x: r[x], col_index))\n result.add_row(rr)\n print(result)\n\n else:\n #without where cluase\n result = PrettyTable(list(map(lambda x: x.upper(),columns)))\n col_index = list(map(lambda x: all_cols.index(x),columns))\n for r in final_row:\n rr = list(map(lambda x: r[x], col_index))\n result.add_row(rr)\n print(result)\n\n def null_operation(self, items):\n if len(items) == 3:\n return False\n else:\n return True\n\n def null_predicate(self, items):\n if items[-1]:\n if len(items) > 2:\n return (f\"{items[0]}.{items[1]}\",\"is\",None)\n else:\n return(items[0],\"is\",None)\n else:\n if len(items) > 2:\n return (f\"{items[0]}.{items[1]}\",\"is\",None)\n else:\n return(items[0],\"is not\",None)\n\n def where_clause(self, items):\n #remove WHERE cluase\n return items[1]\n \n def boolean_expr(self, items):\n return ['or',items[0::2]]\n\n def boolean_term(self, items):\n return ['and',items[0::2]]\n\n def comparison_predicate(self, items):\n return tuple(items)\n\n def comp_operand(self, items):\n try:\n type = items[0].type\n if type == 'INT':\n return ('int',int(items[0]))\n elif type == 'DATE':\n return ('date',datetime.datetime.strptime(items[0],'%Y-%m-%d'))\n elif type == 'STR':\n return ('str',items[0][1:-1])\n except:\n if len(items) > 1:\n return ('col',f\"{items[0]}.{items[1]}\")\n else:\n return ('col',items[0])\n \n def COMP_OP(self, items):\n return items\n \n def predicate(self, items):\n return items[0]\n\n def boolean_test(self,items):\n return items[0]\n \n def parenthesized_boolean_expr(self, items):\n return [items[1]]\n\n def boolean_factor(self, items):\n if len(items) > 1:\n return ['not', items[-1]]\n else:\n return items[-1]\n\n def select_list(self, items):\n col_sel = []\n col_nick = {}\n for i in items:\n if i[0]:\n col_nick[i[-1]] = i[1]\n col_sel.append(i[1])\n return (col_sel, col_nick)\n\n def selected_column(self, items):\n case = len(items)\n if case == 1:\n #only column_name given\n return (False, items[0])\n elif case == 2:\n #table name and column name given\n return (False, f\"{items[0]}.{items[1]}\")\n elif case == 3:\n #column name and nickname given\n return (True, items[0], items[-1])\n elif case == 4:\n #table name and column name nickname given\n return (True, f\"{items[0]}.{items[1]}\", items[-1])\n\n def table_expression(self, items):\n return (len(items) > 1 , items)\n\n def from_clause(self, items):\n return items[-1]\n\n def table_reference_list(self, items):\n tables = []\n nickname = {}\n for i in items:\n if i[0]:\n nickname[i[-1]] = i[1]\n tables.append(i[1])\n return(tables, nickname)\n\n def referred_table(self, items):\n if len(items) > 1:\n return(True,items[0],items[-1])\n else:\n return(False, items[0])\n\n def insert_query(self, items):\n table_name = items[2]\n file_name = f\"db/{table_name}.db\"\n if not os.path.isfile(file_name):\n raise NoSuchTable()\n else:\n myDB = db.DB()\n myDB.open(file_name, dbtype=db.DB_HASH)\n #check if number of column matches\n original_cols = json.loads(myDB.get(b'columns'))\n column_name_list = original_cols\n insert_info = items[-1]\n if len(insert_info) > 1:\n column_name_list = insert_info[0]\n if len(column_name_list) != len(original_cols):\n raise InsertTypeMismatchError()\n for col in column_name_list:\n if col not in original_cols:\n raise InsertColumnExistenceError(col)\n value_list = insert_info[-1]\n\n if len(column_name_list) != len(value_list):\n raise InsertTypeMismatchError()\n\n data_dict = {'referencing': [], 'referenced': []}\n\n for i in range(len(value_list)):\n col_name = column_name_list[i]\n val = value_list[i]\n col_info = json.loads(myDB.get(col_name.encode('utf-8')))\n #check if nullable\n nullable = True\n if col_info['null'] == 'N':\n nullable = False\n #if value is null, check if nullable and store value into dict\n if val is None:\n if nullable:\n data_dict[col_name] = None\n else:\n raise InsertColumnNonNullableError(col_name)\n #if value is not null, check if type is right\n else:\n required_type = col_info['type']\n if required_type == 'int':\n if isinstance(val, int):\n data_dict[col_name] = val\n else:\n raise InsertTypeMismatchError()\n elif required_type == 'date':\n if isinstance(val, datetime.date):\n data_dict[col_name] = val.strftime('%Y-%m-%d')\n else:\n raise InsertTypeMismatchError()\n else:\n #if required type is string\n if isinstance(val, str):\n str_len = int(required_type[5:-1])\n #only store to max size of string\n data_dict[col_name] = val[0:str_len]\n else:\n raise InsertTypeMismatchError()\n\n #find if foreign key values exist in the referenced table\n foreign_key = json.loads(myDB.get(b'foreign_key'))\n for fk_info in foreign_key:\n fk_list = fk_info[0]\n referenced = fk_info[1]\n ori_cols = fk_info[2]\n\n rf_file_name = f\"db/{referenced}.db\"\n rfDB = db.DB()\n rfDB.open(rf_file_name, dbtype=db.DB_HASH)\n\n pk_idx = []\n for fk_idx in range(len(fk_list)):\n pk_idx.append(data_dict[fk_list[fk_idx]])\n\n #if all the foreign keys are null, not have to find, else, find the data from referenced table\n if not all(pk is None for pk in pk_idx):\n rf_pidx = json.dumps(pk_idx).encode('utf-8')\n referenced_data = rfDB.get(rf_pidx)\n if referenced_data is None:\n raise InsertReferentialIntegrityError()\n else:\n ori_referencing = data_dict['referencing']\n ori_referencing.append((referenced, json.loads(rf_pidx)))\n data_dict['referencing'] = ori_referencing\n\n rfDB.close()\n\n\n #make key to store in berkely db\n primary_idx = []\n primary_key = json.loads(myDB.get(b'primary_key'))\n\n for pk in primary_key:\n primary_idx.append(data_dict[pk])\n pidx = json.dumps(primary_idx).encode('utf-8')\n\n #find if data with the same primary key values exists\n cursor = myDB.cursor()\n data = cursor.first()\n while data:\n key, value = data\n if key == pidx:\n raise InsertDuplicatePrimaryKeyError()\n data = cursor.next()\n\n #insert new data to database\n myDB.put(pidx, json.dumps(data_dict).encode('utf-8'))\n for info in data_dict['referencing']:\n rf_table = info[0]\n rf_pidx = json.dumps(info[1]).encode('utf-8')\n rfDB = db.DB()\n rfDB.open(f\"db/{rf_table}.db\", dbtype=db.DB_HASH)\n rf_dict = json.loads(rfDB.get(rf_pidx))\n rf_referenced = rf_dict['referenced']\n rf_referenced.append((table_name,primary_idx))\n rf_dict['referenced'] = rf_referenced\n rfDB.put(rf_pidx, json.dumps(rf_dict).encode('utf-8'))\n rfDB.close()\n\n myDB.close()\n print(prompt,\"The row is inserted\",sep='')\n\n\n\n def insert_columns_and_sources(self, items):\n return items\n\n def value_list(self, items):\n return items[2:-1]\n\n def value(self, items):\n type = items[0].type\n if type == 'INT':\n return int(items[0])\n elif type == 'DATE':\n return datetime.datetime.strptime(items[0],'%Y-%m-%d')\n elif type == 'STR':\n return items[0][1:-1]\n elif type == 'NULL':\n return None\n\n def comparable_value(self, items):\n return items[0]\n\n def delete_query(self, items):\n table_name = items[2]\n file_name = f\"db/{table_name}.db\"\n # check if the file already exists\n if not os.path.isfile(file_name):\n raise NoSuchTable()\n else:\n myDB = db.DB()\n myDB.open(file_name, dbtype=db.DB_HASH)\n #info_list contains each key which is not a key for instance\n columns = json.loads(myDB.get(b'columns'))\n info_list = list(map(lambda col : bytes(col, encoding=\"utf-8\"), columns))\n info_list += [b'primary_key',b'foreign_key',b'referencing',b'referenced',b'columns']\n #to count\n yes_count = 0\n no_count = 0\n #referenced information\n referenced = json.loads(myDB.get(b'referenced'))\n ref_info = {}\n ref_colnames = {}\n for table in referenced:\n rfDB = db.DB()\n rfDB.open(f\"db/{table}.db\", dbtype=db.DB_HASH)\n rf_fk_info = json.loads(rfDB.get(b'foreign_key'))\n for fk_info in rf_fk_info:\n if fk_info[1] == table_name:\n fk_list = fk_info[0]\n can_delete = True\n for col in fk_list:\n if json.loads(rfDB.get(col.encode(\"utf-8\")))['null'] == 'N':\n can_delete = False\n break\n #store info boolean representing if all referenced cols are nullable\n ref_info[table] = can_delete\n ref_colnames[table] = fk_list\n break\n rfDB.close()\n #no where clause, delete all\n if (len(items) == 3):\n cursor = myDB.cursor()\n data = cursor.first()\n while data:\n key, value = data\n if key not in info_list:\n #find if this data can be deleted\n referenced = json.loads(value)['referenced']\n can_delete = True\n for rf in referenced:\n rf_table = rf[0]\n if ref_info[rf_table] == False:\n can_delete = False\n if can_delete:\n #delete this data from referenced\n for rf in referenced:\n rf_table = rf[0]\n rf_key = json.dumps(rf[1]).encode('utf-8')\n rfDB = db.DB()\n rfDB.open(f\"db/{rf_table}.db\", dbtype=db.DB_HASH)\n rf_dict = json.loads(rfDB.get(rf_key))\n #remove this value from 'referencing' of referenced value\n rf_referencing = rf_dict['referencing']\n def checkThis(x):\n return not (json.dumps(x[1]).encode('utf-8') == key and x[0] == table_name)\n rf_referencing = list(filter(checkThis, rf_referencing))\n rf_dict['referencing'] = rf_referencing\n #change all referenced col values to null\n ref_col = ref_colnames[rf_table]\n for col in ref_col:\n rf_dict[col] = None\n #store edited value\n rfDB.put(rf_key, json.dumps(rf_dict).encode('utf-8'))\n rfDB.close()\n\n #delete this data from referencing\n referencing = json.loads(value)['referencing']\n for rfc in referencing:\n rfc_table = rfc[0]\n rfc_key = json.dumps(rfc[1]).encode('utf-8')\n rfcDB = db.DB()\n rfcDB.open(f\"db/{rfc_table}.db\", dbtype=db.DB_HASH)\n rfc_dict = json.loads(rfcDB.get(rfc_key))\n #remove this value from 'referenced' of referencing value\n rfc_referenced = rfc_dict['referenced']\n def checkThis(x):\n return not (json.dumps(x[1]).encode('utf-8') == key and x[0] == table_name)\n rfc_referenced = list(filter(checkThis, rfc_referenced))\n rfc_dict['referenced'] = rfc_referenced\n #store edited value\n rfcDB.put(rfc_key, json.dumps(rfc_dict).encode('utf-8'))\n rfcDB.close()\n #delete this value from database\n myDB.delete(key)\n yes_count += 1\n else:\n #cannot delete this value due to referential integrity\n no_count += 1\n data = cursor.next()\n #with where clause\n else:\n condition = items[3]\n predicates = []\n p_col = []\n def flatten(l):\n for i in l:\n if type(i) == list or (type(i) == tuple and len(i) == 2):\n flatten(i)\n else:\n if type(i) == tuple and len(i) == 3:\n predicates.append(i)\n flatten(condition)\n #check if comparable\n for idx in range(len(predicates)):\n p = predicates[idx]\n oper = p[1]\n if oper in ['is','is not']:\n #null predicate\n #find if the col name is valid\n col_name = p[0]\n if len(col_name.split('.')) > 1:\n t_n , c_n = col_name.split('.')\n #check if specified table\n if t_n != table_name:\n raise WhereTableNotSpecified()\n #check if the col exist\n c_list = json.loads(myDB.get(b'columns'))\n if c_n not in c_list:\n raise WhereColumnNotExist()\n else:\n p_col.append(c_n)\n myDB.close()\n else:\n c_list = json.loads(myDB.get(b'columns'))\n if col_name in c_list:\n p_col.append(col_name)\n else:\n raise WhereColumnNotExist()\n else:\n #comparison predicate\n two_type = []\n for op_idx in (0,2):\n if p[op_idx][0] in ['str','int','date']:\n two_type.append(p[op_idx][0])\n else:\n #if col name, check if valid col name\n col_name = p[op_idx][1]\n if len(col_name.split('.')) > 1:\n t_n , c_n = col_name.split('.')\n #check if specified table\n if t_n != table_name:\n raise WhereTableNotSpecified()\n else:\n c_list = json.loads(myDB.get(b'columns'))\n if c_n in c_list:\n #find it\n p_col.append(c_n)\n type_s = json.loads(myDB.get(c_n.encode('utf-8')))['type']\n if type_s in ['int','date']:\n two_type.append(type_s)\n else:\n two_type.append('str')\n else:\n raise WhereColumnNotExist()\n else:\n find_type = ''\n c_list = json.loads(myDB.get(b'columns'))\n if col_name in c_list:\n p_col.append(col_name)\n type_s = json.loads(myDB.get(col_name.encode('utf-8')))['type']\n if type_s in ['int','date']:\n find_type = type_s\n else:\n find_type = 'str'\n two_type.append(find_type)\n else:\n raise WhereColumnNotExist()\n if len(two_type) == 2:\n if two_type[0] != two_type[1]:\n raise WhereIncomparableError()\n\n #iterate through all data in this table\n cursor = myDB.cursor()\n data = cursor.first()\n while data:\n key, value = data\n if key not in info_list:\n #check if this satify where clause\n cond = copy.deepcopy(condition)\n\n def evaluate(l,value_dict):\n for idx in range(len(l)):\n i=l[idx]\n if type(i) == list or (type(i) == tuple and len(i) == 2):\n evaluate(i,value_dict)\n else:\n if type(i) == tuple and len(i) == 3:\n oper = i[1]\n if oper in ['is','is not']:\n #null predicate\n col_name = i[0].split('.')[-1]\n if oper == 'is':\n if value_dict[col_name] is None:\n l[idx] = True\n else:\n l[idx] = False\n elif oper == 'is not':\n if value_dict[col_name] is not None:\n l[idx] = True\n else:\n l[idx] = False\n else:\n #comparison predicate\n two_type = []\n eval = [i[0],i[1],i[2]]\n #if val op col\n if i[0][0] in ['str','int','date'] and i[2][0] == 'col':\n eval[0] = i[0][1]\n col_name = i[2][1].split('.')[-1]\n eval[2] = value_dict[col_name]\n #elif col op val\n elif i[2][0] in ['str','int','date'] and i[0][0] == 'col':\n eval[2] = i[2][1]\n col_name = i[0][1].split('.')[-1]\n eval[0] = value_dict[col_name]\n #elif col op col\n elif i[2][0] == 'col' and i[0][0] == 'col':\n col_name = i[0][1].split('.')[-1]\n eval[0] = value_dict[col_name]\n col_name = i[2][1].split('.')[-1]\n eval[2] = value_dict[col_name]\n #elif val op val\n else:\n eval[0] = i[0][1]\n eval[2] = i[2][1]\n #evaluate\n if eval[1] == \"<\":\n if eval[0] < eval[2]:\n l[idx] = True\n else: \n l[idx] = False\n if eval[1] == \">\":\n if eval[0] > eval[2]:\n l[idx] = True\n else: \n l[idx] = False\n if eval[1] == \"=\":\n if eval[0] == eval[2]:\n l[idx] = True\n else: \n l[idx] = False\n if eval[1] == \">=\":\n if eval[0] >= eval[2]:\n l[idx] = True\n else: \n l[idx] = False\n if eval[1] == \"<=\":\n if eval[0] <= eval[2]:\n l[idx] = True\n else: \n l[idx] = False\n if eval[1] == \"!=\":\n if eval[0] != eval[2]:\n l[idx] = True\n else: \n l[idx] = False\n def combine(l):\n for idx in range(len(l)):\n i=l[idx]\n if type(i) == list:\n if len(i) == 1 and type(i[0]) == bool:\n l[idx] = i[0]\n if len(i) > 1 and i[0] == 'not' and type(i[1]) == bool:\n l[idx] = not i[1]\n if len(i) > 1 and i[0] == 'and' and all(type(x) == bool for x in i[1]):\n if all(x for x in i[1]):\n l[idx] = True\n else:\n l[idx] = False\n elif len(i) > 1 and i[0] == 'or' and all(type(x) == bool for x in i[1]):\n if any(x for x in i[1]):\n l[idx] = True\n else:\n l[idx] = False\n else:\n combine(i)\n\n evaluate(cond, json.loads(value))\n while not all(type(x) == bool for x in cond[1]):\n combine(cond)\n\n if any(x for x in cond[1]):\n #satisfy where clause!!\n #find if this data can be deleted\n referenced = json.loads(value)['referenced']\n can_delete = True\n for rf in referenced:\n rf_table = rf[0]\n if ref_info[rf_table] == False:\n can_delete = False\n if can_delete:\n #delete this data from referenced\n for rf in referenced:\n rf_table = rf[0]\n rf_key = json.dumps(rf[1]).encode('utf-8')\n rfDB = db.DB()\n rfDB.open(f\"db/{rf_table}.db\", dbtype=db.DB_HASH)\n rf_dict = json.loads(rfDB.get(rf_key))\n #remove this value from 'referencing' of referenced value\n rf_referencing = rf_dict['referencing']\n def checkThis(x):\n return not (json.dumps(x[1]).encode('utf-8') == key and x[0] == table_name)\n rf_referencing = list(filter(checkThis, rf_referencing))\n rf_dict['referencing'] = rf_referencing\n #change all referenced col values to null\n ref_col = ref_colnames[rf_table]\n for col in ref_col:\n rf_dict[col] = None\n #store edited value\n rfDB.put(rf_key, json.dumps(rf_dict).encode('utf-8'))\n rfDB.close()\n\n #delete this data from referencing\n referencing = json.loads(value)['referencing']\n for rfc in referencing:\n rfc_table = rfc[0]\n rfc_key = json.dumps(rfc[1]).encode('utf-8')\n rfcDB = db.DB()\n rfcDB.open(f\"db/{rfc_table}.db\", dbtype=db.DB_HASH)\n rfc_dict = json.loads(rfcDB.get(rfc_key))\n #remove this value from 'referenced' of referencing value\n rfc_referenced = rfc_dict['referenced']\n def checkThis(x):\n return not (json.dumps(x[1]).encode('utf-8') == key and x[0] == table_name)\n rfc_referenced = list(filter(checkThis, rfc_referenced))\n rfc_dict['referenced'] = rfc_referenced\n #store edited value\n rfcDB.put(rfc_key, json.dumps(rfc_dict).encode('utf-8'))\n rfcDB.close()\n #delete this value from database\n myDB.delete(key)\n yes_count += 1\n else:\n #cannot delete this value due to referential integrity\n no_count += 1\n data = cursor.next()\n\n myDB.close()\n print(prompt,f\"{yes_count} row(s) are deleted\", sep='')\n if no_count > 0:\n print(prompt, f\"{no_count} row(s) are not deleted due to referential integrity\", sep='')\n\n\n def table_element_list(self, items):\n elem_list = items[1:-1] # get rid of LP and RP\n return elem_list\n\n def table_element(self, items):\n return items[0]\n\n def column_definition(self, items):\n dict = {}\n dict['type'] = items[1]\n #if not null constraint, set null to N\n if len(items) > 2:\n dict['null'] = 'N'\n else:\n dict['null'] = 'Y'\n dict['key'] = ''\n return (items[0], dict)\n\n def data_type(self, items):\n length = len(items)\n if (length == 4):\n #if char length smaller than 1, rais CharLenghError\n if int(items[2]) <= 0:\n raise CharLengthError()\n result = ''\n for i in range(length):\n result += str(items[i])\n return result.lower()\n\n def table_constraint_definition(self, items):\n return items[0]\n\n def primary_key_constraint(self, items):\n return ['primary key', items[2]]\n\n def referential_constraint(self, items):\n col_list = items[2]\n referenced_table = items[4]\n referenced_col_list = items[5]\n return ['foreign key', col_list, referenced_table, referenced_col_list ]\n\n def column_name_list(self, items):\n return list(items[1:-1])\n #table name to lower case\n def table_name(self, t):\n (t,) = t\n return t.lower()\n #column name to lower case\n def column_name(self, c):\n (c,) = c\n return c.lower()\n def IDENTIFIER(self, s):\n return str(s)\n\n\nif __name__ == '__main__':\n\n # make sql_parser with grammar.lark file\n with open('../PRJ1-3_2015-16227/grammar.lark') as file:\n sql_parser = Lark(file.read(), start=\"command\", lexer=\"standard\")\n\n #get input until the program ended\n while(True):\n #get input with prompt message\n data_input = input(prompt)\n #if command 'exit' is given, end the program\n if(data_input == 'exit'):\n sys.exit()\n #get additional input until it ends with semicolon\n while len(data_input) == 0 or data_input[-1] != ';':\n #to prevent error, add white space to data_input\n data_input += ' '\n data_input += input()\n #split the input by semicolon\n input_list = list(data_input.split(';'))\n #exclude the last element of input_list since it is empty string\n for i in range(len(input_list) - 1):\n #restore semicolon in the end of the command\n command = input_list[i] + ';'\n #using try ... except, process the syntax error\n try:\n result = sql_parser.parse(command)\n MyTransformer().transform(result)\n except lark.exceptions.UnexpectedInput:\n print(prompt,\"Syntax error\",sep='')\n #for char length error\n except lark.exceptions.VisitError as e:\n print(prompt + str(e.__context__))\n except SimpleDatabaseError as e:\n print(prompt + str(e))\n\n" }, { "alpha_fraction": 0.6711568832397461, "alphanum_fraction": 0.6714210510253906, "avg_line_length": 26.042856216430664, "blob_id": "cc4f69486da95d139e1d7c7b19f43318de8a949a", "content_id": "5723b721a9b542175c3880ab40388b15142f7cd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3786, "license_type": "no_license", "max_line_length": 77, "num_lines": 140, "path": "/PRJ1-3_2015-16227/exceptions.py", "repo_name": "h-yes-oo/database", "src_encoding": "UTF-8", "text": "class SimpleDatabaseError(Exception):\n pass\n\n\nclass NoSuchTable(SimpleDatabaseError):\n def __str__(self):\n return \"No such table\"\n\n\nclass CharLengthError(SimpleDatabaseError):\n def __str__(self):\n return \"Char length should be over 0\"\n\n\nclass CreateTableError(SimpleDatabaseError):\n def __init__(self, msg):\n self.msg = msg\n\n def __str__(self):\n return f\"Create table has failed: {self.msg}\"\n\n\nclass DropTableError(SimpleDatabaseError):\n def __init__(self, msg):\n self.msg = msg\n\n def __str__(self):\n return f\"Drop table has failed: {self.msg}\"\n\n\nclass DropReferencedTableError(DropTableError):\n def __init__(self, table):\n super().__init__(f\"'{table}' is referenced by other table\")\n\n\nclass DuplicateColumnDefError(CreateTableError):\n def __init__(self):\n super().__init__(\"column definition is duplicated\")\n\n\nclass DuplicatePrimaryKeyDefError(CreateTableError):\n def __init__(self):\n super().__init__(\"primary key definition is duplicated\")\n\n\nclass ReferenceTypeError(CreateTableError):\n def __init__(self):\n super().__init__(\"foreign key references wrong type\")\n\n\nclass ReferenceNonPrimaryKeyError(CreateTableError):\n def __init__(self):\n super().__init__(\"foreign key references non primary key column\")\n\n\nclass ReferenceColumnExistenceError(CreateTableError):\n def __init__(self):\n super().__init__(\"foreign key references non existing column\")\n\n\nclass ReferenceTableExistenceError(CreateTableError):\n def __init__(self):\n super().__init__(\"foreign key references non existing table\")\n\n\nclass NonExistingColumnDefError(CreateTableError):\n def __init__(self, column):\n super().__init__(f\"'{column}' does not exists in column definition\")\n\n\nclass TableExistenceError(CreateTableError):\n def __init__(self):\n super().__init__(\"table with the same name already exists\")\n\n\nclass InsertionError(SimpleDatabaseError):\n def __init__(self, msg):\n self.msg = msg\n\n def __str__(self):\n return f\"Insertion has failed: {self.msg}\"\n\n\nclass InsertTypeMismatchError(InsertionError):\n def __init__(self):\n super().__init__(\"Types are not matched\")\n\n\nclass InsertColumnExistenceError(InsertionError):\n def __init__(self, column):\n super().__init__(f\"'{column}' does not exist\")\n\n\nclass InsertColumnNonNullableError(InsertionError):\n def __init__(self, column):\n super().__init__(f\"'{column}' is not nullable\")\n\n\nclass InsertDuplicatePrimaryKeyError(InsertionError):\n def __init__(self):\n super().__init__(\"Primary key duplication\")\n\n\nclass InsertReferentialIntegrityError(InsertionError):\n def __init__(self):\n super().__init__(\"Referential integrity violation\")\n\n\nclass SelectionError(SimpleDatabaseError):\n def __init__(self, msg):\n self.msg = msg\n\n def __str__(self):\n return f\"Selection has failed: {self.msg}\"\n\n\nclass SelectTableExistenceError(SelectionError):\n def __init__(self, table):\n super().__init__(f\"'{table}' does not exist\")\n\nclass SelectColumnResolveError(SelectionError):\n def __init__(self, column):\n super().__init__(f\"fail to resolve '{column}'\")\n\n\nclass WhereIncomparableError(SimpleDatabaseError):\n def __str__(self):\n return \"Where clause try to compare incomparable values\"\n\nclass WhereTableNotSpecified(SimpleDatabaseError):\n def __str__(self):\n return \"Where clause try to reference tables which are not specified\"\n\nclass WhereColumnNotExist(SimpleDatabaseError):\n def __str__(self):\n return \"Where clause try to reference non existing column\"\n\nclass WhereAmbiguousReference(SimpleDatabaseError):\n def __str__(self):\n return \"Where clause contains ambiguous reference\"\n" }, { "alpha_fraction": 0.5558925867080688, "alphanum_fraction": 0.5694865584373474, "avg_line_length": 32.58490753173828, "blob_id": "96b7491d39e52fb82c997690309808a57055e02f", "content_id": "acf1ba7de8735f06e81558a35961437a19109c77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8901, "license_type": "no_license", "max_line_length": 95, "num_lines": 265, "path": "/PRJ2_2015-16227/run.py", "repo_name": "h-yes-oo/database", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nfrom mysql.connector import connect\nfrom executions import *\nfrom table import TABLES\nfrom messages import *\n\n#connect with db in case it doesn't work at first time, use try except to ensure the connection\ntry:\n connection = connect(\n host='astronaut.snu.ac.kr',\n port=7000,\n user='DB2015_16227',\n password='DB2015_16227',\n db='DB2015_16227',\n charset='utf8'\n )\nexcept:\n connection = connect(\n host='astronaut.snu.ac.kr',\n port=7000,\n user='DB2015_16227',\n password='DB2015_16227',\n db='DB2015_16227',\n charset='utf8'\n )\n\n#make one dictionary cursor, one non-dictionary cursor for convenience\ncurA = connection.cursor(dictionary=True, buffered=True)\ncurB = connection.cursor(dictionary=False, buffered=True)\n\n#print informative message and start program\nprint(info_message)\nwhile(True):\n print(\" \")\n #if input action is not an integer, go to except\n try:\n action = int(input(select_action))\n #if action not in 1~16 print invalid action message\n if action >= 17 or action <= 0:\n print(invalid_action)\n else:\n if action == 1:\n print_building(curA, curB)\n elif action == 2:\n print_performance_all(curA, curB)\n elif action == 3:\n print_audience_all(curA)\n elif action == 4:\n #get name, location and truncate to 200 letters\n name = input(get_building_name)\n if(len(name) > 200):\n name = name[0:200]\n location = input(get_building_location)\n if(len(location) > 200):\n location = location[0:200]\n try:\n #if capacity less than zero, print error message \n capacity = int(input(get_building_capacity))\n if capacity <= 0:\n print(capacity_constraint)\n continue\n else:\n #if every input alright, insert it and commit\n insert_building(curA, name, location, capacity)\n connection.commit()\n print(insert_success_message(\"A building\"))\n except:\n #if user input non-integer capacity, print invalid input\n print(invalid_input)\n continue\n\n elif action == 5:\n try:\n bid = int(input(get_building_id))\n if(check_by_id(curA, 'building', bid)):\n #if building with input id exist, delete and commit\n delete(curA, 'building', bid)\n connection.commit()\n print(delete_success_message(\"A building\"))\n else:\n #if not exists, print message\n print(building_not_exist(bid))\n except:\n #if user input non-integer id, print invalid input\n print(invalid_input)\n\n elif action == 6:\n # get name and type from user and truncate to 200 letters\n name = input(get_performance_name)\n if(len(name) > 200):\n name = name[0:200]\n ptype = input(get_performance_type)\n if(len(ptype) > 200):\n ptype = ptype[0:200]\n try:\n price = int(input(get_performance_price))\n if price < 0:\n print(price_constraint)\n continue\n else:\n #if all input alright, insert it and commit\n insert_performance(curA, name, ptype, price)\n connection.commit()\n print(insert_success_message(\"A performance\"))\n except:\n #if user input non-interger value for price, print invalid input\n print(invalid_input)\n continue\n\n elif action == 7:\n try:\n pid = int(input(get_performance_id))\n #check if performance with the id exists\n if(check_by_id(curA, 'performance', pid)):\n #if exist, delete and commit\n delete(curA, 'performance', pid)\n connection.commit()\n print(delete_success_message(\"A performance\"))\n else:\n #if not exist, print not exist message\n print(performance_not_exist(pid))\n except:\n #if user input non-integer value for id, print invalid input\n print(invalid_input)\n \n elif action == 8:\n #get name and truncate\n name = input(get_audience_name)\n if(len(name) > 200):\n name = name[0:200]\n #get gender and check if equals to M or F\n gender = input(get_audience_gender)\n if gender != \"M\" and gender != \"F\":\n print(gender_constraint)\n continue\n try:\n #get age and check if bigger than 0\n age = int(input(get_audience_age))\n if age < 0:\n print(age_constraint)\n continue\n else:\n #if alright, insert and commit\n insert_audience(curA, name, gender, age)\n connection.commit()\n print(insert_success_message(\"An audience\"))\n except:\n #if user input non-integer value for age, print message\n print(invalid_input)\n continue\n \n elif action == 9:\n try:\n aid = int(input(get_audience_id))\n if(check_by_id(curA, 'audience', aid)):\n #if audience with the id exist, delete and commit\n delete(curA, 'audience', aid)\n connection.commit()\n print(delete_success_message(\"An audience\"))\n else:\n #else, print not exist message\n print(audience_not_exist)\n except:\n #if user input non-integer value for id, print message\n print(invalid_input)\n \n elif action == 10:\n try:\n bid = int(input(get_building_id))\n #if building not exist, print message\n if not check_by_id(curA, 'building', bid):\n print(building_not_exist(bid))\n continue\n pid = int(input(get_performance_id))\n #if performance not exist, print message\n if not check_by_id(curA, 'performance', pid):\n print(performance_not_exist(pid))\n continue\n #if it is able to assign the performance to building, do it and commit\n if(assign_p_to_b(curA, pid, bid)):\n print(assign_success)\n connection.commit()\n except:\n print(invalid_input)\n \n elif action == 11:\n try:\n pid = int(input(get_performance_id))\n # if performance not assigned to any building, print message\n if not check_building_assigned(curA, pid):\n print(performance_not_assigned(pid))\n continue\n aid = int(input(get_audience_id))\n seat_list = list(map(int, input(get_seat_number).split(',')))\n #check if all seats can be reserved\n if(can_reserve(curB, seat_list, pid)):\n for seat in seat_list:\n #reserve each seat and commit\n reserve(curA, pid, aid, seat)\n connection.commit()\n #get price with respect to audience's age\n price = get_ticket_price(curB, pid, aid)\n #multiply the price with the number of ticket being reserved\n total_price = round(price * len(seat_list))\n #print success message and price\n print(book_success)\n print(total_ticket_price(total_price))\n except:\n print(invalid_input)\n\n elif action == 12:\n try:\n bid = int(input(get_building_id))\n #check if building with the id exist and print\n if check_by_id(curA, 'building', bid):\n print_performance_of_building(curA, curB, bid)\n else:\n print(building_not_exist(bid))\n except:\n print(invalid_input)\n\n elif action == 13:\n try:\n pid = int(input(get_performance_id))\n #check if performance with the id exist and print\n if check_by_id(curA, 'performance', pid):\n print_audience_of_performance(curA, pid)\n else:\n print(performance_not_exist(pid))\n except:\n print(invalid_input)\n \n elif action == 14:\n try:\n pid = int(input(get_performance_id))\n #check if performance with the id exist\n if check_by_id(curA, 'performance', pid):\n #check if performance with the id is assigned to any building\n if check_building_assigned(curA, pid):\n print_seat_of_performance(curB, pid)\n else:\n print(performance_not_assigned(pid))\n else:\n print(performance_not_exist(pid))\n except:\n print(invalid_input)\n\n elif action == 15:\n print(bye)\n break\n\n elif action == 16:\n #ensure user about deleting everything\n flag = input(refresh_confirm)\n if flag == 'y':\n refresh(curA, TABLES)\n\n #if non integer input came, print invalid message\n except:\n print(invalid_action)\n\ncurA.close()\ncurB.close()\nconnection.close()\nexit(0)\n\n" }, { "alpha_fraction": 0.5987762212753296, "alphanum_fraction": 0.6451048851013184, "avg_line_length": 21.8799991607666, "blob_id": "dea92a8da6fdc5f2391d65c3cabd83dbae43d986", "content_id": "ad8697d8b0acfc4adabeab1750907978a2ed8c40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1144, "license_type": "no_license", "max_line_length": 94, "num_lines": 50, "path": "/sample.sql", "repo_name": "h-yes-oo/database", "src_encoding": "UTF-8", "text": "create table department (\n name char(5),\n pos char(17),\n number int,\n start date,\n primary key(name)\n);\n\n\ncreate table student (\n ID char(5),\n name char(2) not null,\n dept_name char(5),\n tot_cred int,\n primary key(ID, name),\n foreign key (dept_name) references department(name)\n);\n\ncreate table lover (\n x char(3),\n y char(2),\n dept_name char(5),\n stu_id char(5),\n primary key(x,y,dept_name),\n foreign key (dept_name) references department(name),\n foreign key (y,stu_id) references student(name,id)\n);\n\ncreate table loves (\n she char(2),\n he char(3) not null,\n who char(5),\n love date,\n primary key (love),\n foreign key (who,he,she) references lover(dept_name,x,y)\n);\n\ninsert into department (number,start,pos,name) values(1,2020-10-10,\"pos777777\",'name5555555');\n\n\ninsert into student values('id1','n2','name5',10);\n\ninsert into lover values('xxx','n2','name5','id1');\n\ninsert into loves values('n2','xxx','name5',2015-03-30);\n\n--set null value to primary key\n--set null value to not null primary key\n--len(column) != len(input_column)\n--len(input_column) != len(values)\n" }, { "alpha_fraction": 0.686948835849762, "alphanum_fraction": 0.6984127163887024, "avg_line_length": 29.635135650634766, "blob_id": "dd8eabd0971c7c06a64c1b60fc2ba1f4f0b0e0f0", "content_id": "e9ccece48bd90e9c1a7bb1f7e1a0a210ccdd0b6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2274, "license_type": "no_license", "max_line_length": 74, "num_lines": 74, "path": "/PRJ2_2015-16227/messages.py", "repo_name": "h-yes-oo/database", "src_encoding": "UTF-8", "text": "#informative message about prompt\ninfo_message = '''\n============================================================ \n1. print all buildings\n2. print all performances\n3. print all audiences\n4. insert a new building\n5. remove a building\n6. insert a new performance\n7. remove a performance\n8. insert a new audience\n9. remove an audience\n10. assign a performance to a building\n11. book a performance\n12. print all performances which assigned at a building\n13. print all audiences who booked for a performance\n14. print ticket booking status of a performance\n15. exit\n16. reset database\n============================================================'''\n\ninvalid_action = \"Invalid action\"\ninvalid_input = \"Invalid input\"\n\nselect_action = \"Select your action: \"\n\nget_building_name = \"Building name: \"\nget_building_location = \"Building location: \"\nget_building_capacity = \"Building capacity: \"\nget_building_id = \"Building ID: \"\n\nget_performance_name = \"Performance name: \"\nget_performance_type = \"Performance type: \"\nget_performance_price = \"Performance price: \"\nget_performance_id = \"Performance ID: \"\n\nget_audience_name = \"Audience name: \"\nget_audience_gender = \"Audience gender: \"\nget_audience_age = \"Audience age: \"\nget_audience_id = \"Audience ID: \"\n\nget_seat_number = \"Seat number: \"\n\ncapacity_constraint = \"Capacity should be more than 0\"\nprice_constraint = \"Price should be 0 or more\"\ngender_constraint = \"Gender should be 'M' or 'F'\"\nage_constraint = \"Age should be 0 or more\"\n\nbye = \"Bye!\"\nrefresh_confirm = \"Every table and data will be deleted. Go on ? (y/n) : \"\n\nassign_success = \"Successfully assign a performance\"\nbook_success = \"Successfully book a performance.\"\n\ndef total_ticket_price(total_price):\n return \"Total ticket price is {:,}\".format(total_price)\n\ndef insert_success_message(what):\n return \"{} is successfully inserted\".format(what)\n\ndef delete_success_message(what):\n return \"{} is successfully removed\".format(what)\n\ndef building_not_exist(bid):\n return \"Building {} doesn’t exist\".format(bid)\n\ndef performance_not_exist(pid):\n return \"Performance {} doesn’t exist\".format(pid)\n\ndef audience_not_exist(aid):\n return \"Audience {} doesn’t exist\".format(aid)\n\ndef performance_not_assigned(pid):\n return \"Performance {} isn't assigned\".format(pid)\n\n" } ]
10
JoseEvanan/PagaPeApi
https://github.com/JoseEvanan/PagaPeApi
774a211d26372686733af36d8177f606fa652e78
b265afa2dec3f4d8ce47b30b9932a22f7b7633ea
8c49b7e8a809c626fc65c96e6542bbb17b4dfdc0
refs/heads/master
2021-07-20T05:01:50.900995
2017-10-28T10:30:35
2017-10-28T10:30:35
108,635,254
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.515237033367157, "alphanum_fraction": 0.6179458498954773, "avg_line_length": 35.9375, "blob_id": "6ee5f0b0f1edbdaa722ed7a9c204a3a0dcc5ce15", "content_id": "7b542b4febae0b15bc06d8db8131ea99b050f72b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1772, "license_type": "no_license", "max_line_length": 633, "num_lines": 48, "path": "/app.py", "repo_name": "JoseEvanan/PagaPeApi", "src_encoding": "UTF-8", "text": "import json\nfrom flask import Flask, request\nfrom flask_restful import reqparse, abort, Api, Resource\nfrom utils import _send_email\nfrom pprint import pprint\napp = Flask(__name__)\napi = Api(app)\n\n\nparser = reqparse.RequestParser()\nparser.add_argument('task')\n\n\n# TodoList\n# shows a list of all todos, and lets you POST to add new tasks\nclass SendEmail(Resource):\n def get(self):\n return None, 202 \n\n def post(self):\n print(\"post\")\n d = request.form\n #d = {'{\"_id\":\"59f444e1e2bb163439f9cf3f\",\"updatedAt\":\"2017-10-28T08:50:41.418Z\",\"createdAt\":\"2017-10-28T08:50:41.418Z\",\"debted\":{\"_id\":\"59f431d93a25a3202f86aa04\",\"updatedAt\":\"2017-10-28T07:29:29.526Z\",\"createdAt\":\"2017-10-28T07:29:29.526Z\",\"email\":\"[email protected]\",\"password\":\"$2a$10$Z.rHnTVqm/QeWq1.oGngZe5uwax1Ngu5yQXtCDk.vUfuP0IJl5ZG.\",\"__v\":0,\"tokens\":[],\"active\":false},\"debtor\":{\"_id\":\"59f44375b675e9332c7f5bac\",\"updatedAt\":\"2017-10-28T08:44:37.760Z\",\"createdAt\":\"2017-10-28T08:44:37.760Z\",\"password\":\"$2a$10$/ci2p166jrAeEr6NyST8xO0RQM.Ou9n5VKYxUWezea79kR7P0xeH2\",\"__v\":0,\"tokens\":[],\"active\":true},\"description\":\"Deuda de un cuy\",\"endDate\":\"2017-11-24T00:00:00.000Z\",\"amount\":10000,\"__v\":0,\"accepted\":false,\"status\":0}': ''}\n print(d.keys())\n data = None\n for d in d.keys():\n data = d\n data = json.loads(data)\n pprint(data)\n email = data['debtor']['email']\n description = data['description']\n endDate = data['endDate']\n amount = data['amount']\n name = data['debtor']['profile']['name']\n confirmation = data['_id']\n status = _send_email(email, name, description,\n endDate, amount, confirmation)\n return status, 201\n\n\n##\n## Actually setup the Api resource routing here\n##\napi.add_resource(SendEmail, '/')\n\n\nif __name__ == '__main__':\n app.run(debug=True)" }, { "alpha_fraction": 0.5822784900665283, "alphanum_fraction": 0.6252064108848572, "avg_line_length": 32.0363655090332, "blob_id": "51cb887956f09472473a8e76d10903eeb59ba335", "content_id": "f2fb9756f37bb841b1c8d94e3376f5ea0389e600", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1817, "license_type": "no_license", "max_line_length": 160, "num_lines": 55, "path": "/utils.py", "repo_name": "JoseEvanan/PagaPeApi", "src_encoding": "UTF-8", "text": "import smtplib\n\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\ndef _send_email(email, name, description,\n endDate, amount, confirmation):\n # me == my email address\n # you == recipient's email address\n me = \"[email protected]\"\n you = email\n # Create message container - the correct MIME type is multipart/alternative.\n msg = MIMEMultipart('alternative')\n msg['Subject'] = \"PagaPe\"\n msg['From'] = me\n msg['To'] = you\n\n # Create the body of the message (a plain-text and an HTML version).\n text = \"Hi!\\nHow are you?\\nHere is the link you wanted:\\nhttp://www.python.org\"\n html = \"\"\"\\\n <html>\n <head></head>\n <body>\n <img src=\"https://scontent.faqp1-1.fna.fbcdn.net/v/t34.0-12/22901695_1930361390547116_415760123_n.png?oh=3bd1675bc7bb567e84baaad992e2e49b&oe=59F5D614\" >\n <p>Hola! {}<br>\n {}<br>\n Tienes una deuda de {}, tienes para cancelar hasta {} <a href=\"http://pagape.com/confirmar/{}\">link</a>.\n </p>\n </body>\n </html>\n \"\"\".format( name, description,amount, endDate, confirmation)\n # Record the MIME types of both parts - text/plain and text/html.\n part1 = MIMEText(text, 'plain')\n part2 = MIMEText(html, 'html')\n\n # Attach parts into message container.\n # According to RFC 2046, the last part of a multipart message, in this case\n # the HTML message, is best and preferred.\n msg.attach(part1)\n msg.attach(part2)\n # Send the message via local SMTP server.\n mail = smtplib.SMTP('smtp.gmail.com', 587)\n\n mail.ehlo()\n\n mail.starttls()\n\n mail.login('[email protected]', 'pagainfo2017')\n try:\n mail.sendmail(me, you, msg.as_string())\n mail.quit()\n return True\n except Exception as e:\n print(e)\n return False\n" } ]
2