code
stringlengths
4
1.01M
language
stringclasses
2 values
package me.breidenbach.asyncmailer /** * Copyright © Kevin E. Breidenbach, 5/26/15. */ case class MailerException(message: String, cause: Throwable = null) extends Error(message, cause)
Java
#!/bin/bash cp index.html /var/www/ cp -r js /var/www cp -r img /var/www/img
Java
datab = [{},{"Attribute":{"colspan":"1","rowspan":"1","text":"Modality"},"Tag":{"colspan":"1","rowspan":"1","text":"(0008,0060)"},"Value":{"colspan":"1","rowspan":"1","text":"CT"}},{"Attribute":{"colspan":"1","rowspan":"1","text":"Photometric Interpretation"},"Tag":{"colspan":"1","rowspan":"1","text":"(0028,0004)"},"Value":{"colspan":"1","rowspan":"1","text":"MONOCHROME2"}}];
Java
<!doctype html> <html> <title>commands</title> <meta http-equiv="content-type" value="text/html;utf-8"> <link rel="stylesheet" type="text/css" href="../static/style.css"> <body> <div id="wrapper"> <h1><a href="../api/commands.html">commands</a></h1> <p>npm commands</p> <h2 id="SYNOPSIS">SYNOPSIS</h2> <pre><code>npm.commands[&lt;command&gt;](args, callback)</code></pre> <h2 id="DESCRIPTION">DESCRIPTION</h2> <p>npm comes with a full set of commands, and each of the commands takes a similar set of arguments.</p> <p>In general, all commands on the command object take an <strong>array</strong> of positional argument <strong>strings</strong>. The last argument to any function is a callback. Some commands are special and take other optional arguments.</p> <p>All commands have their own man page. See <code>man npm-&lt;command&gt;</code> for command-line usage, or <code>man 3 npm-&lt;command&gt;</code> for programmatic usage.</p> <h2 id="SEE-ALSO">SEE ALSO</h2> <ul><li><a href="../doc/index.html">index(1)</a></li></ul> </div> <p id="footer">commands &mdash; npm@1.2.23</p> <script> ;(function () { var wrapper = document.getElementById("wrapper") var els = Array.prototype.slice.call(wrapper.getElementsByTagName("*"), 0) .filter(function (el) { return el.parentNode === wrapper && el.tagName.match(/H[1-6]/) && el.id }) var l = 2 , toc = document.createElement("ul") toc.innerHTML = els.map(function (el) { var i = el.tagName.charAt(1) , out = "" while (i > l) { out += "<ul>" l ++ } while (i < l) { out += "</ul>" l -- } out += "<li><a href='#" + el.id + "'>" + ( el.innerText || el.text || el.innerHTML) + "</a>" return out }).join("\n") toc.id = "toc" document.body.appendChild(toc) })() </script> </body></html>
Java
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail()
Java
{% extends "layout.html" %} {% block body %} <title>All Events - Media Services</title> <form id="adminForm" action="" method=post> <div class="container"> <table class="table"> <thead> <td> <ul class="nav nav-pills"> <li class="nav-item"> <a class="nav-link active" href="#">Upcoming Events</a> </li> <li class="nav-item"> <a class="nav-link" href="{{ url_for('past') }}">Past Events</a> </li> </ul> </td> <td> <button type="button" class="btn btn-outline-secondary" onclick="toggleSignUps()"> <span id="signUpText" class="text-muted"> Please Wait...</span> </button> </td> <td style="text-align:right"> <a href="{{ url_for('new') }}" class="btn btn-success"> <i class="fa fa-plus" aria-hidden="true"></i> New Event </a> </td> </thead> </table> <table class="table table-hover"> {% block events %}{% endblock %} </table> <!-- bottom buttons --> </div> </form> <script> currentPage = "edit"; $(window).on('load', function(){ socket.emit("getSignUps") }) function lockEvent(event) { socket.emit("lockEvent", String(event)); document.getElementById("lock_"+event).innerHTML = "Please Wait..."; } function toggleSignUps() { socket.emit("toggleSignUps"); document.getElementById("signUpText").innerHTML = "Please Wait..."; } socket.on('eventLock', function(data) { if (data.locked) { document.getElementById("lock_"+data.event).setAttribute("class", "btn btn-sm btn-danger"); document.getElementById("lock_"+data.event).innerHTML = "<i class=\"fa fa-lock\"> </i> Locked"; } else { document.getElementById("lock_"+data.event).setAttribute("class", "btn btn-sm btn-default"); document.getElementById("lock_"+data.event).innerHTML = "<i class=\"fa fa-unlock\"> </i> Unlocked"; } }); socket.on('signUpsAvailable', function(data) { if (data.available) { document.getElementById("signUpText").setAttribute("class", "text-success"); document.getElementById("signUpText").innerHTML = "<i id=\"signUpIcon\" class=\"fa fa-toggle-on\" aria-hidden=\"true\"></i> Sign-Ups Open"; } else { document.getElementById("signUpText").setAttribute("class", "text-danger"); document.getElementById("signUpText").innerHTML = "<i id=\"signUpIcon\" class=\"fa fa-toggle-off\" aria-hidden=\"true\"></i> Sign-Ups Closed"; } }); </script> {% endblock %}
Java
html, body { font-family: 'Roboto', 'Helvetica', sans-serif; } strong, b { font-weight: 700; } h1, h2, h3 { font-family: "Roboto Slab", "Helvetica", "Arial", sans-serif; } pre, code { font-family: "Roboto mono", monospace; } .ghostdown-edit-content { position: absolute; top: 50px; bottom: 50px; left: 0; right: 0; width: 99%; } .editor-title { font-family: "Roboto Condensed", "Helvetica", "Arial", sans-serif; text-transform: uppercase; font-size: 12px; height: 42px; margin: 0; padding: 0 10px; } .ghostdown-button-save { position: absolute; bottom: 7px; right: 7px; } .ghostdown-container { position: absolute; top: 0; right: 0; bottom: 0; left: 0; } #ghostdown-preview { overflow-y: scroll; position: absolute; top: 42px; right: 0; bottom: 0; left: 0; } #ghostdown-rendered { padding: 0 15px 15px; } #ghostdown-preview img { max-width: 100%; } .ghostdown-panel { position: relative; margin-bottom: 50px; } .ghostdown-footer { position: absolute; left: 0; right: 0; bottom: 0; padding: 15px; } #ghostdown-wordcount { float: right; display: inline-block; margin-top: -42px; padding: 10px 10px 0 0 } /******************************************** * CodeMirror Markup Styling *******************************************/ .CodeMirror { position: absolute; top: 42px; right: 0; bottom: 0; left: 0; height: auto; font-family: "Roboto Mono", monospace; } .CodeMirror-lines{ padding: 0 7px 20px; } .CodeMirror .cm-header{ color: #000; } .CodeMirror .cm-header-1 { font-size: 40px; line-height: 1.35; margin: 18px 0; display: inline-block; } .CodeMirror .cm-header-2 { font-size: 30px; line-height: 1.35; margin: 5px 0; display: inline-block; } .CodeMirror .cm-header-3 { font-size: 24px; line-height: 1.35; margin: 5px 0; display: inline-block; } /******************************************** * Dropzone Styling *******************************************/ p.dropzone { }
Java
function RenderPassManager(renderer) { // not implemented yet throw "Not implemented"; var mRenderPasses = []; return this; } RenderPassManager.prototype.addRenderPass = function(renderPass) { mRenderPasses.push(renderPass); }; RenderPassManager.prototype.render = function() { for(var renderPass in mRenderPasses) { renderPass.sort(); renderPass.render(renderer); renderPass.clear(); } };
Java
--- layout: post title: "IT业编程四大魔道天王" date: 2017-11-10 16:09:16 +0800 tag: [博客] --- IT业编程四大魔道天王的博客地址。 胡正 - [辟支佛胡正 · 阿罗汉尊者 · 功德藏闯菩萨](http://www.huzheng.org/myapps.php) 田春 - [Chun Tian (binghe)](http://tianchunbinghe.blog.163.com/) 李杀 - [Xah Lee Web 李杀网](http://xahlee.org/) 王垠 - [当然我在扯淡](http://www.yinwang.org/)
Java
package com.malalaoshi.android.ui.dialogs; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import com.malalaoshi.android.R; import com.malalaoshi.android.core.network.api.ApiExecutor; import com.malalaoshi.android.core.network.api.BaseApiContext; import com.malalaoshi.android.core.stat.StatReporter; import com.malalaoshi.android.core.utils.MiscUtil; import com.malalaoshi.android.entity.Comment; import com.malalaoshi.android.network.Constants; import com.malalaoshi.android.network.api.PostCommentApi; import com.malalaoshi.android.ui.widgets.DoubleImageView; import org.json.JSONException; import org.json.JSONObject; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by donald on 2017/6/29. */ public class CommentDialog extends BaseDialog { private static String ARGS_DIALOG_COMMENT_TYPE = "comment type"; private static String ARGS_DIALOG_TEACHER_NAME = "teacher name"; private static String ARGS_DIALOG_TEACHER_AVATAR = "teacher avatar"; private static String ARGS_DIALOG_LECTURER_NAME = "lecturer name"; private static String ARGS_DIALOG_LECTURER_AVATAR = "lecturer avatar"; private static String ARGS_DIALOG_ASSIST_NAME = "assist name"; private static String ARGS_DIALOG_ASSIST_AVATAR = "assist avatar"; private static String ARGS_DIALOG_COURSE_NAME = "course name"; private static String ARGS_DIALOG_COMMENT = "comment"; private static String ARGS_DIALOG_TIMESLOT = "timeslot"; @Bind(R.id.div_comment_dialog_avatar) DoubleImageView mDivCommentDialogAvatar; @Bind(R.id.tv_comment_dialog_teacher_course) TextView mTvCommentDialogTeacherCourse; @Bind(R.id.rb_comment_dialog_score) RatingBar mRbCommentDialogScore; @Bind(R.id.et_comment_dialog_input) EditText mEtCommentDialogInput; @Bind(R.id.tv_comment_dialog_commit) TextView mTvCommentDialogCommit; @Bind(R.id.iv_comment_dialog_close) ImageView mIvCommentDialogClose; private int mCommentType; private String mTeacherName; private String mTeacherAvatar; private String mLeactureAvatar; private String mLeactureName; private String mAssistantAvatar; private String mAssistantName; private String mCourseName; private Comment mComment; private long mTimeslot; private OnCommentResultListener mResultListener; public CommentDialog(Context context) { super(context); } public CommentDialog(Context context, Bundle bundle) { super(context); if (bundle != null) { mCommentType = bundle.getInt(ARGS_DIALOG_COMMENT_TYPE); if (mCommentType == 0) { mTeacherName = bundle.getString(ARGS_DIALOG_TEACHER_NAME, ""); mTeacherAvatar = bundle.getString(ARGS_DIALOG_TEACHER_AVATAR, ""); } else if (mCommentType == 1) { mLeactureAvatar = bundle.getString(ARGS_DIALOG_LECTURER_AVATAR, ""); mLeactureName = bundle.getString(ARGS_DIALOG_LECTURER_NAME, ""); mAssistantAvatar = bundle.getString(ARGS_DIALOG_ASSIST_AVATAR, ""); mAssistantName = bundle.getString(ARGS_DIALOG_ASSIST_NAME, ""); } mCourseName = bundle.getString(ARGS_DIALOG_COURSE_NAME, ""); mComment = bundle.getParcelable(ARGS_DIALOG_COMMENT); mTimeslot = bundle.getLong(ARGS_DIALOG_TIMESLOT, 0L); } initView(); } private void initView() { setCancelable(false); if (mCommentType == 0) mDivCommentDialogAvatar.loadImg(mTeacherAvatar, "", DoubleImageView.LOAD_SIGNLE_BIG); else if (mCommentType == 1) mDivCommentDialogAvatar.loadImg(mLeactureAvatar, mAssistantAvatar, DoubleImageView.LOAD_DOUBLE); if (mComment != null) { StatReporter.commentPage(true); updateUI(mComment); mRbCommentDialogScore.setIsIndicator(true); mEtCommentDialogInput.setFocusableInTouchMode(false); mEtCommentDialogInput.setCursorVisible(false); mTvCommentDialogCommit.setText("查看评价"); } else { StatReporter.commentPage(false); mTvCommentDialogCommit.setText("提交"); mRbCommentDialogScore.setIsIndicator(false); mEtCommentDialogInput.setFocusableInTouchMode(true); mEtCommentDialogInput.setCursorVisible(true); } mTvCommentDialogTeacherCourse.setText(mCourseName); mRbCommentDialogScore.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() { @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { if (mComment == null){ if (fromUser && rating > 0 && mEtCommentDialogInput.getText().length() > 0){ mTvCommentDialogCommit.setEnabled(true); }else { mTvCommentDialogCommit.setEnabled(false); } } } }); mEtCommentDialogInput.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (mComment == null){ if (s.length() > 0 && mRbCommentDialogScore.getRating() > 0){ mTvCommentDialogCommit.setEnabled(true); }else { mTvCommentDialogCommit.setEnabled(false); } } } }); } @Override protected View getView() { View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_comment_v2, null); ButterKnife.bind(this, view); return view; } private void updateUI(Comment comment) { if (comment != null) { mRbCommentDialogScore.setRating(comment.getScore()); mEtCommentDialogInput.setText(comment.getContent()); } else { mRbCommentDialogScore.setRating(0); mEtCommentDialogInput.setText(""); } } @Override protected int getDialogStyleId() { return 0; } public static CommentDialog newInstance(Context context, String lecturerName, String lecturerAvatarUrl, String assistName, String assistAvatarUrl, String courseName, Long timeslot, Comment comment) { Bundle args = new Bundle(); args.putInt(ARGS_DIALOG_COMMENT_TYPE, 1); args.putString(ARGS_DIALOG_LECTURER_NAME, lecturerName); args.putString(ARGS_DIALOG_LECTURER_AVATAR, lecturerAvatarUrl); args.putString(ARGS_DIALOG_ASSIST_NAME, assistName); args.putString(ARGS_DIALOG_ASSIST_AVATAR, assistAvatarUrl); args.putString(ARGS_DIALOG_COURSE_NAME, courseName); args.putParcelable(ARGS_DIALOG_COMMENT, comment); args.putLong(ARGS_DIALOG_TIMESLOT, timeslot); // f.setArguments(args); CommentDialog f = new CommentDialog(context, args); return f; } public void setOnCommentResultListener(OnCommentResultListener listener) { mResultListener = listener; } public static CommentDialog newInstance(Context context, String teacherName, String teacherAvatarUrl, String courseName, Long timeslot, Comment comment) { Bundle args = new Bundle(); args.putInt(ARGS_DIALOG_COMMENT_TYPE, 0); args.putString(ARGS_DIALOG_TEACHER_NAME, teacherName); args.putString(ARGS_DIALOG_TEACHER_AVATAR, teacherAvatarUrl); args.putString(ARGS_DIALOG_COURSE_NAME, courseName); args.putParcelable(ARGS_DIALOG_COMMENT, comment); args.putLong(ARGS_DIALOG_TIMESLOT, timeslot); // f.setArguments(args); CommentDialog f = new CommentDialog(context, args); return f; } @OnClick({R.id.tv_comment_dialog_commit, R.id.iv_comment_dialog_close}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.tv_comment_dialog_commit: commit(); dismiss(); break; case R.id.iv_comment_dialog_close: dismiss(); break; } } private void commit() { StatReporter.commentSubmit(); if (mComment != null) { dismiss(); return; } float score = mRbCommentDialogScore.getRating(); if (score == 0.0) { MiscUtil.toast(R.string.rate_the_course); return; } String content = mEtCommentDialogInput.getText().toString(); if (TextUtils.isEmpty(content)) { MiscUtil.toast(R.string.write_few_reviews); return; } JSONObject json = new JSONObject(); try { json.put(Constants.TIMESLOT, mTimeslot); json.put(Constants.SCORE, score); json.put(Constants.CONTENT, content); } catch (JSONException e) { e.printStackTrace(); return; } ApiExecutor.exec(new PostCommentRequest(this, json.toString())); } public interface OnCommentResultListener { void onSuccess(Comment comment); } private static final class PostCommentRequest extends BaseApiContext<CommentDialog, Comment> { private String body; public PostCommentRequest(CommentDialog commentDialog, String body) { super(commentDialog); this.body = body; } @Override public Comment request() throws Exception { return new PostCommentApi().post(body); } @Override public void onApiSuccess(@NonNull Comment response) { get().commentSucceed(response); } @Override public void onApiFailure(Exception exception) { get().commentFailed(); } } private void commentFailed() { MiscUtil.toast(R.string.comment_failed); } private void commentSucceed(Comment response) { MiscUtil.toast(R.string.comment_succeed); if (mResultListener != null) mResultListener.onSuccess(response); dismiss(); } }
Java
#!/usr/bin/env node var path = require('path'); var fs = require('fs'); var optimist = require('optimist'); var prompt = require('prompt'); var efs = require('efs'); var encext = require('./index'); var defaultAlgorithm = 'aes-128-cbc'; var argv = optimist .usage('usage: encext [-r] [-a algorithm] [file ...]') .describe('r', 'recursively encrypt supported files') .boolean('r') .alias('r', 'recursive') .default('r', false) .describe('a', 'encryption algorithm') .string('a') .alias('a', 'algorithm') .default('a', defaultAlgorithm) .argv; if (argv.help) { optimist.showHelp(); } var pwdPrompt = { name: 'password', description: 'Please enter the encryption password', required: true, hidden: true }; prompt.message = 'encext'; prompt.colors = false; prompt.start(); prompt.get(pwdPrompt, function(err, result) { if (err) { console.error('[ERROR]', err); process.exit(1); } efs = efs.init(argv.algorithm, result.password); argv._.forEach(processPath); }); function processPath(fspath) { fs.stat(fspath, onStat); function onStat(err, stats) { if (err) { return exit(err) } if (stats.isDirectory() && argv.recursive) { fs.readdir(fspath, onReaddir); } else if (stats.isFile() && encext.isSupported(fspath)) { encrypt(fspath); } } function onReaddir(err, fspaths) { if (err) { return exit(err) } fspaths.forEach(function(p) { processPath(path.join(fspath, p)); }); } } function encrypt(fspath) { var encpath = fspath + '_enc'; var writeStream = efs.createWriteStream(encpath); writeStream.on('error', exit); var readStream = fs.createReadStream(fspath); readStream.on('error', exit); readStream.on('end', function() { console.info(fspath, 'encrypted and written to', encpath); }); readStream.pipe(writeStream); } function exit(err) { console.error(err); process.exit(1); }
Java
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title> Sebastian Daza | R package to compute statistics from the American Community Survey (ACS) and Decennial US Census </title> <meta name="description" content="A simple, whitespace theme for academics. Based on [*folio](https://github.com/bogoli/-folio) design. "> <!-- Open Graph --> <!-- Bootstrap & MDB --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/css/mdb.min.css" integrity="sha512-RO38pBRxYH3SoOprtPTD86JFOclM51/XTIdEPh5j8sj4tp8jmQIx26twG52UaLi//hQldfrh7e51WzP9wuP32Q==" crossorigin="anonymous" /> <!-- Fonts & Icons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog==" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.9.0/css/academicons.min.css" integrity="sha512-W4yqoT1+8NLkinBLBZko+dFB2ZbHsYLDdr50VElllRcNt2Q4/GSs6u71UHKxB7S6JEMCp5Ve4xjh3eGQl/HRvg==" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:100,300,400,500,700|Material+Icons"> <!-- Code Syntax Highlighting --> <link rel="stylesheet" href="https://gitcdn.xyz/repo/jwarby/jekyll-pygments-themes/master/github.css" /> <!-- Styles --> <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎯</text></svg>"> <link rel="stylesheet" href="/assets/css/main.css"> <link rel="canonical" href="/blog/2016/acsr/"> <!-- JQuery --> <!-- jQuery --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script> <!-- Theming--> <script src="/assets/js/theme.js"></script> <script src="/assets/js/dark_mode.js"></script> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-34554402-2"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'UA-34554402-2'); </script> <!-- MathJax --> <script type="text/javascript"> window.MathJax = { tex: { tags: 'ams' } }; </script> <script defer type="text/javascript" id="MathJax-script" src="https://cdn.jsdelivr.net/npm/mathjax@3.2.0/es5/tex-mml-chtml.js"></script> <script defer src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script> </head> <body class="fixed-top-nav "> <!-- Header --> <header> <!-- Nav Bar --> <nav id="navbar" class="navbar navbar-light navbar-expand-sm fixed-top"> <div class="container"> <a class="navbar-brand title font-weight-lighter" href="https://sdaza.com/"> <span class="font-weight-bold">Sebastian</span> Daza </a> <!-- Navbar Toggle --> <button class="navbar-toggler collapsed ml-auto" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button> <div class="collapse navbar-collapse text-right" id="navbarNav"> <ul class="navbar-nav ml-auto flex-nowrap"> <!-- About --> <li class="nav-item "> <a class="nav-link" href="/"> about </a> </li> <!-- Blog --> <li class="nav-item active"> <a class="nav-link" href="/blog/"> blog </a> </li> <!-- Other pages --> <li class="nav-item "> <a class="nav-link" href="/cv/"> cv </a> </li> <li class="nav-item "> <a class="nav-link" href="/projects/"> projects </a> </li> <li class="nav-item "> <a class="nav-link" href="/publications/"> publications </a> </li> <div class = "toggle-container"> <a id = "light-toggle"> <i class="fas fa-moon"></i> <i class="fas fa-sun"></i> </a> </div> </ul> </div> </div> </nav> </header> <!-- Content --> <div class="container mt-5"> <div class="post"> <header class="post-header"> <h1 class="post-title">R package to compute statistics from the American Community Survey (ACS) and Decennial US Census</h1> <p class="post-meta">July 6, 2016 • Sebastian Daza</p> </header> <article class="post-content"> <p>The <code class="language-plaintext highlighter-rouge">acsr</code> package helps extracting variables and computing statistics using the America Community Survey and Decennial US Census. It was created for the <a href="http://www.apl.wisc.edu/">Applied Population Laboratory</a> (APL) at the University of Wisconsin-Madison.</p> <h2 class="section-heading">Installation</h2> <p>The functions depend on the <code class="language-plaintext highlighter-rouge">acs</code> and <code class="language-plaintext highlighter-rouge">data.table</code> packages, so it is necessary to install then before using <code class="language-plaintext highlighter-rouge">acsr</code>. The <code class="language-plaintext highlighter-rouge">acsr</code> package is hosted on a github repository and can be installed using <code class="language-plaintext highlighter-rouge">devtools</code>:</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">devtools</span><span class="o">::</span><span class="n">install_github</span><span class="p">(</span><span class="s2">"sdaza/acsr"</span><span class="p">)</span><span class="w"> </span><span class="n">library</span><span class="p">(</span><span class="n">acsr</span><span class="p">)</span></code></pre></figure> <p>Remember to set the ACS API key, to check the help documentation and the default values of the <code class="language-plaintext highlighter-rouge">acsr</code> functions.</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">api.key.install</span><span class="p">(</span><span class="n">key</span><span class="o">=</span><span class="s2">"*"</span><span class="p">)</span><span class="w"> </span><span class="o">?</span><span class="n">sumacs</span><span class="w"> </span><span class="o">?</span><span class="n">acsdata</span></code></pre></figure> <p>The default dataset is <code class="language-plaintext highlighter-rouge">acs</code>, the level is <code class="language-plaintext highlighter-rouge">state</code> (Wisconsin, <code class="language-plaintext highlighter-rouge">state = "WI"</code>), the <code class="language-plaintext highlighter-rouge">endyear</code> is 2014, and the confidence level to compute margins of error (MOEs) is 90%.</p> <h2 class="section-heading">Levels</h2> <p>The <code class="language-plaintext highlighter-rouge">acsr</code> functions can extract all the levels available in the <code class="language-plaintext highlighter-rouge">acs</code> package. The table below shows the summary and required levels when using the <code class="language-plaintext highlighter-rouge">acsdata</code> and <code class="language-plaintext highlighter-rouge">sumacs</code> functions:</p> <table> <thead> <tr> <th>summary number</th> <th>levels</th> </tr> </thead> <tbody> <tr> <td>010</td> <td>us</td> </tr> <tr> <td>020</td> <td>region</td> </tr> <tr> <td>030</td> <td>division</td> </tr> <tr> <td>040</td> <td>state</td> </tr> <tr> <td>050</td> <td>state, county</td> </tr> <tr> <td>060</td> <td>state, county, county.subdivision</td> </tr> <tr> <td>140</td> <td>state, county, tract</td> </tr> <tr> <td>150</td> <td>state, county, tract, block.group</td> </tr> <tr> <td>160</td> <td>state, place</td> </tr> <tr> <td>250</td> <td>american.indian.area</td> </tr> <tr> <td>320</td> <td>state, msa</td> </tr> <tr> <td>340</td> <td>state, csa</td> </tr> <tr> <td>350</td> <td>necta</td> </tr> <tr> <td>400</td> <td>urban.area</td> </tr> <tr> <td>500</td> <td>state, congressional.district</td> </tr> <tr> <td>610</td> <td>state, state.legislative.district.upper</td> </tr> <tr> <td>620</td> <td>state, state.legislative.district.lower</td> </tr> <tr> <td>795</td> <td>state, puma</td> </tr> <tr> <td>860</td> <td>zip.code</td> </tr> <tr> <td>950</td> <td>state, school.district.elementary</td> </tr> <tr> <td>960</td> <td>state, school.district.secondary</td> </tr> <tr> <td>970</td> <td>state, school.district.unified</td> </tr> </tbody> </table> <h2 class="section-heading">Getting variables and statistics</h2> <p>We can use the <code class="language-plaintext highlighter-rouge">sumacs</code> function to extract variable and statistics. We have to specify the corresponding method (e.g., <em>proportion</em> or just <em>variable</em>), and the name of the statistic or variable to be included in the output.</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">sumacs</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"(b16004_004 + b16004_026 + b16004_048 / b16004_001)"</span><span class="p">,</span><span class="w"> </span><span class="s2">"b16004_026"</span><span class="p">),</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"mynewvar"</span><span class="p">,</span><span class="w"> </span><span class="s2">"myvar"</span><span class="p">),</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"prop"</span><span class="p">,</span><span class="w"> </span><span class="s2">"variable"</span><span class="p">),</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"division"</span><span class="p">))</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: acs 2014" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 2" ## [1] ". . . . . . Getting division data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 50%" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## sumlevel geoid division mynewvar_est mynewvar_moe myvar_est myvar_moe ## 1: 030 NA 1 0.0762 0.000347 770306 3490 ## 2: 030 NA 2 0.1182 0.000278 3332150 9171 ## 3: 030 NA 3 0.0599 0.000196 1819417 7209 ## 4: 030 NA 4 0.0411 0.000277 547577 4461 ## 5: 030 NA 5 0.1108 0.000246 4526480 11869 ## 6: 030 NA 6 0.0320 0.000265 402475 3781 ## 7: 030 NA 7 0.2203 0.000469 5318126 13044 ## 8: 030 NA 8 0.1582 0.000602 2279303 10746 ## 9: 030 NA 9 0.2335 0.000501 7765838 20289</code></pre></figure> <p>To download the data can be slow, especially when many levels are being used (e.g., blockgroup). A better approach in those cases is, first, download the data using the function <code class="language-plaintext highlighter-rouge">acsdata</code> , and then use them as input.</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">mydata</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">acsdata</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"(b16004_004 + b16004_026 + b16004_048 / b16004_001)"</span><span class="p">,</span><span class="w"> </span><span class="s2">"b16004_026"</span><span class="p">),</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"division"</span><span class="p">))</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] ". . . . . . Getting division data"</code></pre></figure> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">sumacs</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"(b16004_004 + b16004_026 + b16004_048 / b16004_001)"</span><span class="p">,</span><span class="w"> </span><span class="s2">"b16004_026"</span><span class="p">),</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"mynewvar"</span><span class="p">,</span><span class="w"> </span><span class="s2">"myvar"</span><span class="p">),</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"prop"</span><span class="p">,</span><span class="w"> </span><span class="s2">"variable"</span><span class="p">),</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"division"</span><span class="p">),</span><span class="w"> </span><span class="n">data</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">mydata</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: acs 2014" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 2" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 50%" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## sumlevel geoid division mynewvar_est mynewvar_moe myvar_est myvar_moe ## 1: 030 NA 1 0.0762 0.000347 770306 3490 ## 2: 030 NA 2 0.1182 0.000278 3332150 9171 ## 3: 030 NA 3 0.0599 0.000196 1819417 7209 ## 4: 030 NA 4 0.0411 0.000277 547577 4461 ## 5: 030 NA 5 0.1108 0.000246 4526480 11869 ## 6: 030 NA 6 0.0320 0.000265 402475 3781 ## 7: 030 NA 7 0.2203 0.000469 5318126 13044 ## 8: 030 NA 8 0.1582 0.000602 2279303 10746 ## 9: 030 NA 9 0.2335 0.000501 7765838 20289</code></pre></figure> <h2 class="section-heading">Standard errors</h2> <p>When computing statistics there are two ways to define the standard errors:</p> <ul> <li>Including all standard errors of the variables used to compute a statistic (<code class="language-plaintext highlighter-rouge">one.zero = FALSE</code>)</li> <li>Include all standard errors except those of variables that are equal to zero. Only the maximum standard error of the variables equal to zero is included (<code class="language-plaintext highlighter-rouge">one.zero = TRUE</code>)</li> <li>The default value is <code class="language-plaintext highlighter-rouge">one.zero = TRUE</code></li> </ul> <p>For more details about how standard errors are computed for proportions, ratios and aggregations look at <a href="https://www.census.gov/content/dam/Census/library/publications/2008/acs/ACSGeneralHandbook.pdf">A Compass for Understanding and Using American Community Survey Data</a>.</p> <p>Below an example when estimating proportions and using <code class="language-plaintext highlighter-rouge">one.zero = FALSE</code>:</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">sumacs</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"(b16004_004 + b16004_026 + b16004_048) / b16004_001"</span><span class="p">,</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"mynewvar"</span><span class="p">,</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"prop"</span><span class="p">,</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"tract"</span><span class="p">,</span><span class="w"> </span><span class="n">county</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">1</span><span class="p">,</span><span class="w"> </span><span class="n">tract</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">950501</span><span class="p">,</span><span class="w"> </span><span class="n">endyear</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">2013</span><span class="p">,</span><span class="w"> </span><span class="n">one.zero</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">FALSE</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: acs 2013" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 1" ## [1] ". . . . . . Getting tract data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## sumlevel geoid st_fips cnty_fips tract_fips mynewvar_est mynewvar_moe ## 1: 140 55001950501 55 1 950501 0.0226 0.0252</code></pre></figure> \[SE = \sqrt{ \frac{(5.47 ^ 2 + 22.49 ^ 2 + 5.47 ^ 2) - ( 0.02 ^ 2 \times 102.13 ^ 2)}{1546} } \times 1.645 = 0.0252\] <p>When <code class="language-plaintext highlighter-rouge">one.zero = TRUE</code>:</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">sumacs</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"(b16004_004 + b16004_026 + b16004_048) / b16004_001"</span><span class="p">,</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"mynewvar"</span><span class="p">,</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"prop"</span><span class="p">,</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"tract"</span><span class="p">,</span><span class="w"> </span><span class="n">county</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">1</span><span class="p">,</span><span class="w"> </span><span class="n">tract</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">950501</span><span class="p">,</span><span class="w"> </span><span class="n">endyear</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">2013</span><span class="p">,</span><span class="w"> </span><span class="n">one.zero</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">TRUE</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: acs 2013" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 1" ## [1] ". . . . . . Getting tract data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## sumlevel geoid st_fips cnty_fips tract_fips mynewvar_est mynewvar_moe ## 1: 140 55001950501 55 1 950501 0.0226 0.0245</code></pre></figure> \[SE_{\text{ one.zero}} \sqrt{ \frac{(5.47 ^ 2 + 22.49 ^ 2) - ( 0.02 ^ 2 \times 102.13 ^ 2)}{1546} } \times 1.645 = 0.0245\] <p>When the square root value in the standard error formula doesn’t exist (e.g., the square root of a negative number), the ratio formula is instead used. The ratio adjustment is done <strong>variable by variable</strong> .</p> <p>It can also be that the <code class="language-plaintext highlighter-rouge">one.zero</code> option makes the square root undefinable. In those cases, the function uses again the <strong>ratio</strong> formula to compute standard errors. There is also a possibility that the standard error estimates using the <strong>ratio</strong> formula are higher than the <strong>proportion</strong> estimates without the <code class="language-plaintext highlighter-rouge">one.zero</code> option.</p> <h2 class="section-heading">Decennial Data from the US Census</h2> <p>Let’s get the African American and Hispanic population by state. In this case, we don’t have any estimation of margin of error.</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">sumacs</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"p0080004"</span><span class="p">,</span><span class="w"> </span><span class="s2">"p0090002"</span><span class="p">),</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"variable"</span><span class="p">,</span><span class="w"> </span><span class="n">dataset</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"sf1"</span><span class="p">,</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"state"</span><span class="p">,</span><span class="w"> </span><span class="n">state</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"*"</span><span class="p">,</span><span class="w"> </span><span class="n">endyear</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">2010</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: sf1 2010" ## [1] ". . . . . . ACS/Census variables : 2" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 2" ## [1] ". . . . . . Getting state data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 50%" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## sumlevel geoid st_fips p0080004 p0090002 ## 1: 040 01 01 1251311 185602 ## 2: 040 02 02 23263 39249 ## 3: 040 04 04 259008 1895149 ## 4: 040 05 05 449895 186050 ## 5: 040 06 06 2299072 14013719 ## 6: 040 08 08 201737 1038687 ## 7: 040 09 09 362296 479087 ## 8: 040 10 10 191814 73221 ## 9: 040 11 11 305125 54749 ## 10: 040 12 12 2999862 4223806 ## 11: 040 13 13 2950435 853689 ## 12: 040 15 15 21424 120842 ## 13: 040 16 16 9810 175901 ## 14: 040 17 17 1866414 2027578 ## 15: 040 18 18 591397 389707 ## 16: 040 19 19 89148 151544 ## 17: 040 20 20 167864 300042 ## 18: 040 21 21 337520 132836 ## 19: 040 22 22 1452396 192560 ## 20: 040 23 23 15707 16935 ## 21: 040 24 24 1700298 470632 ## 22: 040 25 25 434398 627654 ## 23: 040 26 26 1400362 436358 ## 24: 040 27 27 274412 250258 ## 25: 040 28 28 1098385 81481 ## 26: 040 29 29 693391 212470 ## 27: 040 30 30 4027 28565 ## 28: 040 31 31 82885 167405 ## 29: 040 32 32 218626 716501 ## 30: 040 33 33 15035 36704 ## 31: 040 34 34 1204826 1555144 ## 32: 040 35 35 42550 953403 ## 33: 040 36 36 3073800 3416922 ## 34: 040 37 37 2048628 800120 ## 35: 040 38 38 7960 13467 ## 36: 040 39 39 1407681 354674 ## 37: 040 40 40 277644 332007 ## 38: 040 41 41 69206 450062 ## 39: 040 42 42 1377689 719660 ## 40: 040 44 44 60189 130655 ## 41: 040 45 45 1290684 235682 ## 42: 040 46 46 10207 22119 ## 43: 040 47 47 1057315 290059 ## 44: 040 48 48 2979598 9460921 ## 45: 040 49 49 29287 358340 ## 46: 040 50 50 6277 9208 ## 47: 040 51 51 1551399 631825 ## 48: 040 53 53 240042 755790 ## 49: 040 54 54 63124 22268 ## 50: 040 55 55 359148 336056 ## 51: 040 56 56 4748 50231 ## 52: 040 72 72 461498 3688455 ## sumlevel geoid st_fips p0080004 p0090002</code></pre></figure> <h2 class="section-heading">Output</h2> <p>The output can be formatted using a wide or long format:</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">sumacs</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"(b16004_004 + b16004_026 + b16004_048 / b16004_001)"</span><span class="p">,</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"mynewvar"</span><span class="p">,</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"prop"</span><span class="p">,</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"division"</span><span class="p">,</span><span class="w"> </span><span class="n">format.out</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"long"</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: acs 2014" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 1" ## [1] ". . . . . . Getting division data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## geoid sumlevel division var_name est moe ## 1: NA 030 1 mynewvar 0.0762 0.000347 ## 2: NA 030 2 mynewvar 0.1182 0.000278 ## 3: NA 030 3 mynewvar 0.0599 0.000196 ## 4: NA 030 4 mynewvar 0.0411 0.000277 ## 5: NA 030 5 mynewvar 0.1108 0.000246 ## 6: NA 030 6 mynewvar 0.0320 0.000265 ## 7: NA 030 7 mynewvar 0.2203 0.000469 ## 8: NA 030 8 mynewvar 0.1582 0.000602 ## 9: NA 030 9 mynewvar 0.2335 0.000501</code></pre></figure> <p>And it can also be exported to a csv file:</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">sumacs</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"(b16004_004 + b16004_026 + b16004_048 / b16004_001)"</span><span class="p">,</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"mynewvar"</span><span class="p">,</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"prop"</span><span class="p">,</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"division"</span><span class="p">,</span><span class="w"> </span><span class="n">file</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"myfile.out"</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: acs 2014" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 1" ## [1] ". . . . . . Getting division data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output" ## [1] "Data exported to a CSV file! "</code></pre></figure> <h2 class="section-heading">Combining geographic levels</h2> <p>We can combine geographic levels using two methods: (1) <code class="language-plaintext highlighter-rouge">sumacs</code> and (2) <code class="language-plaintext highlighter-rouge">combine.output</code>. The first one allows only single combinations, the second multiple ones.</p> <p>If I want to combine two states (e.g., Wisconsin and Minnesota) I can use:</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">sumacs</span><span class="p">(</span><span class="s2">"(b16004_004 + b16004_026 + b16004_048 / b16004_001)"</span><span class="p">,</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"mynewvar"</span><span class="p">,</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"prop"</span><span class="p">,</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"state"</span><span class="p">,</span><span class="w"> </span><span class="n">state</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">list</span><span class="p">(</span><span class="s2">"WI"</span><span class="p">,</span><span class="w"> </span><span class="s2">"MN"</span><span class="p">),</span><span class="w"> </span><span class="n">combine</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">TRUE</span><span class="p">,</span><span class="w"> </span><span class="n">print.levels</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">FALSE</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: acs 2014" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 1" ## [1] ". . . . . . Getting combined data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## geoid combined_group mynewvar_est mynewvar_moe ## 1: NA aggregate 0.042 0.000331</code></pre></figure> <p>If I want to put together multiple combinations (e.g., groups of states):</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">combine.output</span><span class="p">(</span><span class="s2">"(b16004_004 + b16004_026 + b16004_048 / b16004_001)"</span><span class="p">,</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"mynewvar"</span><span class="p">,</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"prop"</span><span class="p">,</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">list</span><span class="p">(</span><span class="s2">"state"</span><span class="p">,</span><span class="w"> </span><span class="s2">"state"</span><span class="p">),</span><span class="w"> </span><span class="n">state</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">list</span><span class="p">(</span><span class="w"> </span><span class="nf">list</span><span class="p">(</span><span class="s2">"WI"</span><span class="p">,</span><span class="w"> </span><span class="s2">"MN"</span><span class="p">),</span><span class="w"> </span><span class="nf">list</span><span class="p">(</span><span class="s2">"CA"</span><span class="p">,</span><span class="w"> </span><span class="s2">"OR"</span><span class="p">)),</span><span class="w"> </span><span class="c1"># nested list</span><span class="w"> </span><span class="n">combine.names</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"WI+MN"</span><span class="p">,</span><span class="w"> </span><span class="s2">"CA+OR"</span><span class="p">),</span><span class="w"> </span><span class="n">print.levels</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">FALSE</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] ". . . . . . Defining WI+MN" ## [1] "Extracting data from: acs 2014" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 1" ## [1] ". . . . . . Getting combined data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output" ## [1] ". . . . . . Defining CA+OR" ## [1] "Extracting data from: acs 2014" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 1" ## [1] ". . . . . . Getting combined data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## combined_group mynewvar_est mynewvar_moe ## 1: WI+MN 0.042 0.000331 ## 2: CA+OR 0.269 0.000565</code></pre></figure> <h2 class="section-heading">A map?</h2> <p>Let’s color a map using poverty by county:</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">pov</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">sumacs</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"b17001_002 / b17001_001 * 100"</span><span class="p">,</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"pov"</span><span class="p">),</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"prop"</span><span class="p">),</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"county"</span><span class="p">),</span><span class="w"> </span><span class="n">state</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"*"</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: acs 2014" ## [1] ". . . . . . ACS/Census variables : 2" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 1" ## [1] ". . . . . . Getting county data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">library</span><span class="p">(</span><span class="n">choroplethr</span><span class="p">)</span><span class="w"> </span><span class="n">library</span><span class="p">(</span><span class="n">choroplethrMaps</span><span class="p">)</span><span class="w"> </span><span class="n">pov</span><span class="p">[,</span><span class="w"> </span><span class="n">region</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nf">as.numeric</span><span class="p">(</span><span class="n">geoid</span><span class="p">)]</span><span class="w"> </span><span class="n">setnames</span><span class="p">(</span><span class="n">pov</span><span class="p">,</span><span class="w"> </span><span class="s2">"pov_est"</span><span class="p">,</span><span class="w"> </span><span class="s2">"value"</span><span class="p">)</span><span class="w"> </span><span class="n">county_choropleth</span><span class="p">(</span><span class="n">pov</span><span class="p">,</span><span class="w"> </span><span class="n">num_colors</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">5</span><span class="p">)</span></code></pre></figure> <p><img src="/assets/img/2016-07-06-acsr/unnamed-chunk-15-1.png" alt="center" /></p> <p>In sum, the <code class="language-plaintext highlighter-rouge">acsr</code> package:</p> <ul> <li>Reads formulas directly and extracts any ACS/Census variable</li> <li>Provides an automatized and tailored way to obtain indicators and MOEs</li> <li>Allows different outputs’ formats (wide and long, csv)</li> <li>Provides an easy way to adjust MOEs to different confidence levels</li> <li>Includes a variable-by-variable ratio adjustment of standard errors</li> <li>Includes the zero-option when computing standard errors for proportions, ratios, and aggregations</li> <li>Combines geographic levels flexibly</li> </ul> <p><strong>Last Update: 02/07/2016</strong></p> </article> <div id="disqus_thread"></div> <script type="text/javascript"> var disqus_shortname = 'sdaza'; var disqus_identifier = '/blog/2016/acsr'; var disqus_title = "R package to compute statistics from the American Community Survey (ACS) and Decennial US Census"; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> </div> <!-- Footer --> <footer class="fixed-bottom"> <div class="container mt-0"> &copy; Copyright 2021 Sebastian Daza. Powered by <a href="http://jekyllrb.com/" target="_blank">Jekyll</a> with <a href="https://github.com/alshedivat/al-folio">al-folio</a> theme. Hosted by <a href="https://pages.github.com/" target="_blank">GitHub Pages</a>. Last updated: August 28, 2021. </div> </footer> </body> <!-- Bootsrap & MDB scripts --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.4.4/umd/popper.min.js" integrity="sha512-eUQ9hGdLjBjY3F41CScH3UX+4JDSI9zXeroz7hJ+RteoCaY+GP/LDoM8AO+Pt+DRFw3nXqsjh9Zsts8hnYv8/A==" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha512-M5KW3ztuIICmVIhjSqXe01oV2bpe248gOxqmlcYrEzAvws7Pw3z6BK0iGbrwvdrUQUhi3eXgtxp5I8PDo9YfjQ==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/js/mdb.min.js" integrity="sha512-Mug9KHKmroQFMLm93zGrjhibM2z2Obg9l6qFG2qKjXEXkMp/VDkI4uju9m4QKPjWSwQ6O2qzZEnJDEeCw0Blcw==" crossorigin="anonymous"></script> <!-- Mansory & imagesLoaded --> <script defer src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.min.js"></script> <script defer src="https://unpkg.com/imagesloaded@4/imagesloaded.pkgd.min.js"></script> <script defer src="/assets/js/mansory.js" type="text/javascript"></script> <!-- Enable Tooltips --> <script type="text/javascript"> $(function () {$('[data-toggle="tooltip"]').tooltip()}) </script> <!-- Medium Zoom JS --> <script src="https://cdn.jsdelivr.net/npm/medium-zoom@1.0.6/dist/medium-zoom.min.js" integrity="sha256-EdPgYcPk/IIrw7FYeuJQexva49pVRZNmt3LculEr7zM=" crossorigin="anonymous"></script> <script src="/assets/js/zoom.js"></script> <!-- Load Common JS --> <script src="/assets/js/common.js"></script> </html>
Java
using CertificateManager.Entities; using CertificateManager.Entities.Interfaces; using System.Collections.Generic; using System.Security.Claims; namespace CertificateManager.Logic.Interfaces { public interface IAuditLogic { IEnumerable<AuditEvent> GetAllEvents(); void LogSecurityAuditSuccess(ClaimsPrincipal userContext, ILoggableEntity entity, EventCategory category); void LogSecurityAuditFailure(ClaimsPrincipal userContext, ILoggableEntity entity, EventCategory category); void LogOpsSuccess(ClaimsPrincipal userContext, string target, EventCategory category, string message); void LogOpsError(ClaimsPrincipal userContext, string target, EventCategory category); void LogOpsError(ClaimsPrincipal userContext, string target, EventCategory category, string message); void InitializeMockData(); void ClearLogs(ClaimsPrincipal user); } }
Java
<?php if (empty($content)) { return; } $title = 'Bank Emulator Authorization Center'; ?> <html lang="ru"> <?= View::make('ff-bank-em::layouts.head', array( 'title' => $title, )); ?> <body> <div class="navbar navbar-default"> <?= View::make('ff-bank-em::layouts.navbar-header', array( 'title' => $title, )); ?> </div> <?= $content ?> <?php require(__DIR__ . '/js.php') ?> </body> </html>
Java
export function wedgeYZ(a, b) { return a.y * b.z - a.z * b.y; } export function wedgeZX(a, b) { return a.z * b.x - a.x * b.z; } export function wedgeXY(a, b) { return a.x * b.y - a.y * b.x; }
Java
module Mlblog VERSION = "0.0.1" end
Java
package cloudformation // AWSECSService_DeploymentConfiguration AWS CloudFormation Resource (AWS::ECS::Service.DeploymentConfiguration) // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-deploymentconfiguration.html type AWSECSService_DeploymentConfiguration struct { // MaximumPercent AWS CloudFormation Property // Required: false // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-deploymentconfiguration.html#cfn-ecs-service-deploymentconfiguration-maximumpercent MaximumPercent int `json:"MaximumPercent,omitempty"` // MinimumHealthyPercent AWS CloudFormation Property // Required: false // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-deploymentconfiguration.html#cfn-ecs-service-deploymentconfiguration-minimumhealthypercent MinimumHealthyPercent int `json:"MinimumHealthyPercent,omitempty"` } // AWSCloudFormationType returns the AWS CloudFormation resource type func (r *AWSECSService_DeploymentConfiguration) AWSCloudFormationType() string { return "AWS::ECS::Service.DeploymentConfiguration" }
Java
package sysadmin import org.scalatest._ import scalikejdbc._ import scalikejdbc.scalatest.AutoRollback import skinny.logging.Logging import skinny.test.FactoryGirl class userAdminSpec extends fixture.FunSpec with Matchers with Connection with CreateTables with AutoRollback with Logging { override def db(): DB = NamedDB('sysadmin).toDB() describe("factory.conf") { it("should be available") { implicit session => val user = FactoryGirl(User).create() user.os should equal("Windows 8") user.java should equal("6") user.user should equal("sera") } } describe("with os/java/user attributes") { it("should be available") { implicit session => val user = FactoryGirl(User).withAttributes('os -> "MacOS X", 'java -> "8", 'user -> "sera").create() user.os should equal("MacOS X") user.java should equal("8") user.user should equal("sera") } } }
Java
var scroungejs = require('scroungejs'), startutils = require('./startutil'); startutils.createFileIfNotExist({ pathSrc : './test/indexSrc.html', pathFin : './test/index.html' }, function (err, res) { if (err) return console.log(err); scroungejs.build({ inputPath : [ './test/testbuildSrc', './node_modules', './bttnsys.js' ], outputPath : './test/testbuildFin', isRecursive : true, isSourcePathUnique : true, isCompressed : false, isConcatenated : false, basepage : './test/index.html' }, function (err, res) { return (err) ? console.log(err) : console.log('finished!'); }); });
Java
var Struct = ( function() { return function ( members ) { var mode = "default"; var ctor = function( values ) { if ( mode === "new" ) { mode = "void"; return new Struct(); } if ( mode === "void" ) return; mode = "new"; var instance = Struct(); mode = "default"; extend( instance, members, values || {} ); return instance; }; var Struct = function() { return ctor.apply( undefined, arguments ); }; return Struct; }; function extend( instance, members, values ) { var pending = [{ src: values, tmpl: members, dest: instance }]; while ( pending.length ) { var task = pending.shift(); if ( task.array ) { var i = 0, len = task.array.length; for ( ; i < len; i++ ) { switch ( typeOf( task.array[ i ] ) ) { case "object": var template = task.array[ i ]; task.array[ i ] = {}; pending.push({ tmpl: template, dest: task.array[ i ] }); break; case "array": task.array[ i ] = task.array[ i ].slice( 0 ); pending.push({ array: task.array[ i ] }); break; } } } else { for ( var prop in task.tmpl ) { if ( task.src[ prop ] !== undefined ) task.dest[ prop ] = task.src[ prop ]; else { switch ( typeOf( task.tmpl[ prop ] ) ) { case "object": task.dest[ prop ] = {}; pending.push({ tmpl: task.tmpl[ prop ], dest: task.dest[ prop ] }); break; case "array": task.dest[ prop ] = task.tmpl[ prop ].slice( 0 ); pending.push({ array: task.dest[ prop ] }); break; default: task.dest[ prop ] = task.tmpl[ prop ]; break; } } } } } } } () );
Java
var utils = require('./utils') , request = require('request') ; module.exports = { fetchGithubInfo: function(email, cb) { var githubProfile = {}; var api_call = "https://api.github.com/search/users?q="+email+"%20in:email"; var options = { url: api_call, headers: { 'User-Agent': 'Blogdown' } }; console.log("Calling "+api_call); request(options, function(err, res, body) { if(err) return cb(err); res = JSON.parse(body); if(res.total_count==1) githubProfile = res.items[0]; cb(null, githubProfile); }); }, fetchGravatarProfile: function(email, cb) { var gravatarProfile = {}; var hash = utils.getHash(email); var api_call = "http://en.gravatar.com/"+hash+".json"; console.log("Calling "+api_call); var options = { url: api_call, headers: { 'User-Agent': 'Blogdown' } }; request(options, function(err, res, body) { if(err) return cb(err); try { res = JSON.parse(body); } catch(e) { console.error("fetchGravatarProfile: Couldn't parse response JSON ", body, e); return cb(e); } if(res.entry && res.entry.length > 0) gravatarProfile = res.entry[0]; return cb(null, gravatarProfile); }); } };
Java
// // STShare.h // Loopy // // Created by David Jedeikin on 10/23/13. // Copyright (c) 2013 ShareThis. All rights reserved. // #import "STAPIClient.h" #import <Foundation/Foundation.h> #import <Social/Social.h> @interface STShareActivityUI : NSObject @property (nonatomic, strong) UIViewController *parentController; @property (nonatomic, strong) STAPIClient *apiClient; - (id)initWithParent:(UIViewController *)parent apiClient:(STAPIClient *)client; - (NSArray *)getDefaultActivities:(NSArray *)activityItems; - (UIActivityViewController *)newActivityViewController:(NSArray *)shareItems withActivities:(NSArray *)activities; - (SLComposeViewController *)newActivityShareController:(id)activityObj; - (void)showActivityViewDialog:(UIActivityViewController *)activityController completion:(void (^)(void))completion; - (void)handleShareDidBegin:(NSNotification *)notification; - (void)handleShareDidComplete:(NSNotification *)notification; @end
Java
using Radical.Reflection; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Reflection; namespace Radical.Windows { static class PropertyInfoExtensions { public static string GetDisplayName(this PropertyInfo propertyInfo) { if (propertyInfo != null && propertyInfo.IsAttributeDefined<DisplayAttribute>()) { var a = propertyInfo.GetAttribute<DisplayAttribute>(); return a.GetName(); } if (propertyInfo != null && propertyInfo.IsAttributeDefined<DisplayNameAttribute>()) { var a = propertyInfo.GetAttribute<DisplayNameAttribute>(); return a.DisplayName; } return null; } } }
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SimpleCiphers.Models { public static class ArrayOperations { // Содержится ли text в encAbc. Если да, то возвращаются индексы в encAbc // a b text = 1 // a 1 2 return x = 0, y = 0 // b 3 4 abc[0,0] = aa - расшифрованный // encAbc[0,0] = 1 - зашифрованный public static bool ContainsIn(string text, string[,] encAbc, out int x, out int y) { for (var i = 0; i < encAbc.GetLength(0); i++) { for (var j = 0; j < encAbc.GetLength(1); j++) { if (text != encAbc[i, j]) continue; x = i; y = j; return true; } } x = -1; y = -1; return false; } public static string[,] Turn1DTo2D(string[] encAbc) { var arr = new string[1, encAbc.Length]; for (var i = 0; i < encAbc.Length; i++) { arr[0, i] = $"{encAbc[i]}"; } return arr; } } }
Java
import java.text.NumberFormat; // **************************************************************** // ManageAccounts.java // Use Account class to create and manage Sally and Joe's bank accounts public class ManageAccounts { public static void main(String[] args) { Account acct1, acct2; NumberFormat usMoney = NumberFormat.getCurrencyInstance(); //create account1 for Sally with $1000 acct1 = new Account(1000, "Sally", 1111); //create account2 for Joe with $500 acct2 = new Account(500, "Joe", 1212); //deposit $100 to Joe's account acct2.deposit(100); //print Joe's new balance (use getBalance()) System.out.println("Joe's new balance: " + usMoney.format(acct2.getBalance())); //withdraw $50 from Sally's account acct1.withdraw(50); //print Sally's new balance (use getBalance()) System.out.println("Sally's new balance: " + usMoney.format(acct1.getBalance())); //charge fees to both accounts System.out.println("Sally's new balance after the fee is charged: " + usMoney.format(acct1.chargeFee())); System.out.println("Joe's new balance after the fee is charged: " + usMoney.format(acct2.chargeFee())); //change the name on Joe's account to Joseph acct2.changeName("Joseph"); //print summary for both accounts System.out.println(acct1); System.out.println(acct2); //close and display Sally's account acct1.close(); System.out.println(acct1); //consolidate account test (doesn't work as acct1 Account newAcct = Account.consolidate(acct1, acct2); System.out.println(acct1); } }
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <?php include_http_metas() ?> <?php include_metas() ?> <?php include_title() ?> </head> <body id="body" lang="en"> <?php echo $sf_content ?> </body> </html>
Java
from api_request import Api from util import Util from twocheckout import Twocheckout class Sale(Twocheckout): def __init__(self, dict_): super(self.__class__, self).__init__(dict_) @classmethod def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale @classmethod def list(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/list_sales', params)) return response.sale_summary def refund(self, params=None): if params is None: params = dict() if hasattr(self, 'lineitem_id'): params['lineitem_id'] = self.lineitem_id url = 'sales/refund_lineitem' elif hasattr(self, 'invoice_id'): params['invoice_id'] = self.invoice_id url = 'sales/refund_invoice' else: params['sale_id'] = self.sale_id url = 'sales/refund_invoice' return Sale(Api.call(url, params)) def stop(self, params=None): if params is None: params = dict() if hasattr(self, 'lineitem_id'): params['lineitem_id'] = self.lineitem_id return Api.call('sales/stop_lineitem_recurring', params) elif hasattr(self, 'sale_id'): active_lineitems = Util.active(self) if dict(active_lineitems): result = dict() i = 0 for k, v in active_lineitems.items(): lineitem_id = v params = {'lineitem_id': lineitem_id} result[i] = Api.call('sales/stop_lineitem_recurring', params) i += 1 response = { "response_code": "OK", "response_message": str(len(result)) + " lineitems stopped successfully" } else: response = { "response_code": "NOTICE", "response_message": "No active recurring lineitems" } else: response = { "response_code": "NOTICE", "response_message": "This method can only be called on a sale or lineitem" } return Sale(response) def active(self): active_lineitems = Util.active(self) if dict(active_lineitems): result = dict() i = 0 for k, v in active_lineitems.items(): lineitem_id = v result[i] = lineitem_id i += 1 response = { "response_code": "ACTIVE", "response_message": str(len(result)) + " active recurring lineitems" } else: response = { "response_code": "NOTICE","response_message": "No active recurring lineitems" } return Sale(response) def comment(self, params=None): if params is None: params = dict() params['sale_id'] = self.sale_id return Sale(Api.call('sales/create_comment', params)) def ship(self, params=None): if params is None: params = dict() params['sale_id'] = self.sale_id return Sale(Api.call('sales/mark_shipped', params))
Java
<?php /** * wm.class.php - window manager * * handles window groups and multiple gtkwindow object easily * * This is released under the GPL, see docs/gpl.txt for details * * @author Leon Pegg <leon.pegg@gmail.com> * @author Elizabeth M Smith <emsmith@callicore.net> * @copyright Leon Pegg (c)2006 * @link http://callicore.net/desktop * @license http://www.opensource.org/licenses/gpl-license.php GPL * @version $Id: wm.class.php 64 2006-12-10 18:09:56Z emsmith $ * @since Php 5.1.0 * @package callicore * @subpackage desktop * @category lib * @filesource */ /** * Class for handling multiple GtkWindow objects * * contains all static methods */ class CC_Wm { /** * GtkWindow object array * [string GtkWindow_Name] * array( * GtkWindow - Store GtkWindow object * ) * * @var array */ protected static $windows = array(); /** * GtkWindowGroup - for making grabs work properly (see GtkWidget::grab_add) * * @var object instanceof GtkWindowGroup */ protected static $window_group; /** * public function __construct * * forces only static calls * * @return void */ public function __construct() { throw new CC_Exception('CC_WM contains only static methods and cannot be constructed'); } /** * Adds a GtkWindow object to CC_WM::$windows * * @param object $window instanceof GtkWindow * @return bool */ public static function add_window(GtkWindow $window) { $name = $window->get_name(); if ($name !== '' && !array_key_exists($name, self::$windows)) { if (!is_object(self::$window_group)) { self::$window_group = new GtkWindowGroup(); } self::$window_group->add_window($window); self::$windows[$name] = $window; return true; } return false; } /** * Removes a GtkWindow object from CC_WM::$windows * * @param string $name * @return object instanceof GtkWindow */ public static function remove_window($name) { if ($name !== '' && array_key_exists($name, self::$windows)) { $window = self::$windows[$$name]; unset(self::$windows[$name]); self::$window_group->remove_window($window); return $window; } return false; } /** * Retrives GtkWindow object from CC_WM::$windows * * @param string $name * @return object instanceof GtkWindow */ public static function get_window($name) { if ($name !== '' && array_key_exists($name, self::$windows)) { return self::$windows[$name]; } return false; } /** * Retrives CC_WM::$windows infomation array * Structure: * [int window_id] * array( * name - Name of GtkWindow * class - Name of GtkWindow class * ) * * @return array */ public static function list_windows() { $list = array(); foreach (self::$windows as $name => $class) { $list[] = array('name' => $name, 'class' => $get_class($class)); } return $list; } /** * Shows all windows in the manager */ public static function show_all_windows() { foreach (self::$windows as $window) { $window->show_all(); } } /** * hides all the windows in the manager */ public static function hide_all_windows() { foreach (self::$windows as $window) { $window->hide_all(); } } /** * See if a specific window exists * * @param string $name name of window to check for * @return bool */ public static function is_window($name) { return array_key_exists($name, self::$windows); } /** * public function hide_all * * overrides hide_all for windows manager integration * * @return void */ public function hide_all() { if (class_exists('CC_Wm') && CC_Wm::is_window($this->get_name()) && $this->is_modal) { parent::grab_remove(); $return = parent::hide_all(); $this->is_modal = false; return $return; } else { return parent::hide_all(); } } /** * public function show_all * * overrides show_all for windows manager integration * * @return void */ public function show_all($modal = false) { if (class_exists('CC_Wm') && CC_Wm::is_window($this->get_name())) { $return = parent::show_all(); parent::grab_add(); $this->is_modal = true; return $return; } else { return parent::show_all(); } } }
Java
module.exports = FormButtonsDirective; function FormButtonsDirective () { return { restrict: 'AE', replace: true, scope: { submitClick: '&submitClick', cancelClick: '&cancelClick' }, templateUrl: '/src/utils/views/formButtons.tmpl.html', link: function (scope, elem) { angular.element(elem[0].getElementsByClassName('form-button-submit')).on('click', function () { scope.submitClick(); }); angular.element(elem[0].getElementsByClassName('form-button-cancel')).on('click', function () { scope.cancelClick(); }); } }; }
Java
ActionController::Routing::Routes.draw do |map| map.resources :projects map.resources :priorities map.resources :tasks # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # map.resources :products # Sample resource route with options: # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } # Sample resource route with sub-resources: # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller # Sample resource route with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # Sample resource route within a namespace: # map.namespace :admin do |admin| # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) # admin.resources :products # end # You can have the root of your site routed with map.root -- just remember to delete public/index.html. # map.root :controller => "welcome" # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end
Java
<?php namespace Master\AdvertBundle\Controller; use Elastica\Filter\GeoDistance; use Elastica\Query\Filtered; use Elastica\Query\MatchAll; use Master\AdvertBundle\Document\Advert; use Master\AdvertBundle\Document\Localization; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class DefaultController extends Controller { public function indexAction(Request $request) { $p=1; if($request->query->get('page')!=null) $p=intval($request->query->get('page')); $adverts=$this->advertShow($request,$p); return $this->render('AdvertBundle:Default:index.html.twig',array('advert'=>$adverts)); } public function addAction(Request $request) { if($request->getMethod()=="POST") { $manager=$this->get('doctrine_mongodb'); $localisation=new Localization(); $localisation->setLatitude($request->request->get('lat')); $localisation->setLongitude($request->request->get('long')); $advert = new Advert(); $advert->setTitle($request->request->get('title')); $advert->setDescription($request->request->get('description')); $advert->setFax($request->request->get('fax')); $advert->setTelephone($request->request->get('tel')); $advert->setTokenuser($this->getUser()->getToken()); $advert->setLocalization($localisation); $manager->getManager()->persist($advert); $manager->getManager()->flush(); $adverts=$this->advertShow($request,1); return $this->render('AdvertBundle:Default:index.html.twig',array("advert"=>$adverts)); }else{ return $this->render('AdvertBundle:Advert:add.html.twig'); } } public function testAction(){ $filter = new GeoDistance('location', array('lat' => -2.1741771697998047, 'lon' => 43.28249657890983), '10000km'); $query = new Filtered(new MatchAll(), $filter); $manager=$this->get('fos_elastica.finder.structure.advert'); $test=$manager->find($query); var_dump($test);exit; return new Response("TEST"); } public function advertShow($request,$p) { $manager=$this->get('fos_elastica.finder.structure.advert'); $pagination=$manager->find("",100); // var_dump($pagination);exit; $paginator = $this->get('knp_paginator'); $adverts = $paginator->paginate( $pagination, $request->query->get('page', $p)/*page number*/, 6/*limit per page*/ ); return $adverts; } }
Java
# ASConfigCreator [![Build Status](https://travis-ci.org/Eernie/ASConfigCreator.svg?branch=develop)](https://travis-ci.org/Eernie/ASConfigCreator) [![Coverage Status](https://coveralls.io/repos/Eernie/ASConfigCreator/badge.svg?branch=develop&service=github)](https://coveralls.io/github/Eernie/ASConfigCreator?branch=develop) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/nl.eernie.as/ASConfigCreator/badge.svg)](https://maven-badges.herokuapp.com/maven-central/nl.eernie.as/ASConfigCreator) Sourcecontrol for you application server configuration. ## Builing the source Its as easy as using maven: ```bash mvn install ``` ## Usage There are two ways to use the application, directly or trough the maven plugin. ### Direct For the direct approach you'll have to setup some configuration: ```java Configuration configuration = new Configuration(); configuration.getContexts().addAll(Arrays.asList(contexts)); configuration.getApplicationServers().addAll(applicationServers); configuration.setOutputDirectoryPath(outputDirectory); ASConfigCreator asConfigCreator = new ASConfigCreator(configuration); asConfigCreator.createConfigFiles(masterFile.getAbsolutePath()); ``` ### Maven plugin For the maven plugin you can use the following snippet: ```xml <plugin> <groupId>nl.eernie.as</groupId> <artifactId>ASConfigCreator-maven-plugin</artifactId> <version>[latestVersion]</version> <configuration> <settingsFile>${basedir}/settings.properties</settingsFile> </configuration> </plugin> ```
Java
$context.section('Простое связывание', 'Иерархическое связывание с данными с использованием простых и составных ключей'); //= require data-basic $context.section('Форматирование', 'Механизм одностороннего связывания (one-way-binding)'); //= require data-format $context.section('Настройка', 'Управление изменением виджета при обновлении данных'); //= require data-binding $context.section('Динамическое связывание', 'Управление коллекцией элементов виджета через источник данных'); //= require data-dynamic $context.section('Общие данные'); //= require data-share $context.section('"Грязные" данные', 'Уведомление родительских источников данных о том, что значение изменилось'); //= require data-dirty
Java
/*The MIT License (MIT) Copyright (c) 2016 Muhammad Hammad Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Sogiftware. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ package org.dvare.annotations; import org.dvare.expression.datatype.DataType; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface Type { DataType dataType(); }
Java
import json import os from flask import request, g, render_template, make_response, jsonify, Response from helpers.raw_endpoint import get_id, store_json_to_file from helpers.groups import get_groups from json_controller import JSONController from main import app from pymongo import MongoClient, errors HERE = os.path.dirname(os.path.abspath(__file__)) # setup database connection def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db @app.teardown_appcontext def close_db(error): """Closes connection with Mongo client""" if hasattr(g, 'mongo_client'): g.mongo_client.close() # Begin view routes @app.route('/') @app.route('/index/') def index(): """Landing page for SciNet""" return render_template("index.html") @app.route('/faq/') def faq(): """FAQ page for SciNet""" return render_template("faq.html") @app.route('/leaderboard/') def leaderboard(): """Leaderboard page for SciNet""" get_db() groups = get_groups(g.groups_collection) return render_template("leaderboard.html", groups=groups) @app.route('/ping', methods=['POST']) def ping_endpoint(): """API endpoint determines potential article hash exists in db :return: status code 204 -- hash not present, continue submission :return: status code 201 -- hash already exists, drop submission """ db = get_db() target_hash = request.form.get('hash') if db.raw.find({'hash': target_hash}).count(): return Response(status=201) else: return Response(status=204) @app.route('/articles') def ArticleEndpoint(): """Eventual landing page for searching/retrieving articles""" if request.method == 'GET': return render_template("articles.html") @app.route('/raw', methods=['POST']) def raw_endpoint(): """API endpoint for submitting raw article data :return: status code 405 - invalid JSON or invalid request type :return: status code 400 - unsupported content-type or invalid publisher :return: status code 201 - successful submission """ # Ensure post's content-type is supported if request.headers['content-type'] == 'application/json': # Ensure data is a valid JSON try: user_submission = json.loads(request.data) except ValueError: return Response(status=405) # generate UID for new entry uid = get_id() # store incoming JSON in raw storage file_path = os.path.join( HERE, 'raw_payloads', str(uid) ) store_json_to_file(user_submission, file_path) # hand submission to controller and return Resposne db = get_db() controller_response = JSONController(user_submission, db=db, _id=uid).submit() return controller_response # User submitted an unsupported content-type else: return Response(status=400) #@TODO: Implicit or Explicit group additions? Issue #51 comments on the issues page #@TODO: Add form validation @app.route('/requestnewgroup/', methods=['POST']) def request_new_group(): # Grab submission form data and prepare email message data = request.json msg = "Someone has request that you add {group_name} to the leaderboard \ groups. The groups website is {group_website} and the submitter can \ be reached at {submitter_email}.".format( group_name=data['new_group_name'], group_website=data['new_group_website'], submitter_email=data['submitter_email']) return Response(status=200) ''' try: email( subject="SciNet: A new group has been requested", fro="no-reply@scinet.osf.io", to='harry@scinet.osf.io', msg=msg) return Response(status=200) except: return Response(status=500) ''' # Error handlers @app.errorhandler(404) def not_found(error): return make_response(jsonify( { 'error': 'Page Not Found' } ), 404) @app.errorhandler(405) def method_not_allowed(error): return make_response(jsonify( { 'error': 'Method Not Allowed' } ), 405)
Java
package com.arekusu.datamover.model.jaxb; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.arekusu.com}DefinitionType"/> * &lt;/sequence> * &lt;attribute name="version" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "definitionType" }) @XmlRootElement(name = "ModelType", namespace = "http://www.arekusu.com") public class ModelType { @XmlElement(name = "DefinitionType", namespace = "http://www.arekusu.com", required = true) protected DefinitionType definitionType; @XmlAttribute(name = "version") protected String version; /** * Gets the value of the definitionType property. * * @return * possible object is * {@link DefinitionType } * */ public DefinitionType getDefinitionType() { return definitionType; } /** * Sets the value of the definitionType property. * * @param value * allowed object is * {@link DefinitionType } * */ public void setDefinitionType(DefinitionType value) { this.definitionType = value; } /** * Gets the value of the version property. * * @return * possible object is * {@link String } * */ public String getVersion() { return version; } /** * Sets the value of the version property. * * @param value * allowed object is * {@link String } * */ public void setVersion(String value) { this.version = value; } }
Java
<?php namespace PragmaRX\Sdk\Services\Accounts\Exceptions; use PragmaRX\Sdk\Core\HttpResponseException; class InvalidPassword extends HttpResponseException { protected $message = 'paragraphs.invalid-password'; }
Java
import React from 'react'; import './skills.scss'; export default () => { return ( <section className="skills-section"> <svg className="bigTriangleColor separator-skills" width="100%" height="100" viewBox="0 0 100 102" preserveAspectRatio="none"> <path d="M0 0 L0 100 L70 0 L100 100 L100 0 Z" /> </svg> <h2 className="skills-header">Skills</h2> <p className="skills tlt"> Javascript/ES6 React Redux Node Express MongoDB GraphQL REST Next.js Mocha Jest JSS PostCSS SCSS LESS AWS nginx jQuery Webpack Rollup UI/Design </p> <button className="button button--wayra button--inverted skills-btn"> View My <i className="fa fa-github skills-github"></i><a className="skills-btn-a" href="https://www.github.com/musicbender" target="_blank"></a> </button> </section> ); }
Java
import axios from 'axios'; export default axios.create({ baseURL: 'http://localhost:9000/v1/' });
Java
/* * THIS FILE IS AUTO GENERATED FROM 'lib/lex/lexer.kep' * DO NOT EDIT */ define(["require", "exports", "bennu/parse", "bennu/lang", "nu-stream/stream", "ecma-ast/token", "ecma-ast/position", "./boolean_lexer", "./comment_lexer", "./identifier_lexer", "./line_terminator_lexer", "./null_lexer", "./number_lexer", "./punctuator_lexer", "./reserved_word_lexer", "./string_lexer", "./whitespace_lexer", "./regular_expression_lexer" ], (function(require, exports, parse, __o, __o0, lexToken, __o1, __o2, comment_lexer, __o3, line_terminator_lexer, __o4, __o5, __o6, __o7, __o8, whitespace_lexer, __o9) { "use strict"; var lexer, lexStream, lex, always = parse["always"], attempt = parse["attempt"], binds = parse["binds"], choice = parse["choice"], eof = parse["eof"], getPosition = parse["getPosition"], modifyState = parse["modifyState"], getState = parse["getState"], enumeration = parse["enumeration"], next = parse["next"], many = parse["many"], runState = parse["runState"], never = parse["never"], ParserState = parse["ParserState"], then = __o["then"], streamFrom = __o0["from"], SourceLocation = __o1["SourceLocation"], SourcePosition = __o1["SourcePosition"], booleanLiteral = __o2["booleanLiteral"], identifier = __o3["identifier"], nullLiteral = __o4["nullLiteral"], numericLiteral = __o5["numericLiteral"], punctuator = __o6["punctuator"], reservedWord = __o7["reservedWord"], stringLiteral = __o8["stringLiteral"], regularExpressionLiteral = __o9["regularExpressionLiteral"], type, type0, type1, type2, type3, p, type4, type5, type6, type7, p0, type8, p1, type9, p2, consume = ( function(tok, self) { switch (tok.type) { case "Comment": case "Whitespace": case "LineTerminator": return self; default: return tok; } }), isRegExpCtx = (function(prev) { if ((!prev)) return true; switch (prev.type) { case "Keyword": case "Punctuator": return true; } return false; }), enterRegExpCtx = getState.chain((function(prev) { return (isRegExpCtx(prev) ? always() : never()); })), literal = choice(((type = lexToken.StringToken.create), stringLiteral.map((function(x) { return [type, x]; }))), ((type0 = lexToken.BooleanToken.create), booleanLiteral.map((function(x) { return [type0, x]; }))), ((type1 = lexToken.NullToken.create), nullLiteral.map((function(x) { return [type1, x]; }))), ((type2 = lexToken.NumberToken.create), numericLiteral.map((function(x) { return [type2, x]; }))), ((type3 = lexToken.RegularExpressionToken.create), (p = next(enterRegExpCtx, regularExpressionLiteral)), p.map((function(x) { return [type3, x]; })))), token = choice(attempt(((type4 = lexToken.IdentifierToken), identifier.map((function(x) { return [type4, x]; })))), literal, ((type5 = lexToken.KeywordToken), reservedWord.map((function(x) { return [type5, x]; }))), ((type6 = lexToken.PunctuatorToken), punctuator.map((function(x) { return [type6, x]; })))), inputElement = choice(((type7 = lexToken.CommentToken), (p0 = comment_lexer.comment), p0.map((function( x) { return [type7, x]; }))), ((type8 = lexToken.WhitespaceToken), (p1 = whitespace_lexer.whitespace), p1.map((function(x) { return [type8, x]; }))), ((type9 = lexToken.LineTerminatorToken), (p2 = line_terminator_lexer.lineTerminator), p2.map( (function(x) { return [type9, x]; }))), token); (lexer = then(many(binds(enumeration(getPosition, inputElement, getPosition), (function(start, __o10, end) { var type10 = __o10[0], value = __o10[1]; return always(new(type10)(new(SourceLocation)(start, end, (start.file || end.file)), value)); })) .chain((function(tok) { return next(modifyState(consume.bind(null, tok)), always(tok)); }))), eof)); (lexStream = (function(s, file) { return runState(lexer, new(ParserState)(s, new(SourcePosition)(1, 0, file), null)); })); var y = lexStream; (lex = (function(z) { return y(streamFrom(z)); })); (exports["lexer"] = lexer); (exports["lexStream"] = lexStream); (exports["lex"] = lex); }));
Java
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using IdentityServer3.Core.Events; using IdentityServer3.ElasticSearchEventService.Extensions; using IdentityServer3.ElasticSearchEventService.Mapping; using IdentityServer3.ElasticSearchEventService.Mapping.Configuration; using Serilog.Events; using Unittests.Extensions; using Unittests.Proofs; using Unittests.TestData; using Xunit; namespace Unittests { public class DefaultLogEventMapperTests { [Fact] public void SpecifiedProperties_AreMapped() { var mapper = CreateMapper(b => b .DetailMaps(c => c .For<TestDetails>(m => m .Map(d => d.String) ) )); var details = new TestDetails { String = "Polse" }; var logEvent = mapper.Map(CreateEvent(details)); logEvent.Properties.DoesContain(LogEventValueWith("Details.String", Quote("Polse"))); } [Fact] public void AlwaysAddedValues_AreAlwaysAdded() { var mapper = CreateMapper(b => b.AlwaysAdd("some", "value")); var logEvent = mapper.Map(CreateEvent(new object())); logEvent.Properties.DoesContain(LogEventValueWith("some", Quote("value"))); } [Fact] public void MapToSpecifiedName_MapsToSpecifiedName() { var mapper = CreateMapper(b => b .DetailMaps(m => m .For<TestDetails>(o => o .Map("specificName", d => d.String) ) )); var logEvent = mapper.Map(CreateEvent(new TestDetails {String = Some.String})); logEvent.Properties.DoesContain(LogEventValueWith("Details.specificName", Quote(Some.String))); } [Fact] public void PropertiesThatThrowsException_AreMappedAsException() { var mapper = CreateMapper(b => b .DetailMaps(m => m .For<TestDetails>(o => o .Map(d => d.ThrowsException) ) )); var logEvent = mapper.Map(CreateEvent(new TestDetails())); logEvent.Properties.DoesContain(LogEventValueWith("Details.ThrowsException", s => s.StartsWith("\"threw"))); } [Fact] public void DefaultMapAllMembers_MapsAllPropertiesAndFieldsForDetails() { var mapper = CreateMapper(b => b .DetailMaps(m => m .DefaultMapAllMembers() )); var logEvent = mapper.Map(CreateEvent(new TestDetails())); var members = typeof (TestDetails).GetPublicPropertiesAndFields().Select(m => string.Format("Details.{0}", m.Name)); logEvent.Properties.DoesContainKeys(members); } [Fact] public void ComplexMembers_AreMappedToJson() { var mapper = CreateMapper(b => b .DetailMaps(m => m .DefaultMapAllMembers() )); var details = new TestDetails(); var logEvent = mapper.Map(CreateEvent(details)); var logProperty = logEvent.GetProperty<ScalarValue>("Details.Inner"); logProperty.Value.IsEqualTo(details.Inner.ToJsonSuppressErrors()); } private static string Quote(string value) { return string.Format("\"{0}\"", value); } private static Expression<Func<KeyValuePair<string, LogEventPropertyValue>, bool>> LogEventValueWith(string key, Func<string,bool> satisfies) { return p => p.Key == key && satisfies(p.Value.ToString()); } private static Expression<Func<KeyValuePair<string, LogEventPropertyValue>, bool>> LogEventValueWith(string key, string value) { return p => p.Key == key && p.Value.ToString() == value; } private static Event<T> CreateEvent<T>(T details) { return new Event<T>("category", "name", EventTypes.Information, 42, details); } private static DefaultLogEventMapper CreateMapper(Action<MappingConfigurationBuilder> setup) { var builder = new MappingConfigurationBuilder(); setup(builder); return new DefaultLogEventMapper(builder.GetConfiguration()); } } }
Java
<h1><?=$title?></h1> <h5>Ordered by Points</h5> <?php foreach ($users as $user) : ?> <div class="mini-profile left"> <img class="gravatar left" src="<?= $this->mzHelpers->get_gravatar($user->email, 128); ?>" alt=""> <div class="info"> <a href="<?= $this->url->create('users/id/' . $user->id ); ?>"><?= $user->username ?></a> <br> Points: <?= $user->points ?> </div> </div> <?php endforeach; ?>
Java
// Multiprocessor support // mist32 is not supported multiprocessor #include "types.h" #include "defs.h" #include "param.h" #include "memlayout.h" #include "mmu.h" #include "proc.h" struct cpu cpus[NCPU]; int ismp; int ncpu; void mpinit(void) { ismp = 0; ncpu = 1; lapic = 0; cpus[ncpu].id = ncpu; ncpu++; return; }
Java
#include <stdio.h> #include "cgm_play.h" #include "cgm_list.h" #ifndef _CGM_TYPES_H_ #define _CGM_TYPES_H_ #ifdef __cplusplus extern "C" { #endif typedef int(*CGM_FUNC)(tCGM* cgm); typedef struct { double xmin; double xmax; double ymin; double ymax; } tLimit; typedef struct { unsigned long red; unsigned long green; unsigned long blue; } tRGB; typedef union { unsigned long index; tRGB rgb; } tColor; typedef struct { char *data; int size; /* allocated size */ int len; /* used size */ int bc; /* byte count */ int pc; /* pixel count */ } tData; typedef struct { const char *name; CGM_FUNC func; } tCommand; typedef struct { long index; long type; long linecap; long dashcap; /* unused */ long linejoin; double width; tColor color; } tLineAtt; typedef struct { long index; long type; long linecap; long dashcap; /* unused */ long linejoin; double width; tColor color; short visibility; } tEdgeAtt; typedef struct { long index; long type; double size; tColor color; } tMarkerAtt; typedef struct { long index; long font_index; tList *font_list; short prec; /* unused */ double exp_fact; double char_spacing; /* unused */ tColor color; double height; cgmPoint char_up; /* unused */ cgmPoint char_base; short path; long restr_type; /* unused */ struct { short hor; short ver; double cont_hor; /* unused */ double cont_ver; /* unused */ } alignment; } tTextAtt; typedef struct { long index; short int_style; tColor color; long hatch_index; long pat_index; tList *pat_list; cgmPoint ref_pt; /* unused */ struct { cgmPoint height; /* unused */ cgmPoint width; /* unused */ } pat_size; /* unused */ } tFillAtt; typedef struct { long index; long nx, ny; tColor *pattern; } tPatTable; typedef struct { short type; short value; } tASF; struct _tCGM { FILE *fp; int file_size; tData buff; union { long b_prec; /* 0=8, 1=16, 2=24, 3=32 */ struct { long minint; long maxint; } t_prec ; } int_prec; union { long b_prec; /* 0=float*32, 1=float*64(double), 2=fixed*32, 3=fixed*64 */ struct { double minreal; double maxreal; long digits; } t_prec; } real_prec; union { long b_prec; /* 0=8, 1=16, 2=24, 3=32 */ struct { long minint; long maxint; } t_prec; } ix_prec; long cd_prec; /* used only for binary */ long cix_prec; /* used only for binary */ struct { tRGB black; tRGB white; } color_ext; long max_cix; tRGB* color_table; struct { short mode; /* abstract (pixels, factor is always 1), metric (coordinate * factor = coordinate_mm) */ double factor; } scale_mode; short color_mode; /* indexed, direct */ short linewidth_mode; /* absolute, scaled, fractional, mm */ short markersize_mode; /* absolute, scaled, fractional, mm */ short edgewidth_mode; /* absolute, scaled, fractional, mm */ short interiorstyle_mode; /* absolute, scaled, fractional, mm (unused) */ short vdc_type; /* integer, real */ union { long b_prec; /* 0=8, 1=16, 2=24, 3=32 */ struct { long minint; long maxint; } t_prec; } vdc_int; union { long b_prec; /* 0=float*32, 1=float*64(double), 2=fixed*32, 3=fixed*64 */ struct { double minreal; double maxreal; long digits; } t_prec; } vdc_real; struct { cgmPoint first; /* lower-left corner */ cgmPoint second; /* upper-right corner */ cgmPoint maxFirst; /* maximum lower-left corner */ cgmPoint maxSecond; /* maximum upper-right corner */ short has_max; } vdc_ext; tRGB back_color; tColor aux_color; short transparency; short cell_transp; /* (affects cellarray and pattern) unused */ tColor cell_color; /* unused */ struct { cgmPoint first; cgmPoint second; } clip_rect; short clip_ind; long region_idx; /* unused */ long region_ind; /* unused */ long gdp_sample_type, gdp_n_samples; cgmPoint gdp_pt[4]; char* gdp_data_rec; double mitrelimit; /* unused */ tLineAtt line_att; tMarkerAtt marker_att; tTextAtt text_att; tFillAtt fill_att; tEdgeAtt edge_att; tList* asf_list; /* unused */ cgmPoint* point_list; int point_list_n; cgmPlayFuncs dof; void* userdata; }; #define CGM_CONT 3 enum { CGM_OFF, CGM_ON }; enum { CGM_INTEGER, CGM_REAL }; enum { CGM_STRING, CGM_CHAR, CGM_STROKE }; enum { CGM_ABSOLUTE, CGM_SCALED, CGM_FRACTIONAL, CGM_MM }; enum { CGM_ABSTRACT, CGM_METRIC }; enum { CGM_INDEXED, CGM_DIRECT }; enum { CGM_HOLLOW, CGM_SOLID, CGM_PATTERN, CGM_HATCH, CGM_EMPTY, CGM_GEOPAT, CGM_INTERP }; enum { CGM_INVISIBLE, CGM_VISIBLE, CGM_CLOSE_INVISIBLE, CGM_CLOSE_VISIBLE }; enum { CGM_PATH_RIGHT, CGM_PATH_LEFT, CGM_PATH_UP, CGM_PATH_DOWN }; int cgm_bin_rch(tCGM* cgm); int cgm_txt_rch(tCGM* cgm); void cgm_strupper(char *s); void cgm_calc_arc_3p(cgmPoint start, cgmPoint intermediate, cgmPoint end, cgmPoint *center, double *radius, double *angle1, double *angle2); void cgm_calc_arc(cgmPoint start, cgmPoint end, double *angle1, double *angle2); void cgm_calc_arc_rev(cgmPoint start, cgmPoint end, double *angle1, double *angle2); void cgm_calc_ellipse(cgmPoint center, cgmPoint first, cgmPoint second, cgmPoint start, cgmPoint end, double *angle1, double *angle2); cgmRGB cgm_getcolor(tCGM* cgm, tColor color); cgmRGB cgm_getrgb(tCGM* cgm, tRGB rgb); void cgm_getcolor_ar(tCGM* cgm, tColor color, unsigned char *r, unsigned char *g, unsigned char *b); void cgm_setmarker_attrib(tCGM* cgm); void cgm_setline_attrib(tCGM* cgm); void cgm_setedge_attrib(tCGM* cgm); void cgm_setfill_attrib(tCGM* cgm); void cgm_settext_attrib(tCGM* cgm); int cgm_inccounter(tCGM* cgm); void cgm_polygonset(tCGM* cgm, int np, cgmPoint* pt, short* flags); void cgm_generalizeddrawingprimitive(tCGM* cgm, int id, int np, cgmPoint* pt, const char* data_rec); void cgm_sism5(tCGM* cgm, const char *data_rec); #ifdef __cplusplus } #endif #endif
Java
require 'spec_helper' require 'serializables/vector3' describe Moon::Vector3 do context 'Serialization' do it 'serializes' do src = described_class.new(12, 8, 4) result = described_class.load(src.export) expect(result).to eq(src) end end end
Java
package org.liquidizer.snippet import scala.xml._ import scala.xml.parsing._ import net.liftweb.util._ import net.liftweb.http._ import net.liftweb.http.js._ import net.liftweb.http.js.JsCmds._ import net.liftweb.common._ import org.liquidizer.model._ object Markup { val URL1= "(https?:/[^\\s\"]*[^\\s!?&.<>])" val URL2= "\\["+URL1+" ([^]]*)\\]" val URL_R= (URL1+"|"+URL2).r def renderComment(in : String) : NodeSeq = { if (in==null || in.length==0) NodeSeq.Empty else toXHTML(in) } def toXHTML(input : String) : NodeSeq = { try { val src= scala.io.Source.fromString("<span>"+input+"</span>") tidy(XhtmlParser(src).first.child, false) } catch { case e:FatalError => <p>{input}</p> } } def tidy(seq : NodeSeq, isLink : Boolean) : NodeSeq = seq.flatMap { tidy(_, isLink) } def tidy(node : Node, isLink : Boolean) : NodeSeq = node match { case Elem(ns, tag, attr, scope, ch @ _*) => tag match { case "img" | "em" | "i" => val allowed= Set("src", "width", "height") val fAttr= attr.filter { n=> allowed.contains(n.key) } Elem(ns, tag, fAttr, scope, tidy(ch, true) :_*) case _ => Text(node.toString) } case Text(text) if !isLink => renderBlock(text.split("\n").toList) case _ => Text(node.toString) } def renderBlock(in : List[String]) : List[Node] = { def tail= renderBlock(in.tail) in match { case Nil => Nil case List(line, _*) if line.matches(" *[*-] .*") => { val li = <li>{ renderLine(line.replaceAll("^ *[*-]","")) }</li> tail match { case <ul>{ c @ _* }</ul> :: t => <ul>{ li ++ c }</ul> :: t case t => <ul>{ li }</ul> :: t } } case List(line, _*) => <p>{ renderLine(line) }</p> :: tail } } def renderLine(in : String) = renderHeader(in, x=>x, x=>x) def renderTagList(in:List[String]) : Node = { <span class="keys">{ var isFirst= true in.map { key => val suff= if (isFirst) NodeSeq.Empty else Text(", ") isFirst= false suff ++ <a class="tag" href={Helpers.appendParams("/queries.html",("search",key) :: Nil)}>{key}</a> }}</span> } def renderHeader(in : String, link : String) : NodeSeq = renderHeader(in, { node => <a href={link}>{node}</a> }) def renderHeader(in : String, link : Node=>Node) : NodeSeq = { var c=0 renderHeader(in, link, x=> {c=c+1; "["+c+"]"}) } /** render a header replacing links with a generic short cut */ def renderHeader(in : String, link : Node=>Node, short : String=>String) : NodeSeq = { URL_R.findFirstMatchIn(in) match { case Some(m) => link(Text(m.before.toString)) ++ { if (m.group(1)==null) { eLink(m.group(2), "["+m.group(3)+"]") } else { eLink(m.matched, short(m.matched)) } } ++ renderHeader(m.after.toString, link, short) case _ => link(Text(in)) } } /** make an external link */ def eLink(url : String, display : String) = <a href={url} title={url} target="_blank" class="extern">{display}</a> } class CategoryView(val keys : List[String], rootLink:String) { def this(keyStr : String, rootLink : String) = this(keyStr.toLowerCase.split(",| ").distinct.toList, rootLink) def isActive(tag : String) = keys.contains(tag.toLowerCase) def link(node : Node, keys : List[String]) = { val sort= S.param("sort").map { v => List(("sort", v)) }.getOrElse(Nil) val uri= Helpers.appendParams(rootLink, ("search" -> keys.mkString(" ")) :: sort) <a href={uri}>{node}</a> } def getStyle(isactive : Boolean) = if (isactive) "active" else "inactive" def getKeysWith(tag : String) = tag :: keys def getKeysWithout(tag : String) = keys.filter{ _ != tag.toLowerCase } def renderTag(tag : String) : Node = { if (isActive(tag)) { link(<div class={getStyle(true)}>{tag}</div>, getKeysWithout(tag)) } else { link(<div class={getStyle(false)}>{tag}</div>, getKeysWith(tag)) } } def renderTagList(in:List[String]) : NodeSeq = { renderTagList(in, in.size+1) } def renderTagList(in : List[String], len : Int) : NodeSeq = { renderTagList(in, len, "tagList") } def renderTagList(in : List[String], len : Int, id: String) : NodeSeq = { <span>{in.slice(0, len).map { tag => renderTag(tag) }}</span> <span id={id}>{ if (len < in.size) SHtml.a(() => SetHtml(id, renderTagList(in.drop(len).toList, len, id+"x")), <div class="inactive">...</div>) else NodeSeq.Empty }</span> } } /** The Localizer provides localization for Text nodes * and attributes starting with $ */ object Localizer { def loc(in : NodeSeq) : NodeSeq = in.flatMap(loc(_)) def loc(in : Node) : NodeSeq = in match { case Text(str) if (str.startsWith("$")) => Text(loc(str)) case _ => in } def loc(in : String) = if (in.startsWith("$")) S.?(in.substring(1)) else in /** localize a number of attributes */ def loc(attr : MetaData) : MetaData = if (attr==Null) Null else attr match { case UnprefixedAttribute(key, value, next) => new UnprefixedAttribute(key, loc(value.text), loc(next)) case _ => throw new Exception("Unknown attribute type : "+attr) } } /** Create menu item elements with links and automatic styles */ class MenuMarker extends InRoom { val user= User.currentUser.map { _.id.is }.getOrElse(0L) var isFirst= true def toUrl(url : Option[Seq[Node]]) = uri(url.map { _.text }.getOrElse(S.uri)) def bind(in :NodeSeq) : NodeSeq = in.flatMap(bind(_)) def bind(in :Node) : NodeSeq = { in match { case Elem("menu", "a", attribs, scope, children @ _*) => // determine target and current link var href= toUrl(attribs.get("href")) var active= if (href.startsWith("/")) S.uri.replaceAll("^/room/[^/]*","") == href.replaceAll("^/room/[^/]+","") else S.uri.replaceAll(".*/","") == href // set up parameters attribs.get("action").foreach { action => val value= attribs.get("value").get.text val field= action.text // set the default order if action is sorting if (isFirst && field=="sort") S.set("defaultOrder", value) // Link leads to the currently viewed page active &&= S.param(field).map { value == _ }.getOrElse(isFirst) val search= S.param("search").map { v => List(("search",v))}.getOrElse(Nil) href = Helpers.appendParams(href, (field, value) :: search) isFirst= false } // make menu entry val entry= attribs.get("icon").map { url => <img src={"/images/menu/"+url.text+".png"} alt="" class="menu"/> }.getOrElse(NodeSeq.Empty) ++ Localizer.loc(children) // format link as either active (currently visited) or inaktive val style= if (active) "active" else "inactive" val title= attribs.get("title").map( Localizer.loc(_) ) <li><a href={href} title={title} alt={title}><div class={style}>{entry}</div></a></li> case Elem("local", "a", attribs, scope, children @ _*) => // keep a number of current request attributes in the target url val keep= attribs.get("keep").map{_.text}.getOrElse("") val para= S.param(keep).map { v => List((keep,v))}.getOrElse(Nil) val url= Helpers.appendParams(toUrl(attribs.get("href")), para ) val title= attribs.get("title").map( Localizer.loc(_) ) <a href={url} alt={title} title={title}>{ children }</a> case Elem(prefix, label, attribs, scope, children @ _*) => Elem(prefix, label, Localizer.loc(attribs), scope, bind(children) : _*) case _ => in } } def render(in : NodeSeq) : NodeSeq = { bind(in) } }
Java
<?php /* SQL Laboratory - Web based MySQL administration http://projects.deepcode.net/sqllaboratory/ types.php - list of data types MIT-style license 2008 Calvin Lough <http://calv.in>, 2010 Steve Gricci <http://deepcode.net> */ $typeList[] = "varchar"; $typeList[] = "char"; $typeList[] = "text"; $typeList[] = "tinytext"; $typeList[] = "mediumtext"; $typeList[] = "longtext"; $typeList[] = "tinyint"; $typeList[] = "smallint"; $typeList[] = "mediumint"; $typeList[] = "int"; $typeList[] = "bigint"; $typeList[] = "real"; $typeList[] = "double"; $typeList[] = "float"; $typeList[] = "decimal"; $typeList[] = "numeric"; $typeList[] = "date"; $typeList[] = "time"; $typeList[] = "datetime"; $typeList[] = "timestamp"; $typeList[] = "tinyblob"; $typeList[] = "blob"; $typeList[] = "mediumblob"; $typeList[] = "longblob"; $typeList[] = "binary"; $typeList[] = "varbinary"; $typeList[] = "bit"; $typeList[] = "enum"; $typeList[] = "set"; $textDTs[] = "text"; $textDTs[] = "mediumtext"; $textDTs[] = "longtext"; $numericDTs[] = "tinyint"; $numericDTs[] = "smallint"; $numericDTs[] = "mediumint"; $numericDTs[] = "int"; $numericDTs[] = "bigint"; $numericDTs[] = "real"; $numericDTs[] = "double"; $numericDTs[] = "float"; $numericDTs[] = "decimal"; $numericDTs[] = "numeric"; $binaryDTs[] = "tinyblob"; $binaryDTs[] = "blob"; $binaryDTs[] = "mediumblob"; $binaryDTs[] = "longblob"; $binaryDTs[] = "binary"; $binaryDTs[] = "varbinary"; $sqliteTypeList[] = "varchar"; $sqliteTypeList[] = "integer"; $sqliteTypeList[] = "float"; $sqliteTypeList[] = "varchar"; $sqliteTypeList[] = "nvarchar"; $sqliteTypeList[] = "text"; $sqliteTypeList[] = "boolean"; $sqliteTypeList[] = "clob"; $sqliteTypeList[] = "blob"; $sqliteTypeList[] = "timestamp"; $sqliteTypeList[] = "numeric"; ?>
Java
body { font-family: helvetica, arial, sans-serif; font-size: 24px; line-height: 36px; background: url("3264857348_0cfd8d7e4f_b-lowquality.jpg"); background-position: top center; background-size: cover; background-repeat: none; overflow: hidden; } * { box-sizing: border-box; -moz-box-sizing: border-box; margin: 0; padding: 0; color: #303030; } h1 { height: 25px; width: 640px; position: absolute; top: 50%; left: 50%; margin-left: -322px; margin-top: -290px; font-size: 32px; letter-spacing: -1px; text-shadow: rgba(255, 255, 255, 0.6) 0 0 8px; z-index: 1; } section { display: none; } .bespoke-parent { position: absolute; top: 0; bottom: 0; left: 0; right: 0; } .bespoke-slide { width: 640px; height: 480px; position: absolute; top: 50%; margin-top: -240px; left: 50%; margin-left: -320px; } section.bespoke-slide { -webkit-transition: all .3s ease; -moz-transition: all .3s ease; -ms-transition: all .3s ease; -o-transition: all .3s ease; transition: all .3s ease; display: block; border-radius: 0.5em; padding: 1em; background: -moz-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.40) 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(255, 255, 255, 1)), color-stop(100%, rgba(255, 255, 255, 0.40))); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.40) 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.40) 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.40) 100%); /* IE10+ */ background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.40) 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#40ffffff', GradientType=0); /* IE6-9 */ } .bespoke-inactive { opacity: 0; top: 100%; } .bespoke-active { opacity: 1; } .bespoke-slide aside { display: none; }
Java
#if false using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LionFire.Behaviors { public class Coroutine { } } #endif
Java
package SOLID.Exercise.Logger.model.appenders; import SOLID.Exercise.Logger.api.File; import SOLID.Exercise.Logger.api.Layout; import SOLID.Exercise.Logger.model.files.LogFile; public class FileAppender extends BaseAppender { private File file; public FileAppender(Layout layout) { super(layout); this.setFile(new LogFile()); } public void setFile(File file) { this.file = file; } @Override public void append(String message) { this.file.write(message); } @Override public String toString() { return String.format("%s, File size: %d", super.toString(), this.file.getSize()); } }
Java
/* global describe, it, require */ 'use strict'; // MODULES // var // Expectation library: chai = require( 'chai' ), // Deep close to: deepCloseTo = require( './utils/deepcloseto.js' ), // Module to be tested: log10 = require( './../lib/array.js' ); // VARIABLES // var expect = chai.expect, assert = chai.assert; // TESTS // describe( 'array log10', function tests() { it( 'should export a function', function test() { expect( log10 ).to.be.a( 'function' ); }); it( 'should compute the base-10 logarithm', function test() { var data, actual, expected; data = [ Math.pow( 10, 4 ), Math.pow( 10, 6 ), Math.pow( 10, 9 ), Math.pow( 10, 15 ), Math.pow( 10, 10 ), Math.pow( 10, 25 ) ]; actual = new Array( data.length ); actual = log10( actual, data ); expected = [ 4, 6, 9, 15, 10, 25 ]; assert.isTrue( deepCloseTo( actual, expected, 1e-7 ) ); }); it( 'should return an empty array if provided an empty array', function test() { assert.deepEqual( log10( [], [] ), [] ); }); it( 'should handle non-numeric values by setting the element to NaN', function test() { var data, actual, expected; data = [ true, null, [], {} ]; actual = new Array( data.length ); actual = log10( actual, data ); expected = [ NaN, NaN, NaN, NaN ]; assert.deepEqual( actual, expected ); }); });
Java
match x: | it?(): true
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>circuits: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.5.0~camlp4 / circuits - 8.10.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> circuits <small> 8.10.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2021-12-23 07:49:00 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-12-23 07:49:00 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp4 4.03+1 Camlp4 is a system for writing extensible parsers for programming languages conf-findutils 1 Virtual package relying on findutils conf-which 1 Virtual package relying on which coq 8.5.0~camlp4 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.03.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.03.0 Official 4.03.0 release ocaml-config 1 OCaml Switch Configuration ocamlbuild 0.14.0 OCamlbuild is a build system with builtin rules to easily build most OCaml projects. # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/circuits&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Circuits&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.10&quot; &amp; &lt; &quot;8.11~&quot;} ] tags: [ &quot;keyword: hardware verification&quot; &quot;category: Computer Science/Architecture&quot; ] authors: [ &quot;Laurent Arditi&quot; ] bug-reports: &quot;https://github.com/coq-contribs/circuits/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/circuits.git&quot; synopsis: &quot;Some proofs of hardware (adder, multiplier, memory block instruction)&quot; description: &quot;&quot;&quot; definition and proof of a combinatorial adder, a sequential multiplier, a memory block instruction&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/circuits/archive/v8.10.0.tar.gz&quot; checksum: &quot;md5=791bf534085120bc18d58db26e1123f4&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-circuits.8.10.0 coq.8.5.0~camlp4</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.5.0~camlp4). The following dependencies couldn&#39;t be met: - coq-circuits -&gt; coq &gt;= 8.10 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-circuits.8.10.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>zchinese: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.7.1+1 / zchinese - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> zchinese <small> 8.9.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-02-15 19:37:57 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-15 19:37:57 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.7.1+1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.06.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.06.1 Official 4.06.1 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/zchinese&quot; license: &quot;Unknown&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/ZChinese&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: number theory&quot; &quot;keyword: chinese remainder&quot; &quot;keyword: primality&quot; &quot;keyword: prime numbers&quot; &quot;category: Mathematics/Arithmetic and Number Theory/Number theory&quot; &quot;category: Miscellaneous/Extracted Programs/Arithmetic&quot; ] authors: [ &quot;Valérie Ménissier-Morain&quot; ] bug-reports: &quot;https://github.com/coq-contribs/zchinese/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/zchinese.git&quot; synopsis: &quot;A proof of the Chinese Remainder Lemma&quot; description: &quot;&quot;&quot; This is a rewriting of the contribution chinese-lemma using Zarith&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/zchinese/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=a5fddf5409ff7b7053a84bbf9491b8fc&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-zchinese.8.9.0 coq.8.7.1+1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+1). The following dependencies couldn&#39;t be met: - coq-zchinese -&gt; coq &gt;= 8.9 Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-zchinese.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
Java
import {Component} from 'react' export class Greeter { constructor (message) { this.greeting = message; } greetFrom (...names) { let suffix = names.reduce((s, n) => s + ", " + n.toUpperCase()); return "Hello, " + this.greeting + " from " + suffix; } greetNTimes ({name, times}) { let greeting = this.greetFrom(name); for (let i = 0; i < times; i++) { console.log(greeting) } } } new Greeter("foo").greetNTimes({name: "Webstorm", times: 3}) function foo (x, y, z) { var i = 0; var x = {0: "zero", 1: "one"}; var a = [0, 1, 2]; var foo = function () { } var asyncFoo = async (x, y, z) => { } var v = x.map(s => s.length); if (!i > 10) { for (var j = 0; j < 10; j++) { switch (j) { case 0: value = "zero"; break; case 1: value = "one"; break; } var c = j > 5 ? "GT 5" : "LE 5"; } } else { var j = 0; try { while (j < 10) { if (i == j || j > 5) { a[j] = i + j * 12; } i = (j << 2) & 4; j++; } do { j--; } while (j > 0) } catch (e) { alert("Failure: " + e.message); } finally { reset(a, i); } } }
Java
<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>jsGrid - Data Manipulation</title> <link rel="stylesheet" type="text/css" href="demos.css" /> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300,600,400' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="../css/jsgrid.css" /> <link rel="stylesheet" type="text/css" href="../css/theme.css" /> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/cupertino/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script> <script src="db.js"></script> <script src="../src/jsgrid.core.js"></script> <script src="../src/jsgrid.load-indicator.js"></script> <script src="../src/jsgrid.load-strategies.js"></script> <script src="../src/jsgrid.sort-strategies.js"></script> <script src="../src/jsgrid.field.js"></script> <script src="../src/jsgrid.field.text.js"></script> <script src="../src/jsgrid.field.number.js"></script> <script src="../src/jsgrid.field.select.js"></script> <script src="../src/jsgrid.field.checkbox.js"></script> <script src="../src/jsgrid.field.control.js"></script> <style> .details-form-field input, .details-form-field select { width: 250px; float: right; } .details-form-field { margin: 15px 0; } .ui-widget *, .ui-widget input, .ui-widget select, .ui-widget button { font-family: 'Helvetica Neue Light', 'Open Sans', Helvetica; font-size: 14px; font-weight: 300 !important; } </style> </head> <body> <h1>Data Manipulation</h1> <div id="jsGrid"></div> <div id="detailsForm"> <div class="details-form-field"> <label>Name: <input id="name" type="text" /></label> </div> <div class="details-form-field"> <label>Age: <input id="age" type="number" /></label> </div> <div class="details-form-field"> <label>Address: <input id="address" type="text" /></label> </div> <div class="details-form-field"> <label>Country: <select id="country"> <option value="0">(Select)</option> <option value="1">United States</option> <option value="2">Canada</option> <option value="3">United Kingdom</option> <option value="4">France</option> <option value="5">Brazil</option> <option value="6">China</option> <option value="7">Russia</option> </select> </label> </div> <div class="details-form-field"> <label>Is Married: <input id="married" type="checkbox" /></label> </div> <div class="details-form-field"> <button type="button" id="save">Save</button> </div> </div> <script> $(function() { $("#jsGrid").jsGrid({ height: "70%", width: "100%", editing: true, autoload: true, paging: true, deleteConfirm: function(item) { return "The client \"" + item.Name + "\" will be removed. Are you sure?"; }, rowClick: function(args) { showDetailsDialog("Edit", args.item); }, controller: db, fields: [ { name: "Name", type: "text", width: 150 }, { name: "Age", type: "number", width: 50 }, { name: "Address", type: "text", width: 200 }, { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control", modeSwitchButton: false, editButton: false, headerTemplate: function() { return $("<button>").attr("type", "button").text("Add") .on("click", function () { showDetailsDialog("Add", {}); }); } } ] }); $("#detailsForm").dialog({ autoOpen: false, width: 400 }); var showDetailsDialog = function(dialogType, client) { $("#name").val(client.Name); $("#age").val(client.Age); $("#address").val(client.Address); $("#country").val(client.Country); $("#married").prop("checked", client.Married); $("#save").off("click").on("click", function() { saveClient(client, dialogType === "Add"); }); $("#detailsForm").dialog("option", "title", dialogType + " Client") .dialog("open"); }; var saveClient = function(client, isNew) { $.extend(client, { Name: $("#name").val(), Age: parseInt($("#age").val(), 10), Address: $("#address").val(), Country: parseInt($("#country").val(), 10), Married: $("#married").is(":checked") }); $("#jsGrid").jsGrid(isNew ? "insertItem" : "updateItem", client); $("#detailsForm").dialog("close"); }; }); </script> </body> </html>
Java
/* * COPYRIGHT: Stealthy Labs LLC * DATE: 29th May 2015 * AUTHOR: Stealthy Labs * SOFTWARE: Tea Time */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #include <teatime.h> static int teatime_check_gl_version(uint32_t *major, uint32_t *minor); static int teatime_check_program_errors(GLuint program); static int teatime_check_shader_errors(GLuint shader); #define TEATIME_BREAKONERROR(FN,RC) if ((RC = teatime_check_gl_errors(__LINE__, #FN )) < 0) break #define TEATIME_BREAKONERROR_FB(FN,RC) if ((RC = teatime_check_gl_fb_errors(__LINE__, #FN )) < 0) break teatime_t *teatime_setup() { int rc = 0; teatime_t *obj = calloc(1, sizeof(teatime_t)); if (!obj) { fprintf(stderr, "Out of memory allocating %zu bytes\n", sizeof(teatime_t)); return NULL; } do { uint32_t version[2] = { 0, 0}; if (teatime_check_gl_version(&version[0], &version[1]) < 0) { fprintf(stderr, "Unable to verify OpenGL version\n"); rc = -1; break; } if (version[0] < 3) { fprintf(stderr, "Minimum Required OpenGL version 3.0. You have %u.%u\n", version[0], version[1]); rc = -1; break; } /* initialize off-screen framebuffer */ /* * This is the EXT_framebuffer_object OpenGL extension that allows us to * use an offscreen buffer as a target for rendering operations such as * vector calculations, providing full precision and removing unwanted * clamping issues. * we are turning off the traditional framebuffer here apparently. */ glGenFramebuffersEXT(1, &(obj->ofb)); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, obj->ofb); TEATIME_BREAKONERROR(glBindFramebufferEXT, rc); fprintf(stderr, "Successfully created off-screen framebuffer with id: %d\n", obj->ofb); /* get the texture size */ obj->maxtexsz = -1; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &(obj->maxtexsz)); fprintf(stderr, "Maximum Texture size for the GPU: %d\n", obj->maxtexsz); obj->itexid = obj->otexid = 0; obj->shader = obj->program = 0; } while (0); if (rc < 0) { teatime_cleanup(obj); obj = NULL; } return obj; } void teatime_cleanup(teatime_t *obj) { if (obj) { teatime_delete_program(obj); teatime_delete_textures(obj); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glDeleteFramebuffersEXT(1, &(obj->ofb)); glFlush(); free(obj); obj = NULL; } } int teatime_set_viewport(teatime_t *obj, uint32_t ilen) { uint32_t texsz = (uint32_t)((long)(sqrt(ilen / 4.0))); if (obj && texsz > 0 && texsz < (GLuint)obj->maxtexsz) { /* viewport mapping 1:1 pixel = texel = data mapping */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, texsz, 0.0, texsz); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glViewport(0, 0, texsz, texsz); obj->tex_size = texsz; fprintf(stderr, "Texture size: %u x %u\n", texsz, texsz); return 0; } else if (obj) { fprintf(stderr, "Max. texture size is %d. Calculated: %u from input length: %u\n", obj->maxtexsz, texsz, ilen); } return -EINVAL; } int teatime_create_textures(teatime_t *obj, const uint32_t *input, uint32_t ilen) { if (obj && input && ilen > 0) { int rc = 0; do { uint32_t texsz = (uint32_t)((long)(sqrt(ilen / 4.0))); if (texsz != obj->tex_size) { fprintf(stderr, "Viewport texture size(%u) != Input texture size (%u)\n", obj->tex_size, texsz); rc = -EINVAL; break; } glGenTextures(1, &(obj->itexid)); glGenTextures(1, &(obj->otexid)); fprintf(stderr, "Created input texture with ID: %u\n", obj->itexid); fprintf(stderr, "Created output texture with ID: %u\n", obj->otexid); /** BIND ONE TEXTURE AT A TIME **/ /* the texture target can vary depending on GPU */ glBindTexture(GL_TEXTURE_2D, obj->itexid); TEATIME_BREAKONERROR(glBindTexture, rc); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); /* turn off filtering and set proper wrap mode - this is obligatory for * floating point textures */ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); TEATIME_BREAKONERROR(glTexParameteri, rc); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); TEATIME_BREAKONERROR(glTexParameteri, rc); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); TEATIME_BREAKONERROR(glTexParameteri, rc); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); TEATIME_BREAKONERROR(glTexParameteri, rc); /* create a 2D texture of the same size as the data * internal format: GL_RGBA32UI_EXT * texture format: GL_RGBA_INTEGER * texture type: GL_UNSIGNED_INT */ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32UI_EXT, texsz, texsz, 0, GL_RGBA_INTEGER, GL_UNSIGNED_INT, NULL); TEATIME_BREAKONERROR(glTexImage2D, rc); /* transfer data to texture */ #ifdef WIN32 glTexSubImage2D #else glTexSubImage2DEXT #endif (GL_TEXTURE_2D, 0, 0, 0, obj->tex_size, obj->tex_size, GL_RGBA_INTEGER, GL_UNSIGNED_INT, input); #ifdef WIN32 TEATIME_BREAKONERROR(glTexSubImage2D, rc); #else TEATIME_BREAKONERROR(glTexSubImage2DEXT, rc); #endif fprintf(stderr, "Successfully transferred input data to texture ID: %u\n", obj->itexid); /* BIND the OUTPUT texture and work on it */ /* the texture target can vary depending on GPU */ glBindTexture(GL_TEXTURE_2D, obj->otexid); TEATIME_BREAKONERROR(glBindTexture, rc); /* turn off filtering and set proper wrap mode - this is obligatory for * floating point textures */ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); TEATIME_BREAKONERROR(glTexParameteri, rc); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); TEATIME_BREAKONERROR(glTexParameteri, rc); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); TEATIME_BREAKONERROR(glTexParameteri, rc); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); TEATIME_BREAKONERROR(glTexParameteri, rc); /* create a 2D texture of the same size as the data * internal format: GL_RGBA32UI_EXT * texture format: GL_RGBA_INTEGER * texture type: GL_UNSIGNED_INT */ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32UI_EXT, texsz, texsz, 0, GL_RGBA_INTEGER, GL_UNSIGNED_INT, NULL); TEATIME_BREAKONERROR(glTexImage2D, rc); /* change tex-env to replace instead of the default modulate */ glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); TEATIME_BREAKONERROR(glTexEnvi, rc); /* attach texture */ glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, obj->otexid, 0); TEATIME_BREAKONERROR(glFramebufferTexture2DEXT, rc); TEATIME_BREAKONERROR_FB(glFramebufferTexture2DEXT, rc); glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); TEATIME_BREAKONERROR(glDrawBuffer, rc); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_TEXTURE_2D, obj->otexid, 0); TEATIME_BREAKONERROR(glFramebufferTexture2DEXT, rc); TEATIME_BREAKONERROR_FB(glFramebufferTexture2DEXT, rc); rc = 0; } while (0); return rc; } return -EINVAL; } int teatime_read_textures(teatime_t *obj, uint32_t *output, uint32_t olen) { if (obj && output && olen > 0 && obj->otexid > 0) { int rc = 0; do { uint32_t texsz = (uint32_t)((long)(sqrt(olen / 4.0))); if (texsz != obj->tex_size) { fprintf(stderr, "Viewport texture size(%u) != Input texture size (%u)\n", obj->tex_size, texsz); rc = -EINVAL; break; } /* read the texture back */ glReadBuffer(GL_COLOR_ATTACHMENT0_EXT); TEATIME_BREAKONERROR(glReadBuffer, rc); glReadPixels(0, 0, obj->tex_size, obj->tex_size, GL_RGBA_INTEGER, GL_UNSIGNED_INT, output); TEATIME_BREAKONERROR(glReadPixels, rc); fprintf(stderr, "Successfully read data from the texture\n"); } while (0); return rc; } return -EINVAL; } int teatime_create_program(teatime_t *obj, const char *source) { if (obj && source) { int rc = 0; do { obj->program = glCreateProgram(); TEATIME_BREAKONERROR(glCreateProgram, rc); obj->shader = glCreateShader(GL_FRAGMENT_SHADER_ARB); TEATIME_BREAKONERROR(glCreateShader, rc); glShaderSource(obj->shader, 1, &source, NULL); TEATIME_BREAKONERROR(glShaderSource, rc); glCompileShader(obj->shader); rc = teatime_check_shader_errors(obj->shader); if (rc < 0) break; TEATIME_BREAKONERROR(glCompileShader, rc); glAttachShader(obj->program, obj->shader); TEATIME_BREAKONERROR(glAttachShader, rc); glLinkProgram(obj->program); rc = teatime_check_program_errors(obj->program); if (rc < 0) break; TEATIME_BREAKONERROR(glLinkProgram, rc); obj->locn_input = glGetUniformLocation(obj->program, "idata"); TEATIME_BREAKONERROR(glGetUniformLocation, rc); obj->locn_output = glGetUniformLocation(obj->program, "odata"); TEATIME_BREAKONERROR(glGetUniformLocation, rc); obj->locn_key = glGetUniformLocation(obj->program, "ikey"); TEATIME_BREAKONERROR(glGetUniformLocation, rc); obj->locn_rounds = glGetUniformLocation(obj->program, "rounds"); TEATIME_BREAKONERROR(glGetUniformLocation, rc); rc = 0; } while (0); return rc; } return -EINVAL; } int teatime_run_program(teatime_t *obj, const uint32_t ikey[4], uint32_t rounds) { if (obj && obj->program > 0) { int rc = 0; do { glUseProgram(obj->program); TEATIME_BREAKONERROR(glUseProgram, rc); glActiveTexture(GL_TEXTURE0); TEATIME_BREAKONERROR(glActiveTexture, rc); glBindTexture(GL_TEXTURE_2D, obj->itexid); TEATIME_BREAKONERROR(glBindTexture, rc); glUniform1i(obj->locn_input, 0); TEATIME_BREAKONERROR(glUniform1i, rc); glActiveTexture(GL_TEXTURE1); TEATIME_BREAKONERROR(glActiveTexture, rc); glBindTexture(GL_TEXTURE_2D, obj->otexid); TEATIME_BREAKONERROR(glBindTexture, rc); glUniform1i(obj->locn_output, 1); TEATIME_BREAKONERROR(glUniform1i, rc); glUniform4uiv(obj->locn_key, 1, ikey); TEATIME_BREAKONERROR(glUniform1uiv, rc); glUniform1ui(obj->locn_rounds, rounds); TEATIME_BREAKONERROR(glUniform1ui, rc); glFinish(); glPolygonMode(GL_FRONT, GL_FILL); /* render */ glBegin(GL_QUADS); glTexCoord2i(0, 0); glVertex2i(0, 0); //glTexCoord2i(obj->tex_size, 0); glTexCoord2i(1, 0); glVertex2i(obj->tex_size, 0); //glTexCoord2i(obj->tex_size, obj->tex_size); glTexCoord2i(1, 1); glVertex2i(obj->tex_size, obj->tex_size); glTexCoord2i(0, 1); //glTexCoord2i(0, obj->tex_size); glVertex2i(0, obj->tex_size); glEnd(); glFinish(); TEATIME_BREAKONERROR_FB(Rendering, rc); TEATIME_BREAKONERROR(Rendering, rc); rc = 0; } while (0); return rc; } return -EINVAL; } void teatime_delete_textures(teatime_t *obj) { if (obj) { if (obj->itexid != 0) { glDeleteTextures(1, &(obj->itexid)); obj->itexid = 0; } if (obj->otexid != 0) { glDeleteTextures(1, &(obj->otexid)); obj->otexid = 0; } } } void teatime_delete_program(teatime_t *obj) { if (obj) { if (obj->shader > 0 && obj->program > 0) { glDetachShader(obj->program, obj->shader); } if (obj->shader > 0) glDeleteShader(obj->shader); if (obj->program > 0) glDeleteProgram(obj->program); obj->shader = 0; obj->program = 0; } } void teatime_print_version(FILE *fp) { const GLubyte *version = NULL; version = glGetString(GL_VERSION); fprintf(fp, "GL Version: %s\n", (const char *)version); version = glGetString(GL_SHADING_LANGUAGE_VERSION); fprintf(fp, "GLSL Version: %s\n", (const char *)version); version = glGetString(GL_VENDOR); fprintf(fp, "GL Vendor: %s\n", (const char *)version); } int teatime_check_gl_version(uint32_t *major, uint32_t *minor) { const GLubyte *version = NULL; version = glGetString(GL_VERSION); if (version) { uint32_t ver[2] = { 0, 0 }; char *endp = NULL; char *endp2 = NULL; errno = 0; ver[0] = strtol((const char *)version, &endp, 10); if (errno == ERANGE || (const void *)endp == (const void *)version) { fprintf(stderr, "Version string %s cannot be parsed\n", (const char *)version); return -1; } /* endp[0] = '.' and endp[1] points to minor */ errno = 0; ver[1] = strtol((const char *)&endp[1], &endp2, 10); if (errno == ERANGE || endp2 == &endp[1]) { fprintf(stderr, "Version string %s cannot be parsed\n", (const char *)version); return -1; } if (major) *major = ver[0]; if (minor) *minor = ver[1]; return 0; } return -1; } int teatime_check_gl_errors(int line, const char *fn_name) { GLenum err = glGetError(); if (err != GL_NO_ERROR) { const GLubyte *estr = gluErrorString(err); fprintf(stderr, "%s(): GL Error(%d) on line %d: %s\n", fn_name, err, line, (const char *)estr); return -1; } return 0; } int teatime_check_gl_fb_errors(int line, const char *fn_name) { GLenum st = (GLenum)glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); switch (st) { case GL_FRAMEBUFFER_COMPLETE_EXT: return 0; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: fprintf(stderr, "%s(): GL FB error on line %d: incomplete attachment\n", fn_name, line); break; case GL_FRAMEBUFFER_UNSUPPORTED_EXT: fprintf(stderr, "%s(): GL FB error on line %d: unsupported\n", fn_name, line); break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT: fprintf(stderr, "%s(): GL FB error on line %d: incomplete missing attachment\n", fn_name, line); break; case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT: fprintf(stderr, "%s(): GL FB error on line %d: incomplete dimensions\n", fn_name, line); break; case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT: fprintf(stderr, "%s(): GL FB error on line %d: incomplete formats\n", fn_name, line); break; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT: fprintf(stderr, "%s(): GL FB error on line %d: incomplete draw buffer\n", fn_name, line); break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT: fprintf(stderr, "%s(): GL FB error on line %d: incomplete read buffer\n", fn_name, line); break; default: fprintf(stderr, "%s(): GL FB error on line %d: Unknown. Error Value: %d\n", fn_name, line, st); break; } return -1; } int teatime_check_program_errors(GLuint program) { GLint ilen = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &ilen); if (ilen > 1) { GLsizei wb = 0; GLchar *buf = calloc(ilen, sizeof(GLchar)); if (!buf) { fprintf(stderr, "Out of memory allocating %d bytes\n", ilen); return -ENOMEM; } glGetProgramInfoLog(program, ilen, &wb, buf); buf[wb] = '\0'; fprintf(stderr, "Program Errors:\n%s\n", (const char *)buf); free(buf); } return 0; } int teatime_check_shader_errors(GLuint shader) { GLint ilen = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &ilen); if (ilen > 1) { GLsizei wb = 0; GLchar *buf = calloc(ilen, sizeof(GLchar)); if (!buf) { fprintf(stderr, "Out of memory allocating %d bytes\n", ilen); return -ENOMEM; } glGetShaderInfoLog(shader, ilen, &wb, buf); buf[wb] = '\0'; fprintf(stderr, "Shader Errors:\n%s\n", (const char *)buf); free(buf); } return 0; } #define TEA_ENCRYPT_SOURCE \ "#version 130\n" \ "#extension GL_EXT_gpu_shader4 : enable\n" \ "uniform usampler2D idata;\n" \ "uniform uvec4 ikey; \n" \ "uniform uint rounds; \n" \ "out uvec4 odata; \n" \ "void main(void) {\n" \ " uvec4 x = texture(idata, gl_TexCoord[0].st);\n" \ " uint delta = uint(0x9e3779b9); \n" \ " uint sum = uint(0); \n" \ " for (uint i = uint(0); i < rounds; ++i) {\n" \ " sum += delta; \n" \ " x[0] += (((x[1] << 4) + ikey[0]) ^ (x[1] + sum)) ^ ((x[1] >> 5) + ikey[1]);\n" \ " x[1] += (((x[0] << 4) + ikey[2]) ^ (x[0] + sum)) ^ ((x[0] >> 5) + ikey[3]);\n" \ " x[2] += (((x[3] << 4) + ikey[0]) ^ (x[3] + sum)) ^ ((x[3] >> 5) + ikey[1]);\n" \ " x[3] += (((x[2] << 4) + ikey[2]) ^ (x[2] + sum)) ^ ((x[2] >> 5) + ikey[3]);\n" \ " }\n" \ " odata = x; \n" \ "}\n" #define TEA_DECRYPT_SOURCE \ "#version 130\n" \ "#extension GL_EXT_gpu_shader4 : enable\n" \ "uniform usampler2D idata;\n" \ "uniform uvec4 ikey; \n" \ "uniform uint rounds; \n" \ "out uvec4 odata; \n" \ "void main(void) {\n" \ " uvec4 x = texture(idata, gl_TexCoord[0].st);\n" \ " uint delta = uint(0x9e3779b9); \n" \ " uint sum = delta * rounds; \n" \ " for (uint i = uint(0); i < rounds; ++i) {\n" \ " x[1] -= (((x[0] << 4) + ikey[2]) ^ (x[0] + sum)) ^ ((x[0] >> 5) + ikey[3]);\n" \ " x[0] -= (((x[1] << 4) + ikey[0]) ^ (x[1] + sum)) ^ ((x[1] >> 5) + ikey[1]);\n" \ " x[3] -= (((x[2] << 4) + ikey[2]) ^ (x[2] + sum)) ^ ((x[2] >> 5) + ikey[3]);\n" \ " x[2] -= (((x[3] << 4) + ikey[0]) ^ (x[3] + sum)) ^ ((x[3] >> 5) + ikey[1]);\n" \ " sum -= delta; \n" \ " }\n" \ " odata = x; \n" \ "}\n" const char *teatime_encrypt_source() { return TEA_ENCRYPT_SOURCE; } const char *teatime_decrypt_source() { return TEA_DECRYPT_SOURCE; }
Java
class CreateLists < ActiveRecord::Migration[5.1] def change create_table :lists do |t| t.string :letter t.string :tax_reference t.string :list_type t.date :date_list t.timestamps end end end
Java
var groove = require('groove'); var semver = require('semver'); var EventEmitter = require('events').EventEmitter; var util = require('util'); var mkdirp = require('mkdirp'); var fs = require('fs'); var uuid = require('./uuid'); var path = require('path'); var Pend = require('pend'); var DedupedQueue = require('./deduped_queue'); var findit = require('findit2'); var shuffle = require('mess'); var mv = require('mv'); var MusicLibraryIndex = require('music-library-index'); var keese = require('keese'); var safePath = require('./safe_path'); var PassThrough = require('stream').PassThrough; var url = require('url'); var dbIterate = require('./db_iterate'); var log = require('./log'); var importUrlFilters = require('./import_url_filters'); var youtubeSearch = require('./youtube_search'); var yauzl = require('yauzl'); var importFileFilters = [ { name: 'zip', fn: importFileAsZip, }, { name: 'song', fn: importFileAsSong, }, ]; module.exports = Player; ensureGrooveVersionIsOk(); var cpuCount = 1; var PLAYER_KEY_PREFIX = "Player."; var LIBRARY_KEY_PREFIX = "Library."; var LIBRARY_DIR_PREFIX = "LibraryDir."; var QUEUE_KEY_PREFIX = "Playlist."; var PLAYLIST_KEY_PREFIX = "StoredPlaylist."; var LABEL_KEY_PREFIX = "Label."; var PLAYLIST_META_KEY_PREFIX = "StoredPlaylistMeta."; // db: store in the DB var DB_PROPS = { key: { db: true, clientVisible: true, clientCanModify: false, type: 'string', }, name: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, artistName: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, albumArtistName: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, albumName: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, compilation: { db: true, clientVisible: true, clientCanModify: true, type: 'boolean', }, track: { db: true, clientVisible: true, clientCanModify: true, type: 'integer', }, trackCount: { db: true, clientVisible: true, clientCanModify: true, type: 'integer', }, disc: { db: true, clientVisible: true, clientCanModify: true, type: 'integer', }, discCount: { db: true, clientVisible: true, clientCanModify: true, type: 'integer', }, duration: { db: true, clientVisible: true, clientCanModify: false, type: 'float', }, year: { db: true, clientVisible: true, clientCanModify: true, type: 'integer', }, genre: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, file: { db: true, clientVisible: true, clientCanModify: false, type: 'string', }, mtime: { db: true, clientVisible: false, clientCanModify: false, type: 'integer', }, replayGainAlbumGain: { db: true, clientVisible: false, clientCanModify: false, type: 'float', }, replayGainAlbumPeak: { db: true, clientVisible: false, clientCanModify: false, type: 'float', }, replayGainTrackGain: { db: true, clientVisible: false, clientCanModify: false, type: 'float', }, replayGainTrackPeak: { db: true, clientVisible: false, clientCanModify: false, type: 'float', }, composerName: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, performerName: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, lastQueueDate: { db: true, clientVisible: false, clientCanModify: false, type: 'date', }, fingerprint: { db: true, clientVisible: false, clientCanModify: false, type: 'array_of_integer', }, playCount: { db: true, clientVisible: false, clientCanModify: false, type: 'integer', }, labels: { db: true, clientVisible: true, clientCanModify: false, type: 'set', }, }; var PROP_TYPE_PARSERS = { 'string': function(value) { return value ? String(value) : ""; }, 'date': function(value) { if (!value) return null; var date = new Date(value); if (isNaN(date.getTime())) return null; return date; }, 'integer': parseIntOrNull, 'float': parseFloatOrNull, 'boolean': function(value) { return value == null ? null : !!value; }, 'array_of_integer': function(value) { if (!Array.isArray(value)) return null; value = value.map(parseIntOrNull); for (var i = 0; i < value.length; i++) { if (value[i] == null) return null; } return value; }, 'set': function(value) { var result = {}; for (var key in value) { result[key] = 1; } return result; }, }; var labelColors = [ "#e11d21", "#eb6420", "#fbca04", "#009800", "#006b75", "#207de5", "#0052cc", "#5319e7", "#f7c6c7", "#fad8c7", "#fef2c0", "#bfe5bf", "#bfdadc", "#bfd4f2", "#c7def8", "#d4c5f9", ]; // how many GrooveFiles to keep open, ready to be decoded var OPEN_FILE_COUNT = 8; var PREV_FILE_COUNT = Math.floor(OPEN_FILE_COUNT / 2); var NEXT_FILE_COUNT = OPEN_FILE_COUNT - PREV_FILE_COUNT; var DB_SCALE = Math.log(10.0) * 0.05; var REPLAYGAIN_PREAMP = 0.75; var REPLAYGAIN_DEFAULT = 0.25; Player.REPEAT_OFF = 0; Player.REPEAT_ALL = 1; Player.REPEAT_ONE = 2; Player.trackWithoutIndex = trackWithoutIndex; Player.setGrooveLoggingLevel = setGrooveLoggingLevel; util.inherits(Player, EventEmitter); function Player(db, config) { EventEmitter.call(this); this.setMaxListeners(0); this.db = db; this.musicDirectory = config.musicDirectory; this.dbFilesByPath = {}; this.dbFilesByLabel = {}; this.libraryIndex = new MusicLibraryIndex({ searchFields: MusicLibraryIndex.defaultSearchFields.concat('file'), }); this.addQueue = new DedupedQueue({ processOne: this.addToLibrary.bind(this), // limit to 1 async operation because we're blocking on the hard drive, // it's faster to read one file at a time. maxAsync: 1, }); this.dirs = {}; this.dirScanQueue = new DedupedQueue({ processOne: this.refreshFilesIndex.bind(this), // only 1 dir scanning can happen at a time // we'll pass the dir to scan as the ID so that not more than 1 of the // same dir can queue up maxAsync: 1, }); this.dirScanQueue.on('error', function(err) { log.error("library scanning error:", err.stack); }); this.disableFsRefCount = 0; this.playlist = {}; this.playlists = {}; this.currentTrack = null; this.tracksInOrder = []; // another way to look at playlist this.grooveItems = {}; // maps groove item id to track this.seekRequestPos = -1; // set to >= 0 when we want to seek this.invalidPaths = {}; // files that could not be opened this.playlistItemDeleteQueue = []; this.dontBelieveTheEndOfPlaylistSentinelItsATrap = false; this.queueClearEncodedBuffers = false; this.repeat = Player.REPEAT_OFF; this.desiredPlayerHardwareState = null; // true: normal hardware playback. false: dummy this.pendingPlayerAttachDetach = null; this.isPlaying = false; this.trackStartDate = null; this.pausedTime = 0; this.autoDjOn = false; this.autoDjHistorySize = 10; this.autoDjFutureSize = 10; this.ongoingScans = {}; this.scanQueue = new DedupedQueue({ processOne: this.performScan.bind(this), maxAsync: cpuCount, }); this.headerBuffers = []; this.recentBuffers = []; this.newHeaderBuffers = []; this.openStreamers = []; this.expectHeaders = true; // when a streaming client connects we send them many buffers quickly // in order to get the stream started, then we slow down. this.encodeQueueDuration = config.encodeQueueDuration; this.groovePlaylist = groove.createPlaylist(); this.groovePlayer = null; this.grooveEncoder = groove.createEncoder(); this.grooveEncoder.encodedBufferSize = 128 * 1024; this.detachEncoderTimeout = null; this.pendingEncoderAttachDetach = false; this.desiredEncoderAttachState = false; this.flushEncodedInterval = null; this.groovePlaylist.pause(); this.volume = this.groovePlaylist.gain; this.grooveEncoder.formatShortName = "mp3"; this.grooveEncoder.codecShortName = "mp3"; this.grooveEncoder.bitRate = config.encodeBitRate * 1000; this.importProgress = {}; this.lastImportProgressEvent = new Date(); // tracking playCount this.previousIsPlaying = false; this.playingStart = new Date(); this.playingTime = 0; this.lastPlayingItem = null; this.googleApiKey = config.googleApiKey; this.ignoreExtensions = config.ignoreExtensions.map(makeLower); } Player.prototype.initialize = function(cb) { var self = this; var startupTrackInfo = null; initLibrary(function(err) { if (err) return cb(err); cacheTracksArray(self); self.requestUpdateDb(); cacheAllOptions(function(err) { if (err) return cb(err); setInterval(doPersistCurrentTrack, 10000); if (startupTrackInfo) { self.seek(startupTrackInfo.id, startupTrackInfo.pos); } else { playlistChanged(self); } lazyReplayGainScanPlaylist(self); cb(); }); }); function initLibrary(cb) { var pend = new Pend(); pend.go(cacheAllDb); pend.go(cacheAllDirs); pend.go(cacheAllQueue); pend.go(cacheAllPlaylists); pend.go(cacheAllLabels); pend.wait(cb); } function cacheAllPlaylists(cb) { cacheAllPlaylistMeta(function(err) { if (err) return cb(err); cacheAllPlaylistItems(cb); }); function cacheAllPlaylistMeta(cb) { dbIterate(self.db, PLAYLIST_META_KEY_PREFIX, processOne, cb); function processOne(key, value) { var playlist = deserializePlaylist(value); self.playlists[playlist.id] = playlist; } } function cacheAllPlaylistItems(cb) { dbIterate(self.db, PLAYLIST_KEY_PREFIX, processOne, cb); function processOne(key, value) { var playlistIdEnd = key.indexOf('.', PLAYLIST_KEY_PREFIX.length); var playlistId = key.substring(PLAYLIST_KEY_PREFIX.length, playlistIdEnd); var playlistItem = JSON.parse(value); self.playlists[playlistId].items[playlistItem.id] = playlistItem; } } } function cacheAllLabels(cb) { dbIterate(self.db, LABEL_KEY_PREFIX, processOne, cb); function processOne(key, value) { var labelId = key.substring(LABEL_KEY_PREFIX.length); var labelEntry = JSON.parse(value); self.libraryIndex.addLabel(labelEntry); } } function cacheAllQueue(cb) { dbIterate(self.db, QUEUE_KEY_PREFIX, processOne, cb); function processOne(key, value) { var plEntry = JSON.parse(value); self.playlist[plEntry.id] = plEntry; } } function cacheAllOptions(cb) { var options = { repeat: null, autoDjOn: null, autoDjHistorySize: null, autoDjFutureSize: null, hardwarePlayback: null, volume: null, currentTrackInfo: null, }; var pend = new Pend(); for (var name in options) { pend.go(makeGetFn(name)); } pend.wait(function(err) { if (err) return cb(err); if (options.repeat != null) { self.setRepeat(options.repeat); } if (options.autoDjOn != null) { self.setAutoDjOn(options.autoDjOn); } if (options.autoDjHistorySize != null) { self.setAutoDjHistorySize(options.autoDjHistorySize); } if (options.autoDjFutureSize != null) { self.setAutoDjFutureSize(options.autoDjFutureSize); } if (options.volume != null) { self.setVolume(options.volume); } startupTrackInfo = options.currentTrackInfo; var hardwarePlaybackValue = options.hardwarePlayback == null ? true : options.hardwarePlayback; // start the hardware player first // fall back to dummy self.setHardwarePlayback(hardwarePlaybackValue, function(err) { if (err) { log.error("Unable to attach hardware player, falling back to dummy.", err.stack); self.setHardwarePlayback(false); } cb(); }); }); function makeGetFn(name) { return function(cb) { self.db.get(PLAYER_KEY_PREFIX + name, function(err, value) { if (!err && value != null) { try { options[name] = JSON.parse(value); } catch (err) { cb(err); return; } } cb(); }); }; } } function cacheAllDirs(cb) { dbIterate(self.db, LIBRARY_DIR_PREFIX, processOne, cb); function processOne(key, value) { var dirEntry = JSON.parse(value); self.dirs[dirEntry.dirName] = dirEntry; } } function cacheAllDb(cb) { var scrubCmds = []; dbIterate(self.db, LIBRARY_KEY_PREFIX, processOne, scrubAndCb); function processOne(key, value) { var dbFile = deserializeFileData(value); // scrub duplicates if (self.dbFilesByPath[dbFile.file]) { scrubCmds.push({type: 'del', key: key}); } else { self.libraryIndex.addTrack(dbFile); self.dbFilesByPath[dbFile.file] = dbFile; for (var labelId in dbFile.labels) { var files = self.dbFilesByLabel[labelId]; if (files == null) files = self.dbFilesByLabel[labelId] = {}; files[dbFile.key] = dbFile; } } } function scrubAndCb() { if (scrubCmds.length === 0) return cb(); log.warn("Scrubbing " + scrubCmds.length + " duplicate db entries"); self.db.batch(scrubCmds, function(err) { if (err) log.error("Unable to scrub duplicate tracks from db:", err.stack); cb(); }); } } function doPersistCurrentTrack() { if (self.isPlaying) { self.persistCurrentTrack(); } } }; function startEncoderAttach(self, cb) { if (self.desiredEncoderAttachState) return; self.desiredEncoderAttachState = true; if (self.pendingEncoderAttachDetach) return; self.pendingEncoderAttachDetach = true; self.grooveEncoder.attach(self.groovePlaylist, function(err) { self.pendingEncoderAttachDetach = false; if (err) { self.desiredEncoderAttachState = false; cb(err); } else if (!self.desiredEncoderAttachState) { startEncoderDetach(self, cb); } }); } function startEncoderDetach(self, cb) { if (!self.desiredEncoderAttachState) return; self.desiredEncoderAttachState = false; if (self.pendingEncoderAttachDetach) return; self.pendingEncoderAttachDetach = true; self.grooveEncoder.detach(function(err) { self.pendingEncoderAttachDetach = false; if (err) { self.desiredEncoderAttachState = true; cb(err); } else if (self.desiredEncoderAttachState) { startEncoderAttach(self, cb); } }); } Player.prototype.getBufferedSeconds = function() { if (this.recentBuffers.length < 2) return 0; var firstPts = this.recentBuffers[0].pts; var lastPts = this.recentBuffers[this.recentBuffers.length - 1].pts; var frameCount = lastPts - firstPts; var sampleRate = this.grooveEncoder.actualAudioFormat.sampleRate; return frameCount / sampleRate; }; Player.prototype.attachEncoder = function(cb) { var self = this; cb = cb || logIfError; if (self.flushEncodedInterval) return cb(); log.debug("first streamer connected - attaching encoder"); self.flushEncodedInterval = setInterval(flushEncoded, 100); startEncoderAttach(self, cb); function flushEncoded() { if (!self.desiredEncoderAttachState || self.pendingEncoderAttachDetach) return; var playHead = self.groovePlayer.position(); if (!playHead.item) return; var plItems = self.groovePlaylist.items(); // get rid of old items var buf; while (buf = self.recentBuffers[0]) { /* log.debug(" buf.item " + buf.item.file.filename + "\n" + "playHead.item " + playHead.item.file.filename + "\n" + " playHead.pos " + playHead.pos + "\n" + " buf.pos " + buf.pos); */ if (isBufOld(buf)) { self.recentBuffers.shift(); } else { break; } } // poll the encoder for more buffers until either there are no buffers // available or we get enough buffered while (self.getBufferedSeconds() < self.encodeQueueDuration) { buf = self.grooveEncoder.getBuffer(); if (!buf) break; if (buf.buffer) { if (buf.item) { if (self.expectHeaders) { log.debug("encoder: got first non-header"); self.headerBuffers = self.newHeaderBuffers; self.newHeaderBuffers = []; self.expectHeaders = false; } self.recentBuffers.push(buf); for (var i = 0; i < self.openStreamers.length; i += 1) { self.openStreamers[i].write(buf.buffer); } } else if (self.expectHeaders) { // this is a header log.debug("encoder: got header"); self.newHeaderBuffers.push(buf.buffer); } else { // it's a footer, ignore the fuck out of it log.debug("ignoring encoded audio footer"); } } else { // end of playlist sentinel log.debug("encoder: end of playlist sentinel"); if (self.queueClearEncodedBuffers) { self.queueClearEncodedBuffers = false; self.clearEncodedBuffer(); self.emit('seek'); } self.expectHeaders = true; } } function isBufOld(buf) { // typical case if (buf.item.id === playHead.item.id) { return playHead.pos > buf.pos; } // edge case var playHeadIndex = -1; var bufItemIndex = -1; for (var i = 0; i < plItems.length; i += 1) { var plItem = plItems[i]; if (plItem.id === playHead.item.id) { playHeadIndex = i; } else if (plItem.id === buf.item.id) { bufItemIndex = i; } } return playHeadIndex > bufItemIndex; } } function logIfError(err) { if (err) { log.error("Unable to attach encoder:", err.stack); } } }; Player.prototype.detachEncoder = function(cb) { cb = cb || logIfError; this.clearEncodedBuffer(); this.queueClearEncodedBuffers = false; clearInterval(this.flushEncodedInterval); this.flushEncodedInterval = null; startEncoderDetach(this, cb); this.grooveEncoder.removeAllListeners(); function logIfError(err) { if (err) { log.error("Unable to detach encoder:", err.stack); } } }; Player.prototype.deleteDbMtimes = function(cb) { cb = cb || logIfDbError; var updateCmds = []; for (var key in this.libraryIndex.trackTable) { var dbFile = this.libraryIndex.trackTable[key]; delete dbFile.mtime; persistDbFile(dbFile, updateCmds); } this.db.batch(updateCmds, cb); }; Player.prototype.requestUpdateDb = function(dirName, cb) { var fullPath = path.resolve(this.musicDirectory, dirName || ""); this.dirScanQueue.add(fullPath, { dir: fullPath, }, cb); }; Player.prototype.refreshFilesIndex = function(args, cb) { var self = this; var dir = args.dir; var dirWithSlash = ensureSep(dir); var walker = findit(dirWithSlash, {followSymlinks: true}); var thisScanId = uuid(); var delCmds = []; walker.on('directory', function(fullDirPath, stat, stop, linkPath) { var usePath = linkPath || fullDirPath; var dirName = path.relative(self.musicDirectory, usePath); var baseName = path.basename(dirName); if (isFileIgnored(baseName)) { stop(); return; } var dirEntry = self.getOrCreateDir(dirName, stat); if (usePath === dirWithSlash) return; // ignore root search path var parentDirName = path.dirname(dirName); if (parentDirName === '.') parentDirName = ''; var parentDirEntry = self.getOrCreateDir(parentDirName); parentDirEntry.dirEntries[baseName] = thisScanId; }); walker.on('file', function(fullPath, stat, linkPath) { var usePath = linkPath || fullPath; var relPath = path.relative(self.musicDirectory, usePath); var dirName = path.dirname(relPath); if (dirName === '.') dirName = ''; var baseName = path.basename(relPath); if (isFileIgnored(baseName)) return; var extName = path.extname(relPath); if (isExtensionIgnored(self, extName)) return; var dirEntry = self.getOrCreateDir(dirName); dirEntry.entries[baseName] = thisScanId; var fileMtime = stat.mtime.getTime(); onAddOrChange(self, relPath, fileMtime); }); walker.on('error', function(err) { walker.stop(); cleanupAndCb(err); }); walker.on('end', function() { var dirName = path.relative(self.musicDirectory, dir); checkDirEntry(self.dirs[dirName]); cleanupAndCb(); function checkDirEntry(dirEntry) { if (!dirEntry) return; var id; var baseName; var i; var deletedFiles = []; var deletedDirs = []; for (baseName in dirEntry.entries) { id = dirEntry.entries[baseName]; if (id !== thisScanId) deletedFiles.push(baseName); } for (i = 0; i < deletedFiles.length; i += 1) { baseName = deletedFiles[i]; delete dirEntry.entries[baseName]; onFileMissing(dirEntry, baseName); } for (baseName in dirEntry.dirEntries) { id = dirEntry.dirEntries[baseName]; var childEntry = self.dirs[path.join(dirEntry.dirName, baseName)]; checkDirEntry(childEntry); if (id !== thisScanId) deletedDirs.push(baseName); } for (i = 0; i < deletedDirs.length; i += 1) { baseName = deletedDirs[i]; delete dirEntry.dirEntries[baseName]; onDirMissing(dirEntry, baseName); } self.persistDirEntry(dirEntry); } }); function cleanupAndCb(err) { if (delCmds.length > 0) { self.db.batch(delCmds, logIfDbError); self.emit('deleteDbTrack'); } cb(err); } function onDirMissing(parentDirEntry, baseName) { var dirName = path.join(parentDirEntry.dirName, baseName); log.debug("directory deleted:", dirName); var dirEntry = self.dirs[dirName]; var watcher = dirEntry.watcher; if (watcher) watcher.close(); delete self.dirs[dirName]; delete parentDirEntry.dirEntries[baseName]; } function onFileMissing(parentDirEntry, baseName) { var relPath = path.join(parentDirEntry.dirName, baseName); log.debug("file deleted:", relPath); delete parentDirEntry.entries[baseName]; var dbFile = self.dbFilesByPath[relPath]; if (dbFile) { // batch up some db delete commands to run after walking the file system delDbEntryCmds(self, dbFile, delCmds); } } }; Player.prototype.watchDirEntry = function(dirEntry) { var self = this; var changeTriggered = null; var fullDirPath = path.join(self.musicDirectory, dirEntry.dirName); var watcher; try { watcher = fs.watch(fullDirPath, onChange); watcher.on('error', onWatchError); } catch (err) { log.warn("Unable to fs.watch:", err.stack); watcher = null; } dirEntry.watcher = watcher; function onChange(eventName) { if (changeTriggered) clearTimeout(changeTriggered); changeTriggered = setTimeout(function() { changeTriggered = null; log.debug("dir updated:", dirEntry.dirName); self.dirScanQueue.add(fullDirPath, { dir: fullDirPath }); }, 100); } function onWatchError(err) { log.error("watch error:", err.stack); } }; Player.prototype.getOrCreateDir = function (dirName, stat) { var dirEntry = this.dirs[dirName]; if (!dirEntry) { dirEntry = this.dirs[dirName] = { dirName: dirName, entries: {}, dirEntries: {}, watcher: null, // will be set just below mtime: stat && stat.mtime, }; } else if (stat && dirEntry.mtime !== stat.mtime) { dirEntry.mtime = stat.mtime; } if (!dirEntry.watcher) this.watchDirEntry(dirEntry); return dirEntry; }; Player.prototype.getCurPos = function() { return this.isPlaying ? ((new Date() - this.trackStartDate) / 1000.0) : this.pausedTime; }; function startPlayerSwitchDevice(self, wantHardware, cb) { self.desiredPlayerHardwareState = wantHardware; if (self.pendingPlayerAttachDetach) return; self.pendingPlayerAttachDetach = true; if (self.groovePlayer) { self.groovePlayer.removeAllListeners(); self.groovePlayer.detach(onDetachComplete); } else { onDetachComplete(); } function onDetachComplete(err) { if (err) return cb(err); self.groovePlayer = groove.createPlayer(); self.groovePlayer.deviceIndex = wantHardware ? null : groove.DUMMY_DEVICE; self.groovePlayer.attach(self.groovePlaylist, function(err) { self.pendingPlayerAttachDetach = false; if (err) return cb(err); if (self.desiredPlayerHardwareState !== wantHardware) { startPlayerSwitchDevice(self, self.desiredPlayerHardwareState, cb); } else { cb(); } }); } } Player.prototype.setHardwarePlayback = function(value, cb) { var self = this; cb = cb || logIfError; value = !!value; if (value === self.desiredPlayerHardwareState) return cb(); startPlayerSwitchDevice(self, value, function(err) { if (err) return cb(err); self.clearEncodedBuffer(); self.emit('seek'); self.groovePlayer.on('nowplaying', onNowPlaying); self.persistOption('hardwarePlayback', self.desiredPlayerHardwareState); self.emit('hardwarePlayback', self.desiredPlayerHardwareState); cb(); }); function onNowPlaying() { var playHead = self.groovePlayer.position(); var decodeHead = self.groovePlaylist.position(); if (playHead.item) { var nowMs = (new Date()).getTime(); var posMs = playHead.pos * 1000; self.trackStartDate = new Date(nowMs - posMs); self.currentTrack = self.grooveItems[playHead.item.id]; playlistChanged(self); self.currentTrackChanged(); } else if (!decodeHead.item) { if (!self.dontBelieveTheEndOfPlaylistSentinelItsATrap) { // both play head and decode head are null. end of playlist. log.debug("end of playlist"); self.currentTrack = null; playlistChanged(self); self.currentTrackChanged(); } } } function logIfError(err) { if (err) { log.error("Unable to set hardware playback mode:", err.stack); } } }; Player.prototype.startStreaming = function(resp) { this.headerBuffers.forEach(function(headerBuffer) { resp.write(headerBuffer); }); this.recentBuffers.forEach(function(recentBuffer) { resp.write(recentBuffer.buffer); }); this.cancelDetachEncoderTimeout(); this.attachEncoder(); this.openStreamers.push(resp); this.emit('streamerConnect', resp.client); }; Player.prototype.stopStreaming = function(resp) { for (var i = 0; i < this.openStreamers.length; i += 1) { if (this.openStreamers[i] === resp) { this.openStreamers.splice(i, 1); this.emit('streamerDisconnect', resp.client); break; } } }; Player.prototype.lastStreamerDisconnected = function() { log.debug("last streamer disconnected"); this.startDetachEncoderTimeout(); if (!this.desiredPlayerHardwareState && this.isPlaying) { this.emit("autoPause"); this.pause(); } }; Player.prototype.cancelDetachEncoderTimeout = function() { if (this.detachEncoderTimeout) { clearTimeout(this.detachEncoderTimeout); this.detachEncoderTimeout = null; } }; Player.prototype.startDetachEncoderTimeout = function() { var self = this; self.cancelDetachEncoderTimeout(); // we use encodeQueueDuration for the encoder timeout so that we are // guaranteed to have audio available for the encoder in the case of // detaching and reattaching the encoder. self.detachEncoderTimeout = setTimeout(timeout, self.encodeQueueDuration * 1000); function timeout() { if (self.openStreamers.length === 0 && self.isPlaying) { log.debug("detaching encoder"); self.detachEncoder(); } } }; Player.prototype.deleteFiles = function(keys) { var self = this; var delCmds = []; for (var i = 0; i < keys.length; i += 1) { var key = keys[i]; var dbFile = self.libraryIndex.trackTable[key]; if (!dbFile) continue; var fullPath = path.join(self.musicDirectory, dbFile.file); delDbEntryCmds(self, dbFile, delCmds); fs.unlink(fullPath, logIfError); } if (delCmds.length > 0) { self.emit('deleteDbTrack'); self.db.batch(delCmds, logIfError); } function logIfError(err) { if (err) { log.error("Error deleting files:", err.stack); } } }; function delDbEntryCmds(self, dbFile, dbCmds) { // delete items from the queue that are being deleted from the library var deleteQueueItems = []; for (var queueId in self.playlist) { var queueItem = self.playlist[queueId]; if (queueItem.key === dbFile.key) { deleteQueueItems.push(queueId); } } self.removeQueueItems(deleteQueueItems); // delete items from playlists that are being deleted from the library var playlistRemovals = {}; for (var playlistId in self.playlists) { var playlist = self.playlists[playlistId]; var removals = []; playlistRemovals[playlistId] = removals; for (var playlistItemId in playlist.items) { var playlistItem = playlist.items[playlistItemId]; if (playlistItem.key === dbFile.key) { removals.push(playlistItemId); } } } self.playlistRemoveItems(playlistRemovals); self.libraryIndex.removeTrack(dbFile.key); delete self.dbFilesByPath[dbFile.file]; var baseName = path.basename(dbFile.file); var parentDirName = path.dirname(dbFile.file); if (parentDirName === '.') parentDirName = ''; var parentDirEntry = self.dirs[parentDirName]; if (parentDirEntry) delete parentDirEntry[baseName]; dbCmds.push({type: 'del', key: LIBRARY_KEY_PREFIX + dbFile.key}); } Player.prototype.setVolume = function(value) { value = Math.min(2.0, value); value = Math.max(0.0, value); this.volume = value; this.groovePlaylist.setGain(value); this.persistOption('volume', this.volume); this.emit("volumeUpdate"); }; Player.prototype.importUrl = function(urlString, cb) { var self = this; cb = cb || logIfError; var filterIndex = 0; tryImportFilter(); function tryImportFilter() { var importFilter = importUrlFilters[filterIndex]; if (!importFilter) return cb(); importFilter.fn(urlString, callNextFilter); function callNextFilter(err, dlStream, filenameHintWithoutPath, size) { if (err || !dlStream) { if (err) { log.error(importFilter.name + " import filter error, skipping:", err.stack); } filterIndex += 1; tryImportFilter(); return; } self.importStream(dlStream, filenameHintWithoutPath, size, cb); } } function logIfError(err) { if (err) { log.error("Unable to import by URL.", err.stack, "URL:", urlString); } } }; Player.prototype.importNames = function(names, cb) { var self = this; var pend = new Pend(); var allDbFiles = []; names.forEach(function(name) { pend.go(function(cb) { youtubeSearch(name, self.googleApiKey, function(err, videoUrl) { if (err) { log.error("YouTube search error, skipping " + name + ": " + err.stack); cb(); return; } self.importUrl(videoUrl, function(err, dbFiles) { if (err) { log.error("Unable to import from YouTube: " + err.stack); } else if (!dbFiles) { log.error("Unrecognized YouTube URL: " + videoUrl); } else if (dbFiles.length > 0) { allDbFiles = allDbFiles.concat(dbFiles); } cb(); }); }); }); }); pend.wait(function() { cb(null, allDbFiles); }); }; Player.prototype.importStream = function(readStream, filenameHintWithoutPath, size, cb) { var self = this; var ext = path.extname(filenameHintWithoutPath); var tmpDir = path.join(self.musicDirectory, '.tmp'); var id = uuid(); var destPath = path.join(tmpDir, id + ext); var calledCallback = false; var writeStream = null; var progressTimer = null; var importEvent = { id: id, filenameHintWithoutPath: filenameHintWithoutPath, bytesWritten: 0, size: size, date: new Date(), }; readStream.on('error', cleanAndCb); self.importProgress[importEvent.id] = importEvent; self.emit('importStart', importEvent); mkdirp(tmpDir, function(err) { if (calledCallback) return; if (err) return cleanAndCb(err); writeStream = fs.createWriteStream(destPath); readStream.pipe(writeStream); progressTimer = setInterval(checkProgress, 100); writeStream.on('close', onClose); writeStream.on('error', cleanAndCb); function checkProgress() { importEvent.bytesWritten = writeStream.bytesWritten; self.maybeEmitImportProgress(); } function onClose(){ if (calledCallback) return; checkProgress(); self.importFile(destPath, filenameHintWithoutPath, function(err, dbFiles) { if (calledCallback) return; if (err) { cleanAndCb(err); } else { calledCallback = true; cleanTimer(); delete self.importProgress[importEvent.id]; self.emit('importEnd', importEvent); cb(null, dbFiles); } }); } }); function cleanTimer() { if (progressTimer) { clearInterval(progressTimer); progressTimer = null; } } function cleanAndCb(err) { if (writeStream) { fs.unlink(destPath, onUnlinkDone); writeStream = null; } cleanTimer(); if (calledCallback) return; calledCallback = true; delete self.importProgress[importEvent.id]; self.emit('importAbort', importEvent); cb(err); function onUnlinkDone(err) { if (err) { log.warn("Unable to clean up temp file:", err.stack); } } } }; Player.prototype.importFile = function(srcFullPath, filenameHintWithoutPath, cb) { var self = this; cb = cb || logIfError; var filterIndex = 0; log.debug("importFile open file:", srcFullPath); disableFsListenRef(self, tryImportFilter); function tryImportFilter() { var importFilter = importFileFilters[filterIndex]; if (!importFilter) return cleanAndCb(); importFilter.fn(self, srcFullPath, filenameHintWithoutPath, callNextFilter); function callNextFilter(err, dbFiles) { if (err || !dbFiles) { if (err) { log.debug(importFilter.name + " import filter error, skipping:", err.message); } filterIndex += 1; tryImportFilter(); return; } cleanAndCb(null, dbFiles); } } function cleanAndCb(err, dbFiles) { if (!dbFiles) { fs.unlink(srcFullPath, logIfUnlinkError); } disableFsListenUnref(self); cb(err, dbFiles); } function logIfUnlinkError(err) { if (err) { log.error("unable to unlink file:", err.stack); } } function logIfError(err) { if (err) { log.error("unable to import file:", err.stack); } } }; Player.prototype.maybeEmitImportProgress = function() { var now = new Date(); var passedTime = now - this.lastImportProgressEvent; if (passedTime > 500) { this.lastImportProgressEvent = now; this.emit("importProgress"); } }; Player.prototype.persistDirEntry = function(dirEntry, cb) { cb = cb || logIfError; this.db.put(LIBRARY_DIR_PREFIX + dirEntry.dirName, serializeDirEntry(dirEntry), cb); function logIfError(err) { if (err) { log.error("unable to persist db entry:", dirEntry, err.stack); } } }; Player.prototype.persistDbFile = function(dbFile, updateCmds) { this.libraryIndex.addTrack(dbFile); this.dbFilesByPath[dbFile.file] = dbFile; persistDbFile(dbFile, updateCmds); }; Player.prototype.persistOneDbFile = function(dbFile, cb) { cb = cb || logIfDbError; var updateCmds = []; this.persistDbFile(dbFile, updateCmds); this.db.batch(updateCmds, cb); }; Player.prototype.persistOption = function(name, value, cb) { this.db.put(PLAYER_KEY_PREFIX + name, JSON.stringify(value), cb || logIfError); function logIfError(err) { if (err) { log.error("unable to persist player option:", err.stack); } } }; Player.prototype.addToLibrary = function(args, cb) { var self = this; var relPath = args.relPath; var mtime = args.mtime; var fullPath = path.join(self.musicDirectory, relPath); log.debug("addToLibrary open file:", fullPath); groove.open(fullPath, function(err, file) { if (err) { self.invalidPaths[relPath] = err.message; cb(); return; } var dbFile = self.dbFilesByPath[relPath]; var filenameHintWithoutPath = path.basename(relPath); var newDbFile = grooveFileToDbFile(file, filenameHintWithoutPath, dbFile); newDbFile.file = relPath; newDbFile.mtime = mtime; var pend = new Pend(); pend.go(function(cb) { log.debug("addToLibrary close file:", file.filename); file.close(cb); }); pend.go(function(cb) { self.persistOneDbFile(newDbFile, function(err) { if (err) log.error("Error saving", relPath, "to db:", err.stack); cb(); }); }); self.emit('updateDb'); pend.wait(cb); }); }; Player.prototype.updateTags = function(obj) { var updateCmds = []; for (var key in obj) { var dbFile = this.libraryIndex.trackTable[key]; if (!dbFile) continue; var props = obj[key]; for (var propName in DB_PROPS) { var prop = DB_PROPS[propName]; if (! prop.clientCanModify) continue; if (! (propName in props)) continue; var parser = PROP_TYPE_PARSERS[prop.type]; dbFile[propName] = parser(props[propName]); } this.persistDbFile(dbFile, updateCmds); } if (updateCmds.length > 0) { this.db.batch(updateCmds, logIfDbError); this.emit('updateDb'); } }; Player.prototype.insertTracks = function(index, keys, tagAsRandom) { if (keys.length === 0) return []; if (index < 0) index = 0; if (index > this.tracksInOrder.length) index = this.tracksInOrder.length; var trackBeforeIndex = this.tracksInOrder[index - 1]; var trackAtIndex = this.tracksInOrder[index]; var prevSortKey = trackBeforeIndex ? trackBeforeIndex.sortKey : null; var nextSortKey = trackAtIndex ? trackAtIndex.sortKey : null; var items = {}; var ids = []; var sortKeys = keese(prevSortKey, nextSortKey, keys.length); keys.forEach(function(key, i) { var id = uuid(); var sortKey = sortKeys[i]; items[id] = { key: key, sortKey: sortKey, }; ids.push(id); }); this.addItems(items, tagAsRandom); return ids; }; Player.prototype.appendTracks = function(keys, tagAsRandom) { return this.insertTracks(this.tracksInOrder.length, keys, tagAsRandom); }; // items looks like {id: {key, sortKey}} Player.prototype.addItems = function(items, tagAsRandom) { var self = this; tagAsRandom = !!tagAsRandom; var updateCmds = []; for (var id in items) { var item = items[id]; var dbFile = self.libraryIndex.trackTable[item.key]; if (!dbFile) continue; dbFile.lastQueueDate = new Date(); self.persistDbFile(dbFile, updateCmds); var queueItem = { id: id, key: item.key, sortKey: item.sortKey, isRandom: tagAsRandom, grooveFile: null, pendingGrooveFile: false, deleted: false, }; self.playlist[id] = queueItem; persistQueueItem(queueItem, updateCmds); } if (updateCmds.length > 0) { self.db.batch(updateCmds, logIfDbError); playlistChanged(self); lazyReplayGainScanPlaylist(self); } }; Player.prototype.playlistCreate = function(id, name) { if (this.playlists[id]) { log.warn("tried to create playlist with same id as existing"); return; } var playlist = { id: id, name: name, mtime: new Date().getTime(), items: {}, }; this.playlists[playlist.id] = playlist; this.persistPlaylist(playlist); this.emit('playlistCreate', playlist); return playlist; }; Player.prototype.playlistRename = function(playlistId, newName) { var playlist = this.playlists[playlistId]; if (!playlist) return; playlist.name = newName; playlist.mtime = new Date().getTime(); this.persistPlaylist(playlist); this.emit('playlistUpdate', playlist); }; Player.prototype.playlistDelete = function(playlistIds) { var delCmds = []; for (var i = 0; i < playlistIds.length; i += 1) { var playlistId = playlistIds[i]; var playlist = this.playlists[playlistId]; if (!playlist) continue; for (var id in playlist.items) { var item = playlist.items[id]; if (!item) continue; delCmds.push({type: 'del', key: playlistItemKey(playlist, item)}); delete playlist.items[id]; } delCmds.push({type: 'del', key: playlistKey(playlist)}); delete this.playlists[playlistId]; } if (delCmds.length > 0) { this.db.batch(delCmds, logIfDbError); this.emit('playlistDelete'); } }; Player.prototype.playlistAddItems = function(playlistId, items) { var playlist = this.playlists[playlistId]; if (!playlist) return; var updateCmds = []; for (var id in items) { var item = items[id]; var dbFile = this.libraryIndex.trackTable[item.key]; if (!dbFile) continue; var playlistItem = { id: id, key: item.key, sortKey: item.sortKey, }; playlist.items[id] = playlistItem; updateCmds.push({ type: 'put', key: playlistItemKey(playlist, playlistItem), value: serializePlaylistItem(playlistItem), }); } if (updateCmds.length > 0) { playlist.mtime = new Date().getTime(); updateCmds.push({ type: 'put', key: playlistKey(playlist), value: serializePlaylist(playlist), }); this.db.batch(updateCmds, logIfDbError); this.emit('playlistUpdate', playlist); } }; Player.prototype.playlistRemoveItems = function(removals) { var updateCmds = []; for (var playlistId in removals) { var playlist = this.playlists[playlistId]; if (!playlist) continue; var ids = removals[playlistId]; var dirty = false; for (var i = 0; i < ids.length; i += 1) { var id = ids[i]; var item = playlist.items[id]; if (!item) continue; dirty = true; updateCmds.push({type: 'del', key: playlistItemKey(playlist, item)}); delete playlist.items[id]; } if (dirty) { playlist.mtime = new Date().getTime(); updateCmds.push({ type: 'put', key: playlistKey(playlist), value: serializePlaylist(playlist), }); } } if (updateCmds.length > 0) { this.db.batch(updateCmds, logIfDbError); this.emit('playlistUpdate'); } }; // items looks like {playlistId: {id: {sortKey}}} Player.prototype.playlistMoveItems = function(updates) { var updateCmds = []; for (var playlistId in updates) { var playlist = this.playlists[playlistId]; if (!playlist) continue; var playlistDirty = false; var update = updates[playlistId]; for (var id in update) { var playlistItem = playlist.items[id]; if (!playlistItem) continue; var updateItem = update[id]; playlistItem.sortKey = updateItem.sortKey; playlistDirty = true; updateCmds.push({ type: 'put', key: playlistItemKey(playlist, playlistItem), value: serializePlaylistItem(playlistItem), }); } if (playlistDirty) { playlist.mtime = new Date().getTime(); updateCmds.push({ type: 'put', key: playlistKey(playlist), value: serializePlaylist(playlist), }); } } if (updateCmds.length > 0) { this.db.batch(updateCmds, logIfDbError); this.emit('playlistUpdate'); } }; Player.prototype.persistPlaylist = function(playlist, cb) { cb = cb || logIfDbError; var key = playlistKey(playlist); var payload = serializePlaylist(playlist); this.db.put(key, payload, cb); }; Player.prototype.labelCreate = function(id, name) { if (id in this.libraryIndex.labelTable) { log.warn("tried to create label that already exists"); return; } var color = labelColors[Math.floor(Math.random() * labelColors.length)]; var labelEntry = {id: id, name: name, color: color}; this.libraryIndex.addLabel(labelEntry); var key = LABEL_KEY_PREFIX + id; this.db.put(key, JSON.stringify(labelEntry), logIfDbError); this.emit('labelCreate'); }; Player.prototype.labelRename = function(id, name) { var labelEntry = this.libraryIndex.labelTable[id]; if (!labelEntry) return; labelEntry.name = name; this.libraryIndex.addLabel(labelEntry); var key = LABEL_KEY_PREFIX + id; this.db.put(key, JSON.stringify(labelEntry), logIfDbError); this.emit('labelRename'); }; Player.prototype.labelColorUpdate = function(id, color) { var labelEntry = this.libraryIndex.labelTable[id]; if (!labelEntry) return; labelEntry.color = color; this.libraryIndex.addLabel(labelEntry); var key = LABEL_KEY_PREFIX + id; this.db.put(key, JSON.stringify(labelEntry), logIfDbError); this.emit('labelColorUpdate'); }; Player.prototype.labelDelete = function(ids) { var updateCmds = []; var libraryChanged = false; for (var i = 0; i < ids.length; i++) { var labelId = ids[i]; if (!(labelId in this.libraryIndex.labelTable)) continue; this.libraryIndex.removeLabel(labelId); var key = LABEL_KEY_PREFIX + labelId; updateCmds.push({type: 'del', key: key}); // clean out references from the library var files = this.dbFilesByLabel[labelId]; for (var fileId in files) { var dbFile = files[fileId]; delete dbFile.labels[labelId]; persistDbFile(dbFile, updateCmds); libraryChanged = true; } delete this.dbFilesByLabel[labelId]; } if (updateCmds.length === 0) return; this.db.batch(updateCmds, logIfDbError); if (libraryChanged) { this.emit('updateDb'); } this.emit('labelDelete'); }; Player.prototype.labelAdd = function(additions) { this.changeLabels(additions, true); }; Player.prototype.labelRemove = function(removals) { this.changeLabels(removals, false); }; Player.prototype.changeLabels = function(changes, isAdd) { var self = this; var updateCmds = []; for (var id in changes) { var labelIds = changes[id]; var dbFile = this.libraryIndex.trackTable[id]; if (!dbFile) continue; if (labelIds.length === 0) continue; var changedTrack = false; for (var i = 0; i < labelIds.length; i++) { var labelId = labelIds[i]; var filesByThisLabel = self.dbFilesByLabel[labelId]; if (isAdd) { if (labelId in dbFile.labels) continue; // already got it dbFile.labels[labelId] = 1; if (filesByThisLabel == null) filesByThisLabel = self.dbFilesByLabel[labelId] = {}; filesByThisLabel[dbFile.key] = dbFile; } else { if (!(labelId in dbFile.labels)) continue; // already gone delete dbFile.labels[labelId]; delete filesByThisLabel[dbFile.key]; } changedTrack = true; } if (changedTrack) { this.persistDbFile(dbFile, updateCmds); } } if (updateCmds.length === 0) return; this.db.batch(updateCmds, logIfDbError); this.emit('updateDb'); }; Player.prototype.clearQueue = function() { this.removeQueueItems(Object.keys(this.playlist)); }; Player.prototype.removeAllRandomQueueItems = function() { var idsToRemove = []; for (var i = 0; i < this.tracksInOrder.length; i += 1) { var track = this.tracksInOrder[i]; if (track.isRandom && track !== this.currentTrack) { idsToRemove.push(track.id); } } return this.removeQueueItems(idsToRemove); }; Player.prototype.shufflePlaylist = function() { if (this.tracksInOrder.length === 0) return; if (this.autoDjOn) return this.removeAllRandomQueueItems(); var sortKeys = this.tracksInOrder.map(function(track) { return track.sortKey; }); shuffle(sortKeys); // fix sortKey and index properties var updateCmds = []; for (var i = 0; i < this.tracksInOrder.length; i += 1) { var track = this.tracksInOrder[i]; track.index = i; track.sortKey = sortKeys[i]; persistQueueItem(track, updateCmds); } this.db.batch(updateCmds, logIfDbError); playlistChanged(this); }; Player.prototype.removeQueueItems = function(ids) { if (ids.length === 0) return; var delCmds = []; var currentTrackChanged = false; for (var i = 0; i < ids.length; i += 1) { var id = ids[i]; var item = this.playlist[id]; if (!item) continue; delCmds.push({type: 'del', key: QUEUE_KEY_PREFIX + id}); if (item.grooveFile) this.playlistItemDeleteQueue.push(item); if (item === this.currentTrack) { var nextPos = this.currentTrack.index + 1; for (;;) { var nextTrack = this.tracksInOrder[nextPos]; var nextTrackId = nextTrack && nextTrack.id; this.currentTrack = nextTrackId && this.playlist[nextTrack.id]; if (!this.currentTrack && nextPos < this.tracksInOrder.length) { nextPos += 1; continue; } break; } if (this.currentTrack) { this.seekRequestPos = 0; } currentTrackChanged = true; } delete this.playlist[id]; } if (delCmds.length > 0) this.db.batch(delCmds, logIfDbError); playlistChanged(this); if (currentTrackChanged) { this.currentTrackChanged(); } }; // items looks like {id: {sortKey}} Player.prototype.moveQueueItems = function(items) { var updateCmds = []; for (var id in items) { var track = this.playlist[id]; if (!track) continue; // race conditions, etc. track.sortKey = items[id].sortKey; persistQueueItem(track, updateCmds); } if (updateCmds.length > 0) { this.db.batch(updateCmds, logIfDbError); playlistChanged(this); } }; Player.prototype.moveRangeToPos = function(startPos, endPos, toPos) { var ids = []; for (var i = startPos; i < endPos; i += 1) { var track = this.tracksInOrder[i]; if (!track) continue; ids.push(track.id); } this.moveIdsToPos(ids, toPos); }; Player.prototype.moveIdsToPos = function(ids, toPos) { var trackBeforeIndex = this.tracksInOrder[toPos - 1]; var trackAtIndex = this.tracksInOrder[toPos]; var prevSortKey = trackBeforeIndex ? trackBeforeIndex.sortKey : null; var nextSortKey = trackAtIndex ? trackAtIndex.sortKey : null; var sortKeys = keese(prevSortKey, nextSortKey, ids.length); var updateCmds = []; for (var i = 0; i < ids.length; i += 1) { var id = ids[i]; var queueItem = this.playlist[id]; if (!queueItem) continue; queueItem.sortKey = sortKeys[i]; persistQueueItem(queueItem, updateCmds); } if (updateCmds.length > 0) { this.db.batch(updateCmds, logIfDbError); playlistChanged(this); } }; Player.prototype.pause = function() { if (!this.isPlaying) return; this.isPlaying = false; this.pausedTime = (new Date() - this.trackStartDate) / 1000; this.groovePlaylist.pause(); this.cancelDetachEncoderTimeout(); playlistChanged(this); this.currentTrackChanged(); }; Player.prototype.play = function() { if (!this.currentTrack) { this.currentTrack = this.tracksInOrder[0]; } else if (!this.isPlaying) { this.trackStartDate = new Date(new Date() - this.pausedTime * 1000); } this.groovePlaylist.play(); this.startDetachEncoderTimeout(); this.isPlaying = true; playlistChanged(this); this.currentTrackChanged(); }; // This function should be avoided in favor of seek. Note that it is called by // some MPD protocol commands, because the MPD protocol is stupid. Player.prototype.seekToIndex = function(index, pos) { var track = this.tracksInOrder[index]; if (!track) return null; this.currentTrack = track; this.seekRequestPos = pos; playlistChanged(this); this.currentTrackChanged(); return track; }; Player.prototype.seek = function(id, pos) { var track = this.playlist[id]; if (!track) return null; this.currentTrack = this.playlist[id]; this.seekRequestPos = pos; playlistChanged(this); this.currentTrackChanged(); return track; }; Player.prototype.next = function() { return this.skipBy(1); }; Player.prototype.prev = function() { return this.skipBy(-1); }; Player.prototype.skipBy = function(amt) { var defaultIndex = amt > 0 ? -1 : this.tracksInOrder.length; var currentIndex = this.currentTrack ? this.currentTrack.index : defaultIndex; var newIndex = currentIndex + amt; return this.seekToIndex(newIndex, 0); }; Player.prototype.setRepeat = function(value) { value = Math.floor(value); if (value !== Player.REPEAT_ONE && value !== Player.REPEAT_ALL && value !== Player.REPEAT_OFF) { return; } if (value === this.repeat) return; this.repeat = value; this.persistOption('repeat', this.repeat); playlistChanged(this); this.emit('repeatUpdate'); }; Player.prototype.setAutoDjOn = function(value) { value = !!value; if (value === this.autoDjOn) return; this.autoDjOn = value; this.persistOption('autoDjOn', this.autoDjOn); this.emit('autoDjOn'); this.checkAutoDj(); }; Player.prototype.setAutoDjHistorySize = function(value) { value = Math.floor(value); if (value === this.autoDjHistorySize) return; this.autoDjHistorySize = value; this.persistOption('autoDjHistorySize', this.autoDjHistorySize); this.emit('autoDjHistorySize'); this.checkAutoDj(); }; Player.prototype.setAutoDjFutureSize = function(value) { value = Math.floor(value); if (value === this.autoDjFutureSize) return; this.autoDjFutureSize = value; this.persistOption('autoDjFutureSize', this.autoDjFutureSize); this.emit('autoDjFutureSize'); this.checkAutoDj(); }; Player.prototype.stop = function() { this.isPlaying = false; this.cancelDetachEncoderTimeout(); this.groovePlaylist.pause(); this.seekRequestPos = 0; this.pausedTime = 0; playlistChanged(this); }; Player.prototype.clearEncodedBuffer = function() { while (this.recentBuffers.length > 0) { this.recentBuffers.shift(); } }; Player.prototype.getSuggestedPath = function(track, filenameHint) { var p = ""; if (track.albumArtistName) { p = path.join(p, safePath(track.albumArtistName)); } else if (track.compilation) { p = path.join(p, safePath(this.libraryIndex.variousArtistsName)); } else if (track.artistName) { p = path.join(p, safePath(track.artistName)); } if (track.albumName) { p = path.join(p, safePath(track.albumName)); } var t = ""; if (track.track != null) { t += safePath(zfill(track.track, 2)) + " "; } t += safePath(track.name + path.extname(filenameHint)); return path.join(p, t); }; Player.prototype.queueScan = function(dbFile) { var self = this; var scanKey, scanType; if (dbFile.albumName) { scanType = 'album'; scanKey = self.libraryIndex.getAlbumKey(dbFile); } else { scanType = 'track'; scanKey = dbFile.key; } if (self.scanQueue.idInQueue(scanKey)) { return; } self.scanQueue.add(scanKey, { type: scanType, key: scanKey, }); }; Player.prototype.performScan = function(args, cb) { var self = this; var scanType = args.type; var scanKey = args.key; // build list of files we want to open var dbFilesToOpen; if (scanType === 'album') { var albumKey = scanKey; self.libraryIndex.rebuildTracks(); var album = self.libraryIndex.albumTable[albumKey]; if (!album) { log.warn("wanted to scan album with key", JSON.stringify(albumKey), "but no longer exists."); cb(); return; } log.debug("Scanning album for loudness:", JSON.stringify(albumKey)); dbFilesToOpen = album.trackList; } else if (scanType === 'track') { var trackKey = scanKey; var dbFile = self.libraryIndex.trackTable[trackKey]; if (!dbFile) { log.warn("wanted to scan track with key", JSON.stringify(trackKey), "but no longer exists."); cb(); return; } log.debug("Scanning track for loudness:", JSON.stringify(trackKey)); dbFilesToOpen = [dbFile]; } else { throw new Error("unexpected scan type: " + scanType); } // open all the files in the list var pend = new Pend(); // we're already doing multiple parallel scans. within each scan let's // read one thing at a time to avoid slamming the system. pend.max = 1; var grooveFileList = []; var files = {}; dbFilesToOpen.forEach(function(dbFile) { pend.go(function(cb) { var fullPath = path.join(self.musicDirectory, dbFile.file); log.debug("performScan open file:", fullPath); groove.open(fullPath, function(err, file) { if (err) { log.error("Error opening", fullPath, "in order to scan:", err.stack); } else { var fileInfo; files[file.id] = fileInfo = { dbFile: dbFile, loudnessDone: false, fingerprintDone: false, }; self.ongoingScans[dbFile.key] = fileInfo; grooveFileList.push(file); } cb(); }); }); }); var scanPlaylist; var endOfPlaylistPend = new Pend(); var scanDetector; var scanDetectorAttached = false; var endOfDetectorCb; var scanFingerprinter; var scanFingerprinterAttached = false; var endOfFingerprinterCb; pend.wait(function() { // emit this because we updated ongoingScans self.emit('scanProgress'); scanPlaylist = groove.createPlaylist(); scanPlaylist.setFillMode(groove.ANY_SINK_FULL); scanDetector = groove.createLoudnessDetector(); scanFingerprinter = groove.createFingerprinter(); scanDetector.on('info', onLoudnessInfo); scanFingerprinter.on('info', onFingerprinterInfo); var pend = new Pend(); pend.go(attachLoudnessDetector); pend.go(attachFingerprinter); pend.wait(onEverythingAttached); }); function onEverythingAttached(err) { if (err) { log.error("Error attaching:", err.stack); cleanupAndCb(); return; } grooveFileList.forEach(function(file) { scanPlaylist.insert(file); }); endOfPlaylistPend.wait(function() { for (var fileId in files) { var fileInfo = files[fileId]; var dbFile = fileInfo.dbFile; self.persistOneDbFile(dbFile); self.emit('scanComplete', dbFile); } cleanupAndCb(); }); } function attachLoudnessDetector(cb) { scanDetector.attach(scanPlaylist, function(err) { if (err) return cb(err); scanDetectorAttached = true; endOfPlaylistPend.go(function(cb) { endOfDetectorCb = cb; }); cb(); }); } function attachFingerprinter(cb) { scanFingerprinter.attach(scanPlaylist, function(err) { if (err) return cb(err); scanFingerprinterAttached = true; endOfPlaylistPend.go(function(cb) { endOfFingerprinterCb = cb; }); cb(); }); } function onLoudnessInfo() { var info; while (info = scanDetector.getInfo()) { var gain = groove.loudnessToReplayGain(info.loudness); var dbFile; var fileInfo; if (info.item) { fileInfo = files[info.item.file.id]; fileInfo.loudnessDone = true; dbFile = fileInfo.dbFile; log.info("loudness scan file complete:", dbFile.name, "gain", gain, "duration", info.duration); dbFile.replayGainTrackGain = gain; dbFile.replayGainTrackPeak = info.peak; dbFile.duration = info.duration; checkUpdateGroovePlaylist(self); self.emit('scanProgress'); } else { log.debug("loudness scan complete:", JSON.stringify(scanKey), "gain", gain); for (var fileId in files) { fileInfo = files[fileId]; dbFile = fileInfo.dbFile; dbFile.replayGainAlbumGain = gain; dbFile.replayGainAlbumPeak = info.peak; } checkUpdateGroovePlaylist(self); if (endOfDetectorCb) { endOfDetectorCb(); endOfDetectorCb = null; } return; } } } function onFingerprinterInfo() { var info; while (info = scanFingerprinter.getInfo()) { if (info.item) { var fileInfo = files[info.item.file.id]; fileInfo.fingerprintDone = true; var dbFile = fileInfo.dbFile; log.info("fingerprint scan file complete:", dbFile.name); dbFile.fingerprint = info.fingerprint; self.emit('scanProgress'); } else { log.debug("fingerprint scan complete:", JSON.stringify(scanKey)); if (endOfFingerprinterCb) { endOfFingerprinterCb(); endOfFingerprinterCb = null; } return; } } } function cleanupAndCb() { grooveFileList.forEach(function(file) { pend.go(function(cb) { var fileInfo = files[file.id]; var dbFile = fileInfo.dbFile; delete self.ongoingScans[dbFile.key]; log.debug("performScan close file:", file.filename); file.close(cb); }); }); if (scanDetectorAttached) pend.go(detachLoudnessScanner); if (scanFingerprinterAttached) pend.go(detachFingerprinter); pend.wait(function(err) { // emit this because we changed ongoingScans above self.emit('scanProgress'); cb(err); }); } function detachLoudnessScanner(cb) { scanDetector.detach(cb); } function detachFingerprinter(cb) { scanFingerprinter.detach(cb); } }; Player.prototype.checkAutoDj = function() { var self = this; if (!self.autoDjOn) return; // if no track is playing, assume the first track is about to be var currentIndex = self.currentTrack ? self.currentTrack.index : 0; var deleteCount = Math.max(currentIndex - self.autoDjHistorySize, 0); if (self.autoDjHistorySize < 0) deleteCount = 0; var addCount = Math.max(self.autoDjFutureSize + 1 - (self.tracksInOrder.length - currentIndex), 0); var idsToDelete = []; for (var i = 0; i < deleteCount; i += 1) { idsToDelete.push(self.tracksInOrder[i].id); } var keys = getRandomSongKeys(addCount); self.removeQueueItems(idsToDelete); self.appendTracks(keys, true); function getRandomSongKeys(count) { if (count === 0) return []; var neverQueued = []; var sometimesQueued = []; for (var key in self.libraryIndex.trackTable) { var dbFile = self.libraryIndex.trackTable[key]; if (dbFile.lastQueueDate == null) { neverQueued.push(dbFile); } else { sometimesQueued.push(dbFile); } } // backwards by time sometimesQueued.sort(function(a, b) { return b.lastQueueDate - a.lastQueueDate; }); // distribution is a triangle for ever queued, and a rectangle for never queued // ___ // /| | // / | | // /__|_| var maxWeight = sometimesQueued.length; var triangleArea = Math.floor(maxWeight * maxWeight / 2); if (maxWeight === 0) maxWeight = 1; var rectangleArea = maxWeight * neverQueued.length; var totalSize = triangleArea + rectangleArea; if (totalSize === 0) return []; // decode indexes through the distribution shape var keys = []; for (var i = 0; i < count; i += 1) { var index = Math.random() * totalSize; if (index < triangleArea) { // triangle keys.push(sometimesQueued[Math.floor(Math.sqrt(index))].key); } else { keys.push(neverQueued[Math.floor((index - triangleArea) / maxWeight)].key); } } return keys; } }; Player.prototype.currentTrackChanged = function() { this.persistCurrentTrack(); this.emit('currentTrack'); }; Player.prototype.persistCurrentTrack = function(cb) { // save the current track and time to db var currentTrackInfo = { id: this.currentTrack && this.currentTrack.id, pos: this.getCurPos(), }; this.persistOption('currentTrackInfo', currentTrackInfo, cb); }; Player.prototype.sortAndQueueTracks = function(tracks) { // given an array of tracks, sort them according to the library sorting // and then queue them in the best place if (!tracks.length) return; var sortedTracks = sortTracks(tracks); this.queueTracks(sortedTracks); }; Player.prototype.sortAndQueueTracksInPlaylist = function(playlist, tracks, previousKey, nextKey) { if (!tracks.length) return; var sortedTracks = sortTracks(tracks); var items = {}; var sortKeys = keese(previousKey, nextKey, tracks.length); for (var i = 0; i < tracks.length; i += 1) { var track = tracks[i]; var sortKey = sortKeys[i]; var id = uuid(); items[id] = { key: track.key, sortKey: sortKey, }; } this.playlistAddItems(playlist.id, items); }; Player.prototype.queueTrackKeys = function(trackKeys, previousKey, nextKey) { if (!trackKeys.length) return; if (previousKey == null && nextKey == null) { var defaultPos = this.getDefaultQueuePosition(); previousKey = defaultPos.previousKey; nextKey = defaultPos.nextKey; } var items = {}; var sortKeys = keese(previousKey, nextKey, trackKeys.length); for (var i = 0; i < trackKeys.length; i += 1) { var trackKey = trackKeys[i]; var sortKey = sortKeys[i]; var id = uuid(); items[id] = { key: trackKey, sortKey: sortKey, }; } this.addItems(items, false); }; Player.prototype.queueTracks = function(tracks, previousKey, nextKey) { // given an array of tracks, and a previous sort key and a next sort key, // call addItems correctly var trackKeys = tracks.map(function(track) { return track.key; }).filter(function(key) { return !!key; }); return this.queueTrackKeys(trackKeys, previousKey, nextKey); }; Player.prototype.getDefaultQueuePosition = function() { var previousKey = this.currentTrack && this.currentTrack.sortKey; var nextKey = null; var startPos = this.currentTrack ? this.currentTrack.index + 1 : 0; for (var i = startPos; i < this.tracksInOrder.length; i += 1) { var track = this.tracksInOrder[i]; var sortKey = track.sortKey; if (track.isRandom) { nextKey = sortKey; break; } previousKey = sortKey; } return { previousKey: previousKey, nextKey: nextKey }; }; function persistDbFile(dbFile, updateCmds) { updateCmds.push({ type: 'put', key: LIBRARY_KEY_PREFIX + dbFile.key, value: serializeFileData(dbFile), }); } function persistQueueItem(item, updateCmds) { updateCmds.push({ type: 'put', key: QUEUE_KEY_PREFIX + item.id, value: serializeQueueItem(item), }); } function onAddOrChange(self, relPath, fileMtime, cb) { cb = cb || logIfError; // check the mtime against the mtime of the same file in the db var dbFile = self.dbFilesByPath[relPath]; if (dbFile) { var dbMtime = dbFile.mtime; if (dbMtime >= fileMtime) { // the info we have in our db for this file is fresh cb(null, dbFile); return; } } self.addQueue.add(relPath, { relPath: relPath, mtime: fileMtime, }); self.addQueue.waitForId(relPath, function(err) { var dbFile = self.dbFilesByPath[relPath]; cb(err, dbFile); }); function logIfError(err) { if (err) { log.error("Unable to add to queue:", err.stack); } } } function checkPlayCount(self) { if (self.isPlaying && !self.previousIsPlaying) { self.playingStart = new Date(new Date() - self.playingTime); self.previousIsPlaying = true; } self.playingTime = new Date() - self.playingStart; if (self.currentTrack === self.lastPlayingItem) return; if (self.lastPlayingItem) { var dbFile = self.libraryIndex.trackTable[self.lastPlayingItem.key]; if (dbFile) { var minAmt = 15 * 1000; var maxAmt = 4 * 60 * 1000; var halfAmt = dbFile.duration / 2 * 1000; if (self.playingTime >= minAmt && (self.playingTime >= maxAmt || self.playingTime >= halfAmt)) { dbFile.playCount += 1; self.persistOneDbFile(dbFile); self.emit('play', self.lastPlayingItem, dbFile, self.playingStart); self.emit('updateDb'); } } } self.lastPlayingItem = self.currentTrack; self.previousIsPlaying = self.isPlaying; self.playingStart = new Date(); self.playingTime = 0; } function disableFsListenRef(self, fn) { self.disableFsRefCount += 1; if (self.disableFsRefCount === 1) { log.debug("pause dirScanQueue"); self.dirScanQueue.setPause(true); self.dirScanQueue.waitForProcessing(fn); } else { fn(); } } function disableFsListenUnref(self) { self.disableFsRefCount -= 1; if (self.disableFsRefCount === 0) { log.debug("unpause dirScanQueue"); self.dirScanQueue.setPause(false); } else if (self.disableFsRefCount < 0) { throw new Error("disableFsListenUnref called too many times"); } } function operatorCompare(a, b) { return a < b ? -1 : a > b ? 1 : 0; } function disambiguateSortKeys(self) { var previousUniqueKey = null; var previousKey = null; self.tracksInOrder.forEach(function(track, i) { if (track.sortKey === previousKey) { // move the repeat back track.sortKey = keese(previousUniqueKey, track.sortKey); previousUniqueKey = track.sortKey; } else { previousUniqueKey = previousKey; previousKey = track.sortKey; } }); } // generate self.tracksInOrder from self.playlist function cacheTracksArray(self) { self.tracksInOrder = Object.keys(self.playlist).map(trackById); self.tracksInOrder.sort(asc); self.tracksInOrder.forEach(function(track, index) { track.index = index; }); function asc(a, b) { return operatorCompare(a.sortKey, b.sortKey); } function trackById(id) { return self.playlist[id]; } } function lazyReplayGainScanPlaylist(self) { // clear the queue since we're going to completely rebuild it anyway // this allows the following priority code to work. self.scanQueue.clear(); // prioritize the currently playing track, followed by the next tracks, // followed by the previous tracks var albumGain = {}; var start1 = self.currentTrack ? self.currentTrack.index : 0; var i; for (i = start1; i < self.tracksInOrder.length; i += 1) { checkScan(self.tracksInOrder[i]); } for (i = 0; i < start1; i += 1) { checkScan(self.tracksInOrder[i]); } function checkScan(track) { var dbFile = self.libraryIndex.trackTable[track.key]; if (!dbFile) return; var albumKey = self.libraryIndex.getAlbumKey(dbFile); var needScan = dbFile.fingerprint == null || dbFile.replayGainAlbumGain == null || dbFile.replayGainTrackGain == null || (dbFile.albumName && albumGain[albumKey] && albumGain[albumKey] !== dbFile.replayGainAlbumGain); if (needScan) { self.queueScan(dbFile); } else { albumGain[albumKey] = dbFile.replayGainAlbumGain; } } } function playlistChanged(self) { cacheTracksArray(self); disambiguateSortKeys(self); if (self.currentTrack) { self.tracksInOrder.forEach(function(track, index) { var prevDiff = self.currentTrack.index - index; var nextDiff = index - self.currentTrack.index; var withinPrev = prevDiff <= PREV_FILE_COUNT && prevDiff >= 0; var withinNext = nextDiff <= NEXT_FILE_COUNT && nextDiff >= 0; var shouldHaveGrooveFile = withinPrev || withinNext; var hasGrooveFile = track.grooveFile != null || track.pendingGrooveFile; if (hasGrooveFile && !shouldHaveGrooveFile) { self.playlistItemDeleteQueue.push(track); } else if (!hasGrooveFile && shouldHaveGrooveFile) { preloadFile(self, track); } }); } else { self.isPlaying = false; self.cancelDetachEncoderTimeout(); self.trackStartDate = null; self.pausedTime = 0; } checkUpdateGroovePlaylist(self); performGrooveFileDeletes(self); self.checkAutoDj(); checkPlayCount(self); self.emit('queueUpdate'); } function performGrooveFileDeletes(self) { while (self.playlistItemDeleteQueue.length) { var item = self.playlistItemDeleteQueue.shift(); // we set this so that any callbacks that return which were trying to // set the grooveItem can check if the item got deleted item.deleted = true; if (!item.grooveFile) continue; log.debug("performGrooveFileDeletes close file:", item.grooveFile.filename); var grooveFile = item.grooveFile; item.grooveFile = null; closeFile(grooveFile); } } function preloadFile(self, track) { var relPath = self.libraryIndex.trackTable[track.key].file; var fullPath = path.join(self.musicDirectory, relPath); track.pendingGrooveFile = true; log.debug("preloadFile open file:", fullPath); // set this so that we know we want the file preloaded track.deleted = false; groove.open(fullPath, function(err, file) { track.pendingGrooveFile = false; if (err) { log.error("Error opening", relPath, err.stack); return; } if (track.deleted) { log.debug("preloadFile close file (already deleted):", file.filename); closeFile(file); return; } track.grooveFile = file; checkUpdateGroovePlaylist(self); }); } function checkUpdateGroovePlaylist(self) { if (!self.currentTrack) { self.groovePlaylist.clear(); self.grooveItems = {}; return; } var groovePlaylist = self.groovePlaylist.items(); var playHead = self.groovePlayer.position(); var playHeadItemId = playHead.item && playHead.item.id; var groovePlIndex = 0; var grooveItem; if (playHeadItemId) { while (groovePlIndex < groovePlaylist.length) { grooveItem = groovePlaylist[groovePlIndex]; if (grooveItem.id === playHeadItemId) break; // this groove playlist item is before the current playhead. delete it! self.groovePlaylist.remove(grooveItem); delete self.grooveItems[grooveItem.id]; groovePlIndex += 1; } } var plItemIndex = self.currentTrack.index; var plTrack; var currentGrooveItem = null; // might be different than playHead.item var groovePlItemCount = 0; var gainAndPeak; while (groovePlIndex < groovePlaylist.length) { grooveItem = groovePlaylist[groovePlIndex]; var grooveTrack = self.grooveItems[grooveItem.id]; // now we have deleted all items before the current track. we are now // comparing the libgroove playlist and the groovebasin playlist // side by side. plTrack = self.tracksInOrder[plItemIndex]; if (grooveTrack === plTrack) { // if they're the same, we advance // but we might have to correct the gain gainAndPeak = calcGainAndPeak(plTrack); self.groovePlaylist.setItemGain(grooveItem, gainAndPeak.gain); self.groovePlaylist.setItemPeak(grooveItem, gainAndPeak.peak); currentGrooveItem = currentGrooveItem || grooveItem; groovePlIndex += 1; incrementPlIndex(); continue; } // this groove track is wrong. delete it. self.groovePlaylist.remove(grooveItem); delete self.grooveItems[grooveItem.id]; groovePlIndex += 1; } // we still need to add more libgroove playlist items, but this one has // not yet finished loading from disk. We must take note of this so that // if we receive the end of playlist sentinel, we start playback again // once this track has finished loading. self.dontBelieveTheEndOfPlaylistSentinelItsATrap = true; while (groovePlItemCount < NEXT_FILE_COUNT) { plTrack = self.tracksInOrder[plItemIndex]; if (!plTrack) { // we hit the end of the groove basin playlist. we're done adding tracks // to the libgroove playlist. self.dontBelieveTheEndOfPlaylistSentinelItsATrap = false; break; } if (!plTrack.grooveFile) { break; } // compute the gain adjustment gainAndPeak = calcGainAndPeak(plTrack); grooveItem = self.groovePlaylist.insert(plTrack.grooveFile, gainAndPeak.gain, gainAndPeak.peak); self.grooveItems[grooveItem.id] = plTrack; currentGrooveItem = currentGrooveItem || grooveItem; incrementPlIndex(); } if (currentGrooveItem && self.seekRequestPos >= 0) { var seekPos = self.seekRequestPos; // we want to clear encoded buffers after the seek completes, e.g. after // we get the end of playlist sentinel self.clearEncodedBuffer(); self.queueClearEncodedBuffers = true; self.groovePlaylist.seek(currentGrooveItem, seekPos); self.seekRequestPos = -1; if (self.isPlaying) { var nowMs = (new Date()).getTime(); var posMs = seekPos * 1000; self.trackStartDate = new Date(nowMs - posMs); } else { self.pausedTime = seekPos; } self.currentTrackChanged(); } function calcGainAndPeak(plTrack) { // if the previous item is the previous item from the album, or the // next item is the next item from the album, use album replaygain. // else, use track replaygain. var dbFile = self.libraryIndex.trackTable[plTrack.key]; var albumMode = albumInfoMatch(-1) || albumInfoMatch(1); var gain = REPLAYGAIN_PREAMP; var peak; if (dbFile.replayGainAlbumGain != null && albumMode) { gain *= dBToFloat(dbFile.replayGainAlbumGain); peak = dbFile.replayGainAlbumPeak || 1.0; } else if (dbFile.replayGainTrackGain != null) { gain *= dBToFloat(dbFile.replayGainTrackGain); peak = dbFile.replayGainTrackPeak || 1.0; } else { gain *= REPLAYGAIN_DEFAULT; peak = 1.0; } return {gain: gain, peak: peak}; function albumInfoMatch(dir) { var otherPlTrack = self.tracksInOrder[plTrack.index + dir]; if (!otherPlTrack) return false; var otherDbFile = self.libraryIndex.trackTable[otherPlTrack.key]; if (!otherDbFile) return false; var albumMatch = self.libraryIndex.getAlbumKey(dbFile) === self.libraryIndex.getAlbumKey(otherDbFile); if (!albumMatch) return false; // if there are no track numbers then it's hardly an album, is it? if (dbFile.track == null || otherDbFile.track == null) { return false; } var trackMatch = dbFile.track + dir === otherDbFile.track; if (!trackMatch) return false; return true; } } function incrementPlIndex() { groovePlItemCount += 1; if (self.repeat !== Player.REPEAT_ONE) { plItemIndex += 1; if (self.repeat === Player.REPEAT_ALL && plItemIndex >= self.tracksInOrder.length) { plItemIndex = 0; } } } } function isFileIgnored(basename) { return (/^\./).test(basename) || (/~$/).test(basename); } function isExtensionIgnored(self, extName) { var extNameLower = extName.toLowerCase(); for (var i = 0; i < self.ignoreExtensions.length; i += 1) { if (self.ignoreExtensions[i] === extNameLower) { return true; } } return false; } function deserializeFileData(dataStr) { var dbFile = JSON.parse(dataStr); for (var propName in DB_PROPS) { var propInfo = DB_PROPS[propName]; if (!propInfo) continue; var parser = PROP_TYPE_PARSERS[propInfo.type]; dbFile[propName] = parser(dbFile[propName]); } return dbFile; } function serializeQueueItem(item) { return JSON.stringify({ id: item.id, key: item.key, sortKey: item.sortKey, isRandom: item.isRandom, }); } function serializePlaylistItem(item) { return JSON.stringify({ id: item.id, key: item.key, sortKey: item.sortKey, }); } function trackWithoutIndex(category, dbFile) { var out = {}; for (var propName in DB_PROPS) { var prop = DB_PROPS[propName]; if (!prop[category]) continue; // save space by leaving out null and undefined values var value = dbFile[propName]; if (value == null) continue; if (prop.type === 'set') { out[propName] = copySet(value); } else { out[propName] = value; } } return out; } function serializeFileData(dbFile) { return JSON.stringify(trackWithoutIndex('db', dbFile)); } function serializeDirEntry(dirEntry) { return JSON.stringify({ dirName: dirEntry.dirName, entries: dirEntry.entries, dirEntries: dirEntry.dirEntries, mtime: dirEntry.mtime, }); } function filenameWithoutExt(filename) { var ext = path.extname(filename); return filename.substring(0, filename.length - ext.length); } function closeFile(file) { file.close(function(err) { if (err) { log.error("Error closing", file, err.stack); } }); } function parseTrackString(trackStr) { if (!trackStr) return {}; var parts = trackStr.split('/'); if (parts.length > 1) { return { value: parseIntOrNull(parts[0]), total: parseIntOrNull(parts[1]), }; } return { value: parseIntOrNull(parts[0]), }; } function parseIntOrNull(n) { n = parseInt(n, 10); if (isNaN(n)) return null; return n; } function parseFloatOrNull(n) { n = parseFloat(n); if (isNaN(n)) return null; return n; } function grooveFileToDbFile(file, filenameHintWithoutPath, object) { object = object || {key: uuid()}; var parsedTrack = parseTrackString(file.getMetadata("track")); var parsedDisc = parseTrackString( file.getMetadata("disc") || file.getMetadata("TPA") || file.getMetadata("TPOS")); object.name = (file.getMetadata("title") || filenameWithoutExt(filenameHintWithoutPath) || "").trim(); object.artistName = (file.getMetadata("artist") || "").trim(); object.composerName = (file.getMetadata("composer") || file.getMetadata("TCM") || "").trim(); object.performerName = (file.getMetadata("performer") || "").trim(); object.albumArtistName = (file.getMetadata("album_artist") || "").trim(); object.albumName = (file.getMetadata("album") || "").trim(); object.compilation = !!(parseInt(file.getMetadata("TCP"), 10) || parseInt(file.getMetadata("TCMP"), 10) || file.getMetadata("COMPILATION") || file.getMetadata("Compilation") || file.getMetadata("cpil") || file.getMetadata("WM/IsCompilation")); object.track = parsedTrack.value; object.trackCount = parsedTrack.total; object.disc = parsedDisc.value; object.discCount = parsedDisc.total; object.duration = file.duration(); object.year = parseIntOrNull(file.getMetadata("date")); object.genre = file.getMetadata("genre"); object.replayGainTrackGain = parseFloatOrNull(file.getMetadata("REPLAYGAIN_TRACK_GAIN")); object.replayGainTrackPeak = parseFloatOrNull(file.getMetadata("REPLAYGAIN_TRACK_PEAK")); object.replayGainAlbumGain = parseFloatOrNull(file.getMetadata("REPLAYGAIN_ALBUM_GAIN")); object.replayGainAlbumPeak = parseFloatOrNull(file.getMetadata("REPLAYGAIN_ALBUM_PEAK")); object.labels = {}; return object; } function uniqueFilename(filename) { // break into parts var dirname = path.dirname(filename); var basename = path.basename(filename); var extname = path.extname(filename); var withoutExt = basename.substring(0, basename.length - extname.length); var match = withoutExt.match(/_(\d+)$/); var withoutMatch; var number; if (match) { number = parseInt(match[1], 10); if (!number) number = 0; withoutMatch = withoutExt.substring(0, match.index); } else { number = 0; withoutMatch = withoutExt; } number += 1; // put it back together var newBasename = withoutMatch + "_" + number + extname; return path.join(dirname, newBasename); } function dBToFloat(dB) { return Math.exp(dB * DB_SCALE); } function ensureSep(dir) { return (dir[dir.length - 1] === path.sep) ? dir : (dir + path.sep); } function ensureGrooveVersionIsOk() { var ver = groove.getVersion(); var verStr = ver.major + '.' + ver.minor + '.' + ver.patch; var reqVer = '>=4.1.1'; if (semver.satisfies(verStr, reqVer)) return; log.fatal("Found libgroove", verStr, "need", reqVer); process.exit(1); } function playlistItemKey(playlist, item) { return PLAYLIST_KEY_PREFIX + playlist.id + '.' + item.id; } function playlistKey(playlist) { return PLAYLIST_META_KEY_PREFIX + playlist.id; } function serializePlaylist(playlist) { return JSON.stringify({ id: playlist.id, name: playlist.name, mtime: playlist.mtime, }); } function deserializePlaylist(str) { var playlist = JSON.parse(str); playlist.items = {}; return playlist; } function zfill(number, size) { number = String(number); while (number.length < size) number = "0" + number; return number; } function setGrooveLoggingLevel() { switch (log.level) { case log.levels.Fatal: case log.levels.Error: case log.levels.Info: case log.levels.Warn: groove.setLogging(groove.LOG_QUIET); break; case log.levels.Debug: groove.setLogging(groove.LOG_INFO); break; } } function importFileAsSong(self, srcFullPath, filenameHintWithoutPath, cb) { groove.open(srcFullPath, function(err, file) { if (err) return cb(err); var newDbFile = grooveFileToDbFile(file, filenameHintWithoutPath); var suggestedPath = self.getSuggestedPath(newDbFile, filenameHintWithoutPath); var pend = new Pend(); pend.go(function(cb) { log.debug("importFileAsSong close file:", file.filename); file.close(cb); }); pend.go(function(cb) { tryMv(suggestedPath, cb); }); pend.wait(function(err) { if (err) return cb(err); cb(null, [newDbFile]); }); function tryMv(destRelPath, cb) { var destFullPath = path.join(self.musicDirectory, destRelPath); // before importFileAsSong is called, file system watching is disabled. // So we can safely move files into the library without triggering an // update db. mv(srcFullPath, destFullPath, {mkdirp: true, clobber: false}, function(err) { if (err) { if (err.code === 'EEXIST') { tryMv(uniqueFilename(destRelPath), cb); } else { cb(err); } return; } onAddOrChange(self, destRelPath, (new Date()).getTime(), function(err, dbFile) { if (err) return cb(err); newDbFile = dbFile; cb(); }); }); } }); } function importFileAsZip(self, srcFullPath, filenameHintWithoutPath, cb) { yauzl.open(srcFullPath, function(err, zipfile) { if (err) return cb(err); var allDbFiles = []; var pend = new Pend(); zipfile.on('error', handleError); zipfile.on('entry', onEntry); zipfile.on('end', onEnd); function onEntry(entry) { if (/\/$/.test(entry.fileName)) { // ignore directories return; } pend.go(function(cb) { zipfile.openReadStream(entry, function(err, readStream) { if (err) { log.warn("Error reading zip file:", err.stack); cb(); return; } var entryBaseName = path.basename(entry.fileName); self.importStream(readStream, entryBaseName, entry.uncompressedSize, function(err, dbFiles) { if (err) { log.warn("unable to import entry from zip file:", err.stack); } else if (dbFiles) { allDbFiles = allDbFiles.concat(dbFiles); } cb(); }); }); }); } function onEnd() { pend.wait(function() { unlinkZipFile(); cb(null, allDbFiles); }); } function handleError(err) { unlinkZipFile(); cb(err); } function unlinkZipFile() { fs.unlink(srcFullPath, function(err) { if (err) { log.error("Unable to remove zip file after importing:", err.stack); } }); } }); } // sort keys according to how they appear in the library function sortTracks(tracks) { var lib = new MusicLibraryIndex(); tracks.forEach(function(track) { lib.addTrack(track); }); lib.rebuildTracks(); var results = []; lib.artistList.forEach(function(artist) { artist.albumList.forEach(function(album) { album.trackList.forEach(function(track) { results.push(track); }); }); }); return results; } function logIfDbError(err) { if (err) { log.error("Unable to update DB:", err.stack); } } function makeLower(str) { return str.toLowerCase(); } function copySet(set) { var out = {}; for (var key in set) { out[key] = 1; } return out; }
Java
*** View in [[English](README-en.md)][[中文](README.md)] *** # gocaptcha go语言验证码服务器 Feature ------- * 支持中文验证码 * 支持自定义词库、字库 * 支持自定义滤镜机制,通过滤镜来增加干扰,加大识别难度 * 当前的滤镜包括: * 支持干扰点 * 支持干扰线 * 支持其他模式的干扰 * 更多模式,可实现imagefilter接口来扩展 * 支持自定义存储引擎,存储引擎可扩展 * 目前支持的存储引擎包括: * 内置(buildin) * memcache * redis (from https://github.com/dtynn/gocaptcha) * 如需扩展存储引擎,可实现StoreInterface接口 Useage ------ **安装** go get github.com/hanguofeng/gocaptcha **Quick Start** 参考 [captcha_test.go](captcha_test.go) 参考 [samples/gocaptcha-server](samples/gocaptcha-server) [Demo](http://hanguofeng-gocaptcha.daoapp.io/) **文档** [[captcha.go Wiki](https://github.com/hanguofeng/gocaptcha/wiki)] TODO ---- * 运维管理工具 LICENCE ------- gocaptcha使用[[MIT许可协议](LICENSE)] 使用的开源软件列表,表示感谢 * https://github.com/dchest/captcha * https://github.com/golang/freetype * https://github.com/bradfitz/gomemcache * https://code.google.com/p/zpix/
Java
def add_age puts "How old are you?" age = gets.chomp puts "In 10 years you will be:" puts age.to_i + 10 puts "In 20 years you will be:" puts age.to_i + 20 puts "In 30 years you will be:" puts age.to_i + 30 puts "In 40 years you will be:" puts age.to_i + 40 end add_age
Java
<!DOCTYPE html> <html class="theme-next mist use-motion" lang="zh-Hans"> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/> <meta name="theme-color" content="#222"> <meta http-equiv="Cache-Control" content="no-transform" /> <meta http-equiv="Cache-Control" content="no-siteapp" /> <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" /> <link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" /> <link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" /> <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4"> <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4"> <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4"> <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222"> <meta name="keywords" content="Hexo, NexT" /> <meta name="description" content="About technology and about life."> <meta property="og:type" content="website"> <meta property="og:title" content="Ice summer bug&#39;s notes"> <meta property="og:url" content="https://summerbuger.github.io/archives/2016/index.html"> <meta property="og:site_name" content="Ice summer bug&#39;s notes"> <meta property="og:description" content="About technology and about life."> <meta property="og:locale" content="zh-Hans"> <meta name="twitter:card" content="summary"> <meta name="twitter:title" content="Ice summer bug&#39;s notes"> <meta name="twitter:description" content="About technology and about life."> <script type="text/javascript" id="hexo.configurations"> var NexT = window.NexT || {}; var CONFIG = { root: '/', scheme: 'Mist', version: '5.1.4', sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false}, fancybox: true, tabs: true, motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}, duoshuo: { userId: '0', author: '博主' }, algolia: { applicationID: '', apiKey: '', indexName: '', hits: {"per_page":10}, labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"} } }; </script> <link rel="canonical" href="https://summerbuger.github.io/archives/2016/"/> <title>归档 | Ice summer bug's notes</title> </head> <body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans"> <div class="container sidebar-position-left page-archive"> <div class="headband"></div> <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"> <div class="header-inner"><div class="site-brand-wrapper"> <div class="site-meta "> <div class="custom-logo-site-title"> <a href="/" class="brand" rel="start"> <span class="logo-line-before"><i></i></span> <span class="site-title">Ice summer bug's notes</span> <span class="logo-line-after"><i></i></span> </a> </div> <p class="site-subtitle"></p> </div> <div class="site-nav-toggle"> <button> <span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span> </button> </div> </div> <nav class="site-nav"> <ul id="menu" class="menu"> <li class="menu-item menu-item-home"> <a href="/" rel="section"> <i class="menu-item-icon fa fa-fw fa-home"></i> <br /> 首页 </a> </li> <li class="menu-item menu-item-tags"> <a href="/tags/" rel="section"> <i class="menu-item-icon fa fa-fw fa-tags"></i> <br /> 标签 </a> </li> <li class="menu-item menu-item-categories"> <a href="/categories/" rel="section"> <i class="menu-item-icon fa fa-fw fa-th"></i> <br /> 分类 </a> </li> <li class="menu-item menu-item-archives"> <a href="/archives/" rel="section"> <i class="menu-item-icon fa fa-fw fa-archive"></i> <br /> 归档 </a> </li> </ul> </nav> </div> </header> <main id="main" class="main"> <div class="main-inner"> <div class="content-wrap"> <div id="content" class="content"> <div class="post-block archive"> <div id="posts" class="posts-collapse"> <span class="archive-move-on"></span> <span class="archive-page-counter"> 好! 目前共计 55 篇日志。 继续努力。 </span> <div class="collection-title"> <h1 class="archive-year" id="archive-year-2016">2016</h1> </div> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/12/10/技术/spring/2016-12-10-SpringMvc-@ControllerAdvice/" itemprop="url"> <span itemprop="name">SpringMVC 中的 @ControllerAdvice</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-12-10T21:00:00+08:00" content="2016-12-10" > 12-10 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/12/01/技术/spring/2016-12-01-SpringMVC源码学习-mvc加载过程/" itemprop="url"> <span itemprop="name">SpringMVC源码学习 —— MVC 配置加载过程</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-12-01T21:00:00+08:00" content="2016-12-01" > 12-01 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/10/26/技术/java/2016-10-26-分布式锁/" itemprop="url"> <span itemprop="name">几种分布式锁的实现方式</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-10-26T21:00:00+08:00" content="2016-10-26" > 10-26 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/10/16/技术/mybatis/2016-10-16-mybatis-XMLMapperBuilder/" itemprop="url"> <span itemprop="name">mybatis 中的 Configuration</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-10-16T21:00:00+08:00" content="2016-10-16" > 10-16 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/10/16/技术/mybatis/2016-10-16-mybatis-MapperBuilderAssistant/" itemprop="url"> <span itemprop="name">mybatis 中的 MapperBuilderAssistant</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-10-16T21:00:00+08:00" content="2016-10-16" > 10-16 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/10/16/技术/mybatis/2016-10-16-mybatis-Configuration/" itemprop="url"> <span itemprop="name">mybatis 中的 Configuration</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-10-16T21:00:00+08:00" content="2016-10-16" > 10-16 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/10/16/技术/mybatis/2016-10-16-mybatis-MapperAnnotationBuilder/" itemprop="url"> <span itemprop="name">mybatis 中的 MapperAnnotationBuilder</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-10-16T21:00:00+08:00" content="2016-10-16" > 10-16 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/10/16/技术/mybatis/2016-10-16-mybatis-MapperMethod/" itemprop="url"> <span itemprop="name">mybatis 中的 MapperMethod</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-10-16T21:00:00+08:00" content="2016-10-16" > 10-16 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/09/20/技术/mybatis/2016-09-20-mybatis源码阅读/" itemprop="url"> <span itemprop="name">mybatis 源码阅读(一)</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-09-20T21:00:00+08:00" content="2016-09-20" > 09-20 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/09/13/技术/java/2016-09-13-CPU占用过高处理过程/" itemprop="url"> <span itemprop="name">线上应用故障排查</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-09-13T21:00:00+08:00" content="2016-09-13" > 09-13 </time> </div> </header> </article> </div> </div> <nav class="pagination"> <span class="page-number current">1</span><a class="page-number" href="/archives/2016/page/2/">2</a><a class="extend next" rel="next" href="/archives/2016/page/2/"><i class="fa fa-angle-right"></i></a> </nav> </div> </div> <div class="sidebar-toggle"> <div class="sidebar-toggle-line-wrap"> <span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span> </div> </div> <aside id="sidebar" class="sidebar"> <div class="sidebar-inner"> <section class="site-overview-wrap sidebar-panel sidebar-panel-active"> <div class="site-overview"> <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"> <img class="site-author-image" itemprop="image" src="/images/headPicture.png" alt="Liam Chen" /> <p class="site-author-name" itemprop="name">Liam Chen</p> <p class="site-description motion-element" itemprop="description">About technology and about life.</p> </div> <nav class="site-state motion-element"> <div class="site-state-item site-state-posts"> <a href="/archives/"> <span class="site-state-item-count">55</span> <span class="site-state-item-name">日志</span> </a> </div> <div class="site-state-item site-state-categories"> <a href="/categories/index.html"> <span class="site-state-item-count">21</span> <span class="site-state-item-name">分类</span> </a> </div> <div class="site-state-item site-state-tags"> <a href="/tags/index.html"> <span class="site-state-item-count">41</span> <span class="site-state-item-name">标签</span> </a> </div> </nav> </div> </section> </div> </aside> </div> </main> <footer id="footer" class="footer"> <div class="footer-inner"> <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span> <span class="with-love"> <i class="fa fa-user"></i> </span> <span class="author" itemprop="copyrightHolder">Liam Chen</span> </div> <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div> <span class="post-meta-divider">|</span> <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div> </div> </footer> <div class="back-to-top"> <i class="fa fa-arrow-up"></i> </div> </div> <script type="text/javascript"> if (Object.prototype.toString.call(window.Promise) !== '[object Function]') { window.Promise = null; } </script> <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script> <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script> <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script> <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script> <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script> <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script> <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script> <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script> <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script> </body> </html>
Java
import { stringify } from 'qs' import _request from '@/utils/request' import mini from '@/utils/mini' import env from '@/config/env' // import { modelApis, commonParams } from './model' // import { version } from '../package.json' let apiBaseUrl apiBaseUrl = `${env.apiBaseUrl}` const regHttp = /^https?/i const isMock = true; // const regMock = /^mock?/i function compact(obj) { for (const key in obj) { if (!obj[key]) { delete obj[key] } } return obj } function request(url, options, success, fail) { const originUrl = regHttp.test(url) ? url : `${apiBaseUrl}${url}` return _request(originUrl, compact(options), success, fail) } /** * API 命名规则 * - 使用 camelCase 命名格式(小驼峰命名) * - 命名尽量对应 RESTful 风格,`${动作}${资源}` * - 假数据增加 fake 前缀 * - 便捷易用大于规则,程序是给人看的 */ // api 列表 const modelApis = { // 初始化配置 test: 'https://easy-mock.com/mock/5aa79bf26701e17a67bde1d7/', getConfig: '/common/initconfig', getWxSign: '/common/getwxsign', // 积分兑换 getPointIndex: '/point/index', getPointList: '/point/skulist', getPointDetail: '/point/iteminfo', getPointDetaiMore: '/product/productdetail', getRList: '/point/recommenditems', // 专题 getPointTopicInfo: '/point/topicinfo', getPointTopicList: '/point/topicbuskulist', // 主站专题 getTopicInfo: '/product/topicskusinfo', getTopicList: '/product/topicskulist', // 个人中心 getProfile: '/user/usercenter', // 拼团相关 getCoupleList: '/product/coupleskulist', getCoupleDetail: '/product/coupleskudetail', getMerchantList: '/merchant/coupleskulist', coupleOrderInit: 'POST /order/coupleorderinit', coupleOrderList: '/user/usercouplelist', coupleOrderDetail: '/user/usercoupleorderdetail', coupleUserList: '/market/pinactivitiesuserlist', // 分享页拼团头像列表 coupleShareDetail: '/user/coupleactivitiedetail', // 分享详情 // 首页 getIndex: '/common/index', getIndexNew: '/common/index_v1', getHotSearch: '/common/hotsearchsug', // 主流程 orderInit: 'POST /order/orderinit', orderSubmit: 'POST /order/submitorder', orderPay: 'POST /order/orderpay', orderPayConfirm: '/order/orderpayconfirm', // 确认支付状态 getUserOrders: '/order/getuserorders', // 订单列表 getNeedCommentOrders: '/order/waitcommentlist', // 待评论 getUserRefundorders: '/order/userrefundorder', // 退款 getUserServiceOrders: '/order/userserviceorders', // 售后 orderCancel: 'POST /order/cancelorder', // 取消订单 orderDetail: '/order/orderdetail', confirmReceived: 'POST /order/userorderconfirm', // 确认收货 orderComplaint: 'POST /refund/complaint', // 订单申诉 // 积分订单相关 pointOrderInit: 'POST /tradecenter/pointorderpreview', pointOrderSubmit: 'POST /tradecenter/pointordersubmit', pointOrderCancel: 'POST /tradecenter/ordercancel', pointOrderList: '/tradecenter/orderlist', pointOrderDetail: '/tradecenter/orderinfo', pointOrderSuccess: '/tradecenter/ordersuccess', // 退款相关 refundInit: '/refund/init', refundDetail: '/refund/detail', refundApply: 'POST /refund/apply', // 登录注销 login: 'POST /user/login', logout: 'POST /user/logout', // 地址管理 addressList: '/user/addresslist', addAddress: 'POST /user/addaddress', updateAddress: 'POST /user/updateaddress', setDefaultAddress: 'POST /user/setdefaultaddress', deleteAddress: 'POST /user/deleteaddress', provinceList: '/nation/provincelist', cityList: '/nation/citylist', districtList: '/nation/districtlist', // 查看物流 getDelivery: '/order/deliverymessage', // 获取七牛 token getQiniuToken: '/common/qiniutoken', } // 仅限本地调试支持 // if (__DEV__ && env.mock) { if (__DEV__ && isMock) { apiBaseUrl = `${env.apiMockUrl}` // Object.assign(modelApis, require('../mock')) } // 线上代理 if (__DEV__ && env.proxy) { const proxyUrl = '/proxy' apiBaseUrl = `${env.origin}${proxyUrl}` } const { width, height, } = window.screen // 公共参数 const commonParams = { uuid: '', // 用户唯一标志 udid: '', // 设备唯一标志 device: '', // 设备 net: '', // 网络 uid: '', token: '', timestamp: '', // 时间 channel: 'h5', // 渠道 spm: 'h5', v: env.version, // 系统版本 terminal: env.terminal, // 终端 swidth: width, // 屏幕宽度 分辨率 sheight: height, // 屏幕高度 location: '', // 地理位置 zoneId: 857, // 必须 } // console.log(Object.keys(modelApis)) const apiList = Object.keys(modelApis).reduce((api, key) => { const val = modelApis[key] const [url, methodType = 'GET'] = val.split(/\s+/).reverse() const method = methodType.toUpperCase() // let originUrl = regHttp.test(url) ? url : `${env.apiBaseUrl}${url}`; // NOTE: headers 在此处设置? // if (__DEV__ && regLocalMock.test(url)) { // api[key] = function postRequest(params, success, fail) { // const res = require(`../${url}.json`) // mini.hideLoading() // res.errno === 0 ? success(res) : fail(res) // } // return api // } switch (method) { case 'POST': // originUrl = `${originUrl}`; api[key] = function postRequest(params, success, fail) { return request(url, { headers: { // Accept: 'application/json', // 我们的 post 请求,使用的这个,不是 application/json // 'Content-Type': 'application/x-www-form-urlencoded', }, method, data: compact(Object.assign({}, getCommonParams(), params)), }, success, fail) } break case 'GET': default: api[key] = function getRequest(params, success, fail) { params = compact(Object.assign({}, getCommonParams(), params)) let query = stringify(params) if (query) query = `?${query}` return request(`${url}${query}`, {}, success, fail) } break } return api }, {}) function setCommonParams(params) { return Object.assign(commonParams, params) } function getCommonParams(key) { return key ? commonParams[key] : { // ...commonParams, } } apiList.getCommonParams = getCommonParams apiList.setCommonParams = setCommonParams // console.log(apiList) export default apiList
Java
import m from 'mithril'; import _ from 'underscore'; import postgrest from 'mithril-postgrest'; import models from '../models'; import h from '../h'; import projectDashboardMenu from '../c/project-dashboard-menu'; import projectContributionReportHeader from '../c/project-contribution-report-header'; import projectContributionReportContent from '../c/project-contribution-report-content'; import projectsContributionReportVM from '../vms/projects-contribution-report-vm'; import FilterMain from '../c/filter-main'; import FilterDropdown from '../c/filter-dropdown'; import InfoProjectContributionLegend from '../c/info-project-contribution-legend'; import ProjectContributionStateLegendModal from '../c/project-contribution-state-legend-modal'; import ProjectContributionDeliveryLegendModal from '../c/project-contribution-delivery-legend-modal'; const projectContributionReport = { controller(args) { const listVM = postgrest.paginationVM(models.projectContribution, 'id.desc', { Prefer: 'count=exact' }), filterVM = projectsContributionReportVM, project = m.prop([{}]), rewards = m.prop([]), contributionStateOptions = m.prop([]), reloadSelectOptions = (projectState) => { let opts = [{ value: '', option: 'Todos' }]; const optionsMap = { online: [{ value: 'paid', option: 'Confirmado' }, { value: 'pending', option: 'Iniciado' }, { value: 'refunded,chargeback,deleted,pending_refund', option: 'Contestado' }, ], waiting_funds: [{ value: 'paid', option: 'Confirmado' }, { value: 'pending', option: 'Iniciado' }, { value: 'refunded,chargeback,deleted,pending_refund', option: 'Contestado' }, ], failed: [{ value: 'pending_refund', option: 'Reembolso em andamento' }, { value: 'refunded', option: 'Reembolsado' }, { value: 'paid', option: 'Reembolso não iniciado' }, ], successful: [{ value: 'paid', option: 'Confirmado' }, { value: 'refunded,chargeback,deleted,pending_refund', option: 'Contestado' }, ] }; opts = opts.concat(optionsMap[projectState] || []); contributionStateOptions(opts); }, submit = () => { if (filterVM.reward_id() === 'null') { listVM.firstPage(filterVM.withNullParameters()).then(null); } else { listVM.firstPage(filterVM.parameters()).then(null); } return false; }, filterBuilder = [{ component: FilterMain, data: { inputWrapperClass: '.w-input.text-field', btnClass: '.btn.btn-medium', vm: filterVM.full_text_index, placeholder: 'Busque por nome ou email do apoiador' } }, { label: 'reward_filter', component: FilterDropdown, data: { label: 'Recompensa selecionada', onchange: submit, name: 'reward_id', vm: filterVM.reward_id, wrapper_class: '.w-sub-col.w-col.w-col-4', options: [] } }, { label: 'delivery_filter', component: FilterDropdown, data: { custom_label: [InfoProjectContributionLegend, { content: [ProjectContributionDeliveryLegendModal], text: 'Status da entrega' }], onchange: submit, name: 'delivery_status', vm: filterVM.delivery_status, wrapper_class: '.w-col.w-col-4', options: [{ value: '', option: 'Todos' }, { value: 'undelivered', option: 'Não enviada' }, { value: 'delivered', option: 'Enviada' }, { value: 'error', option: 'Erro no envio' }, { value: 'received', option: 'Recebida' } ] } }, { label: 'payment_state', component: FilterDropdown, data: { custom_label: [InfoProjectContributionLegend, { text: 'Status do apoio', content: [ProjectContributionStateLegendModal, { project }] }], name: 'state', onchange: submit, vm: filterVM.state, wrapper_class: '.w-sub-col.w-col.w-col-4', options: contributionStateOptions } } ]; filterVM.project_id(args.root.getAttribute('data-id')); const lReward = postgrest.loaderWithToken(models.rewardDetail.getPageOptions({ project_id: `eq.${filterVM.project_id()}` })); const lProject = postgrest.loaderWithToken(models.projectDetail.getPageOptions({ project_id: `eq.${filterVM.project_id()}` })); lReward.load().then(rewards); lProject.load().then((data) => { project(data); reloadSelectOptions(_.first(data).state); }); const mapRewardsToOptions = () => { let options = []; if (!lReward()) { options = _.map(rewards(), r => ({ value: r.id, option: `R$ ${h.formatNumber(r.minimum_value, 2, 3)} - ${r.description.substring(0, 20)}` })); } options.unshift({ value: null, option: 'Sem recompensa' }); options.unshift({ value: '', option: 'Todas' }); return options; }; if (!listVM.collection().length) { listVM.firstPage(filterVM.parameters()); } return { listVM, filterVM, filterBuilder, submit, lReward, lProject, rewards, project, mapRewardsToOptions }; }, view(ctrl) { const list = ctrl.listVM; if (!ctrl.lProject()) { return [ m.component(projectDashboardMenu, { project: m.prop(_.first(ctrl.project())) }), m.component(projectContributionReportHeader, { submit: ctrl.submit, filterBuilder: ctrl.filterBuilder, form: ctrl.filterVM.formDescriber, mapRewardsToOptions: ctrl.mapRewardsToOptions, filterVM: ctrl.filterVM }), m('.divider.u-margintop-30'), m.component(projectContributionReportContent, { submit: ctrl.submit, list, filterVM: ctrl.filterVM, project: m.prop(_.first(ctrl.project())) }) ]; } return h.loader(); } }; export default projectContributionReport;
Java
<?php namespace Faker\Provider\fa_IR; class PhoneNumber extends \Faker\Provider\PhoneNumber { /** * @link https://fa.wikipedia.org/wiki/%D8%B4%D9%85%D8%A7%D8%B1%D9%87%E2%80%8C%D9%87%D8%A7%DB%8C_%D8%AA%D9%84%D9%81%D9%86_%D8%AF%D8%B1_%D8%A7%DB%8C%D8%B1%D8%A7%D9%86#.D8.AA.D9.84.D9.81.D9.86.E2.80.8C.D9.87.D8.A7.DB.8C_.D9.87.D9.85.D8.B1.D8.A7.D9.87 */ protected static $formats = array( // land line formts seprated by province "011########", //Mazandaran "013########", //Gilan "017########", //Golestan "021########", //Tehran "023########", //Semnan "024########", //Zanjan "025########", //Qom "026########", //Alborz "028########", //Qazvin "031########", //Isfahan "034########", //Kerman "035########", //Yazd "038########", //Chaharmahal and Bakhtiari "041########", //East Azerbaijan "044########", //West Azerbaijan "045########", //Ardabil "051########", //Razavi Khorasan "054########", //Sistan and Baluchestan "056########", //South Khorasan "058########", //North Khorasan "061########", //Khuzestan "066########", //Lorestan "071########", //Fars "074########", //Kohgiluyeh and Boyer-Ahmad "076########", //Hormozgan "077########", //Bushehr "081########", //Hamadan "083########", //Kermanshah "084########", //Ilam "086########", //Markazi "087########", //Kurdistan ); protected static $mobileNumberPrefixes = array( '0910#######',//mci '0911#######', '0912#######', '0913#######', '0914#######', '0915#######', '0916#######', '0917#######', '0918#######', '0919#######', '0901#######', '0901#######', '0902#######', '0903#######', '0930#######', '0933#######', '0935#######', '0936#######', '0937#######', '0938#######', '0939#######', '0920#######', '0921#######', '0937#######', '0990#######', // MCI ); public static function mobileNumber() { return static::numerify(static::randomElement(static::$mobileNumberPrefixes)); } }
Java
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import { xhr } from 'vs/base/common/network'; import { IConfigurationRegistry, Extensions } from 'vs/platform/configuration/common/configurationRegistry'; import strings = require('vs/base/common/strings'); import nls = require('vs/nls'); import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import platform = require('vs/platform/platform'); import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { BaseRequestService } from 'vs/platform/request/common/baseRequestService'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { assign } from 'vs/base/common/objects'; import { IXHROptions, IXHRResponse } from 'vs/base/common/http'; import { request } from 'vs/base/node/request'; import { getProxyAgent } from 'vs/base/node/proxy'; import { createGunzip } from 'zlib'; import { Stream } from 'stream'; interface IHTTPConfiguration { http?: { proxy?: string; proxyStrictSSL?: boolean; }; } export class RequestService extends BaseRequestService { private disposables: IDisposable[]; private proxyUrl: string = null; private strictSSL: boolean = true; constructor( @IWorkspaceContextService contextService: IWorkspaceContextService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService telemetryService?: ITelemetryService ) { super(contextService, telemetryService); this.disposables = []; const config = configurationService.getConfiguration<IHTTPConfiguration>(); this.configure(config); const disposable = configurationService.onDidUpdateConfiguration(e => this.configure(e.config)); this.disposables.push(disposable); } private configure(config: IHTTPConfiguration) { this.proxyUrl = config.http && config.http.proxy; this.strictSSL = config.http && config.http.proxyStrictSSL; } makeRequest(options: IXHROptions): TPromise<IXHRResponse> { let url = options.url; if (!url) { throw new Error('IRequestService.makeRequest: Url is required.'); } // Support file:// in native environment through XHR if (strings.startsWith(url, 'file://')) { return xhr(options).then(null, (xhr: XMLHttpRequest) => { if (xhr.status === 0 && xhr.responseText) { return xhr; // loading resources locally returns a status of 0 which in WinJS is an error so we need to handle it here } return <any>Promise.wrapError({ status: 404, responseText: nls.localize('localFileNotFound', "File not found.")}); }); } return super.makeRequest(options); } protected makeCrossOriginRequest(options: IXHROptions): TPromise<IXHRResponse> { const { proxyUrl, strictSSL } = this; const agent = getProxyAgent(options.url, { proxyUrl, strictSSL }); options = assign({}, options); options = assign(options, { agent, strictSSL }); return request(options).then(result => new TPromise<IXHRResponse>((c, e, p) => { const res = result.res; let stream: Stream = res; if (res.headers['content-encoding'] === 'gzip') { stream = stream.pipe(createGunzip()); } const data: string[] = []; stream.on('data', c => data.push(c)); stream.on('end', () => { const status = res.statusCode; if (options.followRedirects > 0 && (status >= 300 && status <= 303 || status === 307)) { let location = res.headers['location']; if (location) { let newOptions = { type: options.type, url: location, user: options.user, password: options.password, responseType: options.responseType, headers: options.headers, timeout: options.timeout, followRedirects: options.followRedirects - 1, data: options.data }; xhr(newOptions).done(c, e, p); return; } } const response: IXHRResponse = { responseText: data.join(''), status, getResponseHeader: header => res.headers[header], readyState: 4 }; if ((status >= 200 && status < 300) || status === 1223) { c(response); } else { e(response); } }); }, err => { let message: string; if (agent) { message = 'Unable to to connect to ' + options.url + ' through a proxy . Error: ' + err.message; } else { message = 'Unable to to connect to ' + options.url + '. Error: ' + err.message; } return TPromise.wrapError<IXHRResponse>({ responseText: message, status: 404 }); })); } dispose(): void { this.disposables = dispose(this.disposables); } } // Configuration let confRegistry = <IConfigurationRegistry>platform.Registry.as(Extensions.Configuration); confRegistry.registerConfiguration({ id: 'http', order: 15, title: nls.localize('httpConfigurationTitle', "HTTP configuration"), type: 'object', properties: { 'http.proxy': { type: 'string', pattern: '^https?://[^:]+(:\\d+)?$|^$', description: nls.localize('proxy', "The proxy setting to use. If not set will be taken from the http_proxy and https_proxy environment variables") }, 'http.proxyStrictSSL': { type: 'boolean', default: true, description: nls.localize('strictSSL', "Whether the proxy server certificate should be verified against the list of supplied CAs.") } } });
Java
// // IGViewController.h // KaifKit // // Created by Francis Chong on 04/15/2015. // Copyright (c) 2014 Francis Chong. All rights reserved. // #import <UIKit/UIKit.h> @interface IGViewController : UIViewController @end
Java
version https://git-lfs.github.com/spec/v1 oid sha256:f5c198d5eef0ca0f41f87746ef8fefe819a727fcd59a6477c76b94b55d27128d size 1730
Java
<?php $news = array( array( 'created_at' => '2015-04-29 00:00:00', 'image' => 'http://fakeimg.pl/768x370/3c3c3c/', 'thumb' => 'http://fakeimg.pl/200x200/3c3c3c/', 'title' => 'Blimps to Defend Washington, D.C. Airspace', 'content' => '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque in pulvinar neque. Duis in pharetra purus. Mauris varius porttitor augue in iaculis. Phasellus tincidunt justo magna, eget porta est sagittis quis. Quisque at ante nec dolor euismod elementum sit amet hendrerit nibh. Etiam ut odio tortor. Mauris blandit purus et mauris gravida, eget gravida nulla convallis.</p><p>Vivamus vehicula dignissim malesuada. Donec cursus luctus mi, ac sagittis arcu scelerisque a. Nullam et metus quis sem mollis accumsan. Aenean in sapien pretium, pretium leo eu, ullamcorper sapien. Nulla tempus, metus eu iaculis posuere, ipsum ex faucibus velit, cursus condimentum ligula ex non enim. Aliquam iaculis pellentesque erat molestie feugiat. Morbi ornare maximus rutrum. Pellentesque id euismod erat, eget aliquam massa.</p>' ), array( 'created_at' => '2015-04-26 00:00:00', 'image' => 'http://fakeimg.pl/768x370/3c3c3c/', 'thumb' => 'http://fakeimg.pl/200x200/3c3c3c/', 'title' => 'Eye Receptor Transplants May Restore Eyesight to the Blind', 'content' => '<p>Praesent cursus lobortis dui eu congue. Phasellus pellentesque posuere commodo. Curabitur dignissim placerat sapien, nec egestas ante. Mauris nec commodo est, ac faucibus massa. Nam et dolor at est dignissim condimentum. Quisque consequat tempus aliquam. Mauris consectetur rutrum efficitur.</p><p>Quisque vulputate massa velit, at facilisis turpis euismod id. Pellentesque molestie lectus ut nisl dignissim sagittis. Sed vitae rutrum turpis. Aenean ex est, sagittis vel lectus nec, suscipit condimentum ligula. Ut vitae vehicula lectus. Morbi sit amet cursus arcu. Curabitur quis nunc ultrices, suscipit erat vel, faucibus diam. Sed odio turpis, consequat eu feugiat a, porttitor eget nisl.</p>' ), array( 'created_at' => '2015-04-27 00:00:00', 'image' => 'http://fakeimg.pl/768x370/3c3c3c/', 'thumb' => 'http://fakeimg.pl/200x200/3c3c3c/', 'title' => 'Researchers Look to Tattoos to Monitor Your Sweat', 'content' => '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ultricies malesuada risus, at pretium elit scelerisque in. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vel risus sed leo suscipit tempus vel vel eros. Suspendisse augue elit, tempor a leo tempus, egestas hendrerit leo. Fusce mattis quam magna, ut mattis nulla ultrices at. Etiam sollicitudin tempus placerat. Nulla facilisi. Praesent non porttitor diam, imperdiet volutpat dolor. Pellentesque viverra consectetur auctor. Etiam metus purus, accumsan ac efficitur et, laoreet ut orci. Phasellus rutrum rhoncus lacus a imperdiet. Nam ac scelerisque quam. Donec vitae est pharetra, consequat risus et, maximus odio.</p>' ), ); ?> <?php if ( isset( $news ) ) : ?> <div class="widget widget-featured-news"> <div class="widget-header"> <h3 class="widget-title"> <i class="glyphicon glyphicon-star"></i> Featured News </h3> <!-- /.widget-title --> </div> <!-- /.widget-header --> <div class="widget-content"> <ul class="list-unstyled"> <?php foreach ( $news as $new ) : ?> <li data-title="<?php echo $new['title']; ?>"> <a href="#"> <img alt="<?php echo $new['title']; ?>" class="img-responsive" height="370" src="<?php echo $new['image']; ?>" width="768"> </a> <h2><a href="#"><?php echo $new['title']; ?></a></h2> <div class="article hidden"> <button class="btn btn-close" type="button"><i class="glyphicon glyphicon-remove"></i></button> <p class="h2"><?php echo $new['title']; ?></p> <!-- /.h2 --> <?php echo $new['content']; ?> </div> <!-- /.article hidden --> </li> <?php endforeach; ?> </ul> <!-- /.list-unstyled --> </div> <!-- /.widget-content --> </div> <!-- /.widget widget-featured-news --> <?php endif; ?>
Java
# Dreedi To start your this app: 1. Install dependencies with `mix deps.get` 2. Create and migrate your database with `mix ecto.create && mix ecto.migrate` 3. Start Phoenix endpoint with `mix phoenix.server` Now you can visit [`localhost:4000`](http://localhost:4000) from your browser.
Java
# mpps web repository
Java
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreatePlatformsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('platforms', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('short_name'); $table->string('slug')->unique(); $table->string('logo'); $table->string('banner'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('platforms'); } }
Java
require 'spec_helper' RSpec.describe RailsAdmin::ApplicationHelper, type: :helper do describe '#authorized?' do let(:abstract_model) { RailsAdmin.config(FieldTest).abstract_model } it 'doesn\'t use unpersisted objects' do expect(helper).to receive(:action).with(:edit, abstract_model, nil).and_call_original helper.authorized?(:edit, abstract_model, FactoryBot.build(:field_test)) end end describe 'with #authorized? stubbed' do before do allow(controller).to receive(:authorized?).and_return(true) end describe '#current_action?' do it 'returns true if current_action, false otherwise' do @action = RailsAdmin::Config::Actions.find(:index) expect(helper.current_action?(RailsAdmin::Config::Actions.find(:index))).to be_truthy expect(helper.current_action?(RailsAdmin::Config::Actions.find(:show))).not_to be_truthy end end describe '#action' do it 'returns action by :custom_key' do RailsAdmin.config do |config| config.actions do dashboard do custom_key :my_custom_dashboard_key end end end expect(helper.action(:my_custom_dashboard_key)).to be end it 'returns only visible actions' do RailsAdmin.config do |config| config.actions do dashboard do visible false end end end expect(helper.action(:dashboard)).to be_nil end it 'returns only visible actions, passing all bindings' do RailsAdmin.config do |config| config.actions do member :test_bindings do visible do bindings[:controller].is_a?(ActionView::TestCase::TestController) && bindings[:abstract_model].model == Team && bindings[:object].is_a?(Team) end end end end expect(helper.action(:test_bindings, RailsAdmin::AbstractModel.new(Team), Team.new)).to be expect(helper.action(:test_bindings, RailsAdmin::AbstractModel.new(Team), Player.new)).to be_nil expect(helper.action(:test_bindings, RailsAdmin::AbstractModel.new(Player), Team.new)).to be_nil end end describe '#actions' do it 'returns actions by type' do abstract_model = RailsAdmin::AbstractModel.new(Player) object = FactoryBot.create :player expect(helper.actions(:all, abstract_model, object).collect(&:custom_key)).to eq([:dashboard, :index, :show, :new, :edit, :export, :delete, :bulk_delete, :history_show, :history_index, :show_in_app]) expect(helper.actions(:root, abstract_model, object).collect(&:custom_key)).to eq([:dashboard]) expect(helper.actions(:collection, abstract_model, object).collect(&:custom_key)).to eq([:index, :new, :export, :bulk_delete, :history_index]) expect(helper.actions(:member, abstract_model, object).collect(&:custom_key)).to eq([:show, :edit, :delete, :history_show, :show_in_app]) end it 'only returns visible actions, passing bindings correctly' do RailsAdmin.config do |config| config.actions do member :test_bindings do visible do bindings[:controller].is_a?(ActionView::TestCase::TestController) && bindings[:abstract_model].model == Team && bindings[:object].is_a?(Team) end end end end expect(helper.actions(:all, RailsAdmin::AbstractModel.new(Team), Team.new).collect(&:custom_key)).to eq([:test_bindings]) expect(helper.actions(:all, RailsAdmin::AbstractModel.new(Team), Player.new).collect(&:custom_key)).to eq([]) expect(helper.actions(:all, RailsAdmin::AbstractModel.new(Player), Team.new).collect(&:custom_key)).to eq([]) end end describe '#logout_method' do it 'defaults to :delete when Devise is not defined' do allow(Object).to receive(:defined?).with(Devise).and_return(false) expect(helper.logout_method).to eq(:delete) end it 'uses first sign out method from Devise when it is defined' do allow(Object).to receive(:defined?).with(Devise).and_return(true) expect(Devise).to receive(:sign_out_via).and_return([:whatever_defined_on_devise, :something_ignored]) expect(helper.logout_method).to eq(:whatever_defined_on_devise) end end describe '#wording_for' do it 'gives correct wording even if action is not visible' do RailsAdmin.config do |config| config.actions do index do visible false end end end expect(helper.wording_for(:menu, :index)).to eq('List') end it 'passes correct bindings' do expect(helper.wording_for(:title, :edit, RailsAdmin::AbstractModel.new(Team), Team.new(name: 'the avengers'))).to eq("Edit Team 'the avengers'") end it 'defaults correct bindings' do @action = RailsAdmin::Config::Actions.find :edit @abstract_model = RailsAdmin::AbstractModel.new(Team) @object = Team.new(name: 'the avengers') expect(helper.wording_for(:title)).to eq("Edit Team 'the avengers'") end it 'does not try to use the wrong :label_metod' do @abstract_model = RailsAdmin::AbstractModel.new(Draft) @object = Draft.new expect(helper.wording_for(:link, :new, RailsAdmin::AbstractModel.new(Team))).to eq('Add a new Team') end end describe '#breadcrumb' do it 'gives us a breadcrumb' do @action = RailsAdmin::Config::Actions.find(:edit, abstract_model: RailsAdmin::AbstractModel.new(Team), object: FactoryBot.create(:team, name: 'the avengers')) bc = helper.breadcrumb expect(bc).to match(/Dashboard/) # dashboard expect(bc).to match(/Teams/) # list expect(bc).to match(/the avengers/) # show expect(bc).to match(/Edit/) # current (edit) end end describe '#menu_for' do it 'passes model and object as bindings and generates a menu, excluding non-get actions' do RailsAdmin.config do |config| config.actions do dashboard index do visible do bindings[:abstract_model].model == Team end end show do visible do bindings[:object].class == Team end end delete do http_methods [:post, :put, :delete] end end end @action = RailsAdmin::Config::Actions.find :show @abstract_model = RailsAdmin::AbstractModel.new(Team) @object = FactoryBot.create(:team, name: 'the avengers') expect(helper.menu_for(:root)).to match(/Dashboard/) expect(helper.menu_for(:collection, @abstract_model)).to match(/List/) expect(helper.menu_for(:member, @abstract_model, @object)).to match(/Show/) @abstract_model = RailsAdmin::AbstractModel.new(Player) @object = Player.new expect(helper.menu_for(:collection, @abstract_model)).not_to match(/List/) expect(helper.menu_for(:member, @abstract_model, @object)).not_to match(/Show/) end it 'excludes non-get actions' do RailsAdmin.config do |config| config.actions do dashboard do http_methods [:post, :put, :delete] end end end @action = RailsAdmin::Config::Actions.find :dashboard expect(helper.menu_for(:root)).not_to match(/Dashboard/) end it 'shows actions which are marked as show_in_menu' do I18n.backend.store_translations( :en, admin: {actions: { shown_in_menu: {menu: 'Look this'}, }} ) RailsAdmin.config do |config| config.actions do dashboard do show_in_menu false end root :shown_in_menu, :dashboard do action_name :dashboard show_in_menu true end end end @action = RailsAdmin::Config::Actions.find :dashboard expect(helper.menu_for(:root)).not_to match(/Dashboard/) expect(helper.menu_for(:root)).to match(/Look this/) end end describe '#main_navigation' do it 'shows included models' do RailsAdmin.config do |config| config.included_models = [Ball, Comment] end expect(helper.main_navigation).to match(/(dropdown-header).*(Navigation).*(Balls).*(Comments)/m) end it 'does not draw empty navigation labels' do RailsAdmin.config do |config| config.included_models = [Ball, Comment, Comment::Confirmed] config.model Comment do navigation_label 'Commentz' end config.model Comment::Confirmed do label_plural 'Confirmed' end end expect(helper.main_navigation).to match(/(dropdown-header).*(Navigation).*(Balls).*(Commentz).*(Confirmed)/m) expect(helper.main_navigation).not_to match(/(dropdown-header).*(Navigation).*(Balls).*(Commentz).*(Confirmed).*(Comment)/m) end it 'does not show unvisible models' do RailsAdmin.config do |config| config.included_models = [Ball, Comment] config.model Comment do hide end end result = helper.main_navigation expect(result).to match(/(dropdown-header).*(Navigation).*(Balls)/m) expect(result).not_to match('Comments') end it 'shows children of hidden models' do # https://github.com/sferik/rails_admin/issues/978 RailsAdmin.config do |config| config.included_models = [Ball, Hardball] config.model Ball do hide end end expect(helper.main_navigation).to match(/(dropdown\-header).*(Navigation).*(Hardballs)/m) end it 'shows children of excluded models' do RailsAdmin.config do |config| config.included_models = [Hardball] end expect(helper.main_navigation).to match(/(dropdown-header).*(Navigation).*(Hardballs)/m) end it 'nests in navigation label' do RailsAdmin.config do |config| config.included_models = [Comment] config.model Comment do navigation_label 'commentable' end end expect(helper.main_navigation).to match(/(dropdown\-header).*(commentable).*(Comments)/m) end it 'nests in parent model' do RailsAdmin.config do |config| config.included_models = [Player, Comment] config.model Comment do parent Player end end expect(helper.main_navigation).to match(/(Players).* (nav\-level\-1).*(Comments)/m) end it 'orders' do RailsAdmin.config do |config| config.included_models = [Player, Comment] end expect(helper.main_navigation).to match(/(Comments).*(Players)/m) RailsAdmin.config(Comment) do weight 1 end expect(helper.main_navigation).to match(/(Players).*(Comments)/m) end end describe '#root_navigation' do it 'shows actions which are marked as show_in_sidebar' do I18n.backend.store_translations( :en, admin: {actions: { shown_in_sidebar: {menu: 'Look this'}, }} ) RailsAdmin.config do |config| config.actions do dashboard do show_in_sidebar false end root :shown_in_sidebar, :dashboard do action_name :dashboard show_in_sidebar true end end end expect(helper.root_navigation).not_to match(/Dashboard/) expect(helper.root_navigation).to match(/Look this/) end it 'allows grouping by sidebar_label' do I18n.backend.store_translations( :en, admin: { actions: { foo: {menu: 'Foo'}, bar: {menu: 'Bar'}, }, } ) RailsAdmin.config do |config| config.actions do dashboard do show_in_sidebar true sidebar_label 'One' end root :foo, :dashboard do action_name :dashboard show_in_sidebar true sidebar_label 'Two' end root :bar, :dashboard do action_name :dashboard show_in_sidebar true sidebar_label 'Two' end end end expect(helper.strip_tags(helper.root_navigation).delete(' ')).to eq 'OneDashboardTwoFooBar' end end describe '#static_navigation' do it 'shows not show static nav if no static links defined' do RailsAdmin.config do |config| config.navigation_static_links = {} end expect(helper.static_navigation).to be_empty end it 'shows links if defined' do RailsAdmin.config do |config| config.navigation_static_links = { 'Test Link' => 'http://www.google.com', } end expect(helper.static_navigation).to match(/Test Link/) end it 'shows default header if navigation_static_label not defined in config' do RailsAdmin.config do |config| config.navigation_static_links = { 'Test Link' => 'http://www.google.com', } end expect(helper.static_navigation).to match(I18n.t('admin.misc.navigation_static_label')) end it 'shows custom header if defined' do RailsAdmin.config do |config| config.navigation_static_label = 'Test Header' config.navigation_static_links = { 'Test Link' => 'http://www.google.com', } end expect(helper.static_navigation).to match(/Test Header/) end end describe '#bulk_menu' do it 'includes all visible bulkable actions' do RailsAdmin.config do |config| config.actions do index collection :zorg do bulkable true action_name :zorg_action end collection :blub do bulkable true visible do bindings[:abstract_model].model == Team end end end end # Preload all models to prevent I18n being cleared in Mongoid builds RailsAdmin::AbstractModel.all en = {admin: {actions: { zorg: {bulk_link: 'Zorg all these %{model_label_plural}'}, blub: {bulk_link: 'Blub all these %{model_label_plural}'}, }}} I18n.backend.store_translations(:en, en) @abstract_model = RailsAdmin::AbstractModel.new(Team) result = helper.bulk_menu expect(result).to match('zorg_action') expect(result).to match('Zorg all these Teams') expect(result).to match('blub') expect(result).to match('Blub all these Teams') result_2 = helper.bulk_menu(RailsAdmin::AbstractModel.new(Player)) expect(result_2).to match('zorg_action') expect(result_2).to match('Zorg all these Players') expect(result_2).not_to match('blub') expect(result_2).not_to match('Blub all these Players') end end describe '#edit_user_link' do it "don't include email column" do allow(helper).to receive(:_current_user).and_return(FactoryBot.create(:player)) result = helper.edit_user_link expect(result).to eq nil end it 'include email column' do allow(helper).to receive(:_current_user).and_return(FactoryBot.create(:user)) result = helper.edit_user_link expect(result).to match('href') end it 'show gravatar' do allow(helper).to receive(:_current_user).and_return(FactoryBot.create(:user)) result = helper.edit_user_link expect(result).to include('gravatar') end it "don't show gravatar" do RailsAdmin.config do |config| config.show_gravatar = false end allow(helper).to receive(:_current_user).and_return(FactoryBot.create(:user)) result = helper.edit_user_link expect(result).not_to include('gravatar') end context 'when the user is not authorized to perform edit' do let(:user) { FactoryBot.create(:user) } before do allow_any_instance_of(RailsAdmin::Config::Actions::Edit).to receive(:authorized?).and_return(false) allow(helper).to receive(:_current_user).and_return(user) end it 'show gravatar and email without a link' do result = helper.edit_user_link expect(result).to include('gravatar') expect(result).to include(user.email) expect(result).not_to match('href') end end end end describe '#flash_alert_class' do it 'makes errors red with alert-danger' do expect(helper.flash_alert_class('error')).to eq('alert-danger') end it 'makes alerts yellow with alert-warning' do expect(helper.flash_alert_class('alert')).to eq('alert-warning') end it 'makes notices blue with alert-info' do expect(helper.flash_alert_class('notice')).to eq('alert-info') end it 'prefixes others with "alert-"' do expect(helper.flash_alert_class('foo')).to eq('alert-foo') end end end
Java
package nl.ulso.sprox.json.spotify; import nl.ulso.sprox.Node; import java.time.LocalDate; import java.util.List; /** * Sprox processor for Spotify API album data. This is a very simple processor that ignores most data. * <p> * This implementation creates an Artist object for each and every artist in the response. But only the first one on * album level is kept in the end. * </p> */ public class AlbumFactory { @Node("album") public Album createAlbum(@Node("name") String name, @Node("release_date") LocalDate releaseDate, Artist artist, List<Track> tracks) { return new Album(name, releaseDate, artist, tracks); } @Node("artists") public Artist createArtist(@Node("name") String name) { return new Artist(name); } @Node("items") public Track createTrack(@Node("track_number") Integer trackNumber, @Node("name") String name) { return new Track(trackNumber, name); } }
Java
from corecat.constants import OBJECT_CODES, MODEL_VERSION from ._sqlalchemy import Base, CoreCatBaseMixin from ._sqlalchemy import Column, \ Integer, \ String, Text class Project(CoreCatBaseMixin, Base): """Project Model class represent for the 'projects' table which is used to store project's basic information.""" # Add the real table name here. # TODO: Add the database prefix here __tablename__ = 'project' # Column definition project_id = Column('id', Integer, primary_key=True, autoincrement=True ) project_name = Column('name', String(100), nullable=False ) project_description = Column('description', Text, nullable=True ) # Relationship # TODO: Building relationship def __init__(self, project_name, created_by_user_id, **kwargs): """ Constructor of Project Model Class. :param project_name: Name of the project. :param created_by_user_id: Project is created under this user ID. :param project_description: Description of the project. """ self.set_up_basic_information( MODEL_VERSION[OBJECT_CODES['Project']], created_by_user_id ) self.project_name = project_name self.project_description = kwargs.get('project_description', None)
Java
/** * Angular 2 decorators and services */ import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { environment } from 'environments/environment'; import { AppState } from './app.service'; /** * App Component * Top Level Component */ @Component({ selector: 'my-app', encapsulation: ViewEncapsulation.None, template: ` <nav> <a [routerLink]=" ['./'] " routerLinkActive="active" [routerLinkActiveOptions]= "{exact: true}"> Index </a> </nav> <main> <router-outlet></router-outlet> </main> <pre class="app-state">this.appState.state = {{ appState.state | json }}</pre> <footer> <span>Angular Starter by <a [href]="twitter">@gdi2290</a></span> <div> <a [href]="url"> <img [src]="tipe" width="25%"> </a> </div> </footer> ` }) export class AppComponent implements OnInit { public name = 'Angular Starter'; public tipe = 'assets/img/tipe.png'; public twitter = 'https://twitter.com/gdi2290'; public url = 'https://tipe.io'; public showDevModule: boolean = environment.showDevModule; constructor( public appState: AppState ) {} public ngOnInit() { console.log('Initial App State', this.appState.state); } } /** * Please review the https://github.com/AngularClass/angular2-examples/ repo for * more angular app examples that you may copy/paste * (The examples may not be updated as quickly. Please open an issue on github for us to update it) * For help or questions please contact us at @AngularClass on twitter * or our chat on Slack at https://AngularClass.com/slack-join */
Java
// Copyright (c) 2016-2020 The ZCash developers // Copyright (c) 2020 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. /* See the Zcash protocol specification for more information. https://github.com/zcash/zips/blob/master/protocol/protocol.pdf */ #ifndef ZC_NOTE_ENCRYPTION_H_ #define ZC_NOTE_ENCRYPTION_H_ #include "uint256.h" #include "sapling/address.h" #include "sapling/sapling.h" #include <array> namespace libzcash { // Ciphertext for the recipient to decrypt typedef std::array<unsigned char, ZC_SAPLING_ENCCIPHERTEXT_SIZE> SaplingEncCiphertext; typedef std::array<unsigned char, ZC_SAPLING_ENCPLAINTEXT_SIZE> SaplingEncPlaintext; // Ciphertext for outgoing viewing key to decrypt typedef std::array<unsigned char, ZC_SAPLING_OUTCIPHERTEXT_SIZE> SaplingOutCiphertext; typedef std::array<unsigned char, ZC_SAPLING_OUTPLAINTEXT_SIZE> SaplingOutPlaintext; //! This is not a thread-safe API. class SaplingNoteEncryption { protected: // Ephemeral public key uint256 epk; // Ephemeral secret key uint256 esk; bool already_encrypted_enc; bool already_encrypted_out; SaplingNoteEncryption(uint256 epk, uint256 esk) : epk(epk), esk(esk), already_encrypted_enc(false), already_encrypted_out(false) { } public: static boost::optional<SaplingNoteEncryption> FromDiversifier(diversifier_t d); boost::optional<SaplingEncCiphertext> encrypt_to_recipient( const uint256 &pk_d, const SaplingEncPlaintext &message ); SaplingOutCiphertext encrypt_to_ourselves( const uint256 &ovk, const uint256 &cv, const uint256 &cm, const SaplingOutPlaintext &message ); uint256 get_epk() const { return epk; } uint256 get_esk() const { return esk; } }; // Attempts to decrypt a Sapling note. This will not check that the contents // of the ciphertext are correct. boost::optional<SaplingEncPlaintext> AttemptSaplingEncDecryption( const SaplingEncCiphertext &ciphertext, const uint256 &ivk, const uint256 &epk ); // Attempts to decrypt a Sapling note using outgoing plaintext. // This will not check that the contents of the ciphertext are correct. boost::optional<SaplingEncPlaintext> AttemptSaplingEncDecryption ( const SaplingEncCiphertext &ciphertext, const uint256 &epk, const uint256 &esk, const uint256 &pk_d ); // Attempts to decrypt a Sapling note. This will not check that the contents // of the ciphertext are correct. boost::optional<SaplingOutPlaintext> AttemptSaplingOutDecryption( const SaplingOutCiphertext &ciphertext, const uint256 &ovk, const uint256 &cv, const uint256 &cm, const uint256 &epk ); } #endif /* ZC_NOTE_ENCRYPTION_H_ */
Java
import React from 'react'; import { TypeChooser } from 'react-stockcharts/lib/helper' import Chart from './Chart' import { getData } from './util'; class ChartComponent extends React.Component { componentDidMount () { getData().then(data => { this.setState({ data}) }) } render () { if (this.state == null) { return <div> Loading... </div> } return ( <Chart type='hybrid' data={this.state.data} /> ) } } export default ChartComponent;
Java
# # Cookbook Name:: stow # Spec:: default # # Copyright (c) 2015 Steven Haddox require 'spec_helper' describe 'stow::default' do context 'When all attributes are default, on an unspecified platform' do let(:chef_run) do runner = ChefSpec::ServerRunner.new runner.converge(described_recipe) end it 'converges successfully' do chef_run # This should not raise an error end it 'creates stow src directory' do expect(chef_run).to run_execute('create_stow_source_dir') end it 'adds stow bin to $PATH' do expect(chef_run).to create_template('/etc/profile.d/stow.sh') end end context 'When running on CentOS 6' do let(:chef_run) do runner = ChefSpec::ServerRunner.new(platform: 'centos', version: '6.5') runner.converge(described_recipe) end it 'installs stow' do expect(chef_run).to install_package 'stow' end end context 'When running on Fedora 20' do let(:chef_run) do runner = ChefSpec::ServerRunner.new(platform: 'fedora', version: '20') runner.converge(described_recipe) end it 'installs stow' do expect(chef_run).to install_package 'stow' end end context 'When running on Ubuntu 14' do let(:chef_run) do runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '14.04') runner.converge(described_recipe) end it 'installs stow' do expect(chef_run).to install_package 'stow' end end context 'When running on Debian 7' do let(:chef_run) do runner = ChefSpec::ServerRunner.new(platform: 'debian', version: '7.0') runner.converge(described_recipe) end it 'installs stow' do expect(chef_run).to install_package 'stow' end end context 'When installing from source' do let(:chef_run) do runner = ChefSpec::ServerRunner.new(platform: 'opensuse', version: '12.3') runner.converge(described_recipe) end it 'gets the latest stow' do expect(chef_run).to create_remote_file("/usr/local/stow/src/stow-2.2.0.tar.gz") end it 'installs stow from source' do expect(chef_run).to install_tar_package("file:////usr/local/stow/src/stow-2.2.0.tar.gz") end describe '.stow_stow' do it 'runs on a clean install' do expect(chef_run).to run_execute('stow_stow') end it 'is skipped if stow is up to date' do # Stub package_stowed? to return true allow_any_instance_of(Chef::Resource::Execute).to receive(:package_stowed?).and_return(true) expect(chef_run).to_not run_execute('stow_stow') end end describe '.destow_stow' do it 'is skipped if stow is up to date' do # Stub package_stowed? to return true allow_any_instance_of(Chef::Resource::Execute).to receive(:package_stowed?).and_return(true) expect(chef_run).to_not run_execute('destow_stow') end it 'is skipped if old_stow_packages is blank' do # Stub package_stowed? to return false allow_any_instance_of(Chef::Resource::Execute).to receive(:package_stowed?).and_return(true) # Stub the directory glob to return no package matches allow_any_instance_of(Chef::Resource::Execute).to receive(:old_stow_packages).and_return([]) expect(chef_run).to_not run_execute('destow_stow') end it 'should destow existing stow packages' do # Return array of stow packages that exist in stow's path allow_any_instance_of(Chef::Resource::Execute).to receive(:old_stow_packages).and_return(['/usr/local/stow/stow-+-2.1.3']) # Ensure the directory glob returns the proper package allow(::File).to receive(:exist?).and_call_original allow(::File).to receive(:exist?).with('/usr/local/stow/stow-+-2.1.3').and_return(true) # Ensure the correct files are present # Ensure the symlink is detected expect(chef_run).to run_execute('destow_stow') expect(chef_run).to run_execute('stow_stow') end end end end
Java
/* * database.hpp * * Created on: Sep 22, 2016 * Author: dan */ #ifndef SRC_TURBO_BROCCOLI_DATABASE_HPP_ #define SRC_TURBO_BROCCOLI_DATABASE_HPP_ #include <boost/filesystem.hpp> #include <turbo_broccoli/type/key.hpp> #include <turbo_broccoli/type/value.hpp> #include <turbo_broccoli/type/blob.hpp> #include <turbo_broccoli/type/tags.hpp> #include <turbo_broccoli/type/tagged_records.hpp> #include <turbo_broccoli/type/result_find.hpp> #include <turbo_broccoli/type/result_key.hpp> #include <turbo_broccoli/detail/utils.hpp> namespace turbo_broccoli { using types::blob; using types::db_key; using types::result_key; using types::result_find; struct database { database(const std::string& path) : path_(path) { namespace fs = boost::filesystem; if(!fs::exists(path_) ) { if(!fs::create_directories(path_)) { throw std::runtime_error("cannot open db, cannot create directory: " + path_.generic_string()); } } else { if(!fs::is_directory(path_)) { throw std::runtime_error("cannot open db, is not a directory: " + path_.generic_string()); } } } result_find find(const std::string& key) { return find(detail::calculate_key(key)); } result_find find(const db_key& key) { result_find result{}; result.success = false; if(!record_exists(key)) { std::cout << "no record with key" << types::to_string(key) << std::endl; return result; } auto record = read_record(key); if( is_blob(record)) { result.success = true; result.results.push_back(detail::deserialize<blob>(record.data)); } if(is_tag_list(record)) { auto records = detail::deserialize<types::tagged_records>(record.data); for(auto& t : records.keys) { auto k = types::string_to_key(t); if(record_exists(k)) { auto r = read_record(k); if( is_blob(r)) { result.success = true; result.results.push_back(detail::deserialize<blob>(r.data)); } else { std::cout << "inconsistent: record is not blob " << t << std::endl; } } else { std::cout << "inconsistent no record from tag list " << t << std::endl; } } } return result; } result_key store(const blob& new_blob) { static const result_key failed_result{false, turbo_broccoli::types::nil_key() }; if(record_exists(new_blob)) { /* * read all tags and update them! */ auto r = read_record(new_blob.key_hash()); auto old_blob = detail::deserialize<blob>(r.data); types::tag_list::list_type to_delete = diff( old_blob.tags().tags, new_blob.tags().tags); types::tag_list::list_type to_add = diff( new_blob.tags().tags, old_blob.tags().tags); for(auto& t : to_add ) { update_tag_add(t, types::to_string(new_blob.key_hash())); } for(auto& t : to_delete ) { update_tag_remove(t, types::to_string(new_blob.key_hash())); } } else { detail::create_folder(path_, new_blob.key_hash()); for(auto& t : new_blob.tags().tags ) { update_tag_add(t, types::to_string(new_blob.key_hash())); } } write_blob(new_blob); return {true, new_blob.key_hash()}; return failed_result; } private: inline bool record_exists(const blob& b) { namespace fs = boost::filesystem; return fs::exists(detail::to_filename(path_, b.key_hash())); } inline bool record_exists(const db_key& k) { namespace fs = boost::filesystem; return fs::exists(detail::to_filename(path_, k)); } inline void write_blob(const blob& b) { namespace fs = boost::filesystem; types::value_t v; v.data = detail::serialize(b); v.reccord_type = types::value_type::blob; v.key = b.key(); detail::create_folder(path_, b.key_hash()); detail::write_file(detail::to_filename(path_, b.key_hash()).generic_string(), detail::serialize(v)); } inline types::value_t read_record(const db_key& k) { namespace fs = boost::filesystem; auto tmp = detail::read_file(detail::to_filename(path_, k).generic_string() ); return detail::deserialize<types::value_t>(tmp); } inline void update_tag_add(const std::string& tag_name, const std::string& record_key) { auto tag_key = detail::calculate_key(tag_name); types::value_t v; types::tagged_records records; if(record_exists(tag_key)) { v = read_record(tag_key); if(types::is_tag_list(v)) { records = detail::deserialize<types::tagged_records>(v.data); for(auto& r : records.keys) { if(record_key.compare(r) == 0) { return; } } records.keys.push_back(record_key); } else { throw std::runtime_error("record exissts and is not a tagged_list: " + tag_name); } } else { records.keys.push_back(record_key); v.key = tag_name; v.reccord_type = types::value_type::tag_list; v.data = detail::serialize(records); detail::create_folder(path_, tag_key); } v.data = detail::serialize(records); detail::write_file(detail::to_filename(path_, tag_key).generic_string(), detail::serialize(v)); } inline void update_tag_remove(const std::string& tag_name, const std::string& record_key) { auto tag_key = detail::calculate_key(tag_name); types::value_t v = read_record(tag_key); if(types::is_tag_list(v)) { types::tagged_records records = detail::deserialize<types::tagged_records>(v.data); records.keys.erase(std::remove(records.keys.begin(), records.keys.end(), record_key), records.keys.end()); v.data = detail::serialize(records); detail::write_file(detail::to_filename(path_, tag_key).generic_string(), detail::serialize(v)); } } /* * \brief return list of all elements that are only in a * a{0, 1, 2, 3, 4} * b{3, 4, 5, 6, 7} * d{0, 1, 2} */ inline std::vector<std::string> diff(const std::vector<std::string>& a, const std::vector<std::string>& b) { std::vector<std::string> d; for(auto& a_i : a) { bool contains_b_i{false}; for(auto& b_i : b) { if(a_i.compare(b_i) == 0) { contains_b_i = true; break; } } if(!contains_b_i) { d.push_back(a_i); } } return d; } using path_t = boost::filesystem::path; path_t path_; }; } #endif /* SRC_TURBO_BROCCOLI_DATABASE_HPP_ */
Java
#!/usr/bin/env python from ansible.module_utils.hashivault import hashivault_argspec from ansible.module_utils.hashivault import hashivault_auth_client from ansible.module_utils.hashivault import hashivault_init from ansible.module_utils.hashivault import hashiwrapper ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.1'} DOCUMENTATION = ''' --- module: hashivault_approle_role_get version_added: "3.8.0" short_description: Hashicorp Vault approle role get module description: - Module to get a approle role from Hashicorp Vault. options: name: description: - role name. mount_point: description: - mount point for role default: approle extends_documentation_fragment: hashivault ''' EXAMPLES = ''' --- - hosts: localhost tasks: - hashivault_approle_role_get: name: 'ashley' register: 'vault_approle_role_get' - debug: msg="Role is {{vault_approle_role_get.role}}" ''' def main(): argspec = hashivault_argspec() argspec['name'] = dict(required=True, type='str') argspec['mount_point'] = dict(required=False, type='str', default='approle') module = hashivault_init(argspec) result = hashivault_approle_role_get(module.params) if result.get('failed'): module.fail_json(**result) else: module.exit_json(**result) @hashiwrapper def hashivault_approle_role_get(params): name = params.get('name') client = hashivault_auth_client(params) result = client.get_role(name, mount_point=params.get('mount_point')) return {'role': result} if __name__ == '__main__': main()
Java
package com.gmail.hexragon.gn4rBot.command.ai; import com.gmail.hexragon.gn4rBot.managers.commands.CommandExecutor; import com.gmail.hexragon.gn4rBot.managers.commands.annotations.Command; import com.gmail.hexragon.gn4rBot.util.GnarMessage; import com.google.code.chatterbotapi.ChatterBot; import com.google.code.chatterbotapi.ChatterBotFactory; import com.google.code.chatterbotapi.ChatterBotSession; import com.google.code.chatterbotapi.ChatterBotType; import net.dv8tion.jda.entities.User; import org.apache.commons.lang3.StringUtils; import java.util.Map; import java.util.WeakHashMap; @Command( aliases = {"cbot", "cleverbot"}, usage = "(query)", description = "Talk to Clever-Bot." ) public class PrivateCleverbotCommand extends CommandExecutor { private ChatterBotFactory factory = new ChatterBotFactory(); private ChatterBotSession session = null; private Map<User, ChatterBotSession> sessionMap = new WeakHashMap<>(); @Override public void execute(GnarMessage message, String[] args) { try { if (!sessionMap.containsKey(message.getAuthor())) { ChatterBot bot = factory.create(ChatterBotType.CLEVERBOT); sessionMap.put(message.getAuthor(), bot.createSession()); } message.replyRaw(sessionMap.get(message.getAuthor()).think(StringUtils.join(args, " "))); } catch (Exception e) { message.reply("Chat Bot encountered an exception. Restarting. `:[`"); sessionMap.remove(message.getAuthor()); } } }
Java
--- layout: post title: Bhaas date: '2007-06-17 21:32:00' tags: ["poetry"] --- <p><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://bp2.blogger.com/_cWdd7TsTIWo/RnWon-oIleI/AAAAAAAAAAk/PCXo2q26GsQ/s1600-h/bhas.JPG"><img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;" src="http://bp2.blogger.com/_cWdd7TsTIWo/RnWon-oIleI/AAAAAAAAAAk/PCXo2q26GsQ/s320/bhas.JPG" border="0" alt="" id="BLOGGER_PHOTO_ID_5077149559709799906"/></a></p><div class="blogger-post-footer"><img width="1" height="1" src="https://blogger.googleusercontent.com/tracker/5416117946427095362-1632748105544492475?l=soranthou.blogspot.com" alt=""/></div>
Java
class Projects { public static filters: string[] = []; public static open(): void { $.ajax( { url: "./projects.html", success: (data) => { $("#page").fadeOut( "fast", () => { document.getElementById("page").innerHTML = data; NavTree.Update([ { name: "home", url: "#" }, { name: "projects", url: "#projects" } ]); $("#page").show(0); $(".menu-item").hide(); $(".menu-item").each( (i, e) => { setTimeout( () => { $(e).fadeIn(500); }, i * 100 ) } ) } ); } } ) } }
Java
/** * Created by Keerthikan on 29-Apr-17. */ export {expenseSpyFactory} from './expense-spy-factory'; export {compensationSpyFactory} from './compensation-spy-factory';
Java
package logbook.data; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import javax.annotation.CheckForNull; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import logbook.config.AppConfig; import org.apache.commons.io.FilenameUtils; /** * スクリプトを読み込みEventListenerの実装を取得する * */ public final class ScriptLoader implements Closeable { /** ClassLoader */ private final URLClassLoader classLoader; /** ScriptEngineManager */ private final ScriptEngineManager manager; /** * コンストラクター */ public ScriptLoader() { this.classLoader = URLClassLoader.newInstance(this.getLibraries()); this.manager = new ScriptEngineManager(this.classLoader); } /** * スクリプトを読み込みEventListenerの実装を取得する<br> * * @param script スクリプト * @return スクリプトにより実装されたEventListener、スクリプトエンジンが見つからない、もしくはコンパイル済み関数がEventListenerを実装しない場合null * @throws IOException * @throws ScriptException */ @CheckForNull public EventListener getEventListener(Path script) throws IOException, ScriptException { try (BufferedReader reader = Files.newBufferedReader(script, StandardCharsets.UTF_8)) { // 拡張子からScriptEngineを取得 String ext = FilenameUtils.getExtension(script.toString()); ScriptEngine engine = this.manager.getEngineByExtension(ext); if (engine != null) { // eval engine.eval(reader); // 実装を取得 EventListener listener = ((Invocable) engine).getInterface(EventListener.class); if (listener != null) { return new ScriptEventAdapter(listener, script); } } return null; } } /** * ScriptEngineManagerで使用する追加のライブラリ * * @return ライブラリ */ public URL[] getLibraries() { String[] engines = AppConfig.get().getScriptEngines(); List<URL> libs = new ArrayList<>(); for (String engine : engines) { Path path = Paths.get(engine); if (Files.isReadable(path)) { try { libs.add(path.toUri().toURL()); } catch (MalformedURLException e) { // ここに入るパターンはないはず e.printStackTrace(); } } } return libs.toArray(new URL[libs.size()]); } @Override public void close() throws IOException { this.classLoader.close(); } }
Java
# CMAKE generated file: DO NOT EDIT! # Generated by "MinGW Makefiles" Generator, CMake Version 2.8 # Relative path conversion top directories. SET(CMAKE_RELATIVE_PATH_TOP_SOURCE "D:/lang/OpenCV-2.2.0") SET(CMAKE_RELATIVE_PATH_TOP_BINARY "D:/lang/OpenCV-2.2.0/dbg-w32") # Force unix paths in dependencies. SET(CMAKE_FORCE_UNIX_PATHS 1) # The C and CXX include file search paths: SET(CMAKE_C_INCLUDE_PATH "../." "." "../include" "../include/opencv" "../modules/haartraining" "../modules/core/include" "../modules/imgproc/include" "../modules/objdetect/include" "../modules/ml/include" "../modules/highgui/include" "../modules/video/include" "../modules/features2d/include" "../modules/flann/include" "../modules/calib3d/include" "../modules/legacy/include" ) SET(CMAKE_CXX_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH}) SET(CMAKE_Fortran_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH}) # The C and CXX include file regular expressions for this directory. SET(CMAKE_C_INCLUDE_REGEX_SCAN "^.*$") SET(CMAKE_C_INCLUDE_REGEX_COMPLAIN "^$") SET(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN}) SET(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN ${CMAKE_C_INCLUDE_REGEX_COMPLAIN})
Java
(window.webpackJsonp=window.webpackJsonp||[]).push([[1],{107:function(n,o,c){},108:function(n,o,c){},109:function(n,o,c){},110:function(n,o,c){},150:function(n,o,c){},151:function(n,o,c){}}]); //# sourceMappingURL=styles-fa6c583b3cd626e54a0e.js.map
Java
get '/user' do if logged_in? redirect '/' end erb :create_account end post '/user' do user = User.create(params[:user]) redirect '/' end post '/login' do if user = User.login(params[:user]) session[:permissions] = '3' end redirect '/' end get '/logout' do session.clear session[:permissions] = '0' redirect '/' end
Java
<?php /************************************************************************************* * pascal.php * ---------- * Author: Tux (tux@inamil.cz) * Copyright: (c) 2004 Tux (http://tux.a4.cz/), Nigel McNie (http://qbnz.com/highlighter) * Release Version: 1.0.6 * CVS Revision Version: $Revision: 1.1 $ * Date Started: 2004/07/26 * Last Modified: $Date: 2005/06/02 04:57:18 $ * * Pascal language file for GeSHi. * * CHANGES * ------- * 2004/11/27 (1.0.2) * - Added support for multiple object splitters * 2004/10/27 (1.0.1) * - Added support for URLs * 2004/08/05 (1.0.0) * - Added support for symbols * 2004/07/27 (0.9.1) * - Pascal is OO language. Some new words. * 2004/07/26 (0.9.0) * - First Release * * TODO (updated 2004/11/27) * ------------------------- * ************************************************************************************* * * This file is part of GeSHi. * * GeSHi is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * GeSHi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GeSHi; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ************************************************************************************/ $language_data = array ( 'LANG_NAME' => 'Pascal', 'COMMENT_SINGLE' => array(1 => '//'), 'COMMENT_MULTI' => array('{' => '}','(*' => '*)'), 'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE, 'QUOTEMARKS' => array("'", '"'), 'ESCAPE_CHAR' => '\\', 'KEYWORDS' => array( 1 => array( 'if', 'while', 'until', 'repeat', 'default', 'do', 'else', 'for', 'switch', 'goto','label','asm','begin','end', 'assembler','case', 'downto', 'to','div','mod','far','forward','in','inherited', 'inline','interrupt','label','library','not','var','of','then','stdcall', 'cdecl','end.','raise','try','except','name','finally','resourcestring','override','overload', 'default','public','protected','private','property','published','stored','catch' ), 2 => array( 'nil', 'false', 'break', 'true', 'function', 'procedure','implementation','interface', 'unit','program','initialization','finalization','uses' ), 3 => array( 'abs', 'absolute','and','arc','arctan','chr','constructor','destructor', 'dispose','cos','eof','eoln','exp','get','index','ln','new','xor','write','writeln', 'shr','sin','sqrt','succ','pred','odd','read','readln','ord','ordinal','blockread','blockwrite' ), 4 => array( 'array', 'char', 'const', 'boolean', 'real', 'integer', 'longint', 'word', 'shortint', 'record','byte','bytebool','string', 'type','object','export','exports','external','file','longbool','pointer','set', 'packed','ansistring','union' ), ), 'SYMBOLS' => array( ), 'CASE_SENSITIVE' => array( GESHI_COMMENTS => true, 1 => false, 2 => false, 3 => false, 4 => false, ), 'STYLES' => array( 'KEYWORDS' => array( 1 => 'color: #b1b100;', 2 => 'color: #000000; font-weight: bold;', 3 => '', 4 => 'color: #993333;' ), 'COMMENTS' => array( 1 => 'color: #808080; font-style: italic;', 2 => 'color: #339933;', 'MULTI' => 'color: #808080; font-style: italic;' ), 'ESCAPE_CHAR' => array( 0 => 'color: #000099; font-weight: bold;' ), 'BRACKETS' => array( 0 => 'color: #66cc66;' ), 'STRINGS' => array( 0 => 'color: #ff0000;' ), 'NUMBERS' => array( 0 => 'color: #cc66cc;' ), 'METHODS' => array( 1 => 'color: #202020;' ), 'SYMBOLS' => array( 0 => 'color: #66cc66;' ), 'REGEXPS' => array( ), 'SCRIPT' => array( ) ), 'URLS' => array( 1 => '', 2 => '', 3 => '', 4 => '' ), 'OOLANG' => true, 'OBJECT_SPLITTERS' => array( 1 => '.' ), 'REGEXPS' => array( ), 'STRICT_MODE_APPLIES' => GESHI_NEVER, 'SCRIPT_DELIMITERS' => array( ), 'HIGHLIGHT_STRICT_BLOCK' => array( ) ); ?>
Java
<?php namespace infinitydevphp\gii\migration; use infinitydevphp\MultipleModelValidator\MultipleModelValidator; use infinitydevphp\tableBuilder\TableBuilder; use infinitydevphp\tableBuilder\TableBuilderTemplateMigration; use infinitydevphp\gii\models\Field; use yii\db\ColumnSchema; use yii\db\Schema; use yii\db\TableSchema; use yii\gii\CodeFile; use yii\helpers\ArrayHelper; use yii\gii\Generator as GeneratorBase; use Yii; use yii\validators\RangeValidator; class Generator extends GeneratorBase { public $db = 'db'; public $fields = []; public $tableName; public $migrationPath = '@common/migrations/db'; public $fileName = ''; public $migrationName = ''; public $useTablePrefix = true; public function init() { parent::init(); } public function attributeHints() { return ArrayHelper::merge(parent::attributeHints(), [ 'tableName' => 'Origin table name', 'fieldsOrigin' => 'Origin table fields for DB table creation', 'autoCreateTable' => 'Options for run create table query', 'migrationPath' => 'Migration path', 'fields' => 'Table fields' ]); } public function rules() { $rules = ArrayHelper::merge(parent::rules(), [ // [['tableName'], RangeValidator::className(), 'not' => true, 'range' => $this->tablesList, 'message' => 'Table name exists'], [['tableName'], 'required'], [['tableName'], 'match', 'pattern' => '/^(\w+\.)?([\w\*]+)$/', 'message' => 'Only word characters, and optionally an asterisk and/or a dot are allowed.'], [['fields'], MultipleModelValidator::className(), 'baseModel' => Field::className()], [['useTablePrefix'], 'boolean'], [['migrationPath', 'migrationName'], 'safe'], ]); return $rules; } public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'fields' => 'Table fields' ]); } protected function getTableFields() { if (sizeof($this->fields) > 1) return; $pks = []; $table = Yii::$app->db->schema->getTableSchema($this->tableName); if ($table && $columns = $table->columns) { $pks = $table->primaryKey; /** @var ColumnSchema[] $columns */ $this->fields = []; foreach ($columns as $name => $column) { $this->fields[] = new Field([ 'name' => $name, 'length' => $column->size, 'type' => $column->phpType, 'precision' => $column->precision, 'scale' => $column->scale, 'comment' => $column->comment, 'is_not_null' => !$column->allowNull, 'isCompositeKey' => in_array($name, $pks), ]); } } return $pks; } public function generate() { $this->tableName = preg_replace('/({{%)(\w+)(}})?/', "$2", $this->tableName); $tableName = $this->tableName; if ($this->useTablePrefix) { $tableName = "{{%{$tableName}}}"; } $primary = $this->getTableFields(); $files = []; $this->migrationName = Yii::$app->session->get($this->tableName) ?: false; $mCreate = new TableBuilderTemplateMigration([ 'tableName' => $tableName, 'fields' => $this->fields, 'useTablePrefix' => $this->useTablePrefix, ]); if (!$this->migrationName) { Yii::$app->session->set($this->tableName, $mCreate->migrationName); } $this->migrationName = $this->migrationName ?: Yii::$app->session->get($this->tableName); $mCreate->migrationName = $this->migrationName ?: $mCreate->migrationName; $files[] = new CodeFile( Yii::getAlias($this->migrationPath) . '/' . $mCreate->migrationName . '.php', $mCreate->runQuery() ); return $files; } public function getName() { return 'Migration Generator'; } public function defaultTemplate() { return parent::defaultTemplate(); } public function getDescription() { return 'This generator helps you create migration from existing table'; } public function stickyAttributes() { return ArrayHelper::merge(parent::stickyAttributes(), ['db', 'migrationPath']); } }
Java
delete p1 from person as p1, person as p2 where p1.email = p2.email and p1.id > p2.id;
Java
#include "HotNeedleLightControl.h" HotNeedleLightControlClass::HotNeedleLightControlClass(uint8_t background[NEOPIXEL_COUNT][COLOR_BYTES], uint8_t hotNeedleColor[COLOR_BYTES], float highlightMultiplier, bool useHighlight, uint16_t fadeTime, uint8_t framePeriod, Adafruit_NeoPixel *strip) : LightControlClass(framePeriod, strip) { memcpy(this->backgroundColors, background, COLOR_BYTES*NEOPIXEL_COUNT); memcpy(this->hotNeedleColor, hotNeedleColor, COLOR_BYTES); fadeFrames = fadeTime / framePeriod; this->useHighlight = useHighlight; this->highlightMultiplier = highlightMultiplier; this->maximumLedPosition = 0; this->minimumLedPosition = NEOPIXEL_COUNT; } // Rendering code void HotNeedleLightControlClass::renderFrame(uint16_t pos, NEEDLE_DIRECTION dir) { // Increment existing counters decrementCounters(ledCounters); uint16_t needlePosition = pixelFromInputPosition(pos); // Set current position hot pixel counter to max ledCounters[needlePosition] = fadeFrames; draw(needlePosition); } void HotNeedleLightControlClass::draw(uint16_t needlePosition) { // Calculate display values for each pixel for (uint16_t p = 0; p < NEOPIXEL_COUNT; p++) { float backgroundRatio = (float)(fadeFrames - ledCounters[p]) / fadeFrames; float foregroundRatio = 1.0 - backgroundRatio; for (uint8_t c = 0; c < COLOR_BYTES; c++) { if (useHighlight) { // Foreground color is background color * highlight multiplier // Make sure we don't wrap past 255 int bg = backgroundColors[p][c] * highlightMultiplier; if (bg > 255) { bg = 255; } ledCurrentColors[p][c] = gammaCorrect((foregroundRatio * bg) + (backgroundRatio * backgroundColors[p][c])); } else { ledCurrentColors[p][c] = gammaCorrect((foregroundRatio * hotNeedleColor[c]) + (backgroundRatio * backgroundColors[p][c])); } } strip->setPixelColor(p, ledCurrentColors[p][RED], ledCurrentColors[p][GREEN], ledCurrentColors[p][BLUE]); } if(useMaximum){ updateMaximum(needlePosition); drawMaximum(); } if(useMinimum){ updateMinimum(needlePosition); drawMinimum(); } strip->show(); }
Java
import { createSelector } from 'reselect'; import * as movie from './../actions/movie'; import { Movie } from './../models'; import * as _ from 'lodash'; import { AsyncOperation, AsyncStatus, makeAsyncOp } from "./../utils"; export interface State { entities: { [movieId: string]: Movie }; mapMovieToCinema: { [cinemaId: string]: { releasedIds: string[] otherIds: string[], loadingOp: AsyncOperation, } }; selectedId: string; } export const initialState: State = { entities: {}, mapMovieToCinema: {}, selectedId: null, }; export function reducer(state: State = initialState, actionRaw: movie.Actions): State { switch (actionRaw.type) { case movie.ActionTypes.LOAD: { let action = <movie.LoadAction>actionRaw; let cinemaId = action.payload.cinemaId; return { ...state, mapMovieToCinema: { ...state.mapMovieToCinema, [cinemaId]: { ...state.mapMovieToCinema[cinemaId], releasedIds: [], otherIds: [], loadingOp: makeAsyncOp(AsyncStatus.Pending), }, }, }; } case movie.ActionTypes.LOAD_SUCCESS: { let action = <movie.LoadSuccessAction>actionRaw; let entities = _.flatten([action.payload.released, action.payload.other]) .reduce((entities, movie) => { return { ...entities, [movie.id]: movie, }; }, state.entities); let map = { releasedIds: action.payload.released.map(m => m.id), otherIds: action.payload.other.map(m => m.id), loadingOp: makeAsyncOp(AsyncStatus.Success), }; return { ...state, entities: entities, mapMovieToCinema: { ...state.mapMovieToCinema, [action.payload.cinemaId]: map }, }; } case movie.ActionTypes.LOAD_FAIL: { let action = <movie.LoadFailAction>actionRaw; let cinemaId = action.payload.cinemaId; return { ...state, mapMovieToCinema: { ...state.mapMovieToCinema, [cinemaId]: { ...state.mapMovieToCinema[cinemaId], loadingOp: makeAsyncOp(AsyncStatus.Fail, action.payload.errorMessage), }, }, }; } case movie.ActionTypes.SELECT: { var action = <movie.SelectAction>actionRaw; return { ...state, selectedId: action.payload, }; } default: return state; } } export const getEntities = (state: State) => state.entities; export const getMapToCinema = (state: State) => state.mapMovieToCinema; export const getSelectedId = (state: State) => state.selectedId; export const getSelected = createSelector(getEntities, getSelectedId, (entities, id) => { return entities[id]; });
Java
<!DOCTYPE HTML> <html> <head> <title>Gamecraft CI</title> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css"/> <link rel="stylesheet" href="/css/dashboard.css"/> <script src="/webjars/jquery/1.11.1/jquery.min.js"></script> <script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script> <script src="/js/account_operations.js"></script> <script src="/js/ui_operations.js"></script> <script src="/js/validator.min.js"></script> <script src="/js/lang_operations.js"></script> <script> checkAuthState(); setDefaultLanguage(); loadNavbar(); </script> </head> <body> <div class="navbar-frame"></div> <div class="container"> <!-- Main component for a primary marketing message or call to action --> <div class="jumbotron"> <h1>Welcome to Gamecraft!</h1> <div class="alert alert-success" role="alert">You are logged in as user "<script> document.write(getUsername())</script>".</div> <p>If you have any question on Gamecraft:</p> <ul> <li><a href="https://github.com/iMartinezMateu/gamecraft/issues?state=open" target="_blank" rel="noopener" >Gamecraft bug tracker</a></li> <li><a href="https://github.com/iMartinezMateu/gamecraft/wiki" target="_blank" rel="noopener" >Gamecraft wiki</a></li> </ul> <p> <span jhiTranslate="home.like">If you like Gamecraft, don't forget to give us a star on</span> <a href="https://github.com/iMartinezMateu/gamecraft" target="_blank" rel="noopener" >GitHub</a>! </p> <img src="/img/gamecraft.png" alt="Gamecraft" class="center-block" /> </div> </div> <!-- /container --> </body> </html>
Java
from scrapy.spiders import Spider from scrapy.selector import Selector from scrapy.http import HtmlResponse from FIFAscrape.items import PlayerItem from urlparse import urlparse, urljoin from scrapy.http.request import Request from scrapy.conf import settings import random import time class fifaSpider(Spider): name = "fifa" allowed_domains = ["futhead.com"] start_urls = [ "http://www.futhead.com/16/players/?level=all_nif&bin_platform=ps" ] def parse(self, response): #obtains links from page to page and passes links to parse_playerURL sel = Selector(response) #define selector based on response object (points to urls in start_urls by default) url_list = sel.xpath('//a[@class="display-block padding-0"]/@href') #obtain a list of href links that contain relative links of players for i in url_list: relative_url = self.clean_str(i.extract()) #i is a selector and hence need to extract it to obtain unicode object print urljoin(response.url, relative_url) #urljoin is able to merge absolute and relative paths to form 1 coherent link req = Request(urljoin(response.url, relative_url),callback=self.parse_playerURL) #pass on request with new urls to parse_playerURL req.headers["User-Agent"] = self.random_ua() yield req next_url=sel.xpath('//div[@class="right-nav pull-right"]/a[@rel="next"]/@href').extract_first() if(next_url): #checks if next page exists clean_next_url = self.clean_str(next_url) reqNext = Request(urljoin(response.url, clean_next_url),callback=self.parse) #calls back this function to repeat process on new list of links yield reqNext def parse_playerURL(self, response): #parses player specific data into items list site = Selector(response) items = [] item = PlayerItem() item['1name'] = (response.url).rsplit("/")[-2].replace("-"," ") title = self.clean_str(site.xpath('/html/head/title/text()').extract_first()) item['OVR'] = title.partition("FIFA 16 -")[1].split("-")[0] item['POS'] = self.clean_str(site.xpath('//div[@class="playercard-position"]/text()').extract_first()) #stats = site.xpath('//div[@class="row player-center-container"]/div/a') stat_names = site.xpath('//span[@class="player-stat-title"]') stat_values = site.xpath('//span[contains(@class, "player-stat-value")]') for index in range(len(stat_names)): attr_name = stat_names[index].xpath('.//text()').extract_first() item[attr_name] = stat_values[index].xpath('.//text()').extract_first() items.append(item) return items def clean_str(self,ustring): #removes wierd unicode chars (/u102 bla), whitespaces, tabspaces, etc to form clean string return str(ustring.encode('ascii', 'replace')).strip() def random_ua(self): #randomise user-agent from list to reduce chance of being banned ua = random.choice(settings.get('USER_AGENT_LIST')) if ua: ua='Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36' return ua
Java
<!DOCTYPE HTML> <html> <head> <title>Arbiter - Decisions Simplified</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script> <script src="app.js"></script> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!--[if lte IE 8]><script src="assets/js/ie/html5shiv.js"></script><![endif]--> <link rel="stylesheet" href="assets/css/main.css" /> <!--[if lte IE 9]><link rel="stylesheet" href="assets/css/ie9.css" /><![endif]--> <!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]--> </head> <body ng-app="decisionPage" ng-controller="decisionController" class="single"> <!-- Wrapper --> <div id="wrapper"> <!-- Header --> <header id="header"> <h1><a href="#">Arbiter</a></h1> <nav class="links"> <ul> <li><a href="#">My Posts</a></li> </ul> </nav> <nav class="main"> <ul> <li class="search"> <a class="fa-search" href="#search">Search</a> <form id="search" method="get" action="#"> <input type="text" name="query" placeholder="Search" /> </form> </li> <li class="menu"> <a class="fa-bars" href="#menu">Menu</a> </li> </ul> </nav> </header> <!-- Menu --> <section id="menu"> <!-- Search --> <section> <form class="search" method="get" action="#"> <input type="text" name="query" placeholder="Search" /> </form> </section> <!-- Actions --> <section> <ul class="actions vertical"> <li><a href="#" class="button big fit">Log In</a></li> </ul> </section> </section> <!-- Main --> <div id="main"> <!-- Post --> <article class="post"> <header> <div class="title"> <h2>{{test}}</h2> </div> <div class="meta"> <time class="published" datetime="2015-11-01">November 1, 2015</time> <a href="#" class="author"><span class="name">Jane Doe</span><img src="images/avatar.jpg" alt="" /></a> </div> </header> <footer> <ul class="actions"> <li><a href="#" class="button big">Apple</a></li> <li><a href="#" class="button big">Orange</a></li> </ul> </footer> </article> </div> <!-- Footer --> <section id="footer"> <ul class="icons"> <li><a href="#" class="fa-twitter"><span class="label">Twitter</span></a></li> <li><a href="#" class="fa-facebook"><span class="label">Facebook</span></a></li> <li><a href="#" class="fa-instagram"><span class="label">Instagram</span></a></li> <li><a href="#" class="fa-rss"><span class="label">RSS</span></a></li> <li><a href="#" class="fa-envelope"><span class="label">Email</span></a></li> </ul> <p class="copyright">Made by love @ UCSD</p> </section> </div> <!-- Scripts --> <script src="assets/js/jquery.min.js"></script> <script src="assets/js/skel.min.js"></script> <script src="assets/js/util.js"></script> <!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]--> <script src="assets/js/main.js"></script> </body> </html>
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ $(document).ready(function(){ var div = document.getElementById('content'); var div1 = document.getElementById('leftbox'); div.style.height = document.body.clientHeight + 'px'; div1.style.height = div.style.height; var contentToRemove = document.querySelectorAll(".collapsed-navbox"); $(contentToRemove).hide(); var oritop = -100; $(window).scroll(function() { var scrollt = window.scrollY; var elm = $("#leftbox"); if(oritop < 0) { oritop= elm.offset().top; } if(scrollt >= oritop) { elm.css({"position": "fixed", "top": 0, "left": 0}); } else { elm.css("position", "static"); } }); /*$(window).resize(function() { var wi = $(window).width(); $("p.testp").text('Screen width is currently: ' + wi + 'px.'); }); $(window).resize(function() { var wi = $(window).width(); if (wi <= 767){ var contentToRemove = document.querySelectorAll(".fullscreen-navbox"); $(contentToRemove).hide(); var contentToRemove = document.querySelectorAll(".collapsed-navbox"); $(contentToRemove).show(); $("#leftbox").css("width","30px"); $("#content").css("width","90%"); }else if (wi > 800){ var contentToRemove = document.querySelectorAll(".fullscreen-navbox"); $(contentToRemove).show(); var contentToRemove = document.querySelectorAll(".collapsed-navbox"); $(contentToRemove).hide(); $("#leftbox").css("width","15%"); $("#content").css("width","85%"); } });*/ });
Java
require 'spec_helper' describe Webpack::Rails do it 'has a version number' do expect(Webpack::Rails::VERSION).not_to be nil end end
Java
CREATE TABLE IF NOT EXISTS `comment` ( ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; ;
Java